Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Added proportion_from_point method to VMobject, which uses some new bezier curve utilities (#1469)

Aathish Sivasubrahmanianc11b649e9aed
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 3ba4faba2..b41195ed1 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -1917,6 +1917,9 @@ class Mobject:
def point_from_proportion(self, alpha):
raise NotImplementedError("Please override in a child class.")
+ def proportion_from_point(self, point):
+ raise NotImplementedError("Please override in a child class.")
+
def get_pieces(self, n_pieces):
template = self.copy()
template.submobjects = []
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index aab8f6910..26d7a4f37 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -30,6 +30,8 @@ from ...utils.bezier import (
integer_interpolate,
interpolate,
partial_bezier_points,
+ point_lies_on_bezier,
+ proportions_along_bezier_curve_for_point,
)
from ...utils.color import BLACK, WHITE, color_to_rgba
from ...utils.deprecation import deprecated, deprecated_params
@@ -1030,6 +1032,28 @@ class VMobject(Mobject):
"""
return bezier(self.get_nth_curve_points(n))
+ def get_nth_curve_length(
+ self, n: int, sample_points: Optional[int] = None
+ ) -> float:
+ """Returns the (approximate) length of the nth curve.
+
+ Parameters
+ ----------
+ n
+ The index of the desired curve.
+ sample_points
+ The number of points to sample to find the length.
+
+ Returns
+ -------
+ length : :class:`float`
+ The length of the nth curve.
+ """
+
+ _, length = self.get_nth_curve_function_with_length(n, sample_points)
+
+ return length
+
def get_nth_curve_function_with_length(
self, n: int, sample_points: Optional[int] = None
) -> typing.Tuple[typing.Callable[[float], np.ndarray], float]:
@@ -1155,6 +1179,61 @@ class VMobject(Mobject):
current_length += length
+ def proportion_from_point(
+ self,
+ point: typing.Iterable[typing.Union[float, int]],
+ ) -> float:
+ """Returns the proportion along the path of the :class:`VMobject`
+ a particular given point is at.
+
+ Parameters
+ ----------
+ point
+ The Cartesian coordinates of the point which may or may not lie on the :class:`VMobject`
+
+ Returns
+ -------
+ float
+ The proportion along the path of the :class:`VMobject`.
+
+ Raises
+ ------
+ :exc:`ValueError`
+ If ``point`` does not lie on the curve.
+ :exc:`Exception`
+ If the :class:`VMobject` has no points.
+ """
+ self.throw_error_if_no_points()
+
+ # Iterate over each bezier curve that the ``VMobject`` is composed of, checking
+ # if the point lies on that curve. If it does not lie on that curve, add
+ # the whole length of the curve to ``target_length`` and move onto the next
+ # curve. If the point does lie on the curve, add how far along the curve
+ # the point is to ``target_length``.
+ # Then, divide ``target_length`` by the total arc length of the shape to get
+ # the proportion along the ``VMobject`` the point is at.
+
+ num_curves = self.get_num_curves()
+ total_length = self.get_arc_length()
+ target_length = 0
+ for n in range(num_curves):
+ control_points = self.get_nth_curve_points(n)
+ length = self.get_nth_curve_length(n)
+ proportions_along_bezier = proportions_along_bezier_curve_for_point(
+ point, control_points
+ )
+ if len(proportions_along_bezier) > 0:
+ proportion_along_nth_curve = max(proportions_along_bezier)
+ target_length += length * proportion_along_nth_curve
+ break
+ target_length += length
+ else:
+ raise ValueError(f"Point {point} does not lie on this curve.")
+
+ alpha = target_length / total_length
+
+ return alpha
+
def get_anchors_and_handles(self) -> typing.Iterable[np.ndarray]:
"""Returns anchors1, handles1, handles2, anchors2,
where (anchors1[i], handles1[i], handles2[i], anchors2[i])
diff --git a/manim/utils/bezier.py b/manim/utils/bezier.py
index 8c5f32633..27b28170e 100644
--- a/manim/utils/bezier.py
+++ b/manim/utils/bezier.py
@@ -13,10 +13,13 @@ __all__ = [
"get_smooth_cubic_bezier_handle_points",
"diag_to_matrix",
"is_closed",
+ "proportions_along_bezier_curve_for_point",
+ "point_lies_on_bezier",
]
import typing
+from functools import reduce
import numpy as np
from scipy import linalg
@@ -24,8 +27,6 @@ from scipy import linalg
from ..utils.simple_functions import choose
from ..utils.space_ops import cross2d, find_intersection
-CLOSED_THRESHOLD: float = 0.001
-
def bezier(
points: np.ndarray,
@@ -367,3 +368,120 @@ def get_quadratic_approximation_of_cubic(a0, h0, h1, a1):
def is_closed(points: typing.Tuple[np.ndarray, np.ndarray]) -> bool:
return np.allclose(points[0], points[-1])
+
+
+def proportions_along_bezier_curve_for_point(
+ point: typing.Iterable[typing.Union[float, int]],
+ control_points: typing.Iterable[typing.Iterable[typing.Union[float, int]]],
+ round_to: typing.Optional[typing.Union[float, int]] = 1e-6,
+) -> np.ndarray:
+ """Obtains the proportion along the bezier curve corresponding to a given point
+ given the bezier curve's control points.
+
+ The bezier polynomial is constructed using the coordinates of the given point
+ as well as the bezier curve's control points. On solving the polynomial for each dimension,
+ if there are roots common to every dimension, those roots give the proportion along the
+ curve the point is at. If there are no real roots, the point does not lie on the curve.
+
+ Parameters
+ ----------
+ point
+ The Cartesian Coordinates of the point whose parameter
+ should be obtained.
+ control_points
+ The Cartesian Coordinates of the ordered control
+ points of the bezier curve on which the point may
+ or may not lie.
+ round_to
+ A float whose number of decimal places all values
+ such as coordinates of points will be rounded.
+
+ Returns
+ -------
+ np.ndarray[float]
+ List containing possible parameters (the proportions along the bezier curve)
+ for the given point on the given bezier curve.
+ This usually only contains one or zero elements, but if the
+ point is, say, at the beginning/end of a closed loop, may return
+ a list with more than 1 value, corresponding to the beginning and
+ end etc. of the loop.
+
+ Raises
+ ------
+ :class:`ValueError`
+ When ``point`` and the control points have different shapes.
+ """
+ # Method taken from
+ # http://polymathprogrammer.com/2012/04/03/does-point-lie-on-bezier-curve/
+
+ if not all(np.shape(point) == np.shape(c_p) for c_p in control_points):
+ raise ValueError(
+ f"Point {point} and Control Points {control_points} have different shapes."
+ )
+
+ control_points = np.array(control_points)
+ n = len(control_points) - 1
+
+ roots = []
+ for dim, coord in enumerate(point):
+ control_coords = control_points[:, dim]
+ terms = []
+ for term_power in range(n, -1, -1):
+ outercoeff = choose(n, term_power)
+ term = []
+ sign = 1
+ for subterm_num in range(term_power, -1, -1):
+ innercoeff = choose(term_power, subterm_num) * sign
+ subterm = innercoeff * control_coords[subterm_num]
+ if term_power == 0:
+ subterm -= coord
+ term.append(subterm)
+ sign *= -1
+ terms.append(outercoeff * sum(np.array(term)))
+ if all(term == 0 for term in terms):
+ # Then both Bezier curve and Point lie on the same plane.
+ # Roots will be none, but in this specific instance, we don't need to consider that.
+ continue
+ bezier_polynom = np.polynomial.Polynomial(terms[::-1])
+ polynom_roots = bezier_polynom.roots()
+ if len(polynom_roots) > 0:
+ polynom_roots = np.around(polynom_roots, int(np.log10(1 / round_to)))
+ roots.append(polynom_roots)
+
+ roots = [[root for root in rootlist if root.imag == 0] for rootlist in roots]
+ roots = reduce(np.intersect1d, roots) # Get common roots.
+ roots = np.array([r.real for r in roots])
+ return roots
+
+
+def point_lies_on_bezier(
+ point: typing.Iterable[typing.Union[float, int]],
+ control_points: typing.Iterable[typing.Iterable[typing.Union[float, int]]],
+ round_to: typing.Optional[typing.Union[float, int]] = 1e-6,
+) -> bool:
+ """Checks if a given point lies on the bezier curves with the given control points.
+
+ This is done by solving the bezier polynomial with the point as the constant term; if
+ any real roots exist, the point lies on the bezier curve.
+
+ Parameters
+ ----------
+ point
+ The Cartesian Coordinates of the point to check.
+ control_points
+ The Cartesian Coordinates of the ordered control
+ points of the bezier curve on which the point may
+ or may not lie.
+ round_to
+ A float whose number of decimal places all values
+ such as coordinates of points will be rounded.
+
+ Returns
+ -------
+ bool
+ Whether the point lies on the curve.
+ """
+
+ roots = proportions_along_bezier_curve_for_point(point, control_points, round_to)
+
+ return len(roots) > 0