Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

added typings and docs for vectorized mobjects and bezier related functions (#961)

Hugues Devimeuxb36cdb1933fe
diff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.py
index a33b38bf0..b4507b1b5 100644
--- a/manim/mobject/geometry.py
+++ b/manim/mobject/geometry.py
@@ -919,6 +919,7 @@ class CubicBezier(VMobject):
class Polygon(VMobject):
def __init__(self, *vertices, color=BLUE, **kwargs):
VMobject.__init__(self, color=color, **kwargs)
+ # There are actually four corners, and the first one is repeated twice to form the four vertices.
self.set_points_as_corners([*vertices, vertices[0]])
def get_vertices(self):
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 5b6c64c04..f27f5a476 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -14,6 +14,8 @@ __all__ = [
import itertools as it
import sys
import colour
+from typing import Iterable
+
from ...constants import *
from ...mobject.mobject import Mobject
@@ -437,11 +439,27 @@ class VMobject(Mobject):
def get_points(self):
return np.array(self.points)
- def set_anchors_and_handles(self, anchors1, handles1, handles2, anchors2):
+ def set_anchors_and_handles(
+ self,
+ anchors1: Iterable[float],
+ handles1: Iterable[float],
+ handles2: Iterable[float],
+ anchors2: Iterable[float],
+ ) -> "VMobject":
+ """Given two sets of anchors and handles, process them to set them as anchors and handles of the VMobject.
+
+ anchors1[i], handles1[i], handles2[i] and anchors2[i] define the i-th bezier curve of the vmobject. There are four hardcoded paramaters and this is a problem as it makes the number of points per cubic curve unchangeable from 4. (two anchors and two handles).
+
+ Returns
+ -------
+ VMobject
+ for 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
@@ -462,13 +480,27 @@ class VMobject(Mobject):
self.append_points([point])
return self
- def add_cubic_bezier_curve(self, anchor1, handle1, handle2, anchor2):
+ def add_cubic_bezier_curve(
+ self, anchor1: np.ndarray, handle1: np.ndarray, handle2: np.ndarray, anchor2
+ ) -> None:
# TODO, check the len(self.points) % 4 == 0?
self.append_points([anchor1, handle1, handle2, anchor2])
- def add_cubic_bezier_curve_to(self, handle1, handle2, anchor):
- """
- Add cubic bezier curve to the path.
+ def add_cubic_bezier_curve_to(
+ self, handle1: np.ndarray, handle2: np.ndarray, anchor: np.ndarray
+ ) -> None:
+ """Add cubic bezier curve to the path.
+
+ NOTE : the first anchor is not a paramater as by default the end of the last sub-path!
+
+ Parameters
+ ----------
+ handle1 : np.ndarray
+ first handle
+ handle2 : np.ndarray
+ second handle
+ anchor : np.ndarray
+ anchor
"""
self.throw_error_if_no_points()
new_points = [handle1, handle2, anchor]
@@ -477,7 +509,14 @@ class VMobject(Mobject):
else:
self.append_points([self.get_last_point()] + new_points)
- def add_line_to(self, point):
+ def add_line_to(self, point: np.ndarray) -> "VMobject":
+ """Add a straight line from the last point of VMobject to the given point.
+
+ Parameters :
+ ------------
+ point : np.ndarray
+ end of the straight line.
+ """
nppcc = self.n_points_per_cubic_curve
self.add_cubic_bezier_curve_to(
*[
@@ -487,11 +526,25 @@ class VMobject(Mobject):
)
return self
- def add_smooth_curve_to(self, *points):
- """
- If two points are passed in, the first is interpreted
- as a handle, the second as an anchor
+ def add_smooth_curve_to(self, *points: np.array) -> "VMobject":
+ """Creates a smooth curve from given points and add it to the VMobject. If two points are passed in, the first is interpreted
+ as a handle, the second as an anchor.
+
+ Parameters
+ ----------
+ points: np.array
+ Points (anchor and handle, or just anchor) to add a smooth curve from
+ Returns
+ -------
+ VMobject
+
+
+ Raises
+ ------
+ ValueError
+ If 0 or more than 2 points are given.
"""
+ # TODO remove the value error and just add two parameters with one optional
if len(points) == 1:
handle2 = None
new_anchor = points[0]
@@ -517,22 +570,41 @@ class VMobject(Mobject):
def has_new_path_started(self):
nppcc = self.n_points_per_cubic_curve # 4
+ # A new path starting is defined by a control point which is not part of a bezier subcurve.
return len(self.points) % nppcc == 1
def get_last_point(self):
return self.points[-1]
def is_closed(self):
+ # TODO use consider_points_equals_2d ?
return self.consider_points_equals(self.points[0], self.points[-1])
- def add_points_as_corners(self, points):
+ def add_points_as_corners(self, points: np.ndarray) -> "VMobject":
for point in points:
self.add_line_to(point)
return points
- def set_points_as_corners(self, points):
+ def set_points_as_corners(self, points: Iterable[float]) -> "VMobject":
+ """Given an array of points, set them as corner of the vmobject.
+
+ To achieve that, this algorithm sets handles aligned with the anchors such that the resultant bezier curve will be the segment
+ between the two anchors.
+
+ Parameters
+ ----------
+ points : Iterable[float]
+ Array of points that will be set as corners.
+
+ Returns
+ -------
+ VMobject
+ self. 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)]
)
@@ -543,17 +615,30 @@ class VMobject(Mobject):
self.make_smooth()
return self
- def change_anchor_mode(self, mode):
+ def change_anchor_mode(self, mode: str) -> "VMobject":
+ """Changes the anchor mode of the bezier curves. This will modify the handles.
+
+ There can be only two modes, "jagged", and "smooth".
+
+ Returns
+ -------
+ VMobject
+ For chaining purposes.
+ """
assert mode in ["jagged", "smooth"]
nppcc = self.n_points_per_cubic_curve
for submob in self.family_members_with_points():
subpaths = submob.get_subpaths()
submob.clear_points()
+ # A subpath can be composed of several bezier curves.
for subpath in subpaths:
+ # This will retrieve the anchors of the subpath, by selecting every n element in the array subpath
+ # The append is needed as the last element is not reached when slicing with numpy.
anchors = np.append(subpath[::nppcc], subpath[-1:], 0)
if mode == "smooth":
h1, h2 = get_smooth_handle_points(anchors)
elif mode == "jagged":
+ # The following will make the handles aligned with the anchors, thus making the bezier curve a segment
a1 = anchors[:-1]
a2 = anchors[1:]
h1 = interpolate(a1, a2, 1.0 / 3)
@@ -570,7 +655,7 @@ class VMobject(Mobject):
def make_jagged(self):
return self.change_anchor_mode("jagged")
- def add_subpath(self, points):
+ def add_subpath(self, points: np.ndarray) -> "VMobject":
assert len(points) % 4 == 0
self.points = np.append(self.points, points, axis=0)
return self
@@ -593,18 +678,28 @@ class VMobject(Mobject):
self.make_smooth()
return self
- def scale_handle_to_anchor_distances(self, factor):
- """
- If the distance between a given handle point H and its associated
+ def scale_handle_to_anchor_distances(self, factor: float) -> "VMobject":
+ """If the distance between a given handle point H and its associated
anchor point A is d, then it changes H to be a distances factor*d
away from A, but so that the line from A to H doesn't change.
This is mostly useful in the context of applying a (differentiable)
function, to preserve tangency properties. One would pull all the
handles closer to their anchors, apply the function then push them out
again.
+
+ Paramters
+ ---------
+ factor : float
+ factor used for scaling.
+
+ Returns
+ -------
+ VMobject
+ For chaining.
"""
for submob in self.family_members_with_points():
if len(submob.points) < self.n_points_per_cubic_curve:
+ # The case that a bezier quad is not complete (there is no bezier curve as there is not enough control points.)
continue
a1, h1, h2, a2 = submob.get_anchors_and_handles()
a1_to_h1 = h1 - a1
@@ -618,12 +713,22 @@ class VMobject(Mobject):
def consider_points_equals(self, p0, p1):
return np.allclose(p0, p1, atol=self.tolerance_for_point_equality)
- def consider_points_equals_2d(self, p0, p1):
- """
- Determine if two points are close enough to be considered equal.
+ def consider_points_equals_2d(self, p0: np.ndarray, p1: np.ndarray) -> bool:
+ """Determine if two points are close enough to be considered equal.
This uses the algorithm from np.isclose(), but expanded here for the
2D point case. NumPy is overkill for such a small question.
+ Parameters
+ ----------
+ p0 : np.ndarray
+ first point
+ p1 : np.ndarray
+ second point
+
+ Returns
+ -------
+ bool
+ whether two points considered close.
"""
rtol = 1.0e-5 # default from np.isclose()
atol = self.tolerance_for_point_equality
@@ -637,21 +742,56 @@ class VMobject(Mobject):
def get_cubic_bezier_tuples_from_points(self, points):
return np.array(list(self.gen_cubic_bezier_tuples_from_points(points)))
- def gen_cubic_bezier_tuples_from_points(self, points):
- """
- Get a generator for the cubic bezier tuples of this object.
+ def gen_cubic_bezier_tuples_from_points(self, points: np.ndarray) -> typing.Tuple:
+ """Returns the bezier tuples from an array of points.
+
+ self.points is a list of the anchors and handles of the bezier curves of the mobject (ie [anchor1, handle1, handle2, anchor2, anchor3 ..])
+ This algorithm basically retrieve them by taking an element every n, where n is the number of control points
+ of the bezier curve.
- Generator to not materialize a list or np.array needlessly.
+
+ Parameters
+ ----------
+ points : np.ndarray
+ Points from which control points will be extracted.
+
+ Returns
+ -------
+ typing.Tuple
+ Bezier control points.
"""
nppcc = self.n_points_per_cubic_curve
remainder = len(points) % nppcc
points = points[: len(points) - remainder]
+ # Basically take every nppcc element.
return (points[i : i + nppcc] for i in range(0, len(points), nppcc))
def get_cubic_bezier_tuples(self):
return self.get_cubic_bezier_tuples_from_points(self.get_points())
- def _gen_subpaths_from_points(self, points, filter_func):
+ def _gen_subpaths_from_points(
+ self, points: np.ndarray, filter_func: typing.Callable[[int], bool]
+ ) -> typing.Tuple:
+ """Given an array of points defining the bezier curves of the vmobject, return subpaths formed by these points.
+ Here, Two bezier curves form a path if at least two of their anchors are evaluated True by the relation defined by filter_func.
+
+ The algorithm every bezier tuple (anchors and handles) in ``self.points`` (by regrouping each n elements, where
+ n is the number of points per cubic curve)), and evaluate the relation between two anchors with filter_func.
+ NOTE : The filter_func takes an int n as paramater, and will evaluate the relation between points[n] and points[n - 1]. This should probably be changed so
+ the function takes two points as paramters.
+
+ Parameters
+ ----------
+ points : np.ndarray
+ points defining the bezier curve.
+ filter_func : typing.Callable[int, bool]
+ Filter-func defining the relation.
+
+ Returns
+ -------
+ typing.Tuple
+ subpaths formed by the points.
+ """
nppcc = self.n_points_per_cubic_curve
split_indices = filter(filter_func, range(nppcc, len(points), nppcc))
split_indices = [0] + list(split_indices) + [len(points)]
@@ -675,45 +815,123 @@ class VMobject(Mobject):
lambda n: not self.consider_points_equals_2d(points[n - 1], points[n]),
)
- def get_subpaths(self):
+ def get_subpaths(self) -> typing.Tuple:
+ """Returns subpaths formed by the curves of the VMobject.
+
+ We define a subpath between two curve if one of their extreminities are coincidents.
+
+ Returns
+ -------
+ typing.Tuple
+ subpaths.
+ """
return self.get_subpaths_from_points(self.get_points())
- def get_nth_curve_points(self, n):
+ def get_nth_curve_points(self, n: int) -> np.ndarray:
+ """Returns the points defining the nth curve of the vmobject.
+
+ Parameters
+ ----------
+ n : int
+ index of the desired bezier curve.
+
+ Returns
+ -------
+ np.ndarray
+ points defininf the nth bezier curve (anchors, handles)
+ """
assert n < self.get_num_curves()
nppcc = self.n_points_per_cubic_curve
return self.points[nppcc * n : nppcc * (n + 1)]
- def get_nth_curve_function(self, n):
+ def get_nth_curve_function(self, n: int) -> typing.Callable[[float], np.ndarray]:
+ """Returns the expression of the nth curve.
+
+ Parameters
+ ----------
+ n : int
+ index of the desired curve.
+
+ Returns
+ -------
+ typing.Callable[float]
+ expression of the nth bezier curve.
+ """
return bezier(self.get_nth_curve_points(n))
- def get_num_curves(self):
+ def get_num_curves(self) -> int:
+ """Returns the number of curves of the vmobject.
+
+ Returns
+ -------
+ int
+ number of curves. of the vmobject.
+ """
nppcc = self.n_points_per_cubic_curve
return len(self.points) // nppcc
- def point_from_proportion(self, alpha):
+ def point_from_proportion(self, alpha: float) -> np.ndarray:
+ """Get the bezier curve evaluated at a position P,
+ where P is the point corresponding to the proportion defined by the given alpha.
+
+ Parameters
+ ----------
+ alpha : float
+ Proportion.
+
+ Returns
+ -------
+ np.ndarray
+ Point evaluated.
+ """
num_cubics = self.get_num_curves()
n, residue = integer_interpolate(0, num_cubics, alpha)
curve = self.get_nth_curve_function(n)
return curve(residue)
- def get_anchors_and_handles(self):
- """
- returns anchors1, handles1, handles2, anchors2,
+ def get_anchors_and_handles(self) -> typing.Iterable[np.ndarray]:
+ """Returns anchors1, handles1, handles2, anchors2,
where (anchors1[i], handles1[i], handles2[i], anchors2[i])
will be four points defining a cubic bezier curve
for any i in range(0, len(anchors1))
+
+ Returns
+ -------
+ typing.Iterable[np.ndarray]
+ Iterable of the anchors and handles.
"""
nppcc = self.n_points_per_cubic_curve
return [self.points[i::nppcc] for i in range(nppcc)]
- def get_start_anchors(self):
+ def get_start_anchors(self) -> np.ndarray:
+ """Returns the start anchors of the bezier curves.
+
+ Returns
+ -------
+ np.ndarray
+ Starting anchors
+ """
return self.points[0 :: self.n_points_per_cubic_curve]
- def get_end_anchors(self):
+ def get_end_anchors(self) -> np.ndarray:
+ """Return the starting anchors of the bezier curves.
+
+ Returns
+ -------
+ np.ndarray
+ Starting anchors
+ """
nppcc = self.n_points_per_cubic_curve
return self.points[nppcc - 1 :: nppcc]
- def get_anchors(self):
+ def get_anchors(self) -> np.ndarray:
+ """Returns the anchors of the curves forming the VMobject.
+
+ Returns
+ -------
+ np.ndarray
+ The anchors.
+ """
if self.points.shape[0] == 1:
return self.points
return np.array(
@@ -728,6 +946,7 @@ class VMobject(Mobject):
)
def get_points_defining_boundary(self):
+ # Probably returns all anchors, but this is weird regarding the name of the method.
return np.array(list(it.chain(*[sm.get_anchors() for sm in self.get_family()])))
def get_arc_length(self, n_sample_points=None):
@@ -742,6 +961,8 @@ class VMobject(Mobject):
# Alignment
def align_points(self, vmobject):
+ # This probably makes the current vmobject and the given one have the same number of points,
+ # by adding extra points to the last sub-path. This method is never used in the whole library.
self.align_rgbas(vmobject)
if self.get_num_points() == vmobject.get_num_points():
return
@@ -785,7 +1006,19 @@ class VMobject(Mobject):
vmobject.set_points(new_path2)
return self
- def insert_n_curves(self, n):
+ def insert_n_curves(self, n: int) -> "VMobject":
+ """Inserts n curves to the bezier curves of the vmobject.
+
+ Paramters
+ ---------
+ n : int
+ Number of curves to insert
+
+ Returns
+ -------
+ VMobject
+ for chaining.
+ """
new_path_point = None
if self.has_new_path_started():
new_path_point = self.get_last_point()
@@ -797,6 +1030,22 @@ class VMobject(Mobject):
self.append_points([new_path_point])
return self
+ def insert_n_curves_to_point_list(self, n: int, points: np.ndarray) -> np.ndarray:
+ """Given an array of k points defining a bezier curves (anchors and handles), returns points defining exactly k + n bezier curves.
+
+ Parameters
+ ----------
+ n : int
+ Number of desired curves.
+ points : np.ndarray
+ Starting points.
+
+ Returns
+ -------
+ np.ndarray
+ Points generated.
+ """
+
def insert_n_curves_to_point_list(self, n, points):
if len(points) == 1:
nppcc = self.n_points_per_cubic_curve
@@ -867,7 +1116,21 @@ class VMobject(Mobject):
if alpha == 1.0:
setattr(self, attr, getattr(mobject2, attr))
- def pointwise_become_partial(self, vmobject, a, b):
+ def pointwise_become_partial(
+ self, vmobject: "VMobject", a: float, b: float
+ ) -> "VMobject":
+ """Given two bounds a and b, transforms the points of the self vmobject into the points of the vmobject
+ passed as parameter with respect to the bounds. Points here stand for control points of the bezier curves (anchors and handles)
+
+ Parameters
+ ----------
+ vmobject : VMobject
+ The vmobject that will serve as a model.
+ a : float
+ upper-bound.
+ b : float
+ lower-bound
+ """
assert isinstance(vmobject, VMobject)
# Partial curve includes three portions:
# - A middle section, which matches the curve exactly
@@ -879,6 +1142,9 @@ class VMobject(Mobject):
bezier_quads = vmobject.get_cubic_bezier_tuples()
num_cubics = len(bezier_quads)
+ # The following two lines will compute which bezier curves of the given mobject need to be processed.
+ # The residue basically indicates de proportion of the selected bezier curve that have to be selected.
+ # Ex : if lower_index is 3, and lower_residue is 0.4, then the algorithm will append to the points 0.4 of the third bezier curve
lower_index, lower_residue = integer_interpolate(0, num_cubics, a)
upper_index, upper_residue = integer_interpolate(0, num_cubics, b)
@@ -902,7 +1168,22 @@ class VMobject(Mobject):
)
return self
- def get_subcurve(self, a, b):
+ def get_subcurve(self, a: float, b: float) -> "VMobject":
+ """Returns the subcurve of the VMobject between the interval [a, b].
+ The curve is a VMobject itself.
+
+ Parameters :
+ ------------
+ a : float
+ lower-bound
+ b : float
+ upper-boud
+
+ Returns
+ -------
+ VMobject
+ The subcurve between of [a, b]
+ """
vmob = self.copy()
vmob.pointwise_become_partial(self, a, b)
return vmob
diff --git a/manim/utils/bezier.py b/manim/utils/bezier.py
index ad10f149d..9c3104a3d 100644
--- a/manim/utils/bezier.py
+++ b/manim/utils/bezier.py
@@ -27,6 +27,18 @@ CLOSED_THRESHOLD: float = 0.001
def bezier(
points: np.ndarray,
) -> typing.Callable[[float], typing.Union[int, typing.Iterable]]:
+ """Classic implementation of a bezier curve.
+
+ Parameters
+ ----------
+ points : np.ndarray
+ points defining the desired bezier curve.
+
+ Returns
+ -------
+ typing.Callable[[float], typing.Union[int, typing.Iterable]]
+ function describing the bezier curve.
+ """
n = len(points) - 1
return lambda t: sum(
[
@@ -37,14 +49,24 @@ def bezier(
def partial_bezier_points(points: np.ndarray, a: float, b: float) -> np.ndarray:
- """
- Given an array of points which define
- a bezier curve, and two numbers 0<=a<b<=1,
- return an array of the same size, which
- describes the portion of the original bezier
- curve on the interval [a, b].
+ """Given an array of points which define bezier curve, and two numbers 0<=a<b<=1, return an array of the same size,
+ which describes the portion of the original bezier curve on the interval [a, b].
This algorithm is pretty nifty, and pretty dense.
+
+ Parameters
+ ----------
+ points : np.ndarray
+ set of points defining the bezier curve.
+ a : float
+ lower bound of the desired partial bezier curve.
+ b : float
+ upper bound of the desired partial bezier curve.
+
+ Returns
+ -------
+ np.ndarray
+ Set of points defining the partial bezier curve.
"""
if a == 1:
return [points[-1]] * len(points)
@@ -104,6 +126,19 @@ def match_interpolate(
def get_smooth_handle_points(
points: np.ndarray,
) -> typing.Tuple[np.ndarray, np.ndarray]:
+ """Given some anchors (points), compute handles so the resulting bezier curve is smooth.
+
+ Parameters
+ ----------
+ points : np.ndarray
+ Anchors.
+
+ Returns
+ -------
+ typing.Tuple[np.ndarray, np.ndarray]
+ Computed handles.
+ """
+ # NOTE points here are anchors.
points = np.array(points)
num_handles = len(points) - 1
dim = points.shape[1]