text
stringlengths 2.1k
15.6k
|
|---|
has played. Defaults to 1.0, meaning that the next animation will begin when 100% of the current animation has played. This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time. Examples -------- .. manim:: SuccessionExample class SuccessionExample(Scene): def construct(self): dot1 = Dot(point=LEFT * 2 + UP * 2, radius=0.16, color=BLUE) dot2 = Dot(point=LEFT * 2 + DOWN * 2, radius=0.16, color=MAROON) dot3 = Dot(point=RIGHT * 2 + DOWN * 2, radius=0.16, color=GREEN) dot4 = Dot(point=RIGHT * 2 + UP * 2, radius=0.16, color=YELLOW) self.add(dot1, dot2, dot3, dot4) self.play(Succession( dot1.animate.move_to(dot2), dot2.animate.move_to(dot3), dot3.animate.move_to(dot4), dot4.animate.move_to(dot1) )) """ def __init__(self, *animations: Animation, lag_ratio: float = 1, **kwargs: Any): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) def begin(self) -> None: if not self.animations: raise ValueError( f"Trying to play {self} without animations, this is not supported. " "Please add at least one subanimation." ) self.update_active_animation(0) def finish(self) -> None: while self.active_animation is not None: self.next_animation() def update_mobjects(self, dt: float) -> None: if self.active_animation: self.active_animation.update_mobjects(dt) def _setup_scene(self, scene: Scene | None) -> None: if scene is None: return if self.is_introducer(): for anim in self.animations: if not anim.is_introducer() and anim.mobject is not None: scene.add(anim.mobject) self.scene = scene def update_active_animation(self, index: int) -> None: self.active_index = index if index >= len(self.animations): self.active_animation: Animation | None = None self.active_start_time: float | None = None self.active_end_time: float | None = None else: self.active_animation = self.animations[index] self.active_animation._setup_scene(self.scene) self.active_animation.begin() self.active_start_time = self.anims_with_timings[index]["start"] self.active_end_time = self.anims_with_timings[index]["end"] def next_animation(self) -> None: """Proceeds to the next animation. This method is called right when the active animation finishes. """ if self.active_animation is not None: self.active_animation.finish() self.update_active_animation(self.active_index + 1) def interpolate(self, alpha: float) -> None: current_time = self.rate_func(alpha) * self.max_end_time while self.active_end_time is not None and current_time >= self.active_end_time: self.next_animation() if self.active_animation is not None and self.active_start_time is not None: elapsed = current_time - self.active_start_time active_run_time = self.active_animation.run_time subalpha = elapsed / active_run_time if active_run_time != 0.0 else 1.0 self.active_animation.interpolate(subalpha) class LaggedStart(AnimationGroup): """Adjusts the timing of a series of :class:`~.Animation` according to ``lag_ratio``. Parameters ---------- animations Sequence of :class:`~.Animation` objects to be played. lag_ratio Defines the delay after which the animation is applied to submobjects. A lag_ratio of ``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played. Defaults to 0.05, meaning that the next animation will begin when 5% of the current animation has played. This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time. Examples -------- .. manim:: LaggedStartExample class LaggedStartExample(Scene): def construct(self): title = Text("lag_ratio = 0.25").to_edge(UP) dot1 = Dot(point=LEFT * 2 + UP, radius=0.16) dot2 = Dot(point=LEFT * 2, radius=0.16) dot3 = Dot(point=LEFT * 2 + DOWN, radius=0.16) line_25 = DashedLine( start=LEFT + UP * 2, end=LEFT + DOWN * 2, color=RED ) label = Text("25%", font_size=24).next_to(line_25, UP) self.add(title, dot1, dot2, dot3, line_25, label) self.play(LaggedStart( dot1.animate.shift(RIGHT * 4), dot2.animate.shift(RIGHT * 4), dot3.animate.shift(RIGHT * 4), lag_ratio=0.25, run_time=4 ))
|
* 2, radius=0.16) dot3 = Dot(point=LEFT * 2 + DOWN, radius=0.16) line_25 = DashedLine( start=LEFT + UP * 2, end=LEFT + DOWN * 2, color=RED ) label = Text("25%", font_size=24).next_to(line_25, UP) self.add(title, dot1, dot2, dot3, line_25, label) self.play(LaggedStart( dot1.animate.shift(RIGHT * 4), dot2.animate.shift(RIGHT * 4), dot3.animate.shift(RIGHT * 4), lag_ratio=0.25, run_time=4 )) """ def __init__( self, *animations: Animation, lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO, **kwargs: Any, ): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) class LaggedStartMap(LaggedStart): """Plays a series of :class:`~.Animation` while mapping a function to submobjects. Parameters ---------- AnimationClass :class:`~.Animation` to apply to mobject. mobject :class:`~.Mobject` whose submobjects the animation, and optionally the function, are to be applied. arg_creator Function which will be applied to :class:`~.Mobject`. run_time The duration of the animation in seconds. Examples -------- .. manim:: LaggedStartMapExample class LaggedStartMapExample(Scene): def construct(self): title = Tex("LaggedStartMap").to_edge(UP, buff=LARGE_BUFF) dots = VGroup( *[Dot(radius=0.16) for _ in range(35)] ).arrange_in_grid(rows=5, cols=7, buff=MED_LARGE_BUFF) self.add(dots, title) # Animate yellow ripple effect for mob in dots, title: self.play(LaggedStartMap( ApplyMethod, mob, lambda m : (m.set_color, YELLOW), lag_ratio = 0.1, rate_func = there_and_back, run_time = 2 )) """ def __init__( self, animation_class: type[Animation], mobject: Mobject, arg_creator: Callable[[Mobject], Iterable[Any]] | None = None, run_time: float = 2, **kwargs: Any, ): if arg_creator is None: def identity(mob: Mobject) -> Mobject: return mob arg_creator = identity args_list = [arg_creator(submob) for submob in mobject] anim_kwargs = dict(kwargs) if "lag_ratio" in anim_kwargs: anim_kwargs.pop("lag_ratio") animations = [animation_class(*args, **anim_kwargs) for args in args_list] super().__init__(*animations, run_time=run_time, **kwargs) ================================================ FILE: manim/animation/creation.py ================================================ r"""Animate the display or removal of a mobject from a scene. .. manim:: CreationModule :hide_source: from manim import ManimBanner class CreationModule(Scene): def construct(self): s1 = Square() s2 = Square() s3 = Square() s4 = Square() VGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.9).shift(UP) s5 = Square() s6 = Square() s7 = Square() VGroup(s5, s6, s7).set_x(0).arrange(buff=2.6).shift(2 * DOWN) t1 = Text("Write", font_size=24).next_to(s1, UP) t2 = Text("AddTextLetterByLetter", font_size=24).next_to(s2, UP) t3 = Text("Create", font_size=24).next_to(s3, UP) t4 = Text("Uncreate", font_size=24).next_to(s4, UP) t5 = Text("DrawBorderThenFill", font_size=24).next_to(s5, UP) t6 = Text("ShowIncreasingSubsets", font_size=22).next_to(s6, UP) t7 = Text("ShowSubmobjectsOneByOne", font_size=22).next_to(s7, UP) self.add(s1, s2, s3, s4, s5, s6, s7, t1, t2, t3, t4, t5, t6, t7) texts = [Text("manim", font_size=29), Text("manim", font_size=29)] texts[0].move_to(s1.get_center()) texts[1].move_to(s2.get_center()) self.add(*texts) objs = [ManimBanner().scale(0.25) for _ in range(5)] objs[0].move_to(s3.get_center()) objs[1].move_to(s4.get_center()) objs[2].move_to(s5.get_center()) objs[3].move_to(s6.get_center()) objs[4].move_to(s7.get_center()) self.add(*objs) self.play( # text creation Write(texts[0]), AddTextLetterByLetter(texts[1]), # mobject creation Create(objs[0]), Uncreate(objs[1]), DrawBorderThenFill(objs[2]), ShowIncreasingSubsets(objs[3]), ShowSubmobjectsOneByOne(objs[4]), run_time=3, ) self.wait() """ from __future__ import annotations __all__ = [ "Create", "Uncreate", "DrawBorderThenFill", "Write", "Unwrite", "ShowPartial", "ShowIncreasingSubsets", "SpiralIn", "AddTextLetterByLetter", "RemoveTextLetterByLetter", "ShowSubmobjectsOneByOne", "AddTextWordByWord", "TypeWithCursor", "UntypeWithCursor", ] import itertools as it from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from manim.mobject.text.text_mobject import Text from manim.scene.scene import Scene from manim.constants import RIGHT, TAU from manim.mobject.opengl.opengl_surface import OpenGLSurface from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject from manim.utils.color import ManimColor from .. import config from ..animation.animation import Animation from ..animation.composition import Succession from ..mobject.mobject import Group, Mobject from ..mobject.types.vectorized_mobject import VMobject from ..utils.bezier import integer_interpolate from ..utils.rate_functions import double_smooth, linear class ShowPartial(Animation): """Abstract class for Animations that show the VMobject partially. Raises ------ :class:`TypeError` If ``mobject`` is not an instance of :class:`~.VMobject`. See Also
|
from ..animation.animation import Animation from ..animation.composition import Succession from ..mobject.mobject import Group, Mobject from ..mobject.types.vectorized_mobject import VMobject from ..utils.bezier import integer_interpolate from ..utils.rate_functions import double_smooth, linear class ShowPartial(Animation): """Abstract class for Animations that show the VMobject partially. Raises ------ :class:`TypeError` If ``mobject`` is not an instance of :class:`~.VMobject`. See Also -------- :class:`Create`, :class:`~.ShowPassingFlash` """ def __init__( self, mobject: VMobject | OpenGLVMobject | OpenGLSurface | None, **kwargs, ): pointwise = getattr(mobject, "pointwise_become_partial", None) if not callable(pointwise): raise TypeError(f"{self.__class__.__name__} only works for VMobjects.") super().__init__(mobject, **kwargs) def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> None: submobject.pointwise_become_partial( starting_submobject, *self._get_bounds(alpha) ) def _get_bounds(self, alpha: float) -> tuple[float, float]: raise NotImplementedError("Please use Create or ShowPassingFlash") class Create(ShowPartial): """Incrementally show a VMobject. Parameters ---------- mobject The VMobject to animate. Raises ------ :class:`TypeError` If ``mobject`` is not an instance of :class:`~.VMobject`. Examples -------- .. manim:: CreateScene class CreateScene(Scene): def construct(self): self.play(Create(Square())) See Also -------- :class:`~.ShowPassingFlash` """ def __init__( self, mobject: VMobject | OpenGLVMobject | OpenGLSurface, lag_ratio: float = 1.0, introducer: bool = True, **kwargs, ) -> None: super().__init__(mobject, lag_ratio=lag_ratio, introducer=introducer, **kwargs) def _get_bounds(self, alpha: float) -> tuple[float, float]: return (0, alpha) class Uncreate(Create): """Like :class:`Create` but in reverse. Examples -------- .. manim:: ShowUncreate class ShowUncreate(Scene): def construct(self): self.play(Uncreate(Square())) See Also -------- :class:`Create` """ def __init__( self, mobject: VMobject | OpenGLVMobject, reverse_rate_function: bool = True, remover: bool = True, **kwargs, ) -> None: super().__init__( mobject, reverse_rate_function=reverse_rate_function, introducer=False, remover=remover, **kwargs, ) class DrawBorderThenFill(Animation): """Draw the border first and then show the fill. Examples -------- .. manim:: ShowDrawBorderThenFill class ShowDrawBorderThenFill(Scene): def construct(self): self.play(DrawBorderThenFill(Square(fill_opacity=1, fill_color=ORANGE))) """ def __init__( self, vmobject: VMobject | OpenGLVMobject, run_time: float = 2, rate_func: Callable[[float], float] = double_smooth, stroke_width: float = 2, stroke_color: str = None, introducer: bool = True, **kwargs, ) -> None: self._typecheck_input(vmobject) super().__init__( vmobject, run_time=run_time, introducer=introducer, rate_func=rate_func, **kwargs, ) self.stroke_width = stroke_width self.stroke_color = stroke_color self.outline = self.get_outline() def _typecheck_input(self, vmobject: VMobject | OpenGLVMobject) -> None: if not isinstance(vmobject, (VMobject, OpenGLVMobject)): raise TypeError( f"{self.__class__.__name__} only works for vectorized Mobjects" ) def begin(self) -> None: self.outline = self.get_outline() super().begin() def get_outline(self) -> Mobject: outline = self.mobject.copy() outline.set_fill(opacity=0) for sm in outline.family_members_with_points(): sm.set_stroke(color=self.get_stroke_color(sm), width=self.stroke_width) return outline def get_stroke_color(self, vmobject: VMobject | OpenGLVMobject) -> ManimColor: if self.stroke_color: return self.stroke_color elif vmobject.get_stroke_width() > 0: return vmobject.get_stroke_color() return vmobject.get_color() def get_all_mobjects(self) -> Sequence[Mobject]: return [*super().get_all_mobjects(), self.outline] def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, outline, alpha: float, ) -> None: # Fixme: not matching the parent class? What is outline doing here? index: int subalpha: float index, subalpha = integer_interpolate(0, 2, alpha) if index == 0: submobject.pointwise_become_partial(outline, 0, subalpha) submobject.match_style(outline) else: submobject.interpolate(outline, starting_submobject, subalpha) class Write(DrawBorderThenFill): """Simulate hand-writing a :class:`~.Text` or hand-drawing a :class:`~.VMobject`. Examples -------- .. manim:: ShowWrite class ShowWrite(Scene): def construct(self): self.play(Write(Text("Hello", font_size=144))) .. manim:: ShowWriteReversed class ShowWriteReversed(Scene): def construct(self): self.play(Write(Text("Hello", font_size=144), reverse=True, remover=False)) Tests ----- Check that creating empty :class:`.Write` animations works:: >>> from manim import Write, Text >>> Write(Text('')) Write(Text('')) """ def __init__( self, vmobject: VMobject | OpenGLVMobject, rate_func: Callable[[float], float] = linear, reverse: bool = False, **kwargs, ) -> None: run_time: float |
|
class ShowWriteReversed(Scene): def construct(self): self.play(Write(Text("Hello", font_size=144), reverse=True, remover=False)) Tests ----- Check that creating empty :class:`.Write` animations works:: >>> from manim import Write, Text >>> Write(Text('')) Write(Text('')) """ def __init__( self, vmobject: VMobject | OpenGLVMobject, rate_func: Callable[[float], float] = linear, reverse: bool = False, **kwargs, ) -> None: run_time: float | None = kwargs.pop("run_time", None) lag_ratio: float | None = kwargs.pop("lag_ratio", None) run_time, lag_ratio = self._set_default_config_from_length( vmobject, run_time, lag_ratio, ) self.reverse = reverse if "remover" not in kwargs: kwargs["remover"] = reverse super().__init__( vmobject, rate_func=rate_func, run_time=run_time, lag_ratio=lag_ratio, introducer=not reverse, **kwargs, ) def _set_default_config_from_length( self, vmobject: VMobject | OpenGLVMobject, run_time: float | None, lag_ratio: float | None, ) -> tuple[float, float]: length = len(vmobject.family_members_with_points()) if run_time is None: run_time = 1 if length < 15 else 2 if lag_ratio is None: lag_ratio = min(4.0 / max(1.0, length), 0.2) return run_time, lag_ratio def reverse_submobjects(self) -> None: self.mobject.invert(recursive=True) def begin(self) -> None: if self.reverse: self.reverse_submobjects() super().begin() def finish(self) -> None: super().finish() if self.reverse: self.reverse_submobjects() class Unwrite(Write): """Simulate erasing by hand a :class:`~.Text` or a :class:`~.VMobject`. Parameters ---------- reverse Set True to have the animation start erasing from the last submobject first. Examples -------- .. manim :: UnwriteReverseTrue class UnwriteReverseTrue(Scene): def construct(self): text = Tex("Alice and Bob").scale(3) self.add(text) self.play(Unwrite(text)) .. manim:: UnwriteReverseFalse class UnwriteReverseFalse(Scene): def construct(self): text = Tex("Alice and Bob").scale(3) self.add(text) self.play(Unwrite(text, reverse=False)) """ def __init__( self, vmobject: VMobject, rate_func: Callable[[float], float] = linear, reverse: bool = True, **kwargs, ) -> None: run_time: float | None = kwargs.pop("run_time", None) lag_ratio: float | None = kwargs.pop("lag_ratio", None) run_time, lag_ratio = self._set_default_config_from_length( vmobject, run_time, lag_ratio, ) super().__init__( vmobject, run_time=run_time, lag_ratio=lag_ratio, reverse_rate_function=True, reverse=reverse, **kwargs, ) class SpiralIn(Animation): r"""Create the Mobject with sub-Mobjects flying in on spiral trajectories. Parameters ---------- shapes The Mobject on which to be operated. scale_factor The factor used for scaling the effect. fade_in_fraction Fractional duration of initial fade-in of sub-Mobjects as they fly inward. Examples -------- .. manim :: SpiralInExample class SpiralInExample(Scene): def construct(self): pi = MathTex(r"\pi").scale(7) pi.shift(2.25 * LEFT + 1.5 * UP) circle = Circle(color=GREEN_C, fill_opacity=1).shift(LEFT) square = Square(color=BLUE_D, fill_opacity=1).shift(UP) shapes = VGroup(pi, circle, square) self.play(SpiralIn(shapes)) """ def __init__( self, shapes: Mobject, scale_factor: float = 8, fade_in_fraction=0.3, **kwargs, ) -> None: self.shapes = shapes.copy() self.scale_factor = scale_factor self.shape_center = shapes.get_center() self.fade_in_fraction = fade_in_fraction for shape in shapes: shape.final_position = shape.get_center() shape.initial_position = ( shape.final_position + (shape.final_position - self.shape_center) * self.scale_factor ) shape.move_to(shape.initial_position) shape.save_state() super().__init__(shapes, introducer=True, **kwargs) def interpolate_mobject(self, alpha: float) -> None: alpha = self.rate_func(alpha) for original_shape, shape in zip(self.shapes, self.mobject): shape.restore() fill_opacity = original_shape.get_fill_opacity() stroke_opacity = original_shape.get_stroke_opacity() new_fill_opacity = min( fill_opacity, alpha * fill_opacity / self.fade_in_fraction ) new_stroke_opacity = min( stroke_opacity, alpha * stroke_opacity / self.fade_in_fraction ) shape.shift((shape.final_position - shape.initial_position) * alpha) shape.rotate(TAU * alpha, about_point=self.shape_center) shape.rotate(-TAU * alpha, about_point=shape.get_center_of_mass()) shape.set_fill(opacity=new_fill_opacity) shape.set_stroke(opacity=new_stroke_opacity) class ShowIncreasingSubsets(Animation): """Show one submobject at a time, leaving all previous ones displayed on screen. Examples -------- .. manim:: ShowIncreasingSubsetsScene class ShowIncreasingSubsetsScene(Scene): def construct(self): p = VGroup(Dot(), Square(), Triangle()) self.add(p) self.play(ShowIncreasingSubsets(p)) self.wait() """ def __init__( self, group: Mobject, suspend_mobject_updating: bool = False, int_func: Callable[[np.ndarray], np.ndarray] = np.floor, reverse_rate_function=False, **kwargs, )
|
class ShowIncreasingSubsets(Animation): """Show one submobject at a time, leaving all previous ones displayed on screen. Examples -------- .. manim:: ShowIncreasingSubsetsScene class ShowIncreasingSubsetsScene(Scene): def construct(self): p = VGroup(Dot(), Square(), Triangle()) self.add(p) self.play(ShowIncreasingSubsets(p)) self.wait() """ def __init__( self, group: Mobject, suspend_mobject_updating: bool = False, int_func: Callable[[np.ndarray], np.ndarray] = np.floor, reverse_rate_function=False, **kwargs, ) -> None: self.all_submobs = list(group.submobjects) self.int_func = int_func for mobj in self.all_submobs: mobj.set_opacity(0) super().__init__( group, suspend_mobject_updating=suspend_mobject_updating, reverse_rate_function=reverse_rate_function, **kwargs, ) def interpolate_mobject(self, alpha: float) -> None: n_submobs = len(self.all_submobs) value = ( 1 - self.rate_func(alpha) if self.reverse_rate_function else self.rate_func(alpha) ) index = int(self.int_func(value * n_submobs)) self.update_submobject_list(index) def update_submobject_list(self, index: int) -> None: for mobj in self.all_submobs[:index]: mobj.set_opacity(1) for mobj in self.all_submobs[index:]: mobj.set_opacity(0) class AddTextLetterByLetter(ShowIncreasingSubsets): """Show a :class:`~.Text` letter by letter on the scene. Parameters ---------- time_per_char Frequency of appearance of the letters. .. tip:: This is currently only possible for class:`~.Text` and not for class:`~.MathTex` """ def __init__( self, text: Text, suspend_mobject_updating: bool = False, int_func: Callable[[np.ndarray], np.ndarray] = np.ceil, rate_func: Callable[[float], float] = linear, time_per_char: float = 0.1, run_time: float | None = None, reverse_rate_function=False, introducer=True, **kwargs, ) -> None: self.time_per_char = time_per_char # Check for empty text using family_members_with_points() if not text.family_members_with_points(): raise ValueError( f"The text mobject {text} does not seem to contain any characters." ) if run_time is None: # minimum time per character is 1/frame_rate, otherwise # the animation does not finish. run_time = np.max((1 / config.frame_rate, self.time_per_char)) * len(text) super().__init__( text, suspend_mobject_updating=suspend_mobject_updating, int_func=int_func, rate_func=rate_func, run_time=run_time, reverse_rate_function=reverse_rate_function, introducer=introducer, **kwargs, ) class RemoveTextLetterByLetter(AddTextLetterByLetter): """Remove a :class:`~.Text` letter by letter from the scene. Parameters ---------- time_per_char Frequency of appearance of the letters. .. tip:: This is currently only possible for class:`~.Text` and not for class:`~.MathTex` """ def __init__( self, text: Text, suspend_mobject_updating: bool = False, int_func: Callable[[np.ndarray], np.ndarray] = np.ceil, rate_func: Callable[[float], float] = linear, time_per_char: float = 0.1, run_time: float | None = None, reverse_rate_function=True, introducer=False, remover=True, **kwargs, ) -> None: super().__init__( text, suspend_mobject_updating=suspend_mobject_updating, int_func=int_func, rate_func=rate_func, time_per_char=time_per_char, run_time=run_time, reverse_rate_function=reverse_rate_function, introducer=introducer, remover=remover, **kwargs, ) class ShowSubmobjectsOneByOne(ShowIncreasingSubsets): """Show one submobject at a time, removing all previously displayed ones from screen.""" def __init__( self, group: Iterable[Mobject], int_func: Callable[[np.ndarray], np.ndarray] = np.ceil, **kwargs, ) -> None: new_group = Group(*group) super().__init__(new_group, int_func=int_func, **kwargs) def update_submobject_list(self, index: int) -> None: current_submobjects = self.all_submobs[:index] for mobj in current_submobjects[:-1]: mobj.set_opacity(0) if len(current_submobjects) > 0: current_submobjects[-1].set_opacity(1) # TODO, this is broken... class AddTextWordByWord(Succession): """Show a :class:`~.Text` word by word on the scene. Note: currently broken.""" def __init__( self, text_mobject: Text, run_time: float = None, time_per_char: float = 0.06, **kwargs, ) -> None: self.time_per_char = time_per_char tpc = self.time_per_char anims = it.chain( *( [ ShowIncreasingSubsets(word, run_time=tpc * len(word)), Animation(word, run_time=0.005 * len(word) ** 1.5), ] for word in text_mobject ) ) super().__init__(*anims, **kwargs) class TypeWithCursor(AddTextLetterByLetter): """Similar to :class:`~.AddTextLetterByLetter` , but with an additional cursor mobject at the end. Parameters ---------- time_per_char Frequency of appearance of the letters. cursor :class:`~.Mobject` shown after the last added letter. buff Controls how far away the cursor is to the right of the last added letter. keep_cursor_y If ``True``, the cursor's y-coordinate is
|
, but with an additional cursor mobject at the end. Parameters ---------- time_per_char Frequency of appearance of the letters. cursor :class:`~.Mobject` shown after the last added letter. buff Controls how far away the cursor is to the right of the last added letter. keep_cursor_y If ``True``, the cursor's y-coordinate is set to the center of the ``Text`` and remains the same throughout the animation. Otherwise, it is set to the center of the last added letter. leave_cursor_on Whether to show the cursor after the animation. .. tip:: This is currently only possible for class:`~.Text` and not for class:`~.MathTex`. Examples -------- .. manim:: InsertingTextExample :ref_classes: Blink class InsertingTextExample(Scene): def construct(self): text = Text("Inserting", color=PURPLE).scale(1.5).to_edge(LEFT) cursor = Rectangle( color = GREY_A, fill_color = GREY_A, fill_opacity = 1.0, height = 1.1, width = 0.5, ).move_to(text[0]) # Position the cursor self.play(TypeWithCursor(text, cursor)) self.play(Blink(cursor, blinks=2)) """ def __init__( self, text: Text, cursor: Mobject, buff: float = 0.1, keep_cursor_y: bool = True, leave_cursor_on: bool = True, time_per_char: float = 0.1, reverse_rate_function=False, introducer=True, **kwargs, ) -> None: self.cursor = cursor self.buff = buff self.keep_cursor_y = keep_cursor_y self.leave_cursor_on = leave_cursor_on super().__init__( text, time_per_char=time_per_char, reverse_rate_function=reverse_rate_function, introducer=introducer, **kwargs, ) def begin(self) -> None: self.y_cursor = self.cursor.get_y() self.cursor.initial_position = self.mobject.get_center() if self.keep_cursor_y: self.cursor.set_y(self.y_cursor) self.cursor.set_opacity(0) self.mobject.add(self.cursor) super().begin() def finish(self) -> None: if self.leave_cursor_on: self.cursor.set_opacity(1) else: self.cursor.set_opacity(0) self.mobject.remove(self.cursor) super().finish() def clean_up_from_scene(self, scene: Scene) -> None: if not self.leave_cursor_on: scene.remove(self.cursor) super().clean_up_from_scene(scene) def update_submobject_list(self, index: int) -> None: for mobj in self.all_submobs[:index]: mobj.set_opacity(1) for mobj in self.all_submobs[index:]: mobj.set_opacity(0) if index != 0: self.cursor.next_to( self.all_submobs[index - 1], RIGHT, buff=self.buff ).set_y(self.cursor.initial_position[1]) else: self.cursor.move_to(self.all_submobs[0]).set_y( self.cursor.initial_position[1] ) if self.keep_cursor_y: self.cursor.set_y(self.y_cursor) self.cursor.set_opacity(1) class UntypeWithCursor(TypeWithCursor): """Similar to :class:`~.RemoveTextLetterByLetter` , but with an additional cursor mobject at the end. Parameters ---------- time_per_char Frequency of appearance of the letters. cursor :class:`~.Mobject` shown after the last added letter. buff Controls how far away the cursor is to the right of the last added letter. keep_cursor_y If ``True``, the cursor's y-coordinate is set to the center of the ``Text`` and remains the same throughout the animation. Otherwise, it is set to the center of the last added letter. leave_cursor_on Whether to show the cursor after the animation. .. tip:: This is currently only possible for class:`~.Text` and not for class:`~.MathTex`. Examples -------- .. manim:: DeletingTextExample :ref_classes: Blink class DeletingTextExample(Scene): def construct(self): text = Text("Deleting", color=PURPLE).scale(1.5).to_edge(LEFT) cursor = Rectangle( color = GREY_A, fill_color = GREY_A, fill_opacity = 1.0, height = 1.1, width = 0.5, ).move_to(text[0]) # Position the cursor self.play(UntypeWithCursor(text, cursor)) self.play(Blink(cursor, blinks=2)) """ def __init__( self, text: Text, cursor: VMobject | None = None, time_per_char: float = 0.1, reverse_rate_function=True, introducer=False, remover=True, **kwargs, ) -> None: super().__init__( text, cursor=cursor, time_per_char=time_per_char, reverse_rate_function=reverse_rate_function, introducer=introducer, remover=remover, **kwargs, ) ================================================ FILE: manim/animation/fading.py ================================================ """Fading in and out of view. .. manim:: Fading class Fading(Scene): def construct(self): tex_in = Tex("Fade", "In").scale(3) tex_out = Tex("Fade", "Out").scale(3) self.play(FadeIn(tex_in, shift=DOWN, scale=0.66)) self.play(ReplacementTransform(tex_in, tex_out)) self.play(FadeOut(tex_out, shift=DOWN * 2, scale=1.5)) """ from __future__ import annotations __all__ = [ "FadeOut", "FadeIn", ] from typing import Any import numpy as np from manim.mobject.opengl.opengl_mobject import OpenGLMobject from ..animation.transform import
|
manim:: Fading class Fading(Scene): def construct(self): tex_in = Tex("Fade", "In").scale(3) tex_out = Tex("Fade", "Out").scale(3) self.play(FadeIn(tex_in, shift=DOWN, scale=0.66)) self.play(ReplacementTransform(tex_in, tex_out)) self.play(FadeOut(tex_out, shift=DOWN * 2, scale=1.5)) """ from __future__ import annotations __all__ = [ "FadeOut", "FadeIn", ] from typing import Any import numpy as np from manim.mobject.opengl.opengl_mobject import OpenGLMobject from ..animation.transform import Transform from ..constants import ORIGIN from ..mobject.mobject import Group, Mobject from ..scene.scene import Scene class _Fade(Transform): """Fade :class:`~.Mobject` s in or out. Parameters ---------- mobjects The mobjects to be faded. shift The vector by which the mobject shifts while being faded. target_position The position to/from which the mobject moves while being faded in. In case another mobject is given as target position, its center is used. scale The factor by which the mobject is scaled initially before being rescaling to its original size while being faded in. """ def __init__( self, *mobjects: Mobject, shift: np.ndarray | None = None, target_position: np.ndarray | Mobject | None = None, scale: float = 1, **kwargs: Any, ) -> None: if not mobjects: raise ValueError("At least one mobject must be passed.") mobject = mobjects[0] if len(mobjects) == 1 else Group(*mobjects) self.point_target = False if shift is None: if target_position is not None: if isinstance(target_position, (Mobject, OpenGLMobject)): target_position = target_position.get_center() shift = target_position - mobject.get_center() self.point_target = True else: shift = ORIGIN self.shift_vector = shift self.scale_factor = scale super().__init__(mobject, **kwargs) def _create_faded_mobject(self, fadeIn: bool) -> Mobject: """Create a faded, shifted and scaled copy of the mobject. Parameters ---------- fadeIn Whether the faded mobject is used to fade in. Returns ------- Mobject The faded, shifted and scaled copy of the mobject. """ faded_mobject: Mobject = self.mobject.copy() # type: ignore[assignment] faded_mobject.fade(1) direction_modifier = -1 if fadeIn and not self.point_target else 1 faded_mobject.shift(self.shift_vector * direction_modifier) faded_mobject.scale(self.scale_factor) return faded_mobject class FadeIn(_Fade): r"""Fade in :class:`~.Mobject` s. Parameters ---------- mobjects The mobjects to be faded in. shift The vector by which the mobject shifts while being faded in. target_position The position from which the mobject starts while being faded in. In case another mobject is given as target position, its center is used. scale The factor by which the mobject is scaled initially before being rescaling to its original size while being faded in. Examples -------- .. manim :: FadeInExample class FadeInExample(Scene): def construct(self): dot = Dot(UP * 2 + LEFT) self.add(dot) tex = Tex( "FadeIn with ", "shift ", r" or target\_position", " and scale" ).scale(1) animations = [ FadeIn(tex[0]), FadeIn(tex[1], shift=DOWN), FadeIn(tex[2], target_position=dot), FadeIn(tex[3], scale=1.5), ] self.play(AnimationGroup(*animations, lag_ratio=0.5)) """ def __init__(self, *mobjects: Mobject, **kwargs: Any) -> None: super().__init__(*mobjects, introducer=True, **kwargs) def create_target(self) -> Mobject: return self.mobject # type: ignore[return-value] def create_starting_mobject(self) -> Mobject: return self._create_faded_mobject(fadeIn=True) class FadeOut(_Fade): r"""Fade out :class:`~.Mobject` s. Parameters ---------- mobjects The mobjects to be faded out. shift The vector by which the mobject shifts while being faded out. target_position The position to which the mobject moves while being faded out. In case another mobject is given as target position, its center is used. scale The factor by which the mobject is scaled while being faded
|
out. shift The vector by which the mobject shifts while being faded out. target_position The position to which the mobject moves while being faded out. In case another mobject is given as target position, its center is used. scale The factor by which the mobject is scaled while being faded out. Examples -------- .. manim :: FadeInExample class FadeInExample(Scene): def construct(self): dot = Dot(UP * 2 + LEFT) self.add(dot) tex = Tex( "FadeOut with ", "shift ", r" or target\_position", " and scale" ).scale(1) animations = [ FadeOut(tex[0]), FadeOut(tex[1], shift=DOWN), FadeOut(tex[2], target_position=dot), FadeOut(tex[3], scale=0.5), ] self.play(AnimationGroup(*animations, lag_ratio=0.5)) """ def __init__(self, *mobjects: Mobject, **kwargs: Any) -> None: super().__init__(*mobjects, remover=True, **kwargs) def create_target(self) -> Mobject: return self._create_faded_mobject(fadeIn=False) def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) self.interpolate(0) ================================================ FILE: manim/animation/growing.py ================================================ """Animations that introduce mobjects to scene by growing them from points. .. manim:: Growing class Growing(Scene): def construct(self): square = Square() circle = Circle() triangle = Triangle() arrow = Arrow(LEFT, RIGHT) star = Star() VGroup(square, circle, triangle).set_x(0).arrange(buff=1.5).set_y(2) VGroup(arrow, star).move_to(DOWN).set_x(0).arrange(buff=1.5).set_y(-2) self.play(GrowFromPoint(square, ORIGIN)) self.play(GrowFromCenter(circle)) self.play(GrowFromEdge(triangle, DOWN)) self.play(GrowArrow(arrow)) self.play(SpinInFromNothing(star)) """ from __future__ import annotations __all__ = [ "GrowFromPoint", "GrowFromCenter", "GrowFromEdge", "GrowArrow", "SpinInFromNothing", ] from typing import TYPE_CHECKING, Any from ..animation.transform import Transform from ..constants import PI from ..utils.paths import spiral_path if TYPE_CHECKING: from manim.mobject.geometry.line import Arrow from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.typing import Point3DLike, Vector3DLike from manim.utils.color import ParsableManimColor from ..mobject.mobject import Mobject class GrowFromPoint(Transform): """Introduce an :class:`~.Mobject` by growing it from a point. Parameters ---------- mobject The mobjects to be introduced. point The point from which the mobject grows. point_color Initial color of the mobject before growing to its full size. Leave empty to match mobject's color. Examples -------- .. manim :: GrowFromPointExample class GrowFromPointExample(Scene): def construct(self): dot = Dot(3 * UR, color=GREEN) squares = [Square() for _ in range(4)] VGroup(*squares).set_x(0).arrange(buff=1) self.add(dot) self.play(GrowFromPoint(squares[0], ORIGIN)) self.play(GrowFromPoint(squares[1], [-2, 2, 0])) self.play(GrowFromPoint(squares[2], [3, -2, 0], RED)) self.play(GrowFromPoint(squares[3], dot, dot.get_color())) """ def __init__( self, mobject: Mobject, point: Point3DLike, point_color: ParsableManimColor | None = None, **kwargs: Any, ): self.point = point self.point_color = point_color super().__init__(mobject, introducer=True, **kwargs) def create_target(self) -> Mobject | OpenGLMobject: return self.mobject def create_starting_mobject(self) -> Mobject | OpenGLMobject: start = super().create_starting_mobject() start.scale(0) start.move_to(self.point) if self.point_color: start.set_color(self.point_color) return start class GrowFromCenter(GrowFromPoint): """Introduce an :class:`~.Mobject` by growing it from its center. Parameters ---------- mobject The mobjects to be introduced. point_color Initial color of the mobject before growing to its full size. Leave empty to match mobject's color. Examples -------- .. manim :: GrowFromCenterExample class GrowFromCenterExample(Scene): def construct(self): squares = [Square() for _ in range(2)] VGroup(*squares).set_x(0).arrange(buff=2) self.play(GrowFromCenter(squares[0])) self.play(GrowFromCenter(squares[1], point_color=RED)) """ def __init__( self, mobject: Mobject, point_color: ParsableManimColor | None = None, **kwargs: Any, ): point = mobject.get_center() super().__init__(mobject, point, point_color=point_color, **kwargs) class GrowFromEdge(GrowFromPoint): """Introduce an :class:`~.Mobject` by growing it from one of its bounding box edges. Parameters ---------- mobject The mobjects to be introduced. edge The direction to seek bounding box edge of mobject. point_color Initial color of the mobject before growing to its full size. Leave empty to match mobject's color. Examples -------- .. manim :: GrowFromEdgeExample class GrowFromEdgeExample(Scene):
|
one of its bounding box edges. Parameters ---------- mobject The mobjects to be introduced. edge The direction to seek bounding box edge of mobject. point_color Initial color of the mobject before growing to its full size. Leave empty to match mobject's color. Examples -------- .. manim :: GrowFromEdgeExample class GrowFromEdgeExample(Scene): def construct(self): squares = [Square() for _ in range(4)] VGroup(*squares).set_x(0).arrange(buff=1) self.play(GrowFromEdge(squares[0], DOWN)) self.play(GrowFromEdge(squares[1], RIGHT)) self.play(GrowFromEdge(squares[2], UR)) self.play(GrowFromEdge(squares[3], UP, point_color=RED)) """ def __init__( self, mobject: Mobject, edge: Vector3DLike, point_color: ParsableManimColor | None = None, **kwargs: Any, ): point = mobject.get_critical_point(edge) super().__init__(mobject, point, point_color=point_color, **kwargs) class GrowArrow(GrowFromPoint): """Introduce an :class:`~.Arrow` by growing it from its start toward its tip. Parameters ---------- arrow The arrow to be introduced. point_color Initial color of the arrow before growing to its full size. Leave empty to match arrow's color. Examples -------- .. manim :: GrowArrowExample class GrowArrowExample(Scene): def construct(self): arrows = [Arrow(2 * LEFT, 2 * RIGHT), Arrow(2 * DR, 2 * UL)] VGroup(*arrows).set_x(0).arrange(buff=2) self.play(GrowArrow(arrows[0])) self.play(GrowArrow(arrows[1], point_color=RED)) """ def __init__( self, arrow: Arrow, point_color: ParsableManimColor | None = None, **kwargs: Any ): point = arrow.get_start() super().__init__(arrow, point, point_color=point_color, **kwargs) def create_starting_mobject(self) -> Mobject | OpenGLMobject: start_arrow = self.mobject.copy() start_arrow.scale(0, scale_tips=True, about_point=self.point) if self.point_color: start_arrow.set_color(self.point_color) return start_arrow class SpinInFromNothing(GrowFromCenter): """Introduce an :class:`~.Mobject` spinning and growing it from its center. Parameters ---------- mobject The mobjects to be introduced. angle The amount of spinning before mobject reaches its full size. E.g. 2*PI means that the object will do one full spin before being fully introduced. point_color Initial color of the mobject before growing to its full size. Leave empty to match mobject's color. Examples -------- .. manim :: SpinInFromNothingExample class SpinInFromNothingExample(Scene): def construct(self): squares = [Square() for _ in range(3)] VGroup(*squares).set_x(0).arrange(buff=2) self.play(SpinInFromNothing(squares[0])) self.play(SpinInFromNothing(squares[1], angle=2 * PI)) self.play(SpinInFromNothing(squares[2], point_color=RED)) """ def __init__( self, mobject: Mobject, angle: float = PI / 2, point_color: ParsableManimColor | None = None, **kwargs: Any, ): self.angle = angle super().__init__( mobject, path_func=spiral_path(angle), point_color=point_color, **kwargs ) ================================================ FILE: manim/animation/indication.py ================================================ """Animations drawing attention to particular mobjects. Examples -------- .. manim:: Indications class Indications(Scene): def construct(self): indications = [ApplyWave,Circumscribe,Flash,FocusOn,Indicate,ShowPassingFlash,Wiggle] names = [Tex(i.__name__).scale(3) for i in indications] self.add(names[0]) for i in range(len(names)): if indications[i] is Flash: self.play(Flash(UP)) elif indications[i] is ShowPassingFlash: self.play(ShowPassingFlash(Underline(names[i]))) else: self.play(indications[i](names[i])) self.play(AnimationGroup( FadeOut(names[i], shift=UP*1.5), FadeIn(names[(i+1)%len(names)], shift=UP*1.5), )) """ from __future__ import annotations __all__ = [ "FocusOn", "Indicate", "Flash", "ShowPassingFlash", "ShowPassingFlashWithThinningStrokeWidth", "ApplyWave", "Circumscribe", "Wiggle", "Blink", ] from collections.abc import Iterable from typing import Any import numpy as np from typing_extensions import Self from manim.mobject.geometry.arc import Circle, Dot from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import Rectangle from manim.mobject.geometry.shape_matchers import SurroundingRectangle from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.scene.scene import Scene from .. import config from ..animation.animation import Animation from ..animation.composition import AnimationGroup, Succession from ..animation.creation import Create, ShowPartial, Uncreate from ..animation.fading import FadeIn, FadeOut from ..animation.movement import Homotopy from ..animation.transform import Transform from ..animation.updaters.update import UpdateFromFunc from ..constants import * from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..typing import Point3D, Point3DLike, Vector3DLike from ..utils.bezier import interpolate, inverse_interpolate from ..utils.color import GREY, YELLOW, ParsableManimColor from ..utils.rate_functions import RateFunction,
|
..animation.fading import FadeIn, FadeOut from ..animation.movement import Homotopy from ..animation.transform import Transform from ..animation.updaters.update import UpdateFromFunc from ..constants import * from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..typing import Point3D, Point3DLike, Vector3DLike from ..utils.bezier import interpolate, inverse_interpolate from ..utils.color import GREY, YELLOW, ParsableManimColor from ..utils.rate_functions import RateFunction, smooth, there_and_back, wiggle from ..utils.space_ops import normalize class FocusOn(Transform): """Shrink a spotlight to a position. Parameters ---------- focus_point The point at which to shrink the spotlight. If it is a :class:`.~Mobject` its center will be used. opacity The opacity of the spotlight. color The color of the spotlight. run_time The duration of the animation. Examples -------- .. manim:: UsingFocusOn class UsingFocusOn(Scene): def construct(self): dot = Dot(color=YELLOW).shift(DOWN) self.add(Tex("Focusing on the dot below:"), dot) self.play(FocusOn(dot)) self.wait() """ def __init__( self, focus_point: Point3DLike | Mobject, opacity: float = 0.2, color: ParsableManimColor = GREY, run_time: float = 2, **kwargs: Any, ): self.focus_point = focus_point self.color = color self.opacity = opacity remover = True starting_dot = Dot( radius=config["frame_x_radius"] + config["frame_y_radius"], stroke_width=0, fill_color=self.color, fill_opacity=0, ) super().__init__(starting_dot, run_time=run_time, remover=remover, **kwargs) def create_target(self) -> Dot: little_dot = Dot(radius=0) little_dot.set_fill(self.color, opacity=self.opacity) little_dot.add_updater(lambda d: d.move_to(self.focus_point)) return little_dot class Indicate(Transform): """Indicate a Mobject by temporarily resizing and recoloring it. Parameters ---------- mobject The mobject to indicate. scale_factor The factor by which the mobject will be temporally scaled color The color the mobject temporally takes. rate_func The function defining the animation progress at every point in time. kwargs Additional arguments to be passed to the :class:`~.Succession` constructor Examples -------- .. manim:: UsingIndicate class UsingIndicate(Scene): def construct(self): tex = Tex("Indicate").scale(3) self.play(Indicate(tex)) self.wait() """ def __init__( self, mobject: Mobject, scale_factor: float = 1.2, color: ParsableManimColor = YELLOW, rate_func: RateFunction = there_and_back, **kwargs: Any, ): self.color = color self.scale_factor = scale_factor super().__init__(mobject, rate_func=rate_func, **kwargs) def create_target(self) -> Mobject | OpenGLMobject: target = self.mobject.copy() target.scale(self.scale_factor) target.set_color(self.color) return target class Flash(AnimationGroup): """Send out lines in all directions. Parameters ---------- point The center of the flash lines. If it is a :class:`.~Mobject` its center will be used. line_length The length of the flash lines. num_lines The number of flash lines. flash_radius The distance from `point` at which the flash lines start. line_stroke_width The stroke width of the flash lines. color The color of the flash lines. time_width The time width used for the flash lines. See :class:`.~ShowPassingFlash` for more details. run_time The duration of the animation. kwargs Additional arguments to be passed to the :class:`~.Succession` constructor Examples -------- .. manim:: UsingFlash class UsingFlash(Scene): def construct(self): dot = Dot(color=YELLOW).shift(DOWN) self.add(Tex("Flash the dot below:"), dot) self.play(Flash(dot)) self.wait() .. manim:: FlashOnCircle class FlashOnCircle(Scene): def construct(self): radius = 2 circle = Circle(radius) self.add(circle) self.play(Flash( circle, line_length=1, num_lines=30, color=RED, flash_radius=radius+SMALL_BUFF, time_width=0.3, run_time=2, rate_func = rush_from )) """ def __init__( self, point: Point3DLike | Mobject, line_length: float = 0.2, num_lines: int = 12, flash_radius: float = 0.1, line_stroke_width: int = 3, color: ParsableManimColor = YELLOW, time_width: float = 1, run_time: float = 1.0, **kwargs: Any, ): if isinstance(point, Mobject): self.point: Point3D = point.get_center() else: self.point = np.asarray(point) self.color = color self.line_length = line_length self.num_lines
|
Mobject, line_length: float = 0.2, num_lines: int = 12, flash_radius: float = 0.1, line_stroke_width: int = 3, color: ParsableManimColor = YELLOW, time_width: float = 1, run_time: float = 1.0, **kwargs: Any, ): if isinstance(point, Mobject): self.point: Point3D = point.get_center() else: self.point = np.asarray(point) self.color = color self.line_length = line_length self.num_lines = num_lines self.flash_radius = flash_radius self.line_stroke_width = line_stroke_width self.run_time = run_time self.time_width = time_width self.animation_config = kwargs self.lines = self.create_lines() animations = self.create_line_anims() super().__init__(*animations, group=self.lines) def create_lines(self) -> VGroup: lines = VGroup() for angle in np.arange(0, TAU, TAU / self.num_lines): line = Line(self.point, self.point + self.line_length * RIGHT) line.shift((self.flash_radius) * RIGHT) line.rotate(angle, about_point=self.point) lines.add(line) lines.set_color(self.color) lines.set_stroke(width=self.line_stroke_width) return lines def create_line_anims(self) -> Iterable[ShowPassingFlash]: return [ ShowPassingFlash( line, time_width=self.time_width, run_time=self.run_time, **self.animation_config, ) for line in self.lines ] class ShowPassingFlash(ShowPartial): r"""Show only a sliver of the VMobject each frame. Parameters ---------- mobject The mobject whose stroke is animated. time_width The length of the sliver relative to the length of the stroke. Examples -------- .. manim:: TimeWidthValues class TimeWidthValues(Scene): def construct(self): p = RegularPolygon(5, color=DARK_GRAY, stroke_width=6).scale(3) lbl = VMobject() self.add(p, lbl) p = p.copy().set_color(BLUE) for time_width in [0.2, 0.5, 1, 2]: lbl.become(Tex(r"\texttt{time\_width={{%.1f}}}"%time_width)) self.play(ShowPassingFlash( p.copy().set_color(BLUE), run_time=2, time_width=time_width )) See Also -------- :class:`~.Create` """ def __init__( self, mobject: VMobject, time_width: float = 0.1, **kwargs: Any ) -> None: self.time_width = time_width super().__init__(mobject, remover=True, introducer=True, **kwargs) def _get_bounds(self, alpha: float) -> tuple[float, float]: tw = self.time_width upper = interpolate(0, 1 + tw, alpha) lower = upper - tw upper = min(upper, 1) lower = max(lower, 0) return (lower, upper) def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) for submob, start in self.get_all_families_zipped(): submob.pointwise_become_partial(start, 0, 1) class ShowPassingFlashWithThinningStrokeWidth(AnimationGroup): def __init__( self, vmobject: VMobject, n_segments: int = 10, time_width: float = 0.1, remover: bool = True, **kwargs: Any, ): self.n_segments = n_segments self.time_width = time_width self.remover = remover max_stroke_width = vmobject.get_stroke_width() max_time_width = kwargs.pop("time_width", self.time_width) super().__init__( *( ShowPassingFlash( vmobject.copy().set_stroke(width=stroke_width), time_width=time_width, **kwargs, ) for stroke_width, time_width in zip( np.linspace(0, max_stroke_width, self.n_segments), np.linspace(max_time_width, 0, self.n_segments), ) ), ) class ApplyWave(Homotopy): """Send a wave through the Mobject distorting it temporarily. Parameters ---------- mobject The mobject to be distorted. direction The direction in which the wave nudges points of the shape amplitude The distance points of the shape get shifted wave_func The function defining the shape of one wave flank. time_width The length of the wave relative to the width of the mobject. ripples The number of ripples of the wave run_time The duration of the animation. Examples -------- .. manim:: ApplyingWaves class ApplyingWaves(Scene): def construct(self): tex = Tex("WaveWaveWaveWaveWave").scale(2) self.play(ApplyWave(tex)) self.play(ApplyWave( tex, direction=RIGHT, time_width=0.5, amplitude=0.3 )) self.play(ApplyWave( tex, rate_func=linear, ripples=4 )) """ def __init__( self, mobject: Mobject, direction: Vector3DLike = UP, amplitude: float = 0.2, wave_func: RateFunction = smooth, time_width: float = 1, ripples: int = 1, run_time: float = 2, **kwargs: Any, ): x_min = mobject.get_left()[0] x_max = mobject.get_right()[0] vect = amplitude * normalize(direction) def wave(t: float) -> float: # Creates a wave with n ripples from a simple rate_func # This wave is build up as follows: # The time is split
|
int = 1, run_time: float = 2, **kwargs: Any, ): x_min = mobject.get_left()[0] x_max = mobject.get_right()[0] vect = amplitude * normalize(direction) def wave(t: float) -> float: # Creates a wave with n ripples from a simple rate_func # This wave is build up as follows: # The time is split into 2*ripples phases. In every phase the amplitude # either rises to one or goes down to zero. Consecutive ripples will have # their amplitudes in opposing directions (first ripple from 0 to 1 to 0, # second from 0 to -1 to 0 and so on). This is how two ripples would be # divided into phases: # ####|#### | | # ## | ## | | # ## | ## | | # #### | ####|#### | #### # | | ## | ## # | | ## | ## # | | ####|#### # However, this looks weird in the middle between two ripples. Therefore the # middle phases do actually use only one appropriately scaled version of the # rate like this: # 1 / 4 Time | 2 / 4 Time | 1 / 4 Time # ####|###### | # ## | ### | # ## | ## | # #### | # | #### # | ## | ## # | ### | ## # | ######|#### # Mirrored looks better in the way the wave is used. t = 1 - t # Clamp input if t >= 1 or t <= 0: return 0 phases = ripples * 2 phase = int(t * phases) if phase == 0: # First rising ripple return wave_func(t * phases) elif phase == phases - 1: # last ripple. Rising or falling depending on the number of ripples # The (ripples % 2)-term is used to make this distinction. t -= phase / phases # Time relative to the phase return (1 - wave_func(t * phases)) * (2 * (ripples % 2) - 1) else: # Longer phases: phase = int((phase - 1) / 2) t -= (2 * phase + 1) / phases # Similar to last ripple: return (1 - 2 * wave_func(t * ripples)) * (1 - 2 * ((phase) % 2)) def homotopy( x: float, y: float, z: float, t: float, ) -> tuple[float, float, float]: upper = interpolate(0, 1 + time_width, t) lower = upper - time_width relative_x = inverse_interpolate(x_min, x_max, x) wave_phase = inverse_interpolate(lower, upper, relative_x) nudge = wave(wave_phase) * vect return_value: tuple[float, float, float] = np.array([x, y, z]) + nudge return return_value super().__init__(homotopy, mobject, run_time=run_time, **kwargs) class Wiggle(Animation): """Wiggle a Mobject. Parameters ---------- mobject The mobject to wiggle. scale_value The factor by which the mobject will be temporarily scaled. rotation_angle The wiggle angle. n_wiggles The number of wiggles. scale_about_point The point about which the mobject gets scaled. rotate_about_point The point around which the mobject gets rotated. run_time The duration of the animation Examples -------- .. manim:: ApplyingWaves class ApplyingWaves(Scene): def construct(self): tex = Tex("Wiggle").scale(3) self.play(Wiggle(tex)) self.wait() """ def __init__(
|
rotation_angle The wiggle angle. n_wiggles The number of wiggles. scale_about_point The point about which the mobject gets scaled. rotate_about_point The point around which the mobject gets rotated. run_time The duration of the animation Examples -------- .. manim:: ApplyingWaves class ApplyingWaves(Scene): def construct(self): tex = Tex("Wiggle").scale(3) self.play(Wiggle(tex)) self.wait() """ def __init__( self, mobject: Mobject, scale_value: float = 1.1, rotation_angle: float = 0.01 * TAU, n_wiggles: int = 6, scale_about_point: Point3DLike | None = None, rotate_about_point: Point3DLike | None = None, run_time: float = 2, **kwargs: Any, ): self.scale_value = scale_value self.rotation_angle = rotation_angle self.n_wiggles = n_wiggles self.scale_about_point = scale_about_point if scale_about_point is not None: self.scale_about_point = np.array(scale_about_point) self.rotate_about_point = rotate_about_point if rotate_about_point is not None: self.rotate_about_point = np.array(rotate_about_point) super().__init__(mobject, run_time=run_time, **kwargs) def get_scale_about_point(self) -> Point3D: if self.scale_about_point is None: return self.mobject.get_center() return self.scale_about_point def get_rotate_about_point(self) -> Point3D: if self.rotate_about_point is None: return self.mobject.get_center() return self.rotate_about_point def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> Self: submobject.points[:, :] = starting_submobject.points submobject.scale( interpolate(1, self.scale_value, there_and_back(alpha)), about_point=self.get_scale_about_point(), ) submobject.rotate( wiggle(alpha, self.n_wiggles) * self.rotation_angle, about_point=self.get_rotate_about_point(), ) return self class Circumscribe(Succession): r"""Draw a temporary line surrounding the mobject. Parameters ---------- mobject The mobject to be circumscribed. shape The shape with which to surround the given mobject. Should be either :class:`~.Rectangle` or :class:`~.Circle` fade_in Whether to make the surrounding shape to fade in. It will be drawn otherwise. fade_out Whether to make the surrounding shape to fade out. It will be undrawn otherwise. time_width The time_width of the drawing and undrawing. Gets ignored if either `fade_in` or `fade_out` is `True`. buff The distance between the surrounding shape and the given mobject. color The color of the surrounding shape. run_time The duration of the entire animation. kwargs Additional arguments to be passed to the :class:`~.Succession` constructor Examples -------- .. manim:: UsingCircumscribe class UsingCircumscribe(Scene): def construct(self): lbl = Tex(r"Circum-\\scribe").scale(2) self.add(lbl) self.play(Circumscribe(lbl)) self.play(Circumscribe(lbl, Circle)) self.play(Circumscribe(lbl, fade_out=True)) self.play(Circumscribe(lbl, time_width=2)) self.play(Circumscribe(lbl, Circle, True)) """ def __init__( self, mobject: Mobject, shape: type[Rectangle] | type[Circle] = Rectangle, fade_in: bool = False, fade_out: bool = False, time_width: float = 0.3, buff: float = SMALL_BUFF, color: ParsableManimColor = YELLOW, run_time: float = 1, stroke_width: float = DEFAULT_STROKE_WIDTH, **kwargs: Any, ): if shape is Rectangle: frame: SurroundingRectangle | Circle = SurroundingRectangle( mobject, color=color, buff=buff, stroke_width=stroke_width, ) elif shape is Circle: frame = Circle(color=color, stroke_width=stroke_width).surround( mobject, buffer_factor=1, ) radius = frame.width / 2 frame.scale((radius + buff) / radius) else: raise ValueError("shape should be either Rectangle or Circle.") if fade_in and fade_out: super().__init__( FadeIn(frame, run_time=run_time / 2), FadeOut(frame, run_time=run_time / 2), **kwargs, ) elif fade_in: frame.reverse_direction() super().__init__( FadeIn(frame, run_time=run_time / 2), Uncreate(frame, run_time=run_time / 2), **kwargs, ) elif fade_out: super().__init__( Create(frame, run_time=run_time / 2), FadeOut(frame, run_time=run_time / 2), **kwargs, ) else: super().__init__( ShowPassingFlash(frame, time_width, run_time=run_time), **kwargs ) class Blink(Succession): """Blink the mobject. Parameters ---------- mobject The mobject to be blinked. time_on The duration that the mobject is shown for one blink. time_off The duration that the mobject is hidden for one blink. blinks The number of blinks hide_at_end Whether to hide the mobject at the end of
|
class Blink(Succession): """Blink the mobject. Parameters ---------- mobject The mobject to be blinked. time_on The duration that the mobject is shown for one blink. time_off The duration that the mobject is hidden for one blink. blinks The number of blinks hide_at_end Whether to hide the mobject at the end of the animation. kwargs Additional arguments to be passed to the :class:`~.Succession` constructor. Examples -------- .. manim:: BlinkingExample class BlinkingExample(Scene): def construct(self): text = Text("Blinking").scale(1.5) self.add(text) self.play(Blink(text, blinks=3)) """ def __init__( self, mobject: Mobject, time_on: float = 0.5, time_off: float = 0.5, blinks: int = 1, hide_at_end: bool = False, **kwargs: Any, ): animations = [ UpdateFromFunc( mobject, update_function=lambda mob: mob.set_opacity(1.0), run_time=time_on, ), UpdateFromFunc( mobject, update_function=lambda mob: mob.set_opacity(0.0), run_time=time_off, ), ] * blinks if not hide_at_end: animations.append( UpdateFromFunc( mobject, update_function=lambda mob: mob.set_opacity(1.0), run_time=time_on, ), ) super().__init__(*animations, **kwargs) ================================================ FILE: manim/animation/movement.py ================================================ """Animations related to movement.""" from __future__ import annotations __all__ = [ "Homotopy", "SmoothedVectorizedHomotopy", "ComplexHomotopy", "PhaseFlow", "MoveAlongPath", ] from typing import TYPE_CHECKING, Any, Callable import numpy as np from ..animation.animation import Animation from ..utils.rate_functions import linear if TYPE_CHECKING: from typing_extensions import Self from manim.mobject.types.vectorized_mobject import VMobject from manim.typing import MappingFunction, Point3D from manim.utils.rate_functions import RateFunction from ..mobject.mobject import Mobject class Homotopy(Animation): """A Homotopy. This is an animation transforming the points of a mobject according to the specified transformation function. With the parameter :math:`t` moving from 0 to 1 throughout the animation and :math:`(x, y, z)` describing the coordinates of the point of a mobject, the function passed to the ``homotopy`` keyword argument should transform the tuple :math:`(x, y, z, t)` to :math:`(x', y', z')`, the coordinates the original point is transformed to at time :math:`t`. Parameters ---------- homotopy A function mapping :math:`(x, y, z, t)` to :math:`(x', y', z')`. mobject The mobject transformed under the given homotopy. run_time The run time of the animation. apply_function_kwargs Keyword arguments propagated to :meth:`.Mobject.apply_function`. kwargs Further keyword arguments passed to the parent class. Examples -------- .. manim:: HomotopyExample class HomotopyExample(Scene): def construct(self): square = Square() def homotopy(x, y, z, t): if t <= 0.25: progress = t / 0.25 return (x, y + progress * 0.2 * np.sin(x), z) else: wave_progress = (t - 0.25) / 0.75 return (x, y + 0.2 * np.sin(x + 10 * wave_progress), z) self.play(Homotopy(homotopy, square, rate_func= linear, run_time=2)) """ def __init__( self, homotopy: Callable[[float, float, float, float], tuple[float, float, float]], mobject: Mobject, run_time: float = 3, apply_function_kwargs: dict[str, Any] | None = None, **kwargs: Any, ): self.homotopy = homotopy self.apply_function_kwargs = ( apply_function_kwargs if apply_function_kwargs is not None else {} ) super().__init__(mobject, run_time=run_time, **kwargs) def function_at_time_t(self, t: float) -> MappingFunction: def mapping_function(p: Point3D) -> Point3D: x, y, z = p return np.array(self.homotopy(x, y, z, t)) return mapping_function def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> Self: submobject.points = starting_submobject.points submobject.apply_function( self.function_at_time_t(alpha), **self.apply_function_kwargs, ) return self class SmoothedVectorizedHomotopy(Homotopy): def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> Self: assert isinstance(submobject, VMobject) super().interpolate_submobject(submobject, starting_submobject, alpha) submobject.make_smooth() return self class ComplexHomotopy(Homotopy): def __init__( self, complex_homotopy: Callable[[complex, float],
|
self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> Self: submobject.points = starting_submobject.points submobject.apply_function( self.function_at_time_t(alpha), **self.apply_function_kwargs, ) return self class SmoothedVectorizedHomotopy(Homotopy): def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float, ) -> Self: assert isinstance(submobject, VMobject) super().interpolate_submobject(submobject, starting_submobject, alpha) submobject.make_smooth() return self class ComplexHomotopy(Homotopy): def __init__( self, complex_homotopy: Callable[[complex, float], float], mobject: Mobject, **kwargs: Any, ): """Complex Homotopy a function Cx[0, 1] to C""" def homotopy( x: float, y: float, z: float, t: float, ) -> tuple[float, float, float]: c = complex_homotopy(complex(x, y), t) return (c.real, c.imag, z) super().__init__(homotopy, mobject, **kwargs) class PhaseFlow(Animation): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, virtual_time: float = 1, suspend_mobject_updating: bool = False, rate_func: RateFunction = linear, **kwargs: Any, ): self.virtual_time = virtual_time self.function = function super().__init__( mobject, suspend_mobject_updating=suspend_mobject_updating, rate_func=rate_func, **kwargs, ) def interpolate_mobject(self, alpha: float) -> None: if hasattr(self, "last_alpha"): dt = self.virtual_time * ( self.rate_func(alpha) - self.rate_func(self.last_alpha) ) self.mobject.apply_function(lambda p: p + dt * self.function(p)) self.last_alpha: float = alpha class MoveAlongPath(Animation): """Make one mobject move along the path of another mobject. .. manim:: MoveAlongPathExample class MoveAlongPathExample(Scene): def construct(self): d1 = Dot().set_color(ORANGE) l1 = Line(LEFT, RIGHT) l2 = VMobject() self.add(d1, l1, l2) l2.add_updater(lambda x: x.become(Line(LEFT, d1.get_center()).set_color(ORANGE))) self.play(MoveAlongPath(d1, l1), rate_func=linear) """ def __init__( self, mobject: Mobject, path: VMobject, suspend_mobject_updating: bool = False, **kwargs: Any, ): self.path = path super().__init__( mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: point = self.path.point_from_proportion(self.rate_func(alpha)) self.mobject.move_to(point) ================================================ FILE: manim/animation/numbers.py ================================================ """Animations for changing numbers.""" from __future__ import annotations __all__ = ["ChangingDecimal", "ChangeDecimalToValue"] from collections.abc import Callable from typing import Any from manim.mobject.text.numbers import DecimalNumber from ..animation.animation import Animation from ..utils.bezier import interpolate class ChangingDecimal(Animation): """Animate a :class:`~.DecimalNumber` to values specified by a user-supplied function. Parameters ---------- decimal_mob The :class:`~.DecimalNumber` instance to animate. number_update_func A function that returns the number to display at each point in the animation. suspend_mobject_updating If ``True``, the mobject is not updated outside this animation. Raises ------ TypeError If ``decimal_mob`` is not an instance of :class:`~.DecimalNumber`. Examples -------- .. manim:: ChangingDecimalExample class ChangingDecimalExample(Scene): def construct(self): number = DecimalNumber(0) self.add(number) self.play( ChangingDecimal( number, lambda a: 5 * a, run_time=3 ) ) self.wait() """ def __init__( self, decimal_mob: DecimalNumber, number_update_func: Callable[[float], float], suspend_mobject_updating: bool = False, **kwargs: Any, ) -> None: self.check_validity_of_input(decimal_mob) self.number_update_func = number_update_func super().__init__( decimal_mob, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def check_validity_of_input(self, decimal_mob: DecimalNumber) -> None: if not isinstance(decimal_mob, DecimalNumber): raise TypeError("ChangingDecimal can only take in a DecimalNumber") def interpolate_mobject(self, alpha: float) -> None: self.mobject.set_value(self.number_update_func(self.rate_func(alpha))) # type: ignore[attr-defined] class ChangeDecimalToValue(ChangingDecimal): """Animate a :class:`~.DecimalNumber` to a target value using linear interpolation. Parameters ---------- decimal_mob The :class:`~.DecimalNumber` instance to animate. target_number The target value to transition to. Examples -------- .. manim:: ChangeDecimalToValueExample class ChangeDecimalToValueExample(Scene): def construct(self): number = DecimalNumber(0) self.add(number) self.play(ChangeDecimalToValue(number, 10, run_time=3)) self.wait() """ def __init__( self, decimal_mob: DecimalNumber, target_number: int, **kwargs: Any ) -> None: start_number = decimal_mob.number super().__init__( decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs ) ================================================ FILE: manim/animation/rotation.py ================================================ """Animations related to rotation.""" from __future__ import annotations __all__ = ["Rotating", "Rotate"] from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any import numpy as
|
decimal_mob: DecimalNumber, target_number: int, **kwargs: Any ) -> None: start_number = decimal_mob.number super().__init__( decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs ) ================================================ FILE: manim/animation/rotation.py ================================================ """Animations related to rotation.""" from __future__ import annotations __all__ = ["Rotating", "Rotate"] from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any import numpy as np from ..animation.animation import Animation from ..animation.transform import Transform from ..constants import OUT, PI, TAU from ..utils.rate_functions import linear if TYPE_CHECKING: from ..mobject.mobject import Mobject class Rotating(Animation): """Animation that rotates a Mobject. Parameters ---------- mobject The mobject to be rotated. angle The rotation angle in radians. Predefined constants such as ``DEGREES`` can also be used to specify the angle in degrees. axis The rotation axis as a numpy vector. about_point The rotation center. about_edge If ``about_point`` is ``None``, this argument specifies the direction of the bounding box point to be taken as the rotation center. run_time The duration of the animation in seconds. rate_func The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) . **kwargs Additional keyword arguments passed to :class:`~.Animation`. Examples -------- .. manim:: RotatingDemo class RotatingDemo(Scene): def construct(self): circle = Circle(radius=1, color=BLUE) line = Line(start=ORIGIN, end=RIGHT) arrow = Arrow(start=ORIGIN, end=RIGHT, buff=0, color=GOLD) vg = VGroup(circle,line,arrow) self.add(vg) anim_kw = {"about_point": arrow.get_start(), "run_time": 1} self.play(Rotating(arrow, 180*DEGREES, **anim_kw)) self.play(Rotating(arrow, PI, **anim_kw)) self.play(Rotating(vg, PI, about_point=RIGHT)) self.play(Rotating(vg, PI, axis=UP, about_point=ORIGIN)) self.play(Rotating(vg, PI, axis=RIGHT, about_edge=UP)) self.play(vg.animate.move_to(ORIGIN)) .. manim:: RotatingDifferentAxis class RotatingDifferentAxis(ThreeDScene): def construct(self): axes = ThreeDAxes() cube = Cube() arrow2d = Arrow(start=[0, -1.2, 1], end=[0, 1.2, 1], color=YELLOW_E) cube_group = VGroup(cube,arrow2d) self.set_camera_orientation(gamma=0, phi=40*DEGREES, theta=40*DEGREES) self.add(axes, cube_group) play_kw = {"run_time": 1.5} self.play(Rotating(cube_group, PI), **play_kw) self.play(Rotating(cube_group, PI, axis=UP), **play_kw) self.play(Rotating(cube_group, 180*DEGREES, axis=RIGHT), **play_kw) self.wait(0.5) See also -------- :class:`~.Rotate`, :meth:`~.Mobject.rotate` """ def __init__( self, mobject: Mobject, angle: float = TAU, axis: np.ndarray = OUT, about_point: np.ndarray | None = None, about_edge: np.ndarray | None = None, run_time: float = 5, rate_func: Callable[[float], float] = linear, **kwargs: Any, ) -> None: self.angle = angle self.axis = axis self.about_point = about_point self.about_edge = about_edge super().__init__(mobject, run_time=run_time, rate_func=rate_func, **kwargs) def interpolate_mobject(self, alpha: float) -> None: self.mobject.become(self.starting_mobject) self.mobject.rotate( self.rate_func(alpha) * self.angle, axis=self.axis, about_point=self.about_point, about_edge=self.about_edge, ) class Rotate(Transform): """Animation that rotates a Mobject. Parameters ---------- mobject The mobject to be rotated. angle The rotation angle. axis The rotation axis as a numpy vector. about_point The rotation center. about_edge If ``about_point`` is ``None``, this argument specifies the direction of the bounding box point to be taken as the rotation center. Examples -------- .. manim:: UsingRotate class UsingRotate(Scene): def construct(self): self.play( Rotate( Square(side_length=0.5).shift(UP * 2), angle=2*PI, about_point=ORIGIN, rate_func=linear, ), Rotate(Square(side_length=0.5), angle=2*PI, rate_func=linear), ) See also -------- :class:`~.Rotating`, :meth:`~.Mobject.rotate` """ def __init__( self, mobject: Mobject, angle: float = PI, axis: np.ndarray = OUT, about_point: Sequence[float] | None = None, about_edge: Sequence[float] | None = None, **kwargs: Any, ) -> None: if "path_arc" not in kwargs: kwargs["path_arc"] = angle if "path_arc_axis" not in kwargs: kwargs["path_arc_axis"] = axis self.angle = angle self.axis = axis self.about_edge = about_edge self.about_point = about_point if self.about_point is None: self.about_point = mobject.get_center() super().__init__(mobject, path_arc_centers=self.about_point, **kwargs) def create_target(self) ->
|
| None = None, **kwargs: Any, ) -> None: if "path_arc" not in kwargs: kwargs["path_arc"] = angle if "path_arc_axis" not in kwargs: kwargs["path_arc_axis"] = axis self.angle = angle self.axis = axis self.about_edge = about_edge self.about_point = about_point if self.about_point is None: self.about_point = mobject.get_center() super().__init__(mobject, path_arc_centers=self.about_point, **kwargs) def create_target(self) -> Mobject: target = self.mobject.copy() target.rotate( self.angle, axis=self.axis, about_point=self.about_point, about_edge=self.about_edge, ) return target ================================================ FILE: manim/animation/specialized.py ================================================ from __future__ import annotations __all__ = ["Broadcast"] from collections.abc import Sequence from typing import Any from manim.animation.transform import Restore from manim.mobject.mobject import Mobject from ..constants import * from .composition import LaggedStart class Broadcast(LaggedStart): """Broadcast a mobject starting from an ``initial_width``, up to the actual size of the mobject. Parameters ---------- mobject The mobject to be broadcast. focal_point The center of the broadcast, by default ORIGIN. n_mobs The number of mobjects that emerge from the focal point, by default 5. initial_opacity The starting stroke opacity of the mobjects emitted from the broadcast, by default 1. final_opacity The final stroke opacity of the mobjects emitted from the broadcast, by default 0. initial_width The initial width of the mobjects, by default 0.0. remover Whether the mobjects should be removed from the scene after the animation, by default True. lag_ratio The time between each iteration of the mobject, by default 0.2. run_time The total duration of the animation, by default 3. kwargs Additional arguments to be passed to :class:`~.LaggedStart`. Examples --------- .. manim:: BroadcastExample class BroadcastExample(Scene): def construct(self): mob = Circle(radius=4, color=TEAL_A) self.play(Broadcast(mob)) """ def __init__( self, mobject: Mobject, focal_point: Sequence[float] = ORIGIN, n_mobs: int = 5, initial_opacity: float = 1, final_opacity: float = 0, initial_width: float = 0.0, remover: bool = True, lag_ratio: float = 0.2, run_time: float = 3, **kwargs: Any, ): self.focal_point = focal_point self.n_mobs = n_mobs self.initial_opacity = initial_opacity self.final_opacity = final_opacity self.initial_width = initial_width anims = [] # Works by saving the mob that is passed into the animation, scaling it to 0 (or the initial_width) and then restoring the original mob. fill_o = bool(mobject.fill_opacity) for _ in range(self.n_mobs): mob = mobject.copy() if fill_o: mob.set_opacity(self.final_opacity) else: mob.set_stroke(opacity=self.final_opacity) mob.move_to(self.focal_point) mob.save_state() mob.set(width=self.initial_width) if fill_o: mob.set_opacity(self.initial_opacity) else: mob.set_stroke(opacity=self.initial_opacity) anims.append(Restore(mob, remover=remover)) super().__init__(*anims, run_time=run_time, lag_ratio=lag_ratio, **kwargs) ================================================ FILE: manim/animation/speedmodifier.py ================================================ """Utilities for modifying the speed at which animations are played.""" from __future__ import annotations import inspect import types from collections.abc import Callable from typing import TYPE_CHECKING from numpy import piecewise from ..animation.animation import Animation, Wait, prepare_animation from ..animation.composition import AnimationGroup from ..mobject.mobject import Mobject, _AnimationBuilder from ..scene.scene import Scene if TYPE_CHECKING: from ..mobject.mobject import Updater __all__ = ["ChangeSpeed"] class ChangeSpeed(Animation): """Modifies the speed of passed animation. :class:`AnimationGroup` with different ``lag_ratio`` can also be used which combines multiple animations into one. The ``run_time`` of the passed animation is changed to modify the speed. Parameters ---------- anim Animation of which the speed is to be modified. speedinfo Contains nodes (percentage of ``run_time``) and its corresponding speed factor. rate_func Overrides ``rate_func`` of passed animation, applied before changing speed. Examples -------- .. manim:: SpeedModifierExample class SpeedModifierExample(Scene): def construct(self): a = Dot().shift(LEFT *
|
to modify the speed. Parameters ---------- anim Animation of which the speed is to be modified. speedinfo Contains nodes (percentage of ``run_time``) and its corresponding speed factor. rate_func Overrides ``rate_func`` of passed animation, applied before changing speed. Examples -------- .. manim:: SpeedModifierExample class SpeedModifierExample(Scene): def construct(self): a = Dot().shift(LEFT * 4) b = Dot().shift(RIGHT * 4) self.add(a, b) self.play( ChangeSpeed( AnimationGroup( a.animate(run_time=1).shift(RIGHT * 8), b.animate(run_time=1).shift(LEFT * 8), ), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}, rate_func=linear, ) ) .. manim:: SpeedModifierUpdaterExample class SpeedModifierUpdaterExample(Scene): def construct(self): a = Dot().shift(LEFT * 4) self.add(a) ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt)) self.play( ChangeSpeed( Wait(2), speedinfo={0.4: 1, 0.5: 0.2, 0.8: 0.2, 1: 1}, affects_speed_updaters=True, ) ) .. manim:: SpeedModifierUpdaterExample2 class SpeedModifierUpdaterExample2(Scene): def construct(self): a = Dot().shift(LEFT * 4) self.add(a) ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt)) self.wait() self.play( ChangeSpeed( Wait(), speedinfo={1: 0}, affects_speed_updaters=True, ) ) """ dt = 0 is_changing_dt = False def __init__( self, anim: Animation | _AnimationBuilder, speedinfo: dict[float, float], rate_func: Callable[[float], float] | None = None, affects_speed_updaters: bool = True, **kwargs, ) -> None: if issubclass(type(anim), AnimationGroup): self.anim = type(anim)( *map(self.setup, anim.animations), group=anim.group, run_time=anim.run_time, rate_func=anim.rate_func, lag_ratio=anim.lag_ratio, ) else: self.anim = self.setup(anim) if affects_speed_updaters: assert ChangeSpeed.is_changing_dt is False, ( "Only one animation at a time can play that changes speed (dt) for ChangeSpeed updaters" ) ChangeSpeed.is_changing_dt = True self.t = 0 self.affects_speed_updaters = affects_speed_updaters self.rate_func = self.anim.rate_func if rate_func is None else rate_func # A function where, f(0) = 0, f'(0) = initial speed, f'( f-1(1) ) = final speed # Following function obtained when conditions applied to vertical parabola self.speed_modifier = lambda x, init_speed, final_speed: ( (final_speed**2 - init_speed**2) * x**2 / 4 + init_speed * x ) # f-1(1), returns x for which f(x) = 1 in `speed_modifier` function self.f_inv_1 = lambda init_speed, final_speed: 2 / (init_speed + final_speed) # if speed factors for the starting node (0) and the final node (1) are # not set, set them to 1 and the penultimate factor, respectively if 0 not in speedinfo: speedinfo[0] = 1 if 1 not in speedinfo: speedinfo[1] = sorted(speedinfo.items())[-1][1] self.speedinfo = dict(sorted(speedinfo.items())) self.functions = [] self.conditions = [] # Get the time taken by amimation if `run_time` is assumed to be 1 scaled_total_time = self.get_scaled_total_time() prevnode = 0 init_speed = self.speedinfo[0] curr_time = 0 for node, final_speed in list(self.speedinfo.items())[1:]: dur = node - prevnode def condition( t, curr_time=curr_time, init_speed=init_speed, final_speed=final_speed, dur=dur, ): lower_bound = curr_time / scaled_total_time upper_bound = ( curr_time + self.f_inv_1(init_speed, final_speed) * dur ) / scaled_total_time return lower_bound <= t <= upper_bound self.conditions.append(condition) def function( t, curr_time=curr_time, init_speed=init_speed, final_speed=final_speed, dur=dur, prevnode=prevnode, ): return ( self.speed_modifier( (scaled_total_time * t - curr_time) / dur, init_speed, final_speed, ) * dur + prevnode ) self.functions.append(function) curr_time += self.f_inv_1(init_speed, final_speed) * dur prevnode = node init_speed = final_speed def func(t): if t == 1: ChangeSpeed.is_changing_dt = False new_t = piecewise( self.rate_func(t), [condition(self.rate_func(t)) for condition in self.conditions], self.functions, ) if self.affects_speed_updaters: ChangeSpeed.dt = (new_t - self.t) * self.anim.run_time self.t = new_t return new_t self.anim.set_rate_func(func) super().__init__(
|
) self.functions.append(function) curr_time += self.f_inv_1(init_speed, final_speed) * dur prevnode = node init_speed = final_speed def func(t): if t == 1: ChangeSpeed.is_changing_dt = False new_t = piecewise( self.rate_func(t), [condition(self.rate_func(t)) for condition in self.conditions], self.functions, ) if self.affects_speed_updaters: ChangeSpeed.dt = (new_t - self.t) * self.anim.run_time self.t = new_t return new_t self.anim.set_rate_func(func) super().__init__( self.anim.mobject, rate_func=self.rate_func, run_time=scaled_total_time * self.anim.run_time, **kwargs, ) def setup(self, anim): if type(anim) is Wait: anim.interpolate = types.MethodType( lambda self, alpha: self.rate_func(alpha), anim ) return prepare_animation(anim) def get_scaled_total_time(self) -> float: """The time taken by the animation under the assumption that the ``run_time`` is 1.""" prevnode = 0 init_speed = self.speedinfo[0] total_time = 0 for node, final_speed in list(self.speedinfo.items())[1:]: dur = node - prevnode total_time += dur * self.f_inv_1(init_speed, final_speed) prevnode = node init_speed = final_speed return total_time @classmethod def add_updater( cls, mobject: Mobject, update_function: Updater, index: int | None = None, call_updater: bool = False, ): """This static method can be used to apply speed change to updaters. This updater will follow speed and rate function of any :class:`.ChangeSpeed` animation that is playing with ``affects_speed_updaters=True``. By default, updater functions added via the usual :meth:`.Mobject.add_updater` method do not respect the change of animation speed. Parameters ---------- mobject The mobject to which the updater should be attached. update_function The function that is called whenever a new frame is rendered. index The position in the list of the mobject's updaters at which the function should be inserted. call_updater If ``True``, calls the update function when attaching it to the mobject. See also -------- :class:`.ChangeSpeed` :meth:`.Mobject.add_updater` """ if "dt" in inspect.signature(update_function).parameters: mobject.add_updater( lambda mob, dt: update_function( mob, ChangeSpeed.dt if ChangeSpeed.is_changing_dt else dt ), index=index, call_updater=call_updater, ) else: mobject.add_updater(update_function, index=index, call_updater=call_updater) def interpolate(self, alpha: float) -> None: self.anim.interpolate(alpha) def update_mobjects(self, dt: float) -> None: self.anim.update_mobjects(dt) def finish(self) -> None: ChangeSpeed.is_changing_dt = False self.anim.finish() def begin(self) -> None: self.anim.begin() def clean_up_from_scene(self, scene: Scene) -> None: self.anim.clean_up_from_scene(scene) def _setup_scene(self, scene) -> None: self.anim._setup_scene(scene) ================================================ FILE: manim/animation/transform.py ================================================ """Animations transforming one mobject into another.""" from __future__ import annotations __all__ = [ "Transform", "ReplacementTransform", "TransformFromCopy", "ClockwiseTransform", "CounterclockwiseTransform", "MoveToTarget", "ApplyMethod", "ApplyPointwiseFunction", "ApplyPointwiseFunctionToCenter", "FadeToColor", "FadeTransform", "FadeTransformPieces", "ScaleInPlace", "ShrinkToCenter", "Restore", "ApplyFunction", "ApplyMatrix", "ApplyComplexFunction", "CyclicReplace", "Swap", "TransformAnimations", ] import inspect import types from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING, Any import numpy as np from manim.data_structures import MethodWithArgs from manim.mobject.opengl.opengl_mobject import OpenGLGroup, OpenGLMobject from .. import config from ..animation.animation import Animation from ..constants import ( DEFAULT_POINTWISE_FUNCTION_RUN_TIME, DEGREES, ORIGIN, OUT, RendererType, ) from ..mobject.mobject import Group, Mobject from ..utils.paths import path_along_arc, path_along_circles from ..utils.rate_functions import smooth, squish_rate_func if TYPE_CHECKING: from ..scene.scene import Scene class Transform(Animation): """A Transform transforms a Mobject into a target Mobject. Parameters ---------- mobject The :class:`.Mobject` to be transformed. It will be mutated to become the ``target_mobject``. target_mobject The target of the transformation. path_func A function defining the path that the points of the ``mobject`` are being moved along until they match the points of the ``target_mobject``, see :mod:`.utils.paths`. path_arc The arc angle (in radians) that the points of ``mobject`` will follow to reach the points of the target
|
target of the transformation. path_func A function defining the path that the points of the ``mobject`` are being moved along until they match the points of the ``target_mobject``, see :mod:`.utils.paths`. path_arc The arc angle (in radians) that the points of ``mobject`` will follow to reach the points of the target if using a circular path arc, see ``path_arc_centers``. See also :func:`manim.utils.paths.path_along_arc`. path_arc_axis The axis to rotate along if using a circular path arc, see ``path_arc_centers``. path_arc_centers The center of the circular arcs along which the points of ``mobject`` are moved by the transformation. If this is set and ``path_func`` is not set, then a ``path_along_circles`` path will be generated using the ``path_arc`` parameters and stored in ``path_func``. If ``path_func`` is set, this and the other ``path_arc`` fields are set as attributes, but a ``path_func`` is not generated from it. replace_mobject_with_target_in_scene Controls which mobject is replaced when the transformation is complete. If set to True, ``mobject`` will be removed from the scene and ``target_mobject`` will replace it. Otherwise, ``target_mobject`` is never added and ``mobject`` just takes its shape. Examples -------- .. manim :: TransformPathArc class TransformPathArc(Scene): def construct(self): def make_arc_path(start, end, arc_angle): points = [] p_fn = path_along_arc(arc_angle) # alpha animates between 0.0 and 1.0, where 0.0 # is the beginning of the animation and 1.0 is the end. for alpha in range(0, 11): points.append(p_fn(start, end, alpha / 10.0)) path = VMobject(stroke_color=YELLOW) path.set_points_smoothly(points) return path left = Circle(stroke_color=BLUE_E, fill_opacity=1.0, radius=0.5).move_to(LEFT * 2) colors = [TEAL_A, TEAL_B, TEAL_C, TEAL_D, TEAL_E, GREEN_A] # Positive angles move counter-clockwise, negative angles move clockwise. examples = [-90, 0, 30, 90, 180, 270] anims = [] for idx, angle in enumerate(examples): left_c = left.copy().shift((3 - idx) * UP) left_c.fill_color = colors[idx] right_c = left_c.copy().shift(4 * RIGHT) path_arc = make_arc_path(left_c.get_center(), right_c.get_center(), arc_angle=angle * DEGREES) desc = Text('%d°' % examples[idx]).next_to(left_c, LEFT) # Make the circlesin front of the text in front of the arcs. self.add( path_arc.set_z_index(1), desc.set_z_index(2), left_c.set_z_index(3), ) anims.append(Transform(left_c, right_c, path_arc=angle * DEGREES)) self.play(*anims, run_time=2) self.wait() See also -------- :class:`~.ReplacementTransform`, :meth:`~.Mobject.interpolate`, :meth:`~.Mobject.align_data` """ def __init__( self, mobject: Mobject | None, target_mobject: Mobject | None = None, path_func: Callable | None = None, path_arc: float = 0, path_arc_axis: np.ndarray = OUT, path_arc_centers: np.ndarray = None, replace_mobject_with_target_in_scene: bool = False, **kwargs, ) -> None: self.path_arc_axis: np.ndarray = path_arc_axis self.path_arc_centers: np.ndarray = path_arc_centers self.path_arc: float = path_arc # path_func is a property a few lines below so it doesn't need to be set in any case if path_func is not None: self.path_func: Callable = path_func elif self.path_arc_centers is not None: self.path_func = path_along_circles( path_arc, self.path_arc_centers, self.path_arc_axis, ) self.replace_mobject_with_target_in_scene: bool = ( replace_mobject_with_target_in_scene ) self.target_mobject: Mobject = ( target_mobject if target_mobject is not None else Mobject() ) super().__init__(mobject, **kwargs) @property def path_arc(self) -> float: return self._path_arc @path_arc.setter def path_arc(self, path_arc: float) -> None: self._path_arc = path_arc self._path_func = path_along_arc( arc_angle=self._path_arc, axis=self.path_arc_axis, ) @property def path_func( self, ) -> Callable[ [Iterable[np.ndarray], Iterable[np.ndarray], float], Iterable[np.ndarray], ]: return self._path_func @path_func.setter def path_func( self, path_func: Callable[ [Iterable[np.ndarray], Iterable[np.ndarray], float], Iterable[np.ndarray], ], ) -> None: if path_func
|
-> float: return self._path_arc @path_arc.setter def path_arc(self, path_arc: float) -> None: self._path_arc = path_arc self._path_func = path_along_arc( arc_angle=self._path_arc, axis=self.path_arc_axis, ) @property def path_func( self, ) -> Callable[ [Iterable[np.ndarray], Iterable[np.ndarray], float], Iterable[np.ndarray], ]: return self._path_func @path_func.setter def path_func( self, path_func: Callable[ [Iterable[np.ndarray], Iterable[np.ndarray], float], Iterable[np.ndarray], ], ) -> None: if path_func is not None: self._path_func = path_func def begin(self) -> None: # Use a copy of target_mobject for the align_data # call so that the actual target_mobject stays # preserved. self.target_mobject = self.create_target() self.target_copy = self.target_mobject.copy() # Note, this potentially changes the structure # of both mobject and target_mobject if config.renderer == RendererType.OPENGL: self.mobject.align_data_and_family(self.target_copy) else: self.mobject.align_data(self.target_copy) super().begin() def create_target(self) -> Mobject | OpenGLMobject: # Has no meaningful effect here, but may be useful # in subclasses return self.target_mobject def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) if self.replace_mobject_with_target_in_scene: scene.replace(self.mobject, self.target_mobject) def get_all_mobjects(self) -> Sequence[Mobject]: return [ self.mobject, self.starting_mobject, self.target_mobject, self.target_copy, ] def get_all_families_zipped(self) -> Iterable[tuple]: # more precise typing? mobs = [ self.mobject, self.starting_mobject, self.target_copy, ] if config.renderer == RendererType.OPENGL: return zip(*(mob.get_family() for mob in mobs)) return zip(*(mob.family_members_with_points() for mob in mobs)) def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, target_copy: Mobject, alpha: float, ) -> Transform: submobject.interpolate(starting_submobject, target_copy, alpha, self.path_func) return self class ReplacementTransform(Transform): """Replaces and morphs a mobject into a target mobject. Parameters ---------- mobject The starting :class:`~.Mobject`. target_mobject The target :class:`~.Mobject`. kwargs Further keyword arguments that are passed to :class:`Transform`. Examples -------- .. manim:: ReplacementTransformOrTransform :quality: low class ReplacementTransformOrTransform(Scene): def construct(self): # set up the numbers r_transform = VGroup(*[Integer(i) for i in range(1,4)]) text_1 = Text("ReplacementTransform", color=RED) r_transform.add(text_1) transform = VGroup(*[Integer(i) for i in range(4,7)]) text_2 = Text("Transform", color=BLUE) transform.add(text_2) ints = VGroup(r_transform, transform) texts = VGroup(text_1, text_2).scale(0.75) r_transform.arrange(direction=UP, buff=1) transform.arrange(direction=UP, buff=1) ints.arrange(buff=2) self.add(ints, texts) # The mobs replace each other and none are left behind self.play(ReplacementTransform(r_transform[0], r_transform[1])) self.play(ReplacementTransform(r_transform[1], r_transform[2])) # The mobs linger after the Transform() self.play(Transform(transform[0], transform[1])) self.play(Transform(transform[1], transform[2])) self.wait() """ def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None: super().__init__( mobject, target_mobject, replace_mobject_with_target_in_scene=True, **kwargs ) class TransformFromCopy(Transform): """Performs a reversed Transform""" def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None: super().__init__(target_mobject, mobject, **kwargs) def interpolate(self, alpha: float) -> None: super().interpolate(1 - alpha) class ClockwiseTransform(Transform): """Transforms the points of a mobject along a clockwise oriented arc. See also -------- :class:`.Transform`, :class:`.CounterclockwiseTransform` Examples -------- .. manim:: ClockwiseExample class ClockwiseExample(Scene): def construct(self): dl, dr = Dot(), Dot() sl, sr = Square(), Square() VGroup(dl, sl).arrange(DOWN).shift(2*LEFT) VGroup(dr, sr).arrange(DOWN).shift(2*RIGHT) self.add(dl, dr) self.wait() self.play( ClockwiseTransform(dl, sl), Transform(dr, sr) ) self.wait() """ def __init__( self, mobject: Mobject, target_mobject: Mobject, path_arc: float = -np.pi, **kwargs, ) -> None: super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs) class CounterclockwiseTransform(Transform): """Transforms the points of a mobject along a counterclockwise oriented arc. See also -------- :class:`.Transform`, :class:`.ClockwiseTransform` Examples -------- .. manim:: CounterclockwiseTransform_vs_Transform class CounterclockwiseTransform_vs_Transform(Scene): def construct(self): # set up the numbers c_transform = VGroup(DecimalNumber(number=3.141, num_decimal_places=3), DecimalNumber(number=1.618, num_decimal_places=3)) text_1 = Text("CounterclockwiseTransform", color=RED) c_transform.add(text_1) transform = VGroup(DecimalNumber(number=1.618, num_decimal_places=3), DecimalNumber(number=3.141, num_decimal_places=3)) text_2 = Text("Transform", color=BLUE) transform.add(text_2) ints = VGroup(c_transform, transform) texts = VGroup(text_1, text_2).scale(0.75) c_transform.arrange(direction=UP, buff=1) transform.arrange(direction=UP, buff=1) ints.arrange(buff=2) self.add(ints, texts) # The mobs move in
|
CounterclockwiseTransform_vs_Transform(Scene): def construct(self): # set up the numbers c_transform = VGroup(DecimalNumber(number=3.141, num_decimal_places=3), DecimalNumber(number=1.618, num_decimal_places=3)) text_1 = Text("CounterclockwiseTransform", color=RED) c_transform.add(text_1) transform = VGroup(DecimalNumber(number=1.618, num_decimal_places=3), DecimalNumber(number=3.141, num_decimal_places=3)) text_2 = Text("Transform", color=BLUE) transform.add(text_2) ints = VGroup(c_transform, transform) texts = VGroup(text_1, text_2).scale(0.75) c_transform.arrange(direction=UP, buff=1) transform.arrange(direction=UP, buff=1) ints.arrange(buff=2) self.add(ints, texts) # The mobs move in clockwise direction for ClockwiseTransform() self.play(CounterclockwiseTransform(c_transform[0], c_transform[1])) # The mobs move straight up for Transform() self.play(Transform(transform[0], transform[1])) """ def __init__( self, mobject: Mobject, target_mobject: Mobject, path_arc: float = np.pi, **kwargs, ) -> None: super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs) class MoveToTarget(Transform): """Transforms a mobject to the mobject stored in its ``target`` attribute. After calling the :meth:`~.Mobject.generate_target` method, the :attr:`target` attribute of the mobject is populated with a copy of it. After modifying the attribute, playing the :class:`.MoveToTarget` animation transforms the original mobject into the modified one stored in the :attr:`target` attribute. Examples -------- .. manim:: MoveToTargetExample class MoveToTargetExample(Scene): def construct(self): c = Circle() c.generate_target() c.target.set_fill(color=GREEN, opacity=0.5) c.target.shift(2*RIGHT + UP).scale(0.5) self.add(c) self.play(MoveToTarget(c)) """ def __init__(self, mobject: Mobject, **kwargs) -> None: self.check_validity_of_input(mobject) super().__init__(mobject, mobject.target, **kwargs) def check_validity_of_input(self, mobject: Mobject) -> None: if not hasattr(mobject, "target"): raise ValueError( "MoveToTarget called on mobjectwithout attribute 'target'", ) class _MethodAnimation(MoveToTarget): def __init__(self, mobject: Mobject, methods: list[MethodWithArgs]) -> None: self.methods = methods super().__init__(mobject) def finish(self) -> None: for item in self.methods: item.method.__func__(self.mobject, *item.args, **item.kwargs) super().finish() class ApplyMethod(Transform): """Animates a mobject by applying a method. Note that only the method needs to be passed to this animation, it is not required to pass the corresponding mobject. Furthermore, this animation class only works if the method returns the modified mobject. Parameters ---------- method The method that will be applied in the animation. args Any positional arguments to be passed when applying the method. kwargs Any keyword arguments passed to :class:`~.Transform`. """ def __init__( self, method: Callable, *args, **kwargs ) -> None: # method typing (we want to specify Mobject method)? for args? self.check_validity_of_input(method) self.method = method self.method_args = args super().__init__(method.__self__, **kwargs) def check_validity_of_input(self, method: Callable) -> None: if not inspect.ismethod(method): raise ValueError( "Whoops, looks like you accidentally invoked " "the method you want to animate", ) assert isinstance(method.__self__, (Mobject, OpenGLMobject)) def create_target(self) -> Mobject: method = self.method # Make sure it's a list so that args.pop() works args = list(self.method_args) if len(args) > 0 and isinstance(args[-1], dict): method_kwargs = args.pop() else: method_kwargs = {} target = method.__self__.copy() method.__func__(target, *args, **method_kwargs) return target class ApplyPointwiseFunction(ApplyMethod): """Animation that applies a pointwise function to a mobject. Examples -------- .. manim:: WarpSquare :quality: low class WarpSquare(Scene): def construct(self): square = Square() self.play( ApplyPointwiseFunction( lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square ) ) self.wait() """ def __init__( self, function: types.MethodType, mobject: Mobject, run_time: float = DEFAULT_POINTWISE_FUNCTION_RUN_TIME, **kwargs, ) -> None: super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs) class ApplyPointwiseFunctionToCenter(ApplyPointwiseFunction): def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None: self.function = function super().__init__(mobject.move_to, **kwargs) def begin(self) -> None: self.method_args = [self.function(self.mobject.get_center())] super().begin() class FadeToColor(ApplyMethod): """Animation that changes color of a mobject. Examples -------- .. manim:: FadeToColorExample class FadeToColorExample(Scene): def construct(self): self.play(FadeToColor(Text("Hello World!"), color=RED)) """ def __init__(self, mobject: Mobject, color: str, **kwargs) -> None: super().__init__(mobject.set_color,
|
mobject: Mobject, **kwargs) -> None: self.function = function super().__init__(mobject.move_to, **kwargs) def begin(self) -> None: self.method_args = [self.function(self.mobject.get_center())] super().begin() class FadeToColor(ApplyMethod): """Animation that changes color of a mobject. Examples -------- .. manim:: FadeToColorExample class FadeToColorExample(Scene): def construct(self): self.play(FadeToColor(Text("Hello World!"), color=RED)) """ def __init__(self, mobject: Mobject, color: str, **kwargs) -> None: super().__init__(mobject.set_color, color, **kwargs) class ScaleInPlace(ApplyMethod): """Animation that scales a mobject by a certain factor. Examples -------- .. manim:: ScaleInPlaceExample class ScaleInPlaceExample(Scene): def construct(self): self.play(ScaleInPlace(Text("Hello World!"), 2)) """ def __init__(self, mobject: Mobject, scale_factor: float, **kwargs) -> None: super().__init__(mobject.scale, scale_factor, **kwargs) class ShrinkToCenter(ScaleInPlace): """Animation that makes a mobject shrink to center. Examples -------- .. manim:: ShrinkToCenterExample class ShrinkToCenterExample(Scene): def construct(self): self.play(ShrinkToCenter(Text("Hello World!"))) """ def __init__(self, mobject: Mobject, **kwargs) -> None: super().__init__(mobject, 0, **kwargs) class Restore(ApplyMethod): """Transforms a mobject to its last saved state. To save the state of a mobject, use the :meth:`~.Mobject.save_state` method. Examples -------- .. manim:: RestoreExample class RestoreExample(Scene): def construct(self): s = Square() s.save_state() self.play(FadeIn(s)) self.play(s.animate.set_color(PURPLE).set_opacity(0.5).shift(2*LEFT).scale(3)) self.play(s.animate.shift(5*DOWN).rotate(PI/4)) self.wait() self.play(Restore(s), run_time=2) """ def __init__(self, mobject: Mobject, **kwargs) -> None: super().__init__(mobject.restore, **kwargs) class ApplyFunction(Transform): def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None: self.function = function super().__init__(mobject, **kwargs) def create_target(self) -> Any: target = self.function(self.mobject.copy()) if not isinstance(target, (Mobject, OpenGLMobject)): raise TypeError( "Functions passed to ApplyFunction must return object of type Mobject", ) return target class ApplyMatrix(ApplyPointwiseFunction): """Applies a matrix transform to an mobject. Parameters ---------- matrix The transformation matrix. mobject The :class:`~.Mobject`. about_point The origin point for the transform. Defaults to ``ORIGIN``. kwargs Further keyword arguments that are passed to :class:`ApplyPointwiseFunction`. Examples -------- .. manim:: ApplyMatrixExample class ApplyMatrixExample(Scene): def construct(self): matrix = [[1, 1], [0, 2/3]] self.play(ApplyMatrix(matrix, Text("Hello World!")), ApplyMatrix(matrix, NumberPlane())) """ def __init__( self, matrix: np.ndarray, mobject: Mobject, about_point: np.ndarray = ORIGIN, **kwargs, ) -> None: matrix = self.initialize_matrix(matrix) def func(p): return np.dot(p - about_point, matrix.T) + about_point super().__init__(func, mobject, **kwargs) def initialize_matrix(self, matrix: np.ndarray) -> np.ndarray: matrix = np.array(matrix) if matrix.shape == (2, 2): new_matrix = np.identity(3) new_matrix[:2, :2] = matrix matrix = new_matrix elif matrix.shape != (3, 3): raise ValueError("Matrix has bad dimensions") return matrix class ApplyComplexFunction(ApplyMethod): def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None: self.function = function method = mobject.apply_complex_function super().__init__(method, function, **kwargs) def _init_path_func(self) -> None: func1 = self.function(complex(1)) self.path_arc = np.log(func1).imag super()._init_path_func() ### class CyclicReplace(Transform): """An animation moving mobjects cyclically. In particular, this means: the first mobject takes the place of the second mobject, the second one takes the place of the third mobject, and so on. The last mobject takes the place of the first one. Parameters ---------- mobjects List of mobjects to be transformed. path_arc The angle of the arc (in radians) that the mobjects will follow to reach their target. kwargs Further keyword arguments that are passed to :class:`.Transform`. Examples -------- .. manim :: CyclicReplaceExample class CyclicReplaceExample(Scene): def construct(self): group = VGroup(Square(), Circle(), Triangle(), Star()) group.arrange(RIGHT) self.add(group) for _ in range(4): self.play(CyclicReplace(*group)) """ def __init__( self, *mobjects: Mobject, path_arc: float = 90 * DEGREES, **kwargs ) -> None: self.group = Group(*mobjects) super().__init__(self.group, path_arc=path_arc, **kwargs) def create_target(self) -> Group: target = self.group.copy()
|
.. manim :: CyclicReplaceExample class CyclicReplaceExample(Scene): def construct(self): group = VGroup(Square(), Circle(), Triangle(), Star()) group.arrange(RIGHT) self.add(group) for _ in range(4): self.play(CyclicReplace(*group)) """ def __init__( self, *mobjects: Mobject, path_arc: float = 90 * DEGREES, **kwargs ) -> None: self.group = Group(*mobjects) super().__init__(self.group, path_arc=path_arc, **kwargs) def create_target(self) -> Group: target = self.group.copy() cycled_targets = [target[-1], *target[:-1]] for m1, m2 in zip(cycled_targets, self.group): m1.move_to(m2) return target class Swap(CyclicReplace): pass # Renaming, more understandable for two entries # TODO, this may be deprecated...worth reimplementing? class TransformAnimations(Transform): def __init__( self, start_anim: Animation, end_anim: Animation, rate_func: Callable = squish_rate_func(smooth), **kwargs, ) -> None: self.start_anim = start_anim self.end_anim = end_anim if "run_time" in kwargs: self.run_time = kwargs.pop("run_time") else: self.run_time = max(start_anim.run_time, end_anim.run_time) for anim in start_anim, end_anim: anim.set_run_time(self.run_time) if ( start_anim.starting_mobject is not None and end_anim.starting_mobject is not None and start_anim.starting_mobject.get_num_points() != end_anim.starting_mobject.get_num_points() ): start_anim.starting_mobject.align_data(end_anim.starting_mobject) for anim in start_anim, end_anim: if isinstance(anim, Transform) and anim.starting_mobject is not None: anim.starting_mobject.align_data(anim.target_mobject) super().__init__( start_anim.mobject, end_anim.mobject, rate_func=rate_func, **kwargs ) # Rewire starting and ending mobjects start_anim.mobject = self.starting_mobject end_anim.mobject = self.target_mobject def interpolate(self, alpha: float) -> None: self.start_anim.interpolate(alpha) self.end_anim.interpolate(alpha) super().interpolate(alpha) class FadeTransform(Transform): """Fades one mobject into another. Parameters ---------- mobject The starting :class:`~.Mobject`. target_mobject The target :class:`~.Mobject`. stretch Controls whether the target :class:`~.Mobject` is stretched during the animation. Default: ``True``. dim_to_match If the target mobject is not stretched automatically, this allows to adjust the initial scale of the target :class:`~.Mobject` while it is shifted in. Setting this to 0, 1, and 2, respectively, matches the length of the target with the length of the starting :class:`~.Mobject` in x, y, and z direction, respectively. kwargs Further keyword arguments are passed to the parent class. Examples -------- .. manim:: DifferentFadeTransforms class DifferentFadeTransforms(Scene): def construct(self): starts = [Rectangle(width=4, height=1) for _ in range(3)] VGroup(*starts).arrange(DOWN, buff=1).shift(3*LEFT) targets = [Circle(fill_opacity=1).scale(0.25) for _ in range(3)] VGroup(*targets).arrange(DOWN, buff=1).shift(3*RIGHT) self.play(*[FadeIn(s) for s in starts]) self.play( FadeTransform(starts[0], targets[0], stretch=True), FadeTransform(starts[1], targets[1], stretch=False, dim_to_match=0), FadeTransform(starts[2], targets[2], stretch=False, dim_to_match=1) ) self.play(*[FadeOut(mobj) for mobj in self.mobjects]) """ def __init__(self, mobject, target_mobject, stretch=True, dim_to_match=1, **kwargs): self.to_add_on_completion = target_mobject self.stretch = stretch self.dim_to_match = dim_to_match mobject.save_state() if config.renderer == RendererType.OPENGL: group = OpenGLGroup(mobject, target_mobject.copy()) else: group = Group(mobject, target_mobject.copy()) super().__init__(group, **kwargs) def begin(self): """Initial setup for the animation. The mobject to which this animation is bound is a group consisting of both the starting and the ending mobject. At the start, the ending mobject replaces the starting mobject (and is completely faded). In the end, it is set to be the other way around. """ self.ending_mobject = self.mobject.copy() Animation.begin(self) # Both 'start' and 'end' consists of the source and target mobjects. # At the start, the target should be faded replacing the source, # and at the end it should be the other way around. start, end = self.starting_mobject, self.ending_mobject for m0, m1 in ((start[1], start[0]), (end[0], end[1])): self.ghost_to(m0, m1) def ghost_to(self, source, target): """Replaces the source by the target and sets the opacity to 0. If the provided target has no points, and thus a location of [0, 0, 0] the source will simply
|
start, end = self.starting_mobject, self.ending_mobject for m0, m1 in ((start[1], start[0]), (end[0], end[1])): self.ghost_to(m0, m1) def ghost_to(self, source, target): """Replaces the source by the target and sets the opacity to 0. If the provided target has no points, and thus a location of [0, 0, 0] the source will simply fade out where it currently is. """ # mobject.replace() does not work if the target has no points. if target.get_num_points() or target.submobjects: source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match) source.set_opacity(0) def get_all_mobjects(self) -> Sequence[Mobject]: return [ self.mobject, self.starting_mobject, self.ending_mobject, ] def get_all_families_zipped(self): return Animation.get_all_families_zipped(self) def clean_up_from_scene(self, scene): Animation.clean_up_from_scene(self, scene) scene.remove(self.mobject) self.mobject[0].restore() scene.add(self.to_add_on_completion) class FadeTransformPieces(FadeTransform): """Fades submobjects of one mobject into submobjects of another one. See also -------- :class:`~.FadeTransform` Examples -------- .. manim:: FadeTransformSubmobjects class FadeTransformSubmobjects(Scene): def construct(self): src = VGroup(Square(), Circle().shift(LEFT + UP)) src.shift(3*LEFT + 2*UP) src_copy = src.copy().shift(4*DOWN) target = VGroup(Circle(), Triangle().shift(RIGHT + DOWN)) target.shift(3*RIGHT + 2*UP) target_copy = target.copy().shift(4*DOWN) self.play(FadeIn(src), FadeIn(src_copy)) self.play( FadeTransform(src, target), FadeTransformPieces(src_copy, target_copy) ) self.play(*[FadeOut(mobj) for mobj in self.mobjects]) """ def begin(self): self.mobject[0].align_submobjects(self.mobject[1]) super().begin() def ghost_to(self, source, target): """Replaces the source submobjects by the target submobjects and sets the opacity to 0. """ for sm0, sm1 in zip(source.get_family(), target.get_family()): super().ghost_to(sm0, sm1) ================================================ FILE: manim/animation/transform_matching_parts.py ================================================ """Animations that try to transform Mobjects while keeping track of identical parts.""" from __future__ import annotations __all__ = ["TransformMatchingShapes", "TransformMatchingTex"] from typing import TYPE_CHECKING import numpy as np from manim.mobject.opengl.opengl_mobject import OpenGLGroup, OpenGLMobject from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVGroup, OpenGLVMobject from .._config import config from ..constants import RendererType from ..mobject.mobject import Group, Mobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from .composition import AnimationGroup from .fading import FadeIn, FadeOut from .transform import FadeTransformPieces, Transform if TYPE_CHECKING: from ..scene.scene import Scene class TransformMatchingAbstractBase(AnimationGroup): """Abstract base class for transformations that keep track of matching parts. Subclasses have to implement the two static methods :meth:`~.TransformMatchingAbstractBase.get_mobject_parts` and :meth:`~.TransformMatchingAbstractBase.get_mobject_key`. Basically, this transformation first maps all submobjects returned by the ``get_mobject_parts`` method to certain keys by applying the ``get_mobject_key`` method. Then, submobjects with matching keys are transformed into each other. Parameters ---------- mobject The starting :class:`~.Mobject`. target_mobject The target :class:`~.Mobject`. transform_mismatches Controls whether submobjects without a matching key are transformed into each other by using :class:`~.Transform`. Default: ``False``. fade_transform_mismatches Controls whether submobjects without a matching key are transformed into each other by using :class:`~.FadeTransform`. Default: ``False``. key_map Optional. A dictionary mapping keys belonging to some of the starting mobject's submobjects (i.e., the return values of the ``get_mobject_key`` method) to some keys belonging to the target mobject's submobjects that should be transformed although the keys don't match. kwargs All further keyword arguments are passed to the submobject transformations. Note ---- If neither ``transform_mismatches`` nor ``fade_transform_mismatches`` are set to ``True``, submobjects without matching keys in the starting mobject are faded out in the direction of the unmatched submobjects in the target mobject, and unmatched submobjects in the target mobject are faded in from the direction of the unmatched submobjects in the start mobject. """ def __init__( self, mobject: Mobject, target_mobject: Mobject, transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: dict | None = None, **kwargs,
|
unmatched submobjects in the target mobject, and unmatched submobjects in the target mobject are faded in from the direction of the unmatched submobjects in the start mobject. """ def __init__( self, mobject: Mobject, target_mobject: Mobject, transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: dict | None = None, **kwargs, ): if isinstance(mobject, OpenGLVMobject): group_type = OpenGLVGroup elif isinstance(mobject, OpenGLMobject): group_type = OpenGLGroup elif isinstance(mobject, VMobject): group_type = VGroup else: group_type = Group source_map = self.get_shape_map(mobject) target_map = self.get_shape_map(target_mobject) if key_map is None: key_map = {} # Create two mobjects whose submobjects all match each other # according to whatever keys are used for source_map and # target_map transform_source = group_type() transform_target = group_type() for key in set(source_map).intersection(target_map): transform_source.add(source_map[key]) transform_target.add(target_map[key]) anims = [Transform(transform_source, transform_target, **kwargs)] # User can manually specify when one part should transform # into another despite not matching by using key_map key_mapped_source = group_type() key_mapped_target = group_type() for key1, key2 in key_map.items(): if key1 in source_map and key2 in target_map: key_mapped_source.add(source_map[key1]) key_mapped_target.add(target_map[key2]) source_map.pop(key1, None) target_map.pop(key2, None) if len(key_mapped_source) > 0: anims.append( FadeTransformPieces(key_mapped_source, key_mapped_target, **kwargs), ) fade_source = group_type() fade_target = group_type() for key in set(source_map).difference(target_map): fade_source.add(source_map[key]) for key in set(target_map).difference(source_map): fade_target.add(target_map[key]) fade_target_copy = fade_target.copy() if transform_mismatches: if "replace_mobject_with_target_in_scene" not in kwargs: kwargs["replace_mobject_with_target_in_scene"] = True anims.append(Transform(fade_source, fade_target, **kwargs)) elif fade_transform_mismatches: anims.append(FadeTransformPieces(fade_source, fade_target, **kwargs)) else: anims.append(FadeOut(fade_source, target_position=fade_target, **kwargs)) anims.append( FadeIn(fade_target_copy, target_position=fade_target, **kwargs), ) super().__init__(*anims) self.to_remove = [mobject, fade_target_copy] self.to_add = target_mobject def get_shape_map(self, mobject: Mobject) -> dict: shape_map = {} for sm in self.get_mobject_parts(mobject): key = self.get_mobject_key(sm) if key not in shape_map: if config["renderer"] == RendererType.OPENGL: shape_map[key] = OpenGLVGroup() else: shape_map[key] = VGroup() shape_map[key].add(sm) return shape_map def clean_up_from_scene(self, scene: Scene) -> None: # Interpolate all animations back to 0 to ensure source mobjects remain unchanged. for anim in self.animations: anim.interpolate(0) scene.remove(self.mobject) scene.remove(*self.to_remove) scene.add(self.to_add) @staticmethod def get_mobject_parts(mobject: Mobject): raise NotImplementedError("To be implemented in subclass.") @staticmethod def get_mobject_key(mobject: Mobject): raise NotImplementedError("To be implemented in subclass.") class TransformMatchingShapes(TransformMatchingAbstractBase): """An animation trying to transform groups by matching the shape of their submobjects. Two submobjects match if the hash of their point coordinates after normalization (i.e., after translation to the origin, fixing the submobject height at 1 unit, and rounding the coordinates to three decimal places) matches. See also -------- :class:`~.TransformMatchingAbstractBase` Examples -------- .. manim:: Anagram class Anagram(Scene): def construct(self): src = Text("the morse code") tar = Text("here come dots") self.play(Write(src)) self.wait(0.5) self.play(TransformMatchingShapes(src, tar, path_arc=PI/2)) self.wait(0.5) """ def __init__( self, mobject: Mobject, target_mobject: Mobject, transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: dict | None = None, **kwargs, ): super().__init__( mobject, target_mobject, transform_mismatches=transform_mismatches, fade_transform_mismatches=fade_transform_mismatches, key_map=key_map, **kwargs, ) @staticmethod def get_mobject_parts(mobject: Mobject) -> list[Mobject]: return mobject.family_members_with_points() @staticmethod def get_mobject_key(mobject: Mobject) -> int: mobject.save_state() mobject.center() mobject.set(height=1) rounded_points = np.round(mobject.points, 3) + 0.0 result = hash(rounded_points.tobytes()) mobject.restore() return result class TransformMatchingTex(TransformMatchingAbstractBase): """A transformation trying to transform rendered LaTeX strings. Two submobjects match if their ``tex_string`` matches. See also -------- :class:`~.TransformMatchingAbstractBase` Examples -------- .. manim:: MatchingEquationParts class MatchingEquationParts(Scene): def construct(self): variables = VGroup(MathTex("a"), MathTex("b"), MathTex("c")).arrange_submobjects().shift(UP) eq1 = MathTex("{{x}}^2", "+", "{{y}}^2", "=", "{{z}}^2") eq2 = MathTex("{{a}}^2", "+", "{{b}}^2",
|
mobject.restore() return result class TransformMatchingTex(TransformMatchingAbstractBase): """A transformation trying to transform rendered LaTeX strings. Two submobjects match if their ``tex_string`` matches. See also -------- :class:`~.TransformMatchingAbstractBase` Examples -------- .. manim:: MatchingEquationParts class MatchingEquationParts(Scene): def construct(self): variables = VGroup(MathTex("a"), MathTex("b"), MathTex("c")).arrange_submobjects().shift(UP) eq1 = MathTex("{{x}}^2", "+", "{{y}}^2", "=", "{{z}}^2") eq2 = MathTex("{{a}}^2", "+", "{{b}}^2", "=", "{{c}}^2") eq3 = MathTex("{{a}}^2", "=", "{{c}}^2", "-", "{{b}}^2") self.add(eq1) self.wait(0.5) self.play(TransformMatchingTex(Group(eq1, variables), eq2)) self.wait(0.5) self.play(TransformMatchingTex(eq2, eq3)) self.wait(0.5) """ def __init__( self, mobject: Mobject, target_mobject: Mobject, transform_mismatches: bool = False, fade_transform_mismatches: bool = False, key_map: dict | None = None, **kwargs, ): super().__init__( mobject, target_mobject, transform_mismatches=transform_mismatches, fade_transform_mismatches=fade_transform_mismatches, key_map=key_map, **kwargs, ) @staticmethod def get_mobject_parts(mobject: Mobject) -> list[Mobject]: if isinstance(mobject, (Group, VGroup, OpenGLGroup, OpenGLVGroup)): return [ p for s in mobject.submobjects for p in TransformMatchingTex.get_mobject_parts(s) ] else: assert hasattr(mobject, "tex_string") return mobject.submobjects @staticmethod def get_mobject_key(mobject: Mobject) -> str: return mobject.tex_string ================================================ FILE: manim/animation/updaters/__init__.py ================================================ """Animations and utility mobjects related to update functions. Modules ======= .. autosummary:: :toctree: ../reference ~mobject_update_utils ~update """ ================================================ FILE: manim/animation/updaters/mobject_update_utils.py ================================================ """Utility functions for continuous animation of mobjects.""" from __future__ import annotations __all__ = [ "assert_is_mobject_method", "always", "f_always", "always_redraw", "always_shift", "always_rotate", "turn_animation_into_updater", "cycle_animation", ] import inspect from collections.abc import Callable from typing import TYPE_CHECKING import numpy as np from manim.constants import DEGREES, RIGHT from manim.mobject.mobject import Mobject from manim.opengl import OpenGLMobject from manim.utils.space_ops import normalize if TYPE_CHECKING: from manim.animation.animation import Animation def assert_is_mobject_method(method: Callable) -> None: assert inspect.ismethod(method) mobject = method.__self__ assert isinstance(mobject, (Mobject, OpenGLMobject)) def always(method: Callable, *args, **kwargs) -> Mobject: assert_is_mobject_method(method) mobject = method.__self__ func = method.__func__ mobject.add_updater(lambda m: func(m, *args, **kwargs)) return mobject def f_always(method: Callable[[Mobject], None], *arg_generators, **kwargs) -> Mobject: """ More functional version of always, where instead of taking in args, it takes in functions which output the relevant arguments. """ assert_is_mobject_method(method) mobject = method.__self__ func = method.__func__ def updater(mob): args = [arg_generator() for arg_generator in arg_generators] func(mob, *args, **kwargs) mobject.add_updater(updater) return mobject def always_redraw(func: Callable[[], Mobject]) -> Mobject: """Redraw the mobject constructed by a function every frame. This function returns a mobject with an attached updater that continuously regenerates the mobject according to the specified function. Parameters ---------- func A function without (required) input arguments that returns a mobject. Examples -------- .. manim:: TangentAnimation class TangentAnimation(Scene): def construct(self): ax = Axes() sine = ax.plot(np.sin, color=RED) alpha = ValueTracker(0) point = always_redraw( lambda: Dot( sine.point_from_proportion(alpha.get_value()), color=BLUE ) ) tangent = always_redraw( lambda: TangentLine( sine, alpha=alpha.get_value(), color=YELLOW, length=4 ) ) self.add(ax, sine, point, tangent) self.play(alpha.animate.set_value(1), rate_func=linear, run_time=2) """ mob = func() mob.add_updater(lambda _: mob.become(func())) return mob def always_shift( mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1 ) -> Mobject: """A mobject which is continuously shifted along some direction at a certain rate. Parameters ---------- mobject The mobject to shift. direction The direction to shift. The vector is normalized, the specified magnitude is not relevant. rate Length in Manim units which the mobject travels in one second along the specified direction. Examples -------- .. manim:: ShiftingSquare class ShiftingSquare(Scene): def construct(self): sq = Square().set_fill(opacity=1) tri = Triangle() VGroup(sq, tri).arrange(LEFT) # construct a square which
|
to shift. The vector is normalized, the specified magnitude is not relevant. rate Length in Manim units which the mobject travels in one second along the specified direction. Examples -------- .. manim:: ShiftingSquare class ShiftingSquare(Scene): def construct(self): sq = Square().set_fill(opacity=1) tri = Triangle() VGroup(sq, tri).arrange(LEFT) # construct a square which is continuously # shifted to the right always_shift(sq, RIGHT, rate=5) self.add(sq) self.play(tri.animate.set_fill(opacity=1)) """ mobject.add_updater(lambda m, dt: m.shift(dt * rate * normalize(direction))) return mobject def always_rotate(mobject: Mobject, rate: float = 20 * DEGREES, **kwargs) -> Mobject: """A mobject which is continuously rotated at a certain rate. Parameters ---------- mobject The mobject to be rotated. rate The angle which the mobject is rotated by over one second. kwags Further arguments to be passed to :meth:`.Mobject.rotate`. Examples -------- .. manim:: SpinningTriangle class SpinningTriangle(Scene): def construct(self): tri = Triangle().set_fill(opacity=1).set_z_index(2) sq = Square().to_edge(LEFT) # will keep spinning while there is an animation going on always_rotate(tri, rate=2*PI, about_point=ORIGIN) self.add(tri, sq) self.play(sq.animate.to_edge(RIGHT), rate_func=linear, run_time=1) """ mobject.add_updater(lambda m, dt: m.rotate(dt * rate, **kwargs)) return mobject def turn_animation_into_updater( animation: Animation, cycle: bool = False, delay: float = 0, **kwargs ) -> Mobject: """ Add an updater to the animation's mobject which applies the interpolation and update functions of the animation If cycle is True, this repeats over and over. Otherwise, the updater will be popped upon completion The ``delay`` parameter is the delay (in seconds) before the animation starts.. Examples -------- .. manim:: WelcomeToManim class WelcomeToManim(Scene): def construct(self): words = Text("Welcome to") banner = ManimBanner().scale(0.5) VGroup(words, banner).arrange(DOWN) turn_animation_into_updater(Write(words, run_time=0.9)) self.add(words) self.wait(0.5) self.play(banner.expand(), run_time=0.5) """ mobject = animation.mobject animation.suspend_mobject_updating = False animation.begin() animation.total_time = -delay def update(m: Mobject, dt: float): if animation.total_time >= 0: run_time = animation.get_run_time() time_ratio = animation.total_time / run_time if cycle: alpha = time_ratio % 1 else: alpha = np.clip(time_ratio, 0, 1) if alpha >= 1: animation.finish() m.remove_updater(update) return animation.interpolate(alpha) animation.update_mobjects(dt) animation.total_time += dt mobject.add_updater(update) return mobject def cycle_animation(animation: Animation, **kwargs) -> Mobject: return turn_animation_into_updater(animation, cycle=True, **kwargs) ================================================ FILE: manim/animation/updaters/update.py ================================================ """Animations that update mobjects.""" from __future__ import annotations __all__ = ["UpdateFromFunc", "UpdateFromAlphaFunc", "MaintainPositionRelativeTo"] import operator as op from collections.abc import Callable from typing import TYPE_CHECKING, Any from manim.animation.animation import Animation if TYPE_CHECKING: from manim.mobject.mobject import Mobject class UpdateFromFunc(Animation): """ update_function of the form func(mobject), presumably to be used when the state of one mobject is dependent on another simultaneously animated mobject """ def __init__( self, mobject: Mobject, update_function: Callable[[Mobject], Any], suspend_mobject_updating: bool = False, **kwargs: Any, ) -> None: self.update_function = update_function super().__init__( mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: self.update_function(self.mobject) # type: ignore[arg-type] class UpdateFromAlphaFunc(UpdateFromFunc): def interpolate_mobject(self, alpha: float) -> None: self.update_function(self.mobject, self.rate_func(alpha)) # type: ignore[call-arg, arg-type] class MaintainPositionRelativeTo(Animation): def __init__( self, mobject: Mobject, tracked_mobject: Mobject, **kwargs: Any ) -> None: self.tracked_mobject = tracked_mobject self.diff = op.sub( mobject.get_center(), tracked_mobject.get_center(), ) super().__init__(mobject, **kwargs) def interpolate_mobject(self, alpha: float) -> None: target = self.tracked_mobject.get_center() location = self.mobject.get_center() self.mobject.shift(target - location + self.diff) ================================================ FILE: manim/camera/__init__.py ================================================ [Empty file] ================================================ FILE: manim/camera/camera.py ================================================ """A camera converts the mobjects contained in a Scene into an array of
|
= tracked_mobject self.diff = op.sub( mobject.get_center(), tracked_mobject.get_center(), ) super().__init__(mobject, **kwargs) def interpolate_mobject(self, alpha: float) -> None: target = self.tracked_mobject.get_center() location = self.mobject.get_center() self.mobject.shift(target - location + self.diff) ================================================ FILE: manim/camera/__init__.py ================================================ [Empty file] ================================================ FILE: manim/camera/camera.py ================================================ """A camera converts the mobjects contained in a Scene into an array of pixels.""" from __future__ import annotations __all__ = ["Camera", "BackgroundColoredVMobjectDisplayer"] import copy import itertools as it import operator as op import pathlib from collections.abc import Callable, Iterable from functools import reduce from typing import TYPE_CHECKING, Any import cairo import numpy as np import numpy.typing as npt from PIL import Image from scipy.spatial.distance import pdist from typing_extensions import Self from manim.typing import ( FloatRGBA_Array, FloatRGBALike_Array, ManimInt, PixelArray, Point3D, Point3D_Array, ) from .. import config, logger from ..constants import * from ..mobject.mobject import Mobject from ..mobject.types.point_cloud_mobject import PMobject from ..mobject.types.vectorized_mobject import VMobject from ..utils.color import ManimColor, ParsableManimColor, color_to_int_rgba from ..utils.family import extract_mobject_family_members from ..utils.images import get_full_raster_image_path from ..utils.iterables import list_difference_update from ..utils.space_ops import angle_of_vector if TYPE_CHECKING: from ..mobject.types.image_mobject import AbstractImageMobject LINE_JOIN_MAP = { LineJointType.AUTO: None, # TODO: this could be improved LineJointType.ROUND: cairo.LineJoin.ROUND, LineJointType.BEVEL: cairo.LineJoin.BEVEL, LineJointType.MITER: cairo.LineJoin.MITER, } CAP_STYLE_MAP = { CapStyleType.AUTO: None, # TODO: this could be improved CapStyleType.ROUND: cairo.LineCap.ROUND, CapStyleType.BUTT: cairo.LineCap.BUTT, CapStyleType.SQUARE: cairo.LineCap.SQUARE, } class Camera: """Base camera class. This is the object which takes care of what exactly is displayed on screen at any given moment. Parameters ---------- background_image The path to an image that should be the background image. If not set, the background is filled with :attr:`self.background_color` background What :attr:`background` is set to. By default, ``None``. pixel_height The height of the scene in pixels. pixel_width The width of the scene in pixels. kwargs Additional arguments (``background_color``, ``background_opacity``) to be set. """ def __init__( self, background_image: str | None = None, frame_center: Point3D = ORIGIN, image_mode: str = "RGBA", n_channels: int = 4, pixel_array_dtype: str = "uint8", cairo_line_width_multiple: float = 0.01, use_z_index: bool = True, background: PixelArray | None = None, pixel_height: int | None = None, pixel_width: int | None = None, frame_height: float | None = None, frame_width: float | None = None, frame_rate: float | None = None, background_color: ParsableManimColor | None = None, background_opacity: float | None = None, **kwargs: Any, ) -> None: self.background_image = background_image self.frame_center = frame_center self.image_mode = image_mode self.n_channels = n_channels self.pixel_array_dtype = pixel_array_dtype self.cairo_line_width_multiple = cairo_line_width_multiple self.use_z_index = use_z_index self.background = background self.background_colored_vmobject_displayer: ( BackgroundColoredVMobjectDisplayer | None ) = None if pixel_height is None: pixel_height = config["pixel_height"] self.pixel_height = pixel_height if pixel_width is None: pixel_width = config["pixel_width"] self.pixel_width = pixel_width if frame_height is None: frame_height = config["frame_height"] self.frame_height = frame_height if frame_width is None: frame_width = config["frame_width"] self.frame_width = frame_width if frame_rate is None: frame_rate = config["frame_rate"] self.frame_rate = frame_rate if background_color is None: self._background_color: ManimColor = ManimColor.parse( config["background_color"] ) else: self._background_color = ManimColor.parse(background_color) if background_opacity is None: self._background_opacity: float = config["background_opacity"] else: self._background_opacity = background_opacity # This one is in the same boat as the above, but it doesn't have the # same name as the corresponding key
|
frame_rate if background_color is None: self._background_color: ManimColor = ManimColor.parse( config["background_color"] ) else: self._background_color = ManimColor.parse(background_color) if background_opacity is None: self._background_opacity: float = config["background_opacity"] else: self._background_opacity = background_opacity # This one is in the same boat as the above, but it doesn't have the # same name as the corresponding key so it has to be handled on its own self.max_allowable_norm = config["frame_width"] self.rgb_max_val = np.iinfo(self.pixel_array_dtype).max self.pixel_array_to_cairo_context: dict[int, cairo.Context] = {} # Contains the correct method to process a list of Mobjects of the # corresponding class. If a Mobject is not an instance of a class in # this dict (or an instance of a class that inherits from a class in # this dict), then it cannot be rendered. self.init_background() self.resize_frame_shape() self.reset() def __deepcopy__(self, memo: Any) -> Camera: # This is to address a strange bug where deepcopying # will result in a segfault, which is somehow related # to the aggdraw library self.canvas = None return copy.copy(self) @property def background_color(self) -> ManimColor: return self._background_color @background_color.setter def background_color(self, color: ManimColor) -> None: self._background_color = color self.init_background() @property def background_opacity(self) -> float: return self._background_opacity @background_opacity.setter def background_opacity(self, alpha: float) -> None: self._background_opacity = alpha self.init_background() def type_or_raise( self, mobject: Mobject ) -> type[VMobject] | type[PMobject] | type[AbstractImageMobject] | type[Mobject]: """Return the type of mobject, if it is a type that can be rendered. If `mobject` is an instance of a class that inherits from a class that can be rendered, return the super class. For example, an instance of a Square is also an instance of VMobject, and these can be rendered. Therefore, `type_or_raise(Square())` returns True. Parameters ---------- mobject The object to take the type of. Notes ----- For a list of classes that can currently be rendered, see :meth:`display_funcs`. Returns ------- Type[:class:`~.Mobject`] The type of mobjects, if it can be rendered. Raises ------ :exc:`TypeError` When mobject is not an instance of a class that can be rendered. """ from ..mobject.types.image_mobject import AbstractImageMobject self.display_funcs: dict[ type[Mobject], Callable[[list[Mobject], PixelArray], Any] ] = { VMobject: self.display_multiple_vectorized_mobjects, # type: ignore[dict-item] PMobject: self.display_multiple_point_cloud_mobjects, # type: ignore[dict-item] AbstractImageMobject: self.display_multiple_image_mobjects, # type: ignore[dict-item] Mobject: lambda batch, pa: batch, # Do nothing } # We have to check each type in turn because we are dealing with # super classes. For example, if square = Square(), then # type(square) != VMobject, but isinstance(square, VMobject) == True. for _type in self.display_funcs: if isinstance(mobject, _type): return _type raise TypeError(f"Displaying an object of class {_type} is not supported") def reset_pixel_shape(self, new_height: float, new_width: float) -> None: """This method resets the height and width of a single pixel to the passed new_height and new_width. Parameters ---------- new_height The new height of the entire scene in pixels new_width The new width of the entire scene in pixels """ self.pixel_width = new_width self.pixel_height = new_height self.init_background() self.resize_frame_shape() self.reset() def resize_frame_shape(self, fixed_dimension: int = 0) -> None: """ Changes frame_shape to match the aspect ratio of the pixels, where fixed_dimension determines whether frame_height or frame_width remains fixed while the other changes accordingly. Parameters ----------
|
the entire scene in pixels """ self.pixel_width = new_width self.pixel_height = new_height self.init_background() self.resize_frame_shape() self.reset() def resize_frame_shape(self, fixed_dimension: int = 0) -> None: """ Changes frame_shape to match the aspect ratio of the pixels, where fixed_dimension determines whether frame_height or frame_width remains fixed while the other changes accordingly. Parameters ---------- fixed_dimension If 0, height is scaled with respect to width else, width is scaled with respect to height. """ pixel_height = self.pixel_height pixel_width = self.pixel_width frame_height = self.frame_height frame_width = self.frame_width aspect_ratio = pixel_width / pixel_height if fixed_dimension == 0: frame_height = frame_width / aspect_ratio else: frame_width = aspect_ratio * frame_height self.frame_height = frame_height self.frame_width = frame_width def init_background(self) -> None: """Initialize the background. If self.background_image is the path of an image the image is set as background; else, the default background color fills the background. """ height = self.pixel_height width = self.pixel_width if self.background_image is not None: path = get_full_raster_image_path(self.background_image) image = Image.open(path).convert(self.image_mode) # TODO, how to gracefully handle backgrounds # with different sizes? self.background = np.array(image)[:height, :width] self.background = self.background.astype(self.pixel_array_dtype) else: background_rgba = color_to_int_rgba( self.background_color, self.background_opacity, ) self.background = np.zeros( (height, width, self.n_channels), dtype=self.pixel_array_dtype, ) self.background[:, :] = background_rgba def get_image( self, pixel_array: PixelArray | list | tuple | None = None ) -> Image.Image: """Returns an image from the passed pixel array, or from the current frame if the passed pixel array is none. Parameters ---------- pixel_array The pixel array from which to get an image, by default None Returns ------- PIL.Image.Image The PIL image of the array. """ if pixel_array is None: pixel_array = self.pixel_array return Image.fromarray(pixel_array, mode=self.image_mode) def convert_pixel_array( self, pixel_array: PixelArray | list | tuple, convert_from_floats: bool = False ) -> PixelArray: """Converts a pixel array from values that have floats in then to proper RGB values. Parameters ---------- pixel_array Pixel array to convert. convert_from_floats Whether or not to convert float values to ints, by default False Returns ------- np.array The new, converted pixel array. """ retval = np.array(pixel_array) if convert_from_floats: retval = np.apply_along_axis( lambda f: (f * self.rgb_max_val).astype(self.pixel_array_dtype), 2, retval, ) return retval def set_pixel_array( self, pixel_array: PixelArray | list | tuple, convert_from_floats: bool = False ) -> None: """Sets the pixel array of the camera to the passed pixel array. Parameters ---------- pixel_array The pixel array to convert and then set as the camera's pixel array. convert_from_floats Whether or not to convert float values to proper RGB values, by default False """ converted_array: PixelArray = self.convert_pixel_array( pixel_array, convert_from_floats ) if not ( hasattr(self, "pixel_array") and self.pixel_array.shape == converted_array.shape ): self.pixel_array: PixelArray = converted_array else: # Set in place self.pixel_array[:, :, :] = converted_array[:, :, :] def set_background( self, pixel_array: PixelArray | list | tuple, convert_from_floats: bool = False ) -> None: """Sets the background to the passed pixel_array after converting to valid RGB values. Parameters ---------- pixel_array The pixel array to set the background to. convert_from_floats Whether or not to convert floats values to proper RGB valid ones, by default False """ self.background = self.convert_pixel_array(pixel_array, convert_from_floats) # TODO, this should live in
|
the background to the passed pixel_array after converting to valid RGB values. Parameters ---------- pixel_array The pixel array to set the background to. convert_from_floats Whether or not to convert floats values to proper RGB valid ones, by default False """ self.background = self.convert_pixel_array(pixel_array, convert_from_floats) # TODO, this should live in utils, not as a method of Camera def make_background_from_func( self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray] ) -> PixelArray: """ Makes a pixel array for the background by using coords_to_colors_func to determine each pixel's color. Each input pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not pixel coordinates), and each output is expected to be an RGBA array of 4 floats. Parameters ---------- coords_to_colors_func The function whose input is an (x,y) pair of coordinates and whose return values must be the colors for that point Returns ------- np.array The pixel array which can then be passed to set_background. """ logger.info("Starting set_background") coords = self.get_coords_of_all_pixels() new_background = np.apply_along_axis(coords_to_colors_func, 2, coords) logger.info("Ending set_background") return self.convert_pixel_array(new_background, convert_from_floats=True) def set_background_from_func( self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray] ) -> None: """ Sets the background to a pixel array using coords_to_colors_func to determine each pixel's color. Each input pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not pixel coordinates), and each output is expected to be an RGBA array of 4 floats. Parameters ---------- coords_to_colors_func The function whose input is an (x,y) pair of coordinates and whose return values must be the colors for that point """ self.set_background(self.make_background_from_func(coords_to_colors_func)) def reset(self) -> Self: """Resets the camera's pixel array to that of the background Returns ------- Camera The camera object after setting the pixel array. """ self.set_pixel_array(self.background) return self def set_frame_to_background(self, background: PixelArray) -> None: self.set_pixel_array(background) #### def get_mobjects_to_display( self, mobjects: Iterable[Mobject], include_submobjects: bool = True, excluded_mobjects: list | None = None, ) -> list[Mobject]: """Used to get the list of mobjects to display with the camera. Parameters ---------- mobjects The Mobjects include_submobjects Whether or not to include the submobjects of mobjects, by default True excluded_mobjects Any mobjects to exclude, by default None Returns ------- list list of mobjects """ if include_submobjects: mobjects = extract_mobject_family_members( mobjects, use_z_index=self.use_z_index, only_those_with_points=True, ) if excluded_mobjects: all_excluded = extract_mobject_family_members( excluded_mobjects, use_z_index=self.use_z_index, ) mobjects = list_difference_update(mobjects, all_excluded) return list(mobjects) def is_in_frame(self, mobject: Mobject) -> bool: """Checks whether the passed mobject is in frame or not. Parameters ---------- mobject The mobject for which the checking needs to be done. Returns ------- bool True if in frame, False otherwise. """ fc = self.frame_center fh = self.frame_height fw = self.frame_width return not reduce( op.or_, [ mobject.get_right()[0] < fc[0] - fw / 2, mobject.get_bottom()[1] > fc[1] + fh / 2, mobject.get_left()[0] > fc[0] + fw / 2, mobject.get_top()[1] < fc[1] - fh / 2, ], ) def capture_mobject(self, mobject: Mobject, **kwargs: Any) -> None: """Capture mobjects by storing it in :attr:`pixel_array`. This is a single-mobject version of :meth:`capture_mobjects`. Parameters ---------- mobject Mobject to capture. kwargs Keyword arguments to be passed to :meth:`get_mobjects_to_display`. """ return self.capture_mobjects([mobject],
|
/ 2, mobject.get_top()[1] < fc[1] - fh / 2, ], ) def capture_mobject(self, mobject: Mobject, **kwargs: Any) -> None: """Capture mobjects by storing it in :attr:`pixel_array`. This is a single-mobject version of :meth:`capture_mobjects`. Parameters ---------- mobject Mobject to capture. kwargs Keyword arguments to be passed to :meth:`get_mobjects_to_display`. """ return self.capture_mobjects([mobject], **kwargs) def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs: Any) -> None: """Capture mobjects by printing them on :attr:`pixel_array`. This is the essential function that converts the contents of a Scene into an array, which is then converted to an image or video. Parameters ---------- mobjects Mobjects to capture. kwargs Keyword arguments to be passed to :meth:`get_mobjects_to_display`. Notes ----- For a list of classes that can currently be rendered, see :meth:`display_funcs`. """ # The mobjects will be processed in batches (or runs) of mobjects of # the same type. That is, if the list mobjects contains objects of # types [VMobject, VMobject, VMobject, PMobject, PMobject, VMobject], # then they will be captured in three batches: [VMobject, VMobject, # VMobject], [PMobject, PMobject], and [VMobject]. This must be done # without altering their order. it.groupby computes exactly this # partition while at the same time preserving order. mobjects = self.get_mobjects_to_display(mobjects, **kwargs) for group_type, group in it.groupby(mobjects, self.type_or_raise): self.display_funcs[group_type](list(group), self.pixel_array) # Methods associated with svg rendering # NOTE: None of the methods below have been mentioned outside of their definitions. Their DocStrings are not as # detailed as possible. def get_cached_cairo_context(self, pixel_array: PixelArray) -> cairo.Context | None: """Returns the cached cairo context of the passed pixel array if it exists, and None if it doesn't. Parameters ---------- pixel_array The pixel array to check. Returns ------- cairo.Context The cached cairo context. """ return self.pixel_array_to_cairo_context.get(id(pixel_array), None) def cache_cairo_context(self, pixel_array: PixelArray, ctx: cairo.Context) -> None: """Caches the passed Pixel array into a Cairo Context Parameters ---------- pixel_array The pixel array to cache ctx The context to cache it into. """ self.pixel_array_to_cairo_context[id(pixel_array)] = ctx def get_cairo_context(self, pixel_array: PixelArray) -> cairo.Context: """Returns the cairo context for a pixel array after caching it to self.pixel_array_to_cairo_context If that array has already been cached, it returns the cached version instead. Parameters ---------- pixel_array The Pixel array to get the cairo context of. Returns ------- cairo.Context The cairo context of the pixel array. """ cached_ctx = self.get_cached_cairo_context(pixel_array) if cached_ctx: return cached_ctx pw = self.pixel_width ph = self.pixel_height fw = self.frame_width fh = self.frame_height fc = self.frame_center surface = cairo.ImageSurface.create_for_data( pixel_array.data, cairo.FORMAT_ARGB32, pw, ph, ) ctx = cairo.Context(surface) ctx.scale(pw, ph) ctx.set_matrix( cairo.Matrix( (pw / fw), 0, 0, -(ph / fh), (pw / 2) - fc[0] * (pw / fw), (ph / 2) + fc[1] * (ph / fh), ), ) self.cache_cairo_context(pixel_array, ctx) return ctx def display_multiple_vectorized_mobjects( self, vmobjects: list[VMobject], pixel_array: PixelArray ) -> None: """Displays multiple VMobjects in the pixel_array Parameters ---------- vmobjects list of VMobjects to display pixel_array The pixel array """ if len(vmobjects) == 0: return batch_image_pairs = it.groupby(vmobjects, lambda vm: vm.get_background_image()) for image, batch in batch_image_pairs: if image: self.display_multiple_background_colored_vmobjects(batch, pixel_array) else: self.display_multiple_non_background_colored_vmobjects( batch, pixel_array, ) def display_multiple_non_background_colored_vmobjects( self, vmobjects: Iterable[VMobject], pixel_array: PixelArray )
|
VMobjects in the pixel_array Parameters ---------- vmobjects list of VMobjects to display pixel_array The pixel array """ if len(vmobjects) == 0: return batch_image_pairs = it.groupby(vmobjects, lambda vm: vm.get_background_image()) for image, batch in batch_image_pairs: if image: self.display_multiple_background_colored_vmobjects(batch, pixel_array) else: self.display_multiple_non_background_colored_vmobjects( batch, pixel_array, ) def display_multiple_non_background_colored_vmobjects( self, vmobjects: Iterable[VMobject], pixel_array: PixelArray ) -> None: """Displays multiple VMobjects in the cairo context, as long as they don't have background colors. Parameters ---------- vmobjects list of the VMobjects pixel_array The Pixel array to add the VMobjects to. """ ctx = self.get_cairo_context(pixel_array) for vmobject in vmobjects: self.display_vectorized(vmobject, ctx) def display_vectorized(self, vmobject: VMobject, ctx: cairo.Context) -> Self: """Displays a VMobject in the cairo context Parameters ---------- vmobject The Vectorized Mobject to display ctx The cairo context to use. Returns ------- Camera The camera object """ self.set_cairo_context_path(ctx, vmobject) self.apply_stroke(ctx, vmobject, background=True) self.apply_fill(ctx, vmobject) self.apply_stroke(ctx, vmobject) return self def set_cairo_context_path(self, ctx: cairo.Context, vmobject: VMobject) -> Self: """Sets a path for the cairo context with the vmobject passed Parameters ---------- ctx The cairo context vmobject The VMobject Returns ------- Camera Camera object after setting cairo_context_path """ points = self.transform_points_pre_display(vmobject, vmobject.points) # TODO, shouldn't this be handled in transform_points_pre_display? # points = points - self.get_frame_center() if len(points) == 0: return self ctx.new_path() subpaths = vmobject.gen_subpaths_from_points_2d(points) for subpath in subpaths: quads = vmobject.gen_cubic_bezier_tuples_from_points(subpath) ctx.new_sub_path() start = subpath[0] ctx.move_to(*start[:2]) for _p0, p1, p2, p3 in quads: ctx.curve_to(*p1[:2], *p2[:2], *p3[:2]) if vmobject.consider_points_equals_2d(subpath[0], subpath[-1]): ctx.close_path() return self def set_cairo_context_color( self, ctx: cairo.Context, rgbas: FloatRGBALike_Array, vmobject: VMobject ) -> Self: """Sets the color of the cairo context Parameters ---------- ctx The cairo context rgbas The RGBA array with which to color the context. vmobject The VMobject with which to set the color. Returns ------- Camera The camera object """ if len(rgbas) == 1: # Use reversed rgb because cairo surface is # encodes it in reverse order ctx.set_source_rgba(*rgbas[0][2::-1], rgbas[0][3]) else: points = vmobject.get_gradient_start_and_end_points() points = self.transform_points_pre_display(vmobject, points) pat = cairo.LinearGradient(*it.chain(*(point[:2] for point in points))) step = 1.0 / (len(rgbas) - 1) offsets = np.arange(0, 1 + step, step) for rgba, offset in zip(rgbas, offsets): pat.add_color_stop_rgba(offset, *rgba[2::-1], rgba[3]) ctx.set_source(pat) return self def apply_fill(self, ctx: cairo.Context, vmobject: VMobject) -> Self: """Fills the cairo context Parameters ---------- ctx The cairo context vmobject The VMobject Returns ------- Camera The camera object. """ self.set_cairo_context_color(ctx, self.get_fill_rgbas(vmobject), vmobject) ctx.fill_preserve() return self def apply_stroke( self, ctx: cairo.Context, vmobject: VMobject, background: bool = False ) -> Self: """Applies a stroke to the VMobject in the cairo context. Parameters ---------- ctx The cairo context vmobject The VMobject background Whether or not to consider the background when applying this stroke width, by default False Returns ------- Camera The camera object with the stroke applied. """ width = vmobject.get_stroke_width(background) if width == 0: return self self.set_cairo_context_color( ctx, self.get_stroke_rgbas(vmobject, background=background), vmobject, ) ctx.set_line_width( width * self.cairo_line_width_multiple * (self.frame_width / self.frame_width), # This ensures lines have constant width as you zoom in on them. ) if vmobject.joint_type != LineJointType.AUTO: ctx.set_line_join(LINE_JOIN_MAP[vmobject.joint_type]) if vmobject.cap_style != CapStyleType.AUTO: ctx.set_line_cap(CAP_STYLE_MAP[vmobject.cap_style]) ctx.stroke_preserve() return self def get_stroke_rgbas( self, vmobject: VMobject, background: bool = False ) ->
|
self.get_stroke_rgbas(vmobject, background=background), vmobject, ) ctx.set_line_width( width * self.cairo_line_width_multiple * (self.frame_width / self.frame_width), # This ensures lines have constant width as you zoom in on them. ) if vmobject.joint_type != LineJointType.AUTO: ctx.set_line_join(LINE_JOIN_MAP[vmobject.joint_type]) if vmobject.cap_style != CapStyleType.AUTO: ctx.set_line_cap(CAP_STYLE_MAP[vmobject.cap_style]) ctx.stroke_preserve() return self def get_stroke_rgbas( self, vmobject: VMobject, background: bool = False ) -> FloatRGBA_Array: """Gets the RGBA array for the stroke of the passed VMobject. Parameters ---------- vmobject The VMobject background Whether or not to consider the background when getting the stroke RGBAs, by default False Returns ------- np.ndarray The RGBA array of the stroke. """ return vmobject.get_stroke_rgbas(background) def get_fill_rgbas(self, vmobject: VMobject) -> FloatRGBA_Array: """Returns the RGBA array of the fill of the passed VMobject Parameters ---------- vmobject The VMobject Returns ------- np.array The RGBA Array of the fill of the VMobject """ return vmobject.get_fill_rgbas() def get_background_colored_vmobject_displayer( self, ) -> BackgroundColoredVMobjectDisplayer: """Returns the background_colored_vmobject_displayer if it exists or makes one and returns it if not. Returns ------- BackgroundColoredVMobjectDisplayer Object that displays VMobjects that have the same color as the background. """ if self.background_colored_vmobject_displayer is None: self.background_colored_vmobject_displayer = ( BackgroundColoredVMobjectDisplayer(self) ) return self.background_colored_vmobject_displayer def display_multiple_background_colored_vmobjects( self, cvmobjects: Iterable[VMobject], pixel_array: PixelArray ) -> Self: """Displays multiple vmobjects that have the same color as the background. Parameters ---------- cvmobjects List of Colored VMobjects pixel_array The pixel array. Returns ------- Camera The camera object. """ displayer = self.get_background_colored_vmobject_displayer() cvmobject_pixel_array = displayer.display(*cvmobjects) self.overlay_rgba_array(pixel_array, cvmobject_pixel_array) return self # Methods for other rendering # NOTE: Out of the following methods, only `transform_points_pre_display` and `points_to_pixel_coords` have been mentioned outside of their definitions. # As a result, the other methods do not have as detailed docstrings as would be preferred. def display_multiple_point_cloud_mobjects( self, pmobjects: Iterable[PMobject], pixel_array: PixelArray ) -> None: """Displays multiple PMobjects by modifying the passed pixel array. Parameters ---------- pmobjects List of PMobjects pixel_array The pixel array to modify. """ for pmobject in pmobjects: self.display_point_cloud( pmobject, pmobject.points, pmobject.rgbas, self.adjusted_thickness(pmobject.stroke_width), pixel_array, ) def display_point_cloud( self, pmobject: PMobject, points: Point3D_Array, rgbas: FloatRGBA_Array, thickness: float, pixel_array: PixelArray, ) -> None: """Displays a PMobject by modifying the pixel array suitably. TODO: Write a description for the rgbas argument. Parameters ---------- pmobject Point Cloud Mobject points The points to display in the point cloud mobject rgbas thickness The thickness of each point of the PMobject pixel_array The pixel array to modify. """ if len(points) == 0: return pixel_coords = self.points_to_pixel_coords(pmobject, points) pixel_coords = self.thickened_coordinates(pixel_coords, thickness) rgba_len = pixel_array.shape[2] rgbas = (self.rgb_max_val * rgbas).astype(self.pixel_array_dtype) target_len = len(pixel_coords) factor = target_len // len(rgbas) rgbas = np.array([rgbas] * factor).reshape((target_len, rgba_len)) on_screen_indices = self.on_screen_pixels(pixel_coords) pixel_coords = pixel_coords[on_screen_indices] rgbas = rgbas[on_screen_indices] ph = self.pixel_height pw = self.pixel_width flattener = np.array([1, pw], dtype="int") flattener = flattener.reshape((2, 1)) indices = np.dot(pixel_coords, flattener)[:, 0] indices = indices.astype("int") new_pa = pixel_array.reshape((ph * pw, rgba_len)) new_pa[indices] = rgbas pixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len)) def display_multiple_image_mobjects( self, image_mobjects: Iterable[AbstractImageMobject], pixel_array: PixelArray, ) -> None: """Displays multiple image mobjects by modifying the passed pixel_array. Parameters ---------- image_mobjects list of ImageMobjects pixel_array The pixel array to modify. """ for image_mobject in image_mobjects: self.display_image_mobject(image_mobject, pixel_array) def display_image_mobject( self,
|
new_pa[indices] = rgbas pixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len)) def display_multiple_image_mobjects( self, image_mobjects: Iterable[AbstractImageMobject], pixel_array: PixelArray, ) -> None: """Displays multiple image mobjects by modifying the passed pixel_array. Parameters ---------- image_mobjects list of ImageMobjects pixel_array The pixel array to modify. """ for image_mobject in image_mobjects: self.display_image_mobject(image_mobject, pixel_array) def display_image_mobject( self, image_mobject: AbstractImageMobject, pixel_array: np.ndarray ) -> None: """Displays an ImageMobject by changing the pixel_array suitably. Parameters ---------- image_mobject The imageMobject to display pixel_array The Pixel array to put the imagemobject in. """ corner_coords = self.points_to_pixel_coords(image_mobject, image_mobject.points) ul_coords, ur_coords, dl_coords, _ = corner_coords right_vect = ur_coords - ul_coords down_vect = dl_coords - ul_coords center_coords = ul_coords + (right_vect + down_vect) / 2 sub_image = Image.fromarray(image_mobject.get_pixel_array(), mode="RGBA") # Reshape pixel_width = max(int(pdist([ul_coords, ur_coords]).item()), 1) pixel_height = max(int(pdist([ul_coords, dl_coords]).item()), 1) sub_image = sub_image.resize( (pixel_width, pixel_height), resample=image_mobject.resampling_algorithm, ) # Rotate angle = angle_of_vector(right_vect) adjusted_angle = -int(360 * angle / TAU) if adjusted_angle != 0: sub_image = sub_image.rotate( adjusted_angle, resample=image_mobject.resampling_algorithm, expand=1, ) # TODO, there is no accounting for a shear... # Paste into an image as large as the camera's pixel array full_image = Image.fromarray( np.zeros((self.pixel_height, self.pixel_width)), mode="RGBA", ) new_ul_coords = center_coords - np.array(sub_image.size) / 2 new_ul_coords = new_ul_coords.astype(int) full_image.paste( sub_image, box=( new_ul_coords[0], new_ul_coords[1], new_ul_coords[0] + sub_image.size[0], new_ul_coords[1] + sub_image.size[1], ), ) # Paint on top of existing pixel array self.overlay_PIL_image(pixel_array, full_image) def overlay_rgba_array( self, pixel_array: np.ndarray, new_array: np.ndarray ) -> None: """Overlays an RGBA array on top of the given Pixel array. Parameters ---------- pixel_array The original pixel array to modify. new_array The new pixel array to overlay. """ self.overlay_PIL_image(pixel_array, self.get_image(new_array)) def overlay_PIL_image(self, pixel_array: np.ndarray, image: Image) -> None: """Overlays a PIL image on the passed pixel array. Parameters ---------- pixel_array The Pixel array image The Image to overlay. """ pixel_array[:, :] = np.array( Image.alpha_composite(self.get_image(pixel_array), image), dtype="uint8", ) def adjust_out_of_range_points(self, points: np.ndarray) -> np.ndarray: """If any of the points in the passed array are out of the viable range, they are adjusted suitably. Parameters ---------- points The points to adjust Returns ------- np.array The adjusted points. """ if not np.any(points > self.max_allowable_norm): return points norms = np.apply_along_axis(np.linalg.norm, 1, points) violator_indices = norms > self.max_allowable_norm violators = points[violator_indices, :] violator_norms = norms[violator_indices] reshaped_norms = np.repeat( violator_norms.reshape((len(violator_norms), 1)), points.shape[1], 1, ) rescaled = self.max_allowable_norm * violators / reshaped_norms points[violator_indices] = rescaled return points def transform_points_pre_display( self, mobject: Mobject, points: Point3D_Array, ) -> Point3D_Array: # TODO: Write more detailed docstrings for this method. # NOTE: There seems to be an unused argument `mobject`. # Subclasses (like ThreeDCamera) may want to # adjust points further before they're shown if not np.all(np.isfinite(points)): # TODO, print some kind of warning about # mobject having invalid points? points = np.zeros((1, 3)) return points def points_to_pixel_coords( self, mobject: Mobject, points: Point3D_Array, ) -> npt.NDArray[ManimInt]: # TODO: Write more detailed docstrings for this method. points = self.transform_points_pre_display(mobject, points) shifted_points = points - self.frame_center result = np.zeros((len(points), 2)) pixel_height = self.pixel_height pixel_width = self.pixel_width frame_height = self.frame_height frame_width = self.frame_width width_mult = pixel_width / frame_width width_add = pixel_width / 2 height_mult = pixel_height
|
) -> npt.NDArray[ManimInt]: # TODO: Write more detailed docstrings for this method. points = self.transform_points_pre_display(mobject, points) shifted_points = points - self.frame_center result = np.zeros((len(points), 2)) pixel_height = self.pixel_height pixel_width = self.pixel_width frame_height = self.frame_height frame_width = self.frame_width width_mult = pixel_width / frame_width width_add = pixel_width / 2 height_mult = pixel_height / frame_height height_add = pixel_height / 2 # Flip on y-axis as you go height_mult *= -1 result[:, 0] = shifted_points[:, 0] * width_mult + width_add result[:, 1] = shifted_points[:, 1] * height_mult + height_add return result.astype("int") def on_screen_pixels(self, pixel_coords: np.ndarray) -> PixelArray: """Returns array of pixels that are on the screen from a given array of pixel_coordinates Parameters ---------- pixel_coords The pixel coords to check. Returns ------- np.array The pixel coords on screen. """ return reduce( op.and_, [ pixel_coords[:, 0] >= 0, pixel_coords[:, 0] < self.pixel_width, pixel_coords[:, 1] >= 0, pixel_coords[:, 1] < self.pixel_height, ], ) def adjusted_thickness(self, thickness: float) -> float: """Computes the adjusted stroke width for a zoomed camera. Parameters ---------- thickness The stroke width of a mobject. Returns ------- float The adjusted stroke width that reflects zooming in with the camera. """ # TODO: This seems...unsystematic big_sum: float = op.add(config["pixel_height"], config["pixel_width"]) this_sum: float = op.add(self.pixel_height, self.pixel_width) factor = big_sum / this_sum return 1 + (thickness - 1) * factor def get_thickening_nudges(self, thickness: float) -> PixelArray: """Determine a list of vectors used to nudge two-dimensional pixel coordinates. Parameters ---------- thickness Returns ------- np.array """ thickness = int(thickness) _range = list(range(-thickness // 2 + 1, thickness // 2 + 1)) return np.array(list(it.product(_range, _range))) def thickened_coordinates( self, pixel_coords: np.ndarray, thickness: float ) -> PixelArray: """Returns thickened coordinates for a passed array of pixel coords and a thickness to thicken by. Parameters ---------- pixel_coords Pixel coordinates thickness Thickness Returns ------- np.array Array of thickened pixel coords. """ nudges = self.get_thickening_nudges(thickness) pixel_coords = np.array([pixel_coords + nudge for nudge in nudges]) size = pixel_coords.size return pixel_coords.reshape((size // 2, 2)) # TODO, reimplement using cairo matrix def get_coords_of_all_pixels(self) -> PixelArray: """Returns the cartesian coordinates of each pixel. Returns ------- np.ndarray The array of cartesian coordinates. """ # These are in x, y order, to help me keep things straight full_space_dims = np.array([self.frame_width, self.frame_height]) full_pixel_dims = np.array([self.pixel_width, self.pixel_height]) # These are addressed in the same y, x order as in pixel_array, but the values in them # are listed in x, y order uncentered_pixel_coords = np.indices([self.pixel_height, self.pixel_width])[ ::-1 ].transpose(1, 2, 0) uncentered_space_coords = ( uncentered_pixel_coords * full_space_dims ) / full_pixel_dims # Could structure above line's computation slightly differently, but figured (without much # thought) multiplying by frame_shape first, THEN dividing by pixel_shape, is probably # better than the other order, for avoiding underflow quantization in the division (whereas # overflow is unlikely to be a problem) centered_space_coords = uncentered_space_coords - (full_space_dims / 2) # Have to also flip the y coordinates to account for pixel array being listed in # top-to-bottom order, opposite of screen coordinate convention centered_space_coords = centered_space_coords * (1, -1) return centered_space_coords # NOTE: The methods of the following class have
|
a problem) centered_space_coords = uncentered_space_coords - (full_space_dims / 2) # Have to also flip the y coordinates to account for pixel array being listed in # top-to-bottom order, opposite of screen coordinate convention centered_space_coords = centered_space_coords * (1, -1) return centered_space_coords # NOTE: The methods of the following class have not been mentioned outside of their definitions. # Their DocStrings are not as detailed as preferred. class BackgroundColoredVMobjectDisplayer: """Auxiliary class that handles displaying vectorized mobjects with a set background image. Parameters ---------- camera Camera object to use. """ def __init__(self, camera: Camera): self.camera = camera self.file_name_to_pixel_array_map: dict[str, PixelArray] = {} self.pixel_array = np.array(camera.pixel_array) self.reset_pixel_array() def reset_pixel_array(self) -> None: self.pixel_array[:, :] = 0 def resize_background_array( self, background_array: PixelArray, new_width: float, new_height: float, mode: str = "RGBA", ) -> PixelArray: """Resizes the pixel array representing the background. Parameters ---------- background_array The pixel new_width The new width of the background new_height The new height of the background mode The PIL image mode, by default "RGBA" Returns ------- np.array The numpy pixel array of the resized background. """ image = Image.fromarray(background_array) image = image.convert(mode) resized_image = image.resize((new_width, new_height)) return np.array(resized_image) def resize_background_array_to_match( self, background_array: PixelArray, pixel_array: PixelArray ) -> PixelArray: """Resizes the background array to match the passed pixel array. Parameters ---------- background_array The prospective pixel array. pixel_array The pixel array whose width and height should be matched. Returns ------- np.array The resized background array. """ height, width = pixel_array.shape[:2] mode = "RGBA" if pixel_array.shape[2] == 4 else "RGB" return self.resize_background_array(background_array, width, height, mode) def get_background_array( self, image: Image.Image | pathlib.Path | str ) -> PixelArray: """Gets the background array that has the passed file_name. Parameters ---------- image The background image or its file name. Returns ------- np.ndarray The pixel array of the image. """ image_key = str(image) if image_key in self.file_name_to_pixel_array_map: return self.file_name_to_pixel_array_map[image_key] if isinstance(image, str): full_path = get_full_raster_image_path(image) image = Image.open(full_path) back_array = np.array(image) pixel_array = self.pixel_array if not np.all(pixel_array.shape == back_array.shape): back_array = self.resize_background_array_to_match(back_array, pixel_array) self.file_name_to_pixel_array_map[image_key] = back_array return back_array def display(self, *cvmobjects: VMobject) -> PixelArray | None: """Displays the colored VMobjects. Parameters ---------- *cvmobjects The VMobjects Returns ------- np.array The pixel array with the `cvmobjects` displayed. """ batch_image_pairs = it.groupby(cvmobjects, lambda cv: cv.get_background_image()) curr_array = None for image, batch in batch_image_pairs: background_array = self.get_background_array(image) pixel_array = self.pixel_array self.camera.display_multiple_non_background_colored_vmobjects( batch, pixel_array, ) new_array = np.array( (background_array * pixel_array.astype("float") / 255), dtype=self.camera.pixel_array_dtype, ) if curr_array is None: curr_array = new_array else: curr_array = np.maximum(curr_array, new_array) self.reset_pixel_array() return curr_array ================================================ FILE: manim/camera/mapping_camera.py ================================================ """A camera module that supports spatial mapping between objects for distortion effects.""" from __future__ import annotations __all__ = ["MappingCamera", "OldMultiCamera", "SplitScreenCamera"] import math import numpy as np from ..camera.camera import Camera from ..mobject.types.vectorized_mobject import VMobject from ..utils.config_ops import DictAsObject # TODO: Add an attribute to mobjects under which they can specify that they should just # map their centers but remain otherwise undistorted (useful for labels, etc.) class MappingCamera(Camera): """Parameters ---------- mapping_func : callable Function to map 3D points to new 3D points (identity by default). min_num_curves : int Minimum
|
TODO: Add an attribute to mobjects under which they can specify that they should just # map their centers but remain otherwise undistorted (useful for labels, etc.) class MappingCamera(Camera): """Parameters ---------- mapping_func : callable Function to map 3D points to new 3D points (identity by default). min_num_curves : int Minimum number of curves for VMobjects to avoid visual glitches. allow_object_intrusion : bool If True, modifies original mobjects; else works on copies. kwargs : dict Additional arguments passed to Camera base class. """ def __init__( self, mapping_func=lambda p: p, min_num_curves=50, allow_object_intrusion=False, **kwargs, ): self.mapping_func = mapping_func self.min_num_curves = min_num_curves self.allow_object_intrusion = allow_object_intrusion super().__init__(**kwargs) def points_to_pixel_coords(self, mobject, points): # Map points with custom function before converting to pixels return super().points_to_pixel_coords( mobject, np.apply_along_axis(self.mapping_func, 1, points), ) def capture_mobjects(self, mobjects, **kwargs): """Capture mobjects for rendering after applying the spatial mapping. Copies mobjects unless intrusion is allowed, and ensures vector objects have enough curves for smooth distortion. """ mobjects = self.get_mobjects_to_display(mobjects, **kwargs) if self.allow_object_intrusion: mobject_copies = mobjects else: mobject_copies = [mobject.copy() for mobject in mobjects] for mobject in mobject_copies: if ( isinstance(mobject, VMobject) and 0 < mobject.get_num_curves() < self.min_num_curves ): mobject.insert_n_curves(self.min_num_curves) super().capture_mobjects( mobject_copies, include_submobjects=False, excluded_mobjects=None, ) # Note: This allows layering of multiple cameras onto the same portion of the pixel array, # the later cameras overwriting the former # # TODO: Add optional separator borders between cameras (or perhaps peel this off into a # CameraPlusOverlay class) # TODO, the classes below should likely be deleted class OldMultiCamera(Camera): """Parameters ---------- cameras_with_start_positions : tuple Tuples of (Camera, (start_y, start_x)) indicating camera and its pixel offset on the final frame. """ def __init__(self, *cameras_with_start_positions, **kwargs): self.shifted_cameras = [ DictAsObject( { "camera": camera_with_start_positions[0], "start_x": camera_with_start_positions[1][1], "start_y": camera_with_start_positions[1][0], "end_x": camera_with_start_positions[1][1] + camera_with_start_positions[0].pixel_width, "end_y": camera_with_start_positions[1][0] + camera_with_start_positions[0].pixel_height, }, ) for camera_with_start_positions in cameras_with_start_positions ] super().__init__(**kwargs) def capture_mobjects(self, mobjects, **kwargs): for shifted_camera in self.shifted_cameras: shifted_camera.camera.capture_mobjects(mobjects, **kwargs) self.pixel_array[ shifted_camera.start_y : shifted_camera.end_y, shifted_camera.start_x : shifted_camera.end_x, ] = shifted_camera.camera.pixel_array def set_background(self, pixel_array, **kwargs): for shifted_camera in self.shifted_cameras: shifted_camera.camera.set_background( pixel_array[ shifted_camera.start_y : shifted_camera.end_y, shifted_camera.start_x : shifted_camera.end_x, ], **kwargs, ) def set_pixel_array(self, pixel_array, **kwargs): super().set_pixel_array(pixel_array, **kwargs) for shifted_camera in self.shifted_cameras: shifted_camera.camera.set_pixel_array( pixel_array[ shifted_camera.start_y : shifted_camera.end_y, shifted_camera.start_x : shifted_camera.end_x, ], **kwargs, ) def init_background(self): super().init_background() for shifted_camera in self.shifted_cameras: shifted_camera.camera.init_background() # A OldMultiCamera which, when called with two full-size cameras, initializes itself # as a split screen, also taking care to resize each individual camera within it class SplitScreenCamera(OldMultiCamera): """Initializes a split screen camera setup with two side-by-side cameras. Parameters ---------- left_camera : Camera right_camera : Camera kwargs : dict """ def __init__(self, left_camera, right_camera, **kwargs): Camera.__init__(self, **kwargs) # to set attributes such as pixel_width self.left_camera = left_camera self.right_camera = right_camera half_width = math.ceil(self.pixel_width / 2) for camera in [self.left_camera, self.right_camera]: camera.reset_pixel_shape(camera.pixel_height, half_width) super().__init__( (left_camera, (0, 0)), (right_camera, (0, half_width)), ) ================================================ FILE: manim/camera/moving_camera.py ================================================ """Defines the MovingCamera class, a camera that can pan and zoom through a scene. .. SEEALSO:: :mod:`.moving_camera_scene` """ from __future__ import annotations __all__ = ["MovingCamera"] from collections.abc import Iterable from typing import Any from cairo import Context from manim.typing import PixelArray,
|
0)), (right_camera, (0, half_width)), ) ================================================ FILE: manim/camera/moving_camera.py ================================================ """Defines the MovingCamera class, a camera that can pan and zoom through a scene. .. SEEALSO:: :mod:`.moving_camera_scene` """ from __future__ import annotations __all__ = ["MovingCamera"] from collections.abc import Iterable from typing import Any from cairo import Context from manim.typing import PixelArray, Point3D, Point3DLike from .. import config from ..camera.camera import Camera from ..constants import DOWN, LEFT, RIGHT, UP from ..mobject.frame import ScreenRectangle from ..mobject.mobject import Mobject from ..utils.color import WHITE, ManimColor class MovingCamera(Camera): """A camera that follows and matches the size and position of its 'frame', a Rectangle (or similar Mobject). The frame defines the region of space the camera displays and can move or resize dynamically. .. SEEALSO:: :class:`.MovingCameraScene` """ def __init__( self, frame: Mobject | None = None, fixed_dimension: int = 0, # width default_frame_stroke_color: ManimColor = WHITE, default_frame_stroke_width: int = 0, **kwargs: Any, ): """Frame is a Mobject, (should almost certainly be a rectangle) determining which region of space the camera displays """ self.fixed_dimension = fixed_dimension self.default_frame_stroke_color = default_frame_stroke_color self.default_frame_stroke_width = default_frame_stroke_width if frame is None: frame = ScreenRectangle(height=config["frame_height"]) frame.set_stroke( self.default_frame_stroke_color, self.default_frame_stroke_width, ) self.frame = frame super().__init__(**kwargs) # TODO, make these work for a rotated frame @property def frame_height(self) -> float: """Returns the height of the frame. Returns ------- float The height of the frame. """ return self.frame.height @frame_height.setter def frame_height(self, frame_height: float) -> None: """Sets the height of the frame in MUnits. Parameters ---------- frame_height The new frame_height. """ self.frame.stretch_to_fit_height(frame_height) @property def frame_width(self) -> float: """Returns the width of the frame Returns ------- float The width of the frame. """ return self.frame.width @frame_width.setter def frame_width(self, frame_width: float) -> None: """Sets the width of the frame in MUnits. Parameters ---------- frame_width The new frame_width. """ self.frame.stretch_to_fit_width(frame_width) @property def frame_center(self) -> Point3D: """Returns the centerpoint of the frame in cartesian coordinates. Returns ------- np.array The cartesian coordinates of the center of the frame. """ return self.frame.get_center() @frame_center.setter def frame_center(self, frame_center: Point3DLike | Mobject) -> None: """Sets the centerpoint of the frame. Parameters ---------- frame_center The point to which the frame must be moved. If is of type mobject, the frame will be moved to the center of that mobject. """ self.frame.move_to(frame_center) def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs: Any) -> None: # self.reset_frame_center() # self.realign_frame_shape() super().capture_mobjects(mobjects, **kwargs) def get_cached_cairo_context(self, pixel_array: PixelArray) -> None: """Since the frame can be moving around, the cairo context used for updating should be regenerated at each frame. So no caching. """ return None def cache_cairo_context(self, pixel_array: PixelArray, ctx: Context) -> None: """Since the frame can be moving around, the cairo context used for updating should be regenerated at each frame. So no caching. """ pass # def reset_frame_center(self): # self.frame_center = self.frame.get_center() # def realign_frame_shape(self): # height, width = self.frame_shape # if self.fixed_dimension == 0: # self.frame_shape = (height, self.frame.width # else: # self.frame_shape = (self.frame.height, width) # self.resize_frame_shape(fixed_dimension=self.fixed_dimension) def get_mobjects_indicating_movement(self) -> list[Mobject]: """Returns all mobjects whose movement implies that the camera should think of all other mobjects on the screen as moving Returns ------- list[Mobject]
|
height, width = self.frame_shape # if self.fixed_dimension == 0: # self.frame_shape = (height, self.frame.width # else: # self.frame_shape = (self.frame.height, width) # self.resize_frame_shape(fixed_dimension=self.fixed_dimension) def get_mobjects_indicating_movement(self) -> list[Mobject]: """Returns all mobjects whose movement implies that the camera should think of all other mobjects on the screen as moving Returns ------- list[Mobject] """ return [self.frame] def auto_zoom( self, mobjects: Iterable[Mobject], margin: float = 0, only_mobjects_in_frame: bool = False, animate: bool = True, ) -> Mobject: """Zooms on to a given array of mobjects (or a singular mobject) and automatically resizes to frame all the mobjects. .. NOTE:: This method only works when 2D-objects in the XY-plane are considered, it will not work correctly when the camera has been rotated. Parameters ---------- mobjects The mobject or array of mobjects that the camera will focus on. margin The width of the margin that is added to the frame (optional, 0 by default). only_mobjects_in_frame If set to ``True``, only allows focusing on mobjects that are already in frame. animate If set to ``False``, applies the changes instead of returning the corresponding animation Returns ------- Union[_AnimationBuilder, ScreenRectangle] _AnimationBuilder that zooms the camera view to a given list of mobjects or ScreenRectangle with position and size updated to zoomed position. """ ( scene_critical_x_left, scene_critical_x_right, scene_critical_y_up, scene_critical_y_down, ) = self._get_bounding_box(mobjects, only_mobjects_in_frame) # calculate center x and y x = (scene_critical_x_left + scene_critical_x_right) / 2 y = (scene_critical_y_up + scene_critical_y_down) / 2 # calculate proposed width and height of zoomed scene new_width = abs(scene_critical_x_left - scene_critical_x_right) new_height = abs(scene_critical_y_up - scene_critical_y_down) m_target = self.frame.animate if animate else self.frame # zoom to fit all mobjects along the side that has the largest size if new_width / self.frame.width > new_height / self.frame.height: return m_target.set_x(x).set_y(y).set(width=new_width + margin) else: return m_target.set_x(x).set_y(y).set(height=new_height + margin) def _get_bounding_box( self, mobjects: Iterable[Mobject], only_mobjects_in_frame: bool ) -> tuple[float, float, float, float]: bounding_box_located = False scene_critical_x_left: float = 0 scene_critical_x_right: float = 1 scene_critical_y_up: float = 1 scene_critical_y_down: float = 0 for m in mobjects: if (m == self.frame) or ( only_mobjects_in_frame and not self.is_in_frame(m) ): # detected camera frame, should not be used to calculate final position of camera continue # initialize scene critical points with first mobjects critical points if not bounding_box_located: scene_critical_x_left = m.get_critical_point(LEFT)[0] scene_critical_x_right = m.get_critical_point(RIGHT)[0] scene_critical_y_up = m.get_critical_point(UP)[1] scene_critical_y_down = m.get_critical_point(DOWN)[1] bounding_box_located = True else: if m.get_critical_point(LEFT)[0] < scene_critical_x_left: scene_critical_x_left = m.get_critical_point(LEFT)[0] if m.get_critical_point(RIGHT)[0] > scene_critical_x_right: scene_critical_x_right = m.get_critical_point(RIGHT)[0] if m.get_critical_point(UP)[1] > scene_critical_y_up: scene_critical_y_up = m.get_critical_point(UP)[1] if m.get_critical_point(DOWN)[1] < scene_critical_y_down: scene_critical_y_down = m.get_critical_point(DOWN)[1] if not bounding_box_located: raise Exception( "Could not determine bounding box of the mobjects given to 'auto_zoom'." ) return ( scene_critical_x_left, scene_critical_x_right, scene_critical_y_up, scene_critical_y_down, ) ================================================ FILE: manim/camera/multi_camera.py ================================================ """A camera supporting multiple perspectives.""" from __future__ import annotations __all__ = ["MultiCamera"] from collections.abc import Iterable from typing import Any from typing_extensions import Self from manim.mobject.mobject import Mobject from manim.mobject.types.image_mobject import ImageMobjectFromCamera from ..camera.moving_camera import MovingCamera from ..utils.iterables import list_difference_update class MultiCamera(MovingCamera): """Camera Object that allows for multiple perspectives.""" def __init__( self, image_mobjects_from_cameras: Iterable[ImageMobjectFromCamera] | None = None, allow_cameras_to_capture_their_own_display: bool = False, **kwargs:
|
collections.abc import Iterable from typing import Any from typing_extensions import Self from manim.mobject.mobject import Mobject from manim.mobject.types.image_mobject import ImageMobjectFromCamera from ..camera.moving_camera import MovingCamera from ..utils.iterables import list_difference_update class MultiCamera(MovingCamera): """Camera Object that allows for multiple perspectives.""" def __init__( self, image_mobjects_from_cameras: Iterable[ImageMobjectFromCamera] | None = None, allow_cameras_to_capture_their_own_display: bool = False, **kwargs: Any, ) -> None: """Initialises the MultiCamera Parameters ---------- image_mobjects_from_cameras kwargs Any valid keyword arguments of MovingCamera. """ self.image_mobjects_from_cameras: list[ImageMobjectFromCamera] = [] if image_mobjects_from_cameras is not None: for imfc in image_mobjects_from_cameras: self.add_image_mobject_from_camera(imfc) self.allow_cameras_to_capture_their_own_display = ( allow_cameras_to_capture_their_own_display ) super().__init__(**kwargs) def add_image_mobject_from_camera( self, image_mobject_from_camera: ImageMobjectFromCamera ) -> None: """Adds an ImageMobject that's been obtained from the camera into the list ``self.image_mobject_from_cameras`` Parameters ---------- image_mobject_from_camera The ImageMobject to add to self.image_mobject_from_cameras """ # A silly method to have right now, but maybe there are things # we want to guarantee about any imfc's added later. imfc = image_mobject_from_camera assert isinstance(imfc.camera, MovingCamera) self.image_mobjects_from_cameras.append(imfc) def update_sub_cameras(self) -> None: """Reshape sub_camera pixel_arrays""" for imfc in self.image_mobjects_from_cameras: pixel_height, pixel_width = self.pixel_array.shape[:2] # imfc.camera.frame_shape = ( # imfc.camera.frame.height, # imfc.camera.frame.width, # ) imfc.camera.reset_pixel_shape( int(pixel_height * imfc.height / self.frame_height), int(pixel_width * imfc.width / self.frame_width), ) def reset(self) -> Self: """Resets the MultiCamera. Returns ------- MultiCamera The reset MultiCamera """ for imfc in self.image_mobjects_from_cameras: imfc.camera.reset() super().reset() return self def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs: Any) -> None: self.update_sub_cameras() for imfc in self.image_mobjects_from_cameras: to_add = list(mobjects) if not self.allow_cameras_to_capture_their_own_display: to_add = list_difference_update(to_add, imfc.get_family()) imfc.camera.capture_mobjects(to_add, **kwargs) super().capture_mobjects(mobjects, **kwargs) def get_mobjects_indicating_movement(self) -> list[Mobject]: """Returns all mobjects whose movement implies that the camera should think of all other mobjects on the screen as moving Returns ------- list """ return [self.frame] + [ imfc.camera.frame for imfc in self.image_mobjects_from_cameras ] ================================================ FILE: manim/camera/three_d_camera.py ================================================ """A camera that can be positioned and oriented in three-dimensional space.""" from __future__ import annotations __all__ = ["ThreeDCamera"] from collections.abc import Callable, Iterable from typing import Any import numpy as np from manim.mobject.mobject import Mobject from manim.mobject.three_d.three_d_utils import ( get_3d_vmob_end_corner, get_3d_vmob_end_corner_unit_normal, get_3d_vmob_start_corner, get_3d_vmob_start_corner_unit_normal, ) from manim.mobject.types.vectorized_mobject import VMobject from manim.mobject.value_tracker import ValueTracker from manim.typing import ( FloatRGBA_Array, MatrixMN, Point3D, Point3D_Array, Point3DLike, ) from .. import config from ..camera.camera import Camera from ..constants import * from ..mobject.types.point_cloud_mobject import Point from ..utils.color import get_shaded_rgb from ..utils.family import extract_mobject_family_members from ..utils.space_ops import rotation_about_z, rotation_matrix class ThreeDCamera(Camera): def __init__( self, focal_distance: float = 20.0, shading_factor: float = 0.2, default_distance: float = 5.0, light_source_start_point: Point3DLike = 9 * DOWN + 7 * LEFT + 10 * OUT, should_apply_shading: bool = True, exponential_projection: bool = False, phi: float = 0, theta: float = -90 * DEGREES, gamma: float = 0, zoom: float = 1, **kwargs: Any, ): """Initializes the ThreeDCamera Parameters ---------- *kwargs Any keyword argument of Camera. """ self._frame_center = Point(kwargs.get("frame_center", ORIGIN), stroke_width=0) super().__init__(**kwargs) self.focal_distance = focal_distance self.phi = phi self.theta = theta self.gamma = gamma self.zoom = zoom self.shading_factor = shading_factor self.default_distance = default_distance self.light_source_start_point = light_source_start_point self.light_source = Point(self.light_source_start_point) self.should_apply_shading = should_apply_shading self.exponential_projection = exponential_projection self.max_allowable_norm = 3 * config["frame_width"] self.phi_tracker = ValueTracker(self.phi) self.theta_tracker = ValueTracker(self.theta) self.focal_distance_tracker = ValueTracker(self.focal_distance) self.gamma_tracker = ValueTracker(self.gamma) self.zoom_tracker = ValueTracker(self.zoom) self.fixed_orientation_mobjects:
|
= phi self.theta = theta self.gamma = gamma self.zoom = zoom self.shading_factor = shading_factor self.default_distance = default_distance self.light_source_start_point = light_source_start_point self.light_source = Point(self.light_source_start_point) self.should_apply_shading = should_apply_shading self.exponential_projection = exponential_projection self.max_allowable_norm = 3 * config["frame_width"] self.phi_tracker = ValueTracker(self.phi) self.theta_tracker = ValueTracker(self.theta) self.focal_distance_tracker = ValueTracker(self.focal_distance) self.gamma_tracker = ValueTracker(self.gamma) self.zoom_tracker = ValueTracker(self.zoom) self.fixed_orientation_mobjects: dict[Mobject, Callable[[], Point3D]] = {} self.fixed_in_frame_mobjects: set[Mobject] = set() self.reset_rotation_matrix() @property def frame_center(self) -> Point3D: return self._frame_center.points[0] @frame_center.setter def frame_center(self, point: Point3DLike) -> None: self._frame_center.move_to(point) def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs: Any) -> None: self.reset_rotation_matrix() super().capture_mobjects(mobjects, **kwargs) def get_value_trackers(self) -> list[ValueTracker]: """A list of :class:`ValueTrackers <.ValueTracker>` of phi, theta, focal_distance, gamma and zoom. Returns ------- list list of ValueTracker objects """ return [ self.phi_tracker, self.theta_tracker, self.focal_distance_tracker, self.gamma_tracker, self.zoom_tracker, ] def modified_rgbas( self, vmobject: VMobject, rgbas: FloatRGBA_Array ) -> FloatRGBA_Array: if not self.should_apply_shading: return rgbas if vmobject.shade_in_3d and (vmobject.get_num_points() > 0): light_source_point = self.light_source.points[0] if len(rgbas) < 2: shaded_rgbas = rgbas.repeat(2, axis=0) else: shaded_rgbas = np.array(rgbas[:2]) shaded_rgbas[0, :3] = get_shaded_rgb( shaded_rgbas[0, :3], get_3d_vmob_start_corner(vmobject), get_3d_vmob_start_corner_unit_normal(vmobject), light_source_point, ) shaded_rgbas[1, :3] = get_shaded_rgb( shaded_rgbas[1, :3], get_3d_vmob_end_corner(vmobject), get_3d_vmob_end_corner_unit_normal(vmobject), light_source_point, ) return shaded_rgbas return rgbas def get_stroke_rgbas( self, vmobject: VMobject, background: bool = False, ) -> FloatRGBA_Array: # NOTE : DocStrings From parent return self.modified_rgbas(vmobject, vmobject.get_stroke_rgbas(background)) def get_fill_rgbas( self, vmobject: VMobject ) -> FloatRGBA_Array: # NOTE : DocStrings From parent return self.modified_rgbas(vmobject, vmobject.get_fill_rgbas()) def get_mobjects_to_display( self, *args: Any, **kwargs: Any ) -> list[Mobject]: # NOTE : DocStrings From parent mobjects = super().get_mobjects_to_display(*args, **kwargs) rot_matrix = self.get_rotation_matrix() def z_key(mob: Mobject) -> float: if not (hasattr(mob, "shade_in_3d") and mob.shade_in_3d): return np.inf # type: ignore[no-any-return] # Assign a number to a three dimensional mobjects # based on how close it is to the camera distance: float = np.dot(mob.get_z_index_reference_point(), rot_matrix.T)[2] return distance return sorted(mobjects, key=z_key) def get_phi(self) -> float: """Returns the Polar angle (the angle off Z_AXIS) phi. Returns ------- float The Polar angle in radians. """ return self.phi_tracker.get_value() def get_theta(self) -> float: """Returns the Azimuthal i.e the angle that spins the camera around the Z_AXIS. Returns ------- float The Azimuthal angle in radians. """ return self.theta_tracker.get_value() def get_focal_distance(self) -> float: """Returns focal_distance of the Camera. Returns ------- float The focal_distance of the Camera in MUnits. """ return self.focal_distance_tracker.get_value() def get_gamma(self) -> float: """Returns the rotation of the camera about the vector from the ORIGIN to the Camera. Returns ------- float The angle of rotation of the camera about the vector from the ORIGIN to the Camera in radians """ return self.gamma_tracker.get_value() def get_zoom(self) -> float: """Returns the zoom amount of the camera. Returns ------- float The zoom amount of the camera. """ return self.zoom_tracker.get_value() def set_phi(self, value: float) -> None: """Sets the polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians. Parameters ---------- value The new value of the polar angle in radians. """ self.phi_tracker.set_value(value) def set_theta(self, value: float) -> None: """Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians. Parameters ---------- value The new value of the azimuthal angle in radians. """ self.theta_tracker.set_value(value) def set_focal_distance(self, value: float) -> None:
|
value of the polar angle in radians. """ self.phi_tracker.set_value(value) def set_theta(self, value: float) -> None: """Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians. Parameters ---------- value The new value of the azimuthal angle in radians. """ self.theta_tracker.set_value(value) def set_focal_distance(self, value: float) -> None: """Sets the focal_distance of the Camera. Parameters ---------- value The focal_distance of the Camera. """ self.focal_distance_tracker.set_value(value) def set_gamma(self, value: float) -> None: """Sets the angle of rotation of the camera about the vector from the ORIGIN to the Camera. Parameters ---------- value The new angle of rotation of the camera. """ self.gamma_tracker.set_value(value) def set_zoom(self, value: float) -> None: """Sets the zoom amount of the camera. Parameters ---------- value The zoom amount of the camera. """ self.zoom_tracker.set_value(value) def reset_rotation_matrix(self) -> None: """Sets the value of self.rotation_matrix to the matrix corresponding to the current position of the camera """ self.rotation_matrix = self.generate_rotation_matrix() def get_rotation_matrix(self) -> MatrixMN: """Returns the matrix corresponding to the current position of the camera. Returns ------- np.array The matrix corresponding to the current position of the camera. """ return self.rotation_matrix def generate_rotation_matrix(self) -> MatrixMN: """Generates a rotation matrix based off the current position of the camera. Returns ------- np.array The matrix corresponding to the current position of the camera. """ phi = self.get_phi() theta = self.get_theta() gamma = self.get_gamma() matrices = [ rotation_about_z(-theta - 90 * DEGREES), rotation_matrix(-phi, RIGHT), rotation_about_z(gamma), ] result = np.identity(3) for matrix in matrices: result = np.dot(matrix, result) return result def project_points(self, points: Point3D_Array) -> Point3D_Array: """Applies the current rotation_matrix as a projection matrix to the passed array of points. Parameters ---------- points The list of points to project. Returns ------- np.array The points after projecting. """ frame_center = self.frame_center focal_distance = self.get_focal_distance() zoom = self.get_zoom() rot_matrix = self.get_rotation_matrix() points = points - frame_center points = np.dot(points, rot_matrix.T) zs = points[:, 2] for i in 0, 1: if self.exponential_projection: # Proper projection would involve multiplying # x and y by d / (d-z). But for points with high # z value that causes weird artifacts, and applying # the exponential helps smooth it out. factor = np.exp(zs / focal_distance) lt0 = zs < 0 factor[lt0] = focal_distance / (focal_distance - zs[lt0]) else: factor = focal_distance / (focal_distance - zs) factor[(focal_distance - zs) < 0] = 10**6 points[:, i] *= factor * zoom return points def project_point(self, point: Point3D) -> Point3D: """Applies the current rotation_matrix as a projection matrix to the passed point. Parameters ---------- point The point to project. Returns ------- np.array The point after projection. """ return self.project_points(point.reshape((1, 3)))[0, :] def transform_points_pre_display( self, mobject: Mobject, points: Point3D_Array, ) -> Point3D_Array: # TODO: Write Docstrings for this Method. points = super().transform_points_pre_display(mobject, points) fixed_orientation = mobject in self.fixed_orientation_mobjects fixed_in_frame = mobject in self.fixed_in_frame_mobjects if fixed_in_frame: return points if fixed_orientation: center_func = self.fixed_orientation_mobjects[mobject] center = center_func() new_center = self.project_point(center) return points + (new_center - center) else: return self.project_points(points) def add_fixed_orientation_mobjects( self, *mobjects: Mobject, use_static_center_func: bool = False, center_func: Callable[[], Point3D] | None = None, ) -> None:
|
in self.fixed_orientation_mobjects fixed_in_frame = mobject in self.fixed_in_frame_mobjects if fixed_in_frame: return points if fixed_orientation: center_func = self.fixed_orientation_mobjects[mobject] center = center_func() new_center = self.project_point(center) return points + (new_center - center) else: return self.project_points(points) def add_fixed_orientation_mobjects( self, *mobjects: Mobject, use_static_center_func: bool = False, center_func: Callable[[], Point3D] | None = None, ) -> None: """This method allows the mobject to have a fixed orientation, even when the camera moves around. E.G If it was passed through this method, facing the camera, it will continue to face the camera even as the camera moves. Highly useful when adding labels to graphs and the like. Parameters ---------- *mobjects The mobject whose orientation must be fixed. use_static_center_func Whether or not to use the function that takes the mobject's center as centerpoint, by default False center_func The function which returns the centerpoint with respect to which the mobject will be oriented, by default None """ # This prevents the computation of mobject.get_center # every single time a projection happens def get_static_center_func(mobject: Mobject) -> Callable[[], Point3D]: point = mobject.get_center() return lambda: point for mobject in mobjects: if center_func: func = center_func elif use_static_center_func: func = get_static_center_func(mobject) else: func = mobject.get_center for submob in mobject.get_family(): self.fixed_orientation_mobjects[submob] = func def add_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: """This method allows the mobject to have a fixed position, even when the camera moves around. E.G If it was passed through this method, at the top of the frame, it will continue to be displayed at the top of the frame. Highly useful when displaying Titles or formulae or the like. Parameters ---------- **mobjects The mobject to fix in frame. """ for mobject in extract_mobject_family_members(mobjects): self.fixed_in_frame_mobjects.add(mobject) def remove_fixed_orientation_mobjects(self, *mobjects: Mobject) -> None: """If a mobject was fixed in its orientation by passing it through :meth:`.add_fixed_orientation_mobjects`, then this undoes that fixing. The Mobject will no longer have a fixed orientation. Parameters ---------- mobjects The mobjects whose orientation need not be fixed any longer. """ for mobject in extract_mobject_family_members(mobjects): if mobject in self.fixed_orientation_mobjects: del self.fixed_orientation_mobjects[mobject] def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: """If a mobject was fixed in frame by passing it through :meth:`.add_fixed_in_frame_mobjects`, then this undoes that fixing. The Mobject will no longer be fixed in frame. Parameters ---------- mobjects The mobjects which need not be fixed in frame any longer. """ for mobject in extract_mobject_family_members(mobjects): if mobject in self.fixed_in_frame_mobjects: self.fixed_in_frame_mobjects.remove(mobject) ================================================ FILE: manim/cli/__init__.py ================================================ """The Manim CLI, and the available commands for ``manim``. This page is a work in progress. Please run ``manim`` or ``manim --help`` in your terminal to find more information on the following commands. Available commands ------------------ .. autosummary:: :toctree: ../reference cfg checkhealth init plugins render """ ================================================ FILE: manim/cli/default_group.py ================================================ """``DefaultGroup`` allows a subcommand to act as the main command. In particular, this class is what allows ``manim`` to act as ``manim render``. .. note:: This is a vendored version of https://github.com/click-contrib/click-default-group/ under the BSD 3-Clause "New" or "Revised" License. This library isn't used as a dependency, as we need to inherit from :class:`cloup.Group` instead of :class:`click.Group`. """ from __future__ import annotations
|
this class is what allows ``manim`` to act as ``manim render``. .. note:: This is a vendored version of https://github.com/click-contrib/click-default-group/ under the BSD 3-Clause "New" or "Revised" License. This library isn't used as a dependency, as we need to inherit from :class:`cloup.Group` instead of :class:`click.Group`. """ from __future__ import annotations import warnings from collections.abc import Callable from typing import TYPE_CHECKING, Any import cloup from manim.utils.deprecation import deprecated __all__ = ["DefaultGroup"] if TYPE_CHECKING: from click import Command, Context class DefaultGroup(cloup.Group): """Invokes a subcommand marked with ``default=True`` if any subcommand is not chosen. Parameters ---------- *args Positional arguments to forward to :class:`cloup.Group`. **kwargs Keyword arguments to forward to :class:`cloup.Group`. The keyword ``ignore_unknown_options`` must be set to ``False``. Attributes ---------- default_cmd_name : str | None The name of the default command, if specified through the ``default`` keyword argument. Otherwise, this is set to ``None``. default_if_no_args : bool Whether to include or not the default command, if no command arguments are supplied. This can be specified through the ``default_if_no_args`` keyword argument. Default is ``False``. """ def __init__(self, *args: Any, **kwargs: Any): # To resolve as the default command. if not kwargs.get("ignore_unknown_options", True): raise ValueError("Default group accepts unknown options") self.ignore_unknown_options = True self.default_cmd_name: str | None = kwargs.pop("default", None) self.default_if_no_args: bool = kwargs.pop("default_if_no_args", False) super().__init__(*args, **kwargs) def set_default_command(self, command: Command) -> None: """Sets a command function as the default command. Parameters ---------- command The command to set as default. """ cmd_name = command.name self.add_command(command) self.default_cmd_name = cmd_name def parse_args(self, ctx: Context, args: list[str]) -> list[str]: """Parses the list of ``args`` by forwarding it to :meth:`cloup.Group.parse_args`. Before doing so, if :attr:`default_if_no_args` is set to ``True`` and ``args`` is empty, this function appends to it the name of the default command specified by :attr:`default_cmd_name`. Parameters ---------- ctx The Click context. args A list of arguments. If it's empty and :attr:`default_if_no_args` is ``True``, append the name of the default command to it. Returns ------- list[str] The parsed arguments. """ if not args and self.default_if_no_args and self.default_cmd_name: args.insert(0, self.default_cmd_name) parsed_args: list[str] = super().parse_args(ctx, args) return parsed_args def get_command(self, ctx: Context, cmd_name: str) -> Command | None: """Get a command function by its name, by forwarding the arguments to :meth:`cloup.Group.get_command`. If ``cmd_name`` does not match any of the command names in :attr:`commands`, attempt to get the default command instead. Parameters ---------- ctx The Click context. cmd_name The name of the command to get. Returns ------- :class:`click.Command` | None The command, if found. Otherwise, ``None``. """ if cmd_name not in self.commands and self.default_cmd_name: # No command name matched. ctx.meta["arg0"] = cmd_name cmd_name = self.default_cmd_name return super().get_command(ctx, cmd_name) def resolve_command( self, ctx: Context, args: list[str] ) -> tuple[str | None, Command | None, list[str]]: """Given a list of ``args`` given by a CLI, find a command which matches the first element, and return its name (``cmd_name``), the command function itself (``cmd``) and the rest of the arguments which shall be passed to the function (``cmd_args``). If not found, return ``None``, ``None`` and the rest of the arguments. After resolving the command, if
|
CLI, find a command which matches the first element, and return its name (``cmd_name``), the command function itself (``cmd``) and the rest of the arguments which shall be passed to the function (``cmd_args``). If not found, return ``None``, ``None`` and the rest of the arguments. After resolving the command, if the Click context given by ``ctx`` contains an ``arg0`` attribute in its :attr:`click.Context.meta` dictionary, insert it as the first element of the returned ``cmd_args``. Parameters ---------- ctx The Click context. cmd_name The name of the command to get. Returns ------- cmd_name : str | None The command name, if found. Otherwise, ``None``. cmd : :class:`click.Command` | None The command, if found. Otherwise, ``None``. cmd_args : list[str] The rest of the arguments to be passed to ``cmd``. """ cmd_name, cmd, args = super().resolve_command(ctx, args) if "arg0" in ctx.meta: args.insert(0, ctx.meta["arg0"]) if cmd is not None: cmd_name = cmd.name return cmd_name, cmd, args @deprecated def command( self, *args: Any, **kwargs: Any ) -> Callable[[Callable[..., object]], Command]: """Return a decorator which converts any function into the default subcommand for this :class:`DefaultGroup`. .. warning:: This method is deprecated. Use the ``default`` parameter of :class:`DefaultGroup` or :meth:`set_default_command` instead. Parameters ---------- *args Positional arguments to pass to :meth:`cloup.Group.command`. **kwargs Keyword arguments to pass to :meth:`cloup.Group.command`. Returns ------- Callable[[Callable[..., object]], click.Command] A decorator which transforms its input into this :class:`DefaultGroup`'s default subcommand. """ default = kwargs.pop("default", False) decorator: Callable[[Callable[..., object]], Command] = super().command( *args, **kwargs ) if not default: return decorator warnings.warn( "Use default param of DefaultGroup or set_default_command() instead", DeprecationWarning, stacklevel=1, ) def _decorator(f: Callable) -> Command: cmd = decorator(f) self.set_default_command(cmd) return cmd return _decorator ================================================ FILE: manim/cli/cfg/__init__.py ================================================ [Empty file] ================================================ FILE: manim/cli/cfg/group.py ================================================ """Manim's cfg subcommand. Manim's cfg subcommand is accessed in the command-line interface via ``manim cfg``. Here you can specify options, subcommands, and subgroups for the cfg group. """ from __future__ import annotations import contextlib from ast import literal_eval from pathlib import Path from typing import Any, cast import cloup from rich.errors import StyleSyntaxError from rich.style import Style from manim._config import cli_ctx_settings, console from manim._config.utils import config_file_paths, make_config_parser from manim.constants import EPILOG from manim.utils.file_ops import guarantee_existence, open_file RICH_COLOUR_INSTRUCTIONS: str = """ [red]The default colour is used by the input statement. If left empty, the default colour will be used.[/red] [magenta] For a full list of styles, visit[/magenta] [green]https://rich.readthedocs.io/en/latest/style.html[/green] """ RICH_NON_STYLE_ENTRIES: list[str] = ["log.width", "log.height", "log.timestamps"] __all__ = [ "value_from_string", "value_from_string", "is_valid_style", "replace_keys", "cfg", "write", "show", "export", ] def value_from_string(value: str) -> str | int | bool: """Extract the literal of proper datatype from a ``value`` string. Parameters ---------- value The value to check get the literal from. Returns ------- :class:`str` | :class:`int` | :class:`bool` The literal of appropriate datatype. """ with contextlib.suppress(SyntaxError, ValueError): value = literal_eval(value) return value def _is_expected_datatype( value: str, expected: str, validate_style: bool = False ) -> bool: """Check whether the literal from ``value`` is the same datatype as the literal from ``expected``. If ``validate_style`` is ``True``, also check if the style given by ``value`` is valid, according to
|
ValueError): value = literal_eval(value) return value def _is_expected_datatype( value: str, expected: str, validate_style: bool = False ) -> bool: """Check whether the literal from ``value`` is the same datatype as the literal from ``expected``. If ``validate_style`` is ``True``, also check if the style given by ``value`` is valid, according to ``rich``. Parameters ---------- value The string of the value to check, obtained from reading the user input. expected The string of the literal datatype which must be matched by ``value``. This is obtained from reading the ``cfg`` file. validate_style Whether or not to confirm if ``value`` is a valid style, according to ``rich``. Default is ``False``. Returns ------- :class:`bool` Whether or not the literal from ``value`` matches the datatype of the literal from ``expected``. """ value_literal = value_from_string(value) ExpectedLiteralType = type(value_from_string(expected)) return isinstance(value_literal, ExpectedLiteralType) and ( (isinstance(value_literal, str) and is_valid_style(value_literal)) if validate_style else True ) def is_valid_style(style: str) -> bool: """Checks whether the entered color style is valid, according to ``rich``. Parameters ---------- style The style to check whether it is valid. Returns ------- :class:`bool` Whether the color style is valid or not, according to ``rich``. """ try: Style.parse(style) return True except StyleSyntaxError: return False def replace_keys(default: dict[str, Any]) -> dict[str, Any]: """Replace ``_`` with ``.`` and vice versa in a dictionary's keys for ``rich``. Parameters ---------- default The dictionary whose keys will be checked and replaced. Returns ------- :class:`dict` The dictionary whose keys are modified by replacing ``_`` with ``.`` and vice versa. """ for key in default: if "_" in key: temp = default[key] del default[key] key = key.replace("_", ".") default[key] = temp else: temp = default[key] del default[key] key = key.replace(".", "_") default[key] = temp return default @cloup.group( context_settings=cli_ctx_settings, invoke_without_command=True, no_args_is_help=True, epilog=EPILOG, help="Manages Manim configuration files.", ) @cloup.pass_context def cfg(ctx: cloup.Context) -> None: """Responsible for the cfg subcommand.""" pass @cfg.command(context_settings=cli_ctx_settings, no_args_is_help=True) @cloup.option( "-l", "--level", type=cloup.Choice(["user", "cwd"], case_sensitive=False), default="cwd", help="Specify if this config is for user or the working directory.", ) @cloup.option("-o", "--open", "openfile", is_flag=True) def write(level: str | None = None, openfile: bool = False) -> None: config_paths = config_file_paths() console.print( "[yellow bold]Manim Configuration File Writer[/yellow bold]", justify="center", ) USER_CONFIG_MSG = f"""A configuration file at [yellow]{config_paths[1]}[/yellow] has been created with your required changes. This will be used when running the manim command. If you want to override this config, you will have to create a manim.cfg in the local directory, where you want those changes to be overridden.""" CWD_CONFIG_MSG = f"""A configuration file at [yellow]{config_paths[2]}[/yellow] has been created. To save your config please save that file and place it in your current working directory, from where you run the manim command.""" parser = make_config_parser() if not openfile: action = "save this as" for category in parser: console.print(f"{category}", style="bold green underline") default = cast(dict[str, Any], parser[category]) if category == "logger": console.print(RICH_COLOUR_INSTRUCTIONS) default = replace_keys(default) for key in default: # All the cfg entries for logger need to be validated as styles, # as long as they aren't setting the log width or height etc if category == "logger"
|
style="bold green underline") default = cast(dict[str, Any], parser[category]) if category == "logger": console.print(RICH_COLOUR_INSTRUCTIONS) default = replace_keys(default) for key in default: # All the cfg entries for logger need to be validated as styles, # as long as they aren't setting the log width or height etc if category == "logger" and key not in RICH_NON_STYLE_ENTRIES: desc = "style" style = default[key] else: desc = "value" style = None console.print(f"Enter the {desc} for {key} ", style=style, end="") if category != "logger" or key in RICH_NON_STYLE_ENTRIES: defaultval = ( repr(default[key]) if isinstance(value_from_string(default[key]), str) else default[key] ) console.print(f"(defaults to {defaultval}) :", end="") try: temp = input() except EOFError: raise Exception( """Not enough values in input. You may have added a new entry to default.cfg, in which case you will have to modify write_cfg_subcmd_input to account for it.""", ) from None if temp: while temp and not _is_expected_datatype( temp, default[key], bool(style), ): console.print( f"[red bold]Invalid {desc}. Try again.[/red bold]", ) console.print( f"Enter the {desc} for {key}:", style=style, end="", ) temp = input() default[key] = temp.replace("%", "%%") default = replace_keys(default) if category == "logger" else default parser[category] = { i: v.replace("%", "%%") for i, v in dict(default).items() } else: action = "open" if level is None: console.print( f"Do you want to {action} the default config for this User?(y/n)[[n]]", style="dim purple", end="", ) action_to_userpath = input() else: action_to_userpath = "" if action_to_userpath.lower() == "y" or level == "user": cfg_file_path = config_paths[1] guarantee_existence(config_paths[1].parents[0]) console.print(USER_CONFIG_MSG) else: cfg_file_path = config_paths[2] guarantee_existence(config_paths[2].parents[0]) console.print(CWD_CONFIG_MSG) with cfg_file_path.open("w") as fp: parser.write(fp) if openfile: open_file(cfg_file_path) @cfg.command(context_settings=cli_ctx_settings) def show() -> None: console.print("CONFIG FILES READ", style="bold green underline") for path in config_file_paths(): if path.exists(): console.print(f"{path}") console.print() parser = make_config_parser() rich_non_style_entries = [a.replace(".", "_") for a in RICH_NON_STYLE_ENTRIES] for category in parser: console.print(f"{category}", style="bold green underline") for entry in parser[category]: if category == "logger" and entry not in rich_non_style_entries: console.print(f"{entry} :", end="") console.print( f" {parser[category][entry]}", style=parser[category][entry], ) else: console.print(f"{entry} : {parser[category][entry]}") console.print("\n") @cfg.command(context_settings=cli_ctx_settings) @cloup.option("-d", "--directory", default=Path.cwd()) @cloup.pass_context def export(ctx: cloup.Context, directory: str) -> None: directory_path = Path(directory) if directory_path.absolute == Path.cwd().absolute: console.print( """You are reading the config from the same directory you are exporting to. This means that the exported config will overwrite the config for this directory. Are you sure you want to continue? (y/n)""", style="red bold", end="", ) proceed = input().lower() == "y" else: proceed = True if proceed: if not directory_path.is_dir(): console.print(f"Creating folder: {directory}.", style="red bold") directory_path.mkdir(parents=True) ctx.invoke(write) from_path = Path.cwd() / "manim.cfg" to_path = directory_path / "manim.cfg" console.print(f"Exported final Config at {from_path} to {to_path}.") else: console.print("Aborted...", style="red bold") ================================================ FILE: manim/cli/checkhealth/__init__.py ================================================ [Empty file] ================================================ FILE: manim/cli/checkhealth/checks.py ================================================ """Auxiliary module for the checkhealth subcommand, contains the actual check implementations. """ from __future__ import annotations import os import shutil from collections.abc import Callable from typing import Protocol, cast __all__ = ["HEALTH_CHECKS"] class HealthCheckFunction(Protocol): description: str recommendation: str skip_on_failed: list[str] post_fail_fix_hook: Callable[..., object] | None __name__: str def __call__(self) -> bool: ... HEALTH_CHECKS: list[HealthCheckFunction] = [] def healthcheck( description: str, recommendation: str, skip_on_failed: list[HealthCheckFunction | str] | None = None, post_fail_fix_hook: Callable[..., object] | None
|
typing import Protocol, cast __all__ = ["HEALTH_CHECKS"] class HealthCheckFunction(Protocol): description: str recommendation: str skip_on_failed: list[str] post_fail_fix_hook: Callable[..., object] | None __name__: str def __call__(self) -> bool: ... HEALTH_CHECKS: list[HealthCheckFunction] = [] def healthcheck( description: str, recommendation: str, skip_on_failed: list[HealthCheckFunction | str] | None = None, post_fail_fix_hook: Callable[..., object] | None = None, ) -> Callable[[Callable[[], bool]], HealthCheckFunction]: """Decorator used for declaring health checks. This decorator attaches some data to a function, which is then added to a a list containing all checks. Parameters ---------- description A brief description of this check, displayed when the ``checkhealth`` subcommand is run. recommendation Help text which is displayed in case the check fails. skip_on_failed A list of check functions which, if they fail, cause the current check to be skipped. post_fail_fix_hook A function that is meant to (interactively) help to fix the detected problem, if possible. This is only called upon explicit confirmation of the user. Returns ------- Callable[Callable[[], bool], :class:`HealthCheckFunction`] A decorator which converts a function into a health check function, as required by the ``checkhealth`` subcommand. """ new_skip_on_failed: list[str] if skip_on_failed is None: new_skip_on_failed = [] else: new_skip_on_failed = [ skip.__name__ if callable(skip) else skip for skip in skip_on_failed ] def wrapper(func: Callable[[], bool]) -> HealthCheckFunction: health_func = cast(HealthCheckFunction, func) health_func.description = description health_func.recommendation = recommendation health_func.skip_on_failed = new_skip_on_failed health_func.post_fail_fix_hook = post_fail_fix_hook HEALTH_CHECKS.append(health_func) return health_func return wrapper @healthcheck( description="Checking whether manim is on your PATH", recommendation=( "The command <manim> is currently not on your system's PATH.\n\n" "You can work around this by calling the manim module directly " "via <python -m manim> instead of just <manim>.\n\n" "To fix the PATH issue properly: " "Usually, the Python package installer pip issues a warning " "during the installation which contains more information. " "Consider reinstalling manim via <pip uninstall manim> " "followed by <pip install manim> to see the warning again, " "then consult the internet on how to modify your system's " "PATH variable." ), ) def is_manim_on_path() -> bool: """Check whether ``manim`` is in ``PATH``. Returns ------- :class:`bool` Whether ``manim`` is in ``PATH`` or not. """ path_to_manim = shutil.which("manim") return path_to_manim is not None @healthcheck( description="Checking whether the executable belongs to manim", recommendation=( "The command <manim> does not belong to your installed version " "of this library, it likely belongs to manimgl / manimlib.\n\n" "Run manim via <python -m manim> or via <manimce>, or uninstall " "and reinstall manim via <pip install --upgrade " "--force-reinstall manim> to fix this." ), skip_on_failed=[is_manim_on_path], ) def is_manim_executable_associated_to_this_library() -> bool: """Check whether the ``manim`` executable in ``PATH`` is associated to this library. To verify this, the executable should look like this: .. code-block:: python #!<MANIM_PATH>/.../python import sys from manim.__main__ import main if __name__ == "__main__": sys.exit(main()) Returns ------- :class:`bool` Whether the ``manim`` executable in ``PATH`` is associated to this library or not. """ path_to_manim = shutil.which("manim") assert path_to_manim is not None with open(path_to_manim, "rb") as manim_binary: manim_exec = manim_binary.read() # first condition below corresponds to the executable being # some sort of python script. second condition
|
Returns ------- :class:`bool` Whether the ``manim`` executable in ``PATH`` is associated to this library or not. """ path_to_manim = shutil.which("manim") assert path_to_manim is not None with open(path_to_manim, "rb") as manim_binary: manim_exec = manim_binary.read() # first condition below corresponds to the executable being # some sort of python script. second condition happens when # the executable is actually a Windows batch file. return b"manim.__main__" in manim_exec or b'"%~dp0\\manim"' in manim_exec @healthcheck( description="Checking whether latex is available", recommendation=( "Manim cannot find <latex> on your system's PATH. " "You will not be able to use Tex and MathTex mobjects " "in your scenes.\n\n" "Consult our installation instructions " "at https://docs.manim.community/en/stable/installation.html " "or search the web for instructions on how to install a " "LaTeX distribution on your operating system." ), ) def is_latex_available() -> bool: """Check whether ``latex`` is in ``PATH`` and can be executed. Returns ------- :class:`bool` Whether ``latex`` is in ``PATH`` and can be executed or not. """ path_to_latex = shutil.which("latex") return path_to_latex is not None and os.access(path_to_latex, os.X_OK) @healthcheck( description="Checking whether dvisvgm is available", recommendation=( "Manim could find <latex>, but not <dvisvgm> on your system's " "PATH. Make sure your installed LaTeX distribution comes with " "dvisvgm and consider installing a larger distribution if it " "does not." ), skip_on_failed=[is_latex_available], ) def is_dvisvgm_available() -> bool: """Check whether ``dvisvgm`` is in ``PATH`` and can be executed. Returns ------- :class:`bool` Whether ``dvisvgm`` is in ``PATH`` and can be executed or not. """ path_to_dvisvgm = shutil.which("dvisvgm") return path_to_dvisvgm is not None and os.access(path_to_dvisvgm, os.X_OK) ================================================ FILE: manim/cli/checkhealth/commands.py ================================================ """A CLI utility helping to diagnose problems with your Manim installation. """ from __future__ import annotations import sys import timeit import click import cloup from manim.cli.checkhealth.checks import HEALTH_CHECKS, HealthCheckFunction __all__ = ["checkhealth"] @cloup.command( context_settings=None, ) def checkhealth() -> None: """This subcommand checks whether Manim is installed correctly and has access to its required (and optional) system dependencies. """ click.echo(f"Python executable: {sys.executable}\n") click.echo("Checking whether your installation of Manim Community is healthy...") failed_checks: list[HealthCheckFunction] = [] for check in HEALTH_CHECKS: click.echo(f"- {check.description} ... ", nl=False) if any( failed_check.__name__ in check.skip_on_failed for failed_check in failed_checks ): click.secho("SKIPPED", fg="blue") continue check_result = check() if check_result: click.secho("PASSED", fg="green") else: click.secho("FAILED", fg="red") failed_checks.append(check) click.echo() if failed_checks: click.echo( "There are problems with your installation, " "here are some recommendations to fix them:" ) for ind, failed_check in enumerate(failed_checks): click.echo(failed_check.recommendation) if ind + 1 < len(failed_checks): click.confirm("Continue with next recommendation?") else: # no problems detected! click.echo("No problems detected, your installation seems healthy!") render_test_scene = click.confirm( "Would you like to render and preview a test scene?" ) if render_test_scene: import manim as mn class CheckHealthDemo(mn.Scene): def _inner_construct(self) -> None: banner = mn.ManimBanner().shift(mn.UP * 0.5) self.play(banner.create()) self.wait(0.5) self.play(banner.expand()) self.wait(0.5) text_left = mn.Text("All systems operational!") formula_right = mn.MathTex(r"\oint_{\gamma} f(z)~dz = 0") text_tex_group = mn.VGroup(text_left, formula_right) text_tex_group.arrange(mn.RIGHT, buff=1).next_to(banner, mn.DOWN) self.play(mn.Write(text_tex_group)) self.wait(0.5) self.play( mn.FadeOut(banner, shift=mn.UP), mn.FadeOut(text_tex_group, shift=mn.DOWN), ) def construct(self) -> None: self.execution_time = timeit.timeit(self._inner_construct, number=1) with mn.tempconfig({"preview": True, "disable_caching": True}): scene = CheckHealthDemo() scene.render() click.echo(f"Scene rendered in {scene.execution_time:.2f} seconds.") ================================================ FILE: manim/cli/init/__init__.py ================================================ [Empty file] ================================================ FILE:
|
= mn.MathTex(r"\oint_{\gamma} f(z)~dz = 0") text_tex_group = mn.VGroup(text_left, formula_right) text_tex_group.arrange(mn.RIGHT, buff=1).next_to(banner, mn.DOWN) self.play(mn.Write(text_tex_group)) self.wait(0.5) self.play( mn.FadeOut(banner, shift=mn.UP), mn.FadeOut(text_tex_group, shift=mn.DOWN), ) def construct(self) -> None: self.execution_time = timeit.timeit(self._inner_construct, number=1) with mn.tempconfig({"preview": True, "disable_caching": True}): scene = CheckHealthDemo() scene.render() click.echo(f"Scene rendered in {scene.execution_time:.2f} seconds.") ================================================ FILE: manim/cli/init/__init__.py ================================================ [Empty file] ================================================ FILE: manim/cli/init/commands.py ================================================ """Manim's init subcommand. Manim's init subcommand is accessed in the command-line interface via ``manim init``. Here you can specify options, subcommands, and subgroups for the init group. """ from __future__ import annotations import configparser from pathlib import Path from typing import Any import click import cloup from manim._config import console from manim.constants import CONTEXT_SETTINGS, EPILOG, QUALITIES from manim.utils.file_ops import ( add_import_statement, copy_template_files, get_template_names, get_template_path, ) CFG_DEFAULTS = { "frame_rate": 30, "background_color": "BLACK", "background_opacity": 1, "scene_names": "Default", "resolution": (854, 480), } __all__ = ["select_resolution", "update_cfg", "project", "scene"] def select_resolution() -> tuple[int, int]: """Prompts input of type click.Choice from user. Presents options from QUALITIES constant. Returns ------- tuple[int, int] Tuple containing height and width. """ resolution_options: list[tuple[int, int]] = [] for quality in QUALITIES.items(): resolution_options.append( (quality[1]["pixel_height"], quality[1]["pixel_width"]), ) resolution_options.pop() choice = click.prompt( "\nSelect resolution:\n", type=cloup.Choice([f"{i[0]}p" for i in resolution_options]), show_default=False, default="480p", ) matches = [res for res in resolution_options if f"{res[0]}p" == choice] return matches[0] def update_cfg(cfg_dict: dict[str, Any], project_cfg_path: Path) -> None: """Update the ``manim.cfg`` file after reading it from the specified ``project_cfg_path``. Parameters ---------- cfg_dict Values used to update ``manim.cfg`` which is found in ``project_cfg_path``. project_cfg_path Path of the ``manim.cfg`` file. """ config = configparser.ConfigParser() config.read(project_cfg_path) cli_config = config["CLI"] for key, value in cfg_dict.items(): if key == "resolution": cli_config["pixel_width"] = str(value[0]) cli_config["pixel_height"] = str(value[1]) else: cli_config[key] = str(value) with project_cfg_path.open("w") as conf: config.write(conf) @cloup.command( context_settings=CONTEXT_SETTINGS, epilog=EPILOG, ) @cloup.argument("project_name", type=cloup.Path(path_type=Path), required=False) @cloup.option( "-d", "--default", "default_settings", is_flag=True, help="Default settings for project creation.", nargs=1, ) def project(default_settings: bool, **kwargs: Any) -> None: """Creates a new project. PROJECT_NAME is the name of the folder in which the new project will be initialized. """ project_name: Path if kwargs["project_name"]: project_name = kwargs["project_name"] else: project_name = click.prompt("Project Name", type=Path) # in the future when implementing a full template system. Choices are going to be saved in some sort of config file for templates template_name = click.prompt( "Template", type=click.Choice(get_template_names(), False), default="Default", ) if project_name.is_dir(): console.print( f"\nFolder [red]{project_name}[/red] exists. Please type another name\n", ) else: project_name.mkdir() new_cfg: dict[str, Any] = {} new_cfg_path = Path.resolve(project_name / "manim.cfg") if not default_settings: for key, value in CFG_DEFAULTS.items(): if key == "scene_names": new_cfg[key] = template_name + "Template" elif key == "resolution": new_cfg[key] = select_resolution() else: new_cfg[key] = click.prompt(f"\n{key}", default=value) console.print("\n", new_cfg) if click.confirm("Do you want to continue?", default=True, abort=True): copy_template_files(project_name, template_name) update_cfg(new_cfg, new_cfg_path) else: copy_template_files(project_name, template_name) update_cfg(CFG_DEFAULTS, new_cfg_path) @cloup.command( context_settings=CONTEXT_SETTINGS, no_args_is_help=True, epilog=EPILOG, ) @cloup.argument("scene_name", type=str, required=True) @cloup.argument("file_name", type=str, required=False) def scene(**kwargs: Any) -> None: """Inserts a SCENE to an existing FILE or creates a new FILE. SCENE is the name of the scene that will be inserted. FILE is the name of file in which the SCENE will be inserted. """ template_name: str = click.prompt( "template", type=click.Choice(get_template_names(), False), default="Default", ) scene
|
Any) -> None: """Inserts a SCENE to an existing FILE or creates a new FILE. SCENE is the name of the scene that will be inserted. FILE is the name of file in which the SCENE will be inserted. """ template_name: str = click.prompt( "template", type=click.Choice(get_template_names(), False), default="Default", ) scene = (get_template_path() / f"{template_name}.mtp").resolve().read_text() scene = scene.replace(template_name + "Template", kwargs["scene_name"], 1) if kwargs["file_name"]: file_name = Path(kwargs["file_name"]) if file_name.suffix != ".py": file_name = file_name.with_suffix(file_name.suffix + ".py") if file_name.is_file(): # file exists so we are going to append new scene to that file with file_name.open("a") as f: f.write("\n\n\n" + scene) else: # file does not exist so we create a new file, append the scene and prepend the import statement file_name.write_text("\n\n\n" + scene) add_import_statement(file_name) else: # file name is not provided so we assume it is main.py # if main.py does not exist we do not continue with Path("main.py").open("a") as f: f.write("\n\n\n" + scene) @cloup.group( context_settings=CONTEXT_SETTINGS, invoke_without_command=True, no_args_is_help=True, epilog=EPILOG, help="Create a new project or insert a new scene.", ) @cloup.pass_context def init(ctx: cloup.Context) -> None: pass init.add_command(project) init.add_command(scene) ================================================ FILE: manim/cli/plugins/__init__.py ================================================ [Empty file] ================================================ FILE: manim/cli/plugins/commands.py ================================================ """Manim's plugin subcommand. Manim's plugin subcommand is accessed in the command-line interface via ``manim plugin``. Here you can specify options, subcommands, and subgroups for the plugin group. """ from __future__ import annotations import cloup from manim.constants import CONTEXT_SETTINGS, EPILOG from manim.plugins.plugins_flags import list_plugins __all__ = ["plugins"] @cloup.command( context_settings=CONTEXT_SETTINGS, no_args_is_help=True, epilog=EPILOG, help="Manages Manim plugins.", ) @cloup.option( "-l", "--list", "list_available", is_flag=True, help="List available plugins.", ) def plugins(list_available: bool) -> None: """Print a list of all available plugins when calling ``manim plugins -l`` or ``manim plugins --list``. Parameters ---------- list_available If the ``-l`` or ``-list`` option is passed to ``manim plugins``, this parameter will be set to ``True``, which will print a list of all available plugins. """ if list_available: list_plugins() ================================================ FILE: manim/cli/render/__init__.py ================================================ [Empty file] ================================================ FILE: manim/cli/render/commands.py ================================================ """Manim's default subcommand, render. Manim's render subcommand is accessed in the command-line interface via ``manim``, but can be more explicitly accessed with ``manim render``. Here you can specify options, and arguments for the render command. """ from __future__ import annotations import http.client import json import sys import urllib.error import urllib.request from argparse import Namespace from pathlib import Path from typing import Any, cast import cloup from manim import __version__ from manim._config import ( config, console, error_console, logger, tempconfig, ) from manim.cli.render.ease_of_access_options import ease_of_access_options from manim.cli.render.global_options import global_options from manim.cli.render.output_options import output_options from manim.cli.render.render_options import render_options from manim.constants import EPILOG, RendererType from manim.utils.module_ops import scene_classes_from_file __all__ = ["render"] class ClickArgs(Namespace): def __init__(self, args: dict[str, Any]) -> None: for name in args: setattr(self, name, args[name]) def _get_kwargs(self) -> list[tuple[str, Any]]: return list(self.__dict__.items()) def __eq__(self, other: object) -> bool: if not isinstance(other, ClickArgs): return NotImplemented return vars(self) == vars(other) def __contains__(self, key: str) -> bool: return key in self.__dict__ def __repr__(self) -> str: return str(self.__dict__) @cloup.command( context_settings=None, no_args_is_help=True, epilog=EPILOG, ) @cloup.argument("file", type=cloup.Path(path_type=Path), required=True) @cloup.argument("scene_names", required=False, nargs=-1) @global_options @output_options @render_options @ease_of_access_options def render(**kwargs: Any) -> ClickArgs | dict[str, Any]: """Render
|
if not isinstance(other, ClickArgs): return NotImplemented return vars(self) == vars(other) def __contains__(self, key: str) -> bool: return key in self.__dict__ def __repr__(self) -> str: return str(self.__dict__) @cloup.command( context_settings=None, no_args_is_help=True, epilog=EPILOG, ) @cloup.argument("file", type=cloup.Path(path_type=Path), required=True) @cloup.argument("scene_names", required=False, nargs=-1) @global_options @output_options @render_options @ease_of_access_options def render(**kwargs: Any) -> ClickArgs | dict[str, Any]: """Render SCENE(S) from the input FILE. FILE is the file path of the script or a config file. SCENES is an optional list of scenes in the file. """ if kwargs["save_as_gif"]: logger.warning("--save_as_gif is deprecated, please use --format=gif instead!") kwargs["format"] = "gif" if kwargs["save_pngs"]: logger.warning("--save_pngs is deprecated, please use --format=png instead!") kwargs["format"] = "png" if kwargs["show_in_file_browser"]: logger.warning( "The short form of show_in_file_browser is deprecated and will be moved to support --format.", ) click_args = ClickArgs(kwargs) if kwargs["jupyter"]: return click_args config.digest_args(click_args) file = Path(config.input_file) if config.renderer == RendererType.OPENGL: from manim.renderer.opengl_renderer import OpenGLRenderer try: renderer = OpenGLRenderer() keep_running = True while keep_running: for SceneClass in scene_classes_from_file(file): with tempconfig({}): scene = SceneClass(renderer) rerun = scene.render() if rerun or config["write_all"]: renderer.num_plays = 0 continue else: keep_running = False break if config["write_all"]: keep_running = False except Exception: error_console.print_exception() sys.exit(1) else: for SceneClass in scene_classes_from_file(file): try: with tempconfig({}): scene = SceneClass() scene.render() except Exception: error_console.print_exception() sys.exit(1) if config.notify_outdated_version: manim_info_url = "https://pypi.org/pypi/manim/json" warn_prompt = "Cannot check if latest release of manim is installed" try: with urllib.request.urlopen( urllib.request.Request(manim_info_url), timeout=10, ) as response: response = cast(http.client.HTTPResponse, response) json_data = json.loads(response.read()) except urllib.error.HTTPError: logger.debug("HTTP Error: %s", warn_prompt) except urllib.error.URLError: logger.debug("URL Error: %s", warn_prompt) except json.JSONDecodeError: logger.debug( "Error while decoding JSON from %r: %s", manim_info_url, warn_prompt ) except Exception: logger.debug("Something went wrong: %s", warn_prompt) else: stable = json_data["info"]["version"] if stable != __version__: console.print( f"You are using manim version [red]v{__version__}[/red], but version [green]v{stable}[/green] is available.", ) console.print( "You should consider upgrading via [yellow]pip install -U manim[/yellow]", ) return kwargs ================================================ FILE: manim/cli/render/ease_of_access_options.py ================================================ from __future__ import annotations from cloup import Choice, option, option_group __all__ = ["ease_of_access_options"] ease_of_access_options = option_group( "Ease of access options", option( "--progress_bar", default=None, show_default=False, type=Choice( ["display", "leave", "none"], case_sensitive=False, ), help="Display progress bars and/or keep them displayed.", ), option( "-p", "--preview", is_flag=True, help="Preview the Scene's animation. OpenGL does a live preview in a " "popup window. Cairo opens the rendered video file in the system " "default media player.", default=None, ), option( "-f", "--show_in_file_browser", is_flag=True, help="Show the output file in the file browser.", default=None, ), option( "--jupyter", is_flag=True, help="Using jupyter notebook magic.", default=None, ), ) ================================================ FILE: manim/cli/render/global_options.py ================================================ from __future__ import annotations import logging import re import sys from typing import TYPE_CHECKING from cloup import Choice, option, option_group if TYPE_CHECKING: from click import Context, Option __all__ = ["global_options"] logger = logging.getLogger("manim") def validate_gui_location( ctx: Context, param: Option, value: str | None ) -> tuple[int, int] | None: """If the ``value`` string is given, extract from it the GUI location, which should be in any of these formats: 'x;y', 'x,y' or 'x-y'. Parameters ---------- ctx The Click context. param A Click option. value The optional string which will be parsed. Returns ------- tuple[int, int] | None If ``value`` is ``None``, the
|
string is given, extract from it the GUI location, which should be in any of these formats: 'x;y', 'x,y' or 'x-y'. Parameters ---------- ctx The Click context. param A Click option. value The optional string which will be parsed. Returns ------- tuple[int, int] | None If ``value`` is ``None``, the return value is ``None``. Otherwise, it's the ``(x, y)`` location for the GUI. Raises ------ ValueError If ``value`` has an invalid format. """ if value is None: return None try: x_offset, y_offset = map(int, re.split(r"[;,\-]", value)) except Exception: logger.error("GUI location option is invalid.") sys.exit() return (x_offset, y_offset) global_options = option_group( "Global options", option( "-c", "--config_file", help="Specify the configuration file to use for render settings.", default=None, ), option( "--custom_folders", is_flag=True, default=None, help="Use the folders defined in the [custom_folders] section of the " "config file to define the output folder structure.", ), option( "--disable_caching", is_flag=True, default=None, help="Disable the use of the cache (still generates cache files).", ), option( "--flush_cache", is_flag=True, help="Remove cached partial movie files.", default=None, ), option("--tex_template", help="Specify a custom TeX template file.", default=None), option( "-v", "--verbosity", type=Choice( ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], case_sensitive=False, ), help="Verbosity of CLI output. Changes ffmpeg log level unless 5+.", default=None, ), option( "--notify_outdated_version/--silent", is_flag=True, default=None, help="Display warnings for outdated installation.", ), option( "--enable_gui", is_flag=True, help="Enable GUI interaction.", default=None, ), option( "--gui_location", default=None, callback=validate_gui_location, help="Starting location for the GUI.", ), option( "--fullscreen", is_flag=True, help="Expand the window to its maximum possible size.", default=None, ), option( "--enable_wireframe", is_flag=True, help="Enable wireframe debugging mode in opengl.", default=None, ), option( "--force_window", is_flag=True, help="Force window to open when using the opengl renderer, intended for debugging as it may impact performance", default=None, ), option( "--dry_run", is_flag=True, help="Renders animations without outputting image or video files and disables the window", default=None, ), option( "--no_latex_cleanup", is_flag=True, help="Prevents deletion of .aux, .dvi, and .log files produced by Tex and MathTex.", default=None, ), option( "--preview_command", help="The command used to preview the output file (for example vlc for video files)", default=None, ), ) ================================================ FILE: manim/cli/render/output_options.py ================================================ from __future__ import annotations from cloup import IntRange, Path, option, option_group __all__ = ["output_options"] output_options = option_group( "Output options", option( "-o", "--output_file", type=str, default=None, help="Specify the filename(s) of the rendered scene(s).", ), option( "-0", "--zero_pad", type=IntRange(0, 9), default=None, help="Zero padding for PNG file names.", ), option( "--write_to_movie", is_flag=True, default=None, help="Write the video rendered with opengl to a file.", ), option( "--media_dir", type=Path(), default=None, help="Path to store rendered videos and latex.", ), option( "--log_dir", type=Path(), help="Path to store render logs.", default=None, ), option( "--log_to_file", is_flag=True, default=None, help="Log terminal output to file.", ), ) ================================================ FILE: manim/cli/render/render_options.py ================================================ from __future__ import annotations import logging import re import sys from typing import TYPE_CHECKING from cloup import Choice, option, option_group from manim.constants import QUALITIES, RendererType if TYPE_CHECKING: from click import Context, Option __all__ = ["render_options"] logger = logging.getLogger("manim") def validate_scene_range( ctx: Context, param: Option, value: str | None ) -> tuple[int] | tuple[int, int] | None: """If the ``value`` string is given, extract from it the scene range, which should be in any of these formats:
|
TYPE_CHECKING: from click import Context, Option __all__ = ["render_options"] logger = logging.getLogger("manim") def validate_scene_range( ctx: Context, param: Option, value: str | None ) -> tuple[int] | tuple[int, int] | None: """If the ``value`` string is given, extract from it the scene range, which should be in any of these formats: 'start', 'start;end', 'start,end' or 'start-end'. Otherwise, return ``None``. Parameters ---------- ctx The Click context. param A Click option. value The optional string which will be parsed. Returns ------- tuple[int] | tuple[int, int] | None If ``value`` is ``None``, the return value is ``None``. Otherwise, it's the scene range, given by a tuple which may contain a single value ``start`` or two values ``start`` and ``end``. Raises ------ ValueError If ``value`` has an invalid format. """ if value is None: return None try: start = int(value) return (start,) except Exception: pass try: start, end = map(int, re.split(r"[;,\-]", value)) except Exception: logger.error("Couldn't determine a range for -n option.") sys.exit() return start, end def validate_resolution( ctx: Context, param: Option, value: str | None ) -> tuple[int, int] | None: """If the ``value`` string is given, extract from it the resolution, which should be in any of these formats: 'W;H', 'W,H' or 'W-H'. Otherwise, return ``None``. Parameters ---------- ctx The Click context. param A Click option. value The optional string which will be parsed. Returns ------- tuple[int, int] | None If ``value`` is ``None``, the return value is ``None``. Otherwise, it's the resolution as a ``(W, H)`` tuple. Raises ------ ValueError If ``value`` has an invalid format. """ if value is None: return None try: width, height = map(int, re.split(r"[;,\-]", value)) except Exception: logger.error("Resolution option is invalid.") sys.exit() return width, height render_options = option_group( "Render Options", option( "-n", "--from_animation_number", callback=validate_scene_range, help="Start rendering from n_0 until n_1. If n_1 is left unspecified, " "renders all scenes after n_0.", default=None, ), option( "-a", "--write_all", is_flag=True, help="Render all scenes in the input file.", default=None, ), option( "--format", type=Choice(["png", "gif", "mp4", "webm", "mov"], case_sensitive=False), default=None, ), option( "-s", "--save_last_frame", default=None, is_flag=True, help="Render and save only the last frame of a scene as a PNG image.", ), option( "-q", "--quality", default=None, type=Choice( list(reversed([q["flag"] for q in QUALITIES.values() if q["flag"]])), case_sensitive=False, ), help="Render quality at the follow resolution framerates, respectively: " + ", ".join( reversed( [ f"{q['pixel_width']}x{q['pixel_height']} {q['frame_rate']}FPS" for q in QUALITIES.values() if q["flag"] ] ) ), ), option( "-r", "--resolution", callback=validate_resolution, default=None, help='Resolution in "W,H" for when 16:9 aspect ratio isn\'t possible.', ), option( "--fps", "--frame_rate", "frame_rate", type=float, default=None, help="Render at this frame rate.", ), option( "--renderer", type=Choice( [renderer_type.value for renderer_type in RendererType], case_sensitive=False, ), help="Select a renderer for your Scene.", default="cairo", ), option( "-g", "--save_pngs", is_flag=True, default=None, help="Save each frame as png (Deprecated).", ), option( "-i", "--save_as_gif", default=None, is_flag=True, help="Save as a gif (Deprecated).", ), option( "--save_sections", default=None, is_flag=True, help="Save section videos in addition to movie file.", ), option( "-t", "--transparent", is_flag=True, help="Render scenes with alpha channel.", ), option( "--use_projection_fill_shaders", is_flag=True, help="Use shaders for OpenGLVMobject fill which are compatible with transformation matrices.", default=None, ), option( "--use_projection_stroke_shaders", is_flag=True, help="Use
|
is_flag=True, help="Save as a gif (Deprecated).", ), option( "--save_sections", default=None, is_flag=True, help="Save section videos in addition to movie file.", ), option( "-t", "--transparent", is_flag=True, help="Render scenes with alpha channel.", ), option( "--use_projection_fill_shaders", is_flag=True, help="Use shaders for OpenGLVMobject fill which are compatible with transformation matrices.", default=None, ), option( "--use_projection_stroke_shaders", is_flag=True, help="Use shaders for OpenGLVMobject stroke which are compatible with transformation matrices.", default=None, ), ) ================================================ FILE: manim/mobject/__init__.py ================================================ [Empty file] ================================================ FILE: manim/mobject/frame.py ================================================ """Special rectangles.""" from __future__ import annotations __all__ = [ "ScreenRectangle", "FullScreenRectangle", ] from typing import Any from manim.mobject.geometry.polygram import Rectangle from .. import config class ScreenRectangle(Rectangle): def __init__( self, aspect_ratio: float = 16.0 / 9.0, height: float = 4, **kwargs: Any ) -> None: super().__init__(width=aspect_ratio * height, height=height, **kwargs) @property def aspect_ratio(self) -> float: """The aspect ratio. When set, the width is stretched to accommodate the new aspect ratio. """ return self.width / self.height @aspect_ratio.setter def aspect_ratio(self, value: float) -> None: self.stretch_to_fit_width(value * self.height) class FullScreenRectangle(ScreenRectangle): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self.height = config["frame_height"] ================================================ FILE: manim/mobject/logo.py ================================================ """Utilities for Manim's logo and banner.""" from __future__ import annotations __all__ = ["ManimBanner"] from typing import Any import svgelements as se from manim.animation.updaters.update import UpdateFromAlphaFunc from manim.mobject.geometry.arc import Circle from manim.mobject.geometry.polygram import Square, Triangle from manim.mobject.mobject import Mobject from manim.typing import Vector3D from .. import constants as cst from ..animation.animation import override_animation from ..animation.composition import AnimationGroup, Succession from ..animation.creation import Create, SpiralIn from ..animation.fading import FadeIn from ..mobject.svg.svg_mobject import VMobjectFromSVGPath from ..mobject.types.vectorized_mobject import VGroup from ..utils.rate_functions import ease_in_out_cubic, smooth MANIM_SVG_PATHS: list[se.Path] = [ se.Path( # double stroke letter M "M4.64259-2.092154L2.739726-6.625156C2.660025-6.824408 2.650062-6.824408 " "2.381071-6.824408H.52802C.348692-6.824408 .199253-6.824408 .199253-6.645" "081C.199253-6.475716 .37858-6.475716 .428394-6.475716C.547945-6.475716 ." "816936-6.455791 1.036115-6.37609V-1.05604C1.036115-.846824 1.036115-.408" "468 .358655-.348692C.169365-.328767 .169365-.18929 .169365-.179328C.1693" "65 0 .328767 0 .508095 0H2.052304C2.231631 0 2.381071 0 2.381071-.179328" "C2.381071-.268991 2.30137-.33873 2.221669-.348692C1.454545-.408468 1.454" "545-.826899 1.454545-1.05604V-6.017435L1.464508-6.027397L3.895392-.20921" "5C3.975093-.029888 4.044832 0 4.104608 0C4.224159 0 4.254047-.079701 4.3" "03861-.199253L6.744707-6.027397L6.75467-6.017435V-1.05604C6.75467-.84682" "4 6.75467-.408468 6.07721-.348692C5.88792-.328767 5.88792-.18929 5.88792" "-.179328C5.88792 0 6.047323 0 6.22665 0H8.886675C9.066002 0 9.215442 0 9" ".215442-.179328C9.215442-.268991 9.135741-.33873 9.05604-.348692C8.28891" "7-.408468 8.288917-.826899 8.288917-1.05604V-5.768369C8.288917-5.977584 " "8.288917-6.41594 8.966376-6.475716C9.066002-6.485679 9.155666-6.535492 9" ".155666-6.645081C9.155666-6.824408 9.006227-6.824408 8.826899-6.824408H6" ".90411C6.645081-6.824408 6.625156-6.824408 6.535492-6.615193L4.64259-2.0" "92154ZM4.343711-1.912827C4.423412-1.743462 4.433375-1.733499 4.552927-1." "693649L4.11457-.637609H4.094645L1.823163-6.057285C1.77335-6.1868 1.69364" "9-6.356164 1.554172-6.475716H2.420922L4.343711-1.912827ZM1.334994-.34869" "2H1.165629C1.185554-.37858 1.205479-.408468 1.225405-.428394C1.235367-.4" "38356 1.235367-.448319 1.24533-.458281L1.334994-.348692ZM7.103362-6.4757" "16H8.159402C7.940224-6.22665 7.940224-5.967621 7.940224-5.788294V-1.0361" "15C7.940224-.856787 7.940224-.597758 8.169365-.348692H6.884184C7.103362-" ".597758 7.103362-.856787 7.103362-1.036115V-6.475716Z" ), se.Path( # letter a "M1.464508-4.024907C1.464508-4.234122 1.743462-4.393524 2.092154-4.393524" "C2.669988-4.393524 2.929016-4.124533 2.929016-3.516812V-2.789539C1.77335" "-2.440847 .249066-2.042341 .249066-.916563C.249066-.308842 .71731 .13947" "7 1.354919 .139477C1.92279 .139477 2.381071-.059776 2.929016-.557908C3.0" "38605-.049813 3.257783 .139477 3.745953 .139477C4.174346 .139477 4.48318" "8-.019925 4.861768-.428394L4.712329-.637609L4.612702-.537983C4.582814-.5" "08095 4.552927-.498132 4.503113-.498132C4.363636-.498132 4.293898-.58779" "6 4.293898-.747198V-3.347447C4.293898-4.184309 3.536737-4.712329 2.32129" "5-4.712329C1.195517-4.712329 .438356-4.204234 .438356-3.457036C.438356-3" ".048568 .67746-2.799502 1.085928-2.799502C1.484433-2.799502 1.763387-3.0" "38605 1.763387-3.377335C1.763387-3.676214 1.464508-3.88543 1.464508-4.02" "4907ZM2.919054-.996264C2.650062-.687422 2.450809-.56787 2.211706-.56787C" "1.912827-.56787 1.703611-.836862 1.703611-1.235367C1.703611-1.8132 2.122" "042-2.231631 2.919054-2.440847V-.996264Z" ), se.Path( # letter n "M2.948941-4.044832C3.297634-4.044832 3.466999-3.775841 3.466999-3.217933" "V-.806974C3.466999-.438356 3.337484-.278954 2.998755-.239103V0H5.339975V" "-.239103C4.951432-.268991 4.851806-.388543 4.851806-.806974V-3.307597C4." "851806-4.164384 4.323786-4.712329 3.506849-4.712329C2.909091-4.712329 2." "450809-4.433375 2.082192-3.845579V-4.592777H.179328V-4.353674C.617684-4." "283935 .707347-4.184309 .707347-3.765878V-.836862C.707347-.418431 .62764" "6-.328767 .179328-.239103V0H2.580324V-.239103C2.211706-.288917 2.092154-" ".438356 2.092154-.806974V-3.466999C2.092154-3.576588 2.530511-4.044832 2" ".948941-4.044832Z" ), se.Path( # letter i "M2.15193-4.592777H.239103V-4.353674C.67746-4.26401 .767123-4.174346 .767" "123-3.765878V-.836862C.767123-.428394 .697385-.348692 .239103-.239103V0H" "2.6401V-.239103C2.291407-.288917 2.15193-.428394 2.15193-.806974V-4.5927" "77ZM1.454545-6.884184C1.026152-6.884184 .67746-6.535492 .67746-6.117061C" ".67746-5.668742 1.006227-5.339975 1.444583-5.339975S2.221669-5.668742 2." "221669-6.107098C2.221669-6.535492 1.882939-6.884184 1.454545-6.884184Z" ), se.Path( # letter m "M2.929016-4.044832C3.317559-4.044832 3.466999-3.815691 3.466999-3.217933" "V-.806974C3.466999-.398506 3.35741-.268991 2.988792-.239103V0H5.32005V-." "239103C4.971357-.278954 4.851806-.428394 4.851806-.806974V-3.466999C4.85" "1806-3.576588 5.310087-4.044832 5.69863-4.044832C6.07721-4.044832 6.2266" "5-3.805729 6.22665-3.217933V-.806974C6.22665-.388543 6.117061-.268991 5." "738481-.239103V0H8.109589V-.239103C7.721046-.259029 7.611457-.37858 7.61" "1457-.806974V-3.307597C7.611457-4.164384 7.083437-4.712329
|
se.Path( # letter i "M2.15193-4.592777H.239103V-4.353674C.67746-4.26401 .767123-4.174346 .767" "123-3.765878V-.836862C.767123-.428394 .697385-.348692 .239103-.239103V0H" "2.6401V-.239103C2.291407-.288917 2.15193-.428394 2.15193-.806974V-4.5927" "77ZM1.454545-6.884184C1.026152-6.884184 .67746-6.535492 .67746-6.117061C" ".67746-5.668742 1.006227-5.339975 1.444583-5.339975S2.221669-5.668742 2." "221669-6.107098C2.221669-6.535492 1.882939-6.884184 1.454545-6.884184Z" ), se.Path( # letter m "M2.929016-4.044832C3.317559-4.044832 3.466999-3.815691 3.466999-3.217933" "V-.806974C3.466999-.398506 3.35741-.268991 2.988792-.239103V0H5.32005V-." "239103C4.971357-.278954 4.851806-.428394 4.851806-.806974V-3.466999C4.85" "1806-3.576588 5.310087-4.044832 5.69863-4.044832C6.07721-4.044832 6.2266" "5-3.805729 6.22665-3.217933V-.806974C6.22665-.388543 6.117061-.268991 5." "738481-.239103V0H8.109589V-.239103C7.721046-.259029 7.611457-.37858 7.61" "1457-.806974V-3.307597C7.611457-4.164384 7.083437-4.712329 6.266501-4.71" "2329C5.69863-4.712329 5.32005-4.483188 4.801993-3.845579C4.503113-4.4732" "25 4.154421-4.712329 3.526775-4.712329S2.440847-4.443337 2.062267-3.8455" "79V-4.592777H.179328V-4.353674C.617684-4.293898 .707347-4.174346 .707347" "-3.765878V-.836862C.707347-.428394 .617684-.318804 .179328-.239103V0H2.5" "50436V-.239103C2.201743-.288917 2.092154-.428394 2.092154-.806974V-3.466" "999C2.092154-3.58655 2.530511-4.044832 2.929016-4.044832Z" ), ] class ManimBanner(VGroup): r"""Convenience class representing Manim's banner. Can be animated using custom methods. Parameters ---------- dark_theme If ``True`` (the default), the dark theme version of the logo (with light text font) will be rendered. Otherwise, if ``False``, the light theme version (with dark text font) is used. Examples -------- .. manim:: DarkThemeBanner class DarkThemeBanner(Scene): def construct(self): banner = ManimBanner() self.play(banner.create()) self.play(banner.expand()) self.wait() self.play(Unwrite(banner)) .. manim:: LightThemeBanner class LightThemeBanner(Scene): def construct(self): self.camera.background_color = "#ece6e2" banner = ManimBanner(dark_theme=False) self.play(banner.create()) self.play(banner.expand()) self.wait() self.play(Unwrite(banner)) """ def __init__(self, dark_theme: bool = True): super().__init__() logo_green = "#81b29a" logo_blue = "#454866" logo_red = "#e07a5f" m_height_over_anim_height = 0.75748 self.font_color = "#ece6e2" if dark_theme else "#343434" self.scale_factor = 1.0 self.M = VMobjectFromSVGPath(MANIM_SVG_PATHS[0]).flip(cst.RIGHT).center() self.M.set(stroke_width=0).scale( 7 * cst.DEFAULT_FONT_SIZE * cst.SCALE_FACTOR_PER_FONT_POINT ) self.M.set_fill(color=self.font_color, opacity=1).shift( 2.25 * cst.LEFT + 1.5 * cst.UP ) self.circle = Circle(color=logo_green, fill_opacity=1).shift(cst.LEFT) self.square = Square(color=logo_blue, fill_opacity=1).shift(cst.UP) self.triangle = Triangle(color=logo_red, fill_opacity=1).shift(cst.RIGHT) self.shapes = VGroup(self.triangle, self.square, self.circle) self.add(self.shapes, self.M) self.move_to(cst.ORIGIN) anim = VGroup() for ind, path in enumerate(MANIM_SVG_PATHS[1:]): tex = VMobjectFromSVGPath(path).flip(cst.RIGHT).center() tex.set(stroke_width=0).scale( cst.DEFAULT_FONT_SIZE * cst.SCALE_FACTOR_PER_FONT_POINT ) if ind > 0: tex.next_to(anim, buff=0.01) tex.align_to(self.M, cst.DOWN) anim.add(tex) anim.set_fill(color=self.font_color, opacity=1) anim.height = m_height_over_anim_height * self.M.height # Note: "anim" is only shown in the expanded state # and thus not yet added to the submobjects of self. self.anim = anim def scale(self, scale_factor: float, **kwargs: Any) -> ManimBanner: """Scale the banner by the specified scale factor. Parameters ---------- scale_factor The factor used for scaling the banner. Returns ------- :class:`~.ManimBanner` The scaled banner. """ self.scale_factor *= scale_factor # Note: self.anim is only added to self after expand() if self.anim not in self.submobjects: 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. Parameters ---------- run_time The run time of the animation. Returns ------- :class:`~.AnimationGroup` An animation to be used in a :meth:`.Scene.play` call. """ return AnimationGroup( SpiralIn(self.shapes, run_time=run_time), FadeIn(self.M, run_time=run_time / 2), lag_ratio=0.1, ) def expand(self, run_time: float = 1.5, direction: str = "center") -> Succession: """An animation that expands Manim's logo into its banner. The returned animation transforms the banner from its initial state (representing Manim's logo with just the icons) to its expanded state (showing the full name together with the icons). See the class documentation for how to use this. .. note:: Before calling this method, the text "anim" is not a submobject of the banner object. After the expansion, it is added as a submobject so subsequent animations to the banner object apply to the text "anim" as well. Parameters ---------- run_time The run time of the animation. direction The direction in which the logo is expanded. Returns -------
|
not a submobject of the banner object. After the expansion, it is added as a submobject so subsequent animations to the banner object apply to the text "anim" as well. Parameters ---------- run_time The run time of the animation. direction The direction in which the logo is expanded. Returns ------- :class:`~.Succession` An animation to be used in a :meth:`.Scene.play` call. Examples -------- .. manim:: ExpandDirections class ExpandDirections(Scene): def construct(self): banners = [ManimBanner().scale(0.5).shift(UP*x) for x in [-2, 0, 2]] self.play( banners[0].expand(direction="right"), banners[1].expand(direction="center"), banners[2].expand(direction="left"), ) """ if direction not in ["left", "right", "center"]: raise ValueError("direction must be 'left', 'right' or 'center'.") m_shape_offset = 6.25 * self.scale_factor shape_sliding_overshoot = self.scale_factor * 0.8 m_anim_buff = 0.06 self.anim.next_to(self.M, buff=m_anim_buff).align_to(self.M, cst.DOWN) self.anim.set_opacity(0) self.shapes.save_state() m_clone = self.anim[-1].copy() self.add(m_clone) m_clone.move_to(self.shapes) self.M.save_state() left_group = VGroup(self.M, self.anim, m_clone) def shift(vector: Vector3D) -> None: self.shapes.restore() left_group.align_to(self.M.saved_state, cst.LEFT) if direction == "right": self.shapes.shift(vector) elif direction == "center": self.shapes.shift(vector / 2) left_group.shift(-vector / 2) elif direction == "left": left_group.shift(-vector) def slide_and_uncover(mob: Mobject, alpha: float) -> None: shift(alpha * (m_shape_offset + shape_sliding_overshoot) * cst.RIGHT) # Add letters when they are covered for letter in mob.anim: if mob.square.get_center()[0] > letter.get_center()[0]: letter.set_opacity(1) self.add_to_back(letter) # Finish animation if alpha == 1: self.remove(*[self.anim]) self.add_to_back(self.anim) mob.shapes.set_z_index(0) mob.shapes.save_state() mob.M.save_state() def slide_back(mob: Mobject, alpha: float) -> None: if alpha == 0: m_clone.set_opacity(1) m_clone.move_to(mob.anim[-1]) mob.anim.set_opacity(1) shift(alpha * shape_sliding_overshoot * cst.LEFT) if alpha == 1: mob.remove(m_clone) mob.add_to_back(mob.shapes) return Succession( UpdateFromAlphaFunc( self, slide_and_uncover, run_time=run_time * 2 / 3, rate_func=ease_in_out_cubic, ), UpdateFromAlphaFunc( self, slide_back, run_time=run_time * 1 / 3, rate_func=smooth, ), ) ================================================ FILE: manim/mobject/matrix.py ================================================ r"""Mobjects representing matrices. Examples -------- .. manim:: MatrixExamples :save_last_frame: class MatrixExamples(Scene): def construct(self): m0 = Matrix([["\\pi", 0], [-1, 1]]) m1 = IntegerMatrix([[1.5, 0.], [12, -1.3]], left_bracket="(", right_bracket=")") m2 = DecimalMatrix( [[3.456, 2.122], [33.2244, 12.33]], element_to_mobject_config={"num_decimal_places": 2}, left_bracket=r"\{", right_bracket=r"\}") m3 = MobjectMatrix( [[Circle().scale(0.3), Square().scale(0.3)], [MathTex("\\pi").scale(2), Star().scale(0.3)]], left_bracket="\\langle", right_bracket="\\rangle") g = Group(m0, m1, m2, m3).arrange_in_grid(buff=2) self.add(g) """ from __future__ import annotations __all__ = [ "Matrix", "DecimalMatrix", "IntegerMatrix", "MobjectMatrix", "matrix_to_tex_string", "matrix_to_mobject", "get_det_text", ] import itertools as it from collections.abc import Callable, Iterable, Sequence from typing import Any import numpy as np from typing_extensions import Self from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.text.numbers import DecimalNumber, Integer from manim.mobject.text.tex_mobject import MathTex, Tex from ..constants import * from ..mobject.types.vectorized_mobject import VGroup, VMobject # TO DO : The following two functions are not used in this file. # Not sure if we should keep it or not. def matrix_to_tex_string(matrix: np.ndarray) -> str: matrix = np.array(matrix).astype("str") if matrix.ndim == 1: matrix = matrix.reshape((matrix.size, 1)) n_rows, n_cols = matrix.shape prefix = "\\left[ \\begin{array}{%s}" % ("c" * n_cols) suffix = "\\end{array} \\right]" rows = [" & ".join(row) for row in matrix] return prefix + " \\\\ ".join(rows) + suffix def matrix_to_mobject(matrix: np.ndarray) -> MathTex: return MathTex(matrix_to_tex_string(matrix)) class Matrix(VMobject, metaclass=ConvertToOpenGL): r"""A mobject that displays a matrix on the screen. Parameters ---------- matrix A numpy 2d array or list of lists. v_buff Vertical distance between elements, by default 0.8. h_buff Horizontal distance between elements, by default 1.3. bracket_h_buff Distance of the brackets from the matrix, by default ``MED_SMALL_BUFF``.
|
class Matrix(VMobject, metaclass=ConvertToOpenGL): r"""A mobject that displays a matrix on the screen. Parameters ---------- matrix A numpy 2d array or list of lists. v_buff Vertical distance between elements, by default 0.8. h_buff Horizontal distance between elements, by default 1.3. bracket_h_buff Distance of the brackets from the matrix, by default ``MED_SMALL_BUFF``. bracket_v_buff Height of the brackets, by default ``MED_SMALL_BUFF``. add_background_rectangles_to_entries ``True`` if should add backgraound rectangles to entries, by default ``False``. include_background_rectangle ``True`` if should include background rectangle, by default ``False``. element_to_mobject The mobject class used to construct the elements, by default :class:`~.MathTex`. element_to_mobject_config Additional arguments to be passed to the constructor in ``element_to_mobject``, by default ``{}``. element_alignment_corner The corner to which elements are aligned, by default ``DR``. left_bracket The left bracket type, by default ``"["``. right_bracket The right bracket type, by default ``"]"``. stretch_brackets ``True`` if should stretch the brackets to fit the height of matrix contents, by default ``True``. bracket_config Additional arguments to be passed to :class:`~.MathTex` when constructing the brackets. Examples -------- The first example shows a variety of uses of this module while the second example exlpains the use of the options `add_background_rectangles_to_entries` and `include_background_rectangle`. .. manim:: MatrixExamples :save_last_frame: class MatrixExamples(Scene): def construct(self): m0 = Matrix([[2, r"\pi"], [-1, 1]]) m1 = Matrix([[2, 0, 4], [-1, 1, 5]], v_buff=1.3, h_buff=0.8, bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, left_bracket=r"\{", right_bracket=r"\}") m1.add(SurroundingRectangle(m1.get_columns()[1])) m2 = Matrix([[2, 1], [-1, 3]], element_alignment_corner=UL, left_bracket="(", right_bracket=")") m3 = Matrix([[2, 1], [-1, 3]], left_bracket=r"\langle", right_bracket=r"\rangle") m4 = Matrix([[2, 1], [-1, 3]], ).set_column_colors(RED, GREEN) m5 = Matrix([[2, 1], [-1, 3]], ).set_row_colors(RED, GREEN) g = Group( m0,m1,m2,m3,m4,m5 ).arrange_in_grid(buff=2) self.add(g) .. manim:: BackgroundRectanglesExample :save_last_frame: class BackgroundRectanglesExample(Scene): def construct(self): background= Rectangle().scale(3.2) background.set_fill(opacity=.5) background.set_color([TEAL, RED, YELLOW]) self.add(background) m0 = Matrix([[12, -30], [-1, 15]], add_background_rectangles_to_entries=True) m1 = Matrix([[2, 0], [-1, 1]], include_background_rectangle=True) m2 = Matrix([[12, -30], [-1, 15]]) g = Group(m0, m1, m2).arrange(buff=2) self.add(g) """ def __init__( self, matrix: Iterable, v_buff: float = 0.8, h_buff: float = 1.3, bracket_h_buff: float = MED_SMALL_BUFF, bracket_v_buff: float = MED_SMALL_BUFF, add_background_rectangles_to_entries: bool = False, include_background_rectangle: bool = False, element_to_mobject: type[Mobject] | Callable[..., Mobject] = MathTex, element_to_mobject_config: dict = {}, element_alignment_corner: Sequence[float] = DR, left_bracket: str = "[", right_bracket: str = "]", stretch_brackets: bool = True, bracket_config: dict = {}, **kwargs: Any, ): self.v_buff = v_buff self.h_buff = h_buff self.bracket_h_buff = bracket_h_buff self.bracket_v_buff = bracket_v_buff self.add_background_rectangles_to_entries = add_background_rectangles_to_entries self.include_background_rectangle = include_background_rectangle self.element_to_mobject = element_to_mobject self.element_to_mobject_config = element_to_mobject_config self.element_alignment_corner = element_alignment_corner self.left_bracket = left_bracket self.right_bracket = right_bracket self.stretch_brackets = stretch_brackets super().__init__(**kwargs) mob_matrix = self._matrix_to_mob_matrix(matrix) self._organize_mob_matrix(mob_matrix) self.elements = VGroup(*it.chain(*mob_matrix)) self.add(self.elements) self._add_brackets(self.left_bracket, self.right_bracket, **bracket_config) self.center() self.mob_matrix = mob_matrix if self.add_background_rectangles_to_entries: for mob in self.elements: mob.add_background_rectangle() if self.include_background_rectangle: self.add_background_rectangle() def _matrix_to_mob_matrix(self, matrix: np.ndarray) -> list[list[Mobject]]: return [ [ self.element_to_mobject(item, **self.element_to_mobject_config) for item in row ] for row in matrix ] def _organize_mob_matrix(self, matrix: list[list[Mobject]]) -> Self: for i, row in enumerate(matrix): for j, _ in enumerate(row): mob = matrix[i][j] mob.move_to( i * self.v_buff * DOWN + j * self.h_buff * RIGHT, self.element_alignment_corner, ) return self def _add_brackets(self, left: str = "[", right: str = "]", **kwargs: Any) -> Self: """Adds the brackets to the Matrix mobject.
|
for i, row in enumerate(matrix): for j, _ in enumerate(row): mob = matrix[i][j] mob.move_to( i * self.v_buff * DOWN + j * self.h_buff * RIGHT, self.element_alignment_corner, ) return self def _add_brackets(self, left: str = "[", right: str = "]", **kwargs: Any) -> Self: """Adds the brackets to the Matrix mobject. See Latex document for various bracket types. Parameters ---------- left the left bracket, by default "[" right the right bracket, by default "]" Returns ------- :class:`Matrix` The current matrix object (self). """ # Height per row of LaTeX array with default settings BRACKET_HEIGHT = 0.5977 n = int((self.height) / BRACKET_HEIGHT) + 1 empty_tex_array = "".join( [ r"\begin{array}{c}", *n * [r"\quad \\"], r"\end{array}", ] ) tex_left = "".join( [ r"\left" + left, empty_tex_array, r"\right.", ] ) tex_right = "".join( [ r"\left.", empty_tex_array, r"\right" + right, ] ) l_bracket = MathTex(tex_left, **kwargs) r_bracket = MathTex(tex_right, **kwargs) bracket_pair = VGroup(l_bracket, r_bracket) if self.stretch_brackets: bracket_pair.stretch_to_fit_height(self.height + 2 * self.bracket_v_buff) l_bracket.next_to(self, LEFT, self.bracket_h_buff) r_bracket.next_to(self, RIGHT, self.bracket_h_buff) self.brackets = bracket_pair self.add(l_bracket, r_bracket) return self def get_columns(self) -> VGroup: r"""Return columns of the matrix as VGroups. Returns -------- :class:`~.VGroup` The VGroup contains a nested VGroup for each column of the matrix. Examples -------- .. manim:: GetColumnsExample :save_last_frame: class GetColumnsExample(Scene): def construct(self): m0 = Matrix([[r"\pi", 3], [1, 5]]) m0.add(SurroundingRectangle(m0.get_columns()[1])) self.add(m0) """ return VGroup( *( VGroup(*(row[i] for row in self.mob_matrix)) for i in range(len(self.mob_matrix[0])) ) ) def set_column_colors(self, *colors: str) -> Self: r"""Set individual colors for each columns of the matrix. Parameters ---------- colors The list of colors; each color specified corresponds to a column. Returns ------- :class:`Matrix` The current matrix object (self). Examples -------- .. manim:: SetColumnColorsExample :save_last_frame: class SetColumnColorsExample(Scene): def construct(self): m0 = Matrix([["\\pi", 1], [-1, 3]], ).set_column_colors([RED,BLUE], GREEN) self.add(m0) """ columns = self.get_columns() for color, column in zip(colors, columns): column.set_color(color) return self def get_rows(self) -> VGroup: r"""Return rows of the matrix as VGroups. Returns -------- :class:`~.VGroup` The VGroup contains a nested VGroup for each row of the matrix. Examples -------- .. manim:: GetRowsExample :save_last_frame: class GetRowsExample(Scene): def construct(self): m0 = Matrix([["\\pi", 3], [1, 5]]) m0.add(SurroundingRectangle(m0.get_rows()[1])) self.add(m0) """ return VGroup(*(VGroup(*row) for row in self.mob_matrix)) def set_row_colors(self, *colors: str) -> Self: r"""Set individual colors for each row of the matrix. Parameters ---------- colors The list of colors; each color specified corresponds to a row. Returns ------- :class:`Matrix` The current matrix object (self). Examples -------- .. manim:: SetRowColorsExample :save_last_frame: class SetRowColorsExample(Scene): def construct(self): m0 = Matrix([["\\pi", 1], [-1, 3]], ).set_row_colors([RED,BLUE], GREEN) self.add(m0) """ rows = self.get_rows() for color, row in zip(colors, rows): row.set_color(color) return self def add_background_to_entries(self) -> Self: """Add a black background rectangle to the matrix, see above for an example. Returns ------- :class:`Matrix` The current matrix object (self). """ for mob in self.get_entries(): mob.add_background_rectangle() return self def get_mob_matrix(self) -> list[list[Mobject]]: """Return the underlying mob matrix mobjects. Returns -------- List[:class:`~.VGroup`] Each VGroup contains a row of the matrix. """ return self.mob_matrix def get_entries(self) -> VGroup: """Return the individual entries of the matrix. Returns -------- :class:`~.VGroup` VGroup containing entries of the matrix. Examples -------- .. manim:: GetEntriesExample :save_last_frame: class
|
get_mob_matrix(self) -> list[list[Mobject]]: """Return the underlying mob matrix mobjects. Returns -------- List[:class:`~.VGroup`] Each VGroup contains a row of the matrix. """ return self.mob_matrix def get_entries(self) -> VGroup: """Return the individual entries of the matrix. Returns -------- :class:`~.VGroup` VGroup containing entries of the matrix. Examples -------- .. manim:: GetEntriesExample :save_last_frame: class GetEntriesExample(Scene): def construct(self): m0 = Matrix([[2, 3], [1, 5]]) ent = m0.get_entries() colors = [BLUE, GREEN, YELLOW, RED] for k in range(len(colors)): ent[k].set_color(colors[k]) self.add(m0) """ return self.elements def get_brackets(self) -> VGroup: r"""Return the bracket mobjects. Returns -------- :class:`~.VGroup` A VGroup containing the left and right bracket. Examples -------- .. manim:: GetBracketsExample :save_last_frame: class GetBracketsExample(Scene): def construct(self): m0 = Matrix([["\\pi", 3], [1, 5]]) bra = m0.get_brackets() colors = [BLUE, GREEN] for k in range(len(colors)): bra[k].set_color(colors[k]) self.add(m0) """ return self.brackets class DecimalMatrix(Matrix): r"""A mobject that displays a matrix with decimal entries on the screen. Examples -------- .. manim:: DecimalMatrixExample :save_last_frame: class DecimalMatrixExample(Scene): def construct(self): m0 = DecimalMatrix( [[3.456, 2.122], [33.2244, 12]], element_to_mobject_config={"num_decimal_places": 2}, left_bracket="\\{", right_bracket="\\}") self.add(m0) """ def __init__( self, matrix: Iterable, element_to_mobject: type[Mobject] = DecimalNumber, element_to_mobject_config: dict[str, Any] = {"num_decimal_places": 1}, **kwargs: Any, ): """ Will round/truncate the decimal places as per the provided config. Parameters ---------- matrix A numpy 2d array or list of lists element_to_mobject Mobject to use, by default DecimalNumber element_to_mobject_config Config for the desired mobject, by default {"num_decimal_places": 1} """ super().__init__( matrix, element_to_mobject=element_to_mobject, element_to_mobject_config=element_to_mobject_config, **kwargs, ) class IntegerMatrix(Matrix): """A mobject that displays a matrix with integer entries on the screen. Examples -------- .. manim:: IntegerMatrixExample :save_last_frame: class IntegerMatrixExample(Scene): def construct(self): m0 = IntegerMatrix( [[3.7, 2], [42.2, 12]], left_bracket="(", right_bracket=")") self.add(m0) """ def __init__( self, matrix: Iterable, element_to_mobject: type[Mobject] = Integer, **kwargs: Any, ): """ Will round if there are decimal entries in the matrix. Parameters ---------- matrix A numpy 2d array or list of lists element_to_mobject Mobject to use, by default Integer """ super().__init__(matrix, element_to_mobject=element_to_mobject, **kwargs) class MobjectMatrix(Matrix): r"""A mobject that displays a matrix of mobject entries on the screen. Examples -------- .. manim:: MobjectMatrixExample :save_last_frame: class MobjectMatrixExample(Scene): def construct(self): a = Circle().scale(0.3) b = Square().scale(0.3) c = MathTex("\\pi").scale(2) d = Star().scale(0.3) m0 = MobjectMatrix([[a, b], [c, d]]) self.add(m0) """ def __init__( self, matrix: Iterable, element_to_mobject: type[Mobject] | Callable[..., Mobject] = lambda m: m, **kwargs: Any, ): super().__init__(matrix, element_to_mobject=element_to_mobject, **kwargs) def get_det_text( matrix: Matrix, determinant: int | str | None = None, background_rect: bool = False, initial_scale_factor: float = 2, ) -> VGroup: r"""Helper function to create determinant. Parameters ---------- matrix The matrix whose determinant is to be created determinant The value of the determinant of the matrix background_rect The background rectangle initial_scale_factor The scale of the text `det` w.r.t the matrix Returns -------- :class:`~.VGroup` A VGroup containing the determinant Examples -------- .. manim:: DeterminantOfAMatrix :save_last_frame: class DeterminantOfAMatrix(Scene): def construct(self): matrix = Matrix([ [2, 0], [-1, 1] ]) # scaling down the `det` string det = get_det_text(matrix, determinant=3, initial_scale_factor=1) # must add the matrix self.add(matrix) self.add(det) """ parens = MathTex("(", ")") parens.scale(initial_scale_factor) parens.stretch_to_fit_height(matrix.height) l_paren, r_paren = parens.split() l_paren.next_to(matrix, LEFT, buff=0.1) r_paren.next_to(matrix, RIGHT, buff=0.1) det = Tex("det") det.scale(initial_scale_factor)
|
DeterminantOfAMatrix(Scene): def construct(self): matrix = Matrix([ [2, 0], [-1, 1] ]) # scaling down the `det` string det = get_det_text(matrix, determinant=3, initial_scale_factor=1) # must add the matrix self.add(matrix) self.add(det) """ parens = MathTex("(", ")") parens.scale(initial_scale_factor) parens.stretch_to_fit_height(matrix.height) l_paren, r_paren = parens.split() l_paren.next_to(matrix, LEFT, buff=0.1) r_paren.next_to(matrix, RIGHT, buff=0.1) det = Tex("det") det.scale(initial_scale_factor) det.next_to(l_paren, LEFT, buff=0.1) if background_rect: det.add_background_rectangle() det_text = VGroup(det, l_paren, r_paren) if determinant is not None: eq = MathTex("=") eq.next_to(r_paren, RIGHT, buff=0.1) result = MathTex(str(determinant)) result.next_to(eq, RIGHT, buff=0.2) det_text.add(eq, result) return det_text ================================================ FILE: manim/mobject/table.py ================================================ r"""Mobjects representing tables. Examples -------- .. manim:: TableExamples :save_last_frame: class TableExamples(Scene): def construct(self): t0 = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")], top_left_entry=Text("TOP")) t0.add_highlighted_cell((2,2), color=GREEN) x_vals = np.linspace(-2,2,5) y_vals = np.exp(x_vals) t1 = DecimalTable( [x_vals, y_vals], row_labels=[MathTex("x"), MathTex("f(x)")], include_outer_lines=True) t1.add(t1.get_cell((2,2), color=RED)) t2 = MathTable( [["+", 0, 5, 10], [0, 0, 5, 10], [2, 2, 7, 12], [4, 4, 9, 14]], include_outer_lines=True) t2.get_horizontal_lines()[:3].set_color(BLUE) t2.get_vertical_lines()[:3].set_color(BLUE) t2.get_horizontal_lines()[:3].set_z_index(1) cross = VGroup( Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT)) a = Circle().set_color(RED).scale(0.5) b = cross.set_color(BLUE).scale(0.5) t3 = MobjectTable( [[a.copy(),b.copy(),a.copy()], [b.copy(),a.copy(),a.copy()], [a.copy(),b.copy(),b.copy()]]) t3.add(Line( t3.get_corner(DL), t3.get_corner(UR) ).set_color(RED)) vals = np.arange(1,21).reshape(5,4) t4 = IntegerTable( vals, include_outer_lines=True ) g1 = Group(t0, t1).scale(0.5).arrange(buff=1).to_edge(UP, buff=1) g2 = Group(t2, t3, t4).scale(0.5).arrange(buff=1).to_edge(DOWN, buff=1) self.add(g1, g2) """ from __future__ import annotations __all__ = [ "Table", "MathTable", "MobjectTable", "IntegerTable", "DecimalTable", ] import itertools as it from collections.abc import Callable, Iterable, Sequence from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import Polygon from manim.mobject.geometry.shape_matchers import BackgroundRectangle from manim.mobject.text.numbers import DecimalNumber, Integer from manim.mobject.text.tex_mobject import MathTex from manim.mobject.text.text_mobject import Paragraph from ..animation.animation import Animation from ..animation.composition import AnimationGroup from ..animation.creation import Create, Write from ..animation.fading import FadeIn from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..utils.color import BLACK, YELLOW, ManimColor, ParsableManimColor from .utils import get_vectorized_mobject_class class Table(VGroup): r"""A mobject that displays a table on the screen. Parameters ---------- table A 2D array or list of lists. Content of the table has to be a valid input for the callable set in ``element_to_mobject``. row_labels List of :class:`~.VMobject` representing the labels of each row. col_labels List of :class:`~.VMobject` representing the labels of each column. top_left_entry The top-left entry of the table, can only be specified if row and column labels are given. v_buff Vertical buffer passed to :meth:`~.Mobject.arrange_in_grid`, by default 0.8. h_buff Horizontal buffer passed to :meth:`~.Mobject.arrange_in_grid`, by default 1.3. include_outer_lines ``True`` if the table should include outer lines, by default False. add_background_rectangles_to_entries ``True`` if background rectangles should be added to entries, by default ``False``. entries_background_color Background color of entries if ``add_background_rectangles_to_entries`` is ``True``. include_background_rectangle ``True`` if the table should have a background rectangle, by default ``False``. background_rectangle_color Background color of table if ``include_background_rectangle`` is ``True``. element_to_mobject The :class:`~.Mobject` class applied to the table entries. by default :class:`~.Paragraph`. For common choices, see :mod:`~.text_mobject`/:mod:`~.tex_mobject`. element_to_mobject_config Custom configuration passed to :attr:`element_to_mobject`, by default {}. arrange_in_grid_config Dict passed to :meth:`~.Mobject.arrange_in_grid`, customizes the arrangement of the table. line_config Dict passed to :class:`~.Line`, customizes the lines of the table. kwargs Additional arguments to be passed to :class:`~.VGroup`. Examples -------- .. manim:: TableExamples :save_last_frame: class TableExamples(Scene): def
|
see :mod:`~.text_mobject`/:mod:`~.tex_mobject`. element_to_mobject_config Custom configuration passed to :attr:`element_to_mobject`, by default {}. arrange_in_grid_config Dict passed to :meth:`~.Mobject.arrange_in_grid`, customizes the arrangement of the table. line_config Dict passed to :class:`~.Line`, customizes the lines of the table. kwargs Additional arguments to be passed to :class:`~.VGroup`. Examples -------- .. manim:: TableExamples :save_last_frame: class TableExamples(Scene): def construct(self): t0 = Table( [["This", "is a"], ["simple", "Table in \\n Manim."]]) t1 = Table( [["This", "is a"], ["simple", "Table."]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) t1.add_highlighted_cell((2,2), color=YELLOW) t2 = Table( [["This", "is a"], ["simple", "Table."]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")], top_left_entry=Star().scale(0.3), include_outer_lines=True, arrange_in_grid_config={"cell_alignment": RIGHT}) t2.add(t2.get_cell((2,2), color=RED)) t3 = Table( [["This", "is a"], ["simple", "Table."]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")], top_left_entry=Star().scale(0.3), include_outer_lines=True, line_config={"stroke_width": 1, "color": YELLOW}) t3.remove(*t3.get_vertical_lines()) g = Group( t0,t1,t2,t3 ).scale(0.7).arrange_in_grid(buff=1) self.add(g) .. manim:: BackgroundRectanglesExample :save_last_frame: class BackgroundRectanglesExample(Scene): def construct(self): background = Rectangle(height=6.5, width=13) background.set_fill(opacity=.5) background.set_color([TEAL, RED, YELLOW]) self.add(background) t0 = Table( [["This", "is a"], ["simple", "Table."]], add_background_rectangles_to_entries=True) t1 = Table( [["This", "is a"], ["simple", "Table."]], include_background_rectangle=True) g = Group(t0, t1).scale(0.7).arrange(buff=0.5) self.add(g) """ def __init__( self, table: Iterable[Iterable[float | str | VMobject]], row_labels: Iterable[VMobject] | None = None, col_labels: Iterable[VMobject] | None = None, top_left_entry: VMobject | None = None, v_buff: float = 0.8, h_buff: float = 1.3, include_outer_lines: bool = False, add_background_rectangles_to_entries: bool = False, entries_background_color: ParsableManimColor = BLACK, include_background_rectangle: bool = False, background_rectangle_color: ParsableManimColor = BLACK, element_to_mobject: Callable[ [float | str | VMobject], VMobject, ] = Paragraph, element_to_mobject_config: dict = {}, arrange_in_grid_config: dict = {}, line_config: dict = {}, **kwargs, ): self.row_labels = row_labels self.col_labels = col_labels self.top_left_entry = top_left_entry self.row_dim = len(table) self.col_dim = len(table[0]) self.v_buff = v_buff self.h_buff = h_buff self.include_outer_lines = include_outer_lines self.add_background_rectangles_to_entries = add_background_rectangles_to_entries self.entries_background_color = ManimColor(entries_background_color) self.include_background_rectangle = include_background_rectangle self.background_rectangle_color = ManimColor(background_rectangle_color) self.element_to_mobject = element_to_mobject self.element_to_mobject_config = element_to_mobject_config self.arrange_in_grid_config = arrange_in_grid_config self.line_config = line_config for row in table: if len(row) == len(table[0]): pass else: raise ValueError("Not all rows in table have the same length.") super().__init__(**kwargs) mob_table = self._table_to_mob_table(table) self.elements_without_labels = VGroup(*it.chain(*mob_table)) mob_table = self._add_labels(mob_table) self._organize_mob_table(mob_table) self.elements = VGroup(*it.chain(*mob_table)) if len(self.elements[0].get_all_points()) == 0: self.elements.remove(self.elements[0]) self.add(self.elements) self.center() self.mob_table = mob_table self._add_horizontal_lines() self._add_vertical_lines() if self.add_background_rectangles_to_entries: self.add_background_to_entries(color=self.entries_background_color) if self.include_background_rectangle: self.add_background_rectangle(color=self.background_rectangle_color) def _table_to_mob_table( self, table: Iterable[Iterable[float | str | VMobject]], ) -> list: """Initializes the entries of ``table`` as :class:`~.VMobject`. Parameters ---------- table A 2D array or list of lists. Content of the table has to be a valid input for the callable set in ``element_to_mobject``. Returns -------- List List of :class:`~.VMobject` from the entries of ``table``. """ return [ [ self.element_to_mobject(item, **self.element_to_mobject_config) for item in row ] for row in table ] def _organize_mob_table(self, table: Iterable[Iterable[VMobject]]) -> VGroup: """Arranges the :class:`~.VMobject` of ``table`` in a grid. Parameters ---------- table A 2D iterable object with :class:`~.VMobject` entries. Returns -------- :class:`~.VGroup` The :class:`~.VMobject` of the ``table`` in a :class:`~.VGroup` already arranged in a table-like grid. """ help_table = VGroup() for i, row in enumerate(table): for j, _ in enumerate(row): help_table.add(table[i][j]) help_table.arrange_in_grid( rows=len(table), cols=len(table[0]), buff=(self.h_buff, self.v_buff), **self.arrange_in_grid_config, ) return help_table def _add_labels(self, mob_table: VGroup) -> VGroup: """Adds labels to an in a grid arranged :class:`~.VGroup`. Parameters ---------- mob_table An in a grid organized
|
a table-like grid. """ help_table = VGroup() for i, row in enumerate(table): for j, _ in enumerate(row): help_table.add(table[i][j]) help_table.arrange_in_grid( rows=len(table), cols=len(table[0]), buff=(self.h_buff, self.v_buff), **self.arrange_in_grid_config, ) return help_table def _add_labels(self, mob_table: VGroup) -> VGroup: """Adds labels to an in a grid arranged :class:`~.VGroup`. Parameters ---------- mob_table An in a grid organized class:`~.VGroup`. Returns -------- :class:`~.VGroup` Returns the ``mob_table`` with added labels. """ if self.row_labels is not None: for k in range(len(self.row_labels)): mob_table[k] = [self.row_labels[k]] + mob_table[k] if self.col_labels is not None: if self.row_labels is not None: if self.top_left_entry is not None: col_labels = [self.top_left_entry] + self.col_labels mob_table.insert(0, col_labels) else: # Placeholder to use arrange_in_grid if top_left_entry is not set. # Import OpenGLVMobject to work with --renderer=opengl dummy_mobject = get_vectorized_mobject_class()() col_labels = [dummy_mobject] + self.col_labels mob_table.insert(0, col_labels) else: mob_table.insert(0, self.col_labels) return mob_table def _add_horizontal_lines(self) -> Table: """Adds the horizontal lines to the table.""" anchor_left = self.get_left()[0] - 0.5 * self.h_buff anchor_right = self.get_right()[0] + 0.5 * self.h_buff line_group = VGroup() if self.include_outer_lines: anchor = self.get_rows()[0].get_top()[1] + 0.5 * self.v_buff line = Line( [anchor_left, anchor, 0], [anchor_right, anchor, 0], **self.line_config ) line_group.add(line) self.add(line) anchor = self.get_rows()[-1].get_bottom()[1] - 0.5 * self.v_buff line = Line( [anchor_left, anchor, 0], [anchor_right, anchor, 0], **self.line_config ) line_group.add(line) self.add(line) for k in range(len(self.mob_table) - 1): anchor = self.get_rows()[k + 1].get_top()[1] + 0.5 * ( self.get_rows()[k].get_bottom()[1] - self.get_rows()[k + 1].get_top()[1] ) line = Line( [anchor_left, anchor, 0], [anchor_right, anchor, 0], **self.line_config ) line_group.add(line) self.add(line) self.horizontal_lines = line_group return self def _add_vertical_lines(self) -> Table: """Adds the vertical lines to the table""" anchor_top = self.get_rows().get_top()[1] + 0.5 * self.v_buff anchor_bottom = self.get_rows().get_bottom()[1] - 0.5 * self.v_buff line_group = VGroup() if self.include_outer_lines: anchor = self.get_columns()[0].get_left()[0] - 0.5 * self.h_buff line = Line( [anchor, anchor_top, 0], [anchor, anchor_bottom, 0], **self.line_config ) line_group.add(line) self.add(line) anchor = self.get_columns()[-1].get_right()[0] + 0.5 * self.h_buff line = Line( [anchor, anchor_top, 0], [anchor, anchor_bottom, 0], **self.line_config ) line_group.add(line) self.add(line) for k in range(len(self.mob_table[0]) - 1): anchor = self.get_columns()[k + 1].get_left()[0] + 0.5 * ( self.get_columns()[k].get_right()[0] - self.get_columns()[k + 1].get_left()[0] ) line = Line( [anchor, anchor_bottom, 0], [anchor, anchor_top, 0], **self.line_config ) line_group.add(line) self.add(line) self.vertical_lines = line_group return self def get_horizontal_lines(self) -> VGroup: """Return the horizontal lines of the table. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing all the horizontal lines of the table. Examples -------- .. manim:: GetHorizontalLinesExample :save_last_frame: class GetHorizontalLinesExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.get_horizontal_lines().set_color(RED) self.add(table) """ return self.horizontal_lines def get_vertical_lines(self) -> VGroup: """Return the vertical lines of the table. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing all the vertical lines of the table. Examples -------- .. manim:: GetVerticalLinesExample :save_last_frame: class GetVerticalLinesExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.get_vertical_lines()[0].set_color(RED) self.add(table) """ return self.vertical_lines def get_columns(self) -> VGroup: """Return columns of the table as a :class:`~.VGroup` of :class:`~.VGroup`. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing each column in a :class:`~.VGroup`. Examples -------- .. manim:: GetColumnsExample :save_last_frame: class GetColumnsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.add(SurroundingRectangle(table.get_columns()[1])) self.add(table) """ return VGroup( *( VGroup(*(row[i] for row in self.mob_table)) for
|
of the table as a :class:`~.VGroup` of :class:`~.VGroup`. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing each column in a :class:`~.VGroup`. Examples -------- .. manim:: GetColumnsExample :save_last_frame: class GetColumnsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.add(SurroundingRectangle(table.get_columns()[1])) self.add(table) """ return VGroup( *( VGroup(*(row[i] for row in self.mob_table)) for i in range(len(self.mob_table[0])) ) ) def get_rows(self) -> VGroup: """Return the rows of the table as a :class:`~.VGroup` of :class:`~.VGroup`. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing each row in a :class:`~.VGroup`. Examples -------- .. manim:: GetRowsExample :save_last_frame: class GetRowsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.add(SurroundingRectangle(table.get_rows()[1])) self.add(table) """ return VGroup(*(VGroup(*row) for row in self.mob_table)) def set_column_colors(self, *colors: Iterable[ParsableManimColor]) -> Table: """Set individual colors for each column of the table. Parameters ---------- colors An iterable of colors; each color corresponds to a column. Examples -------- .. manim:: SetColumnColorsExample :save_last_frame: class SetColumnColorsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")] ).set_column_colors([RED,BLUE], GREEN) self.add(table) """ columns = self.get_columns() for color, column in zip(colors, columns): column.set_color(color) return self def set_row_colors(self, *colors: Iterable[ParsableManimColor]) -> Table: """Set individual colors for each row of the table. Parameters ---------- colors An iterable of colors; each color corresponds to a row. Examples -------- .. manim:: SetRowColorsExample :save_last_frame: class SetRowColorsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")] ).set_row_colors([RED,BLUE], GREEN) self.add(table) """ rows = self.get_rows() for color, row in zip(colors, rows): row.set_color(color) return self def get_entries( self, pos: Sequence[int] | None = None, ) -> VMobject | VGroup: """Return the individual entries of the table (including labels) or one specific entry if the parameter, ``pos``, is set. Parameters ---------- pos The position of a specific entry on the table. ``(1,1)`` being the top left entry of the table. Returns ------- Union[:class:`~.VMobject`, :class:`~.VGroup`] :class:`~.VGroup` containing all entries of the table (including labels) or the :class:`~.VMobject` at the given position if ``pos`` is set. Examples -------- .. manim:: GetEntriesExample :save_last_frame: class GetEntriesExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) ent = table.get_entries() for item in ent: item.set_color(random_bright_color()) table.get_entries((2,2)).rotate(PI) self.add(table) """ if pos is not None: if ( self.row_labels is not None and self.col_labels is not None and self.top_left_entry is None ): index = len(self.mob_table[0]) * (pos[0] - 1) + pos[1] - 2 return self.elements[index] else: index = len(self.mob_table[0]) * (pos[0] - 1) + pos[1] - 1 return self.elements[index] else: return self.elements def get_entries_without_labels( self, pos: Sequence[int] | None = None, ) -> VMobject | VGroup: """Return the individual entries of the table (without labels) or one specific entry if the parameter, ``pos``, is set. Parameters ---------- pos The position of a specific entry on the table. ``(1,1)`` being the top left entry of the table (without labels). Returns ------- Union[:class:`~.VMobject`, :class:`~.VGroup`] :class:`~.VGroup` containing all entries of the table (without labels) or the :class:`~.VMobject` at the given position if ``pos`` is set. Examples -------- .. manim:: GetEntriesWithoutLabelsExample :save_last_frame: class GetEntriesWithoutLabelsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) ent = table.get_entries_without_labels()
|
table (without labels). Returns ------- Union[:class:`~.VMobject`, :class:`~.VGroup`] :class:`~.VGroup` containing all entries of the table (without labels) or the :class:`~.VMobject` at the given position if ``pos`` is set. Examples -------- .. manim:: GetEntriesWithoutLabelsExample :save_last_frame: class GetEntriesWithoutLabelsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) ent = table.get_entries_without_labels() colors = [BLUE, GREEN, YELLOW, RED] for k in range(len(colors)): ent[k].set_color(colors[k]) table.get_entries_without_labels((2,2)).rotate(PI) self.add(table) """ if pos is not None: index = self.col_dim * (pos[0] - 1) + pos[1] - 1 return self.elements_without_labels[index] else: return self.elements_without_labels def get_row_labels(self) -> VGroup: """Return the row labels of the table. Returns ------- :class:`~.VGroup` :class:`~.VGroup` containing the row labels of the table. Examples -------- .. manim:: GetRowLabelsExample :save_last_frame: class GetRowLabelsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) lab = table.get_row_labels() for item in lab: item.set_color(random_bright_color()) self.add(table) """ return VGroup(*self.row_labels) def get_col_labels(self) -> VGroup: """Return the column labels of the table. Returns -------- :class:`~.VGroup` VGroup containing the column labels of the table. Examples -------- .. manim:: GetColLabelsExample :save_last_frame: class GetColLabelsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) lab = table.get_col_labels() for item in lab: item.set_color(random_bright_color()) self.add(table) """ return VGroup(*self.col_labels) def get_labels(self) -> VGroup: """Returns the labels of the table. Returns -------- :class:`~.VGroup` :class:`~.VGroup` containing all the labels of the table. Examples -------- .. manim:: GetLabelsExample :save_last_frame: class GetLabelsExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) lab = table.get_labels() colors = [BLUE, GREEN, YELLOW, RED] for k in range(len(colors)): lab[k].set_color(colors[k]) self.add(table) """ label_group = VGroup() if self.top_left_entry is not None: label_group.add(self.top_left_entry) for label in (self.col_labels, self.row_labels): if label is not None: label_group.add(*label) return label_group def add_background_to_entries(self, color: ParsableManimColor = BLACK) -> Table: """Adds a black :class:`~.BackgroundRectangle` to each entry of the table.""" for mob in self.get_entries(): mob.add_background_rectangle(color=ManimColor(color)) return self def get_cell(self, pos: Sequence[int] = (1, 1), **kwargs) -> Polygon: """Returns one specific cell as a rectangular :class:`~.Polygon` without the entry. Parameters ---------- pos The position of a specific entry on the table. ``(1,1)`` being the top left entry of the table. kwargs Additional arguments to be passed to :class:`~.Polygon`. Returns ------- :class:`~.Polygon` Polygon mimicking one specific cell of the Table. Examples -------- .. manim:: GetCellExample :save_last_frame: class GetCellExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) cell = table.get_cell((2,2), color=RED) self.add(table, cell) """ row = self.get_rows()[pos[0] - 1] col = self.get_columns()[pos[1] - 1] edge_UL = [ col.get_left()[0] - self.h_buff / 2, row.get_top()[1] + self.v_buff / 2, 0, ] edge_UR = [ col.get_right()[0] + self.h_buff / 2, row.get_top()[1] + self.v_buff / 2, 0, ] edge_DL = [ col.get_left()[0] - self.h_buff / 2, row.get_bottom()[1] - self.v_buff / 2, 0, ] edge_DR = [ col.get_right()[0] + self.h_buff / 2, row.get_bottom()[1] - self.v_buff / 2, 0, ] rec = Polygon(edge_UL, edge_UR, edge_DR, edge_DL, **kwargs) return rec def get_highlighted_cell( self, pos: Sequence[int] = (1, 1), color: ParsableManimColor = YELLOW, **kwargs ) -> BackgroundRectangle: """Returns a :class:`~.BackgroundRectangle` of the cell at the given position. Parameters ---------- pos The position of a specific entry on
|
self.v_buff / 2, 0, ] rec = Polygon(edge_UL, edge_UR, edge_DR, edge_DL, **kwargs) return rec def get_highlighted_cell( self, pos: Sequence[int] = (1, 1), color: ParsableManimColor = YELLOW, **kwargs ) -> BackgroundRectangle: """Returns a :class:`~.BackgroundRectangle` of the cell at the given position. Parameters ---------- pos The position of a specific entry on the table. ``(1,1)`` being the top left entry of the table. color The color used to highlight the cell. kwargs Additional arguments to be passed to :class:`~.BackgroundRectangle`. Examples -------- .. manim:: GetHighlightedCellExample :save_last_frame: class GetHighlightedCellExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) highlight = table.get_highlighted_cell((2,2), color=GREEN) table.add_to_back(highlight) self.add(table) """ cell = self.get_cell(pos) bg_cell = BackgroundRectangle(cell, color=ManimColor(color), **kwargs) return bg_cell def add_highlighted_cell( self, pos: Sequence[int] = (1, 1), color: ParsableManimColor = YELLOW, **kwargs ) -> Table: """Highlights one cell at a specific position on the table by adding a :class:`~.BackgroundRectangle`. Parameters ---------- pos The position of a specific entry on the table. ``(1,1)`` being the top left entry of the table. color The color used to highlight the cell. kwargs Additional arguments to be passed to :class:`~.BackgroundRectangle`. Examples -------- .. manim:: AddHighlightedCellExample :save_last_frame: class AddHighlightedCellExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) table.add_highlighted_cell((2,2), color=GREEN) self.add(table) """ bg_cell = self.get_highlighted_cell(pos, color=ManimColor(color), **kwargs) self.add_to_back(bg_cell) entry = self.get_entries(pos) entry.background_rectangle = bg_cell return self def create( self, lag_ratio: float = 1, line_animation: Callable[[VMobject | VGroup], Animation] = Create, label_animation: Callable[[VMobject | VGroup], Animation] = Write, element_animation: Callable[[VMobject | VGroup], Animation] = Create, entry_animation: Callable[[VMobject | VGroup], Animation] = FadeIn, **kwargs, ) -> AnimationGroup: """Customized create-type function for tables. Parameters ---------- lag_ratio The lag ratio of the animation. line_animation The animation style of the table lines, see :mod:`~.creation` for examples. label_animation The animation style of the table labels, see :mod:`~.creation` for examples. element_animation The animation style of the table elements, see :mod:`~.creation` for examples. entry_animation The entry animation of the table background, see :mod:`~.creation` for examples. kwargs Further arguments passed to the creation animations. Returns ------- :class:`~.AnimationGroup` AnimationGroup containing creation of the lines and of the elements. Examples -------- .. manim:: CreateTableExample class CreateTableExample(Scene): def construct(self): table = Table( [["First", "Second"], ["Third","Fourth"]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")], include_outer_lines=True) self.play(table.create()) self.wait() """ animations: Sequence[Animation] = [ line_animation( VGroup(self.vertical_lines, self.horizontal_lines), **kwargs, ), element_animation(self.elements_without_labels.set_z_index(2), **kwargs), ] if self.get_labels(): animations += [ label_animation(self.get_labels(), **kwargs), ] if self.get_entries(): for entry in self.elements_without_labels: try: animations += [ entry_animation( entry.background_rectangle, **kwargs, ) ] except AttributeError: continue return AnimationGroup(*animations, lag_ratio=lag_ratio) def scale(self, scale_factor: float, **kwargs): # h_buff and v_buff must be adjusted so that Table.get_cell # can construct an accurate polygon for a cell. self.h_buff *= scale_factor self.v_buff *= scale_factor super().scale(scale_factor, **kwargs) return self class MathTable(Table): """A specialized :class:`~.Table` mobject for use with LaTeX. Examples -------- .. manim:: MathTableExample :save_last_frame: class MathTableExample(Scene): def construct(self): t0 = MathTable( [["+", 0, 5, 10], [0, 0, 5, 10], [2, 2, 7, 12], [4, 4, 9, 14]], include_outer_lines=True) self.add(t0) """ def __init__( self, table: Iterable[Iterable[float | str]], element_to_mobject: Callable[[float | str], VMobject] = MathTex, **kwargs, ): """ Special case
|
-------- .. manim:: MathTableExample :save_last_frame: class MathTableExample(Scene): def construct(self): t0 = MathTable( [["+", 0, 5, 10], [0, 0, 5, 10], [2, 2, 7, 12], [4, 4, 9, 14]], include_outer_lines=True) self.add(t0) """ def __init__( self, table: Iterable[Iterable[float | str]], element_to_mobject: Callable[[float | str], VMobject] = MathTex, **kwargs, ): """ Special case of :class:`~.Table` with `element_to_mobject` set to :class:`~.MathTex`. Every entry in `table` is set in a Latex `align` environment. Parameters ---------- table A 2d array or list of lists. Content of the table have to be valid input for :class:`~.MathTex`. element_to_mobject The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.MathTex`. kwargs Additional arguments to be passed to :class:`~.Table`. """ super().__init__( table, element_to_mobject=element_to_mobject, **kwargs, ) class MobjectTable(Table): """A specialized :class:`~.Table` mobject for use with :class:`~.Mobject`. Examples -------- .. manim:: MobjectTableExample :save_last_frame: class MobjectTableExample(Scene): def construct(self): cross = VGroup( Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT), ) a = Circle().set_color(RED).scale(0.5) b = cross.set_color(BLUE).scale(0.5) t0 = MobjectTable( [[a.copy(),b.copy(),a.copy()], [b.copy(),a.copy(),a.copy()], [a.copy(),b.copy(),b.copy()]] ) line = Line( t0.get_corner(DL), t0.get_corner(UR) ).set_color(RED) self.add(t0, line) """ def __init__( self, table: Iterable[Iterable[VMobject]], element_to_mobject: Callable[[VMobject], VMobject] = lambda m: m, **kwargs, ): """ Special case of :class:`~.Table` with ``element_to_mobject`` set to an identity function. Here, every item in ``table`` must already be of type :class:`~.Mobject`. Parameters ---------- table A 2D array or list of lists. Content of the table must be of type :class:`~.Mobject`. element_to_mobject The :class:`~.Mobject` class applied to the table entries. Set as ``lambda m : m`` to return itself. kwargs Additional arguments to be passed to :class:`~.Table`. """ super().__init__(table, element_to_mobject=element_to_mobject, **kwargs) class IntegerTable(Table): r"""A specialized :class:`~.Table` mobject for use with :class:`~.Integer`. Examples -------- .. manim:: IntegerTableExample :save_last_frame: class IntegerTableExample(Scene): def construct(self): t0 = IntegerTable( [[0,30,45,60,90], [90,60,45,30,0]], col_labels=[ MathTex(r"\frac{\sqrt{0}}{2}"), MathTex(r"\frac{\sqrt{1}}{2}"), MathTex(r"\frac{\sqrt{2}}{2}"), MathTex(r"\frac{\sqrt{3}}{2}"), MathTex(r"\frac{\sqrt{4}}{2}")], row_labels=[MathTex(r"\sin"), MathTex(r"\cos")], h_buff=1, element_to_mobject_config={"unit": r"^{\circ}"}) self.add(t0) """ def __init__( self, table: Iterable[Iterable[float | str]], element_to_mobject: Callable[[float | str], VMobject] = Integer, **kwargs, ): """ Special case of :class:`~.Table` with `element_to_mobject` set to :class:`~.Integer`. Will round if there are decimal entries in the table. Parameters ---------- table A 2d array or list of lists. Content of the table has to be valid input for :class:`~.Integer`. element_to_mobject The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.Integer`. kwargs Additional arguments to be passed to :class:`~.Table`. """ super().__init__(table, element_to_mobject=element_to_mobject, **kwargs) class DecimalTable(Table): """A specialized :class:`~.Table` mobject for use with :class:`~.DecimalNumber` to display decimal entries. Examples -------- .. manim:: DecimalTableExample :save_last_frame: class DecimalTableExample(Scene): def construct(self): x_vals = [-2,-1,0,1,2] y_vals = np.exp(x_vals) t0 = DecimalTable( [x_vals, y_vals], row_labels=[MathTex("x"), MathTex("f(x)=e^{x}")], h_buff=1, element_to_mobject_config={"num_decimal_places": 2}) self.add(t0) """ def __init__( self, table: Iterable[Iterable[float | str]], element_to_mobject: Callable[[float | str], VMobject] = DecimalNumber, element_to_mobject_config: dict = {"num_decimal_places": 1}, **kwargs, ): """ Special case of :class:`~.Table` with ``element_to_mobject`` set to :class:`~.DecimalNumber`. By default, ``num_decimal_places`` is set to 1. Will round/truncate the decimal places based on the provided ``element_to_mobject_config``. Parameters ---------- table A 2D array, or a list of lists. Content of the table must be valid input for :class:`~.DecimalNumber`. element_to_mobject The :class:`~.Mobject` class applied to the table entries. Set as
|
:class:`~.DecimalNumber`. By default, ``num_decimal_places`` is set to 1. Will round/truncate the decimal places based on the provided ``element_to_mobject_config``. Parameters ---------- table A 2D array, or a list of lists. Content of the table must be valid input for :class:`~.DecimalNumber`. element_to_mobject The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.DecimalNumber`. element_to_mobject_config Element to mobject config, here set as {"num_decimal_places": 1}. kwargs Additional arguments to be passed to :class:`~.Table`. """ super().__init__( table, element_to_mobject=element_to_mobject, element_to_mobject_config=element_to_mobject_config, **kwargs, ) ================================================ FILE: manim/mobject/utils.py ================================================ """Utilities for working with mobjects.""" from __future__ import annotations __all__ = [ "get_mobject_class", "get_point_mobject_class", "get_vectorized_mobject_class", ] from .._config import config from ..constants import RendererType from .mobject import Mobject from .opengl.opengl_mobject import OpenGLMobject from .opengl.opengl_point_cloud_mobject import OpenGLPMobject from .opengl.opengl_vectorized_mobject import OpenGLVMobject from .types.point_cloud_mobject import PMobject from .types.vectorized_mobject import VMobject def get_mobject_class() -> type: """Gets the base mobject class, depending on the currently active renderer. .. NOTE:: This method is intended to be used in the code base of Manim itself or in plugins where code should work independent of the selected renderer. Examples -------- The function has to be explicitly imported. We test that the name of the returned class is one of the known mobject base classes:: >>> from manim.mobject.utils import get_mobject_class >>> get_mobject_class().__name__ in ['Mobject', 'OpenGLMobject'] True """ if config.renderer == RendererType.CAIRO: return Mobject if config.renderer == RendererType.OPENGL: return OpenGLMobject raise NotImplementedError( "Base mobjects are not implemented for the active renderer." ) def get_vectorized_mobject_class() -> type: """Gets the vectorized mobject class, depending on the currently active renderer. .. NOTE:: This method is intended to be used in the code base of Manim itself or in plugins where code should work independent of the selected renderer. Examples -------- The function has to be explicitly imported. We test that the name of the returned class is one of the known mobject base classes:: >>> from manim.mobject.utils import get_vectorized_mobject_class >>> get_vectorized_mobject_class().__name__ in ['VMobject', 'OpenGLVMobject'] True """ if config.renderer == RendererType.CAIRO: return VMobject if config.renderer == RendererType.OPENGL: return OpenGLVMobject raise NotImplementedError( "Vectorized mobjects are not implemented for the active renderer." ) def get_point_mobject_class() -> type: """Gets the point cloud mobject class, depending on the currently active renderer. .. NOTE:: This method is intended to be used in the code base of Manim itself or in plugins where code should work independent of the selected renderer. Examples -------- The function has to be explicitly imported. We test that the name of the returned class is one of the known mobject base classes:: >>> from manim.mobject.utils import get_point_mobject_class >>> get_point_mobject_class().__name__ in ['PMobject', 'OpenGLPMobject'] True """ if config.renderer == RendererType.CAIRO: return PMobject if config.renderer == RendererType.OPENGL: return OpenGLPMobject raise NotImplementedError( "Point cloud mobjects are not implemented for the active renderer." ) ================================================ FILE: manim/mobject/value_tracker.py ================================================ """Simple mobjects that can be used for storing (and updating) a value.""" from __future__ import annotations __all__ = ["ValueTracker", "ComplexValueTracker"] from typing import TYPE_CHECKING, Any import numpy as np from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.utils.paths import straight_path if TYPE_CHECKING: from typing_extensions import Self from manim.typing import PathFuncType
|
mobjects that can be used for storing (and updating) a value.""" from __future__ import annotations __all__ = ["ValueTracker", "ComplexValueTracker"] from typing import TYPE_CHECKING, Any import numpy as np from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.utils.paths import straight_path if TYPE_CHECKING: from typing_extensions import Self from manim.typing import PathFuncType class ValueTracker(Mobject, metaclass=ConvertToOpenGL): """A mobject that can be used for tracking (real-valued) parameters. Useful for animating parameter changes. Not meant to be displayed. Instead the position encodes some number, often one which another animation or continual_animation uses for its update function, and by treating it as a mobject it can still be animated and manipulated just like anything else. This value changes continuously when animated using the :attr:`animate` syntax. Examples -------- .. manim:: ValueTrackerExample class ValueTrackerExample(Scene): def construct(self): number_line = NumberLine() pointer = Vector(DOWN) label = MathTex("x").add_updater(lambda m: m.next_to(pointer, UP)) tracker = ValueTracker(0) pointer.add_updater( lambda m: m.next_to( number_line.n2p(tracker.get_value()), UP ) ) self.add(number_line, pointer,label) tracker += 1.5 self.wait(1) tracker -= 4 self.wait(0.5) self.play(tracker.animate.set_value(5)) self.wait(0.5) self.play(tracker.animate.set_value(3)) self.play(tracker.animate.increment_value(-2)) self.wait(0.5) .. note:: You can also link ValueTrackers to updaters. In this case, you have to make sure that the ValueTracker is added to the scene by ``add`` .. manim:: ValueTrackerExample class ValueTrackerExample(Scene): def construct(self): tracker = ValueTracker(0) label = Dot(radius=3).add_updater(lambda x : x.set_x(tracker.get_value())) self.add(label) self.add(tracker) tracker.add_updater(lambda mobject, dt: mobject.increment_value(dt)) self.wait(2) """ def __init__(self, value: float = 0, **kwargs: Any) -> None: super().__init__(**kwargs) self.set(points=np.zeros((1, 3))) self.set_value(value) def get_value(self) -> float: """Get the current value of this ValueTracker.""" value: float = self.points[0, 0] return value def set_value(self, value: float) -> Self: """Sets a new scalar value to the ValueTracker.""" self.points[0, 0] = value return self def increment_value(self, d_value: float) -> Self: """Increments (adds) a scalar value to the ValueTracker.""" self.set_value(self.get_value() + d_value) return self def __bool__(self) -> bool: """Return whether the value of this ValueTracker evaluates as true.""" return bool(self.get_value()) def __add__(self, d_value: float | Mobject) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value plus ``d_value``. """ if isinstance(d_value, Mobject): raise ValueError( "Cannot increment ValueTracker by a Mobject. Please provide a scalar value." ) return ValueTracker(self.get_value() + d_value) def __iadd__(self, d_value: float | Mobject) -> Self: """adds ``+=`` syntax to increment the value of the ValueTracker.""" if isinstance(d_value, Mobject): raise ValueError( "Cannot increment ValueTracker by a Mobject. Please provide a scalar value." ) self.increment_value(d_value) return self def __floordiv__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the floor division of the current tracker's value by ``d_value``. """ return ValueTracker(self.get_value() // d_value) def __ifloordiv__(self, d_value: float) -> Self: """Set the value of this ValueTracker to the floor division of the current value by ``d_value``.""" self.set_value(self.get_value() // d_value) return self def __mod__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value modulo ``d_value``. """ return ValueTracker(self.get_value() % d_value) def __imod__(self, d_value: float) -> Self: """Set the value of this ValueTracker to the current value modulo ``d_value``.""" self.set_value(self.get_value() % d_value) return self def __mul__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is
|
whose value is the current tracker's value modulo ``d_value``. """ return ValueTracker(self.get_value() % d_value) def __imod__(self, d_value: float) -> Self: """Set the value of this ValueTracker to the current value modulo ``d_value``.""" self.set_value(self.get_value() % d_value) return self def __mul__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value multiplied by ``d_value``. """ return ValueTracker(self.get_value() * d_value) def __imul__(self, d_value: float) -> Self: """Set the value of this ValueTracker to the product of the current value and ``d_value``.""" self.set_value(self.get_value() * d_value) return self def __pow__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value raised to the power of ``d_value``. """ return ValueTracker(self.get_value() ** d_value) def __ipow__(self, d_value: float) -> Self: """Set the value of this ValueTracker to the current value raised to the power of ``d_value``.""" self.set_value(self.get_value() ** d_value) return self def __sub__(self, d_value: float | Mobject) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value minus ``d_value``. """ if isinstance(d_value, Mobject): raise ValueError( "Cannot decrement ValueTracker by a Mobject. Please provide a scalar value." ) return ValueTracker(self.get_value() - d_value) def __isub__(self, d_value: float | Mobject) -> Self: """Adds ``-=`` syntax to decrement the value of the ValueTracker.""" if isinstance(d_value, Mobject): raise ValueError( "Cannot decrement ValueTracker by a Mobject. Please provide a scalar value." ) self.increment_value(-d_value) return self def __truediv__(self, d_value: float) -> ValueTracker: """Return a new :class:`ValueTracker` whose value is the current tracker's value divided by ``d_value``. """ return ValueTracker(self.get_value() / d_value) def __itruediv__(self, d_value: float) -> Self: """Sets the value of this ValueTracker to the current value divided by ``d_value``.""" self.set_value(self.get_value() / d_value) return self def interpolate( self, mobject1: Mobject, mobject2: Mobject, alpha: float, path_func: PathFuncType = straight_path(), ) -> Self: """Turns ``self`` into an interpolation between ``mobject1`` and ``mobject2``.""" self.set(points=path_func(mobject1.points, mobject2.points, alpha)) return self class ComplexValueTracker(ValueTracker): """Tracks a complex-valued parameter. The value is internally stored as a points array [a, b, 0]. This can be accessed directly to represent the value geometrically, see the usage example. When the value is set through :attr:`animate`, the value will take a straight path from the source point to the destination point. Examples -------- .. manim:: ComplexValueTrackerExample class ComplexValueTrackerExample(Scene): def construct(self): tracker = ComplexValueTracker(-2+1j) dot = Dot().add_updater( lambda x: x.move_to(tracker.points) ) self.add(NumberPlane(), dot) self.play(tracker.animate.set_value(3+2j)) self.play(tracker.animate.set_value(tracker.get_value() * 1j)) self.play(tracker.animate.set_value(tracker.get_value() - 2j)) self.play(tracker.animate.set_value(tracker.get_value() / (-2 + 3j))) """ def get_value(self) -> complex: # type: ignore [override] """Get the current value of this ComplexValueTracker as a complex number.""" return complex(*self.points[0, :2]) def set_value(self, value: complex | float) -> Self: """Sets a new complex value to the ComplexValueTracker.""" z = complex(value) self.points[0, :2] = (z.real, z.imag) return self ================================================ FILE: manim/mobject/vector_field.py ================================================ """Mobjects representing vector fields.""" from __future__ import annotations __all__ = [ "VectorField", "ArrowVectorField", "StreamLines", ] import itertools as it import random from collections.abc import Callable, Iterable, Sequence from math import ceil, floor from typing import TYPE_CHECKING import numpy as np from PIL import Image from manim.animation.updaters.update import UpdateFromAlphaFunc from manim.mobject.geometry.line import Vector from manim.mobject.graphing.coordinate_systems import CoordinateSystem from
|
annotations __all__ = [ "VectorField", "ArrowVectorField", "StreamLines", ] import itertools as it import random from collections.abc import Callable, Iterable, Sequence from math import ceil, floor from typing import TYPE_CHECKING import numpy as np from PIL import Image from manim.animation.updaters.update import UpdateFromAlphaFunc from manim.mobject.geometry.line import Vector from manim.mobject.graphing.coordinate_systems import CoordinateSystem from .. import config from ..animation.composition import AnimationGroup, Succession from ..animation.creation import Create from ..animation.indication import ShowPassingFlash from ..constants import OUT, RIGHT, UP, RendererType from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VGroup from ..mobject.utils import get_vectorized_mobject_class from ..utils.bezier import interpolate, inverse_interpolate from ..utils.color import ( BLUE_E, GREEN, RED, YELLOW, ManimColor, ParsableManimColor, color_to_rgb, rgb_to_color, ) from ..utils.rate_functions import ease_out_sine, linear from ..utils.simple_functions import sigmoid if TYPE_CHECKING: from manim.typing import ( FloatRGB, FloatRGB_Array, FloatRGBA_Array, Point3D, Vector3D, ) DEFAULT_SCALAR_FIELD_COLORS: list = [BLUE_E, GREEN, YELLOW, RED] class VectorField(VGroup): """A vector field. Vector fields are based on a function defining a vector at every position. This class does by default not include any visible elements but provides methods to move other :class:`~.Mobject` s along the vector field. Parameters ---------- func The function defining the rate of change at every position of the `VectorField`. color The color of the vector field. If set, position-specific coloring is disabled. color_scheme A function mapping a vector to a single value. This value gives the position in the color gradient defined using `min_color_scheme_value`, `max_color_scheme_value` and `colors`. min_color_scheme_value The value of the color_scheme function to be mapped to the first color in `colors`. Lower values also result in the first color of the gradient. max_color_scheme_value The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient. colors The colors defining the color gradient of the vector field. kwargs Additional arguments to be passed to the :class:`~.VGroup` constructor """ def __init__( self, func: Callable[[Point3D], Vector3D], color: ParsableManimColor | None = None, color_scheme: Callable[[Vector3D], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS, **kwargs, ): super().__init__(**kwargs) self.func = func if color is None: self.single_color = False if color_scheme is None: def color_scheme(vec: Vector3D) -> float: return np.linalg.norm(vec) self.color_scheme = color_scheme # TODO maybe other default for direction? self.rgbs: FloatRGB_Array = np.array(list(map(color_to_rgb, colors))) def pos_to_rgb(pos: Point3D) -> FloatRGB: vec = self.func(pos) color_value = np.clip( self.color_scheme(vec), min_color_scheme_value, max_color_scheme_value, ) alpha = inverse_interpolate( min_color_scheme_value, max_color_scheme_value, color_value, ) alpha *= len(self.rgbs) - 1 c1: FloatRGB = self.rgbs[int(alpha)] c2: FloatRGB = self.rgbs[min(int(alpha + 1), len(self.rgbs) - 1)] alpha %= 1 return interpolate(c1, c2, alpha) self.pos_to_rgb = pos_to_rgb self.pos_to_color = lambda pos: rgb_to_color(self.pos_to_rgb(pos)) else: self.single_color = True self.color = ManimColor.parse(color) self.submob_movement_updater = None @staticmethod def shift_func( func: Callable[[np.ndarray], np.ndarray], shift_vector: np.ndarray, ) -> Callable[[np.ndarray], np.ndarray]: """Shift a vector field function. Parameters ---------- func The function defining a vector field. shift_vector The shift to be applied to the vector field. Returns ------- `Callable[[np.ndarray], np.ndarray]` The shifted vector field function. """ return lambda p: func(p - shift_vector) @staticmethod def scale_func( func: Callable[[np.ndarray], np.ndarray], scalar: float, ) -> Callable[[np.ndarray], np.ndarray]:
|
vector field function. Parameters ---------- func The function defining a vector field. shift_vector The shift to be applied to the vector field. Returns ------- `Callable[[np.ndarray], np.ndarray]` The shifted vector field function. """ return lambda p: func(p - shift_vector) @staticmethod def scale_func( func: Callable[[np.ndarray], np.ndarray], scalar: float, ) -> Callable[[np.ndarray], np.ndarray]: """Scale a vector field function. Parameters ---------- func The function defining a vector field. scalar The scalar to be applied to the vector field. Examples -------- .. manim:: ScaleVectorFieldFunction class ScaleVectorFieldFunction(Scene): def construct(self): func = lambda pos: np.sin(pos[1]) * RIGHT + np.cos(pos[0]) * UP vector_field = ArrowVectorField(func) self.add(vector_field) self.wait() func = VectorField.scale_func(func, 0.5) self.play(vector_field.animate.become(ArrowVectorField(func))) self.wait() Returns ------- `Callable[[np.ndarray], np.ndarray]` The scaled vector field function. """ return lambda p: func(p * scalar) def fit_to_coordinate_system(self, coordinate_system: CoordinateSystem): """Scale the vector field to fit a coordinate system. This method is useful when the vector field is defined in a coordinate system different from the one used to display the vector field. This method can only be used once because it transforms the origin of each vector. Parameters ---------- coordinate_system The coordinate system to fit the vector field to. """ self.apply_function(lambda pos: coordinate_system.coords_to_point(*pos)) def nudge( self, mob: Mobject, dt: float = 1, substeps: int = 1, pointwise: bool = False, ) -> VectorField: """Nudge a :class:`~.Mobject` along the vector field. Parameters ---------- mob The mobject to move along the vector field dt A scalar to the amount the mobject is moved along the vector field. The actual distance is based on the magnitude of the vector field. substeps The amount of steps the whole nudge is divided into. Higher values give more accurate approximations. pointwise Whether to move the mobject along the vector field. If `False` the vector field takes effect on the center of the given :class:`~.Mobject`. If `True` the vector field takes effect on the points of the individual points of the :class:`~.Mobject`, potentially distorting it. Returns ------- VectorField This vector field. Examples -------- .. manim:: Nudging class Nudging(Scene): def construct(self): func = lambda pos: np.sin(pos[1] / 2) * RIGHT + np.cos(pos[0] / 2) * UP vector_field = ArrowVectorField( func, x_range=[-7, 7, 1], y_range=[-4, 4, 1], length_func=lambda x: x / 2 ) self.add(vector_field) circle = Circle(radius=2).shift(LEFT) self.add(circle.copy().set_color(GRAY)) dot = Dot().move_to(circle) vector_field.nudge(circle, -2, 60, True) vector_field.nudge(dot, -2, 60) circle.add_updater(vector_field.get_nudge_updater(pointwise=True)) dot.add_updater(vector_field.get_nudge_updater()) self.add(circle, dot) self.wait(6) """ def runge_kutta(self, p: Sequence[float], step_size: float) -> float: """Returns the change in position of a point along a vector field. Parameters ---------- p The position of each point being moved along the vector field. step_size A scalar that is used to determine how much a point is shifted in a single step. Returns ------- float How much the point is shifted. """ k_1 = self.func(p) k_2 = self.func(p + step_size * (k_1 * 0.5)) k_3 = self.func(p + step_size * (k_2 * 0.5)) k_4 = self.func(p + step_size * k_3) return step_size / 6.0 * (k_1 + 2.0 * k_2 + 2.0 * k_3 + k_4) step_size = dt / substeps for _ in range(substeps): if pointwise: mob.apply_function(lambda p:
|
step_size * (k_1 * 0.5)) k_3 = self.func(p + step_size * (k_2 * 0.5)) k_4 = self.func(p + step_size * k_3) return step_size / 6.0 * (k_1 + 2.0 * k_2 + 2.0 * k_3 + k_4) step_size = dt / substeps for _ in range(substeps): if pointwise: mob.apply_function(lambda p: p + runge_kutta(self, p, step_size)) else: mob.shift(runge_kutta(self, mob.get_center(), step_size)) return self def nudge_submobjects( self, dt: float = 1, substeps: int = 1, pointwise: bool = False, ) -> VectorField: """Apply a nudge along the vector field to all submobjects. Parameters ---------- dt A scalar to the amount the mobject is moved along the vector field. The actual distance is based on the magnitude of the vector field. substeps The amount of steps the whole nudge is divided into. Higher values give more accurate approximations. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- VectorField This vector field. """ for mob in self.submobjects: self.nudge(mob, dt, substeps, pointwise) return self def get_nudge_updater( self, speed: float = 1, pointwise: bool = False, ) -> Callable[[Mobject, float], Mobject]: """Get an update function to move a :class:`~.Mobject` along the vector field. When used with :meth:`~.Mobject.add_updater`, the mobject will move along the vector field, where its speed is determined by the magnitude of the vector field. Parameters ---------- speed At `speed=1` the distance a mobject moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of such a mobject. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- Callable[[Mobject, float], Mobject] The update function. """ return lambda mob, dt: self.nudge(mob, dt * speed, pointwise=pointwise) def start_submobject_movement( self, speed: float = 1, pointwise: bool = False, ) -> VectorField: """Start continuously moving all submobjects along the vector field. Calling this method multiple times will result in removing the previous updater created by this method. Parameters ---------- speed The speed at which to move the submobjects. See :meth:`get_nudge_updater` for details. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- VectorField This vector field. """ self.stop_submobject_movement() self.submob_movement_updater = lambda mob, dt: mob.nudge_submobjects( dt * speed, pointwise=pointwise, ) self.add_updater(self.submob_movement_updater) return self def stop_submobject_movement(self) -> VectorField: """Stops the continuous movement started using :meth:`start_submobject_movement`. Returns ------- VectorField This vector field. """ self.remove_updater(self.submob_movement_updater) self.submob_movement_updater = None return self def get_colored_background_image(self, sampling_rate: int = 5) -> Image.Image: """Generate an image that displays the vector field. The color at each position is calculated by passing the positing through a series of steps: Calculate the vector field function at that position, map that vector to a single value using `self.color_scheme` and finally generate a color from that value using the color gradient. Parameters ---------- sampling_rate The stepsize at which pixels get included in the image. Lower values give more accurate results, but may take a long time to compute. Returns ------- Image.Imgae The vector field image. """ if self.single_color: raise ValueError( "There is no
|
color from that value using the color gradient. Parameters ---------- sampling_rate The stepsize at which pixels get included in the image. Lower values give more accurate results, but may take a long time to compute. Returns ------- Image.Imgae The vector field image. """ if self.single_color: raise ValueError( "There is no point in generating an image if the vector field uses a single color.", ) ph = int(config["pixel_height"] / sampling_rate) pw = int(config["pixel_width"] / sampling_rate) fw = config["frame_width"] fh = config["frame_height"] points_array = np.zeros((ph, pw, 3)) x_array = np.linspace(-fw / 2, fw / 2, pw) y_array = np.linspace(fh / 2, -fh / 2, ph) x_array = x_array.reshape((1, len(x_array))) y_array = y_array.reshape((len(y_array), 1)) x_array = x_array.repeat(ph, axis=0) y_array.repeat(pw, axis=1) # TODO why not y_array = y_array.repeat(...)? points_array[:, :, 0] = x_array points_array[:, :, 1] = y_array rgbs = np.apply_along_axis(self.pos_to_rgb, 2, points_array) return Image.fromarray((rgbs * 255).astype("uint8")) def get_vectorized_rgba_gradient_function( self, start: float, end: float, colors: Iterable[ParsableManimColor], ) -> Callable[[Sequence[float], float], FloatRGBA_Array]: """ Generates a gradient of rgbas as a numpy array Parameters ---------- start start value used for inverse interpolation at :func:`~.inverse_interpolate` end end value used for inverse interpolation at :func:`~.inverse_interpolate` colors list of colors to generate the gradient Returns ------- function to generate the gradients as numpy arrays representing rgba values """ rgbs: FloatRGB_Array = np.array([color_to_rgb(c) for c in colors]) def func(values: Sequence[float], opacity: float = 1.0) -> FloatRGBA_Array: alphas = inverse_interpolate(start, end, np.array(values)) alphas = np.clip(alphas, 0, 1) scaled_alphas = alphas * (len(rgbs) - 1) indices = scaled_alphas.astype(int) next_indices = np.clip(indices + 1, 0, len(rgbs) - 1) inter_alphas = scaled_alphas % 1 inter_alphas = inter_alphas.repeat(3).reshape((len(indices), 3)) new_rgbs: FloatRGB_Array = interpolate( rgbs[indices], rgbs[next_indices], inter_alphas ) new_rgbas: FloatRGBA_Array = np.concatenate( (new_rgbs, np.full([len(new_rgbs), 1], opacity)), axis=1, ) return new_rgbas return func class ArrowVectorField(VectorField): """A :class:`VectorField` represented by a set of change vectors. Vector fields are always based on a function defining the :class:`~.Vector` at every position. The values of this functions is displayed as a grid of vectors. By default the color of each vector is determined by it's magnitude. Other color schemes can be used however. Parameters ---------- func The function defining the rate of change at every position of the vector field. color The color of the vector field. If set, position-specific coloring is disabled. color_scheme A function mapping a vector to a single value. This value gives the position in the color gradient defined using `min_color_scheme_value`, `max_color_scheme_value` and `colors`. min_color_scheme_value The value of the color_scheme function to be mapped to the first color in `colors`. Lower values also result in the first color of the gradient. max_color_scheme_value The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient. colors The colors defining the color gradient of the vector field. x_range A sequence of x_min, x_max, delta_x y_range A sequence of y_min, y_max, delta_y z_range A sequence of z_min, z_max, delta_z three_dimensions Enables three_dimensions. Default set to False, automatically turns True if z_range is not None. length_func The
|
gradient. colors The colors defining the color gradient of the vector field. x_range A sequence of x_min, x_max, delta_x y_range A sequence of y_min, y_max, delta_y z_range A sequence of z_min, z_max, delta_z three_dimensions Enables three_dimensions. Default set to False, automatically turns True if z_range is not None. length_func The function determining the displayed size of the vectors. The actual size of the vector is passed, the returned value will be used as display size for the vector. By default this is used to cap the displayed size of vectors to reduce the clutter. opacity The opacity of the arrows. vector_config Additional arguments to be passed to the :class:`~.Vector` constructor kwargs Additional arguments to be passed to the :class:`~.VGroup` constructor Examples -------- .. manim:: BasicUsage :save_last_frame: class BasicUsage(Scene): def construct(self): func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3 self.add(ArrowVectorField(func)) .. manim:: SizingAndSpacing class SizingAndSpacing(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT vf = ArrowVectorField(func, x_range=[-7, 7, 1]) self.add(vf) self.wait() length_func = lambda x: x / 3 vf2 = ArrowVectorField(func, x_range=[-7, 7, 1], length_func=length_func) self.play(vf.animate.become(vf2)) self.wait() .. manim:: Coloring :save_last_frame: class Coloring(Scene): def construct(self): func = lambda pos: pos - LEFT * 5 colors = [RED, YELLOW, BLUE, DARK_GRAY] min_radius = Circle(radius=2, color=colors[0]).shift(LEFT * 5) max_radius = Circle(radius=10, color=colors[-1]).shift(LEFT * 5) vf = ArrowVectorField( func, min_color_scheme_value=2, max_color_scheme_value=10, colors=colors ) self.add(vf, min_radius, max_radius) """ def __init__( self, func: Callable[[np.ndarray], np.ndarray], color: ParsableManimColor | None = None, color_scheme: Callable[[np.ndarray], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS, # Determining Vector positions: x_range: Sequence[float] = None, y_range: Sequence[float] = None, z_range: Sequence[float] = None, three_dimensions: bool = False, # Automatically True if z_range is set # Takes in actual norm, spits out displayed norm length_func: Callable[[float], float] = lambda norm: 0.45 * sigmoid(norm), opacity: float = 1.0, vector_config: dict | None = None, **kwargs, ): self.x_range = x_range or [ floor(-config["frame_width"] / 2), ceil(config["frame_width"] / 2), ] self.y_range = y_range or [ floor(-config["frame_height"] / 2), ceil(config["frame_height"] / 2), ] self.ranges = [self.x_range, self.y_range] if three_dimensions or z_range: self.z_range = z_range or self.y_range.copy() self.ranges += [self.z_range] else: self.ranges += [[0, 0]] for i in range(len(self.ranges)): if len(self.ranges[i]) == 2: self.ranges[i] += [0.5] self.ranges[i][1] += self.ranges[i][2] self.x_range, self.y_range, self.z_range = self.ranges super().__init__( func, color, color_scheme, min_color_scheme_value, max_color_scheme_value, colors, **kwargs, ) self.length_func = length_func self.opacity = opacity if vector_config is None: vector_config = {} self.vector_config = vector_config self.func = func x_range = np.arange(*self.x_range) y_range = np.arange(*self.y_range) z_range = np.arange(*self.z_range) self.add( *[ self.get_vector(x * RIGHT + y * UP + z * OUT) for x, y, z in it.product(x_range, y_range, z_range) ] ) self.set_opacity(self.opacity) def get_vector(self, point: np.ndarray): """Creates a vector in the vector field. The created vector is based on the function of the vector field and is rooted in the given point. Color and length fit the specifications of this vector field. Parameters ---------- point The root point of the
|
) self.set_opacity(self.opacity) def get_vector(self, point: np.ndarray): """Creates a vector in the vector field. The created vector is based on the function of the vector field and is rooted in the given point. Color and length fit the specifications of this vector field. Parameters ---------- point The root point of the vector. """ output = np.array(self.func(point)) norm = np.linalg.norm(output) if norm != 0: output *= self.length_func(norm) / norm vect = Vector(output, **self.vector_config) vect.shift(point) if self.single_color: vect.set_color(self.color) else: vect.set_color(self.pos_to_color(point)) return vect class StreamLines(VectorField): """StreamLines represent the flow of a :class:`VectorField` using the trace of moving agents. Vector fields are always based on a function defining the vector at every position. The values of this functions is displayed by moving many agents along the vector field and showing their trace. Parameters ---------- func The function defining the rate of change at every position of the vector field. color The color of the vector field. If set, position-specific coloring is disabled. color_scheme A function mapping a vector to a single value. This value gives the position in the color gradient defined using `min_color_scheme_value`, `max_color_scheme_value` and `colors`. min_color_scheme_value The value of the color_scheme function to be mapped to the first color in `colors`. Lower values also result in the first color of the gradient. max_color_scheme_value The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient. colors The colors defining the color gradient of the vector field. x_range A sequence of x_min, x_max, delta_x y_range A sequence of y_min, y_max, delta_y z_range A sequence of z_min, z_max, delta_z three_dimensions Enables three_dimensions. Default set to False, automatically turns True if z_range is not None. noise_factor The amount by which the starting position of each agent is altered along each axis. Defaults to :code:`delta_y / 2` if not defined. n_repeats The number of agents generated at each starting point. dt The factor by which the distance an agent moves per step is stretched. Lower values result in a better approximation of the trajectories in the vector field. virtual_time The time the agents get to move in the vector field. Higher values therefore result in longer stream lines. However, this whole time gets simulated upon creation. max_anchors_per_line The maximum number of anchors per line. Lines with more anchors get reduced in complexity, not in length. padding The distance agents can move out of the generation area before being terminated. stroke_width The stroke with of the stream lines. opacity The opacity of the stream lines. Examples -------- .. manim:: BasicUsage :save_last_frame: class BasicUsage(Scene): def construct(self): func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3 self.add(StreamLines(func)) .. manim:: SpawningAndFlowingArea :save_last_frame: class SpawningAndFlowingArea(Scene): def construct(self): func = lambda pos: np.sin(pos[0]) * UR + np.cos(pos[1]) * LEFT + pos / 5 stream_lines = StreamLines( func, x_range=[-3, 3, 0.2], y_range=[-2, 2, 0.2], padding=1 ) spawning_area = Rectangle(width=6, height=4) flowing_area = Rectangle(width=8, height=6) labels = [Tex("Spawning Area"), Tex("Flowing Area").shift(DOWN * 2.5)] for lbl
|
:save_last_frame: class SpawningAndFlowingArea(Scene): def construct(self): func = lambda pos: np.sin(pos[0]) * UR + np.cos(pos[1]) * LEFT + pos / 5 stream_lines = StreamLines( func, x_range=[-3, 3, 0.2], y_range=[-2, 2, 0.2], padding=1 ) spawning_area = Rectangle(width=6, height=4) flowing_area = Rectangle(width=8, height=6) labels = [Tex("Spawning Area"), Tex("Flowing Area").shift(DOWN * 2.5)] for lbl in labels: lbl.add_background_rectangle(opacity=0.6, buff=0.05) self.add(stream_lines, spawning_area, flowing_area, *labels) """ def __init__( self, func: Callable[[np.ndarray], np.ndarray], color: ParsableManimColor | None = None, color_scheme: Callable[[np.ndarray], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS, # Determining stream line starting positions: x_range: Sequence[float] = None, y_range: Sequence[float] = None, z_range: Sequence[float] = None, three_dimensions: bool = False, noise_factor: float | None = None, n_repeats=1, # Determining how lines are drawn dt=0.05, virtual_time=3, max_anchors_per_line=100, padding=3, # Determining stream line appearance: stroke_width=1, opacity=1, **kwargs, ): self.x_range = x_range or [ floor(-config["frame_width"] / 2), ceil(config["frame_width"] / 2), ] self.y_range = y_range or [ floor(-config["frame_height"] / 2), ceil(config["frame_height"] / 2), ] self.ranges = [self.x_range, self.y_range] if three_dimensions or z_range: self.z_range = z_range or self.y_range.copy() self.ranges += [self.z_range] else: self.ranges += [[0, 0]] for i in range(len(self.ranges)): if len(self.ranges[i]) == 2: self.ranges[i] += [0.5] self.ranges[i][1] += self.ranges[i][2] self.x_range, self.y_range, self.z_range = self.ranges super().__init__( func, color, color_scheme, min_color_scheme_value, max_color_scheme_value, colors, **kwargs, ) self.noise_factor = ( noise_factor if noise_factor is not None else self.y_range[2] / 2 ) self.n_repeats = n_repeats self.virtual_time = virtual_time self.max_anchors_per_line = max_anchors_per_line self.padding = padding self.stroke_width = stroke_width half_noise = self.noise_factor / 2 np.random.seed(0) start_points = np.array( [ (x - half_noise) * RIGHT + (y - half_noise) * UP + (z - half_noise) * OUT + self.noise_factor * np.random.random(3) for n in range(self.n_repeats) for x in np.arange(*self.x_range) for y in np.arange(*self.y_range) for z in np.arange(*self.z_range) ], ) def outside_box(p): return ( p[0] < self.x_range[0] - self.padding or p[0] > self.x_range[1] + self.padding - self.x_range[2] or p[1] < self.y_range[0] - self.padding or p[1] > self.y_range[1] + self.padding - self.y_range[2] or p[2] < self.z_range[0] - self.padding or p[2] > self.z_range[1] + self.padding - self.z_range[2] ) max_steps = ceil(virtual_time / dt) + 1 if not self.single_color: self.background_img = self.get_colored_background_image() if config["renderer"] == RendererType.OPENGL: self.values_to_rgbas = self.get_vectorized_rgba_gradient_function( min_color_scheme_value, max_color_scheme_value, colors, ) for point in start_points: points = [point] for _ in range(max_steps): last_point = points[-1] new_point = last_point + dt * func(last_point) if outside_box(new_point): break points.append(new_point) step = max_steps if not step: continue line = get_vectorized_mobject_class()() line.duration = step * dt step = max(1, int(len(points) / self.max_anchors_per_line)) line.set_points_smoothly(points[::step]) if self.single_color: line.set_stroke( color=self.color, width=self.stroke_width, opacity=opacity ) else: if config.renderer == RendererType.OPENGL: # scaled for compatibility with cairo line.set_stroke(width=self.stroke_width / 4.0) norms = np.array( [np.linalg.norm(self.func(point)) for point in line.points], ) line.set_rgba_array_direct( self.values_to_rgbas(norms, opacity), name="stroke_rgba", ) else: if np.any(self.z_range != np.array([0, 0.5, 0.5])): line.set_stroke( [self.pos_to_color(p) for p in line.get_anchors()], ) else: line.color_using_background_image(self.background_img) line.set_stroke(width=self.stroke_width, opacity=opacity) self.add(line) self.stream_lines = [*self.submobjects] def create( self, lag_ratio: float | None = None, run_time: Callable[[float], float] | None = None, **kwargs, ) -> AnimationGroup: """The creation animation of the stream lines. The stream lines appear in random order. Parameters ---------- lag_ratio
|
for p in line.get_anchors()], ) else: line.color_using_background_image(self.background_img) line.set_stroke(width=self.stroke_width, opacity=opacity) self.add(line) self.stream_lines = [*self.submobjects] def create( self, lag_ratio: float | None = None, run_time: Callable[[float], float] | None = None, **kwargs, ) -> AnimationGroup: """The creation animation of the stream lines. The stream lines appear in random order. Parameters ---------- lag_ratio The lag ratio of the animation. If undefined, it will be selected so that the total animation length is 1.5 times the run time of each stream line creation. run_time The run time of every single stream line creation. The runtime of the whole animation might be longer due to the `lag_ratio`. If undefined, the virtual time of the stream lines is used as run time. Returns ------- :class:`~.AnimationGroup` The creation animation of the stream lines. Examples -------- .. manim:: StreamLineCreation class StreamLineCreation(Scene): def construct(self): func = lambda pos: (pos[0] * UR + pos[1] * LEFT) - pos stream_lines = StreamLines( func, color=YELLOW, x_range=[-7, 7, 1], y_range=[-4, 4, 1], stroke_width=3, virtual_time=1, # use shorter lines max_anchors_per_line=5, # better performance with fewer anchors ) self.play(stream_lines.create()) # uses virtual_time as run_time self.wait() """ if run_time is None: run_time = self.virtual_time if lag_ratio is None: lag_ratio = run_time / 2 / len(self.submobjects) animations = [ Create(line, run_time=run_time, **kwargs) for line in self.stream_lines ] random.shuffle(animations) return AnimationGroup(*animations, lag_ratio=lag_ratio) def start_animation( self, warm_up: bool = True, flow_speed: float = 1, time_width: float = 0.3, rate_func: Callable[[float], float] = linear, line_animation_class: type[ShowPassingFlash] = ShowPassingFlash, **kwargs, ) -> None: """Animates the stream lines using an updater. The stream lines will continuously flow Parameters ---------- warm_up If `True` the animation is initialized line by line. Otherwise it starts with all lines shown. flow_speed At `flow_speed=1` the distance the flow moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of this flow. time_width The proportion of the stream line shown while being animated rate_func The rate function of each stream line flashing line_animation_class The animation class being used Examples -------- .. manim:: ContinuousMotion class ContinuousMotion(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT stream_lines = StreamLines(func, stroke_width=3, max_anchors_per_line=30) self.add(stream_lines) stream_lines.start_animation(warm_up=False, flow_speed=1.5) self.wait(stream_lines.virtual_time / stream_lines.flow_speed) """ for line in self.stream_lines: run_time = line.duration / flow_speed line.anim = line_animation_class( line, run_time=run_time, rate_func=rate_func, time_width=time_width, **kwargs, ) line.anim.begin() line.time = random.random() * self.virtual_time if warm_up: line.time *= -1 self.add(line.anim.mobject) def updater(mob, dt): for line in mob.stream_lines: line.time += dt * flow_speed if line.time >= self.virtual_time: line.time -= self.virtual_time line.anim.interpolate(np.clip(line.time / line.anim.run_time, 0, 1)) self.add_updater(updater) self.flow_animation = updater self.flow_speed = flow_speed self.time_width = time_width def end_animation(self) -> AnimationGroup: """End the stream line animation smoothly. Returns an animation resulting in fully displayed stream lines without a noticeable cut. Returns ------- :class:`~.AnimationGroup` The animation fading out the running stream animation. Raises ------ ValueError if no stream line animation is running Examples -------- .. manim:: EndAnimation class EndAnimation(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT stream_lines
|
without a noticeable cut. Returns ------- :class:`~.AnimationGroup` The animation fading out the running stream animation. Raises ------ ValueError if no stream line animation is running Examples -------- .. manim:: EndAnimation class EndAnimation(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT stream_lines = StreamLines( func, stroke_width=3, max_anchors_per_line=5, virtual_time=1, color=BLUE ) self.add(stream_lines) stream_lines.start_animation(warm_up=False, flow_speed=1.5, time_width=0.5) self.wait(1) self.play(stream_lines.end_animation()) """ if self.flow_animation is None: raise ValueError("You have to start the animation before fading it out.") def hide_and_wait(mob, alpha): if alpha == 0: mob.set_stroke(opacity=0) elif alpha == 1: mob.set_stroke(opacity=1) def finish_updater_cycle(line, alpha): line.time += dt * self.flow_speed line.anim.interpolate(min(line.time / line.anim.run_time, 1)) if alpha == 1: self.remove(line.anim.mobject) line.anim.finish() max_run_time = self.virtual_time / self.flow_speed creation_rate_func = ease_out_sine creation_staring_speed = creation_rate_func(0.001) * 1000 creation_run_time = ( max_run_time / (1 + self.time_width) * creation_staring_speed ) # creation_run_time is calculated so that the creation animation starts at the same speed # as the regular line flash animation but eases out. dt = 1 / config["frame_rate"] animations = [] self.remove_updater(self.flow_animation) self.flow_animation = None for line in self.stream_lines: create = Create( line, run_time=creation_run_time, rate_func=creation_rate_func, ) if line.time <= 0: animations.append( Succession( UpdateFromAlphaFunc( line, hide_and_wait, run_time=-line.time / self.flow_speed, ), create, ), ) self.remove(line.anim.mobject) line.anim.finish() else: remaining_time = max_run_time - line.time / self.flow_speed animations.append( Succession( UpdateFromAlphaFunc( line, finish_updater_cycle, run_time=remaining_time, ), create, ), ) return AnimationGroup(*animations) # TODO: Variant of StreamLines that is able to respond to changes in the vector field function ================================================ FILE: manim/mobject/geometry/__init__.py ================================================ """Various geometric Mobjects. Modules ======= .. autosummary:: :toctree: ../reference ~arc ~boolean_ops ~labeled ~line ~polygram ~shape_matchers ~tips """ ================================================ FILE: manim/mobject/geometry/arc.py ================================================ r"""Mobjects that are curved. Examples -------- .. manim:: UsefulAnnotations :save_last_frame: class UsefulAnnotations(Scene): def construct(self): m0 = Dot() m1 = AnnotationDot() m2 = LabeledDot("ii") m3 = LabeledDot(MathTex(r"\alpha").set_color(ORANGE)) m4 = CurvedArrow(2*LEFT, 2*RIGHT, radius= -5) m5 = CurvedArrow(2*LEFT, 2*RIGHT, radius= 8) m6 = CurvedDoubleArrow(ORIGIN, 2*RIGHT) self.add(m0, m1, m2, m3, m4, m5, m6) for i, mobj in enumerate(self.mobjects): mobj.shift(DOWN * (i-3)) """ from __future__ import annotations __all__ = [ "TipableVMobject", "Arc", "ArcBetweenPoints", "CurvedArrow", "CurvedDoubleArrow", "Circle", "Dot", "AnnotationDot", "LabeledDot", "Ellipse", "AnnularSector", "Sector", "Annulus", "CubicBezier", "ArcPolygon", "ArcPolygonFromArcs", ] import itertools import warnings from typing import TYPE_CHECKING, Any, cast import numpy as np from typing_extensions import Self from manim.constants import * from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.color import BLACK, BLUE, RED, WHITE, ParsableManimColor from manim.utils.iterables import adjacent_pairs from manim.utils.space_ops import ( angle_of_vector, cartesian_to_spherical, line_intersection, perpendicular_bisector, rotate_vector, ) if TYPE_CHECKING: from collections.abc import Iterable import manim.mobject.geometry.tips as tips from manim.mobject.mobject import Mobject from manim.mobject.text.tex_mobject import SingleStringMathTex, Tex from manim.mobject.text.text_mobject import Text from manim.typing import ( Point3D, Point3DLike, QuadraticSpline, Vector3DLike, ) class TipableVMobject(VMobject, metaclass=ConvertToOpenGL): """Meant for shared functionality between Arc and Line. Functionality can be classified broadly into these groups: * Adding, Creating, Modifying tips - add_tip calls create_tip, before pushing the new tip into the TipableVMobject's list of submobjects - stylistic and positional configuration * Checking for tips - Boolean checks for whether the TipableVMobject has a tip and a starting tip * Getters - Straightforward accessors, returning information pertaining to
|
Creating, Modifying tips - add_tip calls create_tip, before pushing the new tip into the TipableVMobject's list of submobjects - stylistic and positional configuration * Checking for tips - Boolean checks for whether the TipableVMobject has a tip and a starting tip * Getters - Straightforward accessors, returning information pertaining to the TipableVMobject instance's tip(s), its length etc """ def __init__( self, tip_length: float = DEFAULT_ARROW_TIP_LENGTH, normal_vector: Vector3DLike = OUT, tip_style: dict = {}, **kwargs: Any, ) -> None: self.tip_length: float = tip_length self.normal_vector = normal_vector self.tip_style: dict = tip_style super().__init__(**kwargs) # Adding, Creating, Modifying tips def add_tip( self, tip: tips.ArrowTip | None = None, tip_shape: type[tips.ArrowTip] | None = None, tip_length: float | None = None, tip_width: float | None = None, at_start: bool = False, ) -> Self: """Adds a tip to the TipableVMobject instance, recognising that the endpoints might need to be switched if it's a 'starting tip' or not. """ if tip is None: tip = self.create_tip(tip_shape, tip_length, tip_width, at_start) else: self.position_tip(tip, at_start) self.reset_endpoints_based_on_tip(tip, at_start) self.asign_tip_attr(tip, at_start) self.add(tip) return self def create_tip( self, tip_shape: type[tips.ArrowTip] | None = None, tip_length: float | None = None, tip_width: float | None = None, at_start: bool = False, ) -> tips.ArrowTip: """Stylises the tip, positions it spatially, and returns the newly instantiated tip to the caller. """ tip = self.get_unpositioned_tip(tip_shape, tip_length, tip_width) self.position_tip(tip, at_start) return tip def get_unpositioned_tip( self, tip_shape: type[tips.ArrowTip] | None = None, tip_length: float | None = None, tip_width: float | None = None, ) -> tips.ArrowTip | tips.ArrowTriangleFilledTip: """Returns a tip that has been stylistically configured, but has not yet been given a position in space. """ from manim.mobject.geometry.tips import ArrowTriangleFilledTip style: dict[str, Any] = {} if tip_shape is None: tip_shape = ArrowTriangleFilledTip if tip_shape is ArrowTriangleFilledTip: if tip_width is None: tip_width = self.get_default_tip_length() style.update({"width": tip_width}) if tip_length is None: tip_length = self.get_default_tip_length() color = self.get_color() style.update({"fill_color": color, "stroke_color": color}) style.update(self.tip_style) tip = tip_shape(length=tip_length, **style) return tip def position_tip(self, tip: tips.ArrowTip, at_start: bool = False) -> tips.ArrowTip: # Last two control points, defining both # the end, and the tangency direction if at_start: anchor = self.get_start() handle = self.get_first_handle() else: handle = self.get_last_handle() anchor = self.get_end() angles = cartesian_to_spherical((handle - anchor).tolist()) tip.rotate( angles[1] - PI - tip.tip_angle, ) # Rotates the tip along the azimuthal if not hasattr(self, "_init_positioning_axis"): axis = np.array( [ np.sin(angles[1]), -np.cos(angles[1]), 0, ] ) # Obtains the perpendicular of the tip tip.rotate( -angles[2] + PI / 2, axis=axis, ) # Rotates the tip along the vertical wrt the axis self._init_positioning_axis = axis tip.shift(anchor - tip.tip_point) return tip def reset_endpoints_based_on_tip(self, tip: tips.ArrowTip, at_start: bool) -> Self: if self.get_length() == 0: # Zero length, put_start_and_end_on wouldn't work return self if at_start: self.put_start_and_end_on(tip.base, self.get_end()) else: self.put_start_and_end_on(self.get_start(), tip.base) return self def asign_tip_attr(self, tip: tips.ArrowTip, at_start: bool) -> Self: if at_start: self.start_tip = tip else: self.tip = tip return self # Checking for tips def has_tip(self) -> bool: return hasattr(self, "tip") and self.tip in self def has_start_tip(self) -> bool: return hasattr(self, "start_tip") and self.start_tip in self #
|
self.put_start_and_end_on(self.get_start(), tip.base) return self def asign_tip_attr(self, tip: tips.ArrowTip, at_start: bool) -> Self: if at_start: self.start_tip = tip else: self.tip = tip return self # Checking for tips def has_tip(self) -> bool: return hasattr(self, "tip") and self.tip in self def has_start_tip(self) -> bool: return hasattr(self, "start_tip") and self.start_tip in self # Getters def pop_tips(self) -> VGroup: start, end = self.get_start_and_end() result = self.get_group_class()() if self.has_tip(): result.add(self.tip) self.remove(self.tip) if self.has_start_tip(): result.add(self.start_tip) self.remove(self.start_tip) self.put_start_and_end_on(start, end) return result def get_tips(self) -> VGroup: """Returns a VGroup (collection of VMobjects) containing the TipableVMObject instance's tips. """ result = self.get_group_class()() if hasattr(self, "tip"): result.add(self.tip) if hasattr(self, "start_tip"): result.add(self.start_tip) return result def get_tip(self) -> VMobject: """Returns the TipableVMobject instance's (first) tip, otherwise throws an exception. """ tips = self.get_tips() if len(tips) == 0: raise Exception("tip not found") else: tip: VMobject = tips[0] return tip def get_default_tip_length(self) -> float: return self.tip_length def get_first_handle(self) -> Point3D: # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 first_handle: Point3D = self.points[1] return first_handle def get_last_handle(self) -> Point3D: # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 last_handle: Point3D = self.points[-2] return last_handle def get_end(self) -> Point3D: if self.has_tip(): return self.tip.get_start() else: return super().get_end() def get_start(self) -> Point3D: if self.has_start_tip(): return self.start_tip.get_start() else: return super().get_start() def get_length(self) -> float: start, end = self.get_start_and_end() return float(np.linalg.norm(start - end)) class Arc(TipableVMobject): """A circular arc. Examples -------- A simple arc of angle Pi. .. manim:: ArcExample :save_last_frame: class ArcExample(Scene): def construct(self): self.add(Arc(angle=PI)) """ def __init__( self, radius: float | None = 1.0, start_angle: float = 0, angle: float = TAU / 4, num_components: int = 9, arc_center: Point3DLike = ORIGIN, **kwargs: Any, ): if radius is None: # apparently None is passed by ArcBetweenPoints radius = 1.0 self.radius = radius self.num_components = num_components self.arc_center: Point3D = np.asarray(arc_center) self.start_angle = start_angle self.angle = angle self._failed_to_get_center: bool = False super().__init__(**kwargs) def generate_points(self) -> None: self._set_pre_positioned_points() self.scale(self.radius, about_point=ORIGIN) self.shift(self.arc_center) # Points are set a bit differently when rendering via OpenGL. # TODO: refactor Arc so that only one strategy for setting points # has to be used. def init_points(self) -> None: self.set_points( Arc._create_quadratic_bezier_points( angle=self.angle, start_angle=self.start_angle, n_components=self.num_components, ), ) self.scale(self.radius, about_point=ORIGIN) self.shift(self.arc_center) @staticmethod def _create_quadratic_bezier_points( angle: float, start_angle: float = 0, n_components: int = 8 ) -> QuadraticSpline: samples = np.array( [ [np.cos(a), np.sin(a), 0] for a in np.linspace( start_angle, start_angle + angle, 2 * n_components + 1, ) ], ) theta = angle / n_components samples[1::2] /= np.cos(theta / 2) points = np.zeros((3 * n_components, 3)) points[0::3] = samples[0:-1:2] points[1::3] = samples[1::2] points[2::3] = samples[2::2] return points def _set_pre_positioned_points(self) -> None: anchors = np.array( [ np.cos(a) * RIGHT + np.sin(a) * UP for a in np.linspace( self.start_angle, self.start_angle + self.angle, self.num_components, ) ], ) # Figure out which control points will give the # Appropriate tangent lines to the circle d_theta = self.angle / (self.num_components - 1.0) tangent_vectors = np.zeros(anchors.shape) # Rotate all
|
np.array( [ np.cos(a) * RIGHT + np.sin(a) * UP for a in np.linspace( self.start_angle, self.start_angle + self.angle, self.num_components, ) ], ) # Figure out which control points will give the # Appropriate tangent lines to the circle d_theta = self.angle / (self.num_components - 1.0) tangent_vectors = np.zeros(anchors.shape) # Rotate all 90 degrees, via (x, y) -> (-y, x) tangent_vectors[:, 1] = anchors[:, 0] tangent_vectors[:, 0] = -anchors[:, 1] # Use tangent vectors to deduce anchors factor = 4 / 3 * np.tan(d_theta / 4) handles1 = anchors[:-1] + factor * tangent_vectors[:-1] handles2 = anchors[1:] - factor * tangent_vectors[1:] self.set_anchors_and_handles(anchors[:-1], handles1, handles2, anchors[1:]) def get_arc_center(self, warning: bool = True) -> Point3D: """Looks at the normals to the first two anchors, and finds their intersection points """ # First two anchors and handles a1, h1, h2, a2 = self.points[:4] if np.all(a1 == a2): # For a1 and a2 to lie at the same point arc radius # must be zero. Thus arc_center will also lie at # that point. return np.copy(a1) # Tangent vectors t1 = h1 - a1 t2 = h2 - a2 # Normals n1 = rotate_vector(t1, TAU / 4) n2 = rotate_vector(t2, TAU / 4) try: return line_intersection(line1=(a1, a1 + n1), line2=(a2, a2 + n2)) except Exception: if warning: warnings.warn( "Can't find Arc center, using ORIGIN instead", stacklevel=1 ) self._failed_to_get_center = True return np.array(ORIGIN) def move_arc_center_to(self, point: Point3DLike) -> Self: self.shift(point - self.get_arc_center()) return self def stop_angle(self) -> float: return cast( float, angle_of_vector(self.points[-1] - self.get_arc_center()) % TAU, ) class ArcBetweenPoints(Arc): """Inherits from Arc and additionally takes 2 points between which the arc is spanned. Example ------- .. manim:: ArcBetweenPointsExample class ArcBetweenPointsExample(Scene): def construct(self): circle = Circle(radius=2, stroke_color=GREY) dot_1 = Dot(color=GREEN).move_to([2, 0, 0]).scale(0.5) dot_1_text = Tex("(2,0)").scale(0.5).next_to(dot_1, RIGHT).set_color(BLUE) dot_2 = Dot(color=GREEN).move_to([0, 2, 0]).scale(0.5) dot_2_text = Tex("(0,2)").scale(0.5).next_to(dot_2, UP).set_color(BLUE) arc= ArcBetweenPoints(start=2 * RIGHT, end=2 * UP, stroke_color=YELLOW) self.add(circle, dot_1, dot_2, dot_1_text, dot_2_text) self.play(Create(arc)) """ def __init__( self, start: Point3DLike, end: Point3DLike, angle: float = TAU / 4, radius: float | None = None, **kwargs: Any, ) -> None: if radius is not None: self.radius = radius if radius < 0: sign = -2 radius *= -1 else: sign = 2 halfdist = np.linalg.norm(np.array(start) - np.array(end)) / 2 if radius < halfdist: raise ValueError( """ArcBetweenPoints called with a radius that is smaller than half the distance between the points.""", ) arc_height = radius - np.sqrt(radius**2 - halfdist**2) angle = np.arccos((radius - arc_height) / radius) * sign super().__init__(radius=radius, angle=angle, **kwargs) if angle == 0: self.set_points_as_corners(np.array([LEFT, RIGHT])) self.put_start_and_end_on(start, end) if radius is None: center = self.get_arc_center(warning=False) if not self._failed_to_get_center: # np.linalg.norm returns floating[Any] which is not compatible with float self.radius = cast( float, np.linalg.norm(np.array(start) - np.array(center)) ) else: self.radius = np.inf class CurvedArrow(ArcBetweenPoints): def __init__( self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any ) -> None: from manim.mobject.geometry.tips import ArrowTriangleFilledTip tip_shape = kwargs.pop("tip_shape", ArrowTriangleFilledTip) super().__init__(start_point, end_point, **kwargs) self.add_tip(tip_shape=tip_shape) class CurvedDoubleArrow(CurvedArrow): def __init__( self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any ) -> None: if "tip_shape_end" in kwargs: kwargs["tip_shape"] = kwargs.pop("tip_shape_end") from manim.mobject.geometry.tips import ArrowTriangleFilledTip tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip)
|
start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any ) -> None: from manim.mobject.geometry.tips import ArrowTriangleFilledTip tip_shape = kwargs.pop("tip_shape", ArrowTriangleFilledTip) super().__init__(start_point, end_point, **kwargs) self.add_tip(tip_shape=tip_shape) class CurvedDoubleArrow(CurvedArrow): def __init__( self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any ) -> None: if "tip_shape_end" in kwargs: kwargs["tip_shape"] = kwargs.pop("tip_shape_end") from manim.mobject.geometry.tips import ArrowTriangleFilledTip tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip) super().__init__(start_point, end_point, **kwargs) self.add_tip(at_start=True, tip_shape=tip_shape_start) class Circle(Arc): """A circle. Parameters ---------- color The color of the shape. kwargs Additional arguments to be passed to :class:`Arc` Examples -------- .. manim:: CircleExample :save_last_frame: class CircleExample(Scene): def construct(self): circle_1 = Circle(radius=1.0) circle_2 = Circle(radius=1.5, color=GREEN) circle_3 = Circle(radius=1.0, color=BLUE_B, fill_opacity=1) circle_group = Group(circle_1, circle_2, circle_3).arrange(buff=1) self.add(circle_group) """ def __init__( self, radius: float | None = None, color: ParsableManimColor = RED, **kwargs: Any, ) -> None: super().__init__( radius=radius, start_angle=0, angle=TAU, color=color, **kwargs, ) def surround( self, mobject: Mobject, dim_to_match: int = 0, stretch: bool = False, buffer_factor: float = 1.2, ) -> Self: """Modifies a circle so that it surrounds a given mobject. Parameters ---------- mobject The mobject that the circle will be surrounding. dim_to_match buffer_factor Scales the circle with respect to the mobject. A `buffer_factor` < 1 makes the circle smaller than the mobject. stretch Stretches the circle to fit more tightly around the mobject. Note: Does not work with :class:`Line` Examples -------- .. manim:: CircleSurround :save_last_frame: class CircleSurround(Scene): def construct(self): triangle1 = Triangle() circle1 = Circle().surround(triangle1) group1 = Group(triangle1,circle1) # treat the two mobjects as one line2 = Line() circle2 = Circle().surround(line2, buffer_factor=2.0) group2 = Group(line2,circle2) # buffer_factor < 1, so the circle is smaller than the square square3 = Square() circle3 = Circle().surround(square3, buffer_factor=0.5) group3 = Group(square3, circle3) group = Group(group1, group2, group3).arrange(buff=1) self.add(group) """ # Ignores dim_to_match and stretch; result will always be a circle # TODO: Perhaps create an ellipse class to handle single-dimension stretching # Something goes wrong here when surrounding lines? # TODO: Figure out and fix self.replace(mobject, dim_to_match, stretch) self.width = np.sqrt(mobject.width**2 + mobject.height**2) return self.scale(buffer_factor) def point_at_angle(self, angle: float) -> Point3D: """Returns the position of a point on the circle. Parameters ---------- angle The angle of the point along the circle in radians. Returns ------- :class:`numpy.ndarray` The location of the point along the circle's circumference. Examples -------- .. manim:: PointAtAngleExample :save_last_frame: class PointAtAngleExample(Scene): def construct(self): circle = Circle(radius=2.0) p1 = circle.point_at_angle(PI/2) p2 = circle.point_at_angle(270*DEGREES) s1 = Square(side_length=0.25).move_to(p1) s2 = Square(side_length=0.25).move_to(p2) self.add(circle, s1, s2) """ start_angle = angle_of_vector(self.points[0] - self.get_center()) proportion = (angle - start_angle) / TAU proportion -= np.floor(proportion) return self.point_from_proportion(proportion) @staticmethod def from_three_points( p1: Point3DLike, p2: Point3DLike, p3: Point3DLike, **kwargs: Any ) -> Circle: """Returns a circle passing through the specified three points. Example ------- .. manim:: CircleFromPointsExample :save_last_frame: class CircleFromPointsExample(Scene): def construct(self): circle = Circle.from_three_points(LEFT, LEFT + UP, UP * 2, color=RED) dots = VGroup( Dot(LEFT), Dot(LEFT + UP), Dot(UP * 2), ) self.add(NumberPlane(), circle, dots) """ center = line_intersection( perpendicular_bisector([np.asarray(p1), np.asarray(p2)]), perpendicular_bisector([np.asarray(p2), np.asarray(p3)]), ) # np.linalg.norm returns floating[Any] which is not compatible with float radius = cast(float, np.linalg.norm(p1 - center)) return Circle(radius=radius, **kwargs).shift(center) class Dot(Circle): """A circle with a very small radius.
|
= VGroup( Dot(LEFT), Dot(LEFT + UP), Dot(UP * 2), ) self.add(NumberPlane(), circle, dots) """ center = line_intersection( perpendicular_bisector([np.asarray(p1), np.asarray(p2)]), perpendicular_bisector([np.asarray(p2), np.asarray(p3)]), ) # np.linalg.norm returns floating[Any] which is not compatible with float radius = cast(float, np.linalg.norm(p1 - center)) return Circle(radius=radius, **kwargs).shift(center) class Dot(Circle): """A circle with a very small radius. Parameters ---------- point The location of the dot. radius The radius of the dot. stroke_width The thickness of the outline of the dot. fill_opacity The opacity of the dot's fill_colour color The color of the dot. kwargs Additional arguments to be passed to :class:`Circle` Examples -------- .. manim:: DotExample :save_last_frame: class DotExample(Scene): def construct(self): dot1 = Dot(point=LEFT, radius=0.08) dot2 = Dot(point=ORIGIN) dot3 = Dot(point=RIGHT) self.add(dot1,dot2,dot3) """ def __init__( self, point: Point3DLike = ORIGIN, radius: float = DEFAULT_DOT_RADIUS, stroke_width: float = 0, fill_opacity: float = 1.0, color: ParsableManimColor = WHITE, **kwargs: Any, ) -> None: super().__init__( arc_center=point, radius=radius, stroke_width=stroke_width, fill_opacity=fill_opacity, color=color, **kwargs, ) class AnnotationDot(Dot): """A dot with bigger radius and bold stroke to annotate scenes.""" def __init__( self, radius: float = DEFAULT_DOT_RADIUS * 1.3, stroke_width: float = 5, stroke_color: ParsableManimColor = WHITE, fill_color: ParsableManimColor = BLUE, **kwargs: Any, ) -> None: super().__init__( radius=radius, stroke_width=stroke_width, stroke_color=stroke_color, fill_color=fill_color, **kwargs, ) class LabeledDot(Dot): """A :class:`Dot` containing a label in its center. Parameters ---------- label The label of the :class:`Dot`. This is rendered as :class:`~.MathTex` by default (i.e., when passing a :class:`str`), but other classes representing rendered strings like :class:`~.Text` or :class:`~.Tex` can be passed as well. radius The radius of the :class:`Dot`. If ``None`` (the default), the radius is calculated based on the size of the ``label``. Examples -------- .. manim:: SeveralLabeledDots :save_last_frame: class SeveralLabeledDots(Scene): def construct(self): sq = Square(fill_color=RED, fill_opacity=1) self.add(sq) dot1 = LabeledDot(Tex("42", color=RED)) dot2 = LabeledDot(MathTex("a", color=GREEN)) dot3 = LabeledDot(Text("ii", color=BLUE)) dot4 = LabeledDot("3") dot1.next_to(sq, UL) dot2.next_to(sq, UR) dot3.next_to(sq, DL) dot4.next_to(sq, DR) self.add(dot1, dot2, dot3, dot4) """ def __init__( self, label: str | SingleStringMathTex | Text | Tex, radius: float | None = None, **kwargs: Any, ) -> None: if isinstance(label, str): from manim import MathTex rendered_label: VMobject = MathTex(label, color=BLACK) else: rendered_label = label if radius is None: radius = 0.1 + max(rendered_label.width, rendered_label.height) / 2 super().__init__(radius=radius, **kwargs) rendered_label.move_to(self.get_center()) self.add(rendered_label) class Ellipse(Circle): """A circular shape; oval, circle. Parameters ---------- width The horizontal width of the ellipse. height The vertical height of the ellipse. kwargs Additional arguments to be passed to :class:`Circle`. Examples -------- .. manim:: EllipseExample :save_last_frame: class EllipseExample(Scene): def construct(self): ellipse_1 = Ellipse(width=2.0, height=4.0, color=BLUE_B) ellipse_2 = Ellipse(width=4.0, height=1.0, color=BLUE_D) ellipse_group = Group(ellipse_1,ellipse_2).arrange(buff=1) self.add(ellipse_group) """ def __init__(self, width: float = 2, height: float = 1, **kwargs: Any) -> None: super().__init__(**kwargs) self.stretch_to_fit_width(width) self.stretch_to_fit_height(height) class AnnularSector(Arc): """A sector of an annulus. Parameters ---------- inner_radius The inside radius of the Annular Sector. outer_radius The outside radius of the Annular Sector. angle The clockwise angle of the Annular Sector. start_angle The starting clockwise angle of the Annular Sector. fill_opacity The opacity of the color filled in the Annular Sector. stroke_width The stroke width of the Annular Sector. color The color filled into
|
Sector. outer_radius The outside radius of the Annular Sector. angle The clockwise angle of the Annular Sector. start_angle The starting clockwise angle of the Annular Sector. fill_opacity The opacity of the color filled in the Annular Sector. stroke_width The stroke width of the Annular Sector. color The color filled into the Annular Sector. Examples -------- .. manim:: AnnularSectorExample :save_last_frame: class AnnularSectorExample(Scene): def construct(self): # Changes background color to clearly visualize changes in fill_opacity. self.camera.background_color = WHITE # The default parameter start_angle is 0, so the AnnularSector starts from the +x-axis. s1 = AnnularSector(color=YELLOW).move_to(2 * UL) # Different inner_radius and outer_radius than the default. s2 = AnnularSector(inner_radius=1.5, outer_radius=2, angle=45 * DEGREES, color=RED).move_to(2 * UR) # fill_opacity is typically a number > 0 and <= 1. If fill_opacity=0, the AnnularSector is transparent. s3 = AnnularSector(inner_radius=1, outer_radius=1.5, angle=PI, fill_opacity=0.25, color=BLUE).move_to(2 * DL) # With a negative value for the angle, the AnnularSector is drawn clockwise from the start value. s4 = AnnularSector(inner_radius=1, outer_radius=1.5, angle=-3 * PI / 2, color=GREEN).move_to(2 * DR) self.add(s1, s2, s3, s4) """ def __init__( self, inner_radius: float = 1, outer_radius: float = 2, angle: float = TAU / 4, start_angle: float = 0, fill_opacity: float = 1, stroke_width: float = 0, color: ParsableManimColor = WHITE, **kwargs: Any, ) -> None: self.inner_radius = inner_radius self.outer_radius = outer_radius super().__init__( start_angle=start_angle, angle=angle, fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs, ) def generate_points(self) -> None: inner_arc, outer_arc = ( Arc( start_angle=self.start_angle, angle=self.angle, radius=radius, arc_center=self.arc_center, ) for radius in (self.inner_radius, self.outer_radius) ) outer_arc.reverse_points() self.append_points(inner_arc.points) self.add_line_to(outer_arc.points[0]) self.append_points(outer_arc.points) self.add_line_to(inner_arc.points[0]) def init_points(self) -> None: self.generate_points() class Sector(AnnularSector): """A sector of a circle. Examples -------- .. manim:: ExampleSector :save_last_frame: class ExampleSector(Scene): def construct(self): sector = Sector(radius=2) sector2 = Sector(radius=2.5, angle=60*DEGREES).move_to([-3, 0, 0]) sector.set_color(RED) sector2.set_color(PINK) self.add(sector, sector2) """ def __init__(self, radius: float = 1, **kwargs: Any) -> None: super().__init__(inner_radius=0, outer_radius=radius, **kwargs) class Annulus(Circle): """Region between two concentric :class:`Circles <.Circle>`. Parameters ---------- inner_radius The radius of the inner :class:`Circle`. outer_radius The radius of the outer :class:`Circle`. kwargs Additional arguments to be passed to :class:`Annulus` Examples -------- .. manim:: AnnulusExample :save_last_frame: class AnnulusExample(Scene): def construct(self): annulus_1 = Annulus(inner_radius=0.5, outer_radius=1).shift(UP) annulus_2 = Annulus(inner_radius=0.3, outer_radius=0.6, color=RED).next_to(annulus_1, DOWN) self.add(annulus_1, annulus_2) """ def __init__( self, inner_radius: float = 1, outer_radius: float = 2, fill_opacity: float = 1, stroke_width: float = 0, color: ParsableManimColor = WHITE, mark_paths_closed: bool = False, **kwargs: Any, ) -> None: self.mark_paths_closed = mark_paths_closed # is this even used? self.inner_radius = inner_radius self.outer_radius = outer_radius super().__init__( fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs ) def generate_points(self) -> None: self.radius = self.outer_radius outer_circle = Circle(radius=self.outer_radius) inner_circle = Circle(radius=self.inner_radius) inner_circle.reverse_points() self.append_points(outer_circle.points) self.append_points(inner_circle.points) self.shift(self.arc_center) def init_points(self) -> None: self.generate_points() class CubicBezier(VMobject, metaclass=ConvertToOpenGL): """A cubic Bézier curve. Example ------- .. manim:: BezierSplineExample :save_last_frame: class BezierSplineExample(Scene): def construct(self): p1 = np.array([-3, 1, 0]) p1b = p1 + [1, 0, 0] d1 = Dot(point=p1).set_color(BLUE) l1 = Line(p1, p1b) p2 = np.array([3, -1, 0]) p2b = p2 - [1, 0, 0] d2 = Dot(point=p2).set_color(RED) l2 = Line(p2, p2b) bezier = CubicBezier(p1b, p1b + 3 * RIGHT, p2b - 3 * RIGHT, p2b) self.add(l1, d1, l2,
|
p1b = p1 + [1, 0, 0] d1 = Dot(point=p1).set_color(BLUE) l1 = Line(p1, p1b) p2 = np.array([3, -1, 0]) p2b = p2 - [1, 0, 0] d2 = Dot(point=p2).set_color(RED) l2 = Line(p2, p2b) bezier = CubicBezier(p1b, p1b + 3 * RIGHT, p2b - 3 * RIGHT, p2b) self.add(l1, d1, l2, d2, bezier) """ def __init__( self, start_anchor: Point3DLike, start_handle: Point3DLike, end_handle: Point3DLike, end_anchor: Point3DLike, **kwargs: Any, ) -> None: super().__init__(**kwargs) self.add_cubic_bezier_curve(start_anchor, start_handle, end_handle, end_anchor) class ArcPolygon(VMobject, metaclass=ConvertToOpenGL): """A generalized polygon allowing for points to be connected with arcs. This version tries to stick close to the way :class:`Polygon` is used. Points can be passed to it directly which are used to generate the according arcs (using :class:`ArcBetweenPoints`). An angle or radius can be passed to it to use across all arcs, but to configure arcs individually an ``arc_config`` list has to be passed with the syntax explained below. Parameters ---------- vertices A list of vertices, start and end points for the arc segments. angle The angle used for constructing the arcs. If no other parameters are set, this angle is used to construct all arcs. radius The circle radius used to construct the arcs. If specified, overrides the specified ``angle``. arc_config When passing a ``dict``, its content will be passed as keyword arguments to :class:`~.ArcBetweenPoints`. Otherwise, a list of dictionaries containing values that are passed as keyword arguments for every individual arc can be passed. kwargs Further keyword arguments that are passed to the constructor of :class:`~.VMobject`. Attributes ---------- arcs : :class:`list` The arcs created from the input parameters:: >>> from manim import ArcPolygon >>> ap = ArcPolygon([0, 0, 0], [2, 0, 0], [0, 2, 0]) >>> ap.arcs [ArcBetweenPoints, ArcBetweenPoints, ArcBetweenPoints] .. tip:: Two instances of :class:`ArcPolygon` can be transformed properly into one another as well. Be advised that any arc initialized with ``angle=0`` will actually be a straight line, so if a straight section should seamlessly transform into an arced section or vice versa, initialize the straight section with a negligible angle instead (such as ``angle=0.0001``). .. note:: There is an alternative version (:class:`ArcPolygonFromArcs`) that is instantiated with pre-defined arcs. See Also -------- :class:`ArcPolygonFromArcs` Examples -------- .. manim:: SeveralArcPolygons class SeveralArcPolygons(Scene): def construct(self): a = [0, 0, 0] b = [2, 0, 0] c = [0, 2, 0] ap1 = ArcPolygon(a, b, c, radius=2) ap2 = ArcPolygon(a, b, c, angle=45*DEGREES) ap3 = ArcPolygon(a, b, c, arc_config={'radius': 1.7, 'color': RED}) ap4 = ArcPolygon(a, b, c, color=RED, fill_opacity=1, arc_config=[{'radius': 1.7, 'color': RED}, {'angle': 20*DEGREES, 'color': BLUE}, {'radius': 1}]) ap_group = VGroup(ap1, ap2, ap3, ap4).arrange() self.play(*[Create(ap) for ap in [ap1, ap2, ap3, ap4]]) self.wait() For further examples see :class:`ArcPolygonFromArcs`. """ def __init__( self, *vertices: Point3DLike, angle: float = PI / 4, radius: float | None = None, arc_config: list[dict] | None = None, **kwargs: Any, ) -> None: n = len(vertices) point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)] if not arc_config: if radius: all_arc_configs: Iterable[dict] = itertools.repeat( {"radius": radius}, len(point_pairs) ) else: all_arc_configs = itertools.repeat({"angle": angle}, len(point_pairs))
|
float | None = None, arc_config: list[dict] | None = None, **kwargs: Any, ) -> None: n = len(vertices) point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)] if not arc_config: if radius: all_arc_configs: Iterable[dict] = itertools.repeat( {"radius": radius}, len(point_pairs) ) else: all_arc_configs = itertools.repeat({"angle": angle}, len(point_pairs)) elif isinstance(arc_config, dict): all_arc_configs = itertools.repeat(arc_config, len(point_pairs)) else: assert len(arc_config) == n all_arc_configs = arc_config arcs = [ ArcBetweenPoints(*pair, **conf) for (pair, conf) in zip(point_pairs, all_arc_configs) ] super().__init__(**kwargs) # Adding the arcs like this makes ArcPolygon double as a VGroup. # Also makes changes to the ArcPolygon, such as scaling, affect # the arcs, so that their new values are usable. self.add(*arcs) for arc in arcs: self.append_points(arc.points) # This enables the use of ArcPolygon.arcs as a convenience # because ArcPolygon[0] returns itself, not the first Arc. self.arcs = arcs class ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL): """A generalized polygon allowing for points to be connected with arcs. This version takes in pre-defined arcs to generate the arcpolygon and introduces little new syntax. However unlike :class:`Polygon` it can't be created with points directly. For proper appearance the passed arcs should connect seamlessly: ``[a,b][b,c][c,a]`` If there are any gaps between the arcs, those will be filled in with straight lines, which can be used deliberately for any straight sections. Arcs can also be passed as straight lines such as an arc initialized with ``angle=0``. Parameters ---------- arcs These are the arcs from which the arcpolygon is assembled. kwargs Keyword arguments that are passed to the constructor of :class:`~.VMobject`. Affects how the ArcPolygon itself is drawn, but doesn't affect passed arcs. Attributes ---------- arcs The arcs used to initialize the ArcPolygonFromArcs:: >>> from manim import ArcPolygonFromArcs, Arc, ArcBetweenPoints >>> ap = ArcPolygonFromArcs(Arc(), ArcBetweenPoints([1,0,0], [0,1,0]), Arc()) >>> ap.arcs [Arc, ArcBetweenPoints, Arc] .. tip:: Two instances of :class:`ArcPolygon` can be transformed properly into one another as well. Be advised that any arc initialized with ``angle=0`` will actually be a straight line, so if a straight section should seamlessly transform into an arced section or vice versa, initialize the straight section with a negligible angle instead (such as ``angle=0.0001``). .. note:: There is an alternative version (:class:`ArcPolygon`) that can be instantiated with points. .. seealso:: :class:`ArcPolygon` Examples -------- One example of an arcpolygon is the Reuleaux triangle. Instead of 3 straight lines connecting the outer points, a Reuleaux triangle has 3 arcs connecting those points, making a shape with constant width. Passed arcs are stored as submobjects in the arcpolygon. This means that the arcs are changed along with the arcpolygon, for example when it's shifted, and these arcs can be manipulated after the arcpolygon has been initialized. Also both the arcs contained in an :class:`~.ArcPolygonFromArcs`, as well as the arcpolygon itself are drawn, which affects draw time in :class:`~.Create` for example. In most cases the arcs themselves don't need to be drawn, in which case they can be passed as invisible. .. manim:: ArcPolygonExample class ArcPolygonExample(Scene): def construct(self): arc_conf = {"stroke_width": 0} poly_conf = {"stroke_width": 10, "stroke_color": BLUE, "fill_opacity":
|
arcpolygon itself are drawn, which affects draw time in :class:`~.Create` for example. In most cases the arcs themselves don't need to be drawn, in which case they can be passed as invisible. .. manim:: ArcPolygonExample class ArcPolygonExample(Scene): def construct(self): arc_conf = {"stroke_width": 0} poly_conf = {"stroke_width": 10, "stroke_color": BLUE, "fill_opacity": 1, "color": PURPLE} a = [-1, 0, 0] b = [1, 0, 0] c = [0, np.sqrt(3), 0] arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf) arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf) arc2 = ArcBetweenPoints(c, a, radius=2, **arc_conf) reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf) self.play(FadeIn(reuleaux_tri)) self.wait(2) The arcpolygon itself can also be hidden so that instead only the contained arcs are drawn. This can be used to easily debug arcs or to highlight them. .. manim:: ArcPolygonExample2 class ArcPolygonExample2(Scene): def construct(self): arc_conf = {"stroke_width": 3, "stroke_color": BLUE, "fill_opacity": 0.5, "color": GREEN} poly_conf = {"color": None} a = [-1, 0, 0] b = [1, 0, 0] c = [0, np.sqrt(3), 0] arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf) arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf) arc2 = ArcBetweenPoints(c, a, radius=2, stroke_color=RED) reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf) self.play(FadeIn(reuleaux_tri)) self.wait(2) """ def __init__(self, *arcs: Arc | ArcBetweenPoints, **kwargs: Any) -> None: if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs): raise ValueError( "All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints", ) super().__init__(**kwargs) # Adding the arcs like this makes ArcPolygonFromArcs double as a VGroup. # Also makes changes to the ArcPolygonFromArcs, such as scaling, affect # the arcs, so that their new values are usable. self.add(*arcs) # This enables the use of ArcPolygonFromArcs.arcs as a convenience # because ArcPolygonFromArcs[0] returns itself, not the first Arc. self.arcs = [*arcs] from .line import Line for arc1, arc2 in adjacent_pairs(arcs): self.append_points(arc1.points) line = Line(arc1.get_end(), arc2.get_start()) len_ratio = line.get_length() / arc1.get_arc_length() if np.isnan(len_ratio) or np.isinf(len_ratio): continue line.insert_n_curves(int(arc1.get_num_curves() * len_ratio)) self.append_points(line.points) ================================================ FILE: manim/mobject/geometry/boolean_ops.py ================================================ """Boolean operations for two-dimensional mobjects.""" from __future__ import annotations from typing import TYPE_CHECKING, Any import numpy as np from pathops import Path as SkiaPath from pathops import PathVerb, difference, intersection, union, xor from manim import config from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VMobject if TYPE_CHECKING: from manim.typing import Point2DLike_Array, Point3D_Array, Point3DLike_Array from ...constants import RendererType __all__ = ["Union", "Intersection", "Difference", "Exclusion"] class _BooleanOps(VMobject, metaclass=ConvertToOpenGL): """This class contains some helper functions which helps to convert to and from skia objects and manim objects (:class:`~.VMobject`). """ def _convert_2d_to_3d_array( self, points: Point2DLike_Array | Point3DLike_Array, z_dim: float = 0.0, ) -> Point3D_Array: """Converts an iterable with coordinates in 2D to 3D by adding :attr:`z_dim` as the Z coordinate. Parameters ---------- points An iterable of points. z_dim Default value for the Z coordinate. Returns ------- Point3D_Array A list of the points converted to 3D. Example ------- >>> a = _BooleanOps() >>> p = [(1, 2), (3, 4)] >>> a._convert_2d_to_3d_array(p) array([[1., 2., 0.], [3., 4., 0.]]) """ list_of_points = list(points) for i, point in enumerate(list_of_points): if len(point) == 2: list_of_points[i] = np.array(list(point) + [z_dim]) return np.asarray(list_of_points) def _convert_vmobject_to_skia_path(self, vmobject: VMobject) -> SkiaPath: """Converts a :class:`~.VMobject` to SkiaPath. This method only works
|
>>> p = [(1, 2), (3, 4)] >>> a._convert_2d_to_3d_array(p) array([[1., 2., 0.], [3., 4., 0.]]) """ list_of_points = list(points) for i, point in enumerate(list_of_points): if len(point) == 2: list_of_points[i] = np.array(list(point) + [z_dim]) return np.asarray(list_of_points) def _convert_vmobject_to_skia_path(self, vmobject: VMobject) -> SkiaPath: """Converts a :class:`~.VMobject` to SkiaPath. This method only works for cairo renderer because it treats the points as Cubic beizer curves. Parameters ---------- vmobject: The :class:`~.VMobject` to convert from. Returns ------- SkiaPath The converted path. """ path = SkiaPath() if not np.all(np.isfinite(vmobject.points)): points = np.zeros((1, 3)) # point invalid? else: points = vmobject.points if len(points) == 0: # what? No points so return empty path return path # In OpenGL it's quadratic beizer curves while on Cairo it's cubic... if config.renderer == RendererType.OPENGL: subpaths = vmobject.get_subpaths_from_points(points) for subpath in subpaths: quads = vmobject.get_bezier_tuples_from_points(subpath) start = subpath[0] path.moveTo(*start[:2]) for _p0, p1, p2 in quads: path.quadTo(*p1[:2], *p2[:2]) if vmobject.consider_points_equals(subpath[0], subpath[-1]): path.close() elif config.renderer == RendererType.CAIRO: subpaths = vmobject.gen_subpaths_from_points_2d(points) # type: ignore[assignment] for subpath in subpaths: quads = vmobject.gen_cubic_bezier_tuples_from_points(subpath) start = subpath[0] path.moveTo(*start[:2]) for _p0, p1, p2, p3 in quads: path.cubicTo(*p1[:2], *p2[:2], *p3[:2]) if vmobject.consider_points_equals_2d(subpath[0], subpath[-1]): path.close() return path def _convert_skia_path_to_vmobject(self, path: SkiaPath) -> VMobject: """Converts SkiaPath back to VMobject. Parameters ---------- path: The SkiaPath to convert. Returns ------- VMobject: The converted VMobject. """ vmobject = self current_path_start = np.array([0, 0, 0]) for path_verb, points in path: if path_verb == PathVerb.MOVE: parts = self._convert_2d_to_3d_array(points) for part in parts: current_path_start = part vmobject.start_new_path(part) # vmobject.move_to(*part) elif path_verb == PathVerb.CUBIC: n1, n2, n3 = self._convert_2d_to_3d_array(points) vmobject.add_cubic_bezier_curve_to(n1, n2, n3) elif path_verb == PathVerb.LINE: parts = self._convert_2d_to_3d_array(points) vmobject.add_line_to(parts[0]) elif path_verb == PathVerb.CLOSE: vmobject.add_line_to(current_path_start) elif path_verb == PathVerb.QUAD: n1, n2 = self._convert_2d_to_3d_array(points) vmobject.add_quadratic_bezier_curve_to(n1, n2) else: raise Exception(f"Unsupported: {path_verb}") return vmobject class Union(_BooleanOps): """Union of two or more :class:`~.VMobject` s. This returns the common region of the :class:`~VMobject` s. Parameters ---------- vmobjects The :class:`~.VMobject` s to find the union of. Raises ------ ValueError If less than 2 :class:`~.VMobject` s are passed. Example ------- .. manim:: UnionExample :save_last_frame: class UnionExample(Scene): def construct(self): sq = Square(color=RED, fill_opacity=1) sq.move_to([-2, 0, 0]) cr = Circle(color=BLUE, fill_opacity=1) cr.move_to([-1.3, 0.7, 0]) un = Union(sq, cr, color=GREEN, fill_opacity=1) un.move_to([1.5, 0.3, 0]) self.add(sq, cr, un) """ def __init__(self, *vmobjects: VMobject, **kwargs: Any) -> None: if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Union.") super().__init__(**kwargs) paths = [] for vmobject in vmobjects: paths.append(self._convert_vmobject_to_skia_path(vmobject)) outpen = SkiaPath() union(paths, outpen.getPen()) self._convert_skia_path_to_vmobject(outpen) class Difference(_BooleanOps): """Subtracts one :class:`~.VMobject` from another one. Parameters ---------- subject The 1st :class:`~.VMobject`. clip The 2nd :class:`~.VMobject` Example ------- .. manim:: DifferenceExample :save_last_frame: class DifferenceExample(Scene): def construct(self): sq = Square(color=RED, fill_opacity=1) sq.move_to([-2, 0, 0]) cr = Circle(color=BLUE, fill_opacity=1) cr.move_to([-1.3, 0.7, 0]) un = Difference(sq, cr, color=GREEN, fill_opacity=1) un.move_to([1.5, 0, 0]) self.add(sq, cr, un) """ def __init__(self, subject: VMobject, clip: VMobject, **kwargs: Any) -> None: super().__init__(**kwargs) outpen = SkiaPath() difference( [self._convert_vmobject_to_skia_path(subject)], [self._convert_vmobject_to_skia_path(clip)], outpen.getPen(), ) self._convert_skia_path_to_vmobject(outpen) class Intersection(_BooleanOps): """Find the intersection of two :class:`~.VMobject` s. This keeps the parts covered by both :class:`~.VMobject` s. Parameters ---------- vmobjects The :class:`~.VMobject` to find the intersection. Raises ------ ValueError
|
def __init__(self, subject: VMobject, clip: VMobject, **kwargs: Any) -> None: super().__init__(**kwargs) outpen = SkiaPath() difference( [self._convert_vmobject_to_skia_path(subject)], [self._convert_vmobject_to_skia_path(clip)], outpen.getPen(), ) self._convert_skia_path_to_vmobject(outpen) class Intersection(_BooleanOps): """Find the intersection of two :class:`~.VMobject` s. This keeps the parts covered by both :class:`~.VMobject` s. Parameters ---------- vmobjects The :class:`~.VMobject` to find the intersection. Raises ------ ValueError If less the 2 :class:`~.VMobject` are passed. Example ------- .. manim:: IntersectionExample :save_last_frame: class IntersectionExample(Scene): def construct(self): sq = Square(color=RED, fill_opacity=1) sq.move_to([-2, 0, 0]) cr = Circle(color=BLUE, fill_opacity=1) cr.move_to([-1.3, 0.7, 0]) un = Intersection(sq, cr, color=GREEN, fill_opacity=1) un.move_to([1.5, 0, 0]) self.add(sq, cr, un) """ def __init__(self, *vmobjects: VMobject, **kwargs: Any) -> None: if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Intersection.") super().__init__(**kwargs) outpen = SkiaPath() intersection( [self._convert_vmobject_to_skia_path(vmobjects[0])], [self._convert_vmobject_to_skia_path(vmobjects[1])], outpen.getPen(), ) new_outpen = outpen for _i in range(2, len(vmobjects)): new_outpen = SkiaPath() intersection( [outpen], [self._convert_vmobject_to_skia_path(vmobjects[_i])], new_outpen.getPen(), ) outpen = new_outpen self._convert_skia_path_to_vmobject(outpen) class Exclusion(_BooleanOps): """Find the XOR between two :class:`~.VMobject`. This creates a new :class:`~.VMobject` consisting of the region covered by exactly one of them. Parameters ---------- subject The 1st :class:`~.VMobject`. clip The 2nd :class:`~.VMobject` Example ------- .. manim:: IntersectionExample :save_last_frame: class IntersectionExample(Scene): def construct(self): sq = Square(color=RED, fill_opacity=1) sq.move_to([-2, 0, 0]) cr = Circle(color=BLUE, fill_opacity=1) cr.move_to([-1.3, 0.7, 0]) un = Exclusion(sq, cr, color=GREEN, fill_opacity=1) un.move_to([1.5, 0.4, 0]) self.add(sq, cr, un) """ def __init__(self, subject: VMobject, clip: VMobject, **kwargs: Any) -> None: super().__init__(**kwargs) outpen = SkiaPath() xor( [self._convert_vmobject_to_skia_path(subject)], [self._convert_vmobject_to_skia_path(clip)], outpen.getPen(), ) self._convert_skia_path_to_vmobject(outpen) ================================================ FILE: manim/mobject/geometry/labeled.py ================================================ r"""Mobjects that inherit from lines and contain a label along the length.""" from __future__ import annotations __all__ = ["Label", "LabeledLine", "LabeledArrow", "LabeledPolygram"] from typing import TYPE_CHECKING, Any import numpy as np from manim.constants import * from manim.mobject.geometry.line import Arrow, Line from manim.mobject.geometry.polygram import Polygram from manim.mobject.geometry.shape_matchers import ( BackgroundRectangle, SurroundingRectangle, ) from manim.mobject.text.tex_mobject import MathTex, Tex from manim.mobject.text.text_mobject import Text from manim.mobject.types.vectorized_mobject import VGroup from manim.utils.color import WHITE from manim.utils.polylabel import polylabel if TYPE_CHECKING: from manim.typing import Point3DLike_Array class Label(VGroup): """A Label consisting of text surrounded by a frame. Parameters ---------- label Label that will be displayed. label_config A dictionary containing the configuration for the label. This is only applied if ``label`` is of type ``str``. box_config A dictionary containing the configuration for the background box. frame_config A dictionary containing the configuration for the frame. Examples -------- .. manim:: LabelExample :save_last_frame: :quality: high class LabelExample(Scene): def construct(self): label = Label( label=Text('Label Text', font='sans-serif'), box_config = { "color" : BLUE, "fill_opacity" : 0.75 } ) label.scale(3) self.add(label) """ def __init__( self, label: str | Tex | MathTex | Text, label_config: dict[str, Any] | None = None, box_config: dict[str, Any] | None = None, frame_config: dict[str, Any] | None = None, **kwargs: Any, ) -> None: super().__init__(**kwargs) # Setup Defaults default_label_config: dict[str, Any] = { "color": WHITE, "font_size": DEFAULT_FONT_SIZE, } default_box_config: dict[str, Any] = { "color": None, "buff": 0.05, "fill_opacity": 1, "stroke_width": 0.5, } default_frame_config: dict[str, Any] = { "color": WHITE, "buff": 0.05, "stroke_width": 0.5, } # Merge Defaults label_config = default_label_config | (label_config or {}) box_config = default_box_config | (box_config or {}) frame_config =
|
"color": WHITE, "font_size": DEFAULT_FONT_SIZE, } default_box_config: dict[str, Any] = { "color": None, "buff": 0.05, "fill_opacity": 1, "stroke_width": 0.5, } default_frame_config: dict[str, Any] = { "color": WHITE, "buff": 0.05, "stroke_width": 0.5, } # Merge Defaults label_config = default_label_config | (label_config or {}) box_config = default_box_config | (box_config or {}) frame_config = default_frame_config | (frame_config or {}) # Determine the type of label and instantiate the appropriate object self.rendered_label: MathTex | Tex | Text if isinstance(label, str): self.rendered_label = MathTex(label, **label_config) elif isinstance(label, (MathTex, Tex, Text)): self.rendered_label = label else: raise TypeError("Unsupported label type. Must be MathTex, Tex, or Text.") # Add a background box self.background_rect = BackgroundRectangle(self.rendered_label, **box_config) # Add a frame around the label self.frame = SurroundingRectangle(self.rendered_label, **frame_config) # Add components to the VGroup self.add(self.background_rect, self.rendered_label, self.frame) class LabeledLine(Line): """Constructs a line containing a label box somewhere along its length. Parameters ---------- label Label that will be displayed on the line. label_position A ratio in the range [0-1] to indicate the position of the label with respect to the length of the line. Default value is 0.5. label_config A dictionary containing the configuration for the label. This is only applied if ``label`` is of type ``str``. box_config A dictionary containing the configuration for the background box. frame_config A dictionary containing the configuration for the frame. .. seealso:: :class:`LabeledArrow` Examples -------- .. manim:: LabeledLineExample :save_last_frame: :quality: high class LabeledLineExample(Scene): def construct(self): line = LabeledLine( label = '0.5', label_position = 0.8, label_config = { "font_size" : 20 }, start=LEFT+DOWN, end=RIGHT+UP) line.set_length(line.get_length() * 2) self.add(line) """ def __init__( self, label: str | Tex | MathTex | Text, label_position: float = 0.5, label_config: dict[str, Any] | None = None, box_config: dict[str, Any] | None = None, frame_config: dict[str, Any] | None = None, *args: Any, **kwargs: Any, ) -> None: super().__init__(*args, **kwargs) # Create Label self.label = Label( label=label, label_config=label_config, box_config=box_config, frame_config=frame_config, ) # Compute Label Position line_start, line_end = self.get_start_and_end() new_vec = (line_end - line_start) * label_position label_coords = line_start + new_vec self.label.move_to(label_coords) self.add(self.label) class LabeledArrow(LabeledLine, Arrow): """Constructs an arrow containing a label box somewhere along its length. This class inherits its label properties from `LabeledLine`, so the main parameters controlling it are the same. Parameters ---------- label Label that will be displayed on the Arrow. label_position A ratio in the range [0-1] to indicate the position of the label with respect to the length of the line. Default value is 0.5. label_config A dictionary containing the configuration for the label. This is only applied if ``label`` is of type ``str``. box_config A dictionary containing the configuration for the background box. frame_config A dictionary containing the configuration for the frame. .. seealso:: :class:`LabeledLine` Examples -------- .. manim:: LabeledArrowExample :save_last_frame: :quality: high class LabeledArrowExample(Scene): def construct(self): l_arrow = LabeledArrow("0.5", start=LEFT*3, end=RIGHT*3 + UP*2, label_position=0.5) self.add(l_arrow) """ def __init__( self, *args: Any, **kwargs: Any, ) -> None: super().__init__(*args, **kwargs) class LabeledPolygram(Polygram): """Constructs a polygram containing a label box at its pole of inaccessibility. Parameters ---------- vertex_groups Vertices passed to the :class:`~.Polygram` constructor. label Label that
|
def construct(self): l_arrow = LabeledArrow("0.5", start=LEFT*3, end=RIGHT*3 + UP*2, label_position=0.5) self.add(l_arrow) """ def __init__( self, *args: Any, **kwargs: Any, ) -> None: super().__init__(*args, **kwargs) class LabeledPolygram(Polygram): """Constructs a polygram containing a label box at its pole of inaccessibility. Parameters ---------- vertex_groups Vertices passed to the :class:`~.Polygram` constructor. label Label that will be displayed on the Polygram. precision The precision used by the PolyLabel algorithm. label_config A dictionary containing the configuration for the label. This is only applied if ``label`` is of type ``str``. box_config A dictionary containing the configuration for the background box. frame_config A dictionary containing the configuration for the frame. .. note:: The PolyLabel Algorithm expects each vertex group to form a closed ring. If the input is open, :class:`LabeledPolygram` will attempt to close it. This may cause the polygon to intersect itself leading to unexpected results. .. tip:: Make sure the precision corresponds to the scale of your inputs! For instance, if the bounding box of your polygon stretches from 0 to 10,000, a precision of 1.0 or 10.0 should be sufficient. Examples -------- .. manim:: LabeledPolygramExample :save_last_frame: :quality: high class LabeledPolygramExample(Scene): def construct(self): # Define Rings ring1 = [ [-3.8, -2.4, 0], [-2.4, -2.5, 0], [-1.3, -1.6, 0], [-0.2, -1.7, 0], [1.7, -2.5, 0], [2.9, -2.6, 0], [3.5, -1.5, 0], [4.9, -1.4, 0], [4.5, 0.2, 0], [4.7, 1.6, 0], [3.5, 2.4, 0], [1.1, 2.5, 0], [-0.1, 0.9, 0], [-1.2, 0.5, 0], [-1.6, 0.7, 0], [-1.4, 1.9, 0], [-2.6, 2.6, 0], [-4.4, 1.2, 0], [-4.9, -0.8, 0], [-3.8, -2.4, 0] ] ring2 = [ [0.2, -1.2, 0], [0.9, -1.2, 0], [1.4, -2.0, 0], [2.1, -1.6, 0], [2.2, -0.5, 0], [1.4, 0.0, 0], [0.4, -0.2, 0], [0.2, -1.2, 0] ] ring3 = [[-2.7, 1.4, 0], [-2.3, 1.7, 0], [-2.8, 1.9, 0], [-2.7, 1.4, 0]] # Create Polygons (for reference) p1 = Polygon(*ring1, fill_opacity=0.75) p2 = Polygon(*ring2, fill_color=BLACK, fill_opacity=1) p3 = Polygon(*ring3, fill_color=BLACK, fill_opacity=1) # Create Labeled Polygram polygram = LabeledPolygram( *[ring1, ring2, ring3], label=Text('Pole', font='sans-serif'), precision=0.01, ) # Display Circle (for reference) circle = Circle(radius=polygram.radius, color=WHITE).move_to(polygram.pole) self.add(p1, p2, p3) self.add(polygram) self.add(circle) .. manim:: LabeledCountryExample :save_last_frame: :quality: high import requests import json class LabeledCountryExample(Scene): def construct(self): # Fetch JSON data and process arcs data = requests.get('https://cdn.jsdelivr.net/npm/us-atlas@3/nation-10m.json').json() arcs, transform = data['arcs'], data['transform'] sarcs = [np.cumsum(arc, axis=0) * transform['scale'] + transform['translate'] for arc in arcs] ssarcs = sorted(sarcs, key=len, reverse=True)[:1] # Compute Bounding Box points = np.concatenate(ssarcs) mins, maxs = np.min(points, axis=0), np.max(points, axis=0) # Build Axes ax = Axes( x_range=[mins[0], maxs[0], maxs[0] - mins[0]], x_length=10, y_range=[mins[1], maxs[1], maxs[1] - mins[1]], y_length=7, tips=False ) # Adjust Coordinates array = [[ax.c2p(*point) for point in sarc] for sarc in ssarcs] # Add Polygram polygram = LabeledPolygram( *array, label=Text('USA', font='sans-serif'), precision=0.01, fill_color=BLUE, stroke_width=0, fill_opacity=0.75 ) # Display Circle (for reference) circle = Circle(radius=polygram.radius, color=WHITE).move_to(polygram.pole) self.add(ax) self.add(polygram) self.add(circle) """ def __init__( self, *vertex_groups: Point3DLike_Array, label: str | Tex | MathTex | Text, precision: float = 0.01, label_config: dict[str, Any] | None = None, box_config: dict[str, Any] | None = None, frame_config: dict[str, Any] | None
|
) # Display Circle (for reference) circle = Circle(radius=polygram.radius, color=WHITE).move_to(polygram.pole) self.add(ax) self.add(polygram) self.add(circle) """ def __init__( self, *vertex_groups: Point3DLike_Array, label: str | Tex | MathTex | Text, precision: float = 0.01, label_config: dict[str, Any] | None = None, box_config: dict[str, Any] | None = None, frame_config: dict[str, Any] | None = None, **kwargs: Any, ) -> None: # Initialize the Polygram with the vertex groups super().__init__(*vertex_groups, **kwargs) # Create Label self.label = Label( label=label, label_config=label_config, box_config=box_config, frame_config=frame_config, ) # Close Vertex Groups rings = [ group if np.array_equal(group[0], group[-1]) else list(group) + [group[0]] for group in vertex_groups ] # Compute the Pole of Inaccessibility cell = polylabel(rings, precision=precision) self.pole, self.radius = np.pad(cell.c, (0, 1), "constant"), cell.d # Position the label at the pole self.label.move_to(self.pole) self.add(self.label) ================================================ FILE: manim/mobject/geometry/line.py ================================================ r"""Mobjects that are lines or variations of them.""" from __future__ import annotations __all__ = [ "Line", "DashedLine", "TangentLine", "Elbow", "Arrow", "Vector", "DoubleArrow", "Angle", "RightAngle", ] from typing import TYPE_CHECKING, Any, Literal import numpy as np from manim import config from manim.constants import * from manim.mobject.geometry.arc import Arc, ArcBetweenPoints, Dot, TipableVMobject from manim.mobject.geometry.tips import ArrowTriangleFilledTip from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.types.vectorized_mobject import DashedVMobject, VGroup, VMobject from manim.utils.color import WHITE from manim.utils.space_ops import angle_of_vector, line_intersection, normalize if TYPE_CHECKING: from typing_extensions import Self, TypeAlias from manim.typing import Point3D, Point3DLike, Vector2DLike, Vector3D, Vector3DLike from manim.utils.color import ParsableManimColor from ..matrix import Matrix # Avoid circular import AngleQuadrant: TypeAlias = tuple[Literal[-1, 1], Literal[-1, 1]] r"""A tuple of 2 integers which can be either +1 or -1, allowing to select one of the 4 quadrants of the Cartesian plane. Let :math:`L_1,\ L_2` be two lines defined by start points :math:`S_1,\ S_2` and end points :math:`E_1,\ E_2`. We define the "positive direction" of :math:`L_1` as the direction from :math:`S_1` to :math:`E_1`, and its "negative direction" as the opposite one. We do the same with :math:`L_2`. If :math:`L_1` and :math:`L_2` intersect, they divide the plane into 4 quadrants. To pick one quadrant, choose the integers in this tuple in the following way: - If the 1st integer is +1, select one of the 2 quadrants towards the positive direction of :math:`L_1`, i.e. closest to `E_1`. Otherwise, if the 1st integer is -1, select one of the 2 quadrants towards the negative direction of :math:`L_1`, i.e. closest to `S_1`. - Similarly, the sign of the 2nd integer picks the positive or negative direction of :math:`L_2` and, thus, selects one of the 2 quadrants which are closest to :math:`E_2` or :math:`S_2` respectively. """ class Line(TipableVMobject): """A straight or curved line segment between two points or mobjects. Parameters ---------- start The starting point or Mobject of the line. end The ending point or Mobject of the line. buff The distance to shorten the line from both ends. path_arc If nonzero, the line will be curved into an arc with this angle (in radians). kwargs Additional arguments to be passed to :class:`TipableVMobject` Examples -------- .. manim:: LineExample :save_last_frame: class LineExample(Scene): def construct(self): line1 = Line(LEFT*2, RIGHT*2)
|
the line. buff The distance to shorten the line from both ends. path_arc If nonzero, the line will be curved into an arc with this angle (in radians). kwargs Additional arguments to be passed to :class:`TipableVMobject` Examples -------- .. manim:: LineExample :save_last_frame: class LineExample(Scene): def construct(self): line1 = Line(LEFT*2, RIGHT*2) line2 = Line(LEFT*2, RIGHT*2, buff=0.5) line3 = Line(LEFT*2, RIGHT*2, path_arc=PI/2) grp = VGroup(line1,line2,line3).arrange(DOWN, buff=2) self.add(grp) """ def __init__( self, start: Point3DLike | Mobject = LEFT, end: Point3DLike | Mobject = RIGHT, buff: float = 0, path_arc: float = 0, **kwargs: Any, ) -> None: self.dim = 3 self.buff = buff self.path_arc = path_arc self._set_start_and_end_attrs(start, end) super().__init__(**kwargs) def generate_points(self) -> None: self.set_points_by_ends( start=self.start, end=self.end, buff=self.buff, path_arc=self.path_arc, ) def set_points_by_ends( self, start: Point3DLike | Mobject, end: Point3DLike | Mobject, buff: float = 0, path_arc: float = 0, ) -> None: """Sets the points of the line based on its start and end points. Unlike :meth:`put_start_and_end_on`, this method respects `self.buff` and Mobject bounding boxes. Parameters ---------- start The start point or Mobject of the line. end The end point or Mobject of the line. buff The empty space between the start and end of the line, by default 0. path_arc The angle of a circle spanned by this arc, by default 0 which is a straight line. """ self._set_start_and_end_attrs(start, end) if path_arc: arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc) self.set_points(arc.points) else: self.set_points_as_corners(np.asarray([self.start, self.end])) self._account_for_buff(buff) def init_points(self) -> None: self.generate_points() def _account_for_buff(self, buff: float) -> None: if buff <= 0: return length = self.get_length() if self.path_arc == 0 else self.get_arc_length() if length < 2 * buff: return buff_proportion = buff / length self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion) def _set_start_and_end_attrs( self, start: Point3DLike | Mobject, end: Point3DLike | Mobject ) -> None: # If either start or end are Mobjects, this # gives their centers rough_start = self._pointify(start) rough_end = self._pointify(end) vect = normalize(rough_end - rough_start) # Now that we know the direction between them, # we can find the appropriate boundary point from # start and end, if they're mobjects self.start = self._pointify(start, vect) self.end = self._pointify(end, -vect) def _pointify( self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike | None = None, ) -> Point3D: """Transforms a mobject into its corresponding point. Does nothing if a point is passed. ``direction`` determines the location of the point along its bounding box in that direction. Parameters ---------- mob_or_point The mobject or point. direction The direction. """ if isinstance(mob_or_point, (Mobject, OpenGLMobject)): mob = mob_or_point if direction is None: return mob.get_center() else: return mob.get_boundary_point(direction) return np.array(mob_or_point) def set_path_arc(self, new_value: float) -> None: self.path_arc = new_value self.init_points() def put_start_and_end_on( self, start: Point3DLike, end: Point3DLike, ) -> Self: """Sets starts and end coordinates of a line. Examples -------- .. manim:: LineExample class LineExample(Scene): def construct(self): d = VGroup() for i in range(0,10): d.add(Dot()) d.arrange_in_grid(buff=1) self.add(d) l= Line(d[0], d[1]) self.add(l) self.wait() l.put_start_and_end_on(d[1].get_center(), d[2].get_center()) self.wait() l.put_start_and_end_on(d[4].get_center(), d[7].get_center()) self.wait() """ curr_start, curr_end = self.get_start_and_end() if np.all(curr_start == curr_end): # TODO, any problems with resetting # these attrs? self.start = np.asarray(start) self.end = np.asarray(end) self.generate_points() return super().put_start_and_end_on(start,
|
def construct(self): d = VGroup() for i in range(0,10): d.add(Dot()) d.arrange_in_grid(buff=1) self.add(d) l= Line(d[0], d[1]) self.add(l) self.wait() l.put_start_and_end_on(d[1].get_center(), d[2].get_center()) self.wait() l.put_start_and_end_on(d[4].get_center(), d[7].get_center()) self.wait() """ curr_start, curr_end = self.get_start_and_end() if np.all(curr_start == curr_end): # TODO, any problems with resetting # these attrs? self.start = np.asarray(start) self.end = np.asarray(end) self.generate_points() return super().put_start_and_end_on(start, end) def get_vector(self) -> Vector3D: return self.get_end() - self.get_start() def get_unit_vector(self) -> Vector3D: return normalize(self.get_vector()) def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_projection(self, point: Point3DLike) -> Point3D: """Returns the projection of a point onto a line. Parameters ---------- point The point to which the line is projected. """ start = self.get_start() end = self.get_end() unit_vect = normalize(end - start) return start + float(np.dot(point - start, unit_vect)) * unit_vect def get_slope(self) -> float: return float(np.tan(self.get_angle())) def set_angle(self, angle: float, about_point: Point3DLike | None = None) -> Self: if about_point is None: about_point = self.get_start() self.rotate( angle - self.get_angle(), about_point=about_point, ) return self def set_length(self, length: float) -> Self: scale_factor: float = length / self.get_length() return self.scale(scale_factor) class DashedLine(Line): """A dashed :class:`Line`. Parameters ---------- args Arguments to be passed to :class:`Line` dash_length The length of each individual dash of the line. dashed_ratio The ratio of dash space to empty space. Range of 0-1. kwargs Additional arguments to be passed to :class:`Line` .. seealso:: :class:`~.DashedVMobject` Examples -------- .. manim:: DashedLineExample :save_last_frame: class DashedLineExample(Scene): def construct(self): # dash_length increased dashed_1 = DashedLine(config.left_side, config.right_side, dash_length=2.0).shift(UP*2) # normal dashed_2 = DashedLine(config.left_side, config.right_side) # dashed_ratio decreased dashed_3 = DashedLine(config.left_side, config.right_side, dashed_ratio=0.1).shift(DOWN*2) self.add(dashed_1, dashed_2, dashed_3) """ def __init__( self, *args: Any, dash_length: float = DEFAULT_DASH_LENGTH, dashed_ratio: float = 0.5, **kwargs: Any, ) -> None: self.dash_length = dash_length self.dashed_ratio = dashed_ratio super().__init__(*args, **kwargs) dashes = DashedVMobject( self, num_dashes=self._calculate_num_dashes(), dashed_ratio=dashed_ratio, ) self.clear_points() self.add(*dashes) def _calculate_num_dashes(self) -> int: """Returns the number of dashes in the dashed line. Examples -------- :: >>> DashedLine()._calculate_num_dashes() 20 """ # Minimum number of dashes has to be 2 return max( 2, int(np.ceil((self.get_length() / self.dash_length) * self.dashed_ratio)), ) def get_start(self) -> Point3D: """Returns the start point of the line. Examples -------- :: >>> DashedLine().get_start() array([-1., 0., 0.]) """ if len(self.submobjects) > 0: return self.submobjects[0].get_start() else: return super().get_start() def get_end(self) -> Point3D: """Returns the end point of the line. Examples -------- :: >>> DashedLine().get_end() array([1., 0., 0.]) """ if len(self.submobjects) > 0: return self.submobjects[-1].get_end() else: return super().get_end() def get_first_handle(self) -> Point3D: """Returns the point of the first handle. Examples -------- :: >>> DashedLine().get_first_handle() array([-0.98333333, 0. , 0. ]) """ # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 first_handle: Point3D = self.submobjects[0].points[1] return first_handle def get_last_handle(self) -> Point3D: """Returns the point of the last handle. Examples -------- :: >>> DashedLine().get_last_handle() array([0.98333333, 0. , 0. ]) """ # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 last_handle: Point3D = self.submobjects[-1].points[2] return last_handle class TangentLine(Line): """Constructs a line tangent to a :class:`~.VMobject` at a specific point. Parameters ---------- vmob The VMobject on which the
|
""" # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 last_handle: Point3D = self.submobjects[-1].points[2] return last_handle class TangentLine(Line): """Constructs a line tangent to a :class:`~.VMobject` at a specific point. Parameters ---------- vmob The VMobject on which the tangent line is drawn. alpha How far along the shape that the line will be constructed. range: 0-1. length Length of the tangent line. d_alpha The ``dx`` value kwargs Additional arguments to be passed to :class:`Line` .. seealso:: :meth:`~.VMobject.point_from_proportion` Examples -------- .. manim:: TangentLineExample :save_last_frame: class TangentLineExample(Scene): def construct(self): circle = Circle(radius=2) line_1 = TangentLine(circle, alpha=0.0, length=4, color=BLUE_D) # right line_2 = TangentLine(circle, alpha=0.4, length=4, color=GREEN) # top left self.add(circle, line_1, line_2) """ def __init__( self, vmob: VMobject, alpha: float, length: float = 1, d_alpha: float = 1e-6, **kwargs: Any, ) -> None: self.length = length self.d_alpha = d_alpha da = self.d_alpha a1 = np.clip(alpha - da, 0, 1) a2 = np.clip(alpha + da, 0, 1) super().__init__( vmob.point_from_proportion(a1), vmob.point_from_proportion(a2), **kwargs ) self.scale(self.length / self.get_length()) class Elbow(VMobject, metaclass=ConvertToOpenGL): """Two lines that create a right angle about each other: L-shape. Parameters ---------- width The length of the elbow's sides. angle The rotation of the elbow. kwargs Additional arguments to be passed to :class:`~.VMobject` .. seealso:: :class:`RightAngle` Examples -------- .. manim:: ElbowExample :save_last_frame: class ElbowExample(Scene): def construct(self): elbow_1 = Elbow() elbow_2 = Elbow(width=2.0) elbow_3 = Elbow(width=2.0, angle=5*PI/4) elbow_group = Group(elbow_1, elbow_2, elbow_3).arrange(buff=1) self.add(elbow_group) """ def __init__(self, width: float = 0.2, angle: float = 0, **kwargs: Any) -> None: self.angle = angle super().__init__(**kwargs) self.set_points_as_corners(np.array([UP, UP + RIGHT, RIGHT])) self.scale_to_fit_width(width, about_point=ORIGIN) self.rotate(self.angle, about_point=ORIGIN) class Arrow(Line): """An arrow. Parameters ---------- args Arguments to be passed to :class:`Line`. stroke_width The thickness of the arrow. Influenced by :attr:`max_stroke_width_to_length_ratio`. buff The distance of the arrow from its start and end points. max_tip_length_to_length_ratio :attr:`tip_length` scales with the length of the arrow. Increasing this ratio raises the max value of :attr:`tip_length`. max_stroke_width_to_length_ratio :attr:`stroke_width` scales with the length of the arrow. Increasing this ratio ratios the max value of :attr:`stroke_width`. kwargs Additional arguments to be passed to :class:`Line`. .. seealso:: :class:`ArrowTip` :class:`CurvedArrow` Examples -------- .. manim:: ArrowExample :save_last_frame: from manim.mobject.geometry.tips import ArrowSquareTip class ArrowExample(Scene): def construct(self): arrow_1 = Arrow(start=RIGHT, end=LEFT, color=GOLD) arrow_2 = Arrow(start=RIGHT, end=LEFT, color=GOLD, tip_shape=ArrowSquareTip).shift(DOWN) g1 = Group(arrow_1, arrow_2) # the effect of buff square = Square(color=MAROON_A) arrow_3 = Arrow(start=LEFT, end=RIGHT) arrow_4 = Arrow(start=LEFT, end=RIGHT, buff=0).next_to(arrow_1, UP) g2 = Group(arrow_3, arrow_4, square) # a shorter arrow has a shorter tip and smaller stroke width arrow_5 = Arrow(start=ORIGIN, end=config.top).shift(LEFT * 4) arrow_6 = Arrow(start=config.top + DOWN, end=config.top).shift(LEFT * 3) g3 = Group(arrow_5, arrow_6) self.add(Group(g1, g2, g3).arrange(buff=2)) .. manim:: ArrowExample :save_last_frame: class ArrowExample(Scene): def construct(self): left_group = VGroup() # As buff increases, the size of the arrow decreases. for buff in np.arange(0, 2.2, 0.45): left_group += Arrow(buff=buff, start=2 * LEFT, end=2 * RIGHT) # Required to arrange arrows. left_group.arrange(DOWN) left_group.move_to(4 * LEFT) middle_group = VGroup() # As max_stroke_width_to_length_ratio gets bigger, # the width of stroke increases. for i in np.arange(0, 5, 0.5):
|
the size of the arrow decreases. for buff in np.arange(0, 2.2, 0.45): left_group += Arrow(buff=buff, start=2 * LEFT, end=2 * RIGHT) # Required to arrange arrows. left_group.arrange(DOWN) left_group.move_to(4 * LEFT) middle_group = VGroup() # As max_stroke_width_to_length_ratio gets bigger, # the width of stroke increases. for i in np.arange(0, 5, 0.5): middle_group += Arrow(max_stroke_width_to_length_ratio=i) middle_group.arrange(DOWN) UR_group = VGroup() # As max_tip_length_to_length_ratio increases, # the length of the tip increases. for i in np.arange(0, 0.3, 0.1): UR_group += Arrow(max_tip_length_to_length_ratio=i) UR_group.arrange(DOWN) UR_group.move_to(4 * RIGHT + 2 * UP) DR_group = VGroup() DR_group += Arrow(start=LEFT, end=RIGHT, color=BLUE, tip_shape=ArrowSquareTip) DR_group += Arrow(start=LEFT, end=RIGHT, color=BLUE, tip_shape=ArrowSquareFilledTip) DR_group += Arrow(start=LEFT, end=RIGHT, color=YELLOW, tip_shape=ArrowCircleTip) DR_group += Arrow(start=LEFT, end=RIGHT, color=YELLOW, tip_shape=ArrowCircleFilledTip) DR_group.arrange(DOWN) DR_group.move_to(4 * RIGHT + 2 * DOWN) self.add(left_group, middle_group, UR_group, DR_group) """ def __init__( self, *args: Any, stroke_width: float = 6, buff: float = MED_SMALL_BUFF, max_tip_length_to_length_ratio: float = 0.25, max_stroke_width_to_length_ratio: float = 5, **kwargs: Any, ) -> None: self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_stroke_width_to_length_ratio = max_stroke_width_to_length_ratio tip_shape = kwargs.pop("tip_shape", ArrowTriangleFilledTip) super().__init__(*args, buff=buff, stroke_width=stroke_width, **kwargs) # type: ignore[misc] # TODO, should this be affected when # Arrow.set_stroke is called? self.initial_stroke_width = self.stroke_width self.add_tip(tip_shape=tip_shape) self._set_stroke_width_from_length() def scale(self, factor: float, scale_tips: bool = False, **kwargs: Any) -> Self: # type: ignore[override] r"""Scale an arrow, but keep stroke width and arrow tip size fixed. .. seealso:: :meth:`~.Mobject.scale` Examples -------- :: >>> arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0) >>> scaled_arrow = arrow.scale(2) >>> np.round(scaled_arrow.get_start_and_end(), 8) + 0 array([[-2., -2., 0.], [ 2., 2., 0.]]) >>> arrow.tip.length == scaled_arrow.tip.length True Manually scaling the object using the default method :meth:`~.Mobject.scale` does not have the same properties:: >>> new_arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0) >>> another_scaled_arrow = VMobject.scale(new_arrow, 2) >>> another_scaled_arrow.tip.length == arrow.tip.length False """ if self.get_length() == 0: return self if scale_tips: super().scale(factor, **kwargs) self._set_stroke_width_from_length() return self has_tip = self.has_tip() has_start_tip = self.has_start_tip() if has_tip or has_start_tip: old_tips = self.pop_tips() super().scale(factor, **kwargs) self._set_stroke_width_from_length() if has_tip: self.add_tip(tip=old_tips[0]) if has_start_tip: self.add_tip(tip=old_tips[1], at_start=True) return self def get_normal_vector(self) -> Vector3D: """Returns the normal of a vector. Examples -------- :: >>> np.round(Arrow().get_normal_vector()) + 0. # add 0. to avoid negative 0 in output array([ 0., 0., -1.]) """ p0, p1, p2 = self.tip.get_start_anchors()[:3] return normalize(np.cross(p2 - p1, p1 - p0)) def reset_normal_vector(self) -> Self: """Resets the normal of a vector""" self.normal_vector = self.get_normal_vector() return self def get_default_tip_length(self) -> float: """Returns the default tip_length of the arrow. Examples -------- :: >>> Arrow().get_default_tip_length() 0.35 """ max_ratio = self.max_tip_length_to_length_ratio return min(self.tip_length, max_ratio * self.get_length()) def _set_stroke_width_from_length(self) -> Self: """Sets stroke width based on length.""" max_ratio = self.max_stroke_width_to_length_ratio if config.renderer == RendererType.OPENGL: # Mypy does not recognize that the self object in this case # is a OpenGLVMobject and that the set_stroke method is # defined here: # mobject/opengl/opengl_vectorized_mobject.py#L248 self.set_stroke( # type: ignore[call-arg] width=min(self.initial_stroke_width, max_ratio * self.get_length()), recurse=False, ) else: self.set_stroke( width=min(self.initial_stroke_width, max_ratio * self.get_length()), family=False, ) return self class Vector(Arrow): """A vector specialized for use in graphs. .. caution:: Do not confuse with the :class:`~.Vector2D`, :class:`~.Vector3D` or :class:`~.VectorND` type aliases, which are not Mobjects! Parameters ---------- direction The
|
self.set_stroke( # type: ignore[call-arg] width=min(self.initial_stroke_width, max_ratio * self.get_length()), recurse=False, ) else: self.set_stroke( width=min(self.initial_stroke_width, max_ratio * self.get_length()), family=False, ) return self class Vector(Arrow): """A vector specialized for use in graphs. .. caution:: Do not confuse with the :class:`~.Vector2D`, :class:`~.Vector3D` or :class:`~.VectorND` type aliases, which are not Mobjects! Parameters ---------- direction The direction of the arrow. buff The distance of the vector from its endpoints. kwargs Additional arguments to be passed to :class:`Arrow` Examples -------- .. manim:: VectorExample :save_last_frame: class VectorExample(Scene): def construct(self): plane = NumberPlane() vector_1 = Vector([1,2]) vector_2 = Vector([-5,-2]) self.add(plane, vector_1, vector_2) """ def __init__( self, direction: Vector2DLike | Vector3DLike = RIGHT, buff: float = 0, **kwargs: Any, ) -> None: self.buff = buff if len(direction) == 2: direction = np.hstack([direction, 0]) super().__init__(ORIGIN, direction, buff=buff, **kwargs) def coordinate_label( self, integer_labels: bool = True, n_dim: int = 2, color: ParsableManimColor | None = None, **kwargs: Any, ) -> Matrix: """Creates a label based on the coordinates of the vector. Parameters ---------- integer_labels Whether or not to round the coordinates to integers. n_dim The number of dimensions of the vector. color Sets the color of label, optional. kwargs Additional arguments to be passed to :class:`~.Matrix`. Returns ------- :class:`~.Matrix` The label. Examples -------- .. manim:: VectorCoordinateLabel :save_last_frame: class VectorCoordinateLabel(Scene): def construct(self): plane = NumberPlane() vec_1 = Vector([1, 2]) vec_2 = Vector([-3, -2]) label_1 = vec_1.coordinate_label() label_2 = vec_2.coordinate_label(color=YELLOW) self.add(plane, vec_1, vec_2, label_1, label_2) """ # avoiding circular imports from ..matrix import Matrix vect = np.array(self.get_end()) if integer_labels: vect = np.round(vect).astype(int) vect = vect[:n_dim] vect = vect.reshape((n_dim, 1)) label = Matrix(vect, **kwargs) label.scale(LARGE_BUFF - 0.2) shift_dir = np.array(self.get_end()) if shift_dir[0] >= 0: # Pointing right shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT else: # Pointing left shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT label.shift(shift_dir) if color is not None: label.set_color(color) return label class DoubleArrow(Arrow): """An arrow with tips on both ends. Parameters ---------- args Arguments to be passed to :class:`Arrow` kwargs Additional arguments to be passed to :class:`Arrow` .. seealso:: :class:`.~ArrowTip` :class:`.~CurvedDoubleArrow` Examples -------- .. manim:: DoubleArrowExample :save_last_frame: from manim.mobject.geometry.tips import ArrowCircleFilledTip class DoubleArrowExample(Scene): def construct(self): circle = Circle(radius=2.0) d_arrow = DoubleArrow(start=circle.get_left(), end=circle.get_right()) d_arrow_2 = DoubleArrow(tip_shape_end=ArrowCircleFilledTip, tip_shape_start=ArrowCircleFilledTip) group = Group(Group(circle, d_arrow), d_arrow_2).arrange(UP, buff=1) self.add(group) .. manim:: DoubleArrowExample2 :save_last_frame: class DoubleArrowExample2(Scene): def construct(self): box = Square() p1 = box.get_left() p2 = box.get_right() d1 = DoubleArrow(p1, p2, buff=0) d2 = DoubleArrow(p1, p2, buff=0, tip_length=0.2, color=YELLOW) d3 = DoubleArrow(p1, p2, buff=0, tip_length=0.4, color=BLUE) Group(d1, d2, d3).arrange(DOWN) self.add(box, d1, d2, d3) """ def __init__(self, *args: Any, **kwargs: Any) -> None: if "tip_shape_end" in kwargs: kwargs["tip_shape"] = kwargs.pop("tip_shape_end") tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip) super().__init__(*args, **kwargs) self.add_tip(at_start=True, tip_shape=tip_shape_start) class Angle(VMobject, metaclass=ConvertToOpenGL): """A circular arc or elbow-type mobject representing an angle of two lines. Parameters ---------- line1 : The first line. line2 : The second line. radius : The radius of the :class:`Arc`. quadrant A sequence of two :class:`int` numbers determining which of the 4 quadrants should be used. The first value indicates whether to anchor the arc on the first line closer to the end point (1) or start point
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.