Coverage for src/manimgx/animation/timeline.py: 98%

534 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1"""Animation time: lifecycle, exact composition windows, and speed profiles. 

2 

3The scalar lifecycle phases and vector schedules use the same group layout. 

4Scene chooses the instants; an animation tree evaluates what acts at each instant.""" 

5 

6from __future__ import annotations 

7 

8import weakref 

9from collections.abc import Callable, Iterable, Iterator, Sequence 

10from fractions import Fraction 

11from itertools import pairwise 

12from typing import ( 

13 TYPE_CHECKING, 

14 ClassVar, 

15 Literal, 

16 NamedTuple, 

17 Self, 

18 TypeIs, 

19 Unpack, 

20) 

21from warnings import deprecated 

22 

23import numpy as np 

24from typing_extensions import TypedDict 

25 

26from manimgx.animation import clock 

27from manimgx.animation.easing import linear, smooth 

28from manimgx.caches import Memo 

29from manimgx.drawing.geometry import integer_interpolate 

30from manimgx.mobject import ( 

31 Group, 

32 Mobject, 

33 _per_frame, 

34 flow, 

35 remove_list_redundancies, 

36 simulated, 

37) 

38from manimgx.typing import RateFunc 

39 

40if TYPE_CHECKING: 

41 from manimgx.scene import Scene 

42 

43if TYPE_CHECKING: 

44 from manimgx.mobject import VGroup 

45 

46if TYPE_CHECKING: 

47 from manimgx.mobject import Updater 

48 

49__all__ = [ 

50 "Add", 

51 "Animation", 

52 "AnimationGroup", 

53 "ChangeSpeed", 

54 "LaggedStart", 

55 "LaggedStartMap", 

56 "Succession", 

57 "Wait", 

58] 

59 

60 

61class _Untimed(TypedDict, total=False): 

62 """Untimed's keys, open, for the keywords that add to them.""" 

63 

64 lag_ratio: float 

65 """How the parts of the mobject are staggered: each begins this fraction of its run 

66 after the one before it begins (default 0: all together; 1: one after another).""" 

67 rate_func: RateFunc 

68 """How the animation's progress runs with time: a function from [0, 1] to [0, 1] 

69 (default [`smooth`][manimgx.smooth]; see 

70 [rate functions][manimgx.animation.easing]).""" 

71 reverse_rate_function: bool 

72 """Whether to run the animation backward (default False).""" 

73 name: str | None 

74 """A name for the animation.""" 

75 remover: bool 

76 """Whether the mobject leaves the scene when the animation finishes 

77 (default False).""" 

78 suspend_mobject_updating: bool 

79 """Whether the mobject's updaters run beneath the animation (default True): they 

80 keep acting on the mobject, and each frame shows the animation applied to the result. 

81 If False, they act on the animated mobject itself.""" 

82 introducer: bool 

83 """Whether the mobject joins the scene when the animation begins (default False); 

84 otherwise the play brings it in when the play begins, if the scene lacks it.""" 

85 use_override: bool 

86 """Whether a mobject whose class plays another animation in place of this one 

87 does so (default True).""" 

88 

89 

90class Untimed(_Untimed, total=False, closed=True): 

91 """Every animation option but `run_time`, which [`Wait`][manimgx.Wait] takes by 

92 position.""" 

93 

94 

95class _AnimationOptions(_Untimed, total=False): 

96 """AnimationOptions's keys, open, for the keywords that add to them.""" 

97 

98 run_time: float 

99 """How long the animation plays, in seconds (default 1).""" 

100 

101 

102class AnimationOptions(_AnimationOptions, total=False, closed=True): 

103 """The options every animation takes, by keyword. 

104 

105 Each animation class sets its own defaults for them: [`Create`][manimgx.Create], for 

106 instance, draws the parts of a mobject one after another (`lag_ratio=1`). 

107 """ 

108 

109 

110_CASCADES: Memo[type, AnimationOptions] = Memo(1 << 12) 

111 

112 

113def animation_defaults(cls: type[Animation]) -> AnimationOptions: 

114 """The options an animation class sets by default. 

115 

116 Each class in its hierarchy adds only what it changes (its `defaults`), the most 

117 derived last. 

118 

119 Args: 

120 cls: The animation class. 

121 

122 Returns: 

123 Its default options. 

124 """ 

125 cached = _CASCADES.get(cls) 

126 if cached is None: 

127 cached = AnimationOptions() 

128 for klass in reversed(cls.__mro__): 

129 if issubclass(klass, Animation) and "defaults" in vars(klass): 

130 cached = cached | klass.defaults 

131 _CASCADES.keep(cls, cached) 

132 return cached 

133 

134 

135type Key = "Mobject | Callable[[Mobject], Mobject] | None" 

136 

137 

138"""A keyframe as an animation declares it: its object as it begins (None), a function of a copy of 

139that, or an object of its own (copied when the animation begins).""" 

140 

141 

142def keyframe_at(steps: int, alpha: float) -> tuple[int, float]: 

143 """Where an eased progress falls among `steps` keyframe intervals: the interval, and 

144 how far along it. Past the ends (a rate function that overshoots, or backs up), the 

145 end intervals run on: the fraction is below 0 or above 1.""" 

146 if alpha < 0: 

147 return 0, alpha * steps 

148 if alpha > 1: 

149 return steps - 1, 1 + (alpha - 1) * steps 

150 return integer_interpolate(0, steps, alpha) 

151 

152 

153class Animation[M: Mobject = Mobject]: 

154 """A change of mobjects over a stretch of scene time. 

155 

156 An animation plays for `run_time` seconds of the scene's time. Its progress, 

157 `alpha`, goes from 0 at its start to 1 at its end, eased by its rate function (by 

158 default [`smooth`][manimgx.smooth]: slow, fast, slow). The parts of its mobject (the 

159 members of its family that have points) can be staggered: with a `lag_ratio`, each 

160 part begins that fraction of its run after the part before it, so 0 moves them all 

161 together and 1 one after another. 

162 

163 [`Scene.play`][manimgx.Scene.play] plays it. An animation that brings its mobject in 

164 adds it to the scene as it starts, and one that takes its mobject out removes it as 

165 it ends. The mobject's own updaters keep running while it plays: each frame shows 

166 the animation applied to the mobject as its updaters have it then, and when the 

167 animation ends, the mobject is as its last frame showed it. 

168 

169 To make an animation of your own, make a class from it, and override 

170 [`interpolate_mobject`][manimgx.Animation.interpolate_mobject]: it sets the whole 

171 mobject at the animation's progress, from 0 to 1, as it is before the rate function 

172 eases it, so apply `self.rate_func(alpha)` yourself. The options are attributes of 

173 the same names (`self.rate_func`, `self.lag_ratio`, …). An `Animation` itself 

174 changes nothing: it holds its mobject in the scene for its run time. 

175 

176 Args: 

177 mobject: The mobject to animate: a plain `Mobject()` for an animation that 

178 changes none, as a [`Wait`][manimgx.Wait] does. 

179 **options: [Animation options][manimgx.animation.timeline.AnimationOptions]. 

180 

181 Examples: 

182 ```python 

183 import manimgx as m 

184 

185 

186 class DropIn(m.Animation): 

187 def interpolate_submobject( 

188 self, submobject: m.Mobject, start: m.Mobject, alpha: float 

189 ) -> None: 

190 submobject.points = start.points 

191 submobject.shift((1 - alpha) * 2 * m.UP).set_opacity(alpha) 

192 

193 

194 class AnimationExample(m.Scene): 

195 def construct(self) -> None: 

196 word = m.Text("manimgx", font_size=144) 

197 self.play(DropIn(word, lag_ratio=0.3, run_time=2)) 

198 ``` 

199 """ 

200 

201 _call: tuple[tuple[object, ...], dict[str, object]] 

202 defaults: ClassVar[AnimationOptions] = {} 

203 """The options this class sets by default, only those it changes from its base 

204 classes' (they cascade down the class hierarchy).""" 

205 keys: Sequence[Key] = (None,) # the base part-by-part hook's starting state 

206 _held: Sequence[Mobject] = () # the members whose updating it suspended (`take`) 

207 

208 def __new__(cls, *args: object, **kwargs: object) -> Self: 

209 """Construction makes the class it names (so it type-checks like any call), keeping the 

210 arguments for a mobject that plays something else (`override_animation`).""" 

211 animation = super().__new__(cls) 

212 animation._call = args, kwargs 

213 return animation 

214 

215 def __init__(self, mobject: M, **options: Unpack[AnimationOptions]) -> None: 

216 o = animation_defaults(type(self)) | options 

217 self.run_time = o.get("run_time", 1.0) 

218 self.rate_func = o.get("rate_func", smooth) 

219 self.reverse_rate_function = o.get("reverse_rate_function", False) 

220 self.name = o.get("name") 

221 self.remover = o.get("remover", False) 

222 self.introducer = o.get("introducer", False) 

223 self.suspend_mobject_updating = o.get("suspend_mobject_updating", True) 

224 self.lag_ratio = o.get("lag_ratio", 0.0) 

225 self.use_override = o.get("use_override", True) 

226 self.frames: list[Mobject] = [] # the keyframes, as derived (`derive`) 

227 self._rest: Mobject | None = None # what its mobject is once it ends (`derive`) 

228 self._model: M | None = None 

229 self._scene: Scene | None = None # the scene it plays in (`_setup_scene`) 

230 self._mobject = mobject 

231 

232 # read-only, so an animation of a Circle is an animation of a Mobject (M is covariant) 

233 @property 

234 def mobject(self) -> M: 

235 """The mobject the animation changes.""" 

236 return self._mobject 

237 

238 @property 

239 @deprecated( 

240 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

241 category=None, 

242 ) 

243 def model(self) -> M | None: 

244 """The mobject as its updaters have it while the animation plays. 

245 

246 A copy they run on, taken when the animation begins; None if the mobject has no 

247 updaters, or they act on it directly (`suspend_mobject_updating` False). 

248 """ 

249 return self._model 

250 

251 @property 

252 @deprecated( 

253 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

254 category=None, 

255 ) 

256 def hidden(self) -> Sequence[Mobject]: 

257 """The parts of its mobject the animation leaves out of the picture now. 

258 

259 While the animation plays, the scene draws what it holds but these, with their 

260 families; the parts themselves are not changed, so whatever else acts on them 

261 shows once they are drawn again. Most animations hide nothing; 

262 [`ShowIncreasingSubsets`][manimgx.ShowIncreasingSubsets] hides the parts it has 

263 not shown yet. 

264 """ 

265 return () 

266 

267 @property 

268 def run_time(self) -> float: 

269 """How long the animation plays, in seconds; never negative.""" 

270 return self._run_time 

271 

272 @run_time.setter 

273 def run_time(self, value: float) -> None: 

274 if value < 0: 

275 raise ValueError( 

276 f"The run_time of {type(self).__name__} cannot be negative. The given" 

277 f" value was {value}." 

278 ) 

279 self._run_time = value 

280 

281 @property 

282 def _duration(self) -> Fraction: 

283 """The scene's duration; compositions retain their computed rational exactly.""" 

284 return clock.rational(self.run_time) 

285 

286 @deprecated( 

287 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

288 category=None, 

289 ) 

290 def build(self) -> Animation: 

291 """Return what plays for this animation: itself, unless it stands for another. 

292 

293 An [`.animate`][manimgx.Mobject.animate] call of a method that a mobject 

294 overrides with [`override_animate`][manimgx.override_animate] stands for the 

295 animation that method returns. [`Scene.play`][manimgx.Scene.play] calls it 

296 before playing. 

297 

298 Returns: 

299 The animation to play. 

300 """ 

301 return self 

302 

303 # ── lifecycle ───────────────────────────────────────────────────────── 

304 @deprecated( 

305 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

306 category=None, 

307 ) 

308 def begin(self) -> None: 

309 """Start the animation: derive its keyframes from the mobject as it is now, and 

310 take the mobject, changing nothing. 

311 

312 [`Scene.play`][manimgx.Scene.play] calls it when the animation starts; a part of 

313 a composition, when its window opens. The animation acts only when interpolated, 

314 as a function of its progress: a part may begin between two frames, and its 

315 first frame then shows it past progress 0, so set nothing up at progress 0. 

316 Override it to set up an animation of your own, and call the base's. 

317 """ 

318 # an animation is a function of α: one that set itself up at α = 0 

319 # (`if alpha == 0:`) would depend on where a play's frames fall 

320 self.derive(self.mobject) 

321 self.take() 

322 

323 @deprecated( 

324 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

325 category=None, 

326 ) 

327 def take(self) -> None: 

328 """Take the mobject as it is now, changing nothing. 

329 

330 If the mobject has updaters, the animation takes a copy for them to run on (its 

331 model), and the mobject's own updating is suspended while the animation plays 

332 (unless `suspend_mobject_updating` is False). So animations that begin together 

333 all begin from the world as it was before any of them acted. `begin` calls it. 

334 """ 

335 if _updating( 

336 self.mobject 

337 ): # as it is now: its time-based updaters brought here 

338 framing, clock.framing = clock.framing, False # (its per-frame ones ran) 

339 self.mobject.advance(clock.now) 

340 clock.framing = framing 

341 if self.suspend_mobject_updating and _updating(self.mobject): 

342 self._model = self.mobject.copy() 

343 if self.suspend_mobject_updating: 

344 # what it suspends it resumes when it finishes: not what was suspended already 

345 self._held = [ 

346 m for m in self.mobject.get_family() if not m.updating_suspended 

347 ] 

348 self.mobject.suspend_updating() 

349 

350 @deprecated( 

351 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

352 category=None, 

353 ) 

354 def derive(self, source: Mobject) -> None: 

355 """Derive the animation's keyframes from `source` as it is now, and align the 

356 mobject with every one of them. 

357 

358 `begin` calls it on the mobject, and `rederive` on its model. 

359 

360 Args: 

361 source: The mobject, or its model. 

362 """ 

363 own = [ 

364 ( 

365 None 

366 if key is None 

367 else key.copy() 

368 if isinstance(key, Mobject) 

369 else key(source.copy()) 

370 ) 

371 for key in self.keys 

372 ] 

373 self._rest = self._resting(source, own) # before alignment changes them 

374 for frame in own: 

375 if frame is not None: 

376 self.mobject.align_data(frame) 

377 self.frames = [source.copy() if frame is None else frame for frame in own] 

378 

379 def _resting(self, source: Mobject, own: list[Mobject | None]) -> Mobject | None: 

380 """What the mobject is once the animation ends, as `become` makes it: None, for an 

381 animation whose own steps decide it (a [`Transform`][manimgx.Transform] rests as a 

382 keyframe, as it finishes).""" 

383 return None 

384 

385 @deprecated( 

386 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

387 category=None, 

388 ) 

389 def finish(self) -> None: 

390 """End the animation: show progress 1, and resume the updaters it suspended 

391 (those suspended before it began stay so). 

392 

393 [`Scene.play`][manimgx.Scene.play] calls it at the animation's end; a part of a 

394 composition, when its window closes. 

395 """ 

396 self.interpolate(1) 

397 self._release() 

398 

399 def _release(self) -> None: 

400 """Resume the updating it suspended when it began.""" 

401 if self.suspend_mobject_updating: 

402 for member in self._held: 

403 member.resume_updating(recursive=False) 

404 

405 @deprecated( 

406 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

407 category=None, 

408 ) 

409 def clean_up_from_scene(self, scene: Scene) -> None: 

410 """Leave the scene as the animation leaves it: a remover takes its mobject out. 

411 

412 [`Scene.play`][manimgx.Scene.play] calls it after `finish`; a part of a 

413 composition, when its window closes. 

414 

415 Args: 

416 scene: The scene the animation played in. 

417 """ 

418 if self.is_remover(): 

419 scene.remove(*_held(self.mobject)) 

420 

421 def _setup_scene(self, scene: Scene) -> None: 

422 self._scene = scene 

423 if self.is_introducer(): 

424 scene._introduce(_held(self.mobject)) 

425 

426 @deprecated( 

427 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

428 category=None, 

429 ) 

430 def get_all_families_zipped(self) -> Iterable[tuple[Mobject, ...]]: 

431 """Return the parts of the animation's mobjects, matched up. 

432 

433 Returns: 

434 For each part with points of the mobject, a tuple of it and the same part of 

435 each of the animation's keyframes. 

436 """ 

437 families = [ 

438 m.family_members_with_points() for m in (self.mobject, *self.frames) 

439 ] 

440 if any(len(f) != len(families[0]) for f in families[1:]): 

441 # another tween that began with this one restructured the mobject (aligning it 

442 # with its own keyframes): these follow, as alignment only adds parts 

443 for frame in self.frames: 

444 self.mobject.align_data(frame) 

445 families = [ 

446 m.family_members_with_points() for m in (self.mobject, *self.frames) 

447 ] 

448 return zip(*families, strict=True) 

449 

450 @deprecated( 

451 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

452 category=None, 

453 ) 

454 def advance(self, t: Fraction) -> None: 

455 """Bring the mobject's updaters to scene time `t`, on its model. 

456 

457 Then it derives what the animation shows from the model again (`rederive`). The 

458 scene calls it at every instant it computes while the animation plays, before 

459 `interpolate`. At the end of the play, before `finish`, time alone brings the 

460 model there: the per-frame updaters then run once, on the mobject itself. 

461 

462 Args: 

463 t: The scene time, in seconds, as an exact fraction. 

464 """ 

465 if self.model is not None: 

466 self.model.advance(t) 

467 self.rederive() 

468 

469 @deprecated( 

470 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

471 category=None, 

472 ) 

473 def rederive(self) -> None: 

474 """Derive the animation's keyframes again, from the mobject's model as it is now. 

475 

476 The mobject then shows the model, and the animation acts on it: an animation acts 

477 on the mobject as its updaters have it at that frame. `advance` calls it. 

478 """ 

479 model = self.model 

480 if model is None: 

481 return 

482 self.mobject.become(model) 

483 self.derive(model) 

484 

485 # ── the per-frame function ──────────────────────────────────────────── 

486 @deprecated( 

487 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

488 category=None, 

489 ) 

490 def interpolate(self, alpha: float) -> None: 

491 """Show the animation at a progress. 

492 

493 [`Scene.play`][manimgx.Scene.play] calls it at every frame; it hands the work to 

494 `interpolate_mobject`. 

495 

496 Args: 

497 alpha: The animation's progress, from 0 at its start to 1 at its end, not 

498 yet eased by the rate function. 

499 """ 

500 self.interpolate_mobject(alpha) 

501 

502 def interpolate_mobject(self, alpha: float) -> None: 

503 """Set the whole mobject at a progress of the animation. 

504 

505 By default, it sets each part at its own progress (`get_sub_alpha`: staggered by 

506 `lag_ratio`, eased by the rate function) through `interpolate_keyframes`. 

507 Override it to set the whole mobject at once, and apply `self.rate_func(alpha)` 

508 yourself. 

509 

510 Args: 

511 alpha: The animation's progress, from 0 to 1, not yet eased. 

512 """ 

513 families = list(self.get_all_families_zipped()) 

514 for i, (submobject, *keys) in enumerate(families): 

515 self.interpolate_keyframes( 

516 submobject, keys, self.get_sub_alpha(alpha, i, len(families)) 

517 ) 

518 

519 @deprecated( 

520 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

521 category=None, 

522 ) 

523 def interpolate_keyframes( 

524 self, submobject: Mobject, keys: Sequence[Mobject], alpha: float 

525 ) -> None: 

526 """Set one part of the mobject at its progress through its keyframes. 

527 

528 The keyframes are the states of the part the animation passes through, in order. 

529 By default the only one is the part's starting state, and this calls 

530 `interpolate_submobject`. 

531 

532 Args: 

533 submobject: The part of the mobject to set. 

534 keys: The same part of each keyframe. 

535 alpha: The part's progress, staggered and eased. 

536 """ 

537 # with one keyframe (a start state) this is CE's `interpolate_submobject`, the 

538 # hook custom animations override 

539 self.interpolate_submobject(submobject, keys[0], alpha) 

540 

541 @deprecated( 

542 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

543 category=None, 

544 ) 

545 def interpolate_submobject( 

546 self, submobject: Mobject, starting_submobject: Mobject, alpha: float 

547 ) -> None: 

548 """Set one part of the mobject at its own progress; the base does nothing. 

549 

550 The hook to override for an animation that acts part by part: 

551 `interpolate_mobject` calls it for each part with points, at every frame. 

552 

553 Args: 

554 submobject: The part of the mobject to set. 

555 starting_submobject: The same part as it was when the animation began. 

556 alpha: The part's progress, from 0 to 1: staggered by `lag_ratio` and eased 

557 by the rate function. 

558 """ 

559 

560 @deprecated( 

561 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

562 category=None, 

563 ) 

564 def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float: 

565 """Return a part's progress at a progress of the animation. 

566 

567 The parts are staggered by `lag_ratio`: each has a window of the animation's 

568 progress, the first opening at 0 and the last closing at 1, and runs through it 

569 (held at 0 before it, at 1 after it), eased by the rate function (run backward 

570 with `reverse_rate_function`). A part's window closes exactly: its progress there 

571 is 1, and a finished animation is exactly its end. 

572 

573 Args: 

574 alpha: The animation's progress, from 0 to 1. 

575 index: The part's position among the parts, from 0. 

576 num_submobjects: How many parts there are. 

577 

578 Returns: 

579 The part's progress, eased. 

580 """ 

581 lag = self.lag_ratio 

582 opens = index * lag 

583 span = (num_submobjects - 1) * lag + 1 # the stagger's length, in part runs 

584 # the window [opens, opens + 1] of `span`, as fractions: the last one's end is 

585 # span / span, exactly 1 

586 start, end = opens / span, (opens + 1) / span 

587 value = min(max((alpha - start) / (end - start), 0.0), 1.0) 

588 return ( 

589 self.rate_func(1 - value) 

590 if self.reverse_rate_function 

591 else self.rate_func(value) 

592 ) 

593 

594 # ── CE accessors ────────────────────────────────────────────────────── 

595 @deprecated("get_run_time() is run_time: use it", category=None) 

596 def get_run_time(self) -> float: 

597 """How long the animation plays. 

598 

599 Returns: 

600 Its run time, in seconds. 

601 """ 

602 return self.run_time 

603 

604 @deprecated( 

605 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

606 category=None, 

607 ) 

608 def is_remover(self) -> bool: 

609 """Whether the mobject leaves the scene when the animation finishes.""" 

610 return self.remover 

611 

612 @deprecated( 

613 "Manim CE's machinery: ManimGX calls it itself (a custom animation overrides interpolate_mobject)", 

614 category=None, 

615 ) 

616 def is_introducer(self) -> bool: 

617 """Whether the mobject joins the scene when the animation begins.""" 

618 return self.introducer 

619 

620 

621def _lacks(mob: Mobject, members: list[Mobject]) -> bool: 

622 """Do a scene's members lack a mobject with anything to draw or to run?""" 

623 return mob not in members and any( 

624 m.has_points() or m.updaters for m in mob.get_family() 

625 ) 

626 

627 

628_GATHERED: weakref.WeakSet[Mobject] = weakref.WeakSet() 

629 

630 

631def _gathered(*mobjects: Mobject) -> Group: 

632 """A group an animation makes of the mobjects it is given, to act on them as one: no 

633 scene holds it (`_held`).""" 

634 group = Group(*mobjects) 

635 _GATHERED.add(group) 

636 return group 

637 

638 

639def _held(mob: Mobject) -> list[Mobject]: 

640 """What a scene holds of a mobject an animation acts on: the mobject, or the members 

641 of a group the animation gathered them in, each where it is or by itself.""" 

642 return list(mob.submobjects) if mob in _GATHERED else [mob] 

643 

644 

645def _updating(mob: Mobject) -> bool: 

646 return any(m.updaters for m in mob.get_family()) 

647 

648 

649def _flatten(items: Iterable[object]) -> list[object]: 

650 """Flatten nested iterables of animations into one list: a mobject, an animation or 

651 a string is one item, not an iterable to flatten. 

652 

653 Args: 

654 items: The items, nested in lists, tuples or other iterables. 

655 

656 Returns: 

657 The items, in order. 

658 """ 

659 out: list[object] = [] 

660 for item in items: 

661 if ( 

662 isinstance(item, Iterable) 

663 and not isinstance(item, str) 

664 and not hasattr(item, "begin") 

665 and not hasattr(item, "points") 

666 ): 

667 out.extend(_flatten(item)) 

668 else: 

669 out.append(item) 

670 return out 

671 

672 

673def prepare(anim: object) -> Animation: 

674 """Return what plays for an animation: as built, or what its mobject plays instead. 

675 

676 The animation is built first (`build`); a mobject may play another animation in its 

677 place (see `override_animation`). 

678 

679 Args: 

680 anim: The animation; anything else raises a TypeError. 

681 

682 Returns: 

683 The animation to play. 

684 """ 

685 if not isinstance(anim, Animation): 

686 raise TypeError(f"Object {anim} cannot be converted to an animation") 

687 anim = anim.build() 

688 override = ( 

689 anim.mobject.animation_override_for(type(anim)) if anim.use_override else None 

690 ) 

691 if override is None: 

692 return anim 

693 args, kwargs = anim._call 

694 extra = {k: v for k, v in kwargs.items() if k not in ("mobject", "use_override")} 

695 return prepare(override(anim.mobject, *args[1:], **extra)) 

696 

697 

698class Wait(Animation[Mobject]): 

699 """Let the scene's time run on, animating nothing. 

700 

701 The scene's updaters and its mobjects' keep running through it; 

702 [`Scene.wait`][manimgx.Scene.wait] plays one. Played alone, it can end early, at 

703 `stop_condition`, or freeze the frame; in a composition, it only takes up its time. 

704 

705 Args: 

706 run_time: How long it lasts, in seconds. 

707 stop_condition: A function checked at every frame: the wait ends at the first 

708 frame at which it returns True. None: it lasts its whole run time. 

709 frozen_frame: Whether time stands still: one frame is held, and the updaters do 

710 not run, then go on as if no time had passed. It cannot be combined with a 

711 `stop_condition` (a ValueError). 

712 **kwargs: The other [animation options][manimgx.animation.timeline.AnimationOptions] 

713 (all but `run_time`). 

714 

715 Examples: 

716 ```python 

717 import manimgx as m 

718 

719 

720 class WaitExample(m.Scene): 

721 def construct(self) -> None: 

722 finish = m.Line(3 * m.UP, 3 * m.DOWN, color=m.RED).shift(3 * m.RIGHT) 

723 dot = m.Dot(4 * m.LEFT, radius=0.3, color=m.YELLOW) 

724 dot.add_updater(lambda mob, dt: mob.shift(3 * dt * m.RIGHT)) 

725 self.add(finish, dot) 

726 self.play(m.Wait(10, stop_condition=lambda: dot.get_x() >= 3)) 

727 ``` 

728 """ 

729 

730 defaults: ClassVar[AnimationOptions] = {"rate_func": linear} 

731 

732 def __init__( 

733 self, 

734 run_time: float = 1, 

735 stop_condition: Callable[[], bool] | None = None, 

736 frozen_frame: bool | None = None, 

737 **kwargs: Unpack[Untimed], 

738 ) -> None: 

739 if stop_condition and frozen_frame: 

740 raise ValueError("A static Wait animation cannot have a stop condition.") 

741 self.duration = run_time 

742 self.stop_condition = stop_condition 

743 self.is_static_wait = frozen_frame 

744 super().__init__(Mobject(), run_time=run_time, **kwargs) 

745 

746 def begin(self) -> None: ... 

747 def finish(self) -> None: ... 

748 def clean_up_from_scene(self, scene: Scene) -> None: ... 

749 def advance(self, t: Fraction) -> None: ... 

750 def interpolate(self, alpha: float) -> None: ... 

751 

752 

753class Add(Animation[Mobject]): 

754 """Add mobjects to the scene at a moment of a composition. 

755 

756 It adds its mobjects when it begins and, by default, takes no time: in a 

757 [`Succession`][manimgx.Succession], they appear when the animations before it have 

758 finished. With a `run_time`, it holds that long after adding them. 

759 

760 Args: 

761 *mobjects: The mobjects to add; several are added as one group. 

762 

763 Examples: 

764 ```python 

765 import manimgx as m 

766 

767 

768 class AddExample(m.Scene): 

769 def construct(self) -> None: 

770 words = m.VGroup( 

771 *(m.Text(word, font_size=96) for word in ("one", "two", "three")) 

772 ).arrange(m.DOWN, buff=0.5) 

773 box = m.SurroundingRectangle(words, buff=0.5, color=m.BLUE) 

774 self.play( 

775 m.Create(box, run_time=3), 

776 m.Succession(*(m.Add(word, run_time=1) for word in words)), 

777 ) 

778 ``` 

779 """ 

780 

781 defaults: ClassVar[AnimationOptions] = {"run_time": 0.0, "introducer": True} 

782 

783 def __init__(self, *mobjects: Mobject, **kwargs: Unpack[AnimationOptions]) -> None: 

784 super().__init__( 

785 mobjects[0] if len(mobjects) == 1 else _gathered(*mobjects), **kwargs 

786 ) 

787 

788 def begin(self) -> None: ... 

789 def finish(self) -> None: ... 

790 def clean_up_from_scene(self, scene: Scene) -> None: ... 

791 def advance(self, t: Fraction) -> None: ... 

792 def interpolate(self, alpha: float) -> None: ... 

793 

794 

795prepare_animation = prepare 

796 

797 

798"""The same as `prepare`: what plays for an animation.""" 

799 

800 

801DEFAULT_LAGGED_START_LAG_RATIO: float = 0.05 

802 

803 

804_0, _1 = Fraction(0), Fraction(1) 

805 

806 

807type Phase = Literal["run", "begin", "fresh"] 

808 

809 

810_PHASES: tuple[Phase, ...] = ("run", "begin", "fresh") 

811 

812 

813class Window(NamedTuple): 

814 """A part of an animation that acts itself, with where its window opens and closes in 

815 the whole's progress (None: with the whole), and its path (see `windows`).""" 

816 

817 part: Animation 

818 opens: Fraction 

819 closes: Fraction | None 

820 path: tuple[int, ...] 

821 

822 

823type Route = dict[int, "Route | None"] 

824 

825 

826"""The parts of a group an instant concerns: each by its index, with the route into it if it 

827is a group (None: a part that acts itself).""" 

828 

829 

830type Placed = tuple[float, float, bool, Fraction, Fraction] 

831 

832 

833"""A part's window in a time: its ends, whether it closes before its group's end, and its 

834ends exactly.""" 

835 

836 

837def warp(rate_func: RateFunc, alpha: np.ndarray) -> np.ndarray: 

838 """Apply a rate function to several progresses at once. 

839 

840 Args: 

841 rate_func: The rate function. 

842 alpha: The progresses; NaN for a part that has not begun, which stays so. 

843 

844 Returns: 

845 The eased progresses. 

846 """ 

847 # the scalar function itself, so a frame computed alone gets the same bits 

848 return np.fromiter( 

849 (rate_func(float(a)) if a == a else np.nan for a in alpha), float, len(alpha) 

850 ) 

851 

852 

853def stagger(time: np.ndarray, start: float, end: float) -> np.ndarray: 

854 """Return a part's progress through its window at several times of its group. 

855 

856 Args: 

857 time: The group's times, as fractions of its run. 

858 start: Where the part's window opens, as a fraction of the group's run. 

859 end: Where it closes. 

860 

861 Returns: 

862 The part's progress at each time; NaN (not begun) before its window, and held 

863 at 1 after it. 

864 """ 

865 if end <= start: 

866 return np.where(time < start, np.nan, 1.0) 

867 return np.where(time < start, np.nan, np.clip((time - start) / (end - start), 0, 1)) 

868 

869 

870def _through(time: float, start: float, end: float) -> float: 

871 """A begun part's progress through its window at a time of its group: held at 0 

872 before it (the group's time came back), at 1 after it.""" 

873 if end <= start: 

874 return 1.0 if time >= end else 0.0 

875 return min(max((time - start) / (end - start), 0.0), 1.0) 

876 

877 

878def schedule( 

879 anim: Animation, alpha: np.ndarray 

880) -> Iterator[tuple[Animation, np.ndarray, np.ndarray]]: 

881 """Find every animation under `anim` that acts on its mobjects itself. 

882 

883 Args: 

884 anim: The animation, a composition or not. 

885 alpha: Progresses of `anim`. 

886 

887 Yields: 

888 Each such animation, with its progress at each of those of `anim` (NaN before its 

889 window opens), and whether its window has closed there: it has finished, and left 

890 the scene as it leaves it. 

891 """ 

892 for node, progress, closed in walk(anim, alpha): 

893 if not isinstance(node, AnimationGroup): 

894 yield node, progress, closed 

895 

896 

897def walk( 

898 anim: Animation, 

899 time: np.ndarray, 

900 start: Fraction = Fraction(0), 

901 end: Fraction = Fraction(1), 

902 closed: np.ndarray | None = None, 

903) -> Iterator[tuple[Animation, np.ndarray, np.ndarray]]: 

904 """Every animation under `anim`, itself first, as `AnimationGroup.interpolate` plays it. 

905 

906 Args: 

907 anim: The animation. 

908 time: The times it is given. 

909 start: Where its window opens in that time. 

910 end: Where it closes. 

911 closed: Where it has closed; None for nowhere. 

912 

913 Yields: 

914 Each animation, with its progress at each time (NaN before its window), and 

915 whether its window has closed there. 

916 """ 

917 closed = np.zeros(len(time), bool) if closed is None else closed 

918 progress = stagger(time, float(start), float(end)) 

919 yield anim, progress, closed 

920 if isinstance(anim, AnimationGroup): 

921 eased, spans = anim._spans_in(start, end) 

922 own = warp(anim.rate_func, progress) if eased else time 

923 for part, (_, fb, early, a, b) in zip(anim.animations, spans, strict=True): 

924 yield from walk(part, own, a, b, closed | ((own >= fb) & early)) 

925 

926 

927def windows(anim: Animation) -> list[Window]: 

928 """Every animation under `anim` that acts on its mobjects itself, with where, in `anim`'s 

929 progress, its window opens and closes: exact where the groups above it keep linear 

930 time; otherwise the first progress at which a group's eased time reaches the window, as 

931 `interpolate` finds it. A scene computes these instants, so that a part begins and 

932 finishes at its window, whatever the frame rate. 

933 

934 Args: 

935 anim: The animation, a composition or not. 

936 

937 Returns: 

938 Each such animation, where it opens, where it closes (None: with `anim`), and its 

939 path from `anim` (the indices of the parts that hold it). 

940 """ 

941 found: list[Window] = [] 

942 

943 def first(time_of: Callable[[float], float], at: float) -> Fraction: 

944 # the first progress of the whole at which a group's time reaches `at` (its time 

945 # going forward), to the float 

946 if time_of(0.0) >= at: 

947 return _0 

948 if time_of(1.0) < at: 

949 return _1 

950 lo, hi = 0.0, 1.0 

951 while lo < (mid := (lo + hi) / 2) < hi: 

952 if time_of(mid) >= at: 

953 hi = mid 

954 else: 

955 lo = mid 

956 return Fraction(hi) 

957 

958 def visit( 

959 group: AnimationGroup, 

960 time_of: Callable[[float], float] | None, 

961 start: Fraction, 

962 end: Fraction, 

963 opened: Fraction, 

964 closes: Fraction | None, 

965 path: tuple[int, ...], 

966 ) -> None: 

967 # time_of: the group's given time at the whole's progress (None: that progress); 

968 # opened: where the group itself opens (its parts, not before) 

969 if group.rate_func is linear: 

970 spans, inner = group._in(start, end), time_of 

971 else: 

972 spans, given = group._in(_0, _1), time_of or (lambda a: a) 

973 fs, fe, rate = float(start), float(end), group.rate_func 

974 inner = lambda a: rate(_through(given(a), fs, fe)) # noqa: E731 

975 for i, (part, (fa, fb, early, a, b)) in enumerate( 

976 zip(group.animations, spans, strict=True) 

977 ): 

978 opens = max(opened, a if inner is None else first(inner, fa)) 

979 ends = ( 

980 max(opens, b if inner is None else first(inner, fb)) 

981 if early 

982 else closes 

983 ) 

984 if _nested(part): 

985 visit(part, inner, a, b, opens, ends, (*path, i)) 

986 else: 

987 found.append(Window(part, opens, ends, (*path, i))) 

988 

989 if _nested(anim): 

990 visit(anim, None, _0, _1, _0, None, ()) 

991 else: 

992 found.append(Window(anim, _0, None, ())) 

993 return found 

994 

995 

996def route(paths: Iterable[tuple[int, ...]]) -> Route: 

997 """The route to some parts of a group, from their paths (see `windows`).""" 

998 out: Route = {} 

999 for path in paths: 

1000 at = out 

1001 for i in path[:-1]: 

1002 nxt = at.get(i) 

1003 if nxt is None: 

1004 nxt = at[i] = {} 

1005 at = nxt 

1006 at.setdefault(path[-1], None) 

1007 return out 

1008 

1009 

1010def _nested(anim: Animation) -> TypeIs[AnimationGroup]: 

1011 """Is it a group whose parts are laid out in the time given it (as `_at` plays them)?""" 

1012 return ( 

1013 isinstance(anim, AnimationGroup) 

1014 and type(anim).interpolate is AnimationGroup.interpolate 

1015 ) 

1016 

1017 

1018class AnimationGroup(Animation): 

1019 """Play animations together, each in its own window of the group's time. 

1020 

1021 The parts are laid out in time: each begins when the part before it has played 

1022 `lag_ratio` of its run time (all together with the default 0, one after another at 

1023 1, overlapping in between), and plays for its own run time. The group lasts until 

1024 its last part ends, unless given a `run_time`, which stretches or squeezes the whole 

1025 layout to fit. Its rate function (by default `linear`) warps the group's time, and 

1026 each part still eases its own window with its own. 

1027 

1028 A part begins when its window opens, taking its mobjects as they are then (and 

1029 bringing its mobject into the scene, if it introduces it), and finishes when its 

1030 window closes, whatever else is still playing, leaving the scene as it leaves it (a 

1031 remover's mobject leaves it). A part whose window ends with the group's finishes with 

1032 the group, where the group's rate function ends its time. Before its window a part has 

1033 touched nothing; after it, what it did stays done. The group itself is not a mobject 

1034 of the scene: it adds nothing of its own. [`Scene.play`][manimgx.Scene.play] plays 

1035 several animations as such a group. 

1036 

1037 Args: 

1038 *animations: The animations, or iterables of them. 

1039 group: The mobject the group animates; by default, a group of its parts' 

1040 mobjects, but those that parts introduce. 

1041 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]: 

1042 `lag_ratio` lays the parts out, `run_time` fits the whole, `rate_func` warps 

1043 its time, and `remover` makes every part a remover. 

1044 

1045 Examples: 

1046 ```python 

1047 import manimgx as m 

1048 

1049 

1050 class AnimationGroupExample(m.Scene): 

1051 def construct(self) -> None: 

1052 shapes = ( 

1053 m.VGroup( 

1054 m.Square(color=m.BLUE, fill_opacity=0.5), 

1055 m.Circle(color=m.YELLOW, fill_opacity=0.5), 

1056 m.Triangle(color=m.GREEN, fill_opacity=0.5), 

1057 ) 

1058 .scale(1.2) 

1059 .arrange(buff=1) 

1060 ) 

1061 self.play( 

1062 m.AnimationGroup( 

1063 m.Create(shapes[0]), 

1064 m.FadeIn(shapes[1], shift=m.UP), 

1065 m.GrowFromCenter(shapes[2]), 

1066 lag_ratio=0.5, 

1067 ) 

1068 ) 

1069 ``` 

1070 """ 

1071 

1072 defaults: ClassVar[AnimationOptions] = {"rate_func": linear} 

1073 

1074 def __init__( 

1075 self, 

1076 *animations: Animation 

1077 | Iterable[Animation], # of any mobjects (Animation is invariant in its) 

1078 group: Group | VGroup | None = None, 

1079 **kwargs: Unpack[AnimationOptions], 

1080 ): 

1081 self.animations = [prepare(a) for a in _flatten(animations)] 

1082 self.group = group or Group( 

1083 *remove_list_redundancies( 

1084 [a.mobject for a in self.animations if not a.is_introducer()] 

1085 ) 

1086 ) 

1087 super().__init__(self.group, **kwargs) 

1088 self.scene: Scene | None = None 

1089 self.begun: set[int] = set() 

1090 self.done: set[int] = set() 

1091 self._fresh: set[int] = set() # the parts begun at the instant being computed 

1092 # a run time given; None: the layout's own, where its last part ends 

1093 self._given: float | Fraction | None = ( 

1094 animation_defaults(type(self)) | kwargs 

1095 ).get("run_time") 

1096 self._layout: tuple[tuple[object, ...], Fraction, list[Placed]] = ((), _0, []) 

1097 self._playing = False # between `begin` and `finish`: its layout fixed 

1098 self._placed: tuple[tuple[object, ...], list[Placed]] = ((), []) 

1099 

1100 def _laid_out(self) -> tuple[Fraction, list[Placed]]: 

1101 """(where the last part ends, each part's window in the group's own time), from the 

1102 lag and the parts' run times as they are now (a play's options set them after the 

1103 group is made), fixed while it plays.""" 

1104 if self._playing: 

1105 return self._layout[1], self._layout[2] 

1106 lengths = tuple(anim._duration for anim in self.animations) 

1107 key = (self.lag_ratio, *lengths) 

1108 if key != self._layout[0]: 

1109 spans, start = [], _0 

1110 lag = clock.rational(self.lag_ratio) 

1111 for length in lengths: 

1112 spans.append((start, start + length)) 

1113 start += length * lag 

1114 total = max((end for _, end in spans), default=_0) 

1115 windows = [(a / total, b / total) if total else (_0, _0) for a, b in spans] 

1116 placed = [(float(a), float(b), b < 1, a, b) for a, b in windows] 

1117 self._layout = (key, total, placed) 

1118 return self._layout[1], self._layout[2] 

1119 

1120 def _in(self, start: Fraction, end: Fraction) -> list[Placed]: 

1121 """Each part's window in a time in which the group's own is [start, end]: exact (so 

1122 a group laid out in place is its parts, to the bit), with its ends as floats and 

1123 whether it closes before the group's end.""" 

1124 if start == 0 and end == 1: 

1125 return self._laid_out()[1] 

1126 key = (self._layout[0], start, end) 

1127 if key != self._placed[0]: 

1128 span = end - start 

1129 placed = [] 

1130 for *_, a, b in self._laid_out()[1]: 

1131 a, b = start + a * span, start + b * span 

1132 placed.append((float(a), float(b), b < end, a, b)) 

1133 self._placed = (key, placed) 

1134 return self._placed[1] 

1135 

1136 def _spans_in(self, start: Fraction, end: Fraction) -> tuple[bool, list[Placed]]: 

1137 """(whether the group eases its time, its parts' windows in the time they are laid 

1138 out in), where its own window is [start, end] in the time it is given: linear, that 

1139 time; otherwise its own, eased.""" 

1140 if self.rate_func is linear: 

1141 return False, self._in(start, end) 

1142 return True, self._in(_0, _1) 

1143 

1144 @property 

1145 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1146 def max_end_time(self) -> float: 

1147 """Where the last part ends, in seconds: the group's own run time.""" 

1148 return float(self._laid_out()[0]) 

1149 

1150 @property 

1151 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1152 def hidden(self) -> Sequence[Mobject]: 

1153 """What its parts leave out of the picture now (a part hides nothing until it 

1154 begins, nor once it has ended).""" 

1155 return [m for anim in self.animations for m in anim.hidden] 

1156 

1157 @property 

1158 def run_time(self) -> float: 

1159 """How long the group plays, in seconds: the run time it was given, else where its 

1160 last part ends.""" 

1161 return self.max_end_time if self._given is None else float(self._given) 

1162 

1163 @run_time.setter 

1164 def run_time(self, value: float) -> None: 

1165 if value < 0: 

1166 raise ValueError( 

1167 f"The run_time of {type(self).__name__} cannot be negative. The given" 

1168 f" value was {value}." 

1169 ) 

1170 self._given = value 

1171 

1172 @property 

1173 def _duration(self) -> Fraction: 

1174 if type(self).run_time is not AnimationGroup.run_time: 

1175 return clock.rational(self.run_time) 

1176 return ( 

1177 self._laid_out()[0] if self._given is None else clock.rational(self._given) 

1178 ) 

1179 

1180 def _setup_scene(self, scene: Scene) -> None: 

1181 self.scene = scene # each part is set up when it begins 

1182 

1183 def begin(self) -> None: 

1184 if not self.animations: 

1185 raise ValueError( 

1186 f"Trying to play {self} without animations, this is not supported." 

1187 " Please add at least one subanimation." 

1188 ) 

1189 self.begun, self.done, self._fresh = set(), set(), set() 

1190 if self.remover: # every part a remover 

1191 for anim in self.animations: 

1192 anim.remover = True 

1193 self._playing = False 

1194 self._laid_out() 

1195 self._playing = True 

1196 # its parts begin as their windows open, at the instants computed (`_at`) 

1197 

1198 def _begin(self, i: int) -> None: 

1199 self.begun.add(i) 

1200 self._fresh.add(i) # brought to its progress at the instant's "fresh" phase 

1201 if self.scene is not None: 

1202 self.animations[i]._setup_scene(self.scene) 

1203 self.animations[i].begin() 

1204 

1205 def _end(self, i: int) -> None: 

1206 """Part i's window has closed: it finishes, and leaves the scene as it leaves it.""" 

1207 self.done.add(i) 

1208 self.animations[i].finish() 

1209 if self.scene is not None: 

1210 self.animations[i].clean_up_from_scene(self.scene) 

1211 

1212 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1213 def begin_all(self) -> None: 

1214 """Begin every part at once, for a play the scene computes ahead of time. 

1215 

1216 In such a play no part's mobjects change before its window opens, so each part 

1217 takes what it would take then. Beginning changes no look (a tween acts only when 

1218 interpolated; aligning a mobject with its keyframes restructures it invisibly), so 

1219 each mobject shows its state from before the play until its window opens. The 

1220 scene calls it. 

1221 """ 

1222 for i, anim in enumerate(self.animations): 

1223 if i not in self.begun: 

1224 self._begin(i) 

1225 if isinstance(anim, AnimationGroup): 

1226 anim.begin_all() 

1227 

1228 def interpolate(self, alpha: float) -> None: 

1229 for phase in _PHASES: 

1230 self._at(alpha, _0, _1, phase) 

1231 

1232 def _at( 

1233 self, 

1234 given: float, 

1235 start: Fraction, 

1236 end: Fraction, 

1237 phase: Phase, 

1238 only: Route | None = None, 

1239 ) -> None: 

1240 """The group at a time it is given, in which its window is [start, end], in one of 

1241 an instant's phases (in order, each over the whole tree): "run", the parts running 

1242 are brought to it (and those whose windows close, closed); "begin", those whose 

1243 windows open begin, taking the world as it is then (so those beginning together 

1244 all find it as it was); "fresh", those are brought to it. `only`: the parts an 

1245 instant concerns, the others left as they are; None for all.""" 

1246 eased, spans = self._spans_in(start, end) 

1247 time = ( 

1248 self.rate_func(_through(given, float(start), float(end))) 

1249 if eased 

1250 else given 

1251 ) 

1252 for i in range(len(self.animations)) if only is None else sorted(only): 

1253 if i in self.done: 

1254 continue 

1255 anim, (fa, fb, early, a, b) = self.animations[i], spans[i] 

1256 inner = None if only is None else only[i] 

1257 if phase == "begin": 

1258 if i not in self.begun: 

1259 if time < fa: 

1260 continue 

1261 self._begin(i) 

1262 if _nested(anim): 

1263 anim._at(time, a, b, phase, inner) 

1264 elif (i in self._fresh) == (phase == "fresh") and i in self.begun: 

1265 if time >= fb and early: # its window closed before the group's end 

1266 self._end(i) 

1267 elif _nested(anim): 

1268 anim._at(time, a, b, phase, inner) 

1269 else: 

1270 anim.interpolate(_through(time, fa, fb)) 

1271 elif _nested(anim) and i in self.begun: # running: what opens in it 

1272 anim._at(time, a, b, phase, inner) 

1273 if phase == "fresh": 

1274 self._fresh.clear() 

1275 

1276 def _step(self, alpha: float, only: Route | None = None) -> Callable[[], None]: 

1277 """An instant of the group, as a scene computes it: the parts running (of `only`, if 

1278 given) are brought to it now; the returned function begins the parts whose windows 

1279 open, once the world is at that instant.""" 

1280 self._at(alpha, _0, _1, "run", only) 

1281 

1282 def opening() -> None: 

1283 self._at(alpha, _0, _1, "begin", only) 

1284 self._at(alpha, _0, _1, "fresh", only) 

1285 

1286 return opening 

1287 

1288 def finish(self) -> None: 

1289 # the group's time where its rate function ends it: a part whose window it has 

1290 # reached finishes; one it came back from stays where it puts it 

1291 eased, spans = self._spans_in(_0, _1) 

1292 time = self.rate_func(1.0) if eased else 1.0 

1293 self.interpolate(1.0) 

1294 for i, (anim, (_, fb, *_)) in enumerate( 

1295 zip(self.animations, spans, strict=True) 

1296 ): 

1297 if i in self.begun and i not in self.done: 

1298 if time >= fb: 

1299 self._end(i) 

1300 else: 

1301 self.done.add(i) 

1302 anim._release() 

1303 self._playing = False 

1304 

1305 def _release(self) -> None: 

1306 for i in self.begun - self.done: 

1307 self.done.add(i) 

1308 self.animations[i]._release() 

1309 

1310 def advance(self, t: Fraction, only: Route | None = None) -> None: 

1311 for i in self.begun - self.done if only is None else only.keys() - self.done: 

1312 anim, inner = self.animations[i], None if only is None else only[i] 

1313 if isinstance(anim, AnimationGroup): 

1314 anim.advance(t, inner) 

1315 elif i in self.begun: 

1316 anim.advance(t) 

1317 

1318 def clean_up_from_scene(self, scene: Scene) -> None: 

1319 pass # its parts left the scene as their windows closed 

1320 

1321 

1322class Succession(AnimationGroup): 

1323 """Play animations one after another. 

1324 

1325 An [`AnimationGroup`][manimgx.AnimationGroup] whose `lag_ratio` is 1: each part 

1326 begins when the one before it ends, from the state it left. 

1327 

1328 Args: 

1329 *animations: The animations, in order, or iterables of them. 

1330 group: The mobject the group animates; by default, a group of its parts' 

1331 mobjects, but those that parts introduce. 

1332 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for 

1333 the whole. 

1334 

1335 Examples: 

1336 ```python 

1337 import manimgx as m 

1338 

1339 

1340 class SuccessionExample(m.Scene): 

1341 def construct(self) -> None: 

1342 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5) 

1343 square.shift(3 * m.LEFT) 

1344 self.play( 

1345 m.Succession( 

1346 m.Create(square), 

1347 square.animate.shift(6 * m.RIGHT), 

1348 m.Rotate(square, m.PI / 4), 

1349 square.animate.set_color(m.YELLOW), 

1350 ) 

1351 ) 

1352 ``` 

1353 """ 

1354 

1355 defaults: ClassVar[AnimationOptions] = {"lag_ratio": 1.0} 

1356 

1357 

1358class LaggedStart(AnimationGroup): 

1359 """Play animations one shortly after another, overlapping. 

1360 

1361 An [`AnimationGroup`][manimgx.AnimationGroup] whose `lag_ratio` is small (0.05 by 

1362 default): each part begins when the one before it has played that fraction of its 

1363 run time. 

1364 

1365 Args: 

1366 *animations: The animations, in order, or iterables of them. 

1367 group: The mobject the group animates; by default, a group of its parts' 

1368 mobjects, but those that parts introduce. 

1369 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for 

1370 the whole. 

1371 

1372 Examples: 

1373 ```python 

1374 import manimgx as m 

1375 

1376 

1377 class LaggedStartExample(m.Scene): 

1378 def construct(self) -> None: 

1379 dots = m.VGroup(*(m.Dot(radius=0.25, color=m.YELLOW) for _ in range(8))) 

1380 dots.arrange(buff=0.8).shift(2 * m.UP) 

1381 self.add(dots) 

1382 self.play( 

1383 m.LaggedStart( 

1384 *(dot.animate.shift(4 * m.DOWN) for dot in dots), lag_ratio=0.2 

1385 ) 

1386 ) 

1387 ``` 

1388 """ 

1389 

1390 defaults: ClassVar[AnimationOptions] = {"lag_ratio": DEFAULT_LAGGED_START_LAG_RATIO} 

1391 

1392 

1393class LaggedStartMap(LaggedStart): 

1394 """Play an animation on each submobject of a mobject, one shortly after another. 

1395 

1396 Each submobject's animation is `animation_class(*arg_creator(submobject), **kwargs)` 

1397 (by default, `animation_class(submobject, **kwargs)`), and they play as a 

1398 [`LaggedStart`][manimgx.LaggedStart]. `run_time` (2 seconds by default) and 

1399 `lag_ratio` time the whole; every other option goes to each animation. 

1400 

1401 Args: 

1402 animation_class: The animation to play on each submobject: a class, or any 

1403 function returning an animation. 

1404 mobject: The mobject whose submobjects are animated. 

1405 arg_creator: A function from a submobject to the animation's positional 

1406 arguments; None for the submobject alone. 

1407 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]: 

1408 `run_time` and `lag_ratio` for the whole, the others for each animation. 

1409 

1410 Examples: 

1411 ```python 

1412 import manimgx as m 

1413 

1414 

1415 class LaggedStartMapExample(m.Scene): 

1416 def construct(self) -> None: 

1417 dots = m.VGroup(*(m.Dot(radius=0.2) for _ in range(35))) 

1418 dots.arrange_in_grid(rows=5, cols=7, buff=0.6) 

1419 self.play(m.LaggedStartMap(m.GrowFromCenter, dots, lag_ratio=0.1)) 

1420 ``` 

1421 """ 

1422 

1423 defaults: ClassVar[AnimationOptions] = {"run_time": 2.0} 

1424 

1425 def __init__( 

1426 self, 

1427 animation_class: Callable[ 

1428 ..., Animation 

1429 ], # given each part's arguments (`arg_creator`) 

1430 mobject: Mobject, 

1431 arg_creator: Callable[[Mobject], Iterable[object]] | None = None, 

1432 **kwargs: Unpack[AnimationOptions], 

1433 ): 

1434 timing: AnimationOptions = {} 

1435 if "run_time" in kwargs: 

1436 timing["run_time"] = kwargs.pop("run_time") 

1437 if "lag_ratio" in kwargs: 

1438 timing["lag_ratio"] = kwargs.pop("lag_ratio") 

1439 arguments = arg_creator or (lambda part: (part,)) 

1440 super().__init__( 

1441 *(animation_class(*arguments(part), **kwargs) for part in mobject), **timing 

1442 ) 

1443 

1444 

1445class ChangeSpeed(AnimationGroup): 

1446 """Play an animation faster or slower along the way: at speeds that change as it 

1447 plays. 

1448 

1449 `speedinfo` gives speeds at points of the animation's progress: `{0.5: 2}` plays it 

1450 at its own speed at the start, speeding up to twice as fast at its middle, and twice 

1451 as fast from there on. Between two points the speed changes steadily (at a constant 

1452 acceleration, in the scene's time), so the stretch from progress `a` to `b`, at 

1453 speeds `v` and `w`, takes `(b - a) · 2 / (v + w)` of the animation's run time; the 

1454 play lasts as long as its stretches take. Unless given, the speed at the start is 1 

1455 and the speed at the end the last point's. 

1456 

1457 With `affects_speed_updaters`, the updaters added with 

1458 [`ChangeSpeed.add_updater`][manimgx.ChangeSpeed.add_updater] run at the same speeds 

1459 while it plays, so that whatever they move keeps pace with the animation. 

1460 

1461 The speeds change only the animation's timing: it keeps its own rate function (and 

1462 its parts' stagger), so at a speed of 1 throughout it is the animation itself. 

1463 

1464 Args: 

1465 anim: The animation to play. 

1466 speedinfo: Speeds at points of the animation's progress, from 0 to 1: a speed of 

1467 2 plays it twice as fast, 0.5 half as fast. 

1468 affects_speed_updaters: Whether the updaters added with 

1469 `ChangeSpeed.add_updater` follow the speeds while it plays. 

1470 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for 

1471 the whole: its `rate_func` (by default `linear`) eases the play's time before 

1472 the speeds warp it. Its run time is what the speeds make it: a `run_time` 

1473 given here is ignored. 

1474 

1475 Examples: 

1476 ```python 

1477 import manimgx as m 

1478 

1479 

1480 class ChangeSpeedExample(m.Scene): 

1481 def construct(self) -> None: 

1482 steady = m.Dot(5 * m.LEFT + m.UP, radius=0.25, color=m.BLUE) 

1483 slowed = m.Dot(5 * m.LEFT + m.DOWN, radius=0.25, color=m.YELLOW) 

1484 self.add(steady, slowed) 

1485 self.play( 

1486 steady.animate(run_time=2, rate_func=m.linear).set_x(5), 

1487 m.ChangeSpeed( 

1488 slowed.animate(run_time=2, rate_func=m.linear).set_x(5), 

1489 speedinfo={0.3: 1, 0.4: 0.2, 0.6: 0.2, 0.7: 1}, 

1490 ), 

1491 ) 

1492 ``` 

1493 """ 

1494 

1495 def __init__( 

1496 self, 

1497 anim: Animation, 

1498 speedinfo: dict[float, float], 

1499 affects_speed_updaters: bool = True, 

1500 **kwargs: Unpack[AnimationOptions], 

1501 ) -> None: 

1502 self.anim = prepare(anim) 

1503 speeds = dict(sorted(({0: 1} | speedinfo).items())) 

1504 speeds.setdefault(1, speeds[max(speeds)]) 

1505 self.speedinfo = speeds 

1506 self.affects_speed_updaters = affects_speed_updaters 

1507 # each stretch: (from, to, speed at from, speed at to, where it starts in real time) 

1508 self._stretches: list[tuple[float, float, float, float, float]] = [] 

1509 total = _0 # real time, per second of the wrapped animation 

1510 for (a, v), (b, w) in pairwise(speeds.items()): 

1511 self._stretches.append((a, b, v, w, float(total))) 

1512 total += ( 

1513 2 

1514 * (clock.rational(b) - clock.rational(a)) 

1515 / (clock.rational(v) + clock.rational(w)) 

1516 ) 

1517 self._total = float(total) 

1518 self._before = kwargs.pop("rate_func", linear) 

1519 kwargs["rate_func"] = self._rate 

1520 duration = total * self.anim._duration 

1521 kwargs["run_time"] = float(duration) 

1522 super().__init__(self.anim, **kwargs) 

1523 self._given = duration 

1524 

1525 def _rate(self, t: float) -> float: 

1526 """Its rate function: the wrapped animation's progress at the rate function given 

1527 (a method, so that a copy reads its own stretches).""" 

1528 return self.progress(self._before(t)) 

1529 

1530 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1531 def progress(self, t: float) -> float: 

1532 """The animation's progress at a time of the play. 

1533 

1534 Within each stretch between two points of `speedinfo`, it is the distance 

1535 covered by a speed that goes steadily from one point's to the other's. 

1536 

1537 Args: 

1538 t: The play's time, as a fraction of its run time, eased by its rate 

1539 function. 

1540 

1541 Returns: 

1542 The animation's progress, from 0 to 1. 

1543 """ 

1544 if t >= 1: 

1545 return 1.0 

1546 # at a node, the later stretch (CE's piecewise lets the last condition win) 

1547 for a, b, v, w, start in reversed(self._stretches): 

1548 if start / self._total <= t: 

1549 x = (self._total * t - start) / (b - a) 

1550 d = ((w**2 - v**2) * (x * x) / 4 + v * x) * (b - a) 

1551 return min(max(d + a, a), b) # never past its stretch's ends 

1552 return 0.0 

1553 

1554 @classmethod 

1555 def add_updater( 

1556 cls, 

1557 mobject: Mobject, 

1558 update_function: Updater[Mobject], 

1559 index: int | None = None, 

1560 call_updater: bool = False, 

1561 ) -> None: 

1562 """Add an updater to a mobject whose time follows the speed of any `ChangeSpeed` 

1563 playing. 

1564 

1565 A time-based updater added this way is handed, as `dt`, the time of a clock that 

1566 runs with the scene's, except while a `ChangeSpeed` with 

1567 `affects_speed_updaters` plays: then it runs at that `ChangeSpeed`'s speeds (its 

1568 `speedinfo`, whatever its rate function eases), and while several play at once, 

1569 at the speeds of the one that began last. The clock never runs backward. It 

1570 keeps its kind: a [flow][manimgx.mobject.flow] stays a flow, and any other 

1571 time-based updater still steps on the simulation clock. A per-frame updater has 

1572 no time, and is added as it is. 

1573 

1574 Args: 

1575 mobject: The mobject to add it to. 

1576 update_function: The updater: a function of the mobject, or of the mobject 

1577 and `dt` (see [`add_updater`][manimgx.Mobject.add_updater]). 

1578 index: Where it goes among the mobject's updaters, which run in order; None 

1579 for last. 

1580 call_updater: Whether to run it once right away; a time-based one is handed 

1581 a `dt` of 0. 

1582 """ 

1583 if not _per_frame(update_function): 

1584 on_clock = _OnClock(update_function, clock.speed) 

1585 update_function = on_clock if simulated(update_function) else flow(on_clock) 

1586 mobject.add_updater(update_function, index=index, call_updater=call_updater) 

1587 

1588 def begin(self) -> None: 

1589 # from the instant it begins (a part of a composition begins inside the play), 

1590 # at its speeds: the speed profile over the play's own time 

1591 if self.affects_speed_updaters: 

1592 clock.speed.warp( 

1593 float(clock.now), self.run_time, self.anim.run_time, self.progress 

1594 ) 

1595 super().begin() 

1596 

1597 

1598class _OnClock: 

1599 """A time-based updater that lives on another clock than scene time.""" 

1600 

1601 def __init__( 

1602 self, function: Callable[[Mobject, float], object], on: clock.Clock 

1603 ) -> None: 

1604 self.function = function 

1605 self.clock = on 

1606 

1607 def __call__(self, mob: Mobject, dt: float) -> object: 

1608 return self.function(mob, dt)