Coverage for src/manimgx/animation/updaters.py: 99%
191 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# SPDX-FileCopyrightText: 2026 Academa, Inc.
2# SPDX-FileCopyrightText: 2024 the Manim Community Developers
3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
4# SPDX-License-Identifier: MIT
6"""Continuous motion: updater tools, animated outlines and recorded paths."""
8from __future__ import annotations
10from warnings import deprecated
12__all__ = [
13 "AnimatedBoundary",
14 "TracedPath",
15 "always",
16 "always_redraw",
17 "always_rotate",
18 "always_shift",
19 "assert_is_mobject_method",
20 "cycle_animation",
21 "f_always",
22 "turn_animation_into_updater",
23]
24import inspect
25import itertools
26from collections.abc import Callable, Sequence
27from dataclasses import dataclass
28from typing import TYPE_CHECKING, Self, Unpack
30import numpy as np
32from manimgx.animation import clock
33from manimgx.animation.easing import RateFunction, smooth
34from manimgx.constants import DEGREES, OUT, RIGHT
35from manimgx.drawing.geometry import normalize
36from manimgx.drawing.paint import (
37 BLUE_B,
38 BLUE_D,
39 BLUE_E,
40 GREY_BROWN,
41 WHITE,
42 ParsableManimColor,
43 Style,
44)
45from manimgx.mobject import Mobject, Pivot, VGroup, VMobject, flow, record
46from manimgx.typing import Point3DLike, Vector3DLike
48if TYPE_CHECKING:
49 from manimgx.animation.timeline import Animation
52def _owner(method: Callable[..., object]) -> tuple[Mobject, Callable[..., object]]:
53 """The mobject a bound method belongs to, and its plain function."""
54 if not inspect.ismethod(method) or not isinstance(method.__self__, Mobject):
55 raise TypeError("expected a method of a mobject, such as `square.move_to`")
56 return method.__self__, method.__func__
59@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
60def assert_is_mobject_method(method: Callable[..., object]) -> None:
61 """Check that `method` is a method of a mobject, bound to it (as `square.move_to`):
62 anything else raises a TypeError.
64 Args:
65 method: The method to check.
66 """
67 _owner(method)
70@deprecated(
71 "always(mobject.method, *args) is mobject.always.method(*args): use it",
72 category=None,
73)
74def always[**P](
75 method: Callable[P, object], *args: P.args, **kwargs: P.kwargs
76) -> Mobject:
77 """Call a method of a mobject every frame, with the same arguments: the relation it
78 sets is kept.
80 `always(label.next_to, dot, UP)` keeps the label above the dot, wherever the dot
81 goes. It adds a per-frame updater to the mobject the method belongs to (see
82 [`add_updater`][manimgx.Mobject.add_updater]), which first runs at the next frame,
83 not now. The arguments are taken once, as written: pass the mobject to follow
84 (`dot`), not its position (`dot.get_center()`), which would stay where it was.
85 [`Mobject.always`][manimgx.Mobject.always] does the same, as
86 `label.always.next_to(dot, UP)`.
88 Args:
89 method: A method of a mobject, bound to it (`label.next_to`).
90 *args: Its positional arguments.
91 **kwargs: Its keyword arguments.
93 Returns:
94 The mobject the method belongs to.
95 """
96 mobject, func = _owner(method)
97 mobject.add_updater(lambda m: func(m, *args, **kwargs))
98 return mobject
101@deprecated("use add_updater, or always_redraw", category=None)
102def f_always(
103 method: Callable[..., object],
104 *arg_generators: Callable[[], object],
105 **kwargs: object,
106) -> Mobject:
107 """Call a method of a mobject every frame, with arguments computed anew each time.
109 Each positional argument is given as a function of no arguments, called every frame
110 for the value to pass: `f_always(dot.set_x, tracker.get_value)` keeps the dot at the
111 x the tracker holds. It adds a per-frame updater to the mobject the method belongs
112 to (see [`add_updater`][manimgx.Mobject.add_updater]), which first runs at the next
113 frame, not now.
115 Args:
116 method: A method of a mobject, bound to it (`dot.set_x`).
117 *arg_generators: For each positional argument, a function of no arguments that
118 gives its value.
119 **kwargs: Keyword arguments, passed as they are.
121 Returns:
122 The mobject the method belongs to.
123 """
124 mobject, func = _owner(method)
125 mobject.add_updater(
126 lambda m: func(m, *(generate() for generate in arg_generators), **kwargs)
127 )
128 return mobject
131def always_redraw[M: Mobject](func: Callable[[], M]) -> M:
132 """Make a mobject that is built anew every frame, by a function.
134 `func` builds the mobject now, and every frame the mobject becomes what `func`
135 builds then (see [`become`][manimgx.Mobject.become]): it stays one object in the
136 scene, and follows whatever `func` reads — value trackers, other mobjects. Use it
137 for a shape that depends on others in a way no motion follows: a brace that fits a
138 growing shape, a line between two moving dots, the area under a graph.
140 Args:
141 func: A function of no arguments that builds the mobject.
143 Returns:
144 The mobject, with its updater: add it to the scene.
146 Examples:
147 ```python
148 import manimgx as m
151 class AlwaysRedrawExample(m.Scene):
152 def construct(self) -> None:
153 width = m.ValueTracker(2)
154 box = m.always_redraw(
155 lambda: m.Rectangle(width=width.get_value(), height=3, color=m.BLUE)
156 )
157 brace = m.always_redraw(lambda: m.Brace(box, m.DOWN, color=m.YELLOW))
158 self.add(box, brace)
159 self.play(width.animate.set_value(11), run_time=2)
160 self.play(width.animate.set_value(5))
161 ```
162 """
163 mob = func()
164 mob.add_updater(lambda m: m.become(func()))
165 return mob
168def always_shift[M: Mobject](
169 mobject: M, direction: Vector3DLike = RIGHT, rate: float = 0.1
170) -> M:
171 """Keep a mobject moving in a direction, at a steady speed.
173 It adds a time-based updater, a [flow][manimgx.mobject.flow], so at every frame
174 the mobject is exactly where its speed has brought it, through plays and waits
175 alike.
177 Args:
178 mobject: The mobject to move.
179 direction: The direction to move in; only its direction counts, not its length.
180 rate: The speed, in scene units per second.
182 Returns:
183 The mobject, with its updater.
185 Examples:
186 ```python
187 import manimgx as m
190 class AlwaysShiftExample(m.Scene):
191 def construct(self) -> None:
192 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.8)
193 square.shift(5 * m.LEFT)
194 m.always_shift(square, m.RIGHT, rate=2.5)
195 self.add(square)
196 self.play(square.animate.set_color(m.YELLOW), run_time=2)
197 self.wait(2)
198 ```
199 """
200 unit = normalize(direction)
201 mobject.add_updater(flow(lambda m, dt: m.shift(dt * rate * unit)))
202 return mobject
205def always_rotate[M: Mobject](
206 mobject: M,
207 rate: float = 20 * DEGREES,
208 axis: Vector3DLike = OUT,
209 **kwargs: Unpack[Pivot],
210) -> M:
211 """Keep a mobject turning, at a steady speed.
213 It adds a time-based updater, a [flow][manimgx.mobject.flow], so at every frame
214 the mobject is at exactly the angle its speed has brought it to, through plays and
215 waits alike.
217 Args:
218 mobject: The mobject to turn.
219 rate: The speed, in radians per second; a positive one turns counterclockwise.
220 axis: The axis it turns about.
221 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point it turns
222 about, its center unless given.
224 Returns:
225 The mobject, with its updater.
227 Examples:
228 ```python
229 import manimgx as m
232 class AlwaysRotateExample(m.Scene):
233 def construct(self) -> None:
234 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
235 square.shift(3.5 * m.LEFT)
236 m.always_rotate(square, rate=m.PI / 2) # a quarter turn a second
237 center = m.Dot(3.5 * m.RIGHT, color=m.YELLOW)
238 moon = m.Dot(3.5 * m.RIGHT + 2 * m.UP, radius=0.25, color=m.TEAL)
239 m.always_rotate(moon, rate=-m.PI, about_point=center.get_center())
240 self.add(square, center, moon)
241 self.wait(4)
242 ```
243 """
244 mobject.add_updater(flow(lambda m, dt: m.rotate(dt * rate, axis, **kwargs)))
245 return mobject
248def turn_animation_into_updater(
249 animation: Animation, cycle: bool = False, delay: float = 0
250) -> Mobject:
251 """Play an animation from an updater of its mobject, on the mobject's own time,
252 instead of in a play.
254 The animation begins at once: it takes its mobject as it is now, and shows its
255 start. Its time then runs with the scene's, from now or from when the mobject joins
256 the scene; after `delay` seconds it plays, at its run time and rate function. When
257 it ends, it finishes and its updater is removed; with `cycle`, it starts over from
258 its beginning instead, again and again. Nothing is added to the scene or taken out
259 of it: add the mobject yourself. The animation and its time are the mobject's: a
260 copy of it plays a copy of them, on itself.
262 Args:
263 cycle: Whether it repeats forever.
264 delay: How long it waits before it starts, in seconds.
266 Returns:
267 The animation's mobject, with its updater.
269 Examples:
270 ```python
271 import manimgx as m
274 class TurnAnimationIntoUpdaterExample(m.Scene):
275 def construct(self) -> None:
276 shape = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5)
277 squares = m.VGroup(*(shape.copy() for _ in range(3))).arrange(buff=1.5)
278 self.add(squares)
279 for i, square in enumerate(squares): # half a second apart
280 m.turn_animation_into_updater(
281 m.Rotate(square, m.PI / 2, run_time=1), delay=0.5 * i
282 )
283 self.wait(2.5)
284 ```
285 """
286 mobject = animation.mobject
287 animation.suspend_mobject_updating = False
288 animation.begin()
289 animation.interpolate(
290 0
291 ) # the object is the animation's from now: at its start, until then
292 # the animation and its time are kept on the mobject, so that a copy of it plays a copy
293 # of them: the updater holds only their key, and plays those of the mobject it runs on
294 key = next(_PLAYED_KEYS)
295 played: dict[int, _Played] = mobject.__dict__.setdefault("_played", {})
296 played[key] = _Played(animation, -delay)
298 def update(m: Mobject, dt: float) -> None:
299 state = m.__dict__.get("_played", {}).get(key)
300 if state is None: # nothing of its own to play
301 return
302 state.elapsed += dt # its time now: what this frame shows
303 if state.elapsed < 0:
304 return
305 animation, elapsed = state.animation, state.elapsed
306 run_time = animation.get_run_time()
307 if run_time > 0 and (cycle or elapsed < run_time):
308 animation.interpolate(
309 (elapsed / run_time) % 1 if cycle else elapsed / run_time
310 )
311 animation.advance(clock.now)
312 else:
313 animation.finish()
314 m.remove_updater(update)
315 del m.__dict__["_played"][key]
317 mobject.add_updater(flow(update)) # the animation at the time it has run
318 return mobject
321@dataclass
322class _Played:
323 """An animation [turn_animation_into_updater][manimgx.turn_animation_into_updater]
324 plays, and the time it has run (before its delay, negative)."""
326 animation: Animation
327 elapsed: float
330_PLAYED_KEYS = itertools.count()
333def cycle_animation(animation: Animation, delay: float = 0) -> Mobject:
334 """Play an animation over and over, from an updater of its mobject:
335 [`turn_animation_into_updater`][manimgx.turn_animation_into_updater] with `cycle`.
337 Each cycle starts the animation over from its beginning: an animation that does not
338 end where it began jumps back at every cycle.
340 Args:
341 delay: How long it waits before its first cycle, in seconds.
343 Returns:
344 The animation's mobject, with its updater.
346 Examples:
347 ```python
348 import manimgx as m
351 class CycleAnimationExample(m.Scene):
352 def construct(self) -> None:
353 orbit = m.Circle(radius=3, color=m.BLUE)
354 planet = m.Dot(orbit.get_start(), radius=0.25, color=m.YELLOW)
355 m.cycle_animation(
356 m.MoveAlongPath(planet, orbit, rate_func=m.linear, run_time=2)
357 )
358 self.add(orbit, planet)
359 self.wait(4)
360 ```
361 """
362 return turn_animation_into_updater(animation, cycle=True, delay=delay)
365class AnimatedBoundary(VGroup):
366 """An outline that keeps drawing itself around a mobject, cycling through colors.
368 Each cycle draws the mobject's outline in the next color, while the outline the
369 cycle before drew thins away; with `back_and_forth`, every other cycle draws it the
370 other way around. It follows the mobject: every frame, it takes the mobject's
371 outline as it is then. It draws only the outline: add it to the scene with the
372 mobject.
374 Args:
375 vmobject: The mobject to outline.
376 colors: The colors, one per cycle, in turn.
377 max_stroke_width: The outline's stroke width, in hundredths of a scene unit.
378 cycle_rate: How many cycles a second.
379 back_and_forth: Whether every other cycle draws the outline from its end back to
380 its start.
381 draw_rate_func: How each drawing is paced: a rate function.
382 fade_rate_func: How each thinning away is paced: a rate function.
383 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself.
385 Examples:
386 ```python
387 import manimgx as m
390 class AnimatedBoundaryExample(m.Scene):
391 def construct(self) -> None:
392 word = m.Text("So shiny!", font_size=144)
393 boundary = m.AnimatedBoundary(
394 word,
395 colors=[m.RED, m.YELLOW, m.BLUE],
396 max_stroke_width=8,
397 cycle_rate=1, # a color a second
398 )
399 self.add(word, boundary)
400 self.wait(3)
401 ```
402 """
404 def __init__(
405 self,
406 vmobject: Mobject,
407 colors: Sequence[ParsableManimColor] = (BLUE_D, BLUE_B, BLUE_E, GREY_BROWN),
408 max_stroke_width: float = 3,
409 cycle_rate: float = 0.5,
410 back_and_forth: bool = True,
411 draw_rate_func: RateFunction = smooth,
412 fade_rate_func: RateFunction = smooth,
413 **kwargs: Unpack[Style],
414 ):
415 super().__init__(**kwargs)
416 self.colors = list(colors) # its own: the default, or what was given, as it was
417 self.max_stroke_width = max_stroke_width
418 self.cycle_rate = cycle_rate
419 self.back_and_forth = back_and_forth
420 self.draw_rate_func = draw_rate_func
421 self.fade_rate_func = fade_rate_func
422 self.vmobject = vmobject
423 self.boundary_copies = [
424 vmobject.copy().set_style(stroke_width=0, fill_opacity=0) for x in range(2)
425 ]
426 self.add(*self.boundary_copies)
427 self.total_time = 0.0
428 self.add_updater(flow(lambda m, dt: m.update_boundary_copies(dt)))
430 @deprecated("Manim CE's machinery: its updater calls it", category=None)
431 def update_boundary_copies(self, dt: float) -> None:
432 """Move the outline on by some time: its updater calls it every frame.
434 Args:
435 dt: The time since it last moved on, in seconds.
436 """
437 self.total_time += dt # its time now: what this frame shows
438 time = self.total_time * self.cycle_rate
439 growing, fading = self.boundary_copies
440 colors = self.colors
441 msw = self.max_stroke_width
442 vmobject = self.vmobject
443 index = int(time % len(colors))
444 alpha = time % 1
445 draw_alpha = self.draw_rate_func(alpha)
446 fade_alpha = self.fade_rate_func(alpha)
447 if self.back_and_forth and int(time) % 2 == 1:
448 bounds = (1.0 - draw_alpha, 1.0)
449 else:
450 bounds = (0.0, draw_alpha)
451 self.full_family_become_partial(growing, vmobject, *bounds)
452 growing.set_stroke(colors[index], width=msw)
453 if time >= 1:
454 self.full_family_become_partial(fading, vmobject, 0, 1)
455 fading.set_stroke(color=colors[index - 1], width=(1 - fade_alpha) * msw)
457 @deprecated("Manim CE's machinery: its updater calls it", category=None)
458 def full_family_become_partial(
459 self, mob1: Mobject, mob2: Mobject, a: float, b: float
460 ) -> Self:
461 """Make each drawn member of one mobject a stretch of its counterpart in
462 another.
464 The members with points are paired in family order; each member of `mob1` takes
465 the stretch of its counterpart from proportion `a` to proportion `b` of its
466 curves.
468 Args:
469 mob1: The mobject whose members change.
470 mob2: The mobject whose members they take stretches of.
471 a: Where each stretch starts, from 0 to 1.
472 b: Where it ends, from `a` to 1.
474 Returns:
475 This boundary, for chaining.
476 """
477 family1 = mob1.family_members_with_points()
478 family2 = mob2.family_members_with_points()
479 for sm1, sm2 in zip(family1, family2, strict=False):
480 sm1.pointwise_become_partial(sm2, a, b)
481 return self
484class TracedPath(VMobject):
485 """The path a moving point traces: a line through everywhere it has been.
487 `traced_point_func` gives the point. The path records where it is at every tick of
488 the simulation clock
489 ([`config.simulation_rate`][manimgx.settings.Config.simulation_rate] times a second)
490 and at the end of each play and wait, so it is the same path at any frame rate; at a
491 frame between two ticks, it runs on to where the point is then. It traces while it
492 is in the scene, from when it joins it, and at each instant once everything else
493 has moved: its updater is a [recorder][manimgx.mobject.record].
495 A per-frame updater moves the point at frames only, so what it moves the point by
496 at a frame is its change over the frame that ends there: the path spreads that move
497 over the frame, in proportion to time. A point that a play carries while a
498 per-frame updater turns it traces one smooth curve, not stairs. With
499 `dissipating_time`, only the stretch traced in the last that many seconds remains.
501 Args:
502 traced_point_func: A function of no arguments that gives the point to trace
503 (`dot.get_center`).
504 dissipating_time: How long each stretch of the path remains, in seconds; None:
505 all of it remains.
506 **kwargs: [Style keywords][manimgx.drawing.paint.Style] (by default a white stroke,
507 2 wide).
509 Examples:
510 ```python
511 import manimgx as m
514 class TracedPathExample(m.Scene):
515 def construct(self) -> None:
516 wheel = m.Circle(radius=1, color=m.BLUE).shift(5 * m.LEFT)
517 dot = m.Dot(wheel.get_bottom(), radius=0.12, color=m.YELLOW)
518 rolling = m.VGroup(wheel, dot)
519 path = m.TracedPath(
520 dot.get_center, stroke_color=m.YELLOW, stroke_width=4
521 )
523 def roll(mob: m.Mobject, dt: float) -> None: # 2.5 radians a second
524 mob.rotate(-2.5 * dt, about_point=mob[0].get_center())
526 rolling.add_updater(roll)
527 self.add(path, rolling)
528 # 2.5 units a second: the wheel rolls without slipping
529 self.play(
530 rolling.animate.shift(10 * m.RIGHT), run_time=4, rate_func=m.linear
531 )
532 ```
533 """
535 def __init__(
536 self,
537 traced_point_func: Callable[[], Point3DLike],
538 dissipating_time: float | None = None,
539 **kwargs: Unpack[Style],
540 ) -> None:
541 if kwargs.get("stroke_color") is None: # not given, None too
542 kwargs["stroke_color"] = WHITE
543 if kwargs.get("stroke_width") is None: # not given, None too
544 kwargs["stroke_width"] = 2
545 super().__init__(**kwargs)
546 self.traced_point_func = traced_point_func
547 self.dissipating_time = dissipating_time
548 self.time = 0.0 # the path's own time
549 # when each curve's end was traced (its own time)
550 self._traced: list[float] = []
551 # the scene time of each curve's end since the last frame
552 self._open: list[float] = []
553 self._framed: float | None = None # the scene time of the last frame (or event)
554 self._last = np.zeros(3) # the point as last traced
555 self._loose = (
556 False # its last curve runs on to the point at a frame between two ticks
557 )
558 self.add_updater(
559 _trace
560 ) # (a function of the path it runs on: a copy traces itself)
562 @record
563 @deprecated("Manim CE's machinery: its updater calls it", category=None)
564 def update_path(self, mob: Mobject, dt: float) -> None:
565 """Trace the point where it is now: the path's updater, a
566 [recorder][manimgx.mobject.record].
568 At a tick of the simulation clock or at the end of a play or wait, the point is
569 traced for good; at a frame between two ticks, the path runs on to it, a
570 stretch the next instant takes back. A frame or an end runs it a second time
571 once the per-frame updaters have run: what they moved the point by is spread
572 over the frame that ends there, each stretch traced since the frame before
573 moved by its share of the frame's time. A dissipating path then drops what it
574 traced more than `dissipating_time` seconds ago.
576 Args:
577 mob: The path the updater runs on.
578 dt: The time since it last ran, in seconds.
579 """
580 # the second run is the instant's second pass (`clock.framing`, see
581 # `Scene._instant`): `_settle` spreads the move
582 point = np.asarray(self.traced_point_func(), dtype=float)
583 now = float(clock.now)
584 if clock.framing:
585 self._settle(point, now)
586 return
587 if self._loose:
588 self._loose = False
589 self.set_points(self.points[: -self.n_points_per_curve])
590 self._open.pop()
591 if self.has_points():
592 self._last = self.points[-1].copy()
593 self.time += dt
594 if not clock.stepping: # a frame between two ticks: loose, if the point moved
595 if not self.has_points() or not np.array_equal(point, self._last):
596 self._trace(point, now)
597 self._loose = True
598 return
599 self._trace(point, now)
600 if self.dissipating_time:
601 self._traced.append(self.time)
602 old = 0
603 while self._traced[old] < self.time - self.dissipating_time:
604 old += 1
605 if old:
606 del self._traced[:old]
607 self.set_points(self.points[old * self.n_points_per_curve :])
608 del self._open[: max(0, len(self._open) - len(self._traced))]
610 def _trace(self, point: np.ndarray, now: float) -> None:
611 if not self.has_points():
612 self.start_new_path(point)
613 self.add_line_to(point)
614 self._open.append(now)
615 self._last = point
617 def _settle(self, point: np.ndarray, now: float) -> None:
618 """The frame (or event) ending `now` moved the point on to `point`: each curve traced
619 since the last one takes its share of that move, by when it was traced. A curve's
620 handles move with its anchors, so it stays straight."""
621 jump = point - self._last
622 if jump.any():
623 if not self._open or self._open[-1] != now: # nothing traced here yet
624 self._trace(self._last, now)
625 self._loose = True
626 start = self._open[0] if self._framed is None else self._framed
627 span = now - start
628 ends = np.array(
629 [(t - start) / span if span > 0 else 1.0 for t in self._open]
630 )
631 first = ends[0] if self._framed is None else 0.0
632 starts = np.concatenate(([first], ends[:-1]))
633 weights = np.stack(
634 (starts, (2 * starts + ends) / 3, (starts + 2 * ends) / 3, ends), axis=1
635 ).reshape(-1, 1)
636 points = self.points.copy()
637 points[-len(weights) :] += weights * jump
638 self.set_points(points)
639 self._last = point
640 self._open = [now] if self._loose else []
641 self._framed = now
644@record
645def _trace(path: Mobject, dt: float) -> None:
646 """A traced path's updater: it traces the path it runs on (its copies, a path that takes
647 its updaters over), and holds nothing of the path it was made for."""
648 if isinstance(path, TracedPath):
649 path.update_path(path, dt)