Coverage for src/manimgx/animation/transform.py: 95%
353 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1"""Transforms: keyframe evaluation, recorded method calls, and concurrent leaf composition.
3A Transform moves geometry and paint between states; Animate derives those states
4from recorded calls. The play's compositor combines transforms sharing a leaf."""
6from __future__ import annotations
8import functools
9import inspect
10from collections.abc import Callable, Sequence
11from typing import TYPE_CHECKING, Literal, Never, Protocol, Self, Unpack, overload
12from warnings import deprecated
14import numpy as np
16from manimgx.animation import clock
17from manimgx.animation.timeline import (
18 Animation,
19 AnimationOptions,
20 Key,
21 _AnimationOptions,
22 _updating,
23 keyframe_at,
24)
25from manimgx.constants import ORIGIN, OUT, PI
26from manimgx.drawing.geometry import (
27 Blend,
28 Floats,
29 Path,
30 Step,
31 carried,
32 path_along_arc,
33 path_along_circles,
34)
35from manimgx.mobject import Group, Mobject, VMobject, _animate_plays
36from manimgx.typing import (
37 PathFunc,
38 Point3DLike,
39 Point3DLike_Array,
40 Vector3DLike,
41)
43if TYPE_CHECKING:
44 from fractions import Fraction
46 from manimgx.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER, RIGHT
47 from manimgx.mobject import Beside
48 from manimgx.mobjects.numbers import DecimalNumber
49 from manimgx.scene import Scene
51if TYPE_CHECKING:
52 from manimgx.animation.updaters import AnimatedBoundary
53 from manimgx.mobject import (
54 ComplexValueTracker,
55 Mobject1D,
56 PMobject,
57 ValueTracker,
58 VDict,
59 VectorizedPoint,
60 )
61 from manimgx.mobjects.annotations import Brace, BraceLabel
62 from manimgx.mobjects.graph import GenericGraph
63 from manimgx.mobjects.grid import Matrix, Table
64 from manimgx.mobjects.images import ImageMobject, ImageMobjectFromCamera
65 from manimgx.mobjects.plotting import (
66 Axes,
67 BarChart,
68 ComplexPlane,
69 NumberLine,
70 PolarPlane,
71 SampleSpace,
72 _Plane,
73 )
74 from manimgx.mobjects.shapes import (
75 Arc,
76 Arrow,
77 Circle,
78 Line,
79 Polygram,
80 TipableVMobject,
81 )
82 from manimgx.mobjects.text import BulletedList, MathTex, Typst
83 from manimgx.mobjects.three_d import (
84 Cylinder,
85 Line3D,
86 Polyhedron,
87 Surface,
88 _DirectedSurface,
89 )
90 from manimgx.mobjects.vector_field import StreamLines, VectorField
92 class _Of[T](Protocol):
93 """A proxy of a T (covariant: `_Of[Circle]` is an `_Of[VMobject]`)."""
95 @property
96 def mobject(self) -> T: ...
98 class _Method[
99 S1: Mobject,
100 **P1,
101 S2: Mobject = Never,
102 **P2 = ...,
103 S3: Mobject = Never,
104 **P3 = ...,
105 S4: Mobject = Never,
106 **P4 = ...,
107 ]:
108 """A mobject method as a proxy records it: for mobjects of kind S (the method's own
109 class), the method's parameters P, returning the proxy — per kind, first match.
110 """
112 @overload
113 def __get__(self, proxy: None, owner: type) -> Self: ...
114 @overload
115 def __get__[R](self, proxy: R, owner: type[_Of[S1]]) -> Callable[P1, R]: ...
116 @overload
117 def __get__[R](self, proxy: R, owner: type[_Of[S2]]) -> Callable[P2, R]: ...
118 @overload
119 def __get__[R](self, proxy: R, owner: type[_Of[S3]]) -> Callable[P3, R]: ...
120 @overload
121 def __get__[R](self, proxy: R, owner: type[_Of[S4]]) -> Callable[P4, R]: ...
122 def __get__(self, proxy: object, owner: type) -> object:
123 raise NotImplementedError # typing only
125 def _on[K](kind: type[K], /) -> K:
126 """A K, for its bound methods: their parameters without `self`, returning K."""
127 raise NotImplementedError # typing only
129 @overload
130 def recorded[A: Mobject, **PA](m1: Callable[PA, A], /) -> _Method[A, PA]: ...
132 @overload
133 def recorded[A: Mobject, **PA, B: Mobject, **PB](
134 m1: Callable[PA, A], m2: Callable[PB, B], /
135 ) -> _Method[A, PA, B, PB]: ...
137 @overload
138 def recorded[A: Mobject, **PA, B: Mobject, **PB, C: Mobject, **PC](
139 m1: Callable[PA, A], m2: Callable[PB, B], m3: Callable[PC, C], /
140 ) -> _Method[A, PA, B, PB, C, PC]: ...
142 @overload
143 def recorded[
144 A: Mobject,
145 **PA,
146 B: Mobject,
147 **PB,
148 C: Mobject,
149 **PC,
150 D: Mobject,
151 **PD,
152 ](
153 m1: Callable[PA, A],
154 m2: Callable[PB, B],
155 m3: Callable[PC, C],
156 m4: Callable[PD, D],
157 /,
158 ) -> _Method[A, PA, B, PB, C, PC, D, PD]: ...
160 def recorded(*methods: object) -> object:
161 """A method a proxy records, from each kind's bound method (its kind is what it returns)."""
162 raise NotImplementedError # typing only
165__all__ = ["Animate", "Transform"]
168class TransformOptions(_AnimationOptions, total=False, closed=True):
169 """The options a transform takes, by keyword: the animation options and its path."""
171 path_func: PathFunc | None
172 """How each point travels from its start to its end: a function of the start points,
173 the end points and the progress (see [paths][manimgx.Path]); it replaces
174 `path_arc` and `path_arc_centers` (default None: a straight path)."""
175 path_arc: float
176 """The angle each point turns through on its way, in radians: 0 is a straight path,
177 and a positive angle turns counterclockwise about `path_arc_axis` (default 0)."""
178 path_arc_axis: Vector3DLike
179 """The axis the arcs of `path_arc` turn about (default [`OUT`][manimgx.OUT]: in the
180 plane of the screen)."""
181 path_arc_centers: Point3DLike | Point3DLike_Array | None
182 """A point the mobject turns about by `path_arc` on its way, or one for each of its
183 points (default None: each point turns about the center of its own arc)."""
184 replace_mobject_with_target_in_scene: bool
185 """Whether the target takes the mobject's place in the scene when the animation
186 finishes, as with [`ReplacementTransform`][manimgx.ReplacementTransform]
187 (default False)."""
190class Transform[M: Mobject = Mobject](Animation[M]):
191 """Transform a mobject into the shape and style of another.
193 The mobject stays in the scene and ends as `target_mobject` is, which is not added
194 (with [`ReplacementTransform`][manimgx.ReplacementTransform], the target takes the
195 mobject's place): it [becomes][manimgx.Mobject.become] the target. On the way, their
196 parts are matched up one to one (the side with fewer parts gains some, and so do the
197 points of each pair), and each point travels from its start to its end in a straight
198 line, or along an arc with `path_arc`; what the matching gained goes when it ends.
200 Transforms that begin together on one mobject compose: `square.animate.shift(RIGHT)`
201 and `Rotate(square)` played together move the square and turn it, and it ends as
202 their last frame shows it. One that begins later takes the mobject over from where
203 the others have brought it. A target that has updaters and is not in the scene moves
204 while the animation plays (the animation runs its updaters), and the mobject follows
205 it.
207 Args:
208 mobject: The mobject to transform.
209 target_mobject: The mobject it turns into; None creates an empty target when
210 `keys` is omitted. Passing only `keys` leaves `target_mobject` as None.
211 path_func: How each point travels from its start to its end: a function of the
212 start points, the end points and the progress (see
213 [paths][manimgx.Path]); it replaces `path_arc` and `path_arc_centers`.
214 None: a straight path.
215 path_arc: The angle each point turns through on its way, in radians: 0 is a
216 straight path, and a positive angle turns counterclockwise.
217 path_arc_axis: The axis the arcs of `path_arc` turn about.
218 path_arc_centers: A point the mobject turns about by `path_arc` on its way, or
219 one for each of its points; None: each point turns about the center of its
220 own arc.
221 replace_mobject_with_target_in_scene: Whether an independent target takes
222 the mobject's place when the animation finishes. Presets without
223 such a target retain their usual removal or restoration behavior.
224 keys: Two or more states to pass through, in order: None for the mobject as the
225 animation starts, a function of it, or a mobject, copied when the animation
226 starts. Without them, the states are the mobject and `target_mobject`.
228 Examples:
229 ```python
230 import manimgx as m
233 class TransformExample(m.Scene):
234 def construct(self) -> None:
235 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
236 circle = m.Circle(radius=1.5, color=m.YELLOW, fill_opacity=0.5)
237 square.shift(3 * m.LEFT)
238 circle.shift(3 * m.RIGHT)
239 self.add(square)
240 self.play(m.Transform(square, circle, path_arc=m.PI / 2, run_time=2))
241 ```
242 """
244 # each leaf moves between its keyframes along `path_func`: from the object to a target
245 # of its own, or between states a preset derives (`keys`)
246 _moving: Mobject | Literal[False] | None = None # `moving_target`, once decided
248 def __init__(
249 self,
250 mobject: M,
251 target_mobject: Mobject | None = None,
252 path_func: PathFunc | None = None,
253 path_arc: float = 0,
254 path_arc_axis: Vector3DLike = OUT,
255 path_arc_centers: Point3DLike | Point3DLike_Array | None = None,
256 replace_mobject_with_target_in_scene: bool = False,
257 *,
258 keys: Sequence[Key] | None = None,
259 **kwargs: Unpack[AnimationOptions],
260 ) -> None:
261 self.path_arc_axis, self.path_arc_centers = path_arc_axis, path_arc_centers
262 self.path_arc = path_arc
263 if path_func is not None:
264 self._path_func = path_func
265 elif path_arc_centers is not None:
266 self._path_func = path_along_circles(
267 path_arc, path_arc_centers, path_arc_axis
268 )
269 self.replace_mobject_with_target_in_scene = replace_mobject_with_target_in_scene
270 self.target_mobject = target_mobject
271 if keys is None:
272 if self.target_mobject is None:
273 self.target_mobject = Mobject()
274 keys = (None, self.target_mobject)
275 self.keys: Sequence[Key] = keys
276 self.shared: set[int] = set() # its leaves other tweens drive too (`compose`)
277 super().__init__(mobject, **kwargs)
279 @property
280 def path_arc(self) -> float:
281 """The angle each point turns through on its way, in radians.
283 Setting it makes the path an arc of that angle about `path_arc_axis`.
284 """
285 return self._path_arc
287 @path_arc.setter
288 def path_arc(self, value: float) -> None:
289 self._path_arc = value
290 self._path_func = path_along_arc(arc_angle=value, axis=self.path_arc_axis)
292 @property
293 def path_func(self) -> PathFunc:
294 """How each point travels from its start to its end.
296 A function of the start points, the end points and the progress; setting None
297 keeps the current one.
298 """
299 return self._path_func
301 @path_func.setter
302 def path_func(self, value: PathFunc | None) -> None:
303 if value is not None:
304 self._path_func = value
306 def begin(self) -> None:
307 # the base begin (the keyframes and the object; a tween acts only when
308 # interpolated), whether the target moves decided afresh: a target that moves runs
309 # from now, its updaters live from when the animation begins to run them
310 self._moving = None
311 super().begin()
312 if (target := self.moving_target()) is not None:
313 target._stamp(clock.now)
315 def take(self) -> None:
316 # take the object; in a play, join the tweens driving its leaves
317 super().take()
318 self.__dict__.pop("motion", None)
319 self.shared = set()
320 if (compositor := self._compositor()) is not None:
321 compositor.join(self)
323 def finish(self) -> None:
324 # it rests as it ends, where it alone drove its leaves; where others drove them too,
325 # they compose, and one that ends as given leaves what the others did
326 super().finish()
327 compositor = self._compositor()
328 if compositor is None or not self.shared:
329 if self._rest is not None:
330 self.mobject.become(self._rest)
331 elif self._ends_as_given():
332 compositor.leave(self)
333 if compositor is not None:
334 compositor.finished.add(id(self))
336 def _compositor(self) -> Compositor | None:
337 return None if self._scene is None else self._scene.compositor
339 @functools.cached_property
340 @deprecated("ManimGX's machinery: the play calls it", category=None)
341 def motion(self) -> tuple[tuple[Step, ...], Floats] | None:
342 """The motion that carries the mobject from its first keyframe to its last, or
343 None.
345 For transforms that compose: its steps (turns about points of the mobject as it
346 began, and moves; a straight path's is the move of its center) and the whole
347 motion undone. None when the path is not a motion.
348 """
349 path, frames = self.path_func, self.frames
350 if not (isinstance(path, Path) and path.kind == "motion" and len(frames) == 2):
351 return None
352 moved = frames[1].get_center() - frames[0].get_center()
353 steps = path.steps or ((moved,) if np.any(moved) else ())
354 return steps, np.linalg.inv(carried((step, 1.0) for step in steps))
356 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
357 def moving_target(self) -> Mobject | None:
358 """The target, if it moves while the animation plays; None if it doesn't.
360 It moves when it is a mobject of its own with updaters that the scene does not
361 run: the animation runs them (`advance`), and the keyframes follow it. Decided
362 once, when first asked.
363 """
364 # decided once: not a walk of the scene per animation, nor of the target per
365 # frame
366 moving = self._moving
367 if moving is None:
368 target = self.keys[-1]
369 moving = False
370 if (
371 isinstance(target, Mobject)
372 and _updating(target)
373 and (
374 self._scene is None
375 or not any(
376 target is m for m in self._scene.get_mobject_family_members()
377 )
378 )
379 ):
380 moving = target
381 self._moving = moving
382 return None if moving is False else moving
384 def advance(self, t: Fraction) -> None:
385 # the object's updaters, brought to scene time `t` on its model, a moving target's
386 # too; then the keyframes follow
387 moving = self.moving_target()
388 if self.model is None and moving is None:
389 return
390 if self.model is not None:
391 self.model.advance(t)
392 if moving is not None:
393 moving.advance(t)
394 self.rederive()
396 def _ends_as_given(self) -> bool:
397 """Whether it leaves its mobject as it was given, whatever its last frame shows: a
398 remover does, as it takes it out of the scene."""
399 return self.is_remover()
401 def _resting(self, source: Mobject, own: list[Mobject | None]) -> Mobject | None:
402 # as it was given, if it ends so; else, when its frames blend its keyframes, the
403 # keyframe its last frame shows, as derived
404 if self._ends_as_given():
405 return source.copy()
406 at = self._resting_at(len(own) - 1)
407 if at is None:
408 return None
409 frame = own[at]
410 return (source if frame is None else frame).copy()
412 def _resting_at(self, steps: int) -> int | None:
413 # the keyframe the last frame shows: none, for frames of a class's own making (not
414 # this blend of keyframes at the eased progress) or that end between two
415 kind = type(self)
416 if (
417 kind.interpolate is not Animation.interpolate
418 or kind.interpolate_mobject is not Animation.interpolate_mobject
419 or kind.interpolate_keyframes is not Transform.interpolate_keyframes
420 ):
421 return None
422 i, t = keyframe_at(steps, self.get_sub_alpha(1.0, 0, 1))
423 return i + int(t) if t in (0.0, 1.0) else None
425 def rederive(self) -> None:
426 # the keyframes again (from the model, if the object updates; own objects copied
427 # afresh), aligned with the object; and what it rests as, from them
428 model = self.model
429 self.frames = [
430 (
431 key.copy()
432 if isinstance(key, Mobject)
433 else (
434 frame
435 if model is None
436 else model.copy()
437 if key is None
438 else key(model.copy())
439 )
440 )
441 for key, frame in zip(self.keys, self.frames, strict=True)
442 ]
443 if self._ends_as_given():
444 if model is not None: # as its updaters have it now
445 self._rest = model.copy()
446 elif (at := self._resting_at(len(self.frames) - 1)) is not None and (
447 model is not None or isinstance(self.keys[at], Mobject)
448 ): # a keyframe derived afresh, not yet aligned
449 self._rest = self.frames[at].copy()
450 for _ in range(2):
451 for frame in self.frames:
452 self.mobject.align_data(frame)
454 def interpolate_keyframes(
455 self, submobject: Mobject, keys: Sequence[Mobject], alpha: float
456 ) -> None:
457 i, t = keyframe_at(len(keys) - 1, alpha) # past its ends, it runs on
458 a, b = keys[i], keys[i + 1]
459 shared = self.shared and id(submobject) in self.shared
460 compositor = self._compositor() if shared else None
461 if compositor is None or not compositor.write(submobject, self, a, b, t):
462 submobject.interpolate(a, b, t, self.path_func)
464 def clean_up_from_scene(self, scene: Scene) -> None:
465 super().clean_up_from_scene(scene)
466 if (
467 self.replace_mobject_with_target_in_scene
468 and self.target_mobject is not None
469 ):
470 scene.replace(self.mobject, self.target_mobject)
473class _Call:
474 """A method call, with mobject arguments captured when it is written."""
476 __slots__ = ("args", "function", "kwargs")
478 def __init__(
479 self,
480 function: Callable[..., object],
481 args: tuple[object, ...],
482 kwargs: dict[str, object],
483 own: set[int],
484 ) -> None:
485 def written(value: object) -> object:
486 return (
487 value.copy()
488 if isinstance(value, Mobject) and id(value) not in own
489 else value
490 )
492 self.function = function
493 self.args = tuple(written(value) for value in args)
494 self.kwargs = {key: written(value) for key, value in kwargs.items()}
496 def __call__(self, target: Mobject) -> Mobject:
497 self.function(target, *self.args, **self.kwargs)
498 return target
501_EYE = np.eye(3)
504_ZERO = np.zeros(3)
507_BRUSHES = ("fill", "stroke", "background")
510_FIELDS = ( # every paint field a tween changes but the sheen's direction
511 "fill",
512 "stroke",
513 "background",
514 "stroke_width",
515 "background_width",
516 "sheen_factor",
517 "trim",
518 "pace",
519 "dash",
520)
523class Compositor:
524 """A play's leaves, and the tweens driving each (`Scene.play` makes one per play)."""
526 def __init__(self) -> None:
527 self.leaves: dict[int, _Leaf] = {}
528 self.finished: set[int] = set() # the tweens that have finished
530 def join(self, tween: Transform) -> None:
531 """`tween` begins: it joins the tweens on a leaf they have not moved since they began (the leaf
532 is then shared), and takes over any other leaf."""
533 for leaf in tween.mobject.family_members_with_points():
534 entry = self.leaves.get(id(leaf))
535 if entry is not None and entry.found(leaf):
536 entry.parts.append(_Part(tween))
537 for part in entry.parts:
538 part.tween.shared.add(id(leaf))
539 continue
540 for part in entry.parts if entry is not None else ():
541 if id(part.tween) not in self.finished:
542 part.tween.shared.add(id(leaf))
543 self.leaves[id(leaf)] = _Leaf(leaf, tween)
545 def leave(self, tween: Transform) -> None:
546 """`tween` ends, leaving its mobject as it was given: each leaf it drove with others
547 is as they have it, and one it drove alone as they all found it."""
548 for leaf in tween.mobject.family_members_with_points():
549 entry = self.leaves.get(id(leaf))
550 if entry is None or all(p.tween is not tween for p in entry.parts):
551 continue
552 entry.parts = [p for p in entry.parts if p.tween is not tween]
553 if entry.parts:
554 entry.compose()
555 else:
556 leaf._geometry, leaf.paint = entry.geometry, entry.paint
558 def write(
559 self, leaf: Mobject, tween: Transform, a: Mobject, b: Mobject, t: float
560 ) -> bool:
561 """Write a shared `leaf` as `tween` has it — between keyframes a and b, at t — with
562 the other tweens driving it. False: the tween writes it itself."""
563 entry = self.leaves[id(leaf)]
564 part = next((p for p in entry.parts if p.tween is tween), None)
565 if part is None: # the leaf was taken over from it
566 return True
567 part.keys, part.t = (a, b), t
568 return entry.compose()
571class _Part:
572 def __init__(self, tween: Transform) -> None:
573 self.tween = tween
574 self.keys: tuple[Mobject, Mobject] | None = None # once it has written
575 self.t = 0.0
578class _Leaf:
579 """A leaf as its tweens found it when they began, and those tweens."""
581 def __init__(self, leaf: Mobject, tween: Transform) -> None:
582 self.leaf, self.geometry, self.paint = leaf, leaf._geometry, leaf.paint
583 self.parts = [_Part(tween)]
585 def found(self, leaf: Mobject) -> bool:
586 """Is the leaf as its tweens found it (none of them has moved it)?"""
587 return leaf._geometry is self.geometry and leaf.paint is self.paint
589 def compose(self) -> bool:
590 parts = [(p.tween, p.keys, p.t) for p in self.parts if p.keys is not None]
591 n = self.geometry.n
592 if any(k._geometry.n != n for _, keys, _ in parts for k in keys):
593 return False
594 steps: list[tuple[Step, float]] = []
595 body, paint = self.geometry, self.paint
596 changed: dict[str, object] = {}
597 for tween, (a, b), t in parts:
598 if tween.motion is None: # not a motion: the leaf as the tween has it
599 path = tween.path_func
600 rest = (
601 Blend.mix(a._geometry, b._geometry, path.coefficients(t))
602 if isinstance(path, Path)
603 else Blend.of(path(a.points, b.points, t))
604 )
605 else: # its chord in the frame its motion carries
606 own, undo = tween.motion
607 steps += [(step, t) for step in own]
608 coefficients = ((1 - t) * _EYE, t * undo[:3, :3], t * undo[:3, 3])
609 rest = Blend.mix(a._geometry, b._geometry, coefficients)
610 body = Blend.mix(body, rest, (_EYE, _EYE, _ZERO))
611 body = Blend.mix(body, self.geometry, (_EYE, -_EYE, _ZERO))
612 mixed = paint.mixed(a.paint, b.paint, t)
613 for name in _FIELDS:
614 if (value := getattr(mixed, name)) is getattr(paint, name):
615 continue
616 if name in _BRUSHES and name in changed:
617 value = _channels(changed[name], value, getattr(paint, name))
618 changed[name] = value
619 motion = carried(steps)
620 changed["sheen_direction"] = motion[:3, :3] @ paint.sheen_direction
621 self.leaf._geometry = body.transformed(motion[:3])
622 self.leaf.paint = paint.but(**changed)
623 return True
626def _channels(before: object, value: np.ndarray, own: np.ndarray) -> np.ndarray:
627 """A brush that two tweens change: its colors the last changer's, and its opacities (a
628 brush of other rows: the last changer's whole)."""
629 if not (
630 isinstance(before, np.ndarray) and before.shape == value.shape == own.shape
631 ):
632 return value
633 out = np.array(before)
634 if not np.array_equal(value[:, :3], own[:, :3]):
635 out[:, :3] = value[:, :3]
636 if not np.array_equal(value[:, 3], own[:, 3]):
637 out[:, 3] = value[:, 3]
638 return out
641class _Methods:
642 """Every `-> Self` method of the library, by the class that defines it (see the module doc)."""
644 if TYPE_CHECKING:
645 # Mobject
646 add = recorded(_on(VDict).add, _on(Group).add, _on(Mobject).add)
647 add_background_rectangle = recorded(_on(Mobject).add_background_rectangle)
648 add_n_more_submobjects = recorded(_on(Mobject).add_n_more_submobjects)
649 add_to_back = recorded(_on(Mobject).add_to_back)
650 add_updater = recorded(_on(Mobject).add_updater)
651 align_data = recorded(_on(Mobject).align_data)
652 align_on_border = recorded(_on(Mobject).align_on_border)
653 align_points = recorded(_on(Mobject).align_points)
654 align_points_with_larger = recorded(_on(Mobject).align_points_with_larger)
655 align_submobjects = recorded(_on(Mobject).align_submobjects)
656 align_to = recorded(_on(Mobject).align_to)
657 apply_complex_function = recorded(_on(Mobject).apply_complex_function)
658 apply_function = recorded(_on(Mobject).apply_function)
659 apply_function_to_position = recorded(_on(Mobject).apply_function_to_position)
660 apply_function_to_submobject_positions = recorded(
661 _on(Mobject).apply_function_to_submobject_positions
662 )
663 apply_matrix = recorded(_on(Mobject).apply_matrix)
664 apply_points_function_about_point = recorded(
665 _on(Mobject).apply_points_function_about_point
666 )
667 arrange = recorded(_on(Mobject).arrange)
668 arrange_in_grid = recorded(_on(Mobject).arrange_in_grid)
670 @deprecated("arrange_submobjects is arrange: use it", category=None)
671 def arrange_submobjects(
672 self,
673 direction: Vector3DLike = RIGHT,
674 buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
675 center: bool = True,
676 **kwargs: Unpack[Beside],
677 ) -> Self: ...
679 become = recorded(_on(Mobject).become)
680 center = recorded(_on(Mobject).center)
681 clear_updaters = recorded(_on(Mobject).clear_updaters)
682 fade = recorded(_on(Mobject).fade)
683 fade_to = recorded(_on(Mobject).fade_to)
684 flip = recorded(_on(Mobject).flip)
685 generate_points = recorded(_on(Mobject).generate_points)
686 generate_target = recorded(_on(Mobject).generate_target)
687 init_colors = recorded(_on(Mobject).init_colors)
688 init_points = recorded(_on(Mobject).init_points)
689 insert = recorded(_on(Mobject).insert)
690 interpolate_color = recorded(_on(Mobject).interpolate_color)
691 invert = recorded(_on(Mobject).invert)
692 match_color = recorded(_on(Mobject).match_color)
693 match_coord = recorded(_on(Mobject).match_coord)
694 match_depth = recorded(_on(Mobject).match_depth)
695 match_dim_size = recorded(_on(Mobject).match_dim_size)
696 match_height = recorded(_on(Mobject).match_height)
697 match_points = recorded(_on(Mobject).match_points)
698 match_style = recorded(_on(Mobject).match_style)
699 match_updaters = recorded(_on(Mobject).match_updaters)
700 match_width = recorded(_on(Mobject).match_width)
701 match_x = recorded(_on(Mobject).match_x)
702 match_y = recorded(_on(Mobject).match_y)
703 match_z = recorded(_on(Mobject).match_z)
704 move_to = recorded(_on(Mobject).move_to)
705 next_to = recorded(_on(Mobject).next_to)
706 null_point_align = recorded(_on(Mobject).null_point_align)
707 pointwise_become_partial = recorded(_on(Mobject).pointwise_become_partial)
708 push_self_into_submobjects = recorded(_on(Mobject).push_self_into_submobjects)
709 put_start_and_end_on = recorded(_on(Mobject).put_start_and_end_on)
710 remove = recorded(_on(VDict).remove, _on(Mobject).remove)
711 remove_updater = recorded(_on(Mobject).remove_updater)
712 replace = recorded(_on(Mobject).replace)
713 rescale_to_fit = recorded(_on(Mobject).rescale_to_fit)
714 reset_points = recorded(_on(Mobject).reset_points)
715 restore = recorded(_on(Mobject).restore)
716 resume_updating = recorded(_on(Mobject).resume_updating)
717 reverse_points = recorded(_on(Mobject).reverse_points)
718 rotate = recorded(_on(Mobject).rotate)
720 @deprecated(
721 "rotate_about_origin(angle, axis) is rotate(angle, axis, about_point=ORIGIN)",
722 category=None,
723 )
724 def rotate_about_origin(
725 self, angle: float, axis: Vector3DLike = OUT
726 ) -> Self: ...
728 save_state = recorded(_on(Mobject).save_state)
729 scale = recorded(_on(Arrow).scale, _on(Typst).scale, _on(Mobject).scale)
730 scale_to_fit_height = recorded(_on(Mobject).scale_to_fit_height)
731 scale_to_fit_width = recorded(_on(Mobject).scale_to_fit_width)
732 set = recorded(_on(Mobject).set)
733 set_color = recorded(_on(ImageMobject).set_color, _on(Mobject).set_color)
734 set_color_by_gradient = recorded(_on(Mobject).set_color_by_gradient)
735 set_colors_by_radial_gradient = recorded(
736 _on(Mobject).set_colors_by_radial_gradient
737 )
738 set_coord = recorded(_on(Mobject).set_coord)
739 set_fill = recorded(_on(Mobject).set_fill)
740 set_material = recorded(_on(Mobject).set_material)
741 set_opacity = recorded(_on(ImageMobject).set_opacity, _on(Mobject).set_opacity)
742 set_points = recorded(_on(Mobject).set_points)
743 set_sheen = recorded(_on(Mobject).set_sheen)
744 set_sheen_direction = recorded(_on(Mobject).set_sheen_direction)
745 set_stroke = recorded(_on(Mobject).set_stroke)
746 set_style = recorded(_on(Mobject).set_style)
747 set_submobject_colors_by_gradient = recorded(
748 _on(Mobject).set_submobject_colors_by_gradient
749 )
750 set_submobject_colors_by_radial_gradient = recorded(
751 _on(Mobject).set_submobject_colors_by_radial_gradient
752 )
753 set_x = recorded(_on(Mobject).set_x)
754 set_y = recorded(_on(Mobject).set_y)
755 set_z = recorded(_on(Mobject).set_z)
756 set_z_index = recorded(_on(Mobject).set_z_index)
757 shift = recorded(_on(Mobject).shift)
758 shift_onto_screen = recorded(_on(Mobject).shift_onto_screen)
759 shuffle = recorded(_on(Mobject).shuffle)
760 sort = recorded(_on(Mobject).sort)
761 sort_submobjects = recorded(_on(Mobject).sort_submobjects)
762 space_out_submobjects = recorded(_on(Mobject).space_out_submobjects)
763 stretch = recorded(_on(Mobject).stretch)
764 stretch_about_point = recorded(_on(Mobject).stretch_about_point)
765 stretch_to_fit_height = recorded(_on(Mobject).stretch_to_fit_height)
766 stretch_to_fit_width = recorded(_on(Mobject).stretch_to_fit_width)
767 surround = recorded(_on(Circle).surround)
768 suspend_updating = recorded(_on(Mobject).suspend_updating)
769 to_corner = recorded(_on(Mobject).to_corner)
770 to_edge = recorded(_on(Mobject).to_edge)
771 to_original_color = recorded(_on(Mobject).to_original_color)
772 update = recorded(_on(Mobject).update)
773 # VMobject
774 add_cubic_bezier_curve = recorded(_on(VMobject).add_cubic_bezier_curve)
775 add_cubic_bezier_curve_to = recorded(_on(VMobject).add_cubic_bezier_curve_to)
776 add_cubic_bezier_curves = recorded(_on(VMobject).add_cubic_bezier_curves)
777 add_line_to = recorded(_on(VMobject).add_line_to)
778 add_points_as_corners = recorded(_on(VMobject).add_points_as_corners)
779 add_quadratic_bezier_curve_to = recorded(
780 _on(VMobject).add_quadratic_bezier_curve_to
781 )
782 add_smooth_curve_to = recorded(_on(VMobject).add_smooth_curve_to)
783 add_subpath = recorded(_on(VMobject).add_subpath)
784 append_points = recorded(_on(VMobject).append_points)
785 append_vectorized_mobject = recorded(_on(VMobject).append_vectorized_mobject)
786 change_anchor_mode = recorded(_on(VMobject).change_anchor_mode)
787 clear_points = recorded(_on(VMobject).clear_points)
788 close_path = recorded(_on(VMobject).close_path)
789 force_direction = recorded(_on(VMobject).force_direction)
790 get_subcurve = recorded(_on(VMobject).get_subcurve)
791 insert_n_curves = recorded(_on(VMobject).insert_n_curves)
792 make_jagged = recorded(_on(VMobject).make_jagged)
793 make_smooth = recorded(_on(VMobject).make_smooth)
794 reverse_direction = recorded(_on(VMobject).reverse_direction)
795 scale_handle_to_anchor_distances = recorded(
796 _on(VMobject).scale_handle_to_anchor_distances
797 )
798 set_anchors_and_handles = recorded(_on(VMobject).set_anchors_and_handles)
799 set_cap_style = recorded(_on(VMobject).set_cap_style)
800 set_points_as_corners = recorded(_on(VMobject).set_points_as_corners)
801 set_points_smoothly = recorded(_on(VMobject).set_points_smoothly)
802 set_shade_in_3d = recorded(_on(VMobject).set_shade_in_3d)
803 start_new_path = recorded(_on(VMobject).start_new_path)
804 # the kinds' own
805 add_background_to_entries = recorded(_on(Table).add_background_to_entries)
806 add_bases = recorded(_on(Cylinder).add_bases)
807 add_coordinates = recorded(
808 _on(PolarPlane).add_coordinates,
809 _on(ComplexPlane).add_coordinates,
810 _on(Axes).add_coordinates,
811 )
812 add_display_frame = recorded(_on(ImageMobjectFromCamera).add_display_frame)
813 add_highlighted_cell = recorded(_on(Table).add_highlighted_cell)
814 add_key_value_pair = recorded(_on(VDict).add_key_value_pair)
815 add_labels = recorded(_on(NumberLine).add_labels)
816 add_line = recorded(_on(Mobject1D).add_line)
817 add_numbers = recorded(_on(NumberLine).add_numbers)
818 add_points = recorded(_on(PMobject).add_points)
819 add_ticks = recorded(_on(NumberLine).add_ticks)
820 add_tip = recorded(_on(TipableVMobject).add_tip)
821 assign_tip_attr = recorded(_on(TipableVMobject).assign_tip_attr)
822 change_bar_values = recorded(_on(BarChart).change_bar_values)
823 change_label = recorded(_on(BraceLabel).change_label)
824 change_layout = recorded(_on(GenericGraph).change_layout)
825 divide_vertically = recorded(_on(SampleSpace).divide_vertically)
826 fade_all_but = recorded(_on(BulletedList).fade_all_but)
827 fit_to_coordinate_system = recorded(_on(VectorField).fit_to_coordinate_system)
828 full_family_become_partial = recorded(
829 _on(AnimatedBoundary).full_family_become_partial
830 )
831 increment_value = recorded(
832 _on(ValueTracker[complex]).increment_value,
833 _on(ValueTracker).increment_value,
834 _on(DecimalNumber).increment_value,
835 _on(DecimalNumber[complex]).increment_value,
836 )
837 match_colors = recorded(_on(PMobject).match_colors)
838 move_arc_center_to = recorded(_on(Arc).move_arc_center_to)
839 nudge = recorded(_on(VectorField).nudge)
840 nudge_submobjects = recorded(_on(VectorField).nudge_submobjects)
841 prepare_for_nonlinear_transform = recorded(
842 _on(_Plane).prepare_for_nonlinear_transform
843 )
844 put_at_tip = recorded(_on(Brace).put_at_tip)
845 reset_endpoints_based_on_tip = recorded(
846 _on(TipableVMobject).reset_endpoints_based_on_tip
847 )
848 reset_normal_vector = recorded(_on(Arrow).reset_normal_vector)
849 rotate_about_number = recorded(_on(NumberLine).rotate_about_number)
850 rotate_about_zero = recorded(_on(NumberLine).rotate_about_zero)
851 round_corners = recorded(_on(Polygram).round_corners)
852 set_angle = recorded(_on(Line).set_angle)
853 set_color_by_tex = recorded(_on(MathTex).set_color_by_tex)
854 set_color_by_tex_to_color_map = recorded(
855 _on(MathTex).set_color_by_tex_to_color_map
856 )
857 set_column_colors = recorded(
858 _on(Matrix).set_column_colors, _on(Table).set_column_colors
859 )
860 set_direction = recorded(_on(_DirectedSurface).set_direction)
861 set_fill_by_checkerboard = recorded(_on(Surface).set_fill_by_checkerboard)
862 set_fill_by_value = recorded(_on(Surface).set_fill_by_value)
863 set_length = recorded(_on(Line).set_length)
864 set_location = recorded(_on(VectorizedPoint).set_location)
865 set_path_arc = recorded(_on(Line).set_path_arc)
866 set_points_by_ends = recorded(_on(Line).set_points_by_ends)
867 set_resampling_algorithm = recorded(_on(ImageMobject).set_resampling_algorithm)
868 set_row_colors = recorded(_on(Matrix).set_row_colors, _on(Table).set_row_colors)
869 set_start_and_end_attrs = recorded(_on(Line3D).set_start_and_end_attrs)
870 set_value = recorded(
871 _on(ComplexValueTracker).set_value,
872 _on(ValueTracker).set_value,
873 _on(DecimalNumber).set_value,
874 _on(DecimalNumber[complex]).set_value,
875 )
876 start_animation = recorded(_on(StreamLines).start_animation)
877 start_submobject_movement = recorded(_on(VectorField).start_submobject_movement)
878 stop_submobject_movement = recorded(_on(VectorField).stop_submobject_movement)
879 thin_out = recorded(_on(PMobject).thin_out)
880 update_edges = recorded(_on(GenericGraph).update_edges)
881 update_faces = recorded(_on(Polyhedron).update_faces)
884class Animate[M: Mobject](Transform[M], _Methods):
885 """An animation of a mobject's method calls.
887 It is what [`mobject.animate`][manimgx.Mobject.animate] returns. Call methods on it
888 as on the mobject, `square.animate.shift(RIGHT).scale(2)`, and play it: it is the
889 animation. Each call is recorded and tried at once on a copy, so a wrong call fails
890 where it is written, and the calls are carried out on the mobject as it is when the
891 animation begins (in a [`Succession`][manimgx.Succession], after the parts before
892 it). When it finishes, the mobject is exactly what the calls make of it.
894 The mobject moves as the calls do: a turn among them (`rotate`, `flip`) turns it
895 rigidly, through its whole angle (`rotate(TAU)` is a full turn), about its pivot as
896 the motion carries it; any other call moves its
897 center in a straight line; and the rest of the change (a scale, a color, a new
898 shape) happens along the way. A `path_arc` or `path_func` of its own replaces that
899 motion.
901 Called before any method, it takes the animation's
902 [options][manimgx.animation.transform.TransformOptions]:
903 `square.animate(run_time=2, rate_func=linear).shift(RIGHT)`. It also takes an edit,
904 a function applied to the mobject as a method would be:
905 `square.animate(lambda mob: mob.shift(RIGHT))`.
907 Args:
908 mobject: The mobject whose method calls are animated.
910 Examples:
911 ```python
912 import manimgx as m
915 class AnimateExample(m.Scene):
916 def construct(self) -> None:
917 bar = m.Rectangle(width=3, height=1, color=m.BLUE, fill_opacity=0.5)
918 self.add(bar.shift(4 * m.LEFT))
919 self.play(
920 bar.animate(run_time=2)
921 .shift(8 * m.RIGHT)
922 .rotate(m.PI / 2)
923 .set_color(m.YELLOW)
924 )
925 ```
926 """
928 def __init__(self, mobject: M) -> None:
929 self._target = mobject.generate_target()
930 self._override: Animation | None = None
931 self._chaining = False
932 self._anim_args: TransformOptions = {}
933 self.methods: list[_Call] = []
934 super().__init__(mobject, self._target)
935 self._chosen: PathFunc | None = self._path_func
936 self.keys = (None, self._replay)
938 def __call__(
939 self,
940 function: Callable[[M], object] | None = None,
941 /,
942 **anim_args: Unpack[TransformOptions],
943 ) -> Self:
944 """Set the animation's options, before any method is recorded; and record a
945 function of the mobject, as a method's call is recorded.
947 A function can make any change, with methods of your own class too, and a type
948 checker checks it against the mobject's class: `box.animate(lambda b: b.grow(2))`.
949 (`box.animate.grow(2)` works as well, but through `animate` a type checker knows
950 only ManimGX's methods.)
952 Args:
953 function: A function that changes the mobject: tried at once on a copy, so a
954 wrong call fails where it is written, and carried out as recorded methods
955 are. None for none.
956 **anim_args: [Transform options][manimgx.animation.transform.TransformOptions].
958 Returns:
959 This animation, for chaining.
960 """
961 if self._chaining and anim_args:
962 raise ValueError(
963 "Animation arguments must be passed before accessing methods and can"
964 " only be passed once"
965 )
966 if (
967 anim_args
968 ): # the animation, constructed with them (an override gets them too)
969 self._anim_args = anim_args
970 super().__init__(self.mobject, self.mobject.target, **anim_args)
971 self._chosen = (
972 None
973 if any(
974 k in anim_args
975 for k in ("path_func", "path_arc", "path_arc_centers")
976 )
977 else self._path_func
978 )
979 self.keys = (None, self._replay)
980 if function is not None:
981 if self._override is not None:
982 raise NotImplementedError(
983 "Method chaining is currently not supported for overridden animations"
984 )
985 self._record(function, (), {})
986 self._chaining = True
987 return self
989 def _record(
990 self,
991 function: Callable[..., object],
992 args: tuple[object, ...],
993 kwargs: dict[str, object],
994 ) -> None:
995 """Record a call of `function` on the mobject, tried at once on the target: a
996 wrong call fails where it is written."""
997 function(self._target, *args, **kwargs)
998 own = {id(m) for mob in (self.mobject, self._target) for m in mob.get_family()}
999 self.methods.append(_Call(function, args, kwargs, own))
1001 def _recorder(self, name: str) -> Callable[..., Animation]:
1002 """The mobject's method `name`, which records its calls."""
1003 if name.startswith("_") or "_target" not in self.__dict__:
1004 raise AttributeError(name)
1005 method = getattr(self._target, name)
1006 override = (
1007 _animate_plays.get(method.__func__) if inspect.ismethod(method) else None
1008 )
1009 if (self._chaining and override is not None) or self._override is not None:
1010 raise NotImplementedError(
1011 "Method chaining is currently not supported for overridden animations"
1012 )
1014 def record(*args: object, **kwargs: object) -> Animation:
1015 if override is not None:
1016 animation: Animation = override(
1017 self.mobject, *args, anim_args=self._anim_args, **kwargs
1018 )
1019 self._override = animation
1020 return animation
1021 self._record(method.__func__, args, kwargs)
1022 return self
1024 self._chaining = True
1025 return record
1027 if (
1028 not TYPE_CHECKING
1029 ): # a type checker knows the methods by the table, and no others
1030 __getattr__ = _recorder
1032 def _replay(self, target: Mobject) -> Mobject:
1033 """The recorded calls, carried out on (a copy of) the object as it is when the animation
1034 begins, on their arguments as written."""
1035 turns = [_turn(item) for item in self.methods]
1036 if self._path_func is not self._chosen or not any(turns):
1037 for item in self.methods:
1038 item(target)
1039 return target
1040 steps: list[Step] = []
1041 for item, turn in zip(self.methods, turns, strict=True):
1042 if turn is not None:
1043 angle, axis, pivot = turn
1044 # its pivot as a point of the object as it began: where the steps so far took it
1045 whole = carried((step, 1.0) for step in steps)
1046 point = np.linalg.solve(whole, np.append(pivot(target), 1.0))[:3]
1047 steps.append((angle, axis, point))
1048 item(target)
1049 continue
1050 before = target.get_center()
1051 item(target)
1052 moved = target.get_center() - before
1053 if np.any(moved):
1054 steps.append(moved)
1055 self._path_func = self._chosen = Path(steps=tuple(steps))
1056 return target
1058 def finish(self) -> None:
1059 for item in self.methods:
1060 item(self.mobject)
1061 super().finish()
1063 def build(self) -> Animation:
1064 return self if self._override is None else self._override
1067def _turn(
1068 item: _Call,
1069) -> tuple[float, Floats, Callable[[Mobject], Floats]] | None:
1070 """(angle, axis, pivot) of a recorded call that turns the object (`rotate`, `flip`,
1071 `rotate_about_origin`), the pivot as the call finds it; None for any other call."""
1072 func = item.function
1073 name = getattr(func, "__name__", "")
1074 if name not in ("rotate", "flip", "rotate_about_origin"):
1075 return None
1076 try:
1077 bound = inspect.signature(func).bind(None, *item.args, **item.kwargs)
1078 bound.apply_defaults()
1079 given = bound.arguments
1080 angle = PI if name == "flip" else float(given["angle"])
1081 axis = np.asarray(given["axis"], dtype=np.float64)
1082 except (TypeError, KeyError, ValueError):
1083 return None
1084 point = ORIGIN if name == "rotate_about_origin" else given.get("about_point")
1085 edge = given.get("about_edge")
1087 def pivot(mob: Mobject) -> Floats:
1088 if point is not None:
1089 return np.asarray(point, dtype=np.float64)
1090 return mob.get_critical_point(ORIGIN if edge is None else edge)
1092 return angle, axis, pivot
1095class Always[M: Mobject](_Methods):
1096 """A mobject's method calls, each made again at every frame.
1098 It is what [`mobject.always`][manimgx.Mobject.always] returns. Each call, as
1099 `label.always.next_to(dot, UP)`, is made at once and then at every frame, as an
1100 updater of the mobject; calls chain. Their arguments are taken as they are written:
1101 pass mobjects (`dot`), which the call reads anew at every frame, not values computed
1102 from them (`dot.get_center()`), which stay as they were.
1104 Args:
1105 mobject: The mobject whose method calls become updaters.
1106 """
1108 def __init__(self, mobject: M) -> None:
1109 self._mobject = mobject
1111 @property
1112 def mobject(self) -> M: # (typing: the proxy of a mobject of this kind)
1113 """The mobject whose method calls become updaters."""
1114 return self._mobject
1116 def _updater(self, name: str) -> Callable[..., Self]:
1117 """The mobject's method `name`, whose calls become its updaters."""
1118 if name.startswith("_"):
1119 raise AttributeError(name)
1121 def add_updater(*args: object, **kwargs: object) -> Self:
1122 self._mobject.add_updater(
1123 lambda m: getattr(m, name)(*args, **kwargs), call_updater=True
1124 )
1125 return self
1127 return add_updater
1129 if (
1130 not TYPE_CHECKING
1131 ): # a type checker knows the methods by the table, and no others
1132 __getattr__ = _updater