A community-maintained Python framework for creating mathematical animations.
Basic Arc Animation
Devin Nealbbd52a35f660
diff --git a/example_scenes/basic.py b/example_scenes/basic.pyindex 5f691d121..10be4ff19 100644--- a/example_scenes/basic.py+++ b/example_scenes/basic.py@@ -85,11 +85,10 @@ class SquareToCircle(Scene):# self.play(Transform(square, circle))# self.play(FadeOut(square))- square = Arc()- square2 = Arc()- square2.data["points"] += 2 * RIGHT- square2.points += 2 * RIGHT- self.play(Transform(square, square2))+ mob = ArcBetweenPoints(LEFT, RIGHT)+ mob2 = ArcBetweenPoints(LEFT, RIGHT)+ mob2.shift(RIGHT)+ self.play(Transform(mob, mob2))class WarpSquare(Scene):diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.pyindex f44b58796..aa83f94ea 100644--- a/manim/mobject/mobject.py+++ b/manim/mobject/mobject.py@@ -29,6 +29,7 @@ from ..utils.simple_functions import get_parametersfrom ..utils.space_ops import angle_of_vectorfrom ..utils.space_ops import get_normfrom ..utils.space_ops import rotation_matrix+from ..utils.space_ops import rotation_matrix_transpose# TODO: Explain array_attrs@@ -61,13 +62,16 @@ class Mobject(Container):self.generate_points()self.init_colors()+ # OpenGL data.self.data = dict()self.depth_test = Falseself.is_fixed_in_frame = Falseself.gloss = 0.0self.shadow = 0.0+ self.needs_new_bounding_box = True+ self.parents = []+ self.family = [self]- # OpenGL data.self.init_gl_data()self.init_gl_points()self.init_gl_colors()@@ -83,6 +87,30 @@ class Mobject(Container):def init_gl_colors(self):pass+ def get_bounding_box(self):+ if self.needs_new_bounding_box:+ self.data["bounding_box"] = self.compute_bounding_box()+ self.needs_new_bounding_box = False+ return self.data["bounding_box"]++ def compute_bounding_box(self):+ all_points = np.vstack([+ self.data["points"],+ *(+ mob.get_bounding_box()+ for mob in self.get_family()[1:]+ if mob.has_points()+ )+ ])+ if len(all_points) == 0:+ return np.zeros((3, self.dim))+ else:+ # Lower left and upper right corners+ mins = all_points.min(0)+ maxs = all_points.max(0)+ mids = (mins + maxs) / 2+ return np.array([mins, mids, maxs])+@propertydef animate(self):"""Used to animate the application of a method.@@ -156,8 +184,13 @@ class Mobject(Container):# Typically implemented in subclass, unless purposefully left blankpass- def refresh_bounding_box(self):- pass+ def refresh_bounding_box(self, recurse_down=False, recurse_up=True):+ for mob in self.get_family(recurse_down):+ mob.needs_new_bounding_box = True+ if recurse_up:+ for parent in self.parents:+ parent.refresh_bounding_box()+ return selfdef add(self, *mobjects):"""Add mobjects as submobjects.@@ -217,13 +250,24 @@ class Mobject(Container):ValueError: Mobject cannot contain self"""- for m in mobjects:- if not isinstance(m, Mobject):- raise TypeError("All submobjects must be of type Mobject")- if m is self:- raise ValueError("Mobject cannot contain self")- self.submobjects = list_update(self.submobjects, mobjects)- return self+ if config["use_opengl_renderer"]:+ if self in mobjects:+ raise Exception("Mobject cannot contain self")+ for mobject in mobjects:+ if mobject not in self.submobjects:+ self.submobjects.append(mobject)+ if self not in mobject.parents:+ mobject.parents.append(self)+ self.assemble_family()+ return self+ else:+ for m in mobjects:+ if not isinstance(m, Mobject):+ raise TypeError("All submobjects must be of type Mobject")+ if m is self:+ raise ValueError("Mobject cannot contain self")+ self.submobjects = list_update(self.submobjects, mobjects)+ return selfdef __add__(self, mobject):raise NotImplementedError@@ -600,11 +644,21 @@ class Mobject(Container):func(mob)def shift(self, *vectors):- total_vector = reduce(op.add, vectors)- for mob in self.family_members_with_points():- mob.points = mob.points.astype("float")- mob.points += total_vector- return self+ if config["use_opengl_renderer"]:+ self.apply_points_function(+ lambda points: points + vectors[0],+ about_edge=None,+ works_on_bounding_box=True,+ )+ return self+ else:+ total_vector = reduce(op.add, vectors)+ for mob in self.family_members_with_points():+ mob.points = mob.points.astype("float")+ mob.points += total_vector+ if hasattr(mob, 'data') and 'points' in mob.data:+ mob.data['points'] += total_vector+ return selfdef scale(self, scale_factor, **kwargs):"""@@ -616,20 +670,36 @@ class Mobject(Container):Otherwise, if about_point is given a value, scaling is done withrespect to that point."""- self.apply_points_function_about_point(- lambda points: scale_factor * points, **kwargs- )- return self+ if config["use_opengl_renderer"]:+ self.apply_points_function(+ lambda points: scale_factor * points,+ works_on_bounding_box=True,+ **kwargs+ )+ return self+ else:+ self.apply_points_function_about_point(+ lambda points: scale_factor * points, **kwargs+ )+ return selfdef rotate_about_origin(self, angle, axis=OUT, axes=[]):return self.rotate(angle, axis, about_point=ORIGIN)def rotate(self, angle, axis=OUT, **kwargs):- rot_matrix = rotation_matrix(angle, axis)- self.apply_points_function_about_point(- lambda points: np.dot(points, rot_matrix.T), **kwargs- )- return self+ if config["use_opengl_renderer"]:+ rot_matrix_T = rotation_matrix_transpose(angle, axis)+ self.apply_points_function(+ lambda points: np.dot(points, rot_matrix_T),+ **kwargs+ )+ return self+ else:+ rot_matrix = rotation_matrix(angle, axis)+ self.apply_points_function_about_point(+ lambda points: np.dot(points, rot_matrix.T), **kwargs+ )+ return selfdef flip(self, axis=UP, **kwargs):return self.rotate(TAU / 2, axis, **kwargs)@@ -712,6 +782,29 @@ class Mobject(Container):# In place operations.# Note, much of these are now redundant with default behavior of# above methods+ def apply_points_function(self, func, about_point=None, about_edge=ORIGIN, works_on_bounding_box=False):+ if about_point is None and about_edge is not None:+ about_point = self.get_bounding_box_point(about_edge)++ for mob in self.get_family():+ arrs = []+ if len(self.data["points"]):+ arrs.append(mob.data["points"])+ if works_on_bounding_box:+ arrs.append(mob.get_bounding_box())++ for arr in arrs:+ if about_point is None:+ arr[:] = func(arr)+ else:+ arr[:] = func(arr - about_point) + about_point++ if not works_on_bounding_box:+ self.refresh_bounding_box(recurse_down=True)+ else:+ for parent in self.parents:+ parent.refresh_bounding_box()+ return selfdef apply_points_function_about_point(self, func, about_point=None, about_edge=None@@ -1281,11 +1374,17 @@ class Mobject(Container):def get_start(self):self.throw_error_if_no_points()- return np.array(self.points[0])+ if config["use_opengl_renderer"]:+ return np.array(self.data['points'][0])+ else:+ return np.array(self.points[0])def get_end(self):self.throw_error_if_no_points()- return np.array(self.points[-1])+ if config["use_opengl_renderer"]:+ return np.array(self.data['points'][-1])+ else:+ return np.array(self.points[-1])def get_start_and_end(self):return self.get_start(), self.get_end()@@ -1390,10 +1489,16 @@ class Mobject(Container):result = [self] if len(self.points) > 0 else []return result + self.submobjects- def get_family(self):- sub_families = list(map(Mobject.get_family, self.submobjects))- all_mobjects = [self] + list(it.chain(*sub_families))- return remove_list_redundancies(all_mobjects)+ def get_family(self, recurse=True):+ if config["use_opengl_renderer"]:+ if recurse:+ return self.family+ else:+ return [self]+ else:+ sub_families = list(map(Mobject.get_family, self.submobjects))+ all_mobjects = [self] + list(it.chain(*sub_families))+ return remove_list_redundancies(all_mobjects)def family_members_with_points(self):return [m for m in self.get_family() if m.get_num_points() > 0]@@ -1616,11 +1721,18 @@ class Mobject(Container):# Errorsdef throw_error_if_no_points(self):- if self.has_no_points():- caller_name = sys._getframe(1).f_code.co_name- raise Exception(- f"Cannot call Mobject.{caller_name} for a Mobject with no points"- )+ if config["use_opengl_renderer"]:+ if len(self.data["points"]) == 0:+ caller_name = sys._getframe(1).f_code.co_name+ raise Exception(+ f"Cannot call Mobject.{caller_name} for a Mobject with no points"+ )+ else:+ if self.has_no_points():+ caller_name = sys._getframe(1).f_code.co_name+ raise Exception(+ f"Cannot call Mobject.{caller_name} for a Mobject with no points"+ )# About z-indexdef set_z_index(self, z_index_value):diff --git a/manim/mobject/opengl_geometry.py b/manim/mobject/opengl_geometry.pyindex 59756ffcf..103f89583 100644--- a/manim/mobject/opengl_geometry.py+++ b/manim/mobject/opengl_geometry.py@@ -9,6 +9,7 @@ from ..utils.space_ops import rotation_matrix_transposefrom ..utils.iterables import adjacent_n_tuplesfrom ..constants import *from ..mobject.geometry import TipableVMobject+from ..mobject.types.vectorized_mobject import VMobjectclass OpenGLArc(TipableVMobject):@@ -95,3 +96,59 @@ class OpenGLArc(TipableVMobject):def move_arc_center_to(self, point):self.shift(point - self.get_arc_center())return self+++class OpenGLArcBetweenPoints(OpenGLArc):+ def __init__(self, start, end, angle=TAU / 4, **kwargs):+ super().__init__(angle=angle, **kwargs)+ if angle == 0:+ self.set_points_as_corners([LEFT, RIGHT])+ self.put_start_and_end_on(start, end)+++class OpenGLPolygon(VMobject):+ def __init__(self, *vertices, **kwargs):+ self.vertices = vertices+ super().__init__(**kwargs)++ def init_points(self):+ verts = self.vertices+ self.set_points_as_corners([*verts, verts[0]])++ def get_vertices(self):+ return self.get_start_anchors()++ def round_corners(self, radius=0.5):+ vertices = self.get_vertices()+ arcs = []+ for v1, v2, v3 in adjacent_n_tuples(vertices, 3):+ vect1 = v2 - v1+ vect2 = v3 - v2+ unit_vect1 = normalize(vect1)+ unit_vect2 = normalize(vect2)+ angle = angle_between_vectors(vect1, vect2)+ # Negative radius gives concave curves+ angle *= np.sign(radius)+ # Distance between vertex and start of the arc+ cut_off_length = radius * np.tan(angle / 2)+ # Determines counterclockwise vs. clockwise+ sign = np.sign(np.cross(vect1, vect2)[2])+ arc = ArcBetweenPoints(+ v2 - unit_vect1 * cut_off_length,+ v2 + unit_vect2 * cut_off_length,+ angle=sign * angle,+ n_components=2,+ )+ arcs.append(arc)++ self.clear_points()+ # To ensure that we loop through starting with last+ arcs = [arcs[-1], *arcs[:-1]]+ for arc1, arc2 in adjacent_pairs(arcs):+ self.append_points(arc1.get_points())+ line = Line(arc1.get_end(), arc2.get_start())+ # Make sure anchors are evenly distributed+ len_ratio = line.get_length() / arc1.get_arc_length()+ line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))+ self.append_points(line.get_points())+ return selfdiff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex eebe7c8eb..d23805303 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -531,15 +531,27 @@ class VMobject(Mobject):VMobjectfor chaining."""- assert len(anchors1) == len(handles1) == len(handles2) == len(anchors2)- nppcc = self.n_points_per_cubic_curve # 4- total_len = nppcc * len(anchors1)- self.points = np.zeros((total_len, self.dim))- # the following will, from the four sets, dispatch them in points such that self.points = [anchors1[0], handles1[0], handles2[0], anchors1[0], anchors1[1], handles1[1], ...]- arrays = [anchors1, handles1, handles2, anchors2]- for index, array in enumerate(arrays):- self.points[index::nppcc] = array- return self+ if config["use_opengl_renderer"]:+ handles = handles1+ anchors2 = handles2+ assert(len(anchors1) == len(handles) == len(anchors2))+ nppc = 3+ new_points = np.zeros((nppc * len(anchors1), self.dim))+ arrays = [anchors1, handles, anchors2]+ for index, array in enumerate(arrays):+ new_points[index::nppc] = array+ self.set_points(new_points)+ return self+ else:+ assert len(anchors1) == len(handles1) == len(handles2) == len(anchors2)+ nppcc = self.n_points_per_cubic_curve # 4+ total_len = nppcc * len(anchors1)+ self.points = np.zeros((total_len, self.dim))+ # the following will, from the four sets, dispatch them in points such that self.points = [anchors1[0], handles1[0], handles2[0], anchors1[0], anchors1[1], handles1[1], ...]+ arrays = [anchors1, handles1, handles2, anchors2]+ for index, array in enumerate(arrays):+ self.points[index::nppcc] = array+ return selfdef clear_points(self):self.points = np.zeros((0, self.dim))@@ -677,14 +689,23 @@ class VMobject(Mobject):VMobjectself. For chaining purposes."""- nppcc = self.n_points_per_cubic_curve- points = np.array(points)- # This will set the handles aligned with the anchors.- # Id est, a bezier curve will be the segment from the two anchors such that the handles belongs to this segment.- self.set_anchors_and_handles(- *[interpolate(points[:-1], points[1:], a) for a in np.linspace(0, 1, nppcc)]- )- return self+ if config["use_opengl_renderer"]:+ nppc = self.n_points_per_curve+ points = np.array(points)+ self.set_anchors_and_handles(*[+ interpolate(points[:-1], points[1:], a)+ for a in np.linspace(0, 1, nppc)+ ])+ return self+ else:+ nppcc = self.n_points_per_cubic_curve+ points = np.array(points)+ # This will set the handles aligned with the anchors.+ # Id est, a bezier curve will be the segment from the two anchors such that the handles belongs to this segment.+ self.set_anchors_and_handles(+ *[interpolate(points[:-1], points[1:], a) for a in np.linspace(0, 1, nppcc)]+ )+ return selfdef set_points_smoothly(self, points):self.set_points_as_corners(points)diff --git a/manim/opengl/__init__.py b/manim/opengl/__init__.pyindex 4e79a2ee3..459d67173 100644--- a/manim/opengl/__init__.py+++ b/manim/opengl/__init__.py@@ -1,3 +1,4 @@from ..mobject.opengl_geometry import *Arc = OpenGLArc+ArcBetweenPoints = OpenGLArcBetweenPointsdiff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.pyindex 4d36b35c3..9a0cb13d3 100644--- a/manim/utils/space_ops.py+++ b/manim/utils/space_ops.py@@ -33,6 +33,7 @@ __all__ = [from functools import reduceimport numpy as np+import mathfrom ..constants import OUTfrom ..constants import PI