Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add annotations and braces

apoogdk413e8507a70a
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/mod.rs b/rust/bridge/crates/manimgx-core/src/geometry/mod.rs
new file mode 100644
index 00000000..db559df2
--- /dev/null
+++ b/rust/bridge/crates/manimgx-core/src/geometry/mod.rs
@@ -0,0 +1,7 @@
+pub mod three_d;
+pub mod two_d;
+
+// Re-exports for existing consumers
+pub use three_d::bezier;
+pub use three_d::mesh;
+pub use three_d::primitives;
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs
new file mode 100644
index 00000000..9b2aad00
--- /dev/null
+++ b/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs
@@ -0,0 +1,4 @@
+pub mod axes;
+pub mod function_plot;
+pub mod polygon;
+pub mod shapes;
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs
new file mode 100644
index 00000000..455822d7
--- /dev/null
+++ b/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs
@@ -0,0 +1,269 @@
+use crate::vertex::Vertex;
+use std::f32::consts::PI;
+
+pub struct RegularPolygon;
+pub struct Polygram;
+pub struct Triangle;
+
+const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
+
+impl RegularPolygon {
+ /// Generate a regular polygon with `sides` sides, centered at origin in the XY plane.
+ /// Fill is a triangle fan, stroke is a quad strip around the perimeter.
+ pub fn generate(
+ sides: u32,
+ radius: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ // Compute corner positions
+ let corners: Vec<[f32; 2]> = (0..sides)
+ .map(|i| {
+ let angle = (i as f32) * 2.0 * PI / sides as f32 - PI / 2.0;
+ [angle.cos() * radius, angle.sin() * radius]
+ })
+ .collect();
+
+ // Fill: triangle fan from center
+ let center_idx = vertices.len() as u32;
+ vertices.push(Vertex::new([0.0, 0.0, 0.0], NORMAL_2D, fill_color));
+
+ for corner in &corners {
+ vertices.push(Vertex::new(
+ [corner[0], corner[1], 0.0],
+ NORMAL_2D,
+ fill_color,
+ ));
+ }
+
+ for i in 0..sides {
+ indices.push(center_idx);
+ indices.push(center_idx + 1 + i);
+ indices.push(center_idx + 1 + (i + 1) % sides);
+ }
+
+ // Stroke: quad strip around perimeter
+ if stroke_width > 0.0 {
+ let half_w = stroke_width / 2.0;
+ let stroke_base = vertices.len() as u32;
+
+ for i in 0..sides {
+ let curr = corners[i as usize];
+ let next = corners[((i + 1) % sides) as usize];
+
+ // Direction along edge
+ let dx = next[0] - curr[0];
+ let dy = next[1] - curr[1];
+ let len = (dx * dx + dy * dy).sqrt();
+ // Outward normal (perpendicular)
+ let nx = -dy / len;
+ let ny = dx / len;
+
+ // Inner and outer vertices for this corner
+ let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
+ let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
+
+ vertices.push(Vertex::new(
+ [inner[0], inner[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [outer[0], outer[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ }
+
+ for i in 0..sides {
+ let base = stroke_base + i * 2;
+ let next_base = stroke_base + ((i + 1) % sides) * 2;
+ // Two triangles forming a quad between this edge and next
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(next_base);
+
+ indices.push(next_base);
+ indices.push(base + 1);
+ indices.push(next_base + 1);
+ }
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl Polygram {
+ /// Generate a star polygon {points/step}.
+ /// `points` = number of outer vertices, `step` = connect every `step`-th vertex.
+ pub fn generate(
+ points: u32,
+ step: u32,
+ outer_radius: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ // Compute inner radius using the star polygon formula
+ let inner_radius =
+ outer_radius * (PI / points as f32).cos() / (PI * step as f32 / points as f32).cos();
+
+ // Generate alternating outer/inner vertices
+ let total = points * 2;
+ let star_pts: Vec<[f32; 2]> = (0..total)
+ .map(|i| {
+ let angle = (i as f32) * PI / points as f32 - PI / 2.0;
+ let r = if i % 2 == 0 {
+ outer_radius
+ } else {
+ inner_radius
+ };
+ [angle.cos() * r, angle.sin() * r]
+ })
+ .collect();
+
+ // Fill: triangle fan from center
+ let center_idx = vertices.len() as u32;
+ vertices.push(Vertex::new([0.0, 0.0, 0.0], NORMAL_2D, fill_color));
+
+ for pt in &star_pts {
+ vertices.push(Vertex::new([pt[0], pt[1], 0.0], NORMAL_2D, fill_color));
+ }
+
+ for i in 0..total {
+ indices.push(center_idx);
+ indices.push(center_idx + 1 + i);
+ indices.push(center_idx + 1 + (i + 1) % total);
+ }
+
+ // Stroke: quad strip around perimeter
+ if stroke_width > 0.0 {
+ let half_w = stroke_width / 2.0;
+ let stroke_base = vertices.len() as u32;
+
+ for i in 0..total {
+ let curr = star_pts[i as usize];
+ let next = star_pts[((i + 1) % total) as usize];
+
+ let dx = next[0] - curr[0];
+ let dy = next[1] - curr[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let nx = -dy / len;
+ let ny = dx / len;
+
+ let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
+ let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
+
+ vertices.push(Vertex::new(
+ [inner[0], inner[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [outer[0], outer[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ }
+
+ for i in 0..total {
+ let base = stroke_base + i * 2;
+ let next_base = stroke_base + ((i + 1) % total) * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(next_base);
+
+ indices.push(next_base);
+ indices.push(base + 1);
+ indices.push(next_base + 1);
+ }
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl Triangle {
+ /// Generate an equilateral triangle with circumradius `radius`.
+ pub fn equilateral(
+ radius: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ RegularPolygon::generate(3, radius, fill_color, stroke_color, stroke_width)
+ }
+
+ /// Generate a triangle from three arbitrary XY vertices.
+ pub fn from_vertices(
+ v0: [f32; 2],
+ v1: [f32; 2],
+ v2: [f32; 2],
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ let corners = [v0, v1, v2];
+
+ // Fill: single triangle
+ for c in &corners {
+ vertices.push(Vertex::new([c[0], c[1], 0.0], NORMAL_2D, fill_color));
+ }
+ indices.extend_from_slice(&[0, 1, 2]);
+
+ // Stroke: quad strip around perimeter
+ if stroke_width > 0.0 {
+ let half_w = stroke_width / 2.0;
+ let stroke_base = vertices.len() as u32;
+
+ for i in 0..3u32 {
+ let curr = corners[i as usize];
+ let next = corners[((i + 1) % 3) as usize];
+
+ let dx = next[0] - curr[0];
+ let dy = next[1] - curr[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let nx = -dy / len;
+ let ny = dx / len;
+
+ let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
+ let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
+
+ vertices.push(Vertex::new(
+ [inner[0], inner[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [outer[0], outer[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ }
+
+ for i in 0..3u32 {
+ let base = stroke_base + i * 2;
+ let next_base = stroke_base + ((i + 1) % 3) * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(next_base);
+
+ indices.push(next_base);
+ indices.push(base + 1);
+ indices.push(next_base + 1);
+ }
+ }
+
+ (vertices, indices)
+ }
+}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs
new file mode 100644
index 00000000..cf58cec2
--- /dev/null
+++ b/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs
@@ -0,0 +1,704 @@
+use crate::vertex::Vertex;
+use std::f32::consts::PI;
+
+pub struct Circle;
+pub struct Rectangle;
+pub struct Line;
+pub struct Arc;
+pub struct Arrow;
+pub struct Dot;
+pub struct CurvedArrow;
+pub struct DashedLine;
+pub struct Brace;
+pub struct FilledRegion;
+pub struct RiemannRects;
+
+const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
+
+impl Circle {
+ /// Generate a filled circle with optional stroke.
+ pub fn generate(
+ radius: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ segments: u32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ // Circle is just a high-segment regular polygon
+ super::polygon::RegularPolygon::generate(
+ segments,
+ radius,
+ fill_color,
+ stroke_color,
+ stroke_width,
+ )
+ }
+}
+
+impl Rectangle {
+ /// Generate a filled rectangle centered at origin in XY plane.
+ pub fn generate(
+ width: f32,
+ height: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let hw = width / 2.0;
+ let hh = height / 2.0;
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ // Fill: two triangles
+ vertices.push(Vertex::new([-hw, -hh, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([hw, -hh, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([hw, hh, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([-hw, hh, 0.0], NORMAL_2D, fill_color));
+ indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);
+
+ // Stroke: quad strip around perimeter
+ if stroke_width > 0.0 {
+ let half_w = stroke_width / 2.0;
+ let corners: [[f32; 2]; 4] = [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]];
+
+ let stroke_base = vertices.len() as u32;
+
+ for i in 0..4u32 {
+ let curr = corners[i as usize];
+ let next = corners[((i + 1) % 4) as usize];
+
+ let dx = next[0] - curr[0];
+ let dy = next[1] - curr[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let nx = -dy / len;
+ let ny = dx / len;
+
+ let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
+ let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
+
+ vertices.push(Vertex::new(
+ [inner[0], inner[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [outer[0], outer[1], 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ }
+
+ for i in 0..4u32 {
+ let base = stroke_base + i * 2;
+ let next_base = stroke_base + ((i + 1) % 4) * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(next_base);
+
+ indices.push(next_base);
+ indices.push(base + 1);
+ indices.push(next_base + 1);
+ }
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl Line {
+ /// Generate a line (quad) between two XY points.
+ pub fn generate(
+ start: [f32; 2],
+ end: [f32; 2],
+ color: [f32; 4],
+ width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let dx = end[0] - start[0];
+ let dy = end[1] - start[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let nx = -dy / len * width / 2.0;
+ let ny = dx / len * width / 2.0;
+
+ let vertices = vec![
+ Vertex::new([start[0] - nx, start[1] - ny, 0.0], NORMAL_2D, color),
+ Vertex::new([start[0] + nx, start[1] + ny, 0.0], NORMAL_2D, color),
+ Vertex::new([end[0] + nx, end[1] + ny, 0.0], NORMAL_2D, color),
+ Vertex::new([end[0] - nx, end[1] - ny, 0.0], NORMAL_2D, color),
+ ];
+ let indices = vec![0, 1, 2, 0, 2, 3];
+
+ (vertices, indices)
+ }
+}
+
+impl Arc {
+ /// Generate an arc (partial circle outline) as a quad strip.
+ pub fn generate(
+ radius: f32,
+ start_angle: f32,
+ end_angle: f32,
+ color: [f32; 4],
+ width: f32,
+ segments: u32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+ let half_w = width / 2.0;
+
+ let angle_span = end_angle - start_angle;
+
+ for i in 0..=segments {
+ let t = i as f32 / segments as f32;
+ let angle = start_angle + t * angle_span;
+ let cos_a = angle.cos();
+ let sin_a = angle.sin();
+
+ // Inner and outer points
+ let inner_r = radius - half_w;
+ let outer_r = radius + half_w;
+
+ vertices.push(Vertex::new(
+ [cos_a * inner_r, sin_a * inner_r, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [cos_a * outer_r, sin_a * outer_r, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ }
+
+ for i in 0..segments {
+ let base = i * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+
+ indices.push(base + 2);
+ indices.push(base + 1);
+ indices.push(base + 3);
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl Arrow {
+ /// Generate an arrow from start to end with a triangular head.
+ pub fn generate(
+ start: [f32; 2],
+ end: [f32; 2],
+ color: [f32; 4],
+ width: f32,
+ head_length: f32,
+ head_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let dx = end[0] - start[0];
+ let dy = end[1] - start[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let ux = dx / len;
+ let uy = dy / len;
+
+ // The shaft ends where the arrowhead begins
+ let shaft_end = [end[0] - ux * head_length, end[1] - uy * head_length];
+
+ // Shaft (line quad)
+ let nx = -uy * width / 2.0;
+ let ny = ux * width / 2.0;
+
+ let mut vertices = vec![
+ Vertex::new([start[0] - nx, start[1] - ny, 0.0], NORMAL_2D, color),
+ Vertex::new([start[0] + nx, start[1] + ny, 0.0], NORMAL_2D, color),
+ Vertex::new(
+ [shaft_end[0] + nx, shaft_end[1] + ny, 0.0],
+ NORMAL_2D,
+ color,
+ ),
+ Vertex::new(
+ [shaft_end[0] - nx, shaft_end[1] - ny, 0.0],
+ NORMAL_2D,
+ color,
+ ),
+ ];
+ let mut indices = vec![0, 1, 2, 0, 2, 3];
+
+ // Arrowhead (triangle)
+ let head_nx = -uy * head_width / 2.0;
+ let head_ny = ux * head_width / 2.0;
+
+ let head_base = vertices.len() as u32;
+ vertices.push(Vertex::new(
+ [shaft_end[0] - head_nx, shaft_end[1] - head_ny, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [shaft_end[0] + head_nx, shaft_end[1] + head_ny, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new([end[0], end[1], 0.0], NORMAL_2D, color));
+
+ indices.push(head_base);
+ indices.push(head_base + 1);
+ indices.push(head_base + 2);
+
+ (vertices, indices)
+ }
+}
+
+impl Dot {
+ /// Generate a small filled circle (dot) at a position.
+ pub fn generate(
+ position: [f32; 2],
+ radius: f32,
+ color: [f32; 4],
+ segments: u32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ // Center vertex
+ let center_idx = 0u32;
+ vertices.push(Vertex::new(
+ [position[0], position[1], 0.0],
+ NORMAL_2D,
+ color,
+ ));
+
+ // Perimeter vertices
+ for i in 0..segments {
+ let angle = (i as f32) * 2.0 * PI / segments as f32;
+ vertices.push(Vertex::new(
+ [
+ position[0] + angle.cos() * radius,
+ position[1] + angle.sin() * radius,
+ 0.0,
+ ],
+ NORMAL_2D,
+ color,
+ ));
+ }
+
+ for i in 0..segments {
+ indices.push(center_idx);
+ indices.push(1 + i);
+ indices.push(1 + (i + 1) % segments);
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl CurvedArrow {
+ /// Generate an arc with an arrowhead at the end.
+ pub fn generate(
+ radius: f32,
+ start_angle: f32,
+ end_angle: f32,
+ color: [f32; 4],
+ width: f32,
+ head_length: f32,
+ head_width: f32,
+ segments: u32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+ let half_w = width / 2.0;
+
+ // Shorten the arc to make room for the arrowhead
+ let angle_span = end_angle - start_angle;
+ let head_angle = head_length / radius;
+ let arc_end = end_angle - head_angle;
+
+ // Arc body (quad strip)
+ let arc_span = arc_end - start_angle;
+ for i in 0..=segments {
+ let t = i as f32 / segments as f32;
+ let angle = start_angle + t * arc_span;
+ let cos_a = angle.cos();
+ let sin_a = angle.sin();
+
+ let inner_r = radius - half_w;
+ let outer_r = radius + half_w;
+
+ vertices.push(Vertex::new(
+ [cos_a * inner_r, sin_a * inner_r, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [cos_a * outer_r, sin_a * outer_r, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ }
+
+ for i in 0..segments {
+ let base = i * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+ indices.push(base + 2);
+ indices.push(base + 1);
+ indices.push(base + 3);
+ }
+
+ // Arrowhead triangle at arc_end
+ let head_base_idx = vertices.len() as u32;
+ let cos_end = arc_end.cos();
+ let sin_end = arc_end.sin();
+
+ // Tangent direction at arc_end (perpendicular to radius, in the direction of angle increase)
+ let sign = if angle_span >= 0.0 { 1.0 } else { -1.0 };
+ let tx = -sin_end * sign;
+ let ty = cos_end * sign;
+
+ // Normal to arc at this point (radial direction)
+ let nx = cos_end;
+ let ny = sin_end;
+
+ // Head base points (perpendicular to tangent)
+ let half_hw = head_width / 2.0;
+ let base_x = cos_end * radius;
+ let base_y = sin_end * radius;
+
+ vertices.push(Vertex::new(
+ [base_x - nx * half_hw, base_y - ny * half_hw, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [base_x + nx * half_hw, base_y + ny * half_hw, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+
+ // Tip point
+ let tip_x = base_x + tx * head_length;
+ let tip_y = base_y + ty * head_length;
+ vertices.push(Vertex::new([tip_x, tip_y, 0.0], NORMAL_2D, color));
+
+ indices.push(head_base_idx);
+ indices.push(head_base_idx + 1);
+ indices.push(head_base_idx + 2);
+
+ (vertices, indices)
+ }
+}
+
+impl DashedLine {
+ /// Generate a dashed line between two points.
+ pub fn generate(
+ start: [f32; 2],
+ end: [f32; 2],
+ color: [f32; 4],
+ width: f32,
+ dash_length: f32,
+ gap_length: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let dx = end[0] - start[0];
+ let dy = end[1] - start[1];
+ let total_len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let ux = dx / total_len;
+ let uy = dy / total_len;
+ let nx = -uy * width / 2.0;
+ let ny = ux * width / 2.0;
+
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ let pattern_len = dash_length + gap_length;
+ let mut dist = 0.0;
+
+ while dist < total_len {
+ let d_end = (dist + dash_length).min(total_len);
+ let sx = start[0] + ux * dist;
+ let sy = start[1] + uy * dist;
+ let ex = start[0] + ux * d_end;
+ let ey = start[1] + uy * d_end;
+
+ let base = vertices.len() as u32;
+ vertices.push(Vertex::new([sx - nx, sy - ny, 0.0], NORMAL_2D, color));
+ vertices.push(Vertex::new([sx + nx, sy + ny, 0.0], NORMAL_2D, color));
+ vertices.push(Vertex::new([ex + nx, ey + ny, 0.0], NORMAL_2D, color));
+ vertices.push(Vertex::new([ex - nx, ey - ny, 0.0], NORMAL_2D, color));
+
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+ indices.push(base);
+ indices.push(base + 2);
+ indices.push(base + 3);
+
+ dist += pattern_len;
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl Brace {
+ /// Generate a curly brace shape in 2D. The brace spans from `start` to `end`
+ /// with the curl pointing in the direction of the normal.
+ pub fn generate(
+ start: [f32; 2],
+ end: [f32; 2],
+ color: [f32; 4],
+ width: f32,
+ curl_size: f32,
+ segments: u32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let dx = end[0] - start[0];
+ let dy = end[1] - start[1];
+ let len = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let ux = dx / len;
+ let uy = dy / len;
+ // Normal pointing outward (perpendicular)
+ let nx = -uy;
+ let ny = ux;
+
+ // Build the brace as a series of quad segments following a parametric path
+ // The brace has 4 arcs: start curl, first half, second half, end curl
+ let total_segs = segments.max(16);
+ let mut path_points = Vec::with_capacity(total_segs as usize + 1);
+
+ for i in 0..=total_segs {
+ let t = i as f32 / total_segs as f32;
+
+ // Parametric brace: smooth curve from start to end with curl at middle
+ let along = start[0] + dx * t;
+ let along_y = start[1] + dy * t;
+
+ // Curl function: peaks at t=0.5, zero at t=0 and t=1
+ // Use sin^2 for smooth bump, with a sharper peak at the midpoint
+ let curl = if t < 0.5 {
+ let s = t * 2.0;
+ curl_size * (s * PI).sin()
+ } else {
+ let s = (t - 0.5) * 2.0;
+ curl_size * ((1.0 - s) * PI).sin()
+ };
+
+ // Add small hooks at the tips
+ let hook = if t < 0.05 {
+ curl_size * 0.3 * ((t / 0.05) * PI * 0.5).sin()
+ } else if t > 0.95 {
+ curl_size * 0.3 * (((1.0 - t) / 0.05) * PI * 0.5).sin()
+ } else {
+ 0.0
+ };
+
+ let px = along + nx * (curl + hook);
+ let py = along_y + ny * (curl + hook);
+ path_points.push([px, py]);
+ }
+
+ // Convert path to quad strip
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+ let half_w = width / 2.0;
+
+ for i in 0..path_points.len() {
+ let p = path_points[i];
+
+ // Compute tangent direction
+ let tangent = if i == 0 {
+ let next = path_points[1];
+ [next[0] - p[0], next[1] - p[1]]
+ } else if i == path_points.len() - 1 {
+ let prev = path_points[i - 1];
+ [p[0] - prev[0], p[1] - prev[1]]
+ } else {
+ let prev = path_points[i - 1];
+ let next = path_points[i + 1];
+ [next[0] - prev[0], next[1] - prev[1]]
+ };
+
+ let tlen = (tangent[0] * tangent[0] + tangent[1] * tangent[1])
+ .sqrt()
+ .max(1e-6);
+ let tnx = -tangent[1] / tlen * half_w;
+ let tny = tangent[0] / tlen * half_w;
+
+ vertices.push(Vertex::new(
+ [p[0] - tnx, p[1] - tny, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [p[0] + tnx, p[1] + tny, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ }
+
+ for i in 0..(path_points.len() as u32 - 1) {
+ let base = i * 2;
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+ indices.push(base + 2);
+ indices.push(base + 1);
+ indices.push(base + 3);
+ }
+
+ // Add the midpoint tip triangle
+ let mid_idx = total_segs / 2;
+ let mid_point = path_points[mid_idx as usize];
+ let tip_base = vertices.len() as u32;
+ let tip_offset = curl_size * 0.4;
+ vertices.push(Vertex::new(
+ [mid_point[0] + nx * tip_offset - ux * width, mid_point[1] + ny * tip_offset - uy * width, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [mid_point[0] + nx * tip_offset + ux * width, mid_point[1] + ny * tip_offset + uy * width, 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ vertices.push(Vertex::new(
+ [mid_point[0] + nx * (tip_offset + curl_size * 0.3), mid_point[1] + ny * (tip_offset + curl_size * 0.3), 0.0],
+ NORMAL_2D,
+ color,
+ ));
+ indices.push(tip_base);
+ indices.push(tip_base + 1);
+ indices.push(tip_base + 2);
+
+ (vertices, indices)
+ }
+}
+
+impl FilledRegion {
+ /// Generate a filled region between a curve (given as points) and the x-axis (y=baseline).
+ pub fn generate(
+ points: &[[f32; 2]],
+ baseline: f32,
+ color: [f32; 4],
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ if points.len() < 2 {
+ return (vertices, indices);
+ }
+
+ // For each point, create a vertex pair: one at the curve, one at the baseline
+ for &p in points {
+ vertices.push(Vertex::new([p[0], p[1], 0.0], NORMAL_2D, color));
+ vertices.push(Vertex::new([p[0], baseline, 0.0], NORMAL_2D, color));
+ }
+
+ // Create quads between adjacent point pairs
+ for i in 0..(points.len() as u32 - 1) {
+ let base = i * 2;
+ // Triangle 1: curve[i], baseline[i], curve[i+1]
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+ // Triangle 2: curve[i+1], baseline[i], baseline[i+1]
+ indices.push(base + 2);
+ indices.push(base + 1);
+ indices.push(base + 3);
+ }
+
+ (vertices, indices)
+ }
+}
+
+impl RiemannRects {
+ /// Generate Riemann sum rectangles for a function sampled at points.
+ /// Each rectangle spans from baseline to y_value at the sampled x position.
+ pub fn generate(
+ x_positions: &[f32],
+ y_values: &[f32],
+ dx: f32,
+ baseline: f32,
+ fill_color: [f32; 4],
+ stroke_color: [f32; 4],
+ stroke_width: f32,
+ ) -> (Vec<Vertex>, Vec<u32>) {
+ let mut vertices = Vec::new();
+ let mut indices = Vec::new();
+
+ let half_dx = dx / 2.0;
+
+ for (&x, &y) in x_positions.iter().zip(y_values.iter()) {
+ let base = vertices.len() as u32;
+
+ // Rectangle fill (2 triangles)
+ let left = x - half_dx;
+ let right = x + half_dx;
+ let bot = baseline;
+ let top = y;
+
+ vertices.push(Vertex::new([left, bot, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([right, bot, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([right, top, 0.0], NORMAL_2D, fill_color));
+ vertices.push(Vertex::new([left, top, 0.0], NORMAL_2D, fill_color));
+
+ indices.push(base);
+ indices.push(base + 1);
+ indices.push(base + 2);
+ indices.push(base);
+ indices.push(base + 2);
+ indices.push(base + 3);
+
+ // Stroke outline
+ if stroke_width > 0.0 {
+ let hw = stroke_width / 2.0;
+ let corners: [[f32; 2]; 4] = [
+ [left, bot],
+ [right, bot],
+ [right, top],
+ [left, top],
+ ];
+
+ for edge in 0..4u32 {
+ let curr = corners[edge as usize];
+ let next = corners[((edge + 1) % 4) as usize];
+
+ let edx = next[0] - curr[0];
+ let edy = next[1] - curr[1];
+ let elen = (edx * edx + edy * edy).sqrt().max(1e-6);
+ let enx = -edy / elen * hw;
+ let eny = edx / elen * hw;
+
+ let sb = vertices.len() as u32;
+ vertices.push(Vertex::new(
+ [curr[0] - enx, curr[1] - eny, 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [curr[0] + enx, curr[1] + eny, 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [next[0] + enx, next[1] + eny, 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+ vertices.push(Vertex::new(
+ [next[0] - enx, next[1] - eny, 0.0],
+ NORMAL_2D,
+ stroke_color,
+ ));
+
+ indices.push(sb);
+ indices.push(sb + 1);
+ indices.push(sb + 2);
+ indices.push(sb);
+ indices.push(sb + 2);
+ indices.push(sb + 3);
+ }
+ }
+ }
+
+ (vertices, indices)
+ }
+}
diff --git a/src/manimgx/drawing/paint.py b/src/manimgx/drawing/paint.py
index f25f9209..79a41b85 100644
--- a/src/manimgx/drawing/paint.py
+++ b/src/manimgx/drawing/paint.py
@@ -1,3 +1,8 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
"""Colors and immutable paint shared by paths, points and meshes.
Colors retain exact RGBA beside their string form. Paint owns the brushes and
@@ -12,6 +17,7 @@ from dataclasses import dataclass
from enum import Enum
from pathlib import PurePath
from typing import TYPE_CHECKING, Final, Self, TypedDict, TypeIs, cast, overload
+from warnings import deprecated
import numpy as np
import numpy.typing as npt
@@ -161,6 +167,7 @@ _LMS_INV: Floats = np.linalg.inv(_LMS)
_LAB_INV: Floats = np.linalg.inv(_LAB)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def to_oklab(rgb: Floats) -> Floats:
"""Convert sRGB colors to OKLab, the color space colors are mixed in.
@@ -178,6 +185,7 @@ def to_oklab(rgb: Floats) -> Floats:
return np.cbrt(linear @ _LMS.T) @ _LAB.T
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def from_oklab(lab: Floats) -> Floats:
"""Convert OKLab colors to sRGB, clipped to the colors a screen shows.
@@ -208,6 +216,7 @@ def _lab(rgba: Floats) -> Floats:
return known[1]
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def mix_rgba(a: Floats, b: Floats, t: float | Floats) -> Floats:
"""Mix colors given as rows of red, green, blue and opacity: `a` at 0, `b` at 1.
@@ -324,6 +333,7 @@ class ManimColor(str):
alpha: float = 1.0,
) -> list[Self]: ...
@classmethod
+ @deprecated("use ManimColor(...)", category=None)
def parse(
cls,
value: "ParsableManimColor | Sequence[ParsableManimColor] | None",
@@ -365,6 +375,7 @@ class ManimColor(str):
"""
return self._rgba
+ @deprecated("use to_rgba", category=None)
def to_rgba_with_alpha(self, alpha: float) -> np.ndarray:
"""The color's red, green and blue, with another opacity.
@@ -390,7 +401,8 @@ class ManimColor(str):
def interpolate(self, other: "ManimColor", alpha: float) -> "ManimColor":
"""The color a fraction of the way from this one to another, mixed as every
- blend of colors is (see [mix_rgba][manimgx.mix_rgba]).
+ blend of colors is: in OKLab, where the colors between two are those the eye sees
+ between them.
Args:
other: The color at 1.
@@ -516,6 +528,7 @@ class ManimColor(str):
"""
return np.array(colorsys.rgb_to_hsv(*self.to_rgb()))
+ @deprecated("use HSV(...)", category=None)
def into[C: "ManimColor"](self, cls: type[C]) -> C:
"""This color as an instance of another color class, such as
[HSV][manimgx.HSV].
@@ -637,6 +650,7 @@ def _parse(value: "ParsableManimColor | None", alpha: float) -> np.ndarray:
raise ValueError(f"ManimColor accepts length 3 or 4 sequences, not {len(arr)}")
+@deprecated("color_to_rgb(color) is ManimColor(color).to_rgb(): use it", category=None)
def color_to_rgb(color: ParsableManimColor) -> np.ndarray:
"""The red, green and blue of a color.
@@ -649,6 +663,7 @@ def color_to_rgb(color: ParsableManimColor) -> np.ndarray:
return ManimColor(color).to_rgb()
+@deprecated("rgb_to_color(rgb) is ManimColor.from_rgb(rgb): use it", category=None)
def rgb_to_color(rgb: Sequence[float] | np.ndarray) -> ManimColor:
"""The color of a red, green and blue.
@@ -676,8 +691,8 @@ def invert_color(color: ParsableManimColor) -> ManimColor:
def interpolate_color(a: ManimColor, b: ManimColor, alpha: float) -> ManimColor:
"""The color a fraction of the way from one color to another.
- The two mix as every blend of colors does (see [mix_rgba][manimgx.mix_rgba]): in
- OKLab, where the colors between two are those the eye sees between them.
+ The two mix as every blend of colors does: in OKLab, where the colors between two
+ are those the eye sees between them.
Args:
a: The color at 0.
@@ -765,9 +780,9 @@ def average_color(*colors: ParsableManimColor) -> ManimColor:
return ManimColor(tuple(from_oklab(lab)))
-type Colorscale = Sequence[ParsableManimColor] | Sequence[
- tuple[ParsableManimColor, float]
-]
+type Colorscale = (
+ Sequence[ParsableManimColor] | Sequence[tuple[ParsableManimColor, float]]
+)
"""Colors for a range of values: colors spread evenly over the range, or (color, value)
pairs, each color at its value (see [colors_by_value][manimgx.colors_by_value])."""
@@ -778,8 +793,8 @@ def colors_by_value(
"""The color of each value on a colorscale: mixed between the colors on either side
of it, and held beyond the colorscale's ends.
- The colors mix as every blend of colors does (see [mix_rgba][manimgx.mix_rgba]);
- [rgbas_by_value][manimgx.rgbas_by_value] gives the same colors as rows of numbers.
+ The colors mix as every blend of colors does: in OKLab, where the colors between
+ two are those the eye sees between them.
Args:
colorscale: Colors spread evenly from `low` to `high`, or (color, value) pairs,
@@ -795,6 +810,7 @@ def colors_by_value(
return [ManimColor(tuple(row)) for row in rows]
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def rgbas_by_value(
colorscale: Colorscale, values: npt.ArrayLike, low: float, high: float
) -> Floats:
@@ -867,6 +883,7 @@ def _numbers(value: object) -> TypeIs[Sequence[float] | np.ndarray]:
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def parse_colors(
value: ParsableManimColor | Iterable[ParsableManimColor] | None,
) -> list[ManimColor]:
@@ -1114,11 +1131,15 @@ class Material:
class MaterialExample(m.ThreeDScene):
def construct(self) -> None:
self.set_camera_orientation(phi=70 * m.DEGREES, theta=-45 * m.DEGREES)
- self.add(m.SunLight(5 * m.UP + 3 * m.OUT), m.AmbientLight(intensity=0.2))
+ self.add(
+ m.SunLight(5 * m.UP + 3 * m.OUT), m.AmbientLight(intensity=0.2)
+ )
for i, roughness in enumerate([0.2, 0.5, 0.9]):
sphere = m.Sphere(radius=0.8, resolution=(48, 48))
sphere.set_color(m.GOLD).shift(2 * (i - 1) * m.RIGHT)
- self.add(sphere.set_material(m.Material(metallic=1, roughness=roughness)))
+ self.add(
+ sphere.set_material(m.Material(metallic=1, roughness=roughness))
+ )
```
"""
@@ -1126,6 +1147,7 @@ class Material:
roughness: float = 0.5
reflectance: float = 0.5
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def mixed(self, other: "Material", alpha: float) -> "Material":
"""This material's numbers moved `alpha` of the way to `other`'s."""
return Material(
@@ -1348,7 +1370,6 @@ def stretch_array(array: np.ndarray, n: int) -> np.ndarray:
Returns:
The array itself if it has `n` items; else a new one.
"""
- # CE's `stretch_array_to_length`
cur = len(array)
if cur == n:
return array
@@ -1357,6 +1378,12 @@ def stretch_array(array: np.ndarray, n: int) -> np.ndarray:
return array[(np.arange(n) * cur // n).astype(int)]
+@deprecated("stretch_array_to_length is stretch_array: use it", category=None)
+def stretch_array_to_length(array: np.ndarray, n: int) -> np.ndarray:
+ """Manim CE's name for [stretch_array][manimgx.stretch_array]."""
+ return stretch_array(array, n)
+
+
def frozen(values: npt.ArrayLike, held: object = None) -> np.ndarray:
"""Adopt an internal float array as read-only; keep `held` when they are equal.
@@ -1480,6 +1507,7 @@ class Paint:
def _but(self, changes: dict[str, object]) -> "Paint":
fields = self.__dict__.copy()
changed = False
+ numbers: list[tuple[object, object]] = [] # given anew: equal to those held?
for name, value in changes.items():
slot = _SLOTS.get(name, name)
held = getattr(self, slot, None)
@@ -1491,9 +1519,13 @@ class Paint:
and unchanged(value, held)
):
value = held
+ elif name in _NUMERIC and value is not held:
+ numbers.append((value, held)) # (compared only if nothing else changes)
+ fields[slot] = value
+ continue
changed = changed or value is not held
fields[slot] = value
- if not changed:
+ if not changed and all(_same_number(*pair) for pair in numbers):
return self
fields["_derived"] = {}
if fields.get("mix") is not None and all(
@@ -1504,10 +1536,12 @@ class Paint:
object.__setattr__(new, "__dict__", fields)
return new
- def window(self, curves: int) -> tuple[float, float]:
- """The reveal window over the curve parameter u ∈ [0, curves] — what the player draws."""
+ def window(self, steps: int) -> tuple[float, float]:
+ """The reveal window over u ∈ [0, steps] — what the player draws. u counts a shape's
+ steps: a path's curves (its parameter, paced by `pace`), a cloud's points, a mesh's
+ triangles, a surface's faces; a step the window reaches into shows, with all it draws."""
if self.pace is None:
- return float(self.trim[0]) * curves, float(self.trim[1]) * curves
+ return float(self.trim[0]) * steps, float(self.trim[1]) * steps
s, u = self.pace
lo, hi = np.interp(self.trim, s, u)
return float(lo), float(hi)
@@ -1655,8 +1689,30 @@ def _kept(name: str, value: object) -> object:
_BRUSHES = ("fill", "stroke", "background")
+
+
+# numbers as concrete classes: `isinstance` on an ABC (`numbers.Real`) is slow
+_NUMBERS = (int, float, np.number)
+
+
+def _same_number(value: object, held: object) -> bool:
+ """Whether `value` is a number, or a tuple of numbers (a dash), equal to the one held: a
+ change to it is none (an equal width of another type, or another object, keeps the
+ paint)."""
+ if isinstance(value, _NUMBERS): # (as floats: a numpy scalar's == is a ufunc's)
+ return isinstance(held, _NUMBERS) and float(value) == float(held)
+ return (
+ isinstance(value, tuple)
+ and isinstance(held, tuple)
+ and len(value) == len(held) > 0
+ and isinstance(value[0], _NUMBERS)
+ and all(map(_same_number, value, held))
+ )
+
+
_SLOTS = {"fill": "_fill", "stroke": "_stroke", "background": "_background"}
_ARRAYS = ("_fill", "_stroke", "_background", "sheen_direction", "trim")
+_NUMERIC = frozenset({"stroke_width", "background_width", "sheen_factor", "dash"})
class PaintAttribute[G, S = G]:
diff --git a/src/manimgx/mobjects/annotations.py b/src/manimgx/mobjects/annotations.py
new file mode 100644
index 00000000..4657e7ce
--- /dev/null
+++ b/src/manimgx/mobjects/annotations.py
@@ -0,0 +1,1018 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
+"Frames, braces and labels placed relative to existing geometric objects."
+
+from __future__ import annotations
+
+__all__ = [
+ "ArcBrace",
+ "BackgroundRectangle",
+ "Brace",
+ "BraceBetweenPoints",
+ "BraceLabel",
+ "BraceText",
+ "Cross",
+ "Label",
+ "LabeledArrow",
+ "LabeledDot",
+ "LabeledLine",
+ "LabeledPolygram",
+ "SurroundingRectangle",
+ "Underline",
+]
+
+from collections.abc import Callable, Sequence
+from typing import TYPE_CHECKING, ClassVar, Self, Unpack
+
+import numpy as np
+
+from manimgx.config import config
+from manimgx.constants import (
+ DEFAULT_FONT_SIZE,
+ DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ DOWN,
+ LEFT,
+ ORIGIN,
+ RIGHT,
+ SMALL_BUFF,
+ UP,
+)
+from manimgx.drawing.geometry import polylabel
+from manimgx.drawing.paint import (
+ BLACK,
+ PURE_YELLOW,
+ RED,
+ WHITE,
+ Look,
+ ParsableManimColor,
+ Style,
+)
+from manimgx.mobject import Mobject, Placement, VGroup, VMobject, _family, _family_box
+from manimgx.mobjects.shapes import (
+ Arc,
+ Arced,
+ Arrow,
+ Dot,
+ Line,
+ LineOptions,
+ Polygram,
+ RoundedRectangle,
+ Tipped,
+)
+from manimgx.mobjects.svg import VMobjectFromSVGPath
+from manimgx.mobjects.text import (
+ MathTex,
+ MathTexOptions,
+ Tex,
+ Text,
+ Typst,
+ TypstOptions,
+)
+from manimgx.typing import ManimTextLabel
+
+if TYPE_CHECKING:
+ from manimgx.mobject import Mobject
+ from manimgx.typing import (
+ ManimTextLabel,
+ Point3D,
+ Point3DLike,
+ Point3DLike_Array,
+ Vector3D,
+ Vector3DLike,
+ )
+
+
+class FrameOptions(Style, total=False):
+ """The keywords of a rectangle made around a mobject, as a
+ [SurroundingRectangle][manimgx.SurroundingRectangle] or a
+ [BackgroundRectangle][manimgx.BackgroundRectangle] is: its margin and its corners,
+ with the style keywords (for the classes that pass them on)."""
+
+ buff: float | tuple[float, float]
+ """The margin around the mobject, in scene units: one for all sides, or
+ (horizontal, vertical) (default 0.1 around a surrounding rectangle, 0 behind a
+ background rectangle)."""
+ corner_radius: float
+ """The radius of the rectangle's corners, in scene units (default 0: square
+ corners)."""
+
+
+class SurroundingRectangle(RoundedRectangle):
+ r"""A rectangle around mobjects: around their bounding box, all of them together,
+ with a margin; bright yellow (`PURE_YELLOW`) unless styled.
+
+ It is sized and placed when it is made, and does not follow the mobjects
+ afterwards.
+
+ Args:
+ *mobjects: The mobjects to surround.
+ buff: The margin around them, in scene units: one for all sides, or
+ (horizontal, vertical).
+ corner_radius: The radius of its corners, in scene units: 0 for square
+ corners.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class SurroundingRectangleExample(m.Scene):
+ def construct(self) -> None:
+ formula = m.MathTex(r"e^{i\pi} + 1 = 0", font_size=96)
+ words = m.Text("Euler's identity").next_to(formula, m.DOWN, buff=1)
+ self.add(formula, words)
+ self.play(
+ m.Create(m.SurroundingRectangle(formula, buff=0.3)),
+ m.Create(
+ m.SurroundingRectangle(words, corner_radius=0.2, color=m.BLUE)
+ ),
+ )
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": PURE_YELLOW}
+
+ def __init__(
+ self,
+ *mobjects: Mobject,
+ buff: float | tuple[float, float] = SMALL_BUFF,
+ corner_radius: float = 0.0,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ if not all(isinstance(mob, Mobject) for mob in mobjects):
+ raise TypeError(
+ "Expected all inputs for parameter mobjects to be a Mobjects"
+ )
+ if isinstance(buff, tuple):
+ buff_x = buff[0]
+ buff_y = buff[1]
+ else:
+ buff_x = buff_y = buff
+ box = _family_box(_family(mobjects))
+ width = (0.0 if box is None else float(box[1, 0] - box[0, 0])) + 2 * buff_x
+ box = _family_box(_family(mobjects))
+ height = (0.0 if box is None else float(box[1, 1] - box[0, 1])) + 2 * buff_y
+ super().__init__(
+ width=width,
+ height=height,
+ corner_radius=corner_radius,
+ **kwargs,
+ )
+ self.buff = buff
+ box = _family_box(_family(mobjects))
+ center = (
+ np.zeros(3)
+ if box is None
+ else np.array([(low + high) / 2 for low, high in zip(*box.tolist())])
+ )
+ self.move_to(center)
+
+
+class BackgroundRectangle(SurroundingRectangle):
+ """A rectangle behind mobjects, in the background's color and three quarters
+ opaque, so they stand out from what lies behind them; without an outline.
+
+ Its color is the scene's background color when it is made, unless given. It goes
+ behind the mobjects: add it to the scene before them.
+
+ Args:
+ *mobjects: The mobjects to go behind.
+ buff: The margin around them, in scene units: one for all sides, or
+ (horizontal, vertical).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BackgroundRectangleExample(m.Scene):
+ def construct(self) -> None:
+ bare = m.Text("on the grid", font_size=60).shift(3.5 * m.LEFT)
+ backed = m.Text("on a background", font_size=60).shift(3.2 * m.RIGHT)
+ background = m.BackgroundRectangle(backed, buff=0.2)
+ self.add(m.NumberPlane(), bare, background, backed)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {
+ "stroke_width": 0,
+ "stroke_opacity": 0.0,
+ "fill_opacity": 0.75,
+ }
+
+ def __init__(
+ self,
+ *mobjects: Mobject,
+ buff: float | tuple[float, float] = 0,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ if kwargs.get("color") is None: # not given (None too): the scene's, when made
+ kwargs["color"] = config.background_color
+ super().__init__(*mobjects, buff=buff, **kwargs)
+ self.original_fill_opacity: float = self.fill_opacity
+
+
+class Cross(VGroup):
+ """A cross, an X: two lines from corner to corner of a mobject's bounding box, or of
+ a square 2 on a side at the origin; red, 6 wide, unless styled.
+
+ Args:
+ mobject: The mobject to cross out: the cross is stretched over its bounding
+ box; None for none.
+ stroke_color: The color of its lines.
+ stroke_width: The width of its lines, in hundredths of a scene unit.
+ scale_factor: How much larger than the bounding box (or the square) it is,
+ about its center.
+ color: The color of its lines, in place of `stroke_color`; None to use that.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CrossExample(m.Scene):
+ def construct(self) -> None:
+ wrong = m.MathTex("2 + 2 = 5", font_size=96).shift(2 * m.RIGHT)
+ self.add(m.Cross().shift(4 * m.LEFT), wrong)
+ self.play(m.Create(m.Cross(wrong, scale_factor=1.2, color=m.YELLOW)))
+ ```
+ """
+
+ def __init__(
+ self,
+ mobject: Mobject | None = None,
+ stroke_color: ParsableManimColor = RED,
+ stroke_width: float = 6.0,
+ scale_factor: float = 1.0,
+ color: ParsableManimColor | None = None,
+ **kwargs: Unpack[Look],
+ ) -> None:
+ super().__init__(
+ Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT), **kwargs
+ )
+ if mobject is not None:
+ self.replace(mobject, stretch=True)
+ self.scale(scale_factor)
+ self.set_stroke(
+ color=stroke_color if color is None else color, width=stroke_width
+ )
+
+
+class Underline(Line):
+ """A line under a mobject: as wide as it, `buff` below it; white unless styled.
+
+ It is sized and placed when it is made, and does not follow the mobject afterwards.
+
+ Args:
+ mobject: The mobject to underline.
+ buff: The gap between the mobject and the line, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class UnderlineExample(m.Scene):
+ def construct(self) -> None:
+ word = m.Text("important", font_size=120)
+ self.add(word)
+ self.play(m.Create(m.Underline(word, buff=0.2, color=m.YELLOW)))
+ ```
+ """
+
+ def __init__(
+ self, mobject: Mobject, buff: float = SMALL_BUFF, **kwargs: Unpack[Arced]
+ ) -> None:
+ super().__init__(LEFT, RIGHT, buff=buff, **kwargs)
+ self.match_width(mobject)
+ self.next_to(mobject, DOWN, buff=self.buff)
+
+
+class Label(VGroup):
+ """A label on a background, in a frame: text or math, over an opaque rectangle in
+ the background's color, inside a thin white outline.
+
+ A string is typeset as math, white, at font size 48 (see
+ [MathTex][manimgx.MathTex]); a mobject of text or math is used as it is. Its parts
+ are its submobjects, in drawing order: its
+ [background_rect][manimgx.Label.background_rect], its
+ [rendered_label][manimgx.Label.rendered_label] and its
+ [frame][manimgx.Label.frame].
+
+ Args:
+ label: The label: a string, typeset as math, or a text or math mobject.
+ label_config: [MathTex
+ keywords][manimgx.mobjects.text.MathTexOptions] for a string
+ label, over white at font size 48.
+ box_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ background, over a margin of 0.05 and an opaque fill (see
+ [BackgroundRectangle][manimgx.BackgroundRectangle]).
+ frame_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ frame, over white, a margin of 0.05 and an outline 0.5 wide.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself; its
+ parts keep the styles the configs give them.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LabelExample(m.Scene):
+ def construct(self) -> None:
+ plain = m.Label("x^2 + y^2 = r^2")
+ styled = m.Label(
+ m.Text("a label", color=m.YELLOW),
+ box_config={"color": m.BLUE, "buff": 0.2},
+ frame_config={"color": m.YELLOW, "stroke_width": 4, "buff": 0.2},
+ )
+ self.add(m.VGroup(plain, styled).arrange(m.DOWN, buff=1).scale(2))
+ ```
+ """
+
+ def __init__(
+ self,
+ label: str | ManimTextLabel,
+ label_config: MathTexOptions | None = None,
+ box_config: FrameOptions | None = None,
+ frame_config: FrameOptions | None = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(**kwargs)
+ label_style = MathTexOptions(color=WHITE, font_size=DEFAULT_FONT_SIZE) | (
+ label_config or MathTexOptions()
+ )
+ box_style = FrameOptions(buff=0.05, fill_opacity=1, stroke_width=0.5) | (
+ box_config or FrameOptions()
+ )
+ frame_style = FrameOptions(color=WHITE, buff=0.05, stroke_width=0.5) | (
+ frame_config or FrameOptions()
+ )
+ if isinstance(label, str):
+ self.rendered_label: ManimTextLabel = MathTex(label, **label_style)
+ """The label's text or math, a submobject."""
+ elif isinstance(label, Typst):
+ self.rendered_label = label
+ else:
+ raise TypeError(
+ "Unsupported label type. Must be MathTex, Tex, Text or Typst."
+ )
+ self.background_rect = BackgroundRectangle(self.rendered_label, **box_style)
+ """The rectangle behind the label, a submobject."""
+ self.frame = SurroundingRectangle(self.rendered_label, **frame_style)
+ """The outline around the label, a submobject."""
+ self.add(self.background_rect, self.rendered_label, self.frame)
+
+
+class LabeledLine(Line):
+ """A line with a label on it: a [Label][manimgx.Label] centered at a point
+ `label_position` of the way from the line's start to its end; white unless styled.
+
+ The label is a submobject, the line's [label][manimgx.LabeledLine.label]. It is
+ placed on the straight way between the ends, even when the line is bent.
+
+ Args:
+ label: The label: a string, typeset as math, or a text or math mobject.
+ label_position: Where the label goes, as a proportion of the way from the
+ line's start (0) to its end (1).
+ label_config: [MathTex
+ keywords][manimgx.mobjects.text.MathTexOptions] for a string
+ label (see [Label][manimgx.Label]).
+ box_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's background.
+ frame_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's frame.
+ start: Where the line starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it ends: a point, or a mobject.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LabeledLineExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [-4, -2, 0], [4, -2, 0], [4, 2.5, 0]
+ sides = m.VGroup(
+ m.LabeledLine("8", start=a, end=b, color=m.BLUE),
+ m.LabeledLine("4.5", start=b, end=c, color=m.GREEN),
+ m.LabeledLine("c", start=c, end=a, label_position=0.4),
+ )
+ self.add(sides)
+ ```
+ """
+
+ def __init__(
+ self,
+ label: str | ManimTextLabel,
+ label_position: float = 0.5,
+ label_config: MathTexOptions | None = None,
+ box_config: FrameOptions | None = None,
+ frame_config: FrameOptions | None = None,
+ *,
+ start: Point3DLike | Mobject = LEFT,
+ end: Point3DLike | Mobject = RIGHT,
+ **kwargs: Unpack[LineOptions],
+ ) -> None:
+ super().__init__(start, end, **kwargs)
+ self.label = Label(
+ label=label,
+ label_config=label_config,
+ box_config=box_config,
+ frame_config=frame_config,
+ )
+ """The label, a submobject."""
+ line_start, line_end = self.get_start_and_end()
+ self.label.move_to(line_start + (line_end - line_start) * label_position)
+ self.add(self.label)
+
+
+class LabeledArrow(LabeledLine, Arrow):
+ """An arrow with a label on it: a [LabeledLine][manimgx.LabeledLine] that is an
+ [Arrow][manimgx.Arrow], stopping 0.25 short of its ends unless given another
+ `buff`; white unless styled.
+
+ Args:
+ label: The label: a string, typeset as math, or a text or math mobject.
+ label_position: Where the label goes, as a proportion of the way from the
+ arrow's start (0) to its tip's point (1).
+ label_config: [MathTex
+ keywords][manimgx.mobjects.text.MathTexOptions] for a string
+ label (see [Label][manimgx.Label]).
+ box_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's background.
+ frame_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's frame.
+ start: Where the arrow starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it points to: a point, or a mobject.
+ **kwargs: [Line keywords][manimgx.mobjects.shapes.LineOptions].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LabeledArrowExample(m.Scene):
+ def construct(self) -> None:
+ arrows = m.VGroup(
+ m.LabeledArrow("F", start=4 * m.LEFT, end=4 * m.RIGHT),
+ m.LabeledArrow(
+ "0.5",
+ label_position=0.3,
+ start=3 * m.LEFT + m.DOWN,
+ end=3 * m.RIGHT + 2 * m.UP,
+ color=m.YELLOW,
+ ),
+ ).arrange(m.DOWN, buff=1)
+ self.add(arrows)
+ ```
+ """
+
+
+class LabeledPolygram(Polygram):
+ """A polygram with a label inside it, at its pole of inaccessibility: the point
+ inside it farthest from its edges, found to within `precision`; blue unless styled.
+
+ The first group of vertices is its outline, and the others are holes the label is
+ kept out of. The label is a submobject, [label][manimgx.LabeledPolygram.label];
+ `pole` is where it is, and `radius` how far that is from the nearest edge.
+
+ Args:
+ *vertex_groups: The groups of vertices, each a closed path (see
+ [Polygram][manimgx.Polygram]): the outline first, then its holes.
+ label: The label: a string, typeset as math, or a text or math mobject.
+ precision: Allowed error in the largest distance from the polygon's edges,
+ in scene units. Several label positions can meet this radius tolerance.
+ label_config: [MathTex
+ keywords][manimgx.mobjects.text.MathTexOptions] for a string
+ label (see [Label][manimgx.Label]).
+ box_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's background.
+ frame_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ label's frame.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LabeledPolygramExample(m.Scene):
+ def construct(self) -> None:
+ outline = [[-6, -3, 0], [5, -3, 0], [6, 3, 0], [0, 0.5, 0], [-5, 3, 0]]
+ hole = [[0, -2, 0], [0, -0.5, 0], [4, -0.5, 0], [4, -2, 0]]
+ shape = m.LabeledPolygram(outline, hole, label="P", fill_opacity=0.3)
+ reach = m.Circle(shape.radius, color=m.YELLOW).move_to(shape.pole)
+ self.add(shape, reach)
+ ```
+ """
+
+ def __init__(
+ self,
+ *vertex_groups: Point3DLike_Array,
+ label: str | ManimTextLabel,
+ precision: float = 0.01,
+ label_config: MathTexOptions | None = None,
+ box_config: FrameOptions | None = None,
+ frame_config: FrameOptions | None = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(*vertex_groups, **kwargs)
+ self.label = Label(
+ label=label,
+ label_config=label_config,
+ box_config=box_config,
+ frame_config=frame_config,
+ )
+ """The label, a submobject."""
+ rings = []
+ for group in vertex_groups:
+ ring = np.asarray(group, dtype=float)
+ rings.append(
+ ring
+ if np.array_equal(ring[0], ring[-1])
+ else np.vstack([ring, ring[:1]])
+ )
+ cell = polylabel(rings, precision=precision)
+ self.pole, self.radius = (np.pad(cell.c, (0, 1), "constant"), cell.d)
+ self.label.move_to(self.pole)
+ self.add(self.label)
+
+
+class BraceOptions(Style, total=False):
+ """A [brace][manimgx.Brace]'s keywords but its direction, for the classes that pass
+ them on.
+
+ Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].
+ """
+
+ buff: float
+ """The gap between the mobject and the brace, in scene units (default 0.2)."""
+ sharpness: float
+ """How sharp the brace's tip and ends are: the higher, the narrower its curls
+ (default 2)."""
+
+
+class Brace(VMobjectFromSVGPath):
+ """A curly brace along a side of a mobject, as long as the mobject is wide there:
+ filled white, without an outline, unless styled.
+
+ The brace lies `buff` beyond the mobject's bounding box, on the side `direction`
+ points to, spanning the mobject across that direction, its tip pointing away; the
+ mobject is left as it is. [get_text][manimgx.Brace.get_text] and
+ [get_tex][manimgx.Brace.get_tex] label its tip.
+
+ Args:
+ mobject: The mobject to brace.
+ direction: The side the brace is on, as a direction (DOWN: below).
+ buff: The gap between the mobject and the brace, in scene units.
+ sharpness: How sharp the brace's tip and ends are: the higher, the narrower its
+ curls.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BraceExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
+ self.add(square)
+ self.play(
+ m.GrowFromCenter(m.Brace(square)),
+ m.GrowFromCenter(m.Brace(square, m.RIGHT, color=m.YELLOW)),
+ m.GrowFromCenter(m.Brace(square, m.UP, buff=0.5, color=m.GREEN)),
+ )
+ ```
+ """
+
+ defaults: ClassVar[Style] = {
+ "stroke_width": 0,
+ "fill_opacity": 1.0,
+ "background_stroke_width": 0,
+ "background_stroke_color": BLACK,
+ }
+
+ def __init__(
+ self,
+ mobject: Mobject,
+ direction: Vector3DLike = DOWN,
+ buff: float = 0.2,
+ sharpness: float = 2,
+ **kwargs: Unpack[Style],
+ ):
+ path_string_template = (
+ "m0.01216 0c-0.01152 0-0.01216 6.103e-4 -0.01216 0.01311v0.007762c0.06776"
+ " 0.122 0.1799 0.1455 0.2307 0.1455h{0}c0.03046 3.899e-4 0.07964 0.00449"
+ " 0.1246 0.02636 0.0537 0.02695 0.07418 0.05816 0.08648 0.07769 0.001562"
+ " 0.002538 0.004539 0.002563 0.01098 0.002563 0.006444-2e-8"
+ " 0.009421-2.47e-5 0.01098-0.002563 0.0123-0.01953 0.03278-0.05074"
+ " 0.08648-0.07769 0.04491-0.02187 0.09409-0.02597"
+ " 0.1246-0.02636h{0}c0.05077 0 0.1629-0.02346"
+ " 0.2307-0.1455v-0.007762c-1.78e-6 -0.0125-6.365e-4"
+ " -0.01311-0.01216-0.01311-0.006444-3.919e-8 -0.009348 2.448e-5 -0.01091"
+ " 0.002563-0.0123 0.01953-0.03278 0.05074-0.08648 0.07769-0.04491"
+ " 0.02187-0.09416 0.02597-0.1246 0.02636h{1}c-0.04786 0-0.1502"
+ " 0.02094-0.2185"
+ " 0.1256-0.06833-0.1046-0.1706-0.1256-0.2185-0.1256h{1}c-0.03046-3.899e-4"
+ " -0.07972-0.004491-0.1246-0.02636-0.0537-0.02695-0.07418-0.05816-0.08648-0.07769-0.001562-0.002538-0.004467-0.002563-0.01091-0.002563z"
+ )
+ default_min_width = 0.90552
+ self.buff = buff
+ dx, dy = np.asarray(direction, dtype=float)[:2]
+ angle = -np.arctan2(dx, dy) + np.pi
+ mobject.rotate(-angle, about_point=ORIGIN)
+ left = mobject.get_corner(DOWN + LEFT)
+ right = mobject.get_corner(DOWN + RIGHT)
+ target_width = right[0] - left[0]
+ linear_section_length = max(
+ 0, (target_width * sharpness - default_min_width) / 2
+ )
+ import svgelements as se
+
+ path = se.Path(
+ path_string_template.format(linear_section_length, -linear_section_length)
+ )
+ super().__init__(path_obj=path, **kwargs)
+ self.flip(RIGHT)
+ self.stretch_to_fit_width(target_width)
+ self.shift(left - self.get_corner(UP + LEFT) + self.buff * DOWN)
+ for mob in (mobject, self):
+ mob.rotate(angle, about_point=ORIGIN)
+
+ def put_at_tip(
+ self, mob: Mobject, use_next_to: bool = True, **kwargs: Unpack[Placement]
+ ) -> Self:
+ """Put a mobject at the brace's tip, beyond it.
+
+ Args:
+ mob: The mobject to put there.
+ use_next_to: Whether it goes next to the tip, on the side the brace points
+ to (its direction rounded to one of the eight compass directions); if
+ not, its center goes from the tip along the brace's direction, by half
+ its width and `buff`.
+ **kwargs: [Placement keywords][manimgx.mobject.Placement]: `buff`, the
+ gap, is 0.25 unless given.
+ """
+ if use_next_to:
+ mob.next_to(self.get_tip(), np.round(self.get_direction()), **kwargs)
+ else:
+ mob.move_to(self.get_tip())
+ buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_MOBJECT_BUFFER)
+ shift_distance = mob.width / 2.0 + buff
+ mob.shift(self.get_direction() * shift_distance)
+ return self
+
+ def get_text(self, *text: str, **kwargs: Unpack[Placement]) -> Tex:
+ """Make a label of LaTeX text at the brace's tip, as
+ [put_at_tip][manimgx.Brace.put_at_tip] puts it.
+
+ Args:
+ *text: The label, in LaTeX: a string per part (see [Tex][manimgx.Tex]).
+ **kwargs: [Placement keywords][manimgx.mobject.Placement].
+
+ Returns:
+ A new [Tex][manimgx.Tex], at the tip; add it to the scene.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BraceGetTextExample(m.Scene):
+ def construct(self) -> None:
+ line = m.Line([-3, -1.5, 0], [3, 1.5, 0], color=m.ORANGE)
+ normal = line.copy().rotate(m.PI / 2).get_unit_vector()
+ below, side = m.Brace(line), m.Brace(line, normal)
+ self.add(line, below, side)
+ self.play(
+ m.Write(below.get_text("Horizontal distance")),
+ m.Write(side.get_tex("x - x_1")),
+ )
+ ```
+ """
+ text_mob = Tex(*text)
+ self.put_at_tip(text_mob, **kwargs)
+ return text_mob
+
+ def get_tex(self, *tex: str, **kwargs: Unpack[Placement]) -> MathTex:
+ """Make a label of LaTeX math at the brace's tip, as
+ [put_at_tip][manimgx.Brace.put_at_tip] puts it.
+
+ Args:
+ *tex: The label, in LaTeX: a string per part (see
+ [MathTex][manimgx.MathTex]).
+ **kwargs: [Placement keywords][manimgx.mobject.Placement].
+
+ Returns:
+ A new [MathTex][manimgx.MathTex], at the tip; add it to the scene.
+ """
+ tex_mob = MathTex(*tex)
+ self.put_at_tip(tex_mob, **kwargs)
+ return tex_mob
+
+ def get_tip(self) -> Point3D:
+ """The brace's tip: the point of its middle cusp.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.points[28]
+
+ def get_direction( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: a brace's direction is a vector, a path's a winding
+ self,
+ ) -> Vector3D:
+ """The direction the brace points to: from its center to its tip.
+
+ Returns:
+ A unit vector.
+ """
+ vect = self.get_tip() - self.get_center()
+ return vect / np.linalg.norm(vect)
+
+
+type LabelMaker = Callable[
+ ..., ManimTextLabel
+] # strings (MathTex takes several) to a label
+
+
+class BraceLabelOptions(Style, total=False):
+ """A [brace label][manimgx.BraceLabel]'s keywords but its label's class, for the
+ classes that choose it.
+
+ Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].
+ """
+
+ brace_direction: Vector3DLike
+ """The side the brace is on, as a direction (default DOWN: below)."""
+ font_size: float
+ """The label's font size (default 48)."""
+ buff: float
+ """The gap between the mobject and the brace, in scene units (default 0.2)."""
+ brace_config: BraceOptions | None
+ """[Brace keywords][manimgx.mobjects.annotations.BraceOptions], over `buff` (default
+ None)."""
+
+
+class BraceLabel(VMobject):
+ r"""A brace along a side of a mobject, and a label at its tip: math unless another
+ label class is given.
+
+ Its parts are its [brace][manimgx.BraceLabel.brace] and its
+ [label][manimgx.BraceLabel.label].
+
+ Args:
+ obj: The mobject to brace.
+ text: The label: a string, or several (as a [MathTex][manimgx.MathTex]'s
+ parts).
+ brace_direction: The side the brace is on, as a direction.
+ label_constructor: The label's class: MathTex, or another text class.
+ font_size: The label's font size.
+ buff: The gap between the mobject and the brace, in scene units.
+ brace_config: [Brace keywords][manimgx.mobjects.annotations.BraceOptions], over
+ `buff`.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself, and
+ of the label when `text` is several strings.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BraceLabelExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
+ side = m.BraceLabel(square, "a", font_size=72)
+ diagonal = m.BraceLabel(square, r"a\sqrt{2}", m.UR, font_size=72)
+ self.add(square)
+ self.play(m.Write(side), m.Write(diagonal))
+ ```
+ """
+
+ def __init__(
+ self,
+ obj: Mobject,
+ text: str | Sequence[str],
+ brace_direction: Vector3DLike = DOWN,
+ label_constructor: LabelMaker = MathTex,
+ font_size: float = DEFAULT_FONT_SIZE,
+ buff: float = 0.2,
+ brace_config: BraceOptions | None = None,
+ **kwargs: Unpack[Style],
+ ):
+ self.label_constructor = label_constructor
+ super().__init__(**kwargs)
+ self.brace_direction = brace_direction
+ self.brace = Brace(
+ obj,
+ brace_direction,
+ **(BraceOptions(buff=buff) | (brace_config or BraceOptions())),
+ )
+ """The brace, a part."""
+ if isinstance(text, str):
+ self.label: ManimTextLabel = self.label_constructor(
+ text, font_size=font_size
+ )
+ """The label, at the brace's tip: a part."""
+ else:
+ self.label = self.label_constructor(*text, font_size=font_size, **kwargs)
+ self.brace.put_at_tip(self.label)
+ self.add(self.brace, self.label)
+
+ def change_label(self, *text: str, **kwargs: Unpack[TypstOptions]) -> Self:
+ """Replace the label with a new one, made of `text` by the label class, at the
+ brace's tip.
+
+ Args:
+ *text: The new label's strings.
+ **kwargs: [Typst keywords][manimgx.mobjects.text.TypstOptions]
+ for it (at font size 48 unless given).
+ """
+ self.remove(self.label)
+ self.label = self.label_constructor(*text, **kwargs)
+ self.brace.put_at_tip(self.label)
+ self.add(self.label)
+ return self
+
+
+class BraceText(BraceLabel):
+ """A brace along a side of a mobject, and a label of text at its tip: a
+ [BraceLabel][manimgx.BraceLabel] whose label is a [Text][manimgx.Text].
+
+ Args:
+ obj: The mobject to brace.
+ text: The label's text.
+ label_constructor: The label's class.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BraceTextExample(m.Scene):
+ def construct(self) -> None:
+ rectangle = m.Rectangle(width=6, height=3, color=m.BLUE)
+ width = m.BraceText(rectangle, "width")
+ height = m.BraceText(rectangle, "height", brace_direction=m.RIGHT)
+ self.add(rectangle, width, height)
+ ```
+ """
+
+ def __init__(
+ self,
+ obj: Mobject,
+ text: str | Sequence[str],
+ label_constructor: LabelMaker = Text,
+ **kwargs: Unpack[BraceLabelOptions],
+ ):
+ super().__init__(obj, text, label_constructor=label_constructor, **kwargs)
+
+
+class BraceBetweenPoints(Brace):
+ """A brace spanning the segment between two points.
+
+ Args:
+ point_1: One end.
+ point_2: The other end.
+ direction: The side the brace is on, as a direction; ORIGIN (the default) for
+ the right-hand side going from `point_1` to `point_2` (below, for points
+ from left to right).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class BraceBetweenPointsExample(m.Scene):
+ def construct(self) -> None:
+ a, b = [-3, -1, 0], [3, 2, 0]
+ self.add(m.Line(a, b), m.Dot(a), m.Dot(b))
+ brace = m.BraceBetweenPoints(a, b, color=m.YELLOW)
+ self.play(m.GrowFromCenter(brace))
+ ```
+ """
+
+ def __init__(
+ self,
+ point_1: Point3DLike,
+ point_2: Point3DLike,
+ direction: Vector3DLike = ORIGIN,
+ **kwargs: Unpack[BraceOptions],
+ ):
+ if not np.any(np.asarray(direction, dtype=float)): # a side of the line
+ line_vector = np.array(point_2, dtype=float) - np.array(
+ point_1, dtype=float
+ )
+ direction = np.array([line_vector[1], -line_vector[0], 0])
+ super().__init__(Line(point_1, point_2), direction=direction, **kwargs)
+
+
+class ArcBrace(Brace):
+ """A brace bent along an arc, outside it or inside.
+
+ Args:
+ arc: The arc to brace; None for one of radius 1, from -1 to 1 radian.
+ direction: RIGHT for the brace outside the arc, LEFT for inside.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArcBraceExample(m.Scene):
+ def construct(self) -> None:
+ arc = m.Arc(radius=2.5, angle=2 * m.PI / 3, color=m.BLUE)
+ arc.shift(1.5 * m.DOWN)
+ self.add(arc)
+ self.play(
+ m.GrowFromCenter(m.ArcBrace(arc)),
+ m.GrowFromCenter(m.ArcBrace(arc, m.LEFT, color=m.YELLOW)),
+ )
+ ```
+ """
+
+ def __init__(
+ self,
+ arc: Arc | None = None,
+ direction: Vector3DLike = RIGHT,
+ **kwargs: Unpack[BraceOptions],
+ ):
+ if arc is None:
+ arc = Arc(start_angle=-1, angle=2, radius=1)
+ arc_end_angle = arc.start_angle + arc.angle
+ line = Line(UP * arc.start_angle, UP * arc_end_angle)
+ scale_shift = RIGHT * np.log(arc.radius)
+ if arc.radius >= 1:
+ line.scale(arc.radius, about_point=ORIGIN)
+ super().__init__(line, direction=direction, **kwargs)
+ self.scale(1 / arc.radius, about_point=ORIGIN)
+ else:
+ super().__init__(line, direction=direction, **kwargs)
+ if arc.radius >= 0.3:
+ self.shift(scale_shift)
+ else:
+ self.shift(RIGHT * np.log(0.3))
+ self.apply_complex_function(np.exp)
+ self.shift(arc.get_arc_center())
+
+
+class LabeledDot(Dot):
+ r"""A dot with a label in its middle: a disc just large enough for the label unless
+ given a radius; white, without an outline, unless styled.
+
+ It is made at the origin, and the label, centered on it, is its submobject.
+
+ Args:
+ label: The label: a string, typeset as math in black (see
+ [MathTex][manimgx.MathTex]), or a mobject, as it is.
+ radius: Its radius, in scene units; None for half the diagonal of the label's
+ bounding box, plus `buff`.
+ buff: The margin between the label's corners and the dot's edge, in scene
+ units, when the radius fits the label.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LabeledDotExample(m.Scene):
+ def construct(self) -> None:
+ dots = m.VGroup(
+ m.LabeledDot("A"),
+ m.LabeledDot("42", color=m.BLUE),
+ m.LabeledDot(m.MathTex(r"\alpha"), color=m.PURPLE, radius=0.5),
+ m.LabeledDot(m.Text("hi", color=m.BLACK), color=m.YELLOW),
+ ).arrange(buff=1)
+ self.add(dots.scale(2))
+ ```
+ """
+
+ def __init__(
+ self,
+ label: str | Mobject,
+ radius: float | None = None,
+ buff: float = SMALL_BUFF,
+ **kwargs: Unpack[Tipped],
+ ) -> None:
+ if isinstance(label, str):
+ from manimgx.mobjects.text import MathTex
+
+ rendered_label: Mobject = MathTex(label, color=BLACK)
+ else:
+ rendered_label = label
+ if radius is None:
+ radius = buff + float(
+ np.linalg.norm([rendered_label.width, rendered_label.height]) / 2
+ )
+ super().__init__(radius=radius, **kwargs)
+ rendered_label.move_to(self.get_center())
+ self.add(rendered_label)
diff --git a/tests/unit/mobjects/test_annotations.py b/tests/unit/mobjects/test_annotations.py
new file mode 100644
index 00000000..7263a601
--- /dev/null
+++ b/tests/unit/mobjects/test_annotations.py
@@ -0,0 +1,30 @@
+"""A rectangle surrounding mobjects is their box grown by its buffer on each side, at their
+center."""
+
+import numpy as np
+from hypothesis import given
+from hypothesis import strategies as st
+from tests.strategies import drawn
+
+import manimgx as m
+
+
+@given(
+ targets=st.lists(drawn, min_size=1, max_size=2),
+ buff=st.floats(0, 1) | st.tuples(st.floats(0, 1), st.floats(0, 1)),
+)
+def test_a_surrounding_rectangle_is_the_box_grown_by_its_buffer(
+ targets: list[m.Mobject], buff: float | tuple[float, float]
+) -> None:
+ box = m.Group(*targets).boundary_box()
+ assert box is not None
+ grown = np.array(buff if isinstance(buff, tuple) else (buff, buff))
+ rectangle = m.SurroundingRectangle(*targets, buff=buff)
+ tolerance = 1e-9 * (1 + np.abs(box).max())
+ np.testing.assert_allclose(
+ rectangle.get_corner(m.DL)[:2], box[0, :2] - grown, atol=tolerance
+ )
+ np.testing.assert_allclose(
+ rectangle.get_corner(m.UR)[:2], box[1, :2] + grown, atol=tolerance
+ )
+ np.testing.assert_allclose(rectangle.get_center(), box.mean(axis=0), atol=tolerance)