A community-maintained Python framework for creating mathematical animations.
Added :func:`~.override_animation` decorator (#1422)
Anton Ballmaierda4f4e026d49
diff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex ce6f03888..3b683762d 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -1,11 +1,11 @@"""Animate mobjects."""-__all__ = ["Animation", "Wait"]+__all__ = ["Animation", "Wait", "override_animation"]from copy import deepcopy-from typing import TYPE_CHECKING, Callable, Iterable, Optional, Tuple, Union+from typing import TYPE_CHECKING, Callable, Iterable, Optional, Tuple, Type, Unionif TYPE_CHECKING:from manim.scene.scene import Scene@@ -22,9 +22,30 @@ DEFAULT_ANIMATION_LAG_RATIO: float = 0.0class Animation:+ def __new__(+ cls,+ mobject: Optional[Mobject] = None,+ *args,+ use_override: bool = True,+ **kwargs,+ ):+ if isinstance(mobject, Mobject) and use_override:+ func = mobject.animation_override_for(cls)+ if func is not None:+ anim = func(mobject, *args, **kwargs)+ logger.debug(+ (+ f"The {cls.__name__} animation has been is overridden for "+ f"{type(mobject).__name__} mobjects. use_override = False can "+ f" be used as keyword argument to prevent animation overriding."+ )+ )+ return anim+ return super().__new__(cls)+def __init__(self,- mobject: Union[Mobject, None],+ mobject: Optional[Mobject],# If lag_ratio is 0, the animation is applied to all submobjects# at the same time# If 1, it is applied to each successively.@@ -263,3 +284,49 @@ class Wait(Animation):def interpolate(self, alpha: float) -> None:pass+++def override_animation(+ animation_class: Type["Animation"],+) -> Callable[[Callable], Callable]:+ """Decorator used to mark methods as overrides for specific :class:`~.Animation` types.++ Should only be used to decorate methods of classes derived from :class:`~.Mobject`.+ ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined+ them. They don't override subclasses of the ``Animation`` they override.++ See Also+ --------+ :meth:`~.Mobject.add_animation_override`++ Parameters+ ----------+ animation_class+ The animation to be overridden.++ Returns+ -------+ Callable[[Callable], Callable]+ The actual decorator. This marks the method as overriding an animation.++ Examples+ --------++ .. manim:: OverrideAnimationExample++ class MySquare(Square):+ @override_animation(FadeIn)+ def _fade_in_override(self, **kwargs):+ return Create(self, **kwargs)++ class OverrideAnimationExample(Scene):+ def construct(self):+ self.play(FadeIn(MySquare()))++ """++ def decorator(func):+ func._override_animation = animation_class+ return func++ return decoratordiff --git a/manim/mobject/logo.py b/manim/mobject/logo.pyindex 8c3c7b4ef..4519ae60a 100644--- a/manim/mobject/logo.py+++ b/manim/mobject/logo.py@@ -2,7 +2,9 @@__all__ = ["ManimBanner"]+from ..animation.animation import override_animationfrom ..animation.composition import AnimationGroup, Succession+from ..animation.creation import Createfrom ..animation.fading import FadeInfrom ..animation.update import UpdateFromAlphaFuncfrom ..constants import DOWN, LEFT, ORIGIN, RIGHT, TAU, UP@@ -107,6 +109,7 @@ class ManimBanner(VGroup):self.anim.scale(scale_factor, **kwargs)return super().scale(scale_factor, **kwargs)+ @override_animation(Create)def create(self, run_time: float = 2) -> AnimationGroup:"""The creation animation for Manim's logo.diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.pyindex 138180072..923da5ea4 100644--- a/manim/mobject/mobject.py+++ b/manim/mobject/mobject.py@@ -14,7 +14,19 @@ import warningsfrom functools import reducefrom math import ceilfrom pathlib import Path-from typing import Callable, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union+from typing import (+ TYPE_CHECKING,+ Callable,+ Dict,+ Iterable,+ List,+ Optional,+ Sequence,+ Tuple,+ Type,+ TypeVar,+ Union,+)import numpy as npfrom colour import Color@@ -30,6 +42,7 @@ from ..utils.color import (color_gradient,interpolate_color,)+from ..utils.exceptions import MultiAnimationOverrideExceptionfrom ..utils.iterables import list_update, remove_list_redundanciesfrom ..utils.paths import straight_pathfrom ..utils.simple_functions import get_parameters@@ -45,6 +58,9 @@ from ..utils.space_ops import (Updater = Union[Callable[["Mobject"], None], Callable[["Mobject", float], None]]T = TypeVar("T", bound="Mobject")+if TYPE_CHECKING:+ from ..animation.animation import Animation+class Mobject(Container):"""Mathematical Object: base class for objects that can be displayed on screen.@@ -66,6 +82,17 @@ class Mobject(Container):"""+ animation_overrides = {}++ @classmethod+ def __init_subclass__(cls, **kwargs):+ super().__init_subclass__(**kwargs)++ cls.animation_overrides: Dict[+ Type["Animation"], Callable[["Mobject"], "Animation"]+ ] = {}+ cls._add_intrinsic_animation_overrides()+def __init__(self, color=WHITE, name=None, dim=3, target=None, z_index=0, **kwargs):self.color = Color(color)self.name = self.__class__.__name__ if name is None else name@@ -96,6 +123,78 @@ class Mobject(Container):Container.__init__(self, **kwargs)+ @classmethod+ def animation_override_for(+ cls, animation_class: Type["Animation"]+ ) -> "Optional[Callable[[Mobject, ...], Animation]]":+ """Returns the function defining a specific animation override for this class.++ Parameters+ ----------+ animation_class+ The animation class for which the override function should be returned.++ Returns+ -------+ Optional[Callable[[Mobject, ...], Animation]]+ The function returning the override animation or ``None`` if no such animation+ override is defined.+ """+ if animation_class in cls.animation_overrides:+ return cls.animation_overrides[animation_class]++ return None++ @classmethod+ def _add_intrinsic_animation_overrides(cls):+ """Initializes animation overrides marked with the :func:`~.override_animation`+ decorator.+ """+ for method_name in dir(cls):+ # Ignore dunder methods+ if method_name.startswith("__"):+ continue++ method = getattr(cls, method_name)+ if hasattr(method, "_override_animation"):+ animation_class = method._override_animation+ cls.add_animation_override(animation_class, method)++ @classmethod+ def add_animation_override(+ cls,+ animation_class: Type["Animation"],+ override_func: "Callable[[Mobject, ...], Animation]",+ ):+ """Add an animation override.++ This does not apply to subclasses.++ Parameters+ ----------+ animation_class+ The animation type to be overridden+ override_func+ The function returning an aniamtion replacing the default animation. It gets+ passed the parameters given to the animnation constructor.++ Raises+ ------+ MultiAnimationOverrideException+ If the overridden animation was already overridden.+ """+ if animation_class not in cls.animation_overrides:+ cls.animation_overrides[animation_class] = override_func+ else:+ raise MultiAnimationOverrideException(+ (+ f"The animation {animation_class.__name__} for "+ f"{cls.__name__} is overridden by more than one method: "+ f"{cls.animation_overrides[animation_class].__qualname__} and "+ f"{override_func.__qualname__}."+ )+ )+def init_gl_data(self):passdiff --git a/manim/utils/exceptions.py b/manim/utils/exceptions.pyindex d99cb9f67..1e98f5ccd 100644--- a/manim/utils/exceptions.py+++ b/manim/utils/exceptions.py@@ -4,3 +4,7 @@ class EndSceneEarlyException(Exception):class RerunSceneException(Exception):pass+++class MultiAnimationOverrideException(Exception):+ passdiff --git a/tests/test_override_animation.py b/tests/test_override_animation.pynew file mode 100644index 000000000..92d3c3bc3--- /dev/null+++ b/tests/test_override_animation.py@@ -0,0 +1,93 @@+import pytest++from manim import Animation, Mobject, override_animation+from manim.utils.exceptions import MultiAnimationOverrideException+++class AnimationA1(Animation):+ pass+++class AnimationA2(Animation):+ pass+++class AnimationA3(Animation):+ pass+++class AnimationB1(AnimationA1):+ pass+++class AnimationC1(AnimationB1):+ pass+++class AnimationX(Animation):+ pass+++class MobjectA(Mobject):+ @override_animation(AnimationA1)+ def anim_a1(self):+ return AnimationA2(self)++ @override_animation(AnimationX)+ def anim_x(self, *args, **kwargs):+ return args, kwargs+++class MobjectB(MobjectA):+ pass+++class MobjectC(MobjectB):+ @override_animation(AnimationA1)+ def anim_a1(self):+ return AnimationA3(self)+++class MobjectX(Mobject):+ @override_animation(AnimationB1)+ def animation(self):+ return "Overridden"+++def test_mobject_inheritance():+ mob = Mobject()+ a = MobjectA()+ b = MobjectB()+ c = MobjectC()++ assert type(AnimationA1(mob)) is AnimationA1+ assert type(AnimationA1(a)) is AnimationA2+ assert type(AnimationA1(b)) is AnimationA2+ assert type(AnimationA1(c)) is AnimationA3+++def test_arguments():+ a = MobjectA()+ args = (1, "two", {"three": 3}, ["f", "o", "u", "r"])+ kwargs = {"test": "manim", "keyword": 42, "arguments": []}+ animA = AnimationX(a, *args, **kwargs)++ assert animA[0] == args+ assert animA[1] == kwargs+++def test_multi_animation_override_exception():+ with pytest.raises(MultiAnimationOverrideException):++ class MobjectB2(MobjectA):+ @override_animation(AnimationA1)+ def anim_a1_different_name(self):+ pass+++def test_animation_inheritance():+ x = MobjectX()++ assert type(AnimationA1(x)) is AnimationA1+ assert AnimationB1(x) == "Overridden"+ assert type(AnimationC1(x)) is AnimationC1