file_path
stringlengths
19
57
content
stringlengths
0
77.2k
manim_3b1b/README.md
<p align="center"> <a href="https://github.com/3b1b/manim"> <img src="https://raw.githubusercontent.com/3b1b/manim/master/logo/cropped.png"> </a> </p> [![pypi version](https://img.shields.io/pypi/v/manimgl?logo=pypi)](https://pypi.org/project/manimgl/) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://choosealicense.com/licenses/mit/) [![Manim Subreddit](https://img.shields.io/reddit/subreddit-subscribers/manim.svg?color=ff4301&label=reddit&logo=reddit)](https://www.reddit.com/r/manim/) [![Manim Discord](https://img.shields.io/discord/581738731934056449.svg?label=discord&logo=discord)](https://discord.com/invite/bYCyhM9Kz2) [![docs](https://github.com/3b1b/manim/workflows/docs/badge.svg)](https://3b1b.github.io/manim/) Manim is an engine for precise programmatic animations, designed for creating explanatory math videos. Note, there are two versions of manim. This repository began as a personal project by the author of [3Blue1Brown](https://www.3blue1brown.com/) for the purpose of animating those videos, with video-specific code available [here](https://github.com/3b1b/videos). In 2020 a group of developers forked it into what is now the [community edition](https://github.com/ManimCommunity/manim/), with a goal of being more stable, better tested, quicker to respond to community contributions, and all around friendlier to get started with. See [this page](https://docs.manim.community/en/stable/faq/installation.html#different-versions) for more details. ## Installation > **WARNING:** These instructions are for ManimGL _only_. Trying to use these instructions to install [ManimCommunity/manim](https://github.com/ManimCommunity/manim) or instructions there to install this version will cause problems. You should first decide which version you wish to install, then only follow the instructions for your desired version. > > **Note**: To install manim directly through pip, please pay attention to the name of the installed package. This repository is ManimGL of 3b1b. The package name is `manimgl` instead of `manim` or `manimlib`. Please use `pip install manimgl` to install the version in this repository. Manim runs on Python 3.7 or higher. System requirements are [FFmpeg](https://ffmpeg.org/), [OpenGL](https://www.opengl.org/) and [LaTeX](https://www.latex-project.org) (optional, if you want to use LaTeX). For Linux, [Pango](https://pango.gnome.org) along with its development headers are required. See instruction [here](https://github.com/ManimCommunity/ManimPango#building). ### Directly ```sh # Install manimgl pip install manimgl # Try it out manimgl ``` For more options, take a look at the [Using manim](#using-manim) sections further below. If you want to hack on manimlib itself, clone this repository and in that directory execute: ```sh # Install manimgl pip install -e . # Try it out manimgl example_scenes.py OpeningManimExample # or manim-render example_scenes.py OpeningManimExample ``` ### Directly (Windows) 1. [Install FFmpeg](https://www.wikihow.com/Install-FFmpeg-on-Windows). 2. Install a LaTeX distribution. [MiKTeX](https://miktex.org/download) is recommended. 3. Install the remaining Python packages. ```sh git clone https://github.com/3b1b/manim.git cd manim pip install -e . manimgl example_scenes.py OpeningManimExample ``` ### Mac OSX 1. Install FFmpeg, LaTeX in terminal using homebrew. ```sh brew install ffmpeg mactex ``` 2. Install latest version of manim using these command. ```sh git clone https://github.com/3b1b/manim.git cd manim pip install -e . manimgl example_scenes.py OpeningManimExample ``` ## Anaconda Install 1. Install LaTeX as above. 2. Create a conda environment using `conda create -n manim python=3.8`. 3. Activate the environment using `conda activate manim`. 4. Install manimgl using `pip install -e .`. ## Using manim Try running the following: ```sh manimgl example_scenes.py OpeningManimExample ``` This should pop up a window playing a simple scene. Some useful flags include: * `-w` to write the scene to a file * `-o` to write the scene to a file and open the result * `-s` to skip to the end and just show the final frame. * `-so` will save the final frame to an image and show it * `-n <number>` to skip ahead to the `n`'th animation of a scene. * `-f` to make the playback window fullscreen Take a look at custom_config.yml for further configuration. To add your customization, you can either edit this file, or add another file by the same name "custom_config.yml" to whatever directory you are running manim from. For example [this is the one](https://github.com/3b1b/videos/blob/master/custom_config.yml) for 3blue1brown videos. There you can specify where videos should be output to, where manim should look for image files and sounds you want to read in, and other defaults regarding style and video quality. Look through the [example scenes](https://3b1b.github.io/manim/getting_started/example_scenes.html) to get a sense of how it is used, and feel free to look through the code behind [3blue1brown videos](https://github.com/3b1b/videos) for a much larger set of example. Note, however, that developments are often made to the library without considering backwards compatibility with those old videos. To run an old project with a guarantee that it will work, you will have to go back to the commit which completed that project. ### Documentation Documentation is in progress at [3b1b.github.io/manim](https://3b1b.github.io/manim/). And there is also a Chinese version maintained by [**@manim-kindergarten**](https://manim.org.cn): [docs.manim.org.cn](https://docs.manim.org.cn/) (in Chinese). [manim-kindergarten](https://github.com/manim-kindergarten/) wrote and collected some useful extra classes and some codes of videos in [manim_sandbox repo](https://github.com/manim-kindergarten/manim_sandbox). ## Contributing Is always welcome. As mentioned above, the [community edition](https://github.com/ManimCommunity/manim) has the most active ecosystem for contributions, with testing and continuous integration, but pull requests are welcome here too. Please explain the motivation for a given change and examples of its effect. ## License This project falls under the MIT license.
manim_3b1b/LICENSE.md
MIT License Copyright (c) 2020-2023 3Blue1Brown LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
manim_3b1b/setup.py
import setuptools setuptools.setup()
manim_3b1b/example_scenes.py
from manimlib import * import numpy as np # To watch one of these scenes, run the following: # manimgl example_scenes.py OpeningManimExample # Use -s to skip to the end and just save the final frame # Use -w to write the animation to a file # Use -o to write it to a file and open it once done # Use -n <number> to skip ahead to the n'th animation of a scene. class OpeningManimExample(Scene): def construct(self): intro_words = Text(""" The original motivation for manim was to better illustrate mathematical functions as transformations. """) intro_words.to_edge(UP) self.play(Write(intro_words)) self.wait(2) # Linear transform grid = NumberPlane((-10, 10), (-5, 5)) matrix = [[1, 1], [0, 1]] linear_transform_words = VGroup( Text("This is what the matrix"), IntegerMatrix(matrix, include_background_rectangle=True), Text("looks like") ) linear_transform_words.arrange(RIGHT) linear_transform_words.to_edge(UP) linear_transform_words.set_backstroke(width=5) self.play( ShowCreation(grid), FadeTransform(intro_words, linear_transform_words) ) self.wait() self.play(grid.animate.apply_matrix(matrix), run_time=3) self.wait() # Complex map c_grid = ComplexPlane() moving_c_grid = c_grid.copy() moving_c_grid.prepare_for_nonlinear_transform() c_grid.set_stroke(BLUE_E, 1) c_grid.add_coordinate_labels(font_size=24) complex_map_words = TexText(""" Or thinking of the plane as $\\mathds{C}$,\\\\ this is the map $z \\rightarrow z^2$ """) complex_map_words.to_corner(UR) complex_map_words.set_backstroke(width=5) self.play( FadeOut(grid), Write(c_grid, run_time=3), FadeIn(moving_c_grid), FadeTransform(linear_transform_words, complex_map_words), ) self.wait() self.play( moving_c_grid.animate.apply_complex_function(lambda z: z**2), run_time=6, ) self.wait(2) class AnimatingMethods(Scene): def construct(self): grid = Tex(R"\pi").get_grid(10, 10, height=4) self.add(grid) # You can animate the application of mobject methods with the # ".animate" syntax: self.play(grid.animate.shift(LEFT)) # Both of those will interpolate between the mobject's initial # state and whatever happens when you apply that method. # For this example, calling grid.shift(LEFT) would shift the # grid one unit to the left, but both of the previous calls to # "self.play" animate that motion. # The same applies for any method, including those setting colors. self.play(grid.animate.set_color(YELLOW)) self.wait() self.play(grid.animate.set_submobject_colors_by_gradient(BLUE, GREEN)) self.wait() self.play(grid.animate.set_height(TAU - MED_SMALL_BUFF)) self.wait() # The method Mobject.apply_complex_function lets you apply arbitrary # complex functions, treating the points defining the mobject as # complex numbers. self.play(grid.animate.apply_complex_function(np.exp), run_time=5) self.wait() # Even more generally, you could apply Mobject.apply_function, # which takes in functions form R^3 to R^3 self.play( grid.animate.apply_function( lambda p: [ p[0] + 0.5 * math.sin(p[1]), p[1] + 0.5 * math.sin(p[0]), p[2] ] ), run_time=5, ) self.wait() class TextExample(Scene): def construct(self): # To run this scene properly, you should have "Consolas" font in your computer # for full usage, you can see https://github.com/3b1b/manim/pull/680 text = Text("Here is a text", font="Consolas", font_size=90) difference = Text( """ The most important difference between Text and TexText is that\n you can change the font more easily, but can't use the LaTeX grammar """, font="Arial", font_size=24, # t2c is a dict that you can choose color for different text t2c={"Text": BLUE, "TexText": BLUE, "LaTeX": ORANGE} ) VGroup(text, difference).arrange(DOWN, buff=1) self.play(Write(text)) self.play(FadeIn(difference, UP)) self.wait(3) fonts = Text( "And you can also set the font according to different words", font="Arial", t2f={"font": "Consolas", "words": "Consolas"}, t2c={"font": BLUE, "words": GREEN} ) fonts.set_width(FRAME_WIDTH - 1) slant = Text( "And the same as slant and weight", font="Consolas", t2s={"slant": ITALIC}, t2w={"weight": BOLD}, t2c={"slant": ORANGE, "weight": RED} ) VGroup(fonts, slant).arrange(DOWN, buff=0.8) self.play(FadeOut(text), FadeOut(difference, shift=DOWN)) self.play(Write(fonts)) self.wait() self.play(Write(slant)) self.wait() class TexTransformExample(Scene): def construct(self): # Tex to color map t2c = { "A": BLUE, "B": TEAL, "C": GREEN, } # Configuration to pass along to each Tex mobject kw = dict(font_size=72, t2c=t2c) lines = VGroup( Tex("A^2 + B^2 = C^2", **kw), Tex("A^2 = C^2 - B^2", **kw), Tex("A^2 = (C + B)(C - B)", **kw), Tex(R"A = \sqrt{(C + B)(C - B)}", **kw), ) lines.arrange(DOWN, buff=LARGE_BUFF) self.add(lines[0]) # The animation TransformMatchingStrings will line up parts # of the source and target which have matching substring strings. # Here, giving it a little path_arc makes each part rotate into # their final positions, which feels appropriate for the idea of # rearranging an equation self.play( TransformMatchingStrings( lines[0].copy(), lines[1], # matched_keys specifies which substring should # line up. If it's not specified, the animation # will align the longest matching substrings. # In this case, the substring "^2 = C^2" would # trip it up matched_keys=["A^2", "B^2", "C^2"], # When you want a substring from the source # to go to a non-equal substring from the target, # use the key map. key_map={"+": "-"}, path_arc=90 * DEGREES, ), ) self.wait() self.play(TransformMatchingStrings( lines[1].copy(), lines[2], matched_keys=["A^2"] )) self.wait() self.play( TransformMatchingStrings( lines[2].copy(), lines[3], key_map={"2": R"\sqrt"}, path_arc=-30 * DEGREES, ), ) self.wait(2) self.play(LaggedStartMap(FadeOut, lines, shift=2 * RIGHT)) # TransformMatchingShapes will try to line up all pieces of a # source mobject with those of a target, regardless of the # what Mobject type they are. source = Text("the morse code", height=1) target = Text("here come dots", height=1) saved_source = source.copy() self.play(Write(source)) self.wait() kw = dict(run_time=3, path_arc=PI / 2) self.play(TransformMatchingShapes(source, target, **kw)) self.wait() self.play(TransformMatchingShapes(target, saved_source, **kw)) self.wait() class TexIndexing(Scene): def construct(self): # You can index into Tex mobject (or other StringMobjects) by substrings equation = Tex(R"e^{\pi i} = -1", font_size=144) self.add(equation) self.play(FlashAround(equation["e"])) self.wait() self.play(Indicate(equation[R"\pi"])) self.wait() self.play(TransformFromCopy( equation[R"e^{\pi i}"].copy().set_opacity(0.5), equation["-1"], path_arc=-PI / 2, run_time=3 )) self.play(FadeOut(equation)) # Or regular expressions equation = Tex("A^2 + B^2 = C^2", font_size=144) self.play(Write(equation)) for part in equation[re.compile(r"\w\^2")]: self.play(FlashAround(part)) self.wait() self.play(FadeOut(equation)) # Indexing by substrings like this may not work when # the order in which Latex draws symbols does not match # the order in which they show up in the string. # For example, here the infinity is drawn before the sigma # so we don't get the desired behavior. equation = Tex(R"\sum_{n = 1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}", font_size=72) self.play(FadeIn(equation)) self.play(equation[R"\infty"].animate.set_color(RED)) # Doesn't hit the infinity self.wait() self.play(FadeOut(equation)) # However you can always fix this by explicitly passing in # a string you might want to isolate later. Also, using # \over instead of \frac helps to avoid the issue for fractions equation = Tex( R"\sum_{n = 1}^\infty {1 \over n^2} = {\pi^2 \over 6}", # Explicitly mark "\infty" as a substring you might want to access isolate=[R"\infty"], font_size=72 ) self.play(FadeIn(equation)) self.play(equation[R"\infty"].animate.set_color(RED)) # Got it! self.wait() self.play(FadeOut(equation)) class UpdatersExample(Scene): def construct(self): square = Square() square.set_fill(BLUE_E, 1) # On all frames, the constructor Brace(square, UP) will # be called, and the mobject brace will set its data to match # that of the newly constructed object brace = always_redraw(Brace, square, UP) label = TexText("Width = 0.00") number = label.make_number_changable("0.00") # This ensures that the method deicmal.next_to(square) # is called on every frame always(label.next_to, brace, UP) # You could also write the following equivalent line # label.add_updater(lambda m: m.next_to(brace, UP)) # If the argument itself might change, you can use f_always, # for which the arguments following the initial Mobject method # should be functions returning arguments to that method. # The following line ensures thst decimal.set_value(square.get_y()) # is called every frame f_always(number.set_value, square.get_width) # You could also write the following equivalent line # number.add_updater(lambda m: m.set_value(square.get_width())) self.add(square, brace, label) # Notice that the brace and label track with the square self.play( square.animate.scale(2), rate_func=there_and_back, run_time=2, ) self.wait() self.play( square.animate.set_width(5, stretch=True), run_time=3, ) self.wait() self.play( square.animate.set_width(2), run_time=3 ) self.wait() # In general, you can alway call Mobject.add_updater, and pass in # a function that you want to be called on every frame. The function # should take in either one argument, the mobject, or two arguments, # the mobject and the amount of time since the last frame. now = self.time w0 = square.get_width() square.add_updater( lambda m: m.set_width(w0 * math.sin(self.time - now) + w0) ) self.wait(4 * PI) class CoordinateSystemExample(Scene): def construct(self): axes = Axes( # x-axis ranges from -1 to 10, with a default step size of 1 x_range=(-1, 10), # y-axis ranges from -2 to 2 with a step size of 0.5 y_range=(-2, 2, 0.5), # The axes will be stretched so as to match the specified # height and width height=6, width=10, # Axes is made of two NumberLine mobjects. You can specify # their configuration with axis_config axis_config=dict( stroke_color=GREY_A, stroke_width=2, numbers_to_exclude=[0], ), # Alternatively, you can specify configuration for just one # of them, like this. y_axis_config=dict( numbers_with_elongated_ticks=[-2, 2], ) ) # Keyword arguments of add_coordinate_labels can be used to # configure the DecimalNumber mobjects which it creates and # adds to the axes axes.add_coordinate_labels( font_size=20, num_decimal_places=1, ) self.add(axes) # Axes descends from the CoordinateSystem class, meaning # you can call call axes.coords_to_point, abbreviated to # axes.c2p, to associate a set of coordinates with a point, # like so: dot = Dot(color=RED) dot.move_to(axes.c2p(0, 0)) self.play(FadeIn(dot, scale=0.5)) self.play(dot.animate.move_to(axes.c2p(3, 2))) self.wait() self.play(dot.animate.move_to(axes.c2p(5, 0.5))) self.wait() # Similarly, you can call axes.point_to_coords, or axes.p2c # print(axes.p2c(dot.get_center())) # We can draw lines from the axes to better mark the coordinates # of a given point. # Here, the always_redraw command means that on each new frame # the lines will be redrawn h_line = always_redraw(lambda: axes.get_h_line(dot.get_left())) v_line = always_redraw(lambda: axes.get_v_line(dot.get_bottom())) self.play( ShowCreation(h_line), ShowCreation(v_line), ) self.play(dot.animate.move_to(axes.c2p(3, -2))) self.wait() self.play(dot.animate.move_to(axes.c2p(1, 1))) self.wait() # If we tie the dot to a particular set of coordinates, notice # that as we move the axes around it respects the coordinate # system defined by them. f_always(dot.move_to, lambda: axes.c2p(1, 1)) self.play( axes.animate.scale(0.75).to_corner(UL), run_time=2, ) self.wait() self.play(FadeOut(VGroup(axes, dot, h_line, v_line))) # Other coordinate systems you can play around with include # ThreeDAxes, NumberPlane, and ComplexPlane. class GraphExample(Scene): def construct(self): axes = Axes((-3, 10), (-1, 8), height=6) axes.add_coordinate_labels() self.play(Write(axes, lag_ratio=0.01, run_time=1)) # Axes.get_graph will return the graph of a function sin_graph = axes.get_graph( lambda x: 2 * math.sin(x), color=BLUE, ) # By default, it draws it so as to somewhat smoothly interpolate # between sampled points (x, f(x)). If the graph is meant to have # a corner, though, you can set use_smoothing to False relu_graph = axes.get_graph( lambda x: max(x, 0), use_smoothing=False, color=YELLOW, ) # For discontinuous functions, you can specify the point of # discontinuity so that it does not try to draw over the gap. step_graph = axes.get_graph( lambda x: 2.0 if x > 3 else 1.0, discontinuities=[3], color=GREEN, ) # Axes.get_graph_label takes in either a string or a mobject. # If it's a string, it treats it as a LaTeX expression. By default # it places the label next to the graph near the right side, and # has it match the color of the graph sin_label = axes.get_graph_label(sin_graph, "\\sin(x)") relu_label = axes.get_graph_label(relu_graph, Text("ReLU")) step_label = axes.get_graph_label(step_graph, Text("Step"), x=4) self.play( ShowCreation(sin_graph), FadeIn(sin_label, RIGHT), ) self.wait(2) self.play( ReplacementTransform(sin_graph, relu_graph), FadeTransform(sin_label, relu_label), ) self.wait() self.play( ReplacementTransform(relu_graph, step_graph), FadeTransform(relu_label, step_label), ) self.wait() parabola = axes.get_graph(lambda x: 0.25 * x**2) parabola.set_stroke(BLUE) self.play( FadeOut(step_graph), FadeOut(step_label), ShowCreation(parabola) ) self.wait() # You can use axes.input_to_graph_point, abbreviated # to axes.i2gp, to find a particular point on a graph dot = Dot(color=RED) dot.move_to(axes.i2gp(2, parabola)) self.play(FadeIn(dot, scale=0.5)) # A value tracker lets us animate a parameter, usually # with the intent of having other mobjects update based # on the parameter x_tracker = ValueTracker(2) f_always( dot.move_to, lambda: axes.i2gp(x_tracker.get_value(), parabola) ) self.play(x_tracker.animate.set_value(4), run_time=3) self.play(x_tracker.animate.set_value(-2), run_time=3) self.wait() class TexAndNumbersExample(Scene): def construct(self): axes = Axes((-3, 3), (-3, 3), unit_size=1) axes.to_edge(DOWN) axes.add_coordinate_labels(font_size=16) circle = Circle(radius=2) circle.set_stroke(YELLOW, 3) circle.move_to(axes.get_origin()) self.add(axes, circle) # When numbers show up in tex, they can be readily # replaced with DecimalMobjects so that methods like # get_value and set_value can be called on them, and # animations like ChangeDecimalToValue can be called # on them. tex = Tex("x^2 + y^2 = 4.00") tex.next_to(axes, UP, buff=0.5) value = tex.make_number_changable("4.00") # This will tie the right hand side of our equation to # the square of the radius of the circle value.add_updater(lambda v: v.set_value(circle.get_radius()**2)) self.add(tex) text = Text(""" You can manipulate numbers in Tex mobjects """, font_size=30) text.next_to(tex, RIGHT, buff=1.5) arrow = Arrow(text, tex) self.add(text, arrow) self.play( circle.animate.set_height(2.0), run_time=4, rate_func=there_and_back, ) # By default, tex.make_number_changable replaces the first occurance # of the number,but by passing replace_all=True it replaces all and # returns a group of the results exponents = tex.make_number_changable("2", replace_all=True) self.play( LaggedStartMap( FlashAround, exponents, lag_ratio=0.2, buff=0.1, color=RED ), exponents.animate.set_color(RED) ) def func(x, y): # Switch from manim coords to axes coords xa, ya = axes.point_to_coords(np.array([x, y, 0])) return xa**4 + ya**4 - 4 new_curve = ImplicitFunction(func) new_curve.match_style(circle) circle.rotate(angle_of_vector(new_curve.get_start())) # Align value.clear_updaters() self.play( *(ChangeDecimalToValue(exp, 4) for exp in exponents), ReplacementTransform(circle.copy(), new_curve), circle.animate.set_stroke(width=1, opacity=0.5), ) class SurfaceExample(ThreeDScene): def construct(self): surface_text = Text("For 3d scenes, try using surfaces") surface_text.fix_in_frame() surface_text.to_edge(UP) self.add(surface_text) self.wait(0.1) torus1 = Torus(r1=1, r2=1) torus2 = Torus(r1=3, r2=1) sphere = Sphere(radius=3, resolution=torus1.resolution) # You can texture a surface with up to two images, which will # be interpreted as the side towards the light, and away from # the light. These can be either urls, or paths to a local file # in whatever you've set as the image directory in # the custom_config.yml file # day_texture = "EarthTextureMap" # night_texture = "NightEarthTextureMap" day_texture = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Whole_world_-_land_and_oceans.jpg/1280px-Whole_world_-_land_and_oceans.jpg" night_texture = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/The_earth_at_night.jpg/1280px-The_earth_at_night.jpg" surfaces = [ TexturedSurface(surface, day_texture, night_texture) for surface in [sphere, torus1, torus2] ] for mob in surfaces: mob.shift(IN) mob.mesh = SurfaceMesh(mob) mob.mesh.set_stroke(BLUE, 1, opacity=0.5) surface = surfaces[0] self.play( FadeIn(surface), ShowCreation(surface.mesh, lag_ratio=0.01, run_time=3), ) for mob in surfaces: mob.add(mob.mesh) surface.save_state() self.play(Rotate(surface, PI / 2), run_time=2) for mob in surfaces[1:]: mob.rotate(PI / 2) self.play( Transform(surface, surfaces[1]), run_time=3 ) self.play( Transform(surface, surfaces[2]), # Move camera frame during the transition self.frame.animate.increment_phi(-10 * DEGREES), self.frame.animate.increment_theta(-20 * DEGREES), run_time=3 ) # Add ambient rotation self.frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt)) # Play around with where the light is light_text = Text("You can move around the light source") light_text.move_to(surface_text) light_text.fix_in_frame() self.play(FadeTransform(surface_text, light_text)) light = self.camera.light_source self.add(light) light.save_state() self.play(light.animate.move_to(3 * IN), run_time=5) self.play(light.animate.shift(10 * OUT), run_time=5) drag_text = Text("Try moving the mouse while pressing d or f") drag_text.move_to(light_text) drag_text.fix_in_frame() self.play(FadeTransform(light_text, drag_text)) self.wait() class InteractiveDevelopment(Scene): def construct(self): circle = Circle() circle.set_fill(BLUE, opacity=0.5) circle.set_stroke(BLUE_E, width=4) square = Square() self.play(ShowCreation(square)) self.wait() # This opens an iPython terminal where you can keep writing # lines as if they were part of this construct method. # In particular, 'square', 'circle' and 'self' will all be # part of the local namespace in that terminal. self.embed() # Try copying and pasting some of the lines below into # the interactive shell self.play(ReplacementTransform(square, circle)) self.wait() self.play(circle.animate.stretch(4, 0)) self.play(Rotate(circle, 90 * DEGREES)) self.play(circle.animate.shift(2 * RIGHT).scale(0.25)) text = Text(""" In general, using the interactive shell is very helpful when developing new scenes """) self.play(Write(text)) # In the interactive shell, you can just type # play, add, remove, clear, wait, save_state and restore, # instead of self.play, self.add, self.remove, etc. # To interact with the window, type touch(). You can then # scroll in the window, or zoom by holding down 'z' while scrolling, # and change camera perspective by holding down 'd' while moving # the mouse. Press 'r' to reset to the standard camera position. # Press 'q' to stop interacting with the window and go back to # typing new commands into the shell. # In principle you can customize a scene to be responsive to # mouse and keyboard interactions always(circle.move_to, self.mouse_point) class ControlsExample(Scene): drag_to_pan = False def setup(self): self.textbox = Textbox() self.checkbox = Checkbox() self.color_picker = ColorSliders() self.panel = ControlPanel( Text("Text", font_size=24), self.textbox, Line(), Text("Show/Hide Text", font_size=24), self.checkbox, Line(), Text("Color of Text", font_size=24), self.color_picker ) self.add(self.panel) def construct(self): text = Text("text", font_size=96) def text_updater(old_text): assert(isinstance(old_text, Text)) new_text = Text(self.textbox.get_value(), font_size=old_text.font_size) # new_text.align_data_and_family(old_text) new_text.move_to(old_text) if self.checkbox.get_value(): new_text.set_fill( color=self.color_picker.get_picked_color(), opacity=self.color_picker.get_picked_opacity() ) else: new_text.set_opacity(0) old_text.become(new_text) text.add_updater(text_updater) self.add(MotionMobject(text)) self.textbox.set_value("Manim") # self.wait(60) # self.embed() # See https://github.com/3b1b/videos for many, many more
manim_3b1b/manimlib/shader_wrapper.py
from __future__ import annotations import copy import os import re import OpenGL.GL as gl import moderngl import numpy as np from manimlib.utils.iterables import resize_array from manimlib.utils.shaders import get_shader_code_from_file from manimlib.utils.shaders import get_shader_program from manimlib.utils.shaders import image_path_to_texture from manimlib.utils.shaders import get_texture_id from manimlib.utils.shaders import get_fill_canvas from manimlib.utils.shaders import release_texture from manimlib.utils.shaders import set_program_uniform from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import List, Optional, Dict from manimlib.typing import UniformDict # Mobjects that should be rendered with # the same shader will be organized and # clumped together based on keeping track # of a dict holding all the relevant information # to that shader class ShaderWrapper(object): def __init__( self, ctx: moderngl.context.Context, vert_data: np.ndarray, vert_indices: Optional[np.ndarray] = None, shader_folder: Optional[str] = None, mobject_uniforms: Optional[UniformDict] = None, # A dictionary mapping names of uniform variables texture_paths: Optional[dict[str, str]] = None, # A dictionary mapping names to filepaths for textures. depth_test: bool = False, render_primitive: int = moderngl.TRIANGLE_STRIP, ): self.ctx = ctx self.vert_data = vert_data self.vert_indices = (vert_indices or np.zeros(0)).astype(int) self.vert_attributes = vert_data.dtype.names self.shader_folder = shader_folder self.depth_test = depth_test self.render_primitive = render_primitive self.program_uniform_mirror: UniformDict = dict() self.bind_to_mobject_uniforms(mobject_uniforms or dict()) self.init_program_code() self.init_program() self.texture_names_to_ids = dict() if texture_paths is not None: self.init_textures(texture_paths) self.init_vao() self.refresh_id() def init_program_code(self) -> None: def get_code(name: str) -> str | None: return get_shader_code_from_file( os.path.join(self.shader_folder, f"{name}.glsl") ) self.program_code: dict[str, str | None] = { "vertex_shader": get_code("vert"), "geometry_shader": get_code("geom"), "fragment_shader": get_code("frag"), } def init_program(self): if not self.shader_folder: self.program = None self.vert_format = None return self.program = get_shader_program(self.ctx, **self.program_code) self.vert_format = moderngl.detect_format(self.program, self.vert_attributes) def init_textures(self, texture_paths: dict[str, str]): self.texture_names_to_ids = { name: get_texture_id(image_path_to_texture(path, self.ctx)) for name, path in texture_paths.items() } def init_vao(self): self.vbo = None self.ibo = None self.vao = None def bind_to_mobject_uniforms(self, mobject_uniforms: UniformDict): self.mobject_uniforms = mobject_uniforms def __eq__(self, shader_wrapper: ShaderWrapper): return all(( np.all(self.vert_data == shader_wrapper.vert_data), np.all(self.vert_indices == shader_wrapper.vert_indices), self.shader_folder == shader_wrapper.shader_folder, all( self.mobject_uniforms[key] == shader_wrapper.mobject_uniforms[key] for key in self.mobject_uniforms ), self.depth_test == shader_wrapper.depth_test, self.render_primitive == shader_wrapper.render_primitive, )) def copy(self): result = copy.copy(self) result.ctx = self.ctx result.vert_data = self.vert_data.copy() result.vert_indices = self.vert_indices.copy() result.init_vao() return result def is_valid(self) -> bool: return all([ self.vert_data is not None, self.program_code["vertex_shader"] is not None, self.program_code["fragment_shader"] is not None, ]) def get_id(self) -> str: return self.id def create_id(self) -> str: # A unique id for a shader program_id = hash("".join( self.program_code[f"{name}_shader"] or "" for name in ("vertex", "geometry", "fragment") )) return "|".join(map(str, [ program_id, self.mobject_uniforms, self.depth_test, self.render_primitive, self.texture_names_to_ids, ])) def refresh_id(self) -> None: self.id = self.create_id() def replace_code(self, old: str, new: str) -> None: code_map = self.program_code for name in code_map: if code_map[name] is None: continue code_map[name] = re.sub(old, new, code_map[name]) self.init_program() self.refresh_id() # Changing context def use_clip_plane(self): if "clip_plane" not in self.mobject_uniforms: return False return any(self.mobject_uniforms["clip_plane"]) def set_ctx_depth_test(self, enable: bool = True) -> None: if enable: self.ctx.enable(moderngl.DEPTH_TEST) else: self.ctx.disable(moderngl.DEPTH_TEST) def set_ctx_clip_plane(self, enable: bool = True) -> None: if enable: gl.glEnable(gl.GL_CLIP_DISTANCE0) # Adding data def combine_with(self, *shader_wrappers: ShaderWrapper) -> ShaderWrapper: if len(shader_wrappers) > 0: data_list = [self.vert_data, *(sw.vert_data for sw in shader_wrappers)] indices_list = [self.vert_indices, *(sw.vert_indices for sw in shader_wrappers)] self.read_in(data_list, indices_list) return self def read_in( self, data_list: List[np.ndarray], indices_list: List[np.ndarray] | None = None ) -> ShaderWrapper: # Assume all are of the same type total_len = sum(len(data) for data in data_list) self.vert_data = resize_array(self.vert_data, total_len) if total_len == 0: return self # Stack the data np.concatenate(data_list, out=self.vert_data) if indices_list is None: self.vert_indices = resize_array(self.vert_indices, 0) return self total_verts = sum(len(vi) for vi in indices_list) if total_verts == 0: return self self.vert_indices = resize_array(self.vert_indices, total_verts) # Stack vert_indices, but adding the appropriate offset # alogn the way n_points = 0 n_verts = 0 for data, indices in zip(data_list, indices_list): new_n_verts = n_verts + len(indices) self.vert_indices[n_verts:new_n_verts] = indices + n_points n_verts = new_n_verts n_points += len(data) return self # Related to data and rendering def pre_render(self): self.set_ctx_depth_test(self.depth_test) self.set_ctx_clip_plane(self.use_clip_plane()) def render(self): assert(self.vao is not None) self.vao.render() def update_program_uniforms(self, camera_uniforms: UniformDict): if self.program is None: return for uniforms in [self.mobject_uniforms, camera_uniforms, self.texture_names_to_ids]: for name, value in uniforms.items(): set_program_uniform(self.program, name, value) def get_vertex_buffer_object(self, refresh: bool = True): if refresh: self.vbo = self.ctx.buffer(self.vert_data) return self.vbo def get_index_buffer_object(self, refresh: bool = True): if refresh and len(self.vert_indices) > 0: self.ibo = self.ctx.buffer(self.vert_indices.astype(np.uint32)) return self.ibo def generate_vao(self, refresh: bool = True): self.release() # Data buffer vbo = self.get_vertex_buffer_object(refresh) ibo = self.get_index_buffer_object(refresh) # Vertex array object self.vao = self.ctx.vertex_array( program=self.program, content=[(vbo, self.vert_format, *self.vert_attributes)], index_buffer=ibo, mode=self.render_primitive, ) return self.vao def release(self): for obj in (self.vbo, self.ibo, self.vao): if obj is not None: obj.release() self.vbo = None self.ibo = None self.vao = None class FillShaderWrapper(ShaderWrapper): def __init__( self, ctx: moderngl.context.Context, *args, **kwargs ): super().__init__(ctx, *args, **kwargs) self.fill_canvas = get_fill_canvas(self.ctx) def render(self): winding = (len(self.vert_indices) == 0) self.program['winding'].value = winding if not winding: super().render() return original_fbo = self.ctx.fbo texture_fbo, texture_vao = self.fill_canvas texture_fbo.clear() texture_fbo.use() gl.glBlendFuncSeparate( # Ordinary blending for colors gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA, # The effect of blending with -a / (1 - a) # should be to cancel out gl.GL_ONE_MINUS_DST_ALPHA, gl.GL_ONE, ) super().render() original_fbo.use() gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA) texture_vao.render() gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
manim_3b1b/manimlib/__main__.py
#!/usr/bin/env python from manimlib import __version__ import manimlib.config import manimlib.extract_scene import manimlib.logger import manimlib.utils.init_config def main(): print(f"ManimGL \033[32mv{__version__}\033[0m") args = manimlib.config.parse_cli() if args.version and args.file is None: return if args.log_level: manimlib.logger.log.setLevel(args.log_level) if args.config: manimlib.utils.init_config.init_customization() else: config = manimlib.config.get_configuration(args) scenes = manimlib.extract_scene.main(config) for scene in scenes: scene.run() if __name__ == "__main__": main()
manim_3b1b/manimlib/default_config.yml
directories: # Set this to true if you want the path to video files # to match the directory structure of the path to the # sourcecode generating that video mirror_module_path: False # Where should manim output video and image files? output: "" # If you want to use images, manim will look to these folders to find them raster_images: "" vector_images: "" # If you want to use sounds, manim will look here to find it. sounds: "" # Manim often generates tex_files or other kinds of serialized data # to keep from having to generate the same thing too many times. By # default, these will be stored at tempfile.gettempdir(), e.g. this might # return whatever is at to the TMPDIR environment variable. If you want to # specify them elsewhere, temporary_storage: "" universal_import_line: "from manimlib import *" style: tex_template: "default" font: "Consolas" text_alignment: "LEFT" background_color: "#333333" # Set the position of preview window, you can use directions, e.g. UL/DR/OL/OO/... # also, you can also specify the position(pixel) of the upper left corner of # the window on the monitor, e.g. "960,540" window_position: UR window_monitor: 0 full_screen: False # If break_into_partial_movies is set to True, then many small # files will be written corresponding to each Scene.play and # Scene.wait call, and these files will then be combined # to form the full scene. Sometimes video-editing is made # easier when working with the broken up scene, which # effectively has cuts at all the places you might want. break_into_partial_movies: False camera_resolutions: low: "854x480" med: "1280x720" high: "1920x1080" 4k: "3840x2160" default_resolution: "high" fps: 30 embed_exception_mode: "Verbose" embed_error_sound: False
manim_3b1b/manimlib/__init__.py
import pkg_resources __version__ = pkg_resources.get_distribution("manimgl").version from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import * from manimlib.constants import * from manimlib.window import * from manimlib.animation.animation import * from manimlib.animation.composition import * from manimlib.animation.creation import * from manimlib.animation.fading import * from manimlib.animation.growing import * from manimlib.animation.indication import * from manimlib.animation.movement import * from manimlib.animation.numbers import * from manimlib.animation.rotation import * from manimlib.animation.specialized import * from manimlib.animation.transform import * from manimlib.animation.transform_matching_parts import * from manimlib.animation.update import * from manimlib.camera.camera import * from manimlib.mobject.boolean_ops import * from manimlib.mobject.changing import * from manimlib.mobject.coordinate_systems import * from manimlib.mobject.frame import * from manimlib.mobject.functions import * from manimlib.mobject.geometry import * from manimlib.mobject.interactive import * from manimlib.mobject.matrix import * from manimlib.mobject.mobject import * from manimlib.mobject.mobject_update_utils import * from manimlib.mobject.number_line import * from manimlib.mobject.numbers import * from manimlib.mobject.probability import * from manimlib.mobject.shape_matchers import * from manimlib.mobject.svg.brace import * from manimlib.mobject.svg.drawings import * from manimlib.mobject.svg.tex_mobject import * from manimlib.mobject.svg.string_mobject import * from manimlib.mobject.svg.svg_mobject import * from manimlib.mobject.svg.special_tex import * from manimlib.mobject.svg.tex_mobject import * from manimlib.mobject.svg.text_mobject import * from manimlib.mobject.three_dimensions import * from manimlib.mobject.types.dot_cloud import * from manimlib.mobject.types.image_mobject import * from manimlib.mobject.types.point_cloud_mobject import * from manimlib.mobject.types.surface import * from manimlib.mobject.types.vectorized_mobject import * from manimlib.mobject.value_tracker import * from manimlib.mobject.vector_field import * from manimlib.scene.interactive_scene import * from manimlib.scene.scene import * from manimlib.utils.bezier import * from manimlib.utils.color import * from manimlib.utils.dict_ops import * from manimlib.utils.customization import * from manimlib.utils.debug import * from manimlib.utils.directories import * from manimlib.utils.file_ops import * from manimlib.utils.images import * from manimlib.utils.iterables import * from manimlib.utils.paths import * from manimlib.utils.rate_functions import * from manimlib.utils.simple_functions import * from manimlib.utils.shaders import * from manimlib.utils.sounds import * from manimlib.utils.space_ops import * from manimlib.utils.tex import *
manim_3b1b/manimlib/constants.py
from __future__ import annotations import numpy as np from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import List from manimlib.typing import ManimColor, Vect3 # Sizes relevant to default camera frame ASPECT_RATIO: float = 16.0 / 9.0 FRAME_HEIGHT: float = 8.0 FRAME_WIDTH: float = FRAME_HEIGHT * ASPECT_RATIO FRAME_SHAPE: tuple[float, float] = (FRAME_WIDTH, FRAME_HEIGHT) FRAME_Y_RADIUS: float = FRAME_HEIGHT / 2 FRAME_X_RADIUS: float = FRAME_WIDTH / 2 DEFAULT_PIXEL_HEIGHT: int = 1080 DEFAULT_PIXEL_WIDTH: int = 1920 DEFAULT_FPS: int = 30 SMALL_BUFF: float = 0.1 MED_SMALL_BUFF: float = 0.25 MED_LARGE_BUFF: float = 0.5 LARGE_BUFF: float = 1 DEFAULT_MOBJECT_TO_EDGE_BUFFER: float = MED_LARGE_BUFF DEFAULT_MOBJECT_TO_MOBJECT_BUFFER: float = MED_SMALL_BUFF # In seconds DEFAULT_WAIT_TIME: float = 1.0 ORIGIN: Vect3 = np.array([0., 0., 0.]) UP: Vect3 = np.array([0., 1., 0.]) DOWN: Vect3 = np.array([0., -1., 0.]) RIGHT: Vect3 = np.array([1., 0., 0.]) LEFT: Vect3 = np.array([-1., 0., 0.]) IN: Vect3 = np.array([0., 0., -1.]) OUT: Vect3 = np.array([0., 0., 1.]) X_AXIS: Vect3 = np.array([1., 0., 0.]) Y_AXIS: Vect3 = np.array([0., 1., 0.]) Z_AXIS: Vect3 = np.array([0., 0., 1.]) NULL_POINTS = np.array([[0., 0., 0.]]) # Useful abbreviations for diagonals UL: Vect3 = UP + LEFT UR: Vect3 = UP + RIGHT DL: Vect3 = DOWN + LEFT DR: Vect3 = DOWN + RIGHT TOP: Vect3 = FRAME_Y_RADIUS * UP BOTTOM: Vect3 = FRAME_Y_RADIUS * DOWN LEFT_SIDE: Vect3 = FRAME_X_RADIUS * LEFT RIGHT_SIDE: Vect3 = FRAME_X_RADIUS * RIGHT PI: float = np.pi TAU: float = 2 * PI DEGREES: float = TAU / 360 # Nice to have a constant for readability # when juxtaposed with expressions like 30 * DEGREES RADIANS: float = 1 FFMPEG_BIN: str = "ffmpeg" JOINT_TYPE_MAP: dict = { "no_joint": 0, "auto": 1, "bevel": 2, "miter": 3, } # Related to Text NORMAL: str = "NORMAL" ITALIC: str = "ITALIC" OBLIQUE: str = "OBLIQUE" BOLD: str = "BOLD" DEFAULT_STROKE_WIDTH: float = 4 # For keyboard interactions CTRL_SYMBOL: int = 65508 SHIFT_SYMBOL: int = 65505 COMMAND_SYMBOL: int = 65517 DELETE_SYMBOL: int = 65288 ARROW_SYMBOLS: list[int] = list(range(65361, 65365)) SHIFT_MODIFIER: int = 1 CTRL_MODIFIER: int = 2 COMMAND_MODIFIER: int = 64 # Colors BLUE_E: ManimColor = "#1C758A" BLUE_D: ManimColor = "#29ABCA" BLUE_C: ManimColor = "#58C4DD" BLUE_B: ManimColor = "#9CDCEB" BLUE_A: ManimColor = "#C7E9F1" TEAL_E: ManimColor = "#49A88F" TEAL_D: ManimColor = "#55C1A7" TEAL_C: ManimColor = "#5CD0B3" TEAL_B: ManimColor = "#76DDC0" TEAL_A: ManimColor = "#ACEAD7" GREEN_E: ManimColor = "#699C52" GREEN_D: ManimColor = "#77B05D" GREEN_C: ManimColor = "#83C167" GREEN_B: ManimColor = "#A6CF8C" GREEN_A: ManimColor = "#C9E2AE" YELLOW_E: ManimColor = "#E8C11C" YELLOW_D: ManimColor = "#F4D345" YELLOW_C: ManimColor = "#FFFF00" YELLOW_B: ManimColor = "#FFEA94" YELLOW_A: ManimColor = "#FFF1B6" GOLD_E: ManimColor = "#C78D46" GOLD_D: ManimColor = "#E1A158" GOLD_C: ManimColor = "#F0AC5F" GOLD_B: ManimColor = "#F9B775" GOLD_A: ManimColor = "#F7C797" RED_E: ManimColor = "#CF5044" RED_D: ManimColor = "#E65A4C" RED_C: ManimColor = "#FC6255" RED_B: ManimColor = "#FF8080" RED_A: ManimColor = "#F7A1A3" MAROON_E: ManimColor = "#94424F" MAROON_D: ManimColor = "#A24D61" MAROON_C: ManimColor = "#C55F73" MAROON_B: ManimColor = "#EC92AB" MAROON_A: ManimColor = "#ECABC1" PURPLE_E: ManimColor = "#644172" PURPLE_D: ManimColor = "#715582" PURPLE_C: ManimColor = "#9A72AC" PURPLE_B: ManimColor = "#B189C6" PURPLE_A: ManimColor = "#CAA3E8" GREY_E: ManimColor = "#222222" GREY_D: ManimColor = "#444444" GREY_C: ManimColor = "#888888" GREY_B: ManimColor = "#BBBBBB" GREY_A: ManimColor = "#DDDDDD" WHITE: ManimColor = "#FFFFFF" BLACK: ManimColor = "#000000" GREY_BROWN: ManimColor = "#736357" DARK_BROWN: ManimColor = "#8B4513" LIGHT_BROWN: ManimColor = "#CD853F" PINK: ManimColor = "#D147BD" LIGHT_PINK: ManimColor = "#DC75CD" GREEN_SCREEN: ManimColor = "#00FF00" ORANGE: ManimColor = "#FF862F" MANIM_COLORS: List[ManimColor] = [ BLACK, GREY_E, GREY_D, GREY_C, GREY_B, GREY_A, WHITE, BLUE_E, BLUE_D, BLUE_C, BLUE_B, BLUE_A, TEAL_E, TEAL_D, TEAL_C, TEAL_B, TEAL_A, GREEN_E, GREEN_D, GREEN_C, GREEN_B, GREEN_A, YELLOW_E, YELLOW_D, YELLOW_C, YELLOW_B, YELLOW_A, GOLD_E, GOLD_D, GOLD_C, GOLD_B, GOLD_A, RED_E, RED_D, RED_C, RED_B, RED_A, MAROON_E, MAROON_D, MAROON_C, MAROON_B, MAROON_A, PURPLE_E, PURPLE_D, PURPLE_C, PURPLE_B, PURPLE_A, GREY_BROWN, DARK_BROWN, LIGHT_BROWN, PINK, LIGHT_PINK, ] # Abbreviated names for the "median" colors BLUE: ManimColor = BLUE_C TEAL: ManimColor = TEAL_C GREEN: ManimColor = GREEN_C YELLOW: ManimColor = YELLOW_C GOLD: ManimColor = GOLD_C RED: ManimColor = RED_C MAROON: ManimColor = MAROON_C PURPLE: ManimColor = PURPLE_C GREY: ManimColor = GREY_C COLORMAP_3B1B: List[ManimColor] = [BLUE_E, GREEN, YELLOW, RED]
manim_3b1b/manimlib/typing.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Union, Tuple, Annotated, Literal, Iterable from colour import Color import numpy as np import re try: from typing import Self except ImportError: from typing_extensions import Self # Abbreviations for a common types ManimColor = Union[str, Color, None] RangeSpecifier = Tuple[float, float, float] | Tuple[float, float] Span = tuple[int, int] SingleSelector = Union[ str, re.Pattern, tuple[Union[int, None], Union[int, None]], ] Selector = Union[SingleSelector, Iterable[SingleSelector]] UniformDict = Dict[str, float | bool | np.ndarray | tuple] # These are various alternate names for np.ndarray meant to specify # certain shapes. # # In theory, these annotations could be used to check arrays sizes # at runtime, but at the moment nothing actually uses them, and # the names are here primarily to enhance readibility and allow # for some stronger type checking if numpy has stronger typing # in the future FloatArray = np.ndarray[int, np.dtype[np.float64]] Vect2 = Annotated[FloatArray, Literal[2]] Vect3 = Annotated[FloatArray, Literal[3]] Vect4 = Annotated[FloatArray, Literal[4]] VectN = Annotated[FloatArray, Literal["N"]] Matrix3x3 = Annotated[FloatArray, Literal[3, 3]] Vect2Array = Annotated[FloatArray, Literal["N", 2]] Vect3Array = Annotated[FloatArray, Literal["N", 3]] Vect4Array = Annotated[FloatArray, Literal["N", 4]] VectNArray = Annotated[FloatArray, Literal["N", "M"]]
manim_3b1b/manimlib/config.py
from __future__ import annotations import argparse from argparse import Namespace import colour import importlib import inspect import os from screeninfo import get_monitors import sys import yaml from manimlib.logger import log from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.init_config import init_customization from manimlib.constants import FRAME_HEIGHT from typing import TYPE_CHECKING if TYPE_CHECKING: Module = importlib.util.types.ModuleType __config_file__ = "custom_config.yml" def parse_cli(): try: parser = argparse.ArgumentParser() module_location = parser.add_mutually_exclusive_group() module_location.add_argument( "file", nargs="?", help="Path to file holding the python code for the scene", ) parser.add_argument( "scene_names", nargs="*", help="Name of the Scene class you want to see", ) parser.add_argument( "-w", "--write_file", action="store_true", help="Render the scene as a movie file", ) parser.add_argument( "-s", "--skip_animations", action="store_true", help="Save the last frame", ) parser.add_argument( "-l", "--low_quality", action="store_true", help="Render at a low quality (for faster rendering)", ) parser.add_argument( "-m", "--medium_quality", action="store_true", help="Render at a medium quality", ) parser.add_argument( "--hd", action="store_true", help="Render at a 1080p", ) parser.add_argument( "--uhd", action="store_true", help="Render at a 4k", ) parser.add_argument( "-f", "--full_screen", action="store_true", help="Show window in full screen", ) parser.add_argument( "-p", "--presenter_mode", action="store_true", help="Scene will stay paused during wait calls until " + \ "space bar or right arrow is hit, like a slide show" ) parser.add_argument( "-g", "--save_pngs", action="store_true", help="Save each frame as a png", ) parser.add_argument( "-i", "--gif", action="store_true", help="Save the video as gif", ) parser.add_argument( "-t", "--transparent", action="store_true", help="Render to a movie file with an alpha channel", ) parser.add_argument( "--vcodec", help="Video codec to use with ffmpeg", ) parser.add_argument( "--pix_fmt", help="Pixel format to use for the output of ffmpeg, defaults to `yuv420p`", ) parser.add_argument( "-q", "--quiet", action="store_true", help="", ) parser.add_argument( "-a", "--write_all", action="store_true", help="Write all the scenes from a file", ) parser.add_argument( "-o", "--open", action="store_true", help="Automatically open the saved file once its done", ) parser.add_argument( "--finder", action="store_true", help="Show the output file in finder", ) parser.add_argument( "--config", action="store_true", help="Guide for automatic configuration", ) parser.add_argument( "--file_name", help="Name for the movie or image file", ) parser.add_argument( "-n", "--start_at_animation_number", help="Start rendering not from the first animation, but " + \ "from another, specified by its index. If you pass " + \ "in two comma separated values, e.g. \"3,6\", it will end " + \ "the rendering at the second value", ) parser.add_argument( "-e", "--embed", nargs="?", const="", help="Creates a new file where the line `self.embed` is inserted " + \ "into the Scenes construct method. " + \ "If a string is passed in, the line will be inserted below the " + \ "last line of code including that string." ) parser.add_argument( "-r", "--resolution", help="Resolution, passed as \"WxH\", e.g. \"1920x1080\"", ) parser.add_argument( "--fps", help="Frame rate, as an integer", ) parser.add_argument( "-c", "--color", help="Background color", ) parser.add_argument( "--leave_progress_bars", action="store_true", help="Leave progress bars displayed in terminal", ) parser.add_argument( "--show_animation_progress", action="store_true", help="Show progress bar for each animation", ) parser.add_argument( "--prerun", action="store_true", help="Calculate total framecount, to display in a progress bar, by doing " + \ "an initial run of the scene which skips animations." ) parser.add_argument( "--video_dir", help="Directory to write video", ) parser.add_argument( "--config_file", help="Path to the custom configuration file", ) parser.add_argument( "-v", "--version", action="store_true", help="Display the version of manimgl" ) parser.add_argument( "--log-level", help="Level of messages to Display, can be DEBUG / INFO / WARNING / ERROR / CRITICAL" ) args = parser.parse_args() args.write_file = any([args.write_file, args.open, args.finder]) return args except argparse.ArgumentError as err: log.error(str(err)) sys.exit(2) def get_manim_dir(): manimlib_module = importlib.import_module("manimlib") manimlib_dir = os.path.dirname(inspect.getabsfile(manimlib_module)) return os.path.abspath(os.path.join(manimlib_dir, "..")) def get_module(file_name: str | None) -> Module: if file_name is None: return None module_name = file_name.replace(os.sep, ".").replace(".py", "") spec = importlib.util.spec_from_file_location(module_name, file_name) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_indent(line: str): return len(line) - len(line.lstrip()) def get_module_with_inserted_embed_line( file_name: str, scene_name: str, line_marker: str ): """ This is hacky, but convenient. When user includes the argument "-e", it will try to recreate a file that inserts the line `self.embed()` into the end of the scene's construct method. If there is an argument passed in, it will insert the line after the last line in the sourcefile which includes that string. """ with open(file_name, 'r') as fp: lines = fp.readlines() try: scene_line_number = next( i for i, line in enumerate(lines) if line.startswith(f"class {scene_name}") ) except StopIteration: log.error(f"No scene {scene_name}") return prev_line_num = -1 n_spaces = None if len(line_marker) == 0: # Find the end of the construct method in_construct = False for index in range(scene_line_number, len(lines) - 1): line = lines[index] if line.lstrip().startswith("def construct"): in_construct = True n_spaces = get_indent(line) + 4 elif in_construct: if len(line.strip()) > 0 and get_indent(line) < (n_spaces or 0): prev_line_num = index - 1 break if prev_line_num < 0: prev_line_num = len(lines) - 1 elif line_marker.isdigit(): # Treat the argument as a line number prev_line_num = int(line_marker) - 1 elif len(line_marker) > 0: # Treat the argument as a string try: prev_line_num = next( i for i in range(scene_line_number, len(lines) - 1) if line_marker in lines[i] ) except StopIteration: log.error(f"No lines matching {line_marker}") sys.exit(2) # Insert the embed line, rewrite file, then write it back when done if n_spaces is None: n_spaces = get_indent(lines[prev_line_num]) inserted_line = " " * n_spaces + "self.embed()\n" new_lines = list(lines) new_lines.insert(prev_line_num + 1, inserted_line) new_file = file_name.replace(".py", "_insert_embed.py") with open(new_file, 'w') as fp: fp.writelines(new_lines) module = get_module(new_file) # This is to pretend the module imported from the edited lines # of code actually comes from the original file. module.__file__ = file_name os.remove(new_file) return module def get_scene_module(args: Namespace) -> Module: if args.embed is None: return get_module(args.file) else: return get_module_with_inserted_embed_line( args.file, args.scene_names[0], args.embed ) def get_custom_config(): global __config_file__ global_defaults_file = os.path.join(get_manim_dir(), "manimlib", "default_config.yml") if os.path.exists(global_defaults_file): with open(global_defaults_file, "r") as file: custom_config = yaml.safe_load(file) if os.path.exists(__config_file__): with open(__config_file__, "r") as file: local_defaults = yaml.safe_load(file) if local_defaults: custom_config = merge_dicts_recursively( custom_config, local_defaults, ) else: with open(__config_file__, "r") as file: custom_config = yaml.safe_load(file) # Check temporary storage(custom_config) if custom_config["directories"]["temporary_storage"] == "" and sys.platform == "win32": log.warning( "You may be using Windows platform and have not specified the path of" + \ " `temporary_storage`, which may cause OSError. So it is recommended" + \ " to specify the `temporary_storage` in the config file (.yml)" ) return custom_config def init_global_config(config_file): global __config_file__ # ensure __config_file__ always exists if config_file is not None: if not os.path.exists(config_file): log.error(f"Can't find {config_file}.") if sys.platform == 'win32': log.info(f"Copying default configuration file to {config_file}...") os.system(f"copy default_config.yml {config_file}") elif sys.platform in ["linux2", "darwin"]: log.info(f"Copying default configuration file to {config_file}...") os.system(f"cp default_config.yml {config_file}") else: log.info("Please create the configuration file manually.") log.info("Read configuration from default_config.yml.") else: __config_file__ = config_file global_defaults_file = os.path.join(get_manim_dir(), "manimlib", "default_config.yml") if not (os.path.exists(global_defaults_file) or os.path.exists(__config_file__)): log.info("There is no configuration file detected. Switch to the config file initializer:") init_customization() elif not os.path.exists(__config_file__): log.info(f"Using the default configuration file, which you can modify in `{global_defaults_file}`") log.info( "If you want to create a local configuration file, you can create a file named" + \ f" `{__config_file__}`, or run `manimgl --config`" ) def get_file_ext(args: Namespace) -> str: if args.transparent: file_ext = ".mov" elif args.gif: file_ext = ".gif" else: file_ext = ".mp4" return file_ext def get_animations_numbers(args: Namespace) -> tuple[int | None, int | None]: stan = args.start_at_animation_number if stan is None: return (None, None) elif "," in stan: return tuple(map(int, stan.split(","))) else: return int(stan), None def get_output_directory(args: Namespace, custom_config: dict) -> str: dir_config = custom_config["directories"] output_directory = args.video_dir or dir_config["output"] if dir_config["mirror_module_path"] and args.file: to_cut = dir_config["removed_mirror_prefix"] ext = os.path.abspath(args.file) ext = ext.replace(to_cut, "").replace(".py", "") if ext.startswith("_"): ext = ext[1:] output_directory = os.path.join(output_directory, ext) return output_directory def get_file_writer_config(args: Namespace, custom_config: dict) -> dict: result = { "write_to_movie": not args.skip_animations and args.write_file, "break_into_partial_movies": custom_config["break_into_partial_movies"], "save_last_frame": args.skip_animations and args.write_file, "save_pngs": args.save_pngs, # If -t is passed in (for transparent), this will be RGBA "png_mode": "RGBA" if args.transparent else "RGB", "movie_file_extension": get_file_ext(args), "output_directory": get_output_directory(args, custom_config), "file_name": args.file_name, "input_file_path": args.file or "", "open_file_upon_completion": args.open, "show_file_location_upon_completion": args.finder, "quiet": args.quiet, } if args.vcodec: result["video_codec"] = args.vcodec elif args.transparent: result["video_codec"] = 'prores_ks' result["pixel_format"] = '' elif args.gif: result["video_codec"] = '' if args.pix_fmt: result["pixel_format"] = args.pix_fmt return result def get_window_config(args: Namespace, custom_config: dict, camera_config: dict) -> dict: # Default to making window half the screen size # but make it full screen if -f is passed in monitors = get_monitors() mon_index = custom_config["window_monitor"] monitor = monitors[min(mon_index, len(monitors) - 1)] aspect_ratio = camera_config["pixel_width"] / camera_config["pixel_height"] window_width = monitor.width if not (args.full_screen or custom_config["full_screen"]): window_width //= 2 window_height = int(window_width / aspect_ratio) return dict(size=(window_width, window_height)) def get_camera_config(args: Namespace, custom_config: dict) -> dict: camera_config = {} camera_resolutions = custom_config["camera_resolutions"] if args.resolution: resolution = args.resolution elif args.low_quality: resolution = camera_resolutions["low"] elif args.medium_quality: resolution = camera_resolutions["med"] elif args.hd: resolution = camera_resolutions["high"] elif args.uhd: resolution = camera_resolutions["4k"] else: resolution = camera_resolutions[camera_resolutions["default_resolution"]] if args.fps: fps = int(args.fps) else: fps = custom_config["fps"] width_str, height_str = resolution.split("x") width = int(width_str) height = int(height_str) camera_config.update({ "pixel_width": width, "pixel_height": height, "frame_config": { "frame_shape": ((width / height) * FRAME_HEIGHT, FRAME_HEIGHT), }, "fps": fps, }) try: bg_color = args.color or custom_config["style"]["background_color"] camera_config["background_color"] = colour.Color(bg_color) except ValueError as err: log.error("Please use a valid color") log.error(err) sys.exit(2) # If rendering a transparent image/move, make sure the # scene has a background opacity of 0 if args.transparent: camera_config["background_opacity"] = 0 return camera_config def get_configuration(args: Namespace) -> dict: init_global_config(args.config_file) custom_config = get_custom_config() camera_config = get_camera_config(args, custom_config) window_config = get_window_config(args, custom_config, camera_config) start, end = get_animations_numbers(args) return { "module": get_scene_module(args), "scene_names": args.scene_names, "file_writer_config": get_file_writer_config(args, custom_config), "camera_config": camera_config, "window_config": window_config, "quiet": args.quiet or args.write_all, "write_all": args.write_all, "skip_animations": args.skip_animations, "start_at_animation_number": start, "end_at_animation_number": end, "preview": not args.write_file, "presenter_mode": args.presenter_mode, "leave_progress_bars": args.leave_progress_bars, "show_animation_progress": args.show_animation_progress, "prerun": args.prerun, "embed_exception_mode": custom_config["embed_exception_mode"], "embed_error_sound": custom_config["embed_error_sound"], }
manim_3b1b/manimlib/tex_templates.yml
# Classical TeX templates default: description: "" compiler: latex preamble: |- \usepackage[english]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \usepackage{pifont} \DisableLigatures{encoding = *, family = * } \linespread{1} ctex: description: "" compiler: xelatex preamble: |- \usepackage[UTF8]{ctex} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \linespread{1} # Simplified TeX templates basic: description: "" compiler: latex preamble: |- \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} basic_ctex: description: "" compiler: xelatex preamble: |- \usepackage[UTF8]{ctex} \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} empty: description: "" compiler: latex preamble: "" empty_ctex: description: "" compiler: xelatex preamble: "" # A collection of TeX templates for the fonts described at # http://jf.burnol.free.fr/showcase.html american_typewriter: description: American Typewriter compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{American Typewriter} \usepackage[defaultmathsizes]{mathastext} antykwa: description: Antykwa Poltawskiego (TX Fonts for Greek and math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[OT4,OT1]{fontenc} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage{antpolt} \usepackage[defaultmathsizes,nolessnomore]{mathastext} apple_chancery: description: Apple Chancery compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Apple Chancery} \usepackage[defaultmathsizes]{mathastext} auriocus_kalligraphicus: description: Auriocus Kalligraphicus (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{aurical} \renewcommand{\rmdefault}{AuriocusKalligraphicus} \usepackage[symbolgreek]{mathastext} baskervald_adf_fourier: description: Baskervald ADF with Fourier compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[upright]{fourier} \usepackage{baskervald} \usepackage[defaultmathsizes,noasterisk]{mathastext} baskerville_it: description: Baskerville (Italic) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Baskerville} \usepackage[defaultmathsizes,italic]{mathastext} biolinum: description: Biolinum compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \setsansfont[Mapping=tex-text,Scale=MatchUppercase]{Myriad Pro} \renewcommand\familydefault\sfdefault \usepackage[defaultmathsizes]{mathastext} \renewcommand\familydefault\rmdefault brushscriptx: description: BrushScriptX-Italic (PX math and Greek) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \renewcommand{\rmdefault}{pbsi} \renewcommand{\mddefault}{xl} \renewcommand{\bfdefault}{xl} \usepackage[defaultmathsizes,noasterisk]{mathastext} \boldmath chalkboard_se: description: Chalkboard SE compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkboard SE} \usepackage[defaultmathsizes]{mathastext} chalkduster: description: Chalkduster compiler: lualatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkduster} \usepackage[defaultmathsizes]{mathastext} comfortaa: description: Comfortaa compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[default]{comfortaa} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \let\varphi\phi \linespread{1.06} comic_sans: description: Comic Sans MS compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Comic Sans MS} \usepackage[defaultmathsizes]{mathastext} droid_sans: description: Droid Sans compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon droid_sans_it: description: Droid Sans (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi droid_serif: description: Droid Serif compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidserif} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon droid_serif_px_it: description: Droid Serif (PX math symbols) (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage[default]{droidserif} \usepackage[LGRgreek,defaultmathsizes,italic,basic]{mathastext} \let\varphi\phi ecf_augie: description: ECF Augie (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \renewcommand\familydefault{fau} \usepackage[defaultmathsizes,eulergreek]{mathastext} ecf_jd: description: ECF JD (with TX fonts) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fjd} \usepackage{mathastext} \mathversion{bold} ecf_skeetch: description: ECF Skeetch (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{fsk}{} \DeclareFontShape{T1}{fsk}{m}{n}{<->s*[1.315] fskmw8t}{} \renewcommand\rmdefault{fsk} \usepackage[noendash,defaultmathsizes,nohbar,defaultimath]{mathastext} ecf_tall_paul: description: ECF Tall Paul (with Symbol font) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \DeclareFontFamily{T1}{ftp}{} \DeclareFontShape{T1}{ftp}{m}{n}{<->s*[1.4] ftpmw8t}{} \renewcommand\familydefault{ftp} \usepackage[symbol]{mathastext} \let\infty\inftypsy ecf_webster: description: ECF Webster (with TX fonts) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fwb} \usepackage{mathastext} \renewcommand{\int}{\intop\limits} \linespread{1.5} \mathversion{bold} electrum_adf: description: Electrum ADF (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[LGRgreek,basic,defaultmathsizes]{mathastext} \usepackage[lf]{electrum} \Mathastext \let\varphi\phi epigrafica: description: Epigrafica compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[LGR,OT1]{fontenc} \usepackage{epigrafica} \usepackage[basic,LGRgreek,defaultmathsizes]{mathastext} \let\varphi\phi \linespread{1.2} fourier_utopia: description: Fourier Utopia (Fourier upright Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{mathastext} french_cursive: description: French Cursive (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{frcursive} \usepackage[eulergreek,noplusnominus,noequal,nohbar,nolessnomore,noasterisk]{mathastext} gfs_bodoni: description: GFS Bodoni compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{bodoni} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} gfs_didot: description: GFS Didot (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand\rmdefault{udidot} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi gfs_neohellenic: description: GFS NeoHellenic compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{neohellenic} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} gnu_freesans_tx: description: GNU FreeSerif (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \usepackage{txfonts} \setmainfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSerifBold,ItalicFont=FreeSerifItalic,BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \usepackage[defaultmathsizes]{mathastext} gnu_freeserif_freesans: description: GNU FreeSerif and FreeSans compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSerifBold,ItalicFont=FreeSerifItalic,BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \setsansfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSansBold,ItalicFont=FreeSansOblique,BoldItalicFont=FreeSansBoldOblique,Scale=MatchLowercase]{FreeSans} \renewcommand{\familydefault}{lmss} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\familydefault}{\sfdefault} \Mathastext \let\varphi\phi \renewcommand{\familydefault}{\rmdefault} helvetica_fourier_it: description: Helvetica with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[scaled]{helvet} \usepackage{fourier} \renewcommand{\rmdefault}{phv} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} latin_modern_tw: description: Latin Modern Typewriter Proportional compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[variablett]{lmodern} \renewcommand{\rmdefault}{\ttdefault} \usepackage[LGRgreek]{mathastext} \MTgreekfont{lmtt} \Mathastext \let\varepsilon\epsilon latin_modern_tw_it: description: Latin Modern Typewriter Proportional (CM Greek) (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[variablett,nomath]{lmodern} \renewcommand{\familydefault}{\ttdefault} \usepackage[frenchmath]{mathastext} \linespread{1.08} libertine: description: Libertine compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{libertine} \usepackage[greek=n]{libgreek} \usepackage[noasterisk,defaultmathsizes]{mathastext} libris_adf_fourier: description: Libris ADF with Fourier compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{libris} \renewcommand{\familydefault}{\sfdefault} \usepackage[noasterisk]{mathastext} minion_pro_myriad_pro: description: Minion Pro and Myriad Pro (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidserif} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon minion_pro_tx: description: Minion Pro (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \usepackage[defaultmathsizes]{mathastext} new_century_schoolbook: description: New Century Schoolbook (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{newcent} \usepackage[symbolgreek]{mathastext} \linespread{1.1} new_century_schoolbook_px: description: New Century Schoolbook (Symbol Greek, PX math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage{newcent} \usepackage[symbolgreek,defaultmathsizes]{mathastext} \linespread{1.06} noteworthy_light: description: Noteworthy Light compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Noteworthy Light} \usepackage[defaultmathsizes]{mathastext} palatino: description: Palatino (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{palatino} \usepackage[symbolmax,defaultmathsizes]{mathastext} papyrus: description: Papyrus compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Papyrus} \usepackage[defaultmathsizes]{mathastext} romande_adf_fourier_it: description: Romande ADF with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{fourier} \usepackage{romande} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\itshape}{\swashstyle} slitex: description: SliTeX (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{tpslifonts} \usepackage[eulergreek,defaultmathsizes]{mathastext} \MTEulerScale{1.06} \linespread{1.2} times_fourier_it: description: Times with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \renewcommand{\rmdefault}{ptm} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} urw_avant_garde: description: URW Avant Garde (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{avant} \renewcommand{\familydefault}{\sfdefault} \usepackage[symbolgreek,defaultmathsizes]{mathastext} urw_zapf_chancery: description: URW Zapf Chancery (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{mb}{sl}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{m}{sl}{<->ssub * pzc/mb/sl}{} \DeclareFontShape{T1}{pzc}{m}{n}{<->ssub * pzc/mb/it}{} \usepackage{chancery} \usepackage{mathastext} \linespread{1.05} \boldmath venturis_adf_fourier_it: description: Venturis ADF with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \usepackage[lf]{venturis} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} verdana_it: description: Verdana (Italic) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Verdana} \usepackage[defaultmathsizes,italic]{mathastext} vollkorn: description: Vollkorn (TX fonts for Greek and math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage{vollkorn} \usepackage[defaultmathsizes]{mathastext} vollkorn_fourier_it: description: Vollkorn with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \usepackage{vollkorn} \usepackage[italic,nohbar]{mathastext} zapf_chancery: description: Zapf Chancery compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \usepackage{chancery} \renewcommand\shapedefault\itdefault \renewcommand\bfdefault\mddefault \usepackage[defaultmathsizes]{mathastext} \linespread{1.05}
manim_3b1b/manimlib/window.py
from __future__ import annotations import numpy as np import moderngl_window as mglw from moderngl_window.context.pyglet.window import Window as PygletWindow from moderngl_window.timers.clock import Timer from screeninfo import get_monitors from manimlib.constants import FRAME_SHAPE from manimlib.utils.customization import get_customization from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.scene.scene import Scene class Window(PygletWindow): fullscreen: bool = False resizable: bool = True gl_version: tuple[int, int] = (3, 3) vsync: bool = True cursor: bool = True def __init__( self, scene: Scene, size: tuple[int, int] = (1280, 720), samples: int = 0 ): scene.window = self super().__init__(size=size, samples=samples) self.default_size = size self.default_position = self.find_initial_position(size) self.scene = scene self.pressed_keys = set() self.title = str(scene) self.size = size mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.to_default_position() def to_default_position(self): self.position = self.default_position # Hack. Sometimes, namely when configured to open in a separate window, # the window needs to be resized to display correctly. w, h = self.default_size self.size = (w - 1, h - 1) self.size = (w, h) def find_initial_position(self, size: tuple[int, int]) -> tuple[int, int]: custom_position = get_customization()["window_position"] monitors = get_monitors() mon_index = get_customization()["window_monitor"] monitor = monitors[min(mon_index, len(monitors) - 1)] window_width, window_height = size # Position might be specified with a string of the form # x,y for integers x and y if "," in custom_position: return tuple(map(int, custom_position.split(","))) # Alternatively, it might be specified with a string like # UR, OO, DL, etc. specifying what corner it should go to char_to_n = {"L": 0, "U": 0, "O": 1, "R": 2, "D": 2} width_diff = monitor.width - window_width height_diff = monitor.height - window_height return ( monitor.x + char_to_n[custom_position[1]] * width_diff // 2, -monitor.y + char_to_n[custom_position[0]] * height_diff // 2, ) # Delegate event handling to scene def pixel_coords_to_space_coords( self, px: int, py: int, relative: bool = False ) -> np.ndarray: if not hasattr(self.scene, "frame"): return np.zeros(3) pixel_shape = np.array(self.size) fixed_frame_shape = np.array(FRAME_SHAPE) frame = self.scene.frame coords = np.zeros(3) coords[:2] = (fixed_frame_shape / pixel_shape) * np.array([px, py]) if not relative: coords[:2] -= 0.5 * fixed_frame_shape return frame.from_fixed_frame_point(coords, relative) def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> None: super().on_mouse_motion(x, y, dx, dy) point = self.pixel_coords_to_space_coords(x, y) d_point = self.pixel_coords_to_space_coords(dx, dy, relative=True) self.scene.on_mouse_motion(point, d_point) def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int) -> None: super().on_mouse_drag(x, y, dx, dy, buttons, modifiers) point = self.pixel_coords_to_space_coords(x, y) d_point = self.pixel_coords_to_space_coords(dx, dy, relative=True) self.scene.on_mouse_drag(point, d_point, buttons, modifiers) def on_mouse_press(self, x: int, y: int, button: int, mods: int) -> None: super().on_mouse_press(x, y, button, mods) point = self.pixel_coords_to_space_coords(x, y) self.scene.on_mouse_press(point, button, mods) def on_mouse_release(self, x: int, y: int, button: int, mods: int) -> None: super().on_mouse_release(x, y, button, mods) point = self.pixel_coords_to_space_coords(x, y) self.scene.on_mouse_release(point, button, mods) def on_mouse_scroll(self, x: int, y: int, x_offset: float, y_offset: float) -> None: super().on_mouse_scroll(x, y, x_offset, y_offset) point = self.pixel_coords_to_space_coords(x, y) offset = self.pixel_coords_to_space_coords(x_offset, y_offset, relative=True) self.scene.on_mouse_scroll(point, offset, x_offset, y_offset) def on_key_press(self, symbol: int, modifiers: int) -> None: self.pressed_keys.add(symbol) # Modifiers? super().on_key_press(symbol, modifiers) self.scene.on_key_press(symbol, modifiers) def on_key_release(self, symbol: int, modifiers: int) -> None: self.pressed_keys.difference_update({symbol}) # Modifiers? super().on_key_release(symbol, modifiers) self.scene.on_key_release(symbol, modifiers) def on_resize(self, width: int, height: int) -> None: super().on_resize(width, height) self.scene.on_resize(width, height) def on_show(self) -> None: super().on_show() self.scene.on_show() def on_hide(self) -> None: super().on_hide() self.scene.on_hide() def on_close(self) -> None: super().on_close() self.scene.on_close() def is_key_pressed(self, symbol: int) -> bool: return (symbol in self.pressed_keys)
manim_3b1b/manimlib/extract_scene.py
import copy import inspect import sys from manimlib.config import get_custom_config from manimlib.logger import log from manimlib.scene.interactive_scene import InteractiveScene from manimlib.scene.scene import Scene class BlankScene(InteractiveScene): def construct(self): exec(get_custom_config()["universal_import_line"]) self.embed() def is_child_scene(obj, module): if not inspect.isclass(obj): return False if not issubclass(obj, Scene): return False if obj == Scene: return False if not obj.__module__.startswith(module.__name__): return False return True def prompt_user_for_choice(scene_classes): name_to_class = {} max_digits = len(str(len(scene_classes))) for idx, scene_class in enumerate(scene_classes, start=1): name = scene_class.__name__ print(f"{str(idx).zfill(max_digits)}: {name}") name_to_class[name] = scene_class try: user_input = input( "\nThat module has multiple scenes, " + \ "which ones would you like to render?" + \ "\nScene Name or Number: " ) return [ name_to_class[split_str] if not split_str.isnumeric() else scene_classes[int(split_str) - 1] for split_str in user_input.replace(" ", "").split(",") ] except IndexError: log.error("Invalid scene number") sys.exit(2) except KeyError: log.error("Invalid scene name") sys.exit(2) except EOFError: sys.exit(1) def get_scene_config(config): scene_parameters = inspect.signature(Scene).parameters.keys() return { key: config[key] for key in set(scene_parameters).intersection(config.keys()) } def compute_total_frames(scene_class, scene_config): """ When a scene is being written to file, a copy of the scene is run with skip_animations set to true so as to count how many frames it will require. This allows for a total progress bar on rendering, and also allows runtime errors to be exposed preemptively for long running scenes. """ pre_config = copy.deepcopy(scene_config) pre_config["file_writer_config"]["write_to_movie"] = False pre_config["file_writer_config"]["save_last_frame"] = False pre_config["file_writer_config"]["quiet"] = True pre_config["skip_animations"] = True pre_scene = scene_class(**pre_config) pre_scene.run() total_time = pre_scene.time - pre_scene.skip_time return int(total_time * scene_config["camera_config"]["fps"]) def scene_from_class(scene_class, scene_config, config): fw_config = scene_config["file_writer_config"] if fw_config["write_to_movie"] and config["prerun"]: fw_config["total_frames"] = compute_total_frames(scene_class, scene_config) return scene_class(**scene_config) def get_scenes_to_render(all_scene_classes, scene_config, config): if config["write_all"]: return [sc(**scene_config) for sc in all_scene_classes] names_to_classes = {sc.__name__ : sc for sc in all_scene_classes} scene_names = config["scene_names"] for name in set.difference(set(scene_names), names_to_classes): log.error(f"No scene named {name} found") scene_names.remove(name) if scene_names: classes_to_run = [names_to_classes[name] for name in scene_names] elif len(all_scene_classes) == 1: classes_to_run = [all_scene_classes[0]] else: classes_to_run = prompt_user_for_choice(all_scene_classes) return [ scene_from_class(scene_class, scene_config, config) for scene_class in classes_to_run ] def get_scene_classes_from_module(module): if hasattr(module, "SCENES_IN_ORDER"): return module.SCENES_IN_ORDER else: return [ member[1] for member in inspect.getmembers( module, lambda x: is_child_scene(x, module) ) ] def main(config): module = config["module"] scene_config = get_scene_config(config) if module is None: # If no module was passed in, just play the blank scene return [BlankScene(**scene_config)] all_scene_classes = get_scene_classes_from_module(module) scenes = get_scenes_to_render(all_scene_classes, scene_config, config) return scenes
manim_3b1b/manimlib/logger.py
import logging from rich.logging import RichHandler __all__ = ["log"] FORMAT = "%(message)s" logging.basicConfig( level=logging.WARNING, format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] ) log = logging.getLogger("manimgl") log.setLevel("DEBUG")
manim_3b1b/manimlib/scene/__init__.py
manim_3b1b/manimlib/scene/interactive_scene.py
from __future__ import annotations import itertools as it import numpy as np import pyperclip from IPython.core.getipython import get_ipython from manimlib.animation.fading import FadeIn from manimlib.constants import ARROW_SYMBOLS, CTRL_SYMBOL, DELETE_SYMBOL, SHIFT_SYMBOL from manimlib.constants import COMMAND_MODIFIER, SHIFT_MODIFIER from manimlib.constants import DL, DOWN, DR, LEFT, ORIGIN, RIGHT, UL, UP, UR from manimlib.constants import FRAME_WIDTH, FRAME_HEIGHT, SMALL_BUFF from manimlib.constants import PI from manimlib.constants import DEGREES from manimlib.constants import MANIM_COLORS, WHITE, GREY_A, GREY_C from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.dot_cloud import DotCloud from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VHighlight from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene import Scene from manimlib.scene.scene import SceneState from manimlib.scene.scene import PAN_3D_KEY from manimlib.utils.family_ops import extract_mobject_family_members from manimlib.utils.space_ops import get_norm from manimlib.utils.tex_file_writing import LatexError from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Vect3 SELECT_KEY = 's' UNSELECT_KEY = 'u' GRAB_KEY = 'g' X_GRAB_KEY = 'h' Y_GRAB_KEY = 'v' GRAB_KEYS = [GRAB_KEY, X_GRAB_KEY, Y_GRAB_KEY] RESIZE_KEY = 't' COLOR_KEY = 'c' INFORMATION_KEY = 'i' CURSOR_KEY = 'k' # Note, a lot of the functionality here is still buggy and very much a work in progress. class InteractiveScene(Scene): """ To select mobjects on screen, hold ctrl and move the mouse to highlight a region, or just tap ctrl to select the mobject under the cursor. Pressing command + t will toggle between modes where you either select top level mobjects part of the scene, or low level pieces. Hold 'g' to grab the selection and move it around Hold 'h' to drag it constrained in the horizontal direction Hold 'v' to drag it constrained in the vertical direction Hold 't' to resize selection, adding 'shift' to resize with respect to a corner Command + 'c' copies the ids of selections to clipboard Command + 'v' will paste either: - The copied mobject - A Tex mobject based on copied LaTeX - A Text mobject based on copied Text Command + 'z' restores selection back to its original state Command + 's' saves the selected mobjects to file """ corner_dot_config = dict( color=WHITE, radius=0.05, glow_factor=2.0, ) selection_rectangle_stroke_color = WHITE selection_rectangle_stroke_width = 1.0 palette_colors = MANIM_COLORS selection_nudge_size = 0.05 cursor_location_config = dict( font_size=24, fill_color=GREY_C, num_decimal_places=3, ) time_label_config = dict( font_size=24, fill_color=GREY_C, num_decimal_places=1, ) crosshair_width = 0.2 crosshair_style = dict( stroke_color=GREY_A, stroke_width=[3, 0, 3], ) def setup(self): self.selection = Group() self.selection_highlight = self.get_selection_highlight() self.selection_rectangle = self.get_selection_rectangle() self.crosshair = self.get_crosshair() self.information_label = self.get_information_label() self.color_palette = self.get_color_palette() self.unselectables = [ self.selection, self.selection_highlight, self.selection_rectangle, self.crosshair, self.information_label, self.camera.frame ] self.select_top_level_mobs = True self.regenerate_selection_search_set() self.is_selecting = False self.is_grabbing = False self.add(self.selection_highlight) def get_selection_rectangle(self): rect = Rectangle( stroke_color=self.selection_rectangle_stroke_color, stroke_width=self.selection_rectangle_stroke_width, ) rect.fix_in_frame() rect.fixed_corner = ORIGIN rect.add_updater(self.update_selection_rectangle) return rect def update_selection_rectangle(self, rect: Rectangle): p1 = rect.fixed_corner p2 = self.frame.to_fixed_frame_point(self.mouse_point.get_center()) rect.set_points_as_corners([ p1, np.array([p2[0], p1[1], 0]), p2, np.array([p1[0], p2[1], 0]), p1, ]) return rect def get_selection_highlight(self): result = Group() result.tracked_mobjects = [] result.add_updater(self.update_selection_highlight) return result def update_selection_highlight(self, highlight: Mobject): if set(highlight.tracked_mobjects) == set(self.selection): return # Otherwise, refresh contents of highlight highlight.tracked_mobjects = list(self.selection) highlight.set_submobjects([ self.get_highlight(mob) for mob in self.selection ]) try: index = min(( i for i, mob in enumerate(self.mobjects) for sm in self.selection if sm in mob.get_family() )) self.mobjects.remove(highlight) self.mobjects.insert(index - 1, highlight) except ValueError: pass def get_crosshair(self): lines = VMobject().replicate(2) lines[0].set_points([LEFT, ORIGIN, RIGHT]) lines[1].set_points([UP, ORIGIN, DOWN]) crosshair = VGroup(*lines) crosshair.set_width(self.crosshair_width) crosshair.set_style(**self.crosshair_style) crosshair.set_animating_status(True) crosshair.fix_in_frame() return crosshair def get_color_palette(self): palette = VGroup(*( Square(fill_color=color, fill_opacity=1, side_length=1) for color in self.palette_colors )) palette.set_stroke(width=0) palette.arrange(RIGHT, buff=0.5) palette.set_width(FRAME_WIDTH - 0.5) palette.to_edge(DOWN, buff=SMALL_BUFF) palette.fix_in_frame() return palette def get_information_label(self): loc_label = VGroup(*( DecimalNumber(**self.cursor_location_config) for n in range(3) )) def update_coords(loc_label): for mob, coord in zip(loc_label, self.mouse_point.get_location()): mob.set_value(coord) loc_label.arrange(RIGHT, buff=loc_label.get_height()) loc_label.to_corner(DR, buff=SMALL_BUFF) loc_label.fix_in_frame() return loc_label loc_label.add_updater(update_coords) time_label = DecimalNumber(0, **self.time_label_config) time_label.to_corner(DL, buff=SMALL_BUFF) time_label.fix_in_frame() time_label.add_updater(lambda m, dt: m.increment_value(dt)) return VGroup(loc_label, time_label) # Overrides def get_state(self): return SceneState(self, ignore=[ self.selection_highlight, self.selection_rectangle, self.crosshair, ]) def restore_state(self, scene_state: SceneState): super().restore_state(scene_state) self.mobjects.insert(0, self.selection_highlight) def add(self, *mobjects: Mobject): super().add(*mobjects) self.regenerate_selection_search_set() def remove(self, *mobjects: Mobject): super().remove(*mobjects) self.regenerate_selection_search_set() # Related to selection def toggle_selection_mode(self): self.select_top_level_mobs = not self.select_top_level_mobs self.refresh_selection_scope() self.regenerate_selection_search_set() def get_selection_search_set(self) -> list[Mobject]: return self.selection_search_set def regenerate_selection_search_set(self): selectable = list(filter( lambda m: m not in self.unselectables, self.mobjects )) if self.select_top_level_mobs: self.selection_search_set = selectable else: self.selection_search_set = [ submob for mob in selectable for submob in mob.family_members_with_points() ] def refresh_selection_scope(self): curr = list(self.selection) if self.select_top_level_mobs: self.selection.set_submobjects([ mob for mob in self.mobjects if any(sm in mob.get_family() for sm in curr) ]) self.selection.refresh_bounding_box(recurse_down=True) else: self.selection.set_submobjects( extract_mobject_family_members( curr, exclude_pointless=True, ) ) def get_corner_dots(self, mobject: Mobject) -> Mobject: dots = DotCloud(**self.corner_dot_config) radius = float(self.corner_dot_config["radius"]) if mobject.get_depth() < 1e-2: vects = [DL, UL, UR, DR] else: vects = np.array(list(it.product(*3 * [[-1, 1]]))) dots.add_updater(lambda d: d.set_points([ mobject.get_corner(v) + v * radius for v in vects ])) return dots def get_highlight(self, mobject: Mobject) -> Mobject: if isinstance(mobject, VMobject) and mobject.has_points() and not self.select_top_level_mobs: length = max([mobject.get_height(), mobject.get_width()]) result = VHighlight( mobject, max_stroke_addition=min([50 * length, 10]), ) result.add_updater(lambda m: m.replace(mobject, stretch=True)) return result elif isinstance(mobject, DotCloud): return Mobject() else: return self.get_corner_dots(mobject) def add_to_selection(self, *mobjects: Mobject): mobs = list(filter( lambda m: m not in self.unselectables and m not in self.selection, mobjects )) if len(mobs) == 0: return self.selection.add(*mobs) for mob in mobs: mob.set_animating_status(True) def toggle_from_selection(self, *mobjects: Mobject): for mob in mobjects: if mob in self.selection: self.selection.remove(mob) mob.set_animating_status(False) mob.refresh_bounding_box() else: self.add_to_selection(mob) def clear_selection(self): for mob in self.selection: mob.set_animating_status(False) mob.refresh_bounding_box() self.selection.set_submobjects([]) def disable_interaction(self, *mobjects: Mobject): for mob in mobjects: for sm in mob.get_family(): self.unselectables.append(sm) self.regenerate_selection_search_set() def enable_interaction(self, *mobjects: Mobject): for mob in mobjects: for sm in mob.get_family(): if sm in self.unselectables: self.unselectables.remove(sm) # Functions for keyboard actions def copy_selection(self): names = [] shell = get_ipython() for mob in self.selection: name = str(id(mob)) if shell is None: continue for key, value in shell.user_ns.items(): if mob is value: name = key names.append(name) pyperclip.copy(", ".join(names)) def paste_selection(self): clipboard_str = pyperclip.paste() # Try pasting a mobject try: ids = map(int, clipboard_str.split(",")) mobs = map(self.id_to_mobject, ids) mob_copies = [m.copy() for m in mobs if m is not None] self.clear_selection() self.play(*( FadeIn(mc, run_time=0.5, scale=1.5) for mc in mob_copies )) self.add_to_selection(*mob_copies) return except ValueError: pass # Otherwise, treat as tex or text if set("\\^=+").intersection(clipboard_str): # Proxy to text for LaTeX try: new_mob = Tex(clipboard_str) except LatexError: return else: new_mob = Text(clipboard_str) self.clear_selection() self.add(new_mob) self.add_to_selection(new_mob) def delete_selection(self): self.remove(*self.selection) self.clear_selection() def enable_selection(self): self.is_selecting = True self.add(self.selection_rectangle) self.selection_rectangle.fixed_corner = self.frame.to_fixed_frame_point( self.mouse_point.get_center() ) def gather_new_selection(self): self.is_selecting = False if self.selection_rectangle in self.mobjects: self.remove(self.selection_rectangle) additions = [] for mob in reversed(self.get_selection_search_set()): if self.selection_rectangle.is_touching(mob): additions.append(mob) if self.selection_rectangle.get_arc_length() < 1e-2: break self.toggle_from_selection(*additions) def prepare_grab(self): mp = self.mouse_point.get_center() self.mouse_to_selection = mp - self.selection.get_center() self.is_grabbing = True def prepare_resizing(self, about_corner=False): center = self.selection.get_center() mp = self.mouse_point.get_center() if about_corner: self.scale_about_point = self.selection.get_corner(center - mp) else: self.scale_about_point = center self.scale_ref_vect = mp - self.scale_about_point self.scale_ref_width = self.selection.get_width() self.scale_ref_height = self.selection.get_height() def toggle_color_palette(self): if len(self.selection) == 0: return if self.color_palette not in self.mobjects: self.save_state() self.add(self.color_palette) else: self.remove(self.color_palette) def display_information(self, show=True): if show: self.add(self.information_label) else: self.remove(self.information_label) def group_selection(self): group = self.get_group(*self.selection) self.add(group) self.clear_selection() self.add_to_selection(group) def ungroup_selection(self): pieces = [] for mob in list(self.selection): self.remove(mob) pieces.extend(list(mob)) self.clear_selection() self.add(*pieces) self.add_to_selection(*pieces) def nudge_selection(self, vect: np.ndarray, large: bool = False): nudge = self.selection_nudge_size if large: nudge *= 10 self.selection.shift(nudge * vect) def save_selection_to_file(self): if len(self.selection) == 1: self.save_mobject_to_file(self.selection[0]) else: self.save_mobject_to_file(self.selection) # Key actions def on_key_press(self, symbol: int, modifiers: int) -> None: super().on_key_press(symbol, modifiers) char = chr(symbol) if char == SELECT_KEY and modifiers == 0: self.enable_selection() if char == UNSELECT_KEY: self.clear_selection() elif char in GRAB_KEYS and modifiers == 0: self.prepare_grab() elif char == RESIZE_KEY and modifiers in [0, SHIFT_MODIFIER]: self.prepare_resizing(about_corner=(modifiers == SHIFT_MODIFIER)) elif symbol == SHIFT_SYMBOL: if self.window.is_key_pressed(ord("t")): self.prepare_resizing(about_corner=True) elif char == COLOR_KEY and modifiers == 0: self.toggle_color_palette() elif char == INFORMATION_KEY and modifiers == 0: self.display_information() elif char == "c" and modifiers == COMMAND_MODIFIER: self.copy_selection() elif char == "v" and modifiers == COMMAND_MODIFIER: self.paste_selection() elif char == "x" and modifiers == COMMAND_MODIFIER: self.copy_selection() self.delete_selection() elif symbol == DELETE_SYMBOL: self.delete_selection() elif char == "a" and modifiers == COMMAND_MODIFIER: self.clear_selection() self.add_to_selection(*self.mobjects) elif char == "g" and modifiers == COMMAND_MODIFIER: self.group_selection() elif char == "g" and modifiers == COMMAND_MODIFIER | SHIFT_MODIFIER: self.ungroup_selection() elif char == "t" and modifiers == COMMAND_MODIFIER: self.toggle_selection_mode() elif char == "s" and modifiers == COMMAND_MODIFIER: self.save_selection_to_file() elif char == PAN_3D_KEY and modifiers == COMMAND_MODIFIER: self.copy_frame_anim_call() elif symbol in ARROW_SYMBOLS: self.nudge_selection( vect=[LEFT, UP, RIGHT, DOWN][ARROW_SYMBOLS.index(symbol)], large=(modifiers & SHIFT_MODIFIER), ) # Adding crosshair if char == CURSOR_KEY: if self.crosshair in self.mobjects: self.remove(self.crosshair) else: self.add(self.crosshair) if char == SELECT_KEY: self.add(self.crosshair) # Conditions for saving state if char in [GRAB_KEY, X_GRAB_KEY, Y_GRAB_KEY, RESIZE_KEY]: self.save_state() def on_key_release(self, symbol: int, modifiers: int) -> None: super().on_key_release(symbol, modifiers) if chr(symbol) == SELECT_KEY: self.gather_new_selection() if chr(symbol) in GRAB_KEYS: self.is_grabbing = False elif chr(symbol) == INFORMATION_KEY: self.display_information(False) elif symbol == SHIFT_SYMBOL and self.window.is_key_pressed(ord(RESIZE_KEY)): self.prepare_resizing(about_corner=False) # Mouse actions def handle_grabbing(self, point: Vect3): diff = point - self.mouse_to_selection if self.window.is_key_pressed(ord(GRAB_KEY)): self.selection.move_to(diff) elif self.window.is_key_pressed(ord(X_GRAB_KEY)): self.selection.set_x(diff[0]) elif self.window.is_key_pressed(ord(Y_GRAB_KEY)): self.selection.set_y(diff[1]) def handle_resizing(self, point: Vect3): if not hasattr(self, "scale_about_point"): return vect = point - self.scale_about_point if self.window.is_key_pressed(CTRL_SYMBOL): for i in (0, 1): scalar = vect[i] / self.scale_ref_vect[i] self.selection.rescale_to_fit( scalar * [self.scale_ref_width, self.scale_ref_height][i], dim=i, about_point=self.scale_about_point, stretch=True, ) else: scalar = get_norm(vect) / get_norm(self.scale_ref_vect) self.selection.set_width( scalar * self.scale_ref_width, about_point=self.scale_about_point ) def handle_sweeping_selection(self, point: Vect3): mob = self.point_to_mobject( point, search_set=self.get_selection_search_set(), buff=SMALL_BUFF ) if mob is not None: self.add_to_selection(mob) def choose_color(self, point: Vect3): # Search through all mobject on the screen, not just the palette to_search = [ sm for mobject in self.mobjects for sm in mobject.family_members_with_points() if mobject not in self.unselectables ] mob = self.point_to_mobject(point, to_search) if mob is not None: self.selection.set_color(mob.get_color()) self.remove(self.color_palette) def on_mouse_motion(self, point: Vect3, d_point: Vect3) -> None: super().on_mouse_motion(point, d_point) self.crosshair.move_to(self.frame.to_fixed_frame_point(point)) if self.is_grabbing: self.handle_grabbing(point) elif self.window.is_key_pressed(ord(RESIZE_KEY)): self.handle_resizing(point) elif self.window.is_key_pressed(ord(SELECT_KEY)) and self.window.is_key_pressed(SHIFT_SYMBOL): self.handle_sweeping_selection(point) def on_mouse_drag( self, point: Vect3, d_point: Vect3, buttons: int, modifiers: int ) -> None: super().on_mouse_drag(point, d_point, buttons, modifiers) self.crosshair.move_to(self.frame.to_fixed_frame_point(point)) def on_mouse_release(self, point: Vect3, button: int, mods: int) -> None: super().on_mouse_release(point, button, mods) if self.color_palette in self.mobjects: self.choose_color(point) else: self.clear_selection() # Copying code to recreate state def copy_frame_anim_call(self): frame = self.frame center = frame.get_center() height = frame.get_height() angles = frame.get_euler_angles() call = f"self.frame.animate.reorient" call += str(tuple((angles / DEGREES).astype(int))) if any(center != 0): call += f".move_to({list(np.round(center, 2))})" if height != FRAME_HEIGHT: call += ".set_height({:.2f})".format(height) pyperclip.copy(call)
manim_3b1b/manimlib/scene/scene.py
from __future__ import annotations from collections import OrderedDict import inspect import os import platform import pyperclip import random import time from functools import wraps from IPython.terminal import pt_inputhooks from IPython.terminal.embed import InteractiveShellEmbed from IPython.core.getipython import get_ipython import numpy as np from tqdm.auto import tqdm as ProgressDisplay from manimlib.animation.animation import prepare_animation from manimlib.animation.fading import VFadeInThenOut from manimlib.camera.camera import Camera from manimlib.camera.camera_frame import CameraFrame from manimlib.config import get_module from manimlib.constants import ARROW_SYMBOLS from manimlib.constants import DEFAULT_WAIT_TIME from manimlib.constants import COMMAND_MODIFIER from manimlib.constants import SHIFT_MODIFIER from manimlib.constants import RED from manimlib.event_handler import EVENT_DISPATCHER from manimlib.event_handler.event_type import EventType from manimlib.logger import log from manimlib.mobject.frame import FullScreenRectangle from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.mobject import Point from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene_file_writer import SceneFileWriter from manimlib.utils.family_ops import extract_mobject_family_members from manimlib.utils.family_ops import recursive_mobject_remove from manimlib.utils.iterables import batch_by_property from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable from manimlib.typing import Vect3 from PIL.Image import Image from manimlib.animation.animation import Animation PAN_3D_KEY = 'd' FRAME_SHIFT_KEY = 'f' RESET_FRAME_KEY = 'r' QUIT_KEY = 'q' class Scene(object): random_seed: int = 0 pan_sensitivity: float = 0.5 scroll_sensitivity: float = 20 drag_to_pan: bool = True max_num_saved_states: int = 50 default_camera_config: dict = dict() default_window_config: dict = dict() default_file_writer_config: dict = dict() samples = 0 # Euler angles, in degrees default_frame_orientation = (0, 0) def __init__( self, window_config: dict = dict(), camera_config: dict = dict(), file_writer_config: dict = dict(), skip_animations: bool = False, always_update_mobjects: bool = False, start_at_animation_number: int | None = None, end_at_animation_number: int | None = None, leave_progress_bars: bool = False, preview: bool = True, presenter_mode: bool = False, show_animation_progress: bool = False, embed_exception_mode: str = "", embed_error_sound: bool = False, ): self.skip_animations = skip_animations self.always_update_mobjects = always_update_mobjects self.start_at_animation_number = start_at_animation_number self.end_at_animation_number = end_at_animation_number self.leave_progress_bars = leave_progress_bars self.preview = preview self.presenter_mode = presenter_mode self.show_animation_progress = show_animation_progress self.embed_exception_mode = embed_exception_mode self.embed_error_sound = embed_error_sound self.camera_config = {**self.default_camera_config, **camera_config} self.window_config = {**self.default_window_config, **window_config} for config in self.camera_config, self.window_config: config["samples"] = self.samples self.file_writer_config = {**self.default_file_writer_config, **file_writer_config} # Initialize window, if applicable if self.preview: from manimlib.window import Window self.window = Window(scene=self, **self.window_config) self.camera_config["window"] = self.window self.camera_config["fps"] = 30 # Where's that 30 from? else: self.window = None # Core state of the scene self.camera: Camera = Camera(**self.camera_config) self.frame: CameraFrame = self.camera.frame self.frame.reorient(*self.default_frame_orientation) self.frame.make_orientation_default() self.file_writer = SceneFileWriter(self, **self.file_writer_config) self.mobjects: list[Mobject] = [self.camera.frame] self.render_groups: list[Mobject] = [] self.id_to_mobject_map: dict[int, Mobject] = dict() self.num_plays: int = 0 self.time: float = 0 self.skip_time: float = 0 self.original_skipping_status: bool = self.skip_animations self.checkpoint_states: dict[str, list[tuple[Mobject, Mobject]]] = dict() self.undo_stack = [] self.redo_stack = [] if self.start_at_animation_number is not None: self.skip_animations = True if self.file_writer.has_progress_display(): self.show_animation_progress = False # Items associated with interaction self.mouse_point = Point() self.mouse_drag_point = Point() self.hold_on_wait = self.presenter_mode self.quit_interaction = False # Much nicer to work with deterministic scenes if self.random_seed is not None: random.seed(self.random_seed) np.random.seed(self.random_seed) def __str__(self) -> str: return self.__class__.__name__ def run(self) -> None: self.virtual_animation_start_time: float = 0 self.real_animation_start_time: float = time.time() self.file_writer.begin() self.setup() try: self.construct() self.interact() except EndScene: pass except KeyboardInterrupt: # Get rid keyboard interupt symbols print("", end="\r") self.file_writer.ended_with_interrupt = True self.tear_down() def setup(self) -> None: """ This is meant to be implement by any scenes which are comonly subclassed, and have some common setup involved before the construct method is called. """ pass def construct(self) -> None: # Where all the animation happens # To be implemented in subclasses pass def tear_down(self) -> None: self.stop_skipping() self.file_writer.finish() if self.window: self.window.destroy() self.window = None def interact(self) -> None: """ If there is a window, enter a loop which updates the frame while under the hood calling the pyglet event loop """ if self.window is None: return log.info( "\nTips: Using the keys `d`, `f`, or `z` " + "you can interact with the scene. " + "Press `command + q` or `esc` to quit" ) self.skip_animations = False while not self.is_window_closing(): self.update_frame(1 / self.camera.fps) def embed( self, close_scene_on_exit: bool = True, show_animation_progress: bool = False, ) -> None: if not self.preview: return # Embed is only relevant with a preview self.stop_skipping() self.update_frame() self.save_state() self.show_animation_progress = show_animation_progress # Create embedded IPython terminal to be configured shell = InteractiveShellEmbed.instance() # Use the locals namespace of the caller caller_frame = inspect.currentframe().f_back local_ns = dict(caller_frame.f_locals) # Add a few custom shortcuts local_ns.update( play=self.play, wait=self.wait, add=self.add, remove=self.remove, clear=self.clear, save_state=self.save_state, undo=self.undo, redo=self.redo, i2g=self.i2g, i2m=self.i2m, checkpoint_paste=self.checkpoint_paste, ) # Enables gui interactions during the embed def inputhook(context): while not context.input_is_ready(): if not self.is_window_closing(): self.update_frame(dt=0) if self.is_window_closing(): shell.ask_exit() pt_inputhooks.register("manim", inputhook) shell.enable_gui("manim") # This is hacky, but there's an issue with ipython which is that # when you define lambda's or list comprehensions during a shell session, # they are not aware of local variables in the surrounding scope. Because # That comes up a fair bit during scene construction, to get around this, # we (admittedly sketchily) update the global namespace to match the local # namespace, since this is just a shell session anyway. shell.events.register( "pre_run_cell", lambda: shell.user_global_ns.update(shell.user_ns) ) # Operation to run after each ipython command def post_cell_func(): if not self.is_window_closing(): self.update_frame(dt=0, ignore_skipping=True) self.save_state() shell.events.register("post_run_cell", post_cell_func) # Flash border, and potentially play sound, on exceptions def custom_exc(shell, etype, evalue, tb, tb_offset=None): # still show the error don't just swallow it shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) if self.embed_error_sound: os.system("printf '\a'") rect = FullScreenRectangle().set_stroke(RED, 30).set_fill(opacity=0) rect.fix_in_frame() self.play(VFadeInThenOut(rect, run_time=0.5)) shell.set_custom_exc((Exception,), custom_exc) # Set desired exception mode shell.magic(f"xmode {self.embed_exception_mode}") # Launch shell shell( local_ns=local_ns, # Pretend like we're embeding in the caller function, not here stack_depth=2, # Specify that the present module is the caller's, not here module=get_module(caller_frame.f_globals["__file__"]) ) # End scene when exiting an embed if close_scene_on_exit: raise EndScene() # Only these methods should touch the camera def get_image(self) -> Image: if self.window is not None: self.camera.use_window_fbo(False) self.camera.capture(*self.render_groups) image = self.camera.get_image() if self.window is not None: self.camera.use_window_fbo(True) return image def show(self) -> None: self.update_frame(ignore_skipping=True) self.get_image().show() def update_frame(self, dt: float = 0, ignore_skipping: bool = False) -> None: self.increment_time(dt) self.update_mobjects(dt) if self.skip_animations and not ignore_skipping: return if self.is_window_closing(): raise EndScene() if self.window: self.window.clear() self.camera.capture(*self.render_groups) if self.window: self.window.swap_buffers() vt = self.time - self.virtual_animation_start_time rt = time.time() - self.real_animation_start_time if rt < vt: self.update_frame(0) def emit_frame(self) -> None: if not self.skip_animations: self.file_writer.write_frame(self.camera) # Related to updating def update_mobjects(self, dt: float) -> None: for mobject in self.mobjects: mobject.update(dt) def should_update_mobjects(self) -> bool: return self.always_update_mobjects or any([ len(mob.get_family_updaters()) > 0 for mob in self.mobjects ]) def has_time_based_updaters(self) -> bool: return any([ sm.has_time_based_updater() for mob in self.mobjects() for sm in mob.get_family() ]) # Related to time def get_time(self) -> float: return self.time def increment_time(self, dt: float) -> None: self.time += dt # Related to internal mobject organization def get_top_level_mobjects(self) -> list[Mobject]: # Return only those which are not in the family # of another mobject from the scene mobjects = self.get_mobjects() families = [m.get_family() for m in mobjects] def is_top_level(mobject): num_families = sum([ (mobject in family) for family in families ]) return num_families == 1 return list(filter(is_top_level, mobjects)) def get_mobject_family_members(self) -> list[Mobject]: return extract_mobject_family_members(self.mobjects) def assemble_render_groups(self): """ Rendering can be more efficient when mobjects of the same type are grouped together, so this function creates Groups of all clusters of adjacent Mobjects in the scene """ batches = batch_by_property( self.mobjects, lambda m: str(type(m)) + str(m.get_uniforms()) ) for group in self.render_groups: group.clear() self.render_groups = [ batch[0].get_group_class()(*batch) for batch, key in batches ] def affects_mobject_list(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) self.assemble_render_groups() return self return wrapper @affects_mobject_list def add(self, *new_mobjects: Mobject): """ Mobjects will be displayed, from background to foreground in the order with which they are added. """ self.remove(*new_mobjects) self.mobjects += new_mobjects self.id_to_mobject_map.update({ id(sm): sm for m in new_mobjects for sm in m.get_family() }) return self def add_mobjects_among(self, values: Iterable): """ This is meant mostly for quick prototyping, e.g. to add all mobjects defined up to a point, call self.add_mobjects_among(locals().values()) """ self.add(*filter( lambda m: isinstance(m, Mobject), values )) return self @affects_mobject_list def replace(self, mobject: Mobject, *replacements: Mobject): if mobject in self.mobjects: index = self.mobjects.index(mobject) self.mobjects = [ *self.mobjects[:index], *replacements, *self.mobjects[index + 1:] ] return self @affects_mobject_list def remove(self, *mobjects_to_remove: Mobject): """ Removes anything in mobjects from scenes mobject list, but in the event that one of the items to be removed is a member of the family of an item in mobject_list, the other family members are added back into the list. For example, if the scene includes Group(m1, m2, m3), and we call scene.remove(m1), the desired behavior is for the scene to then include m2 and m3 (ungrouped). """ to_remove = set(extract_mobject_family_members(mobjects_to_remove)) new_mobjects, _ = recursive_mobject_remove(self.mobjects, to_remove) self.mobjects = new_mobjects def bring_to_front(self, *mobjects: Mobject): self.add(*mobjects) return self @affects_mobject_list def bring_to_back(self, *mobjects: Mobject): self.remove(*mobjects) self.mobjects = list(mobjects) + self.mobjects return self @affects_mobject_list def clear(self): self.mobjects = [] return self def get_mobjects(self) -> list[Mobject]: return list(self.mobjects) def get_mobject_copies(self) -> list[Mobject]: return [m.copy() for m in self.mobjects] def point_to_mobject( self, point: np.ndarray, search_set: Iterable[Mobject] | None = None, buff: float = 0 ) -> Mobject | None: """ E.g. if clicking on the scene, this returns the top layer mobject under a given point """ if search_set is None: search_set = self.mobjects for mobject in reversed(search_set): if mobject.is_point_touching(point, buff=buff): return mobject return None def get_group(self, *mobjects): if all(isinstance(m, VMobject) for m in mobjects): return VGroup(*mobjects) else: return Group(*mobjects) def id_to_mobject(self, id_value): return self.id_to_mobject_map[id_value] def ids_to_group(self, *id_values): return self.get_group(*filter( lambda x: x is not None, map(self.id_to_mobject, id_values) )) def i2g(self, *id_values): return self.ids_to_group(*id_values) def i2m(self, id_value): return self.id_to_mobject(id_value) # Related to skipping def update_skipping_status(self) -> None: if self.start_at_animation_number is not None: if self.num_plays == self.start_at_animation_number: self.skip_time = self.time if not self.original_skipping_status: self.stop_skipping() if self.end_at_animation_number is not None: if self.num_plays >= self.end_at_animation_number: raise EndScene() def stop_skipping(self) -> None: self.virtual_animation_start_time = self.time self.skip_animations = False # Methods associated with running animations def get_time_progression( self, run_time: float, n_iterations: int | None = None, desc: str = "", override_skip_animations: bool = False ) -> list[float] | np.ndarray | ProgressDisplay: if self.skip_animations and not override_skip_animations: return [run_time] times = np.arange(0, run_time, 1 / self.camera.fps) self.file_writer.set_progress_display_description(sub_desc=desc) if self.show_animation_progress: return ProgressDisplay( times, total=n_iterations, leave=self.leave_progress_bars, ascii=True if platform.system() == 'Windows' else None, desc=desc, bar_format="{l_bar} {n_fmt:3}/{total_fmt:3} {rate_fmt}{postfix}", ) else: return times def get_run_time(self, animations: Iterable[Animation]) -> float: return np.max([animation.get_run_time() for animation in animations]) def get_animation_time_progression( self, animations: Iterable[Animation] ) -> list[float] | np.ndarray | ProgressDisplay: animations = list(animations) run_time = self.get_run_time(animations) description = f"{self.num_plays} {animations[0]}" if len(animations) > 1: description += ", etc." time_progression = self.get_time_progression(run_time, desc=description) return time_progression def get_wait_time_progression( self, duration: float, stop_condition: Callable[[], bool] | None = None ) -> list[float] | np.ndarray | ProgressDisplay: kw = {"desc": f"{self.num_plays} Waiting"} if stop_condition is not None: kw["n_iterations"] = -1 # So it doesn't show % progress kw["override_skip_animations"] = True return self.get_time_progression(duration, **kw) def pre_play(self): if self.presenter_mode and self.num_plays == 0: self.hold_loop() self.update_skipping_status() if not self.skip_animations: self.file_writer.begin_animation() if self.window: self.real_animation_start_time = time.time() self.virtual_animation_start_time = self.time def post_play(self): if not self.skip_animations: self.file_writer.end_animation() if self.skip_animations and self.window is not None: # Show some quick frames along the way self.update_frame(dt=0, ignore_skipping=True) self.num_plays += 1 def begin_animations(self, animations: Iterable[Animation]) -> None: for animation in animations: animation.begin() # Anything animated that's not already in the # scene gets added to the scene. Note, for # animated mobjects that are in the family of # those on screen, this can result in a restructuring # of the scene.mobjects list, which is usually desired. if animation.mobject not in self.mobjects: self.add(animation.mobject) def progress_through_animations(self, animations: Iterable[Animation]) -> None: last_t = 0 for t in self.get_animation_time_progression(animations): dt = t - last_t last_t = t for animation in animations: animation.update_mobjects(dt) alpha = t / animation.run_time animation.interpolate(alpha) self.update_frame(dt) self.emit_frame() def finish_animations(self, animations: Iterable[Animation]) -> None: for animation in animations: animation.finish() animation.clean_up_from_scene(self) if self.skip_animations: self.update_mobjects(self.get_run_time(animations)) else: self.update_mobjects(0) @affects_mobject_list def play( self, *proto_animations: Animation | _AnimationBuilder, run_time: float | None = None, rate_func: Callable[[float], float] | None = None, lag_ratio: float | None = None, ) -> None: if len(proto_animations) == 0: log.warning("Called Scene.play with no animations") return animations = list(map(prepare_animation, proto_animations)) for anim in animations: anim.update_rate_info(run_time, rate_func, lag_ratio) self.pre_play() self.begin_animations(animations) self.progress_through_animations(animations) self.finish_animations(animations) self.post_play() def wait( self, duration: float = DEFAULT_WAIT_TIME, stop_condition: Callable[[], bool] = None, note: str = None, ignore_presenter_mode: bool = False ): self.pre_play() self.update_mobjects(dt=0) # Any problems with this? if self.presenter_mode and not self.skip_animations and not ignore_presenter_mode: if note: log.info(note) self.hold_loop() else: time_progression = self.get_wait_time_progression(duration, stop_condition) last_t = 0 for t in time_progression: dt = t - last_t last_t = t self.update_frame(dt) self.emit_frame() if stop_condition is not None and stop_condition(): break self.post_play() def hold_loop(self): while self.hold_on_wait: self.update_frame(dt=1 / self.camera.fps) self.hold_on_wait = True def wait_until( self, stop_condition: Callable[[], bool], max_time: float = 60 ): self.wait(max_time, stop_condition=stop_condition) def force_skipping(self): self.original_skipping_status = self.skip_animations self.skip_animations = True return self def revert_to_original_skipping_status(self): if hasattr(self, "original_skipping_status"): self.skip_animations = self.original_skipping_status return self def add_sound( self, sound_file: str, time_offset: float = 0, gain: float | None = None, gain_to_background: float | None = None ): if self.skip_animations: return time = self.get_time() + time_offset self.file_writer.add_sound(sound_file, time, gain, gain_to_background) # Helpers for interactive development def get_state(self) -> SceneState: return SceneState(self) @affects_mobject_list def restore_state(self, scene_state: SceneState): scene_state.restore_scene(self) def save_state(self) -> None: if not self.preview: return state = self.get_state() if self.undo_stack and state.mobjects_match(self.undo_stack[-1]): return self.redo_stack = [] self.undo_stack.append(state) if len(self.undo_stack) > self.max_num_saved_states: self.undo_stack.pop(0) def undo(self): if self.undo_stack: self.redo_stack.append(self.get_state()) self.restore_state(self.undo_stack.pop()) def redo(self): if self.redo_stack: self.undo_stack.append(self.get_state()) self.restore_state(self.redo_stack.pop()) def checkpoint_paste( self, skip: bool = False, record: bool = False, progress_bar: bool = True ): """ Used during interactive development to run (or re-run) a block of scene code. If the copied selection starts with a comment, this will revert to the state of the scene the first time this function was called on a block of code starting with that comment. """ shell = get_ipython() if shell is None or self.window is None: raise Exception( "Scene.checkpoint_paste cannot be called outside of " + "an ipython shell" ) pasted = pyperclip.paste() line0 = pasted.lstrip().split("\n")[0] if line0.startswith("#"): if line0 not in self.checkpoint_states: self.checkpoint(line0) else: self.revert_to_checkpoint(line0) prev_skipping = self.skip_animations self.skip_animations = skip prev_progress = self.show_animation_progress self.show_animation_progress = progress_bar if record: self.camera.use_window_fbo(False) self.file_writer.begin_insert() shell.run_cell(pasted) if record: self.file_writer.end_insert() self.camera.use_window_fbo(True) self.skip_animations = prev_skipping self.show_animation_progress = prev_progress def checkpoint(self, key: str): self.checkpoint_states[key] = self.get_state() def revert_to_checkpoint(self, key: str): if key not in self.checkpoint_states: log.error(f"No checkpoint at {key}") return all_keys = list(self.checkpoint_states.keys()) index = all_keys.index(key) for later_key in all_keys[index + 1:]: self.checkpoint_states.pop(later_key) self.restore_state(self.checkpoint_states[key]) def clear_checkpoints(self): self.checkpoint_states = dict() def save_mobject_to_file(self, mobject: Mobject, file_path: str | None = None) -> None: if file_path is None: file_path = self.file_writer.get_saved_mobject_path(mobject) if file_path is None: return mobject.save_to_file(file_path) def load_mobject(self, file_name): if os.path.exists(file_name): path = file_name else: directory = self.file_writer.get_saved_mobject_directory() path = os.path.join(directory, file_name) return Mobject.load(path) def is_window_closing(self): return self.window and (self.window.is_closing or self.quit_interaction) # Event handling def on_mouse_motion( self, point: Vect3, d_point: Vect3 ) -> None: assert(self.window is not None) self.mouse_point.move_to(point) event_data = {"point": point, "d_point": d_point} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseMotionEvent, **event_data) if propagate_event is not None and propagate_event is False: return frame = self.camera.frame # Handle perspective changes if self.window.is_key_pressed(ord(PAN_3D_KEY)): ff_d_point = frame.to_fixed_frame_point(d_point, relative=True) ff_d_point *= self.pan_sensitivity frame.increment_theta(-ff_d_point[0]) frame.increment_phi(ff_d_point[1]) # Handle frame movements elif self.window.is_key_pressed(ord(FRAME_SHIFT_KEY)): frame.shift(-d_point) def on_mouse_drag( self, point: Vect3, d_point: Vect3, buttons: int, modifiers: int ) -> None: self.mouse_drag_point.move_to(point) if self.drag_to_pan: self.frame.shift(-d_point) event_data = {"point": point, "d_point": d_point, "buttons": buttons, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseDragEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_press( self, point: Vect3, button: int, mods: int ) -> None: self.mouse_drag_point.move_to(point) event_data = {"point": point, "button": button, "mods": mods} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MousePressEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_release( self, point: Vect3, button: int, mods: int ) -> None: event_data = {"point": point, "button": button, "mods": mods} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseReleaseEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_scroll( self, point: Vect3, offset: Vect3, x_pixel_offset: float, y_pixel_offset: float ) -> None: event_data = {"point": point, "offset": offset} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseScrollEvent, **event_data) if propagate_event is not None and propagate_event is False: return rel_offset = y_pixel_offset / self.camera.get_pixel_height() self.frame.scale( 1 - self.scroll_sensitivity * rel_offset, about_point=point ) def on_key_release( self, symbol: int, modifiers: int ) -> None: event_data = {"symbol": symbol, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyReleaseEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_key_press( self, symbol: int, modifiers: int ) -> None: try: char = chr(symbol) except OverflowError: log.warning("The value of the pressed key is too large.") return event_data = {"symbol": symbol, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyPressEvent, **event_data) if propagate_event is not None and propagate_event is False: return if char == RESET_FRAME_KEY: self.play(self.camera.frame.animate.to_default_state()) elif char == "z" and modifiers == COMMAND_MODIFIER: self.undo() elif char == "z" and modifiers == COMMAND_MODIFIER | SHIFT_MODIFIER: self.redo() # command + q elif char == QUIT_KEY and modifiers == COMMAND_MODIFIER: self.quit_interaction = True # Space or right arrow elif char == " " or symbol == ARROW_SYMBOLS[2]: self.hold_on_wait = False def on_resize(self, width: int, height: int) -> None: pass def on_show(self) -> None: pass def on_hide(self) -> None: pass def on_close(self) -> None: pass class SceneState(): def __init__(self, scene: Scene, ignore: list[Mobject] | None = None): self.time = scene.time self.num_plays = scene.num_plays self.mobjects_to_copies = OrderedDict.fromkeys(scene.mobjects) if ignore: for mob in ignore: self.mobjects_to_copies.pop(mob, None) last_m2c = scene.undo_stack[-1].mobjects_to_copies if scene.undo_stack else dict() for mob in self.mobjects_to_copies: # If it hasn't changed since the last state, just point to the # same copy as before if mob in last_m2c and last_m2c[mob].looks_identical(mob): self.mobjects_to_copies[mob] = last_m2c[mob] else: self.mobjects_to_copies[mob] = mob.copy() def __eq__(self, state: SceneState): return all(( self.time == state.time, self.num_plays == state.num_plays, self.mobjects_to_copies == state.mobjects_to_copies )) def mobjects_match(self, state: SceneState): return self.mobjects_to_copies == state.mobjects_to_copies def n_changes(self, state: SceneState): m2c = state.mobjects_to_copies return sum( 1 - int(mob in m2c and mob.looks_identical(m2c[mob])) for mob in self.mobjects_to_copies ) def restore_scene(self, scene: Scene): scene.time = self.time scene.num_plays = self.num_plays scene.mobjects = [ mob.become(mob_copy) for mob, mob_copy in self.mobjects_to_copies.items() ] class EndScene(Exception): pass class ThreeDScene(Scene): samples = 4 default_frame_orientation = (-30, 70) always_depth_test = True def add(self, *mobjects, set_depth_test: bool = True): for mob in mobjects: if set_depth_test and not mob.is_fixed_in_frame() and self.always_depth_test: mob.apply_depth_test() super().add(*mobjects)
manim_3b1b/manimlib/scene/scene_file_writer.py
from __future__ import annotations import os import platform import shutil import subprocess as sp import sys import numpy as np from pydub import AudioSegment from tqdm.auto import tqdm as ProgressDisplay from manimlib.constants import FFMPEG_BIN from manimlib.logger import log from manimlib.mobject.mobject import Mobject from manimlib.utils.file_ops import add_extension_if_not_present from manimlib.utils.file_ops import get_sorted_integer_files from manimlib.utils.file_ops import guarantee_existence from manimlib.utils.sounds import get_full_sound_file_path from typing import TYPE_CHECKING if TYPE_CHECKING: from PIL.Image import Image from manimlib.camera.camera import Camera from manimlib.scene.scene import Scene class SceneFileWriter(object): def __init__( self, scene: Scene, write_to_movie: bool = False, break_into_partial_movies: bool = False, save_pngs: bool = False, # TODO, this currently does nothing png_mode: str = "RGBA", save_last_frame: bool = False, movie_file_extension: str = ".mp4", # What python file is generating this scene input_file_path: str = "", # Where should this be written output_directory: str | None = None, file_name: str | None = None, subdirectory_for_videos: bool = False, open_file_upon_completion: bool = False, show_file_location_upon_completion: bool = False, quiet: bool = False, total_frames: int = 0, progress_description_len: int = 40, video_codec: str = "libx264", pixel_format: str = "yuv420p", saturation: float = 1.0, gamma: float = 1.0, ): self.scene: Scene = scene self.write_to_movie = write_to_movie self.break_into_partial_movies = break_into_partial_movies self.save_pngs = save_pngs self.png_mode = png_mode self.save_last_frame = save_last_frame self.movie_file_extension = movie_file_extension self.input_file_path = input_file_path self.output_directory = output_directory self.file_name = file_name self.open_file_upon_completion = open_file_upon_completion self.subdirectory_for_videos = subdirectory_for_videos self.show_file_location_upon_completion = show_file_location_upon_completion self.quiet = quiet self.total_frames = total_frames self.progress_description_len = progress_description_len self.video_codec = video_codec self.pixel_format = pixel_format self.saturation = saturation self.gamma = gamma # State during file writing self.writing_process: sp.Popen | None = None self.progress_display: ProgressDisplay | None = None self.ended_with_interrupt: bool = False self.init_output_directories() self.init_audio() # Output directories and files def init_output_directories(self) -> None: out_dir = self.output_directory or "" scene_name = self.file_name or self.get_default_scene_name() if self.save_last_frame: image_dir = guarantee_existence(os.path.join(out_dir, "images")) image_file = add_extension_if_not_present(scene_name, ".png") self.image_file_path = os.path.join(image_dir, image_file) if self.write_to_movie: if self.subdirectory_for_videos: movie_dir = guarantee_existence(os.path.join(out_dir, "videos")) else: movie_dir = guarantee_existence(out_dir) movie_file = add_extension_if_not_present(scene_name, self.movie_file_extension) self.movie_file_path = os.path.join(movie_dir, movie_file) if self.break_into_partial_movies: self.partial_movie_directory = guarantee_existence(os.path.join( movie_dir, "partial_movie_files", scene_name, )) # A place to save mobjects self.saved_mobject_directory = os.path.join( out_dir, "mobjects", str(self.scene) ) def get_default_module_directory(self) -> str: path, _ = os.path.splitext(self.input_file_path) if path.startswith("_"): path = path[1:] return path def get_default_scene_name(self) -> str: name = str(self.scene) saan = self.scene.start_at_animation_number eaan = self.scene.end_at_animation_number if saan is not None: name += f"_{saan}" if eaan is not None: name += f"_{eaan}" return name def get_resolution_directory(self) -> str: pixel_height = self.scene.camera.pixel_height fps = self.scene.camera.fps return "{}p{}".format( pixel_height, fps ) # Directory getters def get_image_file_path(self) -> str: return self.image_file_path def get_next_partial_movie_path(self) -> str: result = os.path.join( self.partial_movie_directory, "{:05}{}".format( self.scene.num_plays, self.movie_file_extension, ) ) return result def get_movie_file_path(self) -> str: return self.movie_file_path def get_saved_mobject_directory(self) -> str: return guarantee_existence(self.saved_mobject_directory) def get_saved_mobject_path(self, mobject: Mobject) -> str | None: directory = self.get_saved_mobject_directory() files = os.listdir(directory) default_name = str(mobject) + "_0.mob" index = 0 while default_name in files: default_name = default_name.replace(str(index), str(index + 1)) index += 1 if platform.system() == 'Darwin': cmds = [ "osascript", "-e", f""" set chosenfile to (choose file name default name "{default_name}" default location "{directory}") POSIX path of chosenfile """, ] process = sp.Popen(cmds, stdout=sp.PIPE) file_path = process.stdout.read().decode("utf-8").split("\n")[0] if not file_path: return else: user_name = input(f"Enter mobject file name (default is {default_name}): ") file_path = os.path.join(directory, user_name or default_name) if os.path.exists(file_path) or os.path.exists(file_path + ".mob"): if input(f"{file_path} already exists. Overwrite (y/n)? ") != "y": return if not file_path.endswith(".mob"): file_path = file_path + ".mob" return file_path # Sound def init_audio(self) -> None: self.includes_sound: bool = False def create_audio_segment(self) -> None: self.audio_segment = AudioSegment.silent() def add_audio_segment( self, new_segment: AudioSegment, time: float | None = None, gain_to_background: float | None = None ) -> None: if not self.includes_sound: self.includes_sound = True self.create_audio_segment() segment = self.audio_segment curr_end = segment.duration_seconds if time is None: time = curr_end if time < 0: raise Exception("Adding sound at timestamp < 0") new_end = time + new_segment.duration_seconds diff = new_end - curr_end if diff > 0: segment = segment.append( AudioSegment.silent(int(np.ceil(diff * 1000))), crossfade=0, ) self.audio_segment = segment.overlay( new_segment, position=int(1000 * time), gain_during_overlay=gain_to_background, ) def add_sound( self, sound_file: str, time: float | None = None, gain: float | None = None, gain_to_background: float | None = None ) -> None: file_path = get_full_sound_file_path(sound_file) new_segment = AudioSegment.from_file(file_path) if gain: new_segment = new_segment.apply_gain(gain) self.add_audio_segment(new_segment, time, gain_to_background) # Writers def begin(self) -> None: if not self.break_into_partial_movies and self.write_to_movie: self.open_movie_pipe(self.get_movie_file_path()) def begin_animation(self) -> None: if self.break_into_partial_movies and self.write_to_movie: self.open_movie_pipe(self.get_next_partial_movie_path()) def end_animation(self) -> None: if self.break_into_partial_movies and self.write_to_movie: self.close_movie_pipe() def finish(self) -> None: if self.write_to_movie: if self.break_into_partial_movies: self.combine_movie_files() else: self.close_movie_pipe() if self.includes_sound: self.add_sound_to_video() self.print_file_ready_message(self.get_movie_file_path()) if self.save_last_frame: self.scene.update_frame(ignore_skipping=True) self.save_final_image(self.scene.get_image()) if self.should_open_file(): self.open_file() def open_movie_pipe(self, file_path: str) -> None: stem, ext = os.path.splitext(file_path) self.final_file_path = file_path self.temp_file_path = stem + "_temp" + ext fps = self.scene.camera.fps width, height = self.scene.camera.get_pixel_shape() vf_arg = 'vflip' if self.pixel_format.startswith("yuv"): vf_arg += f',eq=saturation={self.saturation}:gamma={self.gamma}' command = [ FFMPEG_BIN, '-y', # overwrite output file if it exists '-f', 'rawvideo', '-s', f'{width}x{height}', # size of one frame '-pix_fmt', 'rgba', '-r', str(fps), # frames per second '-i', '-', # The input comes from a pipe '-vf', vf_arg, '-an', # Tells FFMPEG not to expect any audio '-loglevel', 'error', ] if self.video_codec: command += ['-vcodec', self.video_codec] if self.pixel_format: command += ['-pix_fmt', self.pixel_format] command += [self.temp_file_path] self.writing_process = sp.Popen(command, stdin=sp.PIPE) if not self.quiet: self.progress_display = ProgressDisplay( range(self.total_frames), leave=False, ascii=True if platform.system() == 'Windows' else None, dynamic_ncols=True, ) self.set_progress_display_description() def use_fast_encoding(self): self.video_codec = "libx264rgb" self.pixel_format = "rgb32" def begin_insert(self): # Begin writing process self.write_to_movie = True self.init_output_directories() movie_path = self.get_movie_file_path() count = 0 while os.path.exists(name := movie_path.replace(".", f"_insert_{count}.")): count += 1 self.inserted_file_path = name self.open_movie_pipe(self.inserted_file_path) def end_insert(self): self.close_movie_pipe() self.write_to_movie = False self.print_file_ready_message(self.inserted_file_path) def has_progress_display(self): return self.progress_display is not None def set_progress_display_description(self, file: str = "", sub_desc: str = "") -> None: if self.progress_display is None: return desc_len = self.progress_description_len if not file: file = os.path.split(self.get_movie_file_path())[1] full_desc = f"{file} {sub_desc}" if len(full_desc) > desc_len: full_desc = full_desc[:desc_len - 3] + "..." else: full_desc += " " * (desc_len - len(full_desc)) self.progress_display.set_description(full_desc) def write_frame(self, camera: Camera) -> None: if self.write_to_movie: raw_bytes = camera.get_raw_fbo_data() self.writing_process.stdin.write(raw_bytes) if self.progress_display is not None: self.progress_display.update() def close_movie_pipe(self) -> None: self.writing_process.stdin.close() self.writing_process.wait() self.writing_process.terminate() if self.progress_display is not None: self.progress_display.close() if not self.ended_with_interrupt: shutil.move(self.temp_file_path, self.final_file_path) else: self.movie_file_path = self.temp_file_path def combine_movie_files(self) -> None: kwargs = { "remove_non_integer_files": True, "extension": self.movie_file_extension, } if self.scene.start_at_animation_number is not None: kwargs["min_index"] = self.scene.start_at_animation_number if self.scene.end_at_animation_number is not None: kwargs["max_index"] = self.scene.end_at_animation_number else: kwargs["remove_indices_greater_than"] = self.scene.num_plays - 1 partial_movie_files = get_sorted_integer_files( self.partial_movie_directory, **kwargs ) if len(partial_movie_files) == 0: log.warning("No animations in this scene") return # Write a file partial_file_list.txt containing all # partial movie files file_list = os.path.join( self.partial_movie_directory, "partial_movie_file_list.txt" ) with open(file_list, 'w') as fp: for pf_path in partial_movie_files: if os.name == 'nt': pf_path = pf_path.replace('\\', '/') fp.write(f"file \'{pf_path}\'\n") movie_file_path = self.get_movie_file_path() commands = [ FFMPEG_BIN, '-y', # overwrite output file if it exists '-f', 'concat', '-safe', '0', '-i', file_list, '-loglevel', 'error', '-c', 'copy', movie_file_path ] if not self.includes_sound: commands.insert(-1, '-an') combine_process = sp.Popen(commands) combine_process.wait() def add_sound_to_video(self) -> None: movie_file_path = self.get_movie_file_path() stem, ext = os.path.splitext(movie_file_path) sound_file_path = stem + ".wav" # Makes sure sound file length will match video file self.add_audio_segment(AudioSegment.silent(0)) self.audio_segment.export( sound_file_path, bitrate='312k', ) temp_file_path = stem + "_temp" + ext commands = [ FFMPEG_BIN, "-i", movie_file_path, "-i", sound_file_path, '-y', # overwrite output file if it exists "-c:v", "copy", "-c:a", "aac", "-b:a", "320k", # select video stream from first file "-map", "0:v:0", # select audio stream from second file "-map", "1:a:0", '-loglevel', 'error', # "-shortest", temp_file_path, ] sp.call(commands) shutil.move(temp_file_path, movie_file_path) os.remove(sound_file_path) def save_final_image(self, image: Image) -> None: file_path = self.get_image_file_path() image.save(file_path) self.print_file_ready_message(file_path) def print_file_ready_message(self, file_path: str) -> None: if not self.quiet: log.info(f"File ready at {file_path}") def should_open_file(self) -> bool: return any([ self.show_file_location_upon_completion, self.open_file_upon_completion, ]) def open_file(self) -> None: if self.quiet: curr_stdout = sys.stdout sys.stdout = open(os.devnull, "w") current_os = platform.system() file_paths = [] if self.save_last_frame: file_paths.append(self.get_image_file_path()) if self.write_to_movie: file_paths.append(self.get_movie_file_path()) for file_path in file_paths: if current_os == "Windows": os.startfile(file_path) else: commands = [] if current_os == "Linux": commands.append("xdg-open") elif current_os.startswith("CYGWIN"): commands.append("cygstart") else: # Assume macOS commands.append("open") if self.show_file_location_upon_completion: commands.append("-R") commands.append(file_path) FNULL = open(os.devnull, 'w') sp.call(commands, stdout=FNULL, stderr=sp.STDOUT) FNULL.close() if self.quiet: sys.stdout.close() sys.stdout = curr_stdout
manim_3b1b/manimlib/mobject/matrix.py
from __future__ import annotations import itertools as it import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import WHITE from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.numbers import Integer from manimlib.mobject.shape_matchers import BackgroundRectangle from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence import numpy.typing as npt from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Vect3, Self VECTOR_LABEL_SCALE_FACTOR = 0.8 def matrix_to_tex_string(matrix: npt.ArrayLike) -> str: matrix = np.array(matrix).astype("str") if matrix.ndim == 1: matrix = matrix.reshape((matrix.size, 1)) n_rows, n_cols = matrix.shape prefix = R"\left[ \begin{array}{%s}" % ("c" * n_cols) suffix = R"\end{array} \right]" rows = [ " & ".join(row) for row in matrix ] return prefix + R" \\ ".join(rows) + suffix def matrix_to_mobject(matrix: npt.ArrayLike) -> Tex: return Tex(matrix_to_tex_string(matrix)) def vector_coordinate_label( vector_mob: VMobject, integer_labels: bool = True, n_dim: int = 2, color: ManimColor = WHITE ) -> Matrix: vect = np.array(vector_mob.get_end()) if integer_labels: vect = np.round(vect).astype(int) vect = vect[:n_dim] vect = vect.reshape((n_dim, 1)) label = Matrix(vect, add_background_rectangles_to_entries=True) label.scale(VECTOR_LABEL_SCALE_FACTOR) shift_dir = np.array(vector_mob.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) label.set_color(color) label.rect = BackgroundRectangle(label) label.add_to_back(label.rect) return label class Matrix(VMobject): def __init__( self, matrix: Sequence[Sequence[str | float | VMobject]], v_buff: float = 0.8, h_buff: float = 1.0, bracket_h_buff: float = 0.2, bracket_v_buff: float = 0.25, add_background_rectangles_to_entries: bool = False, include_background_rectangle: bool = False, element_alignment_corner: Vect3 = DOWN, **kwargs ): """ Matrix can either include numbers, tex_strings, or mobjects """ super().__init__() mob_matrix = self.matrix_to_mob_matrix(matrix, **kwargs) self.mob_matrix = mob_matrix self.organize_mob_matrix(mob_matrix, v_buff, h_buff, element_alignment_corner) self.elements = VGroup(*it.chain(*mob_matrix)) self.add(self.elements) self.add_brackets(bracket_v_buff, bracket_h_buff) self.center() if add_background_rectangles_to_entries: for mob in self.elements: mob.add_background_rectangle() if include_background_rectangle: self.add_background_rectangle() def element_to_mobject(self, element: str | float | VMobject, **config) -> VMobject: if isinstance(element, VMobject): return element return Tex(str(element), **config) def matrix_to_mob_matrix( self, matrix: Sequence[Sequence[str | float | VMobject]], **config ) -> list[list[VMobject]]: return [ [ self.element_to_mobject(item, **config) for item in row ] for row in matrix ] def organize_mob_matrix( self, matrix: list[list[VMobject]], v_buff: float, h_buff: float, aligned_corner: Vect3, ) -> Self: for i, row in enumerate(matrix): for j, elem in enumerate(row): mob = matrix[i][j] mob.move_to( i * v_buff * DOWN + j * h_buff * RIGHT, aligned_corner ) return self def add_brackets(self, v_buff: float, h_buff: float) -> Self: height = len(self.mob_matrix) brackets = Tex("".join(( R"\left[\begin{array}{c}", *height * [R"\quad \\"], R"\end{array}\right]", ))) brackets.set_height(self.get_height() + v_buff) l_bracket = brackets[:len(brackets) // 2] r_bracket = brackets[len(brackets) // 2:] l_bracket.next_to(self, LEFT, h_buff) r_bracket.next_to(self, RIGHT, h_buff) brackets.set_submobjects([l_bracket, r_bracket]) self.brackets = brackets self.add(*brackets) return self def get_columns(self) -> VGroup: return VGroup(*[ VGroup(*[row[i] for row in self.mob_matrix]) for i in range(len(self.mob_matrix[0])) ]) def get_rows(self) -> VGroup: return VGroup(*[ VGroup(*row) for row in self.mob_matrix ]) def set_column_colors(self, *colors: ManimColor) -> Self: columns = self.get_columns() for color, column in zip(colors, columns): column.set_color(color) return self def add_background_to_entries(self) -> Self: for mob in self.get_entries(): mob.add_background_rectangle() return self def get_mob_matrix(self) -> list[list[Mobject]]: return self.mob_matrix def get_entries(self) -> VGroup: return self.elements def get_brackets(self) -> VGroup: return self.brackets class DecimalMatrix(Matrix): def element_to_mobject(self, element: float, num_decimal_places: int = 1, **config) -> DecimalNumber: return DecimalNumber(element, num_decimal_places=num_decimal_places, **config) class IntegerMatrix(Matrix): def __init__( self, matrix: npt.ArrayLike, element_alignment_corner: Vect3 = UP, **kwargs ): super().__init__(matrix, element_alignment_corner=element_alignment_corner, **kwargs) def element_to_mobject(self, element: int, **config) -> Integer: return Integer(element, **config) class MobjectMatrix(Matrix): def element_to_mobject(self, element: VMobject, **config) -> VMobject: return element def get_det_text( matrix: Matrix, determinant: int | str | None = None, background_rect: bool = False, initial_scale_factor: int = 2 ) -> VGroup: parens = Tex("()") parens.scale(initial_scale_factor) parens.stretch_to_fit_height(matrix.get_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 = TexText("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 = Tex("=") eq.next_to(r_paren, RIGHT, buff=0.1) result = Tex(str(determinant)) result.next_to(eq, RIGHT, buff=0.2) det_text.add(eq, result) return det_text
manim_3b1b/manimlib/mobject/value_tracker.py
from __future__ import annotations import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import listify from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Self class ValueTracker(Mobject): """ 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. """ value_type: type = np.float64 def __init__( self, value: float | complex | np.ndarray = 0, **kwargs ): self.value = value super().__init__(**kwargs) def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["value"] = np.array( listify(self.value), dtype=self.value_type, ) def get_value(self) -> float | complex | np.ndarray: result = self.uniforms["value"] if len(result) == 1: return result[0] return result def set_value(self, value: float | complex | np.ndarray) -> Self: self.uniforms["value"][:] = value return self def increment_value(self, d_value: float | complex) -> None: self.set_value(self.get_value() + d_value) class ExponentialValueTracker(ValueTracker): """ Operates just like ValueTracker, except it encodes the value as the exponential of a position coordinate, which changes how interpolation behaves """ def get_value(self) -> float | complex: return np.exp(ValueTracker.get_value(self)) def set_value(self, value: float | complex): return ValueTracker.set_value(self, np.log(value)) class ComplexValueTracker(ValueTracker): value_type: type = np.complex128
manim_3b1b/manimlib/mobject/__init__.py
manim_3b1b/manimlib/mobject/mobject.py
from __future__ import annotations import copy from functools import wraps import itertools as it import os import pickle import random import sys import moderngl import numbers import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_EDGE_BUFFER from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER from manimlib.constants import DOWN, IN, LEFT, ORIGIN, OUT, RIGHT, UP from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import MED_SMALL_BUFF from manimlib.constants import TAU from manimlib.constants import WHITE from manimlib.event_handler import EVENT_DISPATCHER from manimlib.event_handler.event_listner import EventListener from manimlib.event_handler.event_type import EventType from manimlib.logger import log from manimlib.shader_wrapper import ShaderWrapper from manimlib.utils.color import color_gradient from manimlib.utils.color import color_to_rgb from manimlib.utils.color import get_colormap_list from manimlib.utils.color import rgb_to_hex from manimlib.utils.iterables import arrays_match from manimlib.utils.iterables import array_is_constant from manimlib.utils.iterables import batch_by_property from manimlib.utils.iterables import list_update from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_array from manimlib.utils.iterables import resize_preserving_order from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.paths import straight_path from manimlib.utils.simple_functions import get_parameters from manimlib.utils.shaders import get_colormap_code from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import rotation_matrix_transpose from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Iterator, Union, Tuple, Optional import numpy.typing as npt from manimlib.typing import ManimColor, Vect3, Vect4, Vect3Array, UniformDict, Self from moderngl.context import Context TimeBasedUpdater = Callable[["Mobject", float], "Mobject" | None] NonTimeUpdater = Callable[["Mobject"], "Mobject" | None] Updater = Union[TimeBasedUpdater, NonTimeUpdater] class Mobject(object): """ Mathematical Object """ dim: int = 3 shader_folder: str = "" render_primitive: int = moderngl.TRIANGLE_STRIP # Must match in attributes of vert shader shader_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('rgba', np.float32, (4,)), ]) aligned_data_keys = ['point'] pointlike_data_keys = ['point'] def __init__( self, color: ManimColor = WHITE, opacity: float = 1.0, shading: Tuple[float, float, float] = (0.0, 0.0, 0.0), # For shaders texture_paths: dict[str, str] | None = None, # If true, the mobject will not get rotated according to camera position is_fixed_in_frame: bool = False, depth_test: bool = False, ): self.color = color self.opacity = opacity self.shading = shading self.texture_paths = texture_paths self._is_fixed_in_frame = is_fixed_in_frame self.depth_test = depth_test # Internal state self.submobjects: list[Mobject] = [] self.parents: list[Mobject] = [] self.family: list[Mobject] = [self] self.locked_data_keys: set[str] = set() self.const_data_keys: set[str] = set() self.locked_uniform_keys: set[str] = set() self.needs_new_bounding_box: bool = True self._is_animating: bool = False self.saved_state = None self.target = None self.bounding_box: Vect3Array = np.zeros((3, 3)) self._shaders_initialized: bool = False self._data_has_changed: bool = True self.shader_code_replacements: dict[str, str] = dict() self.init_data() self._data_defaults = np.ones(1, dtype=self.data.dtype) self.init_uniforms() self.init_updaters() self.init_event_listners() self.init_points() self.init_colors() if self.depth_test: self.apply_depth_test() def __str__(self): return self.__class__.__name__ def __add__(self, other: Mobject) -> Mobject: assert(isinstance(other, Mobject)) return self.get_group_class()(self, other) def __mul__(self, other: int) -> Mobject: assert(isinstance(other, int)) return self.replicate(other) def init_data(self, length: int = 0): self.data = np.zeros(length, dtype=self.shader_dtype) def init_uniforms(self): self.uniforms: UniformDict = { "is_fixed_in_frame": float(self._is_fixed_in_frame), "shading": np.array(self.shading, dtype=float), } def init_colors(self): self.set_color(self.color, self.opacity) def init_points(self): # Typically implemented in subclass, unlpess purposefully left blank pass def set_uniforms(self, uniforms: dict) -> Self: for key, value in uniforms.items(): if isinstance(value, np.ndarray): value = value.copy() self.uniforms[key] = value return self @property def animate(self) -> _AnimationBuilder: # Borrowed from https://github.com/ManimCommunity/manim/ return _AnimationBuilder(self) def note_changed_data(self, recurse_up: bool = True) -> Self: self._data_has_changed = True if recurse_up: for mob in self.parents: mob.note_changed_data() return self def affects_data(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) self.note_changed_data() return wrapper def affects_family_data(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) for mob in self.family_members_with_points(): mob.note_changed_data() return self return wrapper # Only these methods should directly affect points @affects_data def set_data(self, data: np.ndarray) -> Self: assert(data.dtype == self.data.dtype) self.resize_points(len(data)) self.data[:] = data return self @affects_data def resize_points( self, new_length: int, resize_func: Callable[[np.ndarray, int], np.ndarray] = resize_array ) -> Self: if new_length == 0: if len(self.data) > 0: self._data_defaults[:1] = self.data[:1] elif self.get_num_points() == 0: self.data = self._data_defaults.copy() self.data = resize_func(self.data, new_length) self.refresh_bounding_box() return self @affects_data def set_points(self, points: Vect3Array | list[Vect3]) -> Self: self.resize_points(len(points), resize_func=resize_preserving_order) self.data["point"][:] = points return self @affects_data def append_points(self, new_points: Vect3Array) -> Self: n = self.get_num_points() self.resize_points(n + len(new_points)) # Have most data default to the last value self.data[n:] = self.data[n - 1] # Then read in new points self.data["point"][n:] = new_points self.refresh_bounding_box() return self @affects_family_data def reverse_points(self) -> Self: for mob in self.get_family(): mob.data[:] = mob.data[::-1] return self @affects_family_data def apply_points_function( self, func: Callable[[np.ndarray], np.ndarray], about_point: Vect3 | None = None, about_edge: Vect3 = ORIGIN, works_on_bounding_box: bool = False ) -> Self: if about_point is None and about_edge is not None: about_point = self.get_bounding_box_point(about_edge) for mob in self.get_family(): arrs = [] if mob.has_points(): for key in mob.pointlike_data_keys: arrs.append(mob.data[key]) if works_on_bounding_box: arrs.append(mob.get_bounding_box()) for arr in arrs: if about_point is None: arr[:] = func(arr) else: arr[:] = func(arr - about_point) + about_point if not works_on_bounding_box: self.refresh_bounding_box(recurse_down=True) else: for parent in self.parents: parent.refresh_bounding_box() return self # Others related to points def match_points(self, mobject: Mobject) -> Self: self.set_points(mobject.get_points()) return self def get_points(self) -> Vect3Array: return self.data["point"] def clear_points(self) -> Self: self.resize_points(0) return self def get_num_points(self) -> int: return len(self.get_points()) def get_all_points(self) -> Vect3Array: if self.submobjects: return np.vstack([sm.get_points() for sm in self.get_family()]) else: return self.get_points() def has_points(self) -> bool: return len(self.get_points()) > 0 def get_bounding_box(self) -> Vect3Array: if self.needs_new_bounding_box: self.bounding_box[:] = self.compute_bounding_box() self.needs_new_bounding_box = False return self.bounding_box def compute_bounding_box(self) -> Vect3Array: all_points = np.vstack([ self.get_points(), *( mob.get_bounding_box() for mob in self.get_family()[1:] if mob.has_points() ) ]) if len(all_points) == 0: return np.zeros((3, self.dim)) else: # Lower left and upper right corners mins = all_points.min(0) maxs = all_points.max(0) mids = (mins + maxs) / 2 return np.array([mins, mids, maxs]) def refresh_bounding_box( self, recurse_down: bool = False, recurse_up: bool = True ) -> Self: for mob in self.get_family(recurse_down): mob.needs_new_bounding_box = True if recurse_up: for parent in self.parents: parent.refresh_bounding_box() return self def are_points_touching( self, points: Vect3Array, buff: float = 0 ) -> np.ndarray: bb = self.get_bounding_box() mins = (bb[0] - buff) maxs = (bb[2] + buff) return ((points >= mins) * (points <= maxs)).all(1) def is_point_touching( self, point: Vect3, buff: float = 0 ) -> bool: return self.are_points_touching(np.array(point, ndmin=2), buff)[0] def is_touching(self, mobject: Mobject, buff: float = 1e-2) -> bool: bb1 = self.get_bounding_box() bb2 = mobject.get_bounding_box() return not any(( (bb2[2] < bb1[0] - buff).any(), # E.g. Right of mobject is left of self's left (bb2[0] > bb1[2] + buff).any(), # E.g. Left of mobject is right of self's right )) # Family matters def __getitem__(self, value: int | slice) -> Self: if isinstance(value, slice): GroupClass = self.get_group_class() return GroupClass(*self.split().__getitem__(value)) return self.split().__getitem__(value) def __iter__(self) -> Iterator[Self]: return iter(self.split()) def __len__(self) -> int: return len(self.split()) def split(self) -> list[Self]: return self.submobjects @affects_data def assemble_family(self) -> Self: sub_families = (sm.get_family() for sm in self.submobjects) self.family = [self, *it.chain(*sub_families)] self.refresh_has_updater_status() self.refresh_bounding_box() for parent in self.parents: parent.assemble_family() return self def get_family(self, recurse: bool = True) -> list[Self]: if recurse: return self.family else: return [self] def family_members_with_points(self) -> list[Self]: return [m for m in self.family if len(m.data) > 0] def get_ancestors(self, extended: bool = False) -> list[Mobject]: """ Returns parents, grandparents, etc. Order of result should be from higher members of the hierarchy down. If extended is set to true, it includes the ancestors of all family members, e.g. any other parents of a submobject """ ancestors = [] to_process = list(self.get_family(recurse=extended)) excluded = set(to_process) while to_process: for p in to_process.pop().parents: if p not in excluded: ancestors.append(p) to_process.append(p) # Ensure mobjects highest in the hierarchy show up first ancestors.reverse() # Remove list redundancies while preserving order return list(dict.fromkeys(ancestors)) def add(self, *mobjects: Mobject) -> Self: if self in mobjects: raise Exception("Mobject cannot contain self") for mobject in mobjects: if mobject not in self.submobjects: self.submobjects.append(mobject) if self not in mobject.parents: mobject.parents.append(self) self.assemble_family() return self def remove( self, *to_remove: Mobject, reassemble: bool = True, recurse: bool = True ) -> Self: for parent in self.get_family(recurse): for child in to_remove: if child in parent.submobjects: parent.submobjects.remove(child) if parent in child.parents: child.parents.remove(parent) if reassemble: parent.assemble_family() return self def clear(self) -> Self: self.remove(*self.submobjects, recurse=False) return self def add_to_back(self, *mobjects: Mobject) -> Self: self.set_submobjects(list_update(mobjects, self.submobjects)) return self def replace_submobject(self, index: int, new_submob: Mobject) -> Self: old_submob = self.submobjects[index] if self in old_submob.parents: old_submob.parents.remove(self) self.submobjects[index] = new_submob new_submob.parents.append(self) self.assemble_family() return self def insert_submobject(self, index: int, new_submob: Mobject) -> Self: self.submobjects.insert(index, new_submob) self.assemble_family() return self def set_submobjects(self, submobject_list: list[Mobject]) -> Self: if self.submobjects == submobject_list: return self self.clear() self.add(*submobject_list) return self def digest_mobject_attrs(self) -> Self: """ Ensures all attributes which are mobjects are included in the submobjects list. """ mobject_attrs = [x for x in list(self.__dict__.values()) if isinstance(x, Mobject)] self.set_submobjects(list_update(self.submobjects, mobject_attrs)) return self # Submobject organization def arrange( self, direction: Vect3 = RIGHT, center: bool = True, **kwargs ) -> Self: for m1, m2 in zip(self.submobjects, self.submobjects[1:]): m2.next_to(m1, direction, **kwargs) if center: self.center() return self def arrange_in_grid( self, n_rows: int | None = None, n_cols: int | None = None, buff: float | None = None, h_buff: float | None = None, v_buff: float | None = None, buff_ratio: float | None = None, h_buff_ratio: float = 0.5, v_buff_ratio: float = 0.5, aligned_edge: Vect3 = ORIGIN, fill_rows_first: bool = True ) -> Self: submobs = self.submobjects if n_rows is None and n_cols is None: n_rows = int(np.sqrt(len(submobs))) if n_rows is None: n_rows = len(submobs) // n_cols if n_cols is None: n_cols = len(submobs) // n_rows if buff is not None: h_buff = buff v_buff = buff else: if buff_ratio is not None: v_buff_ratio = buff_ratio h_buff_ratio = buff_ratio if h_buff is None: h_buff = h_buff_ratio * self[0].get_width() if v_buff is None: v_buff = v_buff_ratio * self[0].get_height() x_unit = h_buff + max([sm.get_width() for sm in submobs]) y_unit = v_buff + max([sm.get_height() for sm in submobs]) for index, sm in enumerate(submobs): if fill_rows_first: x, y = index % n_cols, index // n_cols else: x, y = index // n_rows, index % n_rows sm.move_to(ORIGIN, aligned_edge) sm.shift(x * x_unit * RIGHT + y * y_unit * DOWN) self.center() return self def arrange_to_fit_dim(self, length: float, dim: int, about_edge=ORIGIN) -> Self: ref_point = self.get_bounding_box_point(about_edge) n_submobs = len(self.submobjects) if n_submobs <= 1: return total_length = sum(sm.length_over_dim(dim) for sm in self.submobjects) buff = (length - total_length) / (n_submobs - 1) vect = np.zeros(self.dim) vect[dim] = 1 x = 0 for submob in self.submobjects: submob.set_coord(x, dim, -vect) x += submob.length_over_dim(dim) + buff self.move_to(ref_point, about_edge) return self def arrange_to_fit_width(self, width: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(width, 0, about_edge) def arrange_to_fit_height(self, height: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(height, 1, about_edge) def arrange_to_fit_depth(self, depth: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(depth, 2, about_edge) def sort( self, point_to_num_func: Callable[[np.ndarray], float] = lambda p: p[0], submob_func: Callable[[Mobject]] | None = None ) -> Self: if submob_func is not None: self.submobjects.sort(key=submob_func) else: self.submobjects.sort(key=lambda m: point_to_num_func(m.get_center())) self.assemble_family() return self def shuffle(self, recurse: bool = False) -> Self: if recurse: for submob in self.submobjects: submob.shuffle(recurse=True) random.shuffle(self.submobjects) self.assemble_family() return self def reverse_submobjects(self) -> Self: self.submobjects.reverse() self.assemble_family() return self # Copying and serialization def stash_mobject_pointers(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): uncopied_attrs = ["parents", "target", "saved_state"] stash = dict() for attr in uncopied_attrs: if hasattr(self, attr): value = getattr(self, attr) stash[attr] = value null_value = [] if isinstance(value, list) else None setattr(self, attr, null_value) result = func(self, *args, **kwargs) self.__dict__.update(stash) return result return wrapper @stash_mobject_pointers def serialize(self) -> bytes: return pickle.dumps(self) def deserialize(self, data: bytes) -> Self: self.become(pickle.loads(data)) return self def deepcopy(self) -> Self: result = copy.deepcopy(self) result._shaders_initialized = False result._data_has_changed = True return result def copy(self, deep: bool = False) -> Self: if deep: return self.deepcopy() result = copy.copy(self) result.parents = [] result.target = None result.saved_state = None # copy.copy is only a shallow copy, so the internal # data which are numpy arrays or other mobjects still # need to be further copied. result.uniforms = { key: value.copy() if isinstance(value, np.ndarray) else value for key, value in self.uniforms.items() } # Instead of adding using result.add, which does some checks for updating # updater statues and bounding box, just directly modify the family-related # lists result.submobjects = [sm.copy() for sm in self.submobjects] for sm in result.submobjects: sm.parents = [result] result.family = [result, *it.chain(*(sm.get_family() for sm in result.submobjects))] # Similarly, instead of calling match_updaters, since we know the status # won't have changed, just directly match. result.non_time_updaters = list(self.non_time_updaters) result.time_based_updaters = list(self.time_based_updaters) result._data_has_changed = True result._shaders_initialized = False family = self.get_family() for attr, value in self.__dict__.items(): if isinstance(value, Mobject) and value is not self: if value in family: setattr(result, attr, result.family[self.family.index(value)]) elif isinstance(value, np.ndarray): setattr(result, attr, value.copy()) return result def generate_target(self, use_deepcopy: bool = False) -> Self: self.target = self.copy(deep=use_deepcopy) self.target.saved_state = self.saved_state return self.target def save_state(self, use_deepcopy: bool = False) -> Self: self.saved_state = self.copy(deep=use_deepcopy) self.saved_state.target = self.target return self def restore(self) -> Self: if not hasattr(self, "saved_state") or self.saved_state is None: raise Exception("Trying to restore without having saved") self.become(self.saved_state) return self def save_to_file(self, file_path: str) -> Self: with open(file_path, "wb") as fp: fp.write(self.serialize()) log.info(f"Saved mobject to {file_path}") return self @staticmethod def load(file_path) -> Mobject: if not os.path.exists(file_path): log.error(f"No file found at {file_path}") sys.exit(2) with open(file_path, "rb") as fp: mobject = pickle.load(fp) return mobject def become(self, mobject: Mobject, match_updaters=False) -> Self: """ Edit all data and submobjects to be idential to another mobject """ self.align_family(mobject) family1 = self.get_family() family2 = mobject.get_family() for sm1, sm2 in zip(family1, family2): sm1.set_data(sm2.data) sm1.set_uniforms(sm2.uniforms) sm1.bounding_box[:] = sm2.bounding_box sm1.shader_folder = sm2.shader_folder sm1.texture_paths = sm2.texture_paths sm1.depth_test = sm2.depth_test sm1.render_primitive = sm2.render_primitive sm1.needs_new_bounding_box = sm2.needs_new_bounding_box # Make sure named family members carry over for attr, value in list(mobject.__dict__.items()): if isinstance(value, Mobject) and value in family2: setattr(self, attr, family1[family2.index(value)]) if match_updaters: self.match_updaters(mobject) return self def looks_identical(self, mobject: Mobject) -> bool: fam1 = self.family_members_with_points() fam2 = mobject.family_members_with_points() if len(fam1) != len(fam2): return False for m1, m2 in zip(fam1, fam2): if m1.get_num_points() != m2.get_num_points(): return False if not m1.data.dtype == m2.data.dtype: return False for key in m1.data.dtype.names: if not np.isclose(m1.data[key], m2.data[key]).all(): return False if set(m1.uniforms).difference(m2.uniforms): return False for key in m1.uniforms: value1 = m1.uniforms[key] value2 = m2.uniforms[key] if isinstance(value1, np.ndarray) and isinstance(value2, np.ndarray) and not value1.size == value2.size: return False if not np.isclose(value1, value2).all(): return False return True def has_same_shape_as(self, mobject: Mobject) -> bool: # Normalize both point sets by centering and making height 1 points1, points2 = ( (m.get_all_points() - m.get_center()) / m.get_height() for m in (self, mobject) ) if len(points1) != len(points2): return False return bool(np.isclose(points1, points2, atol=self.get_width() * 1e-2).all()) # Creating new Mobjects from this one def replicate(self, n: int) -> Self: group_class = self.get_group_class() return group_class(*(self.copy() for _ in range(n))) def get_grid( self, n_rows: int, n_cols: int, height: float | None = None, width: float | None = None, group_by_rows: bool = False, group_by_cols: bool = False, **kwargs ) -> Self: """ Returns a new mobject containing multiple copies of this one arranged in a grid """ total = n_rows * n_cols grid = self.replicate(total) if group_by_cols: kwargs["fill_rows_first"] = False grid.arrange_in_grid(n_rows, n_cols, **kwargs) if height is not None: grid.set_height(height) if width is not None: grid.set_height(width) group_class = self.get_group_class() if group_by_rows: return group_class(*(grid[n:n + n_cols] for n in range(0, total, n_cols))) elif group_by_cols: return group_class(*(grid[n:n + n_rows] for n in range(0, total, n_rows))) else: return grid # Updating def init_updaters(self): self.time_based_updaters: list[TimeBasedUpdater] = [] self.non_time_updaters: list[NonTimeUpdater] = [] self.has_updaters: bool = False self.updating_suspended: bool = False def update(self, dt: float = 0, recurse: bool = True) -> Self: if not self.has_updaters or self.updating_suspended: return self if recurse: for submob in self.submobjects: submob.update(dt, recurse) for updater in self.time_based_updaters: updater(self, dt) for updater in self.non_time_updaters: updater(self) return self def get_time_based_updaters(self) -> list[TimeBasedUpdater]: return self.time_based_updaters def has_time_based_updater(self) -> bool: return len(self.time_based_updaters) > 0 def get_updaters(self) -> list[Updater]: return self.time_based_updaters + self.non_time_updaters def get_family_updaters(self) -> list[Updater]: return list(it.chain(*[sm.get_updaters() for sm in self.get_family()])) def add_updater( self, update_function: Updater, index: int | None = None, call_updater: bool = True ) -> Self: if "dt" in get_parameters(update_function): updater_list = self.time_based_updaters else: updater_list = self.non_time_updaters if index is None: updater_list.append(update_function) else: updater_list.insert(index, update_function) self.refresh_has_updater_status() for parent in self.parents: parent.has_updaters = True if call_updater: self.update(dt=0) return self def remove_updater(self, update_function: Updater) -> Self: for updater_list in [self.time_based_updaters, self.non_time_updaters]: while update_function in updater_list: updater_list.remove(update_function) self.refresh_has_updater_status() return self def clear_updaters(self, recurse: bool = True) -> Self: self.time_based_updaters = [] self.non_time_updaters = [] if recurse: for submob in self.submobjects: submob.clear_updaters() self.refresh_has_updater_status() return self def match_updaters(self, mobject: Mobject) -> Self: self.clear_updaters() for updater in mobject.get_updaters(): self.add_updater(updater) return self def suspend_updating(self, recurse: bool = True) -> Self: self.updating_suspended = True if recurse: for submob in self.submobjects: submob.suspend_updating(recurse) return self def resume_updating(self, recurse: bool = True, call_updater: bool = True) -> Self: self.updating_suspended = False if recurse: for submob in self.submobjects: submob.resume_updating(recurse) for parent in self.parents: parent.resume_updating(recurse=False, call_updater=False) if call_updater: self.update(dt=0, recurse=recurse) return self def refresh_has_updater_status(self) -> Self: self.has_updaters = any(mob.get_updaters() for mob in self.get_family()) return self # Check if mark as static or not for camera def is_changing(self) -> bool: return self._is_animating or self.has_updaters def set_animating_status(self, is_animating: bool, recurse: bool = True) -> Self: for mob in (*self.get_family(recurse), *self.get_ancestors()): mob._is_animating = is_animating return self # Transforming operations def shift(self, vector: Vect3) -> Self: self.apply_points_function( lambda points: points + vector, about_edge=None, works_on_bounding_box=True, ) return self def scale( self, scale_factor: float | npt.ArrayLike, min_scale_factor: float = 1e-8, about_point: Vect3 | None = None, about_edge: Vect3 = ORIGIN ) -> Self: """ Default behavior is to scale about the center of the mobject. The argument about_edge can be a vector, indicating which side of the mobject to scale about, e.g., mob.scale(about_edge = RIGHT) scales about mob.get_right(). Otherwise, if about_point is given a value, scaling is done with respect to that point. """ if isinstance(scale_factor, numbers.Number): scale_factor = max(scale_factor, min_scale_factor) else: scale_factor = np.array(scale_factor).clip(min=min_scale_factor) self.apply_points_function( lambda points: scale_factor * points, about_point=about_point, about_edge=about_edge, works_on_bounding_box=True, ) for mob in self.get_family(): mob._handle_scale_side_effects(scale_factor) return self def _handle_scale_side_effects(self, scale_factor): # In case subclasses, such as DecimalNumber, need to make # any other changes when the size gets altered pass def stretch(self, factor: float, dim: int, **kwargs) -> Self: def func(points): points[:, dim] *= factor return points self.apply_points_function(func, works_on_bounding_box=True, **kwargs) return self def rotate_about_origin(self, angle: float, axis: Vect3 = OUT) -> Self: return self.rotate(angle, axis, about_point=ORIGIN) def rotate( self, angle: float, axis: Vect3 = OUT, about_point: Vect3 | None = None, **kwargs ) -> Self: rot_matrix_T = rotation_matrix_transpose(angle, axis) self.apply_points_function( lambda points: np.dot(points, rot_matrix_T), about_point, **kwargs ) return self def flip(self, axis: Vect3 = UP, **kwargs) -> Self: return self.rotate(TAU / 2, axis, **kwargs) def apply_function(self, function: Callable[[np.ndarray], np.ndarray], **kwargs) -> Self: # Default to applying matrix about the origin, not mobjects center if len(kwargs) == 0: kwargs["about_point"] = ORIGIN self.apply_points_function( lambda points: np.array([function(p) for p in points]), **kwargs ) return self def apply_function_to_position(self, function: Callable[[np.ndarray], np.ndarray]) -> Self: self.move_to(function(self.get_center())) return self def apply_function_to_submobject_positions( self, function: Callable[[np.ndarray], np.ndarray] ) -> Self: for submob in self.submobjects: submob.apply_function_to_position(function) return self def apply_matrix(self, matrix: npt.ArrayLike, **kwargs) -> Self: # Default to applying matrix about the origin, not mobjects center if ("about_point" not in kwargs) and ("about_edge" not in kwargs): kwargs["about_point"] = ORIGIN full_matrix = np.identity(self.dim) matrix = np.array(matrix) full_matrix[:matrix.shape[0], :matrix.shape[1]] = matrix self.apply_points_function( lambda points: np.dot(points, full_matrix.T), **kwargs ) return self def apply_complex_function(self, function: Callable[[complex], complex], **kwargs) -> Self: def R3_func(point): x, y, z = point xy_complex = function(complex(x, y)) return [ xy_complex.real, xy_complex.imag, z ] return self.apply_function(R3_func, **kwargs) def wag( self, direction: Vect3 = RIGHT, axis: Vect3 = DOWN, wag_factor: float = 1.0 ) -> Self: for mob in self.family_members_with_points(): alphas = np.dot(mob.get_points(), np.transpose(axis)) alphas -= min(alphas) alphas /= max(alphas) alphas = alphas**wag_factor mob.set_points(mob.get_points() + np.dot( alphas.reshape((len(alphas), 1)), np.array(direction).reshape((1, mob.dim)) )) return self # Positioning methods def center(self) -> Self: self.shift(-self.get_center()) return self def align_on_border( self, direction: Vect3, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER ) -> Self: """ Direction just needs to be a vector pointing towards side or corner in the 2d plane. """ target_point = np.sign(direction) * (FRAME_X_RADIUS, FRAME_Y_RADIUS, 0) point_to_align = self.get_bounding_box_point(direction) shift_val = target_point - point_to_align - buff * np.array(direction) shift_val = shift_val * abs(np.sign(direction)) self.shift(shift_val) return self def to_corner( self, corner: Vect3 = LEFT + DOWN, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER ) -> Self: return self.align_on_border(corner, buff) def to_edge( self, edge: Vect3 = LEFT, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER ) -> Self: return self.align_on_border(edge, buff) def next_to( self, mobject_or_point: Mobject | Vect3, direction: Vect3 = RIGHT, buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER, aligned_edge: Vect3 = ORIGIN, submobject_to_align: Mobject | None = None, index_of_submobject_to_align: int | slice | None = None, coor_mask: Vect3 = np.array([1, 1, 1]), ) -> Self: if isinstance(mobject_or_point, Mobject): mob = mobject_or_point if index_of_submobject_to_align is not None: target_aligner = mob[index_of_submobject_to_align] else: target_aligner = mob target_point = target_aligner.get_bounding_box_point( aligned_edge + direction ) else: target_point = mobject_or_point if submobject_to_align is not None: aligner = submobject_to_align elif index_of_submobject_to_align is not None: aligner = self[index_of_submobject_to_align] else: aligner = self point_to_align = aligner.get_bounding_box_point(aligned_edge - direction) self.shift((target_point - point_to_align + buff * direction) * coor_mask) return self def shift_onto_screen(self, **kwargs) -> Self: space_lengths = [FRAME_X_RADIUS, FRAME_Y_RADIUS] for vect in UP, DOWN, LEFT, RIGHT: dim = np.argmax(np.abs(vect)) buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_EDGE_BUFFER) max_val = space_lengths[dim] - buff edge_center = self.get_edge_center(vect) if np.dot(edge_center, vect) > max_val: self.to_edge(vect, **kwargs) return self def is_off_screen(self) -> bool: if self.get_left()[0] > FRAME_X_RADIUS: return True if self.get_right()[0] < -FRAME_X_RADIUS: return True if self.get_bottom()[1] > FRAME_Y_RADIUS: return True if self.get_top()[1] < -FRAME_Y_RADIUS: return True return False def stretch_about_point(self, factor: float, dim: int, point: Vect3) -> Self: return self.stretch(factor, dim, about_point=point) def stretch_in_place(self, factor: float, dim: int) -> Self: # Now redundant with stretch return self.stretch(factor, dim) def rescale_to_fit(self, length: float, dim: int, stretch: bool = False, **kwargs) -> Self: old_length = self.length_over_dim(dim) if old_length == 0: return self if stretch: self.stretch(length / old_length, dim, **kwargs) else: self.scale(length / old_length, **kwargs) return self def stretch_to_fit_width(self, width: float, **kwargs) -> Self: return self.rescale_to_fit(width, 0, stretch=True, **kwargs) def stretch_to_fit_height(self, height: float, **kwargs) -> Self: return self.rescale_to_fit(height, 1, stretch=True, **kwargs) def stretch_to_fit_depth(self, depth: float, **kwargs) -> Self: return self.rescale_to_fit(depth, 2, stretch=True, **kwargs) def set_width(self, width: float, stretch: bool = False, **kwargs) -> Self: return self.rescale_to_fit(width, 0, stretch=stretch, **kwargs) def set_height(self, height: float, stretch: bool = False, **kwargs) -> Self: return self.rescale_to_fit(height, 1, stretch=stretch, **kwargs) def set_depth(self, depth: float, stretch: bool = False, **kwargs) -> Self: return self.rescale_to_fit(depth, 2, stretch=stretch, **kwargs) def set_max_width(self, max_width: float, **kwargs) -> Self: if self.get_width() > max_width: self.set_width(max_width, **kwargs) return self def set_max_height(self, max_height: float, **kwargs) -> Self: if self.get_height() > max_height: self.set_height(max_height, **kwargs) return self def set_max_depth(self, max_depth: float, **kwargs) -> Self: if self.get_depth() > max_depth: self.set_depth(max_depth, **kwargs) return self def set_min_width(self, min_width: float, **kwargs) -> Self: if self.get_width() < min_width: self.set_width(min_width, **kwargs) return self def set_min_height(self, min_height: float, **kwargs) -> Self: if self.get_height() < min_height: self.set_height(min_height, **kwargs) return self def set_min_depth(self, min_depth: float, **kwargs) -> Self: if self.get_depth() < min_depth: self.set_depth(min_depth, **kwargs) return self def set_shape( self, width: Optional[float] = None, height: Optional[float] = None, depth: Optional[float] = None, **kwargs ) -> Self: if width is not None: self.set_width(width, stretch=True, **kwargs) if height is not None: self.set_height(height, stretch=True, **kwargs) if depth is not None: self.set_depth(depth, stretch=True, **kwargs) return self def set_coord(self, value: float, dim: int, direction: Vect3 = ORIGIN) -> Self: curr = self.get_coord(dim, direction) shift_vect = np.zeros(self.dim) shift_vect[dim] = value - curr self.shift(shift_vect) return self def set_x(self, x: float, direction: Vect3 = ORIGIN) -> Self: return self.set_coord(x, 0, direction) def set_y(self, y: float, direction: Vect3 = ORIGIN) -> Self: return self.set_coord(y, 1, direction) def set_z(self, z: float, direction: Vect3 = ORIGIN) -> Self: return self.set_coord(z, 2, direction) def space_out_submobjects(self, factor: float = 1.5, **kwargs) -> Self: self.scale(factor, **kwargs) for submob in self.submobjects: submob.scale(1. / factor) return self def move_to( self, point_or_mobject: Mobject | Vect3, aligned_edge: Vect3 = ORIGIN, coor_mask: Vect3 = np.array([1, 1, 1]) ) -> Self: if isinstance(point_or_mobject, Mobject): target = point_or_mobject.get_bounding_box_point(aligned_edge) else: target = point_or_mobject point_to_align = self.get_bounding_box_point(aligned_edge) self.shift((target - point_to_align) * coor_mask) return self def replace(self, mobject: Mobject, dim_to_match: int = 0, stretch: bool = False) -> Self: if not mobject.get_num_points() and not mobject.submobjects: self.scale(0) return self if stretch: for i in range(self.dim): self.rescale_to_fit(mobject.length_over_dim(i), i, stretch=True) else: self.rescale_to_fit( mobject.length_over_dim(dim_to_match), dim_to_match, stretch=False ) self.shift(mobject.get_center() - self.get_center()) return self def surround( self, mobject: Mobject, dim_to_match: int = 0, stretch: bool = False, buff: float = MED_SMALL_BUFF ) -> Self: self.replace(mobject, dim_to_match, stretch) length = mobject.length_over_dim(dim_to_match) self.scale((length + buff) / length) return self def put_start_and_end_on(self, start: Vect3, end: Vect3) -> Self: curr_start, curr_end = self.get_start_and_end() curr_vect = curr_end - curr_start if np.all(curr_vect == 0): raise Exception("Cannot position endpoints of closed loop") target_vect = end - start self.scale( get_norm(target_vect) / get_norm(curr_vect), about_point=curr_start, ) self.rotate( angle_of_vector(target_vect) - angle_of_vector(curr_vect), ) self.rotate( np.arctan2(curr_vect[2], get_norm(curr_vect[:2])) - np.arctan2(target_vect[2], get_norm(target_vect[:2])), axis=np.array([-target_vect[1], target_vect[0], 0]), ) self.shift(start - self.get_start()) return self # Color functions @affects_family_data def set_rgba_array( self, rgba_array: npt.ArrayLike, name: str = "rgba", recurse: bool = False ) -> Self: for mob in self.get_family(recurse): data = mob.data if mob.get_num_points() > 0 else mob._data_defaults data[name][:] = rgba_array return self def set_color_by_rgba_func( self, func: Callable[[Vect3], Vect4], recurse: bool = True ) -> Self: """ Func should take in a point in R3 and output an rgba value """ for mob in self.get_family(recurse): rgba_array = [func(point) for point in mob.get_points()] mob.set_rgba_array(rgba_array) return self def set_color_by_rgb_func( self, func: Callable[[Vect3], Vect3], opacity: float = 1, recurse: bool = True ) -> Self: """ Func should take in a point in R3 and output an rgb value """ for mob in self.get_family(recurse): rgba_array = [[*func(point), opacity] for point in mob.get_points()] mob.set_rgba_array(rgba_array) return self @affects_family_data def set_rgba_array_by_color( self, color: ManimColor | Iterable[ManimColor] | None = None, opacity: float | Iterable[float] | None = None, name: str = "rgba", recurse: bool = True ) -> Self: for mob in self.get_family(recurse): data = mob.data if mob.has_points() > 0 else mob._data_defaults if color is not None: rgbs = np.array(list(map(color_to_rgb, listify(color)))) if 1 < len(rgbs): rgbs = resize_with_interpolation(rgbs, len(data)) data[name][:, :3] = rgbs if opacity is not None: if not isinstance(opacity, (float, int)): opacity = resize_with_interpolation(np.array(opacity), len(data)) data[name][:, 3] = opacity return self def set_color( self, color: ManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float] | None = None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color, opacity, recurse=False) # Recurse to submobjects differently from how set_rgba_array_by_color # in case they implement set_color differently if recurse: for submob in self.submobjects: submob.set_color(color, recurse=True) return self def set_opacity( self, opacity: float | Iterable[float] | None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color=None, opacity=opacity, recurse=False) if recurse: for submob in self.submobjects: submob.set_opacity(opacity, recurse=True) return self def get_color(self) -> str: return rgb_to_hex(self.data["rgba"][0, :3]) def get_opacity(self) -> float: return self.data["rgba"][0, 3] def set_color_by_gradient(self, *colors: ManimColor) -> Self: if self.has_points(): self.set_color(colors) else: self.set_submobject_colors_by_gradient(*colors) return self def set_submobject_colors_by_gradient(self, *colors: ManimColor) -> Self: if len(colors) == 0: raise Exception("Need at least one color") elif len(colors) == 1: return self.set_color(*colors) # mobs = self.family_members_with_points() mobs = self.submobjects new_colors = color_gradient(colors, len(mobs)) for mob, color in zip(mobs, new_colors): mob.set_color(color) return self def fade(self, darkness: float = 0.5, recurse: bool = True) -> Self: self.set_opacity(1.0 - darkness, recurse=recurse) def get_shading(self) -> np.ndarray: return self.uniforms["shading"] def set_shading( self, reflectiveness: float | None = None, gloss: float | None = None, shadow: float | None = None, recurse: bool = True ) -> Self: """ Larger reflectiveness makes things brighter when facing the light Larger shadow makes faces opposite the light darker Makes parts bright where light gets reflected toward the camera """ for mob in self.get_family(recurse): for i, value in enumerate([reflectiveness, gloss, shadow]): if value is not None: mob.uniforms["shading"][i] = value return self def get_reflectiveness(self) -> float: return self.get_shading()[0] def get_gloss(self) -> float: return self.get_shading()[1] def get_shadow(self) -> float: return self.get_shading()[2] def set_reflectiveness(self, reflectiveness: float, recurse: bool = True) -> Self: self.set_shading(reflectiveness=reflectiveness, recurse=recurse) return self def set_gloss(self, gloss: float, recurse: bool = True) -> Self: self.set_shading(gloss=gloss, recurse=recurse) return self def set_shadow(self, shadow: float, recurse: bool = True) -> Self: self.set_shading(shadow=shadow, recurse=recurse) return self # Background rectangle def add_background_rectangle( self, color: ManimColor | None = None, opacity: float = 1.0, **kwargs ) -> Self: from manimlib.mobject.shape_matchers import BackgroundRectangle self.background_rectangle = BackgroundRectangle( self, color=color, fill_opacity=opacity, **kwargs ) self.add_to_back(self.background_rectangle) return self def add_background_rectangle_to_submobjects(self, **kwargs) -> Self: for submobject in self.submobjects: submobject.add_background_rectangle(**kwargs) return self def add_background_rectangle_to_family_members_with_points(self, **kwargs) -> Self: for mob in self.family_members_with_points(): mob.add_background_rectangle(**kwargs) return self # Getters def get_bounding_box_point(self, direction: Vect3) -> Vect3: bb = self.get_bounding_box() indices = (np.sign(direction) + 1).astype(int) return np.array([ bb[indices[i]][i] for i in range(3) ]) def get_edge_center(self, direction: Vect3) -> Vect3: return self.get_bounding_box_point(direction) def get_corner(self, direction: Vect3) -> Vect3: return self.get_bounding_box_point(direction) def get_all_corners(self): bb = self.get_bounding_box() return np.array([ [bb[indices[-i + 1]][i] for i in range(3)] for indices in it.product([0, 2], repeat=3) ]) def get_center(self) -> Vect3: return self.get_bounding_box()[1] def get_center_of_mass(self) -> Vect3: return self.get_all_points().mean(0) def get_boundary_point(self, direction: Vect3) -> Vect3: all_points = self.get_all_points() boundary_directions = all_points - self.get_center() norms = np.linalg.norm(boundary_directions, axis=1) boundary_directions /= np.repeat(norms, 3).reshape((len(norms), 3)) index = np.argmax(np.dot(boundary_directions, np.array(direction).T)) return all_points[index] def get_continuous_bounding_box_point(self, direction: Vect3) -> Vect3: dl, center, ur = self.get_bounding_box() corner_vect = (ur - center) return center + direction / np.max(np.abs(np.true_divide( direction, corner_vect, out=np.zeros(len(direction)), where=((corner_vect) != 0) ))) def get_top(self) -> Vect3: return self.get_edge_center(UP) def get_bottom(self) -> Vect3: return self.get_edge_center(DOWN) def get_right(self) -> Vect3: return self.get_edge_center(RIGHT) def get_left(self) -> Vect3: return self.get_edge_center(LEFT) def get_zenith(self) -> Vect3: return self.get_edge_center(OUT) def get_nadir(self) -> Vect3: return self.get_edge_center(IN) def length_over_dim(self, dim: int) -> float: bb = self.get_bounding_box() return abs((bb[2] - bb[0])[dim]) def get_width(self) -> float: return self.length_over_dim(0) def get_height(self) -> float: return self.length_over_dim(1) def get_depth(self) -> float: return self.length_over_dim(2) def get_shape(self) -> Tuple[float]: return tuple(self.length_over_dim(dim) for dim in range(3)) def get_coord(self, dim: int, direction: Vect3 = ORIGIN) -> float: """ Meant to generalize get_x, get_y, get_z """ return self.get_bounding_box_point(direction)[dim] def get_x(self, direction=ORIGIN) -> float: return self.get_coord(0, direction) def get_y(self, direction=ORIGIN) -> float: return self.get_coord(1, direction) def get_z(self, direction=ORIGIN) -> float: return self.get_coord(2, direction) def get_start(self) -> Vect3: self.throw_error_if_no_points() return self.get_points()[0].copy() def get_end(self) -> Vect3: self.throw_error_if_no_points() return self.get_points()[-1].copy() def get_start_and_end(self) -> tuple[Vect3, Vect3]: self.throw_error_if_no_points() points = self.get_points() return (points[0].copy(), points[-1].copy()) def point_from_proportion(self, alpha: float) -> Vect3: points = self.get_points() i, subalpha = integer_interpolate(0, len(points) - 1, alpha) return interpolate(points[i], points[i + 1], subalpha) def pfp(self, alpha): """Abbreviation for point_from_proportion""" return self.point_from_proportion(alpha) def get_pieces(self, n_pieces: int) -> Group: template = self.copy() template.set_submobjects([]) alphas = np.linspace(0, 1, n_pieces + 1) return Group(*[ template.copy().pointwise_become_partial( self, a1, a2 ) for a1, a2 in zip(alphas[:-1], alphas[1:]) ]) def get_z_index_reference_point(self) -> Vect3: # TODO, better place to define default z_index_group? z_index_group = getattr(self, "z_index_group", self) return z_index_group.get_center() # Match other mobject properties def match_color(self, mobject: Mobject) -> Self: return self.set_color(mobject.get_color()) def match_style(self, mobject: Mobject) -> Self: self.set_color(mobject.get_color()) self.set_opacity(mobject.get_opacity()) self.set_shading(*mobject.get_shading()) return self def match_dim_size(self, mobject: Mobject, dim: int, **kwargs) -> Self: return self.rescale_to_fit( mobject.length_over_dim(dim), dim, **kwargs ) def match_width(self, mobject: Mobject, **kwargs) -> Self: return self.match_dim_size(mobject, 0, **kwargs) def match_height(self, mobject: Mobject, **kwargs) -> Self: return self.match_dim_size(mobject, 1, **kwargs) def match_depth(self, mobject: Mobject, **kwargs) -> Self: return self.match_dim_size(mobject, 2, **kwargs) def match_coord( self, mobject_or_point: Mobject | Vect3, dim: int, direction: Vect3 = ORIGIN ) -> Self: if isinstance(mobject_or_point, Mobject): coord = mobject_or_point.get_coord(dim, direction) else: coord = mobject_or_point[dim] return self.set_coord(coord, dim=dim, direction=direction) def match_x( self, mobject_or_point: Mobject | Vect3, direction: Vect3 = ORIGIN ) -> Self: return self.match_coord(mobject_or_point, 0, direction) def match_y( self, mobject_or_point: Mobject | Vect3, direction: Vect3 = ORIGIN ) -> Self: return self.match_coord(mobject_or_point, 1, direction) def match_z( self, mobject_or_point: Mobject | Vect3, direction: Vect3 = ORIGIN ) -> Self: return self.match_coord(mobject_or_point, 2, direction) def align_to( self, mobject_or_point: Mobject | Vect3, direction: Vect3 = ORIGIN ) -> Self: """ Examples: mob1.align_to(mob2, UP) moves mob1 vertically so that its top edge lines ups with mob2's top edge. mob1.align_to(mob2, alignment_vect = RIGHT) moves mob1 horizontally so that it's center is directly above/below the center of mob2 """ if isinstance(mobject_or_point, Mobject): point = mobject_or_point.get_bounding_box_point(direction) else: point = mobject_or_point for dim in range(self.dim): if direction[dim] != 0: self.set_coord(point[dim], dim, direction) return self def get_group_class(self): return Group # Alignment def is_aligned_with(self, mobject: Mobject) -> bool: if len(self.data) != len(mobject.data): return False if len(self.submobjects) != len(mobject.submobjects): return False return all( sm1.is_aligned_with(sm2) for sm1, sm2 in zip(self.submobjects, mobject.submobjects) ) def align_data_and_family(self, mobject: Mobject) -> Self: self.align_family(mobject) self.align_data(mobject) return self def align_data(self, mobject: Mobject) -> Self: for mob1, mob2 in zip(self.get_family(), mobject.get_family()): mob1.align_points(mob2) return self def align_points(self, mobject: Mobject) -> Self: max_len = max(self.get_num_points(), mobject.get_num_points()) for mob in (self, mobject): mob.resize_points(max_len, resize_func=resize_preserving_order) return self def align_family(self, mobject: Mobject) -> Self: mob1 = self mob2 = mobject n1 = len(mob1) n2 = len(mob2) if n1 != n2: mob1.add_n_more_submobjects(max(0, n2 - n1)) mob2.add_n_more_submobjects(max(0, n1 - n2)) # Recurse for sm1, sm2 in zip(mob1.submobjects, mob2.submobjects): sm1.align_family(sm2) return self def push_self_into_submobjects(self) -> Self: copy = self.copy() copy.set_submobjects([]) self.resize_points(0) self.add(copy) return self def add_n_more_submobjects(self, n: int) -> Self: if n == 0: return self curr = len(self.submobjects) if curr == 0: # If empty, simply add n point mobjects null_mob = self.copy() null_mob.set_points([self.get_center()]) self.set_submobjects([ null_mob.copy() for k in range(n) ]) return self target = curr + n repeat_indices = (np.arange(target) * curr) // target split_factors = [ (repeat_indices == i).sum() for i in range(curr) ] new_submobs = [] for submob, sf in zip(self.submobjects, split_factors): new_submobs.append(submob) for k in range(1, sf): new_submobs.append(submob.invisible_copy()) self.set_submobjects(new_submobs) return self def invisible_copy(self) -> Self: return self.copy().set_opacity(0) # Interpolate def interpolate( self, mobject1: Mobject, mobject2: Mobject, alpha: float, path_func: Callable[[np.ndarray, np.ndarray, float], np.ndarray] = straight_path ) -> Self: keys = [k for k in self.data.dtype.names if k not in self.locked_data_keys] if keys: self.note_changed_data() for key in keys: func = path_func if key in self.pointlike_data_keys else interpolate md1 = mobject1.data[key] md2 = mobject2.data[key] if key in self.const_data_keys: md1 = md1[0] md2 = md2[0] self.data[key] = func(md1, md2, alpha) keys = [k for k in self.uniforms if k not in self.locked_uniform_keys] for key in keys: if key not in mobject1.uniforms or key not in mobject2.uniforms: continue self.uniforms[key] = interpolate( mobject1.uniforms[key], mobject2.uniforms[key], alpha ) self.bounding_box[:] = path_func( mobject1.bounding_box, mobject2.bounding_box, alpha ) return self def pointwise_become_partial(self, mobject, a, b) -> Self: """ Set points in such a way as to become only part of mobject. Inputs 0 <= a < b <= 1 determine what portion of mobject to become. """ # To be implemented in subclass return self # Locking data def lock_data(self, keys: Iterable[str]) -> Self: """ To speed up some animations, particularly transformations, it can be handy to acknowledge which pieces of data won't change during the animation so that calls to interpolate can skip this, and so that it's not read into the shader_wrapper objects needlessly """ if self.has_updaters: return self self.locked_data_keys = set(keys) return self def lock_uniforms(self, keys: Iterable[str]) -> Self: if self.has_updaters: return self self.locked_uniform_keys = set(keys) return self def lock_matching_data(self, mobject1: Mobject, mobject2: Mobject) -> Self: tuples = zip( self.get_family(), mobject1.get_family(), mobject2.get_family(), ) for sm, sm1, sm2 in tuples: if not sm.data.dtype == sm1.data.dtype == sm2.data.dtype: continue sm.lock_data( key for key in sm.data.dtype.names if arrays_match(sm1.data[key], sm2.data[key]) ) sm.lock_uniforms( key for key in self.uniforms if all(listify(mobject1.uniforms.get(key, 0) == mobject2.uniforms.get(key, 0))) ) sm.const_data_keys = set( key for key in sm.data.dtype.names if key not in sm.locked_data_keys if all( array_is_constant(mob.data[key]) for mob in (sm, sm1, sm2) ) ) return self def unlock_data(self) -> Self: for mob in self.get_family(): mob.locked_data_keys = set() mob.const_data_keys = set() mob.locked_uniform_keys = set() return self # Operations touching shader uniforms def affects_shader_info_id(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) self.refresh_shader_wrapper_id() return result return wrapper @affects_shader_info_id def set_uniform(self, recurse: bool = True, **new_uniforms) -> Self: for mob in self.get_family(recurse): mob.uniforms.update(new_uniforms) return self @affects_shader_info_id def fix_in_frame(self, recurse: bool = True) -> Self: self.set_uniform(recurse, is_fixed_in_frame=1.0) return self @affects_shader_info_id def unfix_from_frame(self, recurse: bool = True) -> Self: self.set_uniform(recurse, is_fixed_in_frame=0.0) return self def is_fixed_in_frame(self) -> bool: return bool(self.uniforms["is_fixed_in_frame"]) @affects_shader_info_id def apply_depth_test(self, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.depth_test = True return self @affects_shader_info_id def deactivate_depth_test(self, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.depth_test = False return self # Shader code manipulation @affects_data def replace_shader_code(self, old: str, new: str) -> Self: self.shader_code_replacements[old] = new self._shaders_initialized = False for mob in self.get_ancestors(): mob._shaders_initialized = False return self def set_color_by_code(self, glsl_code: str) -> Self: """ Takes a snippet of code and inserts it into a context which has the following variables: vec4 color, vec3 point, vec3 unit_normal. The code should change the color variable """ self.replace_shader_code( "///// INSERT COLOR FUNCTION HERE /////", glsl_code ) return self def set_color_by_xyz_func( self, glsl_snippet: str, min_value: float = -5.0, max_value: float = 5.0, colormap: str = "viridis" ) -> Self: """ Pass in a glsl expression in terms of x, y and z which returns a float. """ # TODO, add a version of this which changes the point data instead # of the shader code for char in "xyz": glsl_snippet = glsl_snippet.replace(char, "point." + char) rgb_list = get_colormap_list(colormap) self.set_color_by_code( "color.rgb = float_to_color({}, {}, {}, {});".format( glsl_snippet, float(min_value), float(max_value), get_colormap_code(rgb_list) ) ) return self # For shader data def init_shader_data(self, ctx: Context): self.shader_indices = np.zeros(0) self.shader_wrapper = ShaderWrapper( ctx=ctx, vert_data=self.data, shader_folder=self.shader_folder, texture_paths=self.texture_paths, depth_test=self.depth_test, render_primitive=self.render_primitive, ) def refresh_shader_wrapper_id(self): if self._shaders_initialized: self.shader_wrapper.refresh_id() return self def get_shader_wrapper(self, ctx: Context) -> ShaderWrapper: if not self._shaders_initialized: self.init_shader_data(ctx) self._shaders_initialized = True self.shader_wrapper.vert_data = self.get_shader_data() self.shader_wrapper.vert_indices = self.get_shader_vert_indices() self.shader_wrapper.bind_to_mobject_uniforms(self.get_uniforms()) self.shader_wrapper.depth_test = self.depth_test for old, new in self.shader_code_replacements.items(): self.shader_wrapper.replace_code(old, new) return self.shader_wrapper def get_shader_wrapper_list(self, ctx: Context) -> list[ShaderWrapper]: shader_wrappers = it.chain( [self.get_shader_wrapper(ctx)], *[sm.get_shader_wrapper_list(ctx) for sm in self.submobjects] ) batches = batch_by_property(shader_wrappers, lambda sw: sw.get_id()) result = [] for wrapper_group, sid in batches: shader_wrapper = wrapper_group[0] if not shader_wrapper.is_valid(): continue shader_wrapper.combine_with(*wrapper_group[1:]) if len(shader_wrapper.vert_data) > 0: result.append(shader_wrapper) return result def get_shader_data(self): return self.data def get_uniforms(self): return self.uniforms def get_shader_vert_indices(self): return self.shader_indices def render(self, ctx: Context, camera_uniforms: dict): if self._data_has_changed: self.shader_wrappers = self.get_shader_wrapper_list(ctx) for shader_wrapper in self.shader_wrappers: shader_wrapper.generate_vao() self._data_has_changed = False for shader_wrapper in self.shader_wrappers: shader_wrapper.update_program_uniforms(camera_uniforms) shader_wrapper.pre_render() shader_wrapper.render() # Event Handlers """ Event handling follows the Event Bubbling model of DOM in javascript. Return false to stop the event bubbling. To learn more visit https://www.quirksmode.org/js/events_order.html Event Callback Argument is a callable function taking two arguments: 1. Mobject 2. EventData """ def init_event_listners(self): self.event_listners: list[EventListener] = [] def add_event_listner( self, event_type: EventType, event_callback: Callable[[Mobject, dict[str]]] ): event_listner = EventListener(self, event_type, event_callback) self.event_listners.append(event_listner) EVENT_DISPATCHER.add_listner(event_listner) return self def remove_event_listner( self, event_type: EventType, event_callback: Callable[[Mobject, dict[str]]] ): event_listner = EventListener(self, event_type, event_callback) while event_listner in self.event_listners: self.event_listners.remove(event_listner) EVENT_DISPATCHER.remove_listner(event_listner) return self def clear_event_listners(self, recurse: bool = True): self.event_listners = [] if recurse: for submob in self.submobjects: submob.clear_event_listners(recurse=recurse) return self def get_event_listners(self): return self.event_listners def get_family_event_listners(self): return list(it.chain(*[sm.get_event_listners() for sm in self.get_family()])) def get_has_event_listner(self): return any( mob.get_event_listners() for mob in self.get_family() ) def add_mouse_motion_listner(self, callback): self.add_event_listner(EventType.MouseMotionEvent, callback) def remove_mouse_motion_listner(self, callback): self.remove_event_listner(EventType.MouseMotionEvent, callback) def add_mouse_press_listner(self, callback): self.add_event_listner(EventType.MousePressEvent, callback) def remove_mouse_press_listner(self, callback): self.remove_event_listner(EventType.MousePressEvent, callback) def add_mouse_release_listner(self, callback): self.add_event_listner(EventType.MouseReleaseEvent, callback) def remove_mouse_release_listner(self, callback): self.remove_event_listner(EventType.MouseReleaseEvent, callback) def add_mouse_drag_listner(self, callback): self.add_event_listner(EventType.MouseDragEvent, callback) def remove_mouse_drag_listner(self, callback): self.remove_event_listner(EventType.MouseDragEvent, callback) def add_mouse_scroll_listner(self, callback): self.add_event_listner(EventType.MouseScrollEvent, callback) def remove_mouse_scroll_listner(self, callback): self.remove_event_listner(EventType.MouseScrollEvent, callback) def add_key_press_listner(self, callback): self.add_event_listner(EventType.KeyPressEvent, callback) def remove_key_press_listner(self, callback): self.remove_event_listner(EventType.KeyPressEvent, callback) def add_key_release_listner(self, callback): self.add_event_listner(EventType.KeyReleaseEvent, callback) def remove_key_release_listner(self, callback): self.remove_event_listner(EventType.KeyReleaseEvent, callback) # Errors def throw_error_if_no_points(self): if not self.has_points(): message = "Cannot call Mobject.{} " +\ "for a Mobject with no points" caller_name = sys._getframe(1).f_code.co_name raise Exception(message.format(caller_name)) class Group(Mobject): def __init__(self, *mobjects: Mobject, **kwargs): if not all([isinstance(m, Mobject) for m in mobjects]): raise Exception("All submobjects must be of type Mobject") Mobject.__init__(self, **kwargs) self.add(*mobjects) if any(m.is_fixed_in_frame() for m in mobjects): self.fix_in_frame() def __add__(self, other: Mobject | Group) -> Self: assert(isinstance(other, Mobject)) return self.add(other) class Point(Mobject): def __init__( self, location: Vect3 = ORIGIN, artificial_width: float = 1e-6, artificial_height: float = 1e-6, **kwargs ): self.artificial_width = artificial_width self.artificial_height = artificial_height super().__init__(**kwargs) self.set_location(location) def get_width(self) -> float: return self.artificial_width def get_height(self) -> float: return self.artificial_height def get_location(self) -> Vect3: return self.get_points()[0].copy() def get_bounding_box_point(self, *args, **kwargs) -> Vect3: return self.get_location() def set_location(self, new_loc: npt.ArrayLike) -> Self: self.set_points(np.array(new_loc, ndmin=2, dtype=float)) return self class _AnimationBuilder: def __init__(self, mobject: Mobject): self.mobject = mobject self.overridden_animation = None self.mobject.generate_target() self.is_chaining = False self.methods: list[Callable] = [] self.anim_args = {} self.can_pass_args = True def __getattr__(self, method_name: str): method = getattr(self.mobject.target, method_name) self.methods.append(method) has_overridden_animation = hasattr(method, "_override_animate") if (self.is_chaining and has_overridden_animation) or self.overridden_animation: raise NotImplementedError( "Method chaining is currently not supported for " + \ "overridden animations" ) def update_target(*method_args, **method_kwargs): if has_overridden_animation: self.overridden_animation = method._override_animate( self.mobject, *method_args, **method_kwargs ) else: method(*method_args, **method_kwargs) return self self.is_chaining = True return update_target def __call__(self, **kwargs): return self.set_anim_args(**kwargs) def set_anim_args(self, **kwargs): ''' You can change the args of :class:`~manimlib.animation.transform.Transform`, such as - ``run_time`` - ``time_span`` - ``rate_func`` - ``lag_ratio`` - ``path_arc`` - ``path_func`` and so on. ''' if not self.can_pass_args: raise ValueError( "Animation arguments can only be passed by calling ``animate`` " + \ "or ``set_anim_args`` and can only be passed once", ) self.anim_args = kwargs self.can_pass_args = False return self def build(self): from manimlib.animation.transform import _MethodAnimation if self.overridden_animation: return self.overridden_animation return _MethodAnimation(self.mobject, self.methods, **self.anim_args) def override_animate(method): def decorator(animation_method): method._override_animate = animation_method return animation_method return decorator
manim_3b1b/manimlib/mobject/coordinate_systems.py
from __future__ import annotations from abc import ABC, abstractmethod import numbers import numpy as np import itertools as it from manimlib.constants import BLACK, BLUE, BLUE_D, BLUE_E, GREEN, GREY_A, WHITE, RED from manimlib.constants import DEGREES, PI from manimlib.constants import DL, UL, DOWN, DR, LEFT, ORIGIN, OUT, RIGHT, UP from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import MED_SMALL_BUFF, SMALL_BUFF from manimlib.mobject.functions import ParametricCurve from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import DashedLine from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.number_line import NumberLine from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.dot_cloud import DotCloud from manimlib.mobject.types.surface import ParametricSurface from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.simple_functions import binary_search from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import normalize from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, Type, TypeVar, Optional from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Vect3, Vect3Array, VectN, RangeSpecifier, Self T = TypeVar("T", bound=Mobject) EPSILON = 1e-8 DEFAULT_X_RANGE = (-8.0, 8.0, 1.0) DEFAULT_Y_RANGE = (-4.0, 4.0, 1.0) class CoordinateSystem(ABC): """ Abstract class for Axes and NumberPlane """ dimension: int = 2 def __init__( self, x_range: RangeSpecifier = DEFAULT_X_RANGE, y_range: RangeSpecifier = DEFAULT_Y_RANGE, num_sampled_graph_points_per_tick: int = 5, ): self.x_range = x_range self.y_range = y_range self.num_sampled_graph_points_per_tick = num_sampled_graph_points_per_tick @abstractmethod def coords_to_point(self, *coords: float | VectN) -> Vect3 | Vect3Array: raise Exception("Not implemented") @abstractmethod def point_to_coords(self, point: Vect3 | Vect3Array) -> tuple[float | VectN, ...]: raise Exception("Not implemented") def c2p(self, *coords: float) -> Vect3 | Vect3Array: """Abbreviation for coords_to_point""" return self.coords_to_point(*coords) def p2c(self, point: Vect3) -> tuple[float | VectN, ...]: """Abbreviation for point_to_coords""" return self.point_to_coords(point) def get_origin(self) -> Vect3: return self.c2p(*[0] * self.dimension) @abstractmethod def get_axes(self) -> VGroup: raise Exception("Not implemented") @abstractmethod def get_all_ranges(self) -> list[np.ndarray]: raise Exception("Not implemented") def get_axis(self, index: int) -> NumberLine: return self.get_axes()[index] def get_x_axis(self) -> NumberLine: return self.get_axis(0) def get_y_axis(self) -> NumberLine: return self.get_axis(1) def get_z_axis(self) -> NumberLine: return self.get_axis(2) def get_x_axis_label( self, label_tex: str, edge: Vect3 = RIGHT, direction: Vect3 = DL, **kwargs ) -> Tex: return self.get_axis_label( label_tex, self.get_x_axis(), edge, direction, **kwargs ) def get_y_axis_label( self, label_tex: str, edge: Vect3 = UP, direction: Vect3 = DR, **kwargs ) -> Tex: return self.get_axis_label( label_tex, self.get_y_axis(), edge, direction, **kwargs ) def get_axis_label( self, label_tex: str, axis: Vect3, edge: Vect3, direction: Vect3, buff: float = MED_SMALL_BUFF ) -> Tex: label = Tex(label_tex) label.next_to( axis.get_edge_center(edge), direction, buff=buff ) label.shift_onto_screen(buff=MED_SMALL_BUFF) return label def get_axis_labels( self, x_label_tex: str = "x", y_label_tex: str = "y" ) -> VGroup: self.axis_labels = VGroup( self.get_x_axis_label(x_label_tex), self.get_y_axis_label(y_label_tex), ) return self.axis_labels def get_line_from_axis_to_point( self, index: int, point: Vect3, line_func: Type[T] = DashedLine, color: ManimColor = GREY_A, stroke_width: float = 2 ) -> T: axis = self.get_axis(index) line = line_func(axis.get_projection(point), point) line.set_stroke(color, stroke_width) return line def get_v_line(self, point: Vect3, **kwargs): return self.get_line_from_axis_to_point(0, point, **kwargs) def get_h_line(self, point: Vect3, **kwargs): return self.get_line_from_axis_to_point(1, point, **kwargs) # Useful for graphing def get_graph( self, function: Callable[[float], float], x_range: Sequence[float] | None = None, bind: bool = False, **kwargs ) -> ParametricCurve: x_range = x_range or self.x_range t_range = np.ones(3) t_range[:len(x_range)] = x_range # For axes, the third coordinate of x_range indicates # tick frequency. But for functions, it indicates a # sample frequency t_range[2] /= self.num_sampled_graph_points_per_tick def parametric_function(t: float) -> Vect3: return self.c2p(t, function(t)) graph = ParametricCurve( parametric_function, t_range=tuple(t_range), **kwargs ) graph.underlying_function = function graph.x_range = x_range if bind: self.bind_graph_to_func(graph, function) return graph def get_parametric_curve( self, function: Callable[[float], Vect3], **kwargs ) -> ParametricCurve: dim = self.dimension graph = ParametricCurve( lambda t: self.coords_to_point(*function(t)[:dim]), **kwargs ) graph.underlying_function = function return graph def input_to_graph_point( self, x: float, graph: ParametricCurve ) -> Vect3 | None: if hasattr(graph, "underlying_function"): return self.coords_to_point(x, graph.underlying_function(x)) else: alpha = binary_search( function=lambda a: self.point_to_coords( graph.quick_point_from_proportion(a) )[0], target=x, lower_bound=self.x_range[0], upper_bound=self.x_range[1], ) if alpha is not None: return graph.quick_point_from_proportion(alpha) else: return None def i2gp(self, x: float, graph: ParametricCurve) -> Vect3 | None: """ Alias for input_to_graph_point """ return self.input_to_graph_point(x, graph) def bind_graph_to_func( self, graph: VMobject, func: Callable[[VectN], VectN], jagged: bool = False, get_discontinuities: Optional[Callable[[], Vect3]] = None ) -> VMobject: """ Use for graphing functions which might change over time, or change with conditions """ x_values = np.array([self.x_axis.p2n(p) for p in graph.get_points()]) def get_graph_points(): xs = x_values if get_discontinuities: ds = get_discontinuities() ep = 1e-6 added_xs = it.chain(*((d - ep, d + ep) for d in ds)) xs[:] = sorted([*x_values, *added_xs])[:len(x_values)] return self.c2p(xs, func(xs)) graph.add_updater( lambda g: g.set_points_as_corners(get_graph_points()) ) if not jagged: graph.add_updater(lambda g: g.make_smooth(approx=True)) return graph def get_graph_label( self, graph: ParametricCurve, label: str | Mobject = "f(x)", x: float | None = None, direction: Vect3 = RIGHT, buff: float = MED_SMALL_BUFF, color: ManimColor | None = None ) -> Tex | Mobject: if isinstance(label, str): label = Tex(label) if color is None: label.match_color(graph) if x is None: # Searching from the right, find a point # whose y value is in bounds max_y = FRAME_Y_RADIUS - label.get_height() max_x = FRAME_X_RADIUS - label.get_width() for x0 in np.arange(*self.x_range)[::-1]: pt = self.i2gp(x0, graph) if abs(pt[0]) < max_x and abs(pt[1]) < max_y: x = x0 break if x is None: x = self.x_range[1] point = self.input_to_graph_point(x, graph) angle = self.angle_of_tangent(x, graph) normal = rotate_vector(RIGHT, angle + 90 * DEGREES) if normal[1] < 0: normal *= -1 label.next_to(point, normal, buff=buff) label.shift_onto_screen() return label def get_v_line_to_graph(self, x: float, graph: ParametricCurve, **kwargs): return self.get_v_line(self.i2gp(x, graph), **kwargs) def get_h_line_to_graph(self, x: float, graph: ParametricCurve, **kwargs): return self.get_h_line(self.i2gp(x, graph), **kwargs) def get_scatterplot(self, x_values: Vect3Array, y_values: Vect3Array, **dot_config): return DotCloud(self.c2p(x_values, y_values), **dot_config) # For calculus def angle_of_tangent( self, x: float, graph: ParametricCurve, dx: float = EPSILON ) -> float: p0 = self.input_to_graph_point(x, graph) p1 = self.input_to_graph_point(x + dx, graph) return angle_of_vector(p1 - p0) def slope_of_tangent( self, x: float, graph: ParametricCurve, **kwargs ) -> float: return np.tan(self.angle_of_tangent(x, graph, **kwargs)) def get_tangent_line( self, x: float, graph: ParametricCurve, length: float = 5, line_func: Type[T] = Line ) -> T: line = line_func(LEFT, RIGHT) line.set_width(length) line.rotate(self.angle_of_tangent(x, graph)) line.move_to(self.input_to_graph_point(x, graph)) return line def get_riemann_rectangles( self, graph: ParametricCurve, x_range: Sequence[float] = None, dx: float | None = None, input_sample_type: str = "left", stroke_width: float = 1, stroke_color: ManimColor = BLACK, fill_opacity: float = 1, colors: Iterable[ManimColor] = (BLUE, GREEN), negative_color: ManimColor = RED, stroke_background: bool = True, show_signed_area: bool = True ) -> VGroup: if x_range is None: x_range = self.x_range[:2] if dx is None: dx = self.x_range[2] if len(x_range) < 3: x_range = [*x_range, dx] rects = [] x_range[1] = x_range[1] + dx xs = np.arange(*x_range) for x0, x1 in zip(xs, xs[1:]): if input_sample_type == "left": sample = x0 elif input_sample_type == "right": sample = x1 elif input_sample_type == "center": sample = 0.5 * x0 + 0.5 * x1 else: raise Exception("Invalid input sample type") height_vect = self.i2gp(sample, graph) - self.c2p(sample, 0) rect = Rectangle( width=self.x_axis.n2p(x1)[0] - self.x_axis.n2p(x0)[0], height=get_norm(height_vect), ) rect.positive = height_vect[1] > 0 rect.move_to(self.c2p(x0, 0), DL if rect.positive else UL) rects.append(rect) result = VGroup(*rects) result.set_submobject_colors_by_gradient(*colors) result.set_style( stroke_width=stroke_width, stroke_color=stroke_color, fill_opacity=fill_opacity, stroke_background=stroke_background ) for rect in result: if not rect.positive: rect.set_fill(negative_color) return result def get_area_under_graph(self, graph, x_range, fill_color=BLUE, fill_opacity=0.5): if not hasattr(graph, "x_range"): raise Exception("Argument `graph` must have attribute `x_range`") alpha_bounds = [ inverse_interpolate(*graph.x_range, x) for x in x_range ] sub_graph = graph.copy() sub_graph.pointwise_become_partial(graph, *alpha_bounds) sub_graph.add_line_to(self.c2p(x_range[1], 0)) sub_graph.add_line_to(self.c2p(x_range[0], 0)) sub_graph.add_line_to(sub_graph.get_start()) sub_graph.set_stroke(width=0) sub_graph.set_fill(fill_color, fill_opacity) return sub_graph class Axes(VGroup, CoordinateSystem): default_axis_config: dict = dict() default_x_axis_config: dict = dict() default_y_axis_config: dict = dict(line_to_number_direction=LEFT) def __init__( self, x_range: RangeSpecifier = DEFAULT_X_RANGE, y_range: RangeSpecifier = DEFAULT_Y_RANGE, axis_config: dict = dict(), x_axis_config: dict = dict(), y_axis_config: dict = dict(), height: float | None = None, width: float | None = None, unit_size: float = 1.0, **kwargs ): CoordinateSystem.__init__(self, x_range, y_range, **kwargs) kwargs.pop("num_sampled_graph_points_per_tick", None) VGroup.__init__(self, **kwargs) axis_config = dict(**axis_config, unit_size=unit_size) self.x_axis = self.create_axis( self.x_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_x_axis_config, axis_config, x_axis_config ), length=width, ) self.y_axis = self.create_axis( self.y_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_y_axis_config, axis_config, y_axis_config ), length=height, ) self.y_axis.rotate(90 * DEGREES, about_point=ORIGIN) # Add as a separate group in case various other # mobjects are added to self, as for example in # NumberPlane below self.axes = VGroup(self.x_axis, self.y_axis) self.add(*self.axes) self.center() def create_axis( self, range_terms: RangeSpecifier, axis_config: dict, length: float | None ) -> NumberLine: axis = NumberLine(range_terms, width=length, **axis_config) axis.shift(-axis.n2p(0)) return axis def coords_to_point(self, *coords: float | VectN) -> Vect3 | Vect3Array: origin = self.x_axis.number_to_point(0) return origin + sum( axis.number_to_point(coord) - origin for axis, coord in zip(self.get_axes(), coords) ) def point_to_coords(self, point: Vect3 | Vect3Array) -> tuple[float | VectN, ...]: return tuple([ axis.point_to_number(point) for axis in self.get_axes() ]) def get_axes(self) -> VGroup: return self.axes def get_all_ranges(self) -> list[Sequence[float]]: return [self.x_range, self.y_range] def add_coordinate_labels( self, x_values: Iterable[float] | None = None, y_values: Iterable[float] | None = None, excluding: Iterable[float] = [0], **kwargs ) -> VGroup: axes = self.get_axes() self.coordinate_labels = VGroup() for axis, values in zip(axes, [x_values, y_values]): labels = axis.add_numbers(values, excluding=excluding, **kwargs) self.coordinate_labels.add(labels) return self.coordinate_labels class ThreeDAxes(Axes): dimension: int = 3 default_z_axis_config: dict = dict() def __init__( self, x_range: RangeSpecifier = (-6.0, 6.0, 1.0), y_range: RangeSpecifier = (-5.0, 5.0, 1.0), z_range: RangeSpecifier = (-4.0, 4.0, 1.0), z_axis_config: dict = dict(), z_normal: Vect3 = DOWN, depth: float | None = None, flat_stroke: bool = False, **kwargs ): Axes.__init__(self, x_range, y_range, **kwargs) self.z_range = z_range self.z_axis = self.create_axis( self.z_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_z_axis_config, kwargs.get("axis_config", {}), z_axis_config ), length=depth, ) self.z_axis.rotate(-PI / 2, UP, about_point=ORIGIN) self.z_axis.rotate( angle_of_vector(z_normal), OUT, about_point=ORIGIN ) self.z_axis.shift(self.x_axis.n2p(0)) self.axes.add(self.z_axis) self.add(self.z_axis) self.set_flat_stroke(flat_stroke) def get_all_ranges(self) -> list[Sequence[float]]: return [self.x_range, self.y_range, self.z_range] def add_axis_labels(self, x_tex="x", y_tex="y", z_tex="z", font_size=24, buff=0.2): x_label, y_label, z_label = labels = VGroup(*( Tex(tex, font_size=font_size) for tex in [x_tex, y_tex, z_tex] )) z_label.rotate(PI / 2, RIGHT) for label, axis in zip(labels, self): label.next_to(axis, normalize(np.round(axis.get_vector()), 2), buff=buff) axis.add(label) self.axis_labels = labels def get_graph( self, func, color=BLUE_E, opacity=0.9, u_range=None, v_range=None, **kwargs ) -> ParametricSurface: xu = self.x_axis.get_unit_size() yu = self.y_axis.get_unit_size() zu = self.z_axis.get_unit_size() x0, y0, z0 = self.get_origin() u_range = u_range or self.x_range[:2] v_range = v_range or self.y_range[:2] return ParametricSurface( lambda u, v: [xu * u + x0, yu * v + y0, zu * func(u, v) + z0], u_range=u_range, v_range=v_range, color=color, opacity=opacity, **kwargs ) def get_parametric_surface( self, func, color=BLUE_E, opacity=0.9, **kwargs ) -> ParametricSurface: surface = ParametricSurface(func, color=color, opacity=opacity, **kwargs) xu = self.x_axis.get_unit_size() yu = self.y_axis.get_unit_size() zu = self.z_axis.get_unit_size() axes = [self.x_axis, self.y_axis, self.z_axis] for dim, axis in zip(range(3), axes): surface.stretch(axis.get_unit_size(), dim, about_point=ORIGIN) surface.shift(self.get_origin()) return surface class NumberPlane(Axes): default_axis_config: dict = dict( stroke_color=WHITE, stroke_width=2, include_ticks=False, include_tip=False, line_to_number_buff=SMALL_BUFF, line_to_number_direction=DL, ) default_y_axis_config: dict = dict( line_to_number_direction=DL, ) def __init__( self, x_range: RangeSpecifier = (-8.0, 8.0, 1.0), y_range: RangeSpecifier = (-4.0, 4.0, 1.0), background_line_style: dict = dict( stroke_color=BLUE_D, stroke_width=2, stroke_opacity=1, ), # Defaults to a faded version of line_config faded_line_style: dict = dict(), faded_line_ratio: int = 4, make_smooth_after_applying_functions: bool = True, **kwargs ): super().__init__(x_range, y_range, **kwargs) self.background_line_style = dict(background_line_style) self.faded_line_style = dict(faded_line_style) self.faded_line_ratio = faded_line_ratio self.make_smooth_after_applying_functions = make_smooth_after_applying_functions self.init_background_lines() def init_background_lines(self) -> None: if not self.faded_line_style: style = dict(self.background_line_style) # For anything numerical, like stroke_width # and stroke_opacity, chop it in half for key in style: if isinstance(style[key], numbers.Number): style[key] *= 0.5 self.faded_line_style = style self.background_lines, self.faded_lines = self.get_lines() self.background_lines.set_style(**self.background_line_style) self.faded_lines.set_style(**self.faded_line_style) self.add_to_back( self.faded_lines, self.background_lines, ) def get_lines(self) -> tuple[VGroup, VGroup]: x_axis = self.get_x_axis() y_axis = self.get_y_axis() x_lines1, x_lines2 = self.get_lines_parallel_to_axis(x_axis, y_axis) y_lines1, y_lines2 = self.get_lines_parallel_to_axis(y_axis, x_axis) lines1 = VGroup(*x_lines1, *y_lines1) lines2 = VGroup(*x_lines2, *y_lines2) return lines1, lines2 def get_lines_parallel_to_axis( self, axis1: NumberLine, axis2: NumberLine ) -> tuple[VGroup, VGroup]: freq = axis2.x_step ratio = self.faded_line_ratio line = Line(axis1.get_start(), axis1.get_end()) dense_freq = (1 + ratio) step = (1 / dense_freq) * freq lines1 = VGroup() lines2 = VGroup() inputs = np.arange(axis2.x_min, axis2.x_max + step, step) for i, x in enumerate(inputs): if abs(x) < 1e-8: continue new_line = line.copy() new_line.shift(axis2.n2p(x) - axis2.n2p(0)) if i % (1 + ratio) == 0: lines1.add(new_line) else: lines2.add(new_line) return lines1, lines2 def get_x_unit_size(self) -> float: return self.get_x_axis().get_unit_size() def get_y_unit_size(self) -> list: return self.get_x_axis().get_unit_size() def get_axes(self) -> VGroup: return self.axes def get_vector(self, coords: Iterable[float], **kwargs) -> Arrow: kwargs["buff"] = 0 return Arrow(self.c2p(0, 0), self.c2p(*coords), **kwargs) def prepare_for_nonlinear_transform(self, num_inserted_curves: int = 50) -> Self: for mob in self.family_members_with_points(): num_curves = mob.get_num_curves() if num_inserted_curves > num_curves: mob.insert_n_curves(num_inserted_curves - num_curves) mob.make_smooth_after_applying_functions = True return self class ComplexPlane(NumberPlane): def number_to_point(self, number: complex | float) -> Vect3: number = complex(number) return self.coords_to_point(number.real, number.imag) def n2p(self, number: complex | float) -> Vect3: return self.number_to_point(number) def point_to_number(self, point: Vect3) -> complex: x, y = self.point_to_coords(point) return complex(x, y) def p2n(self, point: Vect3) -> complex: return self.point_to_number(point) def get_default_coordinate_values( self, skip_first: bool = True ) -> list[complex]: x_numbers = self.get_x_axis().get_tick_range()[1:] y_numbers = self.get_y_axis().get_tick_range()[1:] y_numbers = [complex(0, y) for y in y_numbers if y != 0] return [*x_numbers, *y_numbers] def add_coordinate_labels( self, numbers: list[complex] | None = None, skip_first: bool = True, font_size: int = 36, **kwargs ) -> Self: if numbers is None: numbers = self.get_default_coordinate_values(skip_first) self.coordinate_labels = VGroup() for number in numbers: z = complex(number) if abs(z.imag) > abs(z.real): axis = self.get_y_axis() value = z.imag kwargs["unit_tex"] = "i" else: axis = self.get_x_axis() value = z.real number_mob = axis.get_number_mobject(value, font_size=font_size, **kwargs) # For -i, remove the "1" if z.imag == -1: number_mob.remove(number_mob[1]) number_mob[0].next_to( number_mob[1], LEFT, buff=number_mob[0].get_width() / 4 ) self.coordinate_labels.add(number_mob) self.add(self.coordinate_labels) return self
manim_3b1b/manimlib/mobject/three_dimensions.py
from __future__ import annotations import math import numpy as np from manimlib.constants import BLUE, BLUE_D, BLUE_E, GREY_A, BLACK from manimlib.constants import IN, ORIGIN, OUT, RIGHT from manimlib.constants import PI, TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.surface import SGroup from manimlib.mobject.types.surface import Surface from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Square from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import z_to_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Tuple, TypeVar from manimlib.typing import ManimColor, Vect3, Sequence T = TypeVar("T", bound=Mobject) class SurfaceMesh(VGroup): def __init__( self, uv_surface: Surface, resolution: Tuple[int, int] = (21, 11), stroke_width: float = 1, stroke_color: ManimColor = GREY_A, normal_nudge: float = 1e-2, depth_test: bool = True, joint_type: str = 'no_joint', flat_stroke: bool = False, **kwargs ): self.uv_surface = uv_surface self.resolution = resolution self.normal_nudge = normal_nudge super().__init__( stroke_color=stroke_color, stroke_width=stroke_width, depth_test=depth_test, joint_type=joint_type, **kwargs ) self.set_flat_stroke(flat_stroke) def init_points(self) -> None: uv_surface = self.uv_surface full_nu, full_nv = uv_surface.resolution part_nu, part_nv = self.resolution # 'indices' are treated as floats. Later, there will be # an interpolation between the floor and ceiling of these # indices u_indices = np.linspace(0, full_nu - 1, part_nu) v_indices = np.linspace(0, full_nv - 1, part_nv) points = uv_surface.get_points() normals = uv_surface.get_unit_normals() nudge = self.normal_nudge nudged_points = points + nudge * normals for ui in u_indices: path = VMobject() low_ui = full_nv * int(math.floor(ui)) high_ui = full_nv * int(math.ceil(ui)) path.set_points_smoothly(interpolate( nudged_points[low_ui:low_ui + full_nv], nudged_points[high_ui:high_ui + full_nv], ui % 1 )) self.add(path) for vi in v_indices: path = VMobject() path.set_points_smoothly(interpolate( nudged_points[int(math.floor(vi))::full_nv], nudged_points[int(math.ceil(vi))::full_nv], vi % 1 )) self.add(path) # 3D shapes class Sphere(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (1e-5, PI - 1e-5), resolution: Tuple[int, int] = (101, 51), radius: float = 1.0, **kwargs, ): self.radius = radius super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) def uv_func(self, u: float, v: float) -> np.ndarray: return self.radius * np.array([ math.cos(u) * math.sin(v), math.sin(u) * math.sin(v), -math.cos(v) ]) class Torus(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (0, TAU), r1: float = 3.0, r2: float = 1.0, **kwargs, ): self.r1 = r1 self.r2 = r2 super().__init__( u_range=u_range, v_range=v_range, **kwargs, ) def uv_func(self, u: float, v: float) -> np.ndarray: P = np.array([math.cos(u), math.sin(u), 0]) return (self.r1 - self.r2 * math.cos(v)) * P - self.r2 * math.sin(v) * OUT class Cylinder(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (-1, 1), resolution: Tuple[int, int] = (101, 11), height: float = 2, radius: float = 1, axis: Vect3 = OUT, **kwargs, ): self.height = height self.radius = radius self.axis = axis super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) def init_points(self): super().init_points() self.scale(self.radius) self.set_depth(self.height, stretch=True) self.apply_matrix(z_to_vector(self.axis)) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([np.cos(u), np.sin(u), v]) class Line3D(Cylinder): def __init__( self, start: Vect3, end: Vect3, width: float = 0.05, resolution: Tuple[int, int] = (21, 25), **kwargs ): axis = end - start super().__init__( height=get_norm(axis), radius=width / 2, axis=axis, resolution=resolution, **kwargs ) self.shift((start + end) / 2) class Disk3D(Surface): def __init__( self, radius: float = 1, u_range: Tuple[float, float] = (0, 1), v_range: Tuple[float, float] = (0, TAU), resolution: Tuple[int, int] = (2, 100), **kwargs ): super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs, ) self.scale(radius) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([ u * math.cos(v), u * math.sin(v), 0 ]) class Square3D(Surface): def __init__( self, side_length: float = 2.0, u_range: Tuple[float, float] = (-1, 1), v_range: Tuple[float, float] = (-1, 1), resolution: Tuple[int, int] = (2, 2), **kwargs, ): super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) self.scale(side_length / 2) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([u, v, 0]) def square_to_cube_faces(square: T) -> list[T]: radius = square.get_height() / 2 square.move_to(radius * OUT) result = [square.copy()] result.extend([ square.copy().rotate(PI / 2, axis=vect, about_point=ORIGIN) for vect in compass_directions(4) ]) result.append(square.copy().rotate(PI, RIGHT, about_point=ORIGIN)) return result class Cube(SGroup): def __init__( self, color: ManimColor = BLUE, opacity: float = 1, shading: Tuple[float, float, float] = (0.1, 0.5, 0.1), square_resolution: Tuple[int, int] = (2, 2), side_length: float = 2, **kwargs, ): face = Square3D( resolution=square_resolution, side_length=side_length, color=color, opacity=opacity, shading=shading, ) super().__init__(*square_to_cube_faces(face), **kwargs) class Prism(Cube): def __init__( self, width: float = 3.0, height: float = 2.0, depth: float = 1.0, **kwargs ): super().__init__(**kwargs) for dim, value in enumerate([width, height, depth]): self.rescale_to_fit(value, dim, stretch=True) class VGroup3D(VGroup): def __init__( self, *vmobjects: VMobject, depth_test: bool = True, shading: Tuple[float, float, float] = (0.2, 0.2, 0.2), joint_type: str = "no_joint", **kwargs ): super().__init__(*vmobjects, **kwargs) self.set_shading(*shading) self.set_joint_type(joint_type) if depth_test: self.apply_depth_test() class VCube(VGroup3D): def __init__( self, side_length: float = 2.0, fill_color: ManimColor = BLUE_D, fill_opacity: float = 1, stroke_width: float = 0, **kwargs ): style = dict( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) face = Square(side_length=side_length, **style) super().__init__(*square_to_cube_faces(face), **style) class VPrism(VCube): def __init__( self, width: float = 3.0, height: float = 2.0, depth: float = 1.0, **kwargs ): super().__init__(**kwargs) for dim, value in enumerate([width, height, depth]): self.rescale_to_fit(value, dim, stretch=True) class Dodecahedron(VGroup3D): def __init__( self, fill_color: ManimColor = BLUE_E, fill_opacity: float = 1, stroke_color: ManimColor = BLUE_E, stroke_width: float = 1, shading: Tuple[float, float, float] = (0.2, 0.2, 0.2), **kwargs, ): style = dict( fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, shading=shading, **kwargs ) # Start by creating two of the pentagons, meeting # back to back on the positive x-axis phi = (1 + math.sqrt(5)) / 2 x, y, z = np.identity(3) pentagon1 = Polygon( np.array([phi, 1 / phi, 0]), np.array([1, 1, 1]), np.array([1 / phi, 0, phi]), np.array([1, -1, 1]), np.array([phi, -1 / phi, 0]), **style ) pentagon2 = pentagon1.copy().stretch(-1, 2, about_point=ORIGIN) pentagon2.reverse_points() x_pair = VGroup(pentagon1, pentagon2) z_pair = x_pair.copy().apply_matrix(np.array([z, -x, -y]).T) y_pair = x_pair.copy().apply_matrix(np.array([y, z, x]).T) pentagons = [*x_pair, *y_pair, *z_pair] for pentagon in list(pentagons): pc = pentagon.copy() pc.apply_function(lambda p: -p) pc.reverse_points() pentagons.append(pc) super().__init__(*pentagons, **style) class Prismify(VGroup3D): def __init__(self, vmobject, depth=1.0, direction=IN, **kwargs): # At the moment, this assume stright edges vect = depth * direction pieces = [vmobject.copy()] points = vmobject.get_anchors() for p1, p2 in adjacent_pairs(points): wall = VMobject() wall.match_style(vmobject) wall.set_points_as_corners([p1, p2, p2 + vect, p1 + vect]) pieces.append(wall) top = vmobject.copy() top.shift(vect) top.reverse_points() pieces.append(top) super().__init__(*pieces, **kwargs)
manim_3b1b/manimlib/mobject/mobject_update_utils.py
from __future__ import annotations import inspect from manimlib.constants import DEGREES from manimlib.constants import RIGHT from manimlib.mobject.mobject import Mobject from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable import numpy as np from manimlib.animation.animation import Animation def assert_is_mobject_method(method): assert(inspect.ismethod(method)) mobject = method.__self__ assert(isinstance(mobject, Mobject)) def always(method, *args, **kwargs): 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, *arg_generators, **kwargs): """ 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], *args, **kwargs) -> Mobject: mob = func(*args, **kwargs) mob.add_updater(lambda m: mob.become(func(*args, **kwargs))) return mob def always_shift( mobject: Mobject, direction: np.ndarray = RIGHT, rate: float = 0.1 ) -> Mobject: mobject.add_updater( lambda m, dt: m.shift(dt * rate * direction) ) return mobject def always_rotate( mobject: Mobject, rate: float = 20 * DEGREES, **kwargs ) -> Mobject: mobject.add_updater( lambda m, dt: m.rotate(dt * rate, **kwargs) ) return mobject def turn_animation_into_updater( animation: Animation, cycle: bool = False, **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 uplon completion """ mobject = animation.mobject animation.update_rate_info(**kwargs) animation.suspend_mobject_updating = False animation.begin() animation.total_time = 0 def update(m, dt): run_time = animation.get_run_time() time_ratio = animation.total_time / run_time if cycle: alpha = time_ratio % 1 else: alpha = 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 )
manim_3b1b/manimlib/mobject/interactive.py
from __future__ import annotations import numpy as np from pyglet.window import key as PygletWindowKeys from manimlib.constants import FRAME_HEIGHT, FRAME_WIDTH from manimlib.constants import DOWN, LEFT, ORIGIN, RIGHT, UP from manimlib.constants import MED_LARGE_BUFF, MED_SMALL_BUFF, SMALL_BUFF from manimlib.constants import BLACK, BLUE, GREEN, GREY_A, GREY_C, RED, WHITE from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RoundedRectangle from manimlib.mobject.geometry import Square from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.value_tracker import ValueTracker from manimlib.utils.color import rgb_to_hex from manimlib.utils.space_ops import get_closest_point_on_line from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor # Interactive Mobjects class MotionMobject(Mobject): """ You could hold and drag this object to any position """ def __init__(self, mobject: Mobject, **kwargs): super().__init__(**kwargs) assert(isinstance(mobject, Mobject)) self.mobject = mobject self.mobject.add_mouse_drag_listner(self.mob_on_mouse_drag) # To avoid locking it as static mobject self.mobject.add_updater(lambda mob: None) self.add(mobject) def mob_on_mouse_drag(self, mob: Mobject, event_data: dict[str, np.ndarray]) -> bool: mob.move_to(event_data["point"]) return False class Button(Mobject): """ Pass any mobject and register an on_click method The on_click method takes mobject as argument like updater """ def __init__(self, mobject: Mobject, on_click: Callable[[Mobject]], **kwargs): super().__init__(**kwargs) assert(isinstance(mobject, Mobject)) self.on_click = on_click self.mobject = mobject self.mobject.add_mouse_press_listner(self.mob_on_mouse_press) self.add(self.mobject) def mob_on_mouse_press(self, mob: Mobject, event_data) -> bool: self.on_click(mob) return False # Controls class ControlMobject(ValueTracker): def __init__(self, value: float, *mobjects: Mobject, **kwargs): super().__init__(value=value, **kwargs) self.add(*mobjects) # To avoid lock_static_mobject_data while waiting in scene self.add_updater(lambda mob: None) self.fix_in_frame() def set_value(self, value: float): self.assert_value(value) self.set_value_anim(value) return ValueTracker.set_value(self, value) def assert_value(self, value): # To be implemented in subclasses pass def set_value_anim(self, value): # To be implemented in subclasses pass class EnableDisableButton(ControlMobject): def __init__( self, value: bool = True, value_type: np.dtype = np.dtype(bool), rect_kwargs: dict = { "width": 0.5, "height": 0.5, "fill_opacity": 1.0 }, enable_color: ManimColor = GREEN, disable_color: ManimColor = RED, **kwargs ): self.value = value self.value_type = value_type self.rect_kwargs = rect_kwargs self.enable_color = enable_color self.disable_color = disable_color self.box = Rectangle(**self.rect_kwargs) super().__init__(value, self.box, **kwargs) self.add_mouse_press_listner(self.on_mouse_press) def assert_value(self, value: bool) -> None: assert(isinstance(value, bool)) def set_value_anim(self, value: bool) -> None: if value: self.box.set_fill(self.enable_color) else: self.box.set_fill(self.disable_color) def toggle_value(self) -> None: super().set_value(not self.get_value()) def on_mouse_press(self, mob: Mobject, event_data) -> bool: mob.toggle_value() return False class Checkbox(ControlMobject): def __init__( self, value: bool = True, value_type: np.dtype = np.dtype(bool), rect_kwargs: dict = { "width": 0.5, "height": 0.5, "fill_opacity": 0.0 }, checkmark_kwargs: dict = { "stroke_color": GREEN, "stroke_width": 6, }, cross_kwargs: dict = { "stroke_color": RED, "stroke_width": 6, }, box_content_buff: float = SMALL_BUFF, **kwargs ): self.value_type = value_type self.rect_kwargs = rect_kwargs self.checkmark_kwargs = checkmark_kwargs self.cross_kwargs = cross_kwargs self.box_content_buff = box_content_buff self.box = Rectangle(**self.rect_kwargs) self.box_content = self.get_checkmark() if value else self.get_cross() super().__init__(value, self.box, self.box_content, **kwargs) self.add_mouse_press_listner(self.on_mouse_press) def assert_value(self, value: bool) -> None: assert(isinstance(value, bool)) def toggle_value(self) -> None: super().set_value(not self.get_value()) def set_value_anim(self, value: bool) -> None: if value: self.box_content.become(self.get_checkmark()) else: self.box_content.become(self.get_cross()) def on_mouse_press(self, mob: Mobject, event_data) -> None: mob.toggle_value() return False # Helper methods def get_checkmark(self) -> VGroup: checkmark = VGroup( Line(UP / 2 + 2 * LEFT, DOWN + LEFT, **self.checkmark_kwargs), Line(DOWN + LEFT, UP + RIGHT, **self.checkmark_kwargs) ) checkmark.stretch_to_fit_width(self.box.get_width()) checkmark.stretch_to_fit_height(self.box.get_height()) checkmark.scale(0.5) checkmark.move_to(self.box) return checkmark def get_cross(self) -> VGroup: cross = VGroup( Line(UP + LEFT, DOWN + RIGHT, **self.cross_kwargs), Line(UP + RIGHT, DOWN + LEFT, **self.cross_kwargs) ) cross.stretch_to_fit_width(self.box.get_width()) cross.stretch_to_fit_height(self.box.get_height()) cross.scale(0.5) cross.move_to(self.box) return cross class LinearNumberSlider(ControlMobject): def __init__( self, value: float = 0, value_type: type = np.float64, min_value: float = -10.0, max_value: float = 10.0, step: float = 1.0, rounded_rect_kwargs: dict = { "height": 0.075, "width": 2, "corner_radius": 0.0375 }, circle_kwargs: dict = { "radius": 0.1, "stroke_color": GREY_A, "fill_color": GREY_A, "fill_opacity": 1.0 }, **kwargs ): self.value_type = value_type self.min_value = min_value self.max_value = max_value self.step = step self.rounded_rect_kwargs = rounded_rect_kwargs self.circle_kwargs = circle_kwargs self.bar = RoundedRectangle(**self.rounded_rect_kwargs) self.slider = Circle(**self.circle_kwargs) self.slider_axis = Line( start=self.bar.get_bounding_box_point(LEFT), end=self.bar.get_bounding_box_point(RIGHT) ) self.slider_axis.set_opacity(0.0) self.slider.move_to(self.slider_axis) self.slider.add_mouse_drag_listner(self.slider_on_mouse_drag) super().__init__(value, self.bar, self.slider, self.slider_axis, **kwargs) def assert_value(self, value: float) -> None: assert(self.min_value <= value <= self.max_value) def set_value_anim(self, value: float) -> None: prop = (value - self.min_value) / (self.max_value - self.min_value) self.slider.move_to(self.slider_axis.point_from_proportion(prop)) def slider_on_mouse_drag(self, mob, event_data: dict[str, np.ndarray]) -> bool: self.set_value(self.get_value_from_point(event_data["point"])) return False # Helper Methods def get_value_from_point(self, point: np.ndarray) -> float: start, end = self.slider_axis.get_start_and_end() point_on_line = get_closest_point_on_line(start, end, point) prop = get_norm(point_on_line - start) / get_norm(end - start) value = self.min_value + prop * (self.max_value - self.min_value) no_of_steps = int((value - self.min_value) / self.step) value_nearest_to_step = self.min_value + no_of_steps * self.step return value_nearest_to_step class ColorSliders(Group): def __init__( self, sliders_kwargs: dict = {}, rect_kwargs: dict = { "width": 2.0, "height": 0.5, "stroke_opacity": 1.0 }, background_grid_kwargs: dict = { "colors": [GREY_A, GREY_C], "single_square_len": 0.1 }, sliders_buff: float = MED_LARGE_BUFF, default_rgb_value: int = 255, default_a_value: int = 1, **kwargs ): self.sliders_kwargs = sliders_kwargs self.rect_kwargs = rect_kwargs self.background_grid_kwargs = background_grid_kwargs self.sliders_buff = sliders_buff self.default_rgb_value = default_rgb_value self.default_a_value = default_a_value rgb_kwargs = {"value": self.default_rgb_value, "min_value": 0, "max_value": 255, "step": 1} a_kwargs = {"value": self.default_a_value, "min_value": 0, "max_value": 1, "step": 0.04} self.r_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.g_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.b_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.a_slider = LinearNumberSlider(**self.sliders_kwargs, **a_kwargs) self.sliders = Group( self.r_slider, self.g_slider, self.b_slider, self.a_slider ) self.sliders.arrange(DOWN, buff=self.sliders_buff) self.r_slider.slider.set_color(RED) self.g_slider.slider.set_color(GREEN) self.b_slider.slider.set_color(BLUE) self.a_slider.slider.set_color_by_gradient(BLACK, WHITE) self.selected_color_box = Rectangle(**self.rect_kwargs) self.selected_color_box.add_updater( lambda mob: mob.set_fill( self.get_picked_color(), self.get_picked_opacity() ) ) self.background = self.get_background() super().__init__( Group(self.background, self.selected_color_box).fix_in_frame(), self.sliders, **kwargs ) self.arrange(DOWN) def get_background(self) -> VGroup: single_square_len = self.background_grid_kwargs["single_square_len"] colors = self.background_grid_kwargs["colors"] width = self.rect_kwargs["width"] height = self.rect_kwargs["height"] rows = int(height / single_square_len) cols = int(width / single_square_len) cols = (cols + 1) if (cols % 2 == 0) else cols single_square = Square(single_square_len) grid = single_square.get_grid(n_rows=rows, n_cols=cols, buff=0.0) grid.stretch_to_fit_width(width) grid.stretch_to_fit_height(height) grid.move_to(self.selected_color_box) for idx, square in enumerate(grid): assert(isinstance(square, Square)) square.set_stroke(width=0.0, opacity=0.0) square.set_fill(colors[idx % len(colors)], 1.0) return grid def set_value(self, r: float, g: float, b: float, a: float): self.r_slider.set_value(r) self.g_slider.set_value(g) self.b_slider.set_value(b) self.a_slider.set_value(a) def get_value(self) -> np.ndarary: r = self.r_slider.get_value() / 255 g = self.g_slider.get_value() / 255 b = self.b_slider.get_value() / 255 alpha = self.a_slider.get_value() return np.array((r, g, b, alpha)) def get_picked_color(self) -> str: rgba = self.get_value() return rgb_to_hex(rgba[:3]) def get_picked_opacity(self) -> float: rgba = self.get_value() return rgba[3] class Textbox(ControlMobject): def __init__( self, value: str = "", value_type: np.dtype = np.dtype(object), box_kwargs: dict = { "width": 2.0, "height": 1.0, "fill_color": WHITE, "fill_opacity": 1.0, }, text_kwargs: dict = { "color": BLUE }, text_buff: float = MED_SMALL_BUFF, isInitiallyActive: bool = False, active_color: ManimColor = BLUE, deactive_color: ManimColor = RED, **kwargs ): self.value_type = value_type self.box_kwargs = box_kwargs self.text_kwargs = text_kwargs self.text_buff = text_buff self.isInitiallyActive = isInitiallyActive self.active_color = active_color self.deactive_color = deactive_color self.isActive = self.isInitiallyActive self.box = Rectangle(**self.box_kwargs) self.box.add_mouse_press_listner(self.box_on_mouse_press) self.text = Text(value, **self.text_kwargs) super().__init__(value, self.box, self.text, **kwargs) self.update_text(value) self.active_anim(self.isActive) self.add_key_press_listner(self.on_key_press) def set_value_anim(self, value: str) -> None: self.update_text(value) def update_text(self, value: str) -> None: text = self.text self.remove(text) text.__init__(value, **self.text_kwargs) height = text.get_height() text.set_width(self.box.get_width() - 2 * self.text_buff) if text.get_height() > height: text.set_height(height) text.add_updater(lambda mob: mob.move_to(self.box)) text.fix_in_frame() self.add(text) def active_anim(self, isActive: bool) -> None: if isActive: self.box.set_stroke(self.active_color) else: self.box.set_stroke(self.deactive_color) def box_on_mouse_press(self, mob, event_data) -> bool: self.isActive = not self.isActive self.active_anim(self.isActive) return False def on_key_press(self, mob: Mobject, event_data: dict[str, int]) -> bool | None: symbol = event_data["symbol"] modifiers = event_data["modifiers"] char = chr(symbol) if mob.isActive: old_value = mob.get_value() new_value = old_value if char.isalnum(): if (modifiers & PygletWindowKeys.MOD_SHIFT) or (modifiers & PygletWindowKeys.MOD_CAPSLOCK): new_value = old_value + char.upper() else: new_value = old_value + char.lower() elif symbol in [PygletWindowKeys.SPACE]: new_value = old_value + char elif symbol == PygletWindowKeys.TAB: new_value = old_value + '\t' elif symbol == PygletWindowKeys.BACKSPACE: new_value = old_value[:-1] or '' mob.set_value(new_value) return False class ControlPanel(Group): def __init__( self, *controls: ControlMobject, panel_kwargs: dict = { "width": FRAME_WIDTH / 4, "height": MED_SMALL_BUFF + FRAME_HEIGHT, "fill_color": GREY_C, "fill_opacity": 1.0, "stroke_width": 0.0 }, opener_kwargs: dict = { "width": FRAME_WIDTH / 8, "height": 0.5, "fill_color": GREY_C, "fill_opacity": 1.0 }, opener_text_kwargs: dict = { "text": "Control Panel", "font_size": 20 }, **kwargs ): self.panel_kwargs = panel_kwargs self.opener_kwargs = opener_kwargs self.opener_text_kwargs = opener_text_kwargs self.panel = Rectangle(**self.panel_kwargs) self.panel.to_corner(UP + LEFT, buff=0) self.panel.shift(self.panel.get_height() * UP) self.panel.add_mouse_scroll_listner(self.panel_on_mouse_scroll) self.panel_opener_rect = Rectangle(**self.opener_kwargs) self.panel_info_text = Text(**self.opener_text_kwargs) self.panel_info_text.move_to(self.panel_opener_rect) self.panel_opener = Group(self.panel_opener_rect, self.panel_info_text) self.panel_opener.next_to(self.panel, DOWN, aligned_edge=DOWN) self.panel_opener.add_mouse_drag_listner(self.panel_opener_on_mouse_drag) self.controls = Group(*controls) self.controls.arrange(DOWN, center=False, aligned_edge=ORIGIN) self.controls.move_to(self.panel) super().__init__( self.panel, self.panel_opener, self.controls, **kwargs ) self.move_panel_and_controls_to_panel_opener() self.fix_in_frame() def move_panel_and_controls_to_panel_opener(self) -> None: self.panel.next_to( self.panel_opener_rect, direction=UP, buff=0 ) controls_old_x = self.controls.get_x() self.controls.next_to( self.panel_opener_rect, direction=UP, buff=MED_SMALL_BUFF ) self.controls.set_x(controls_old_x) def add_controls(self, *new_controls: ControlMobject) -> None: self.controls.add(*new_controls) self.move_panel_and_controls_to_panel_opener() def remove_controls(self, *controls_to_remove: ControlMobject) -> None: self.controls.remove(*controls_to_remove) self.move_panel_and_controls_to_panel_opener() def open_panel(self): panel_opener_x = self.panel_opener.get_x() self.panel_opener.to_corner(DOWN + LEFT, buff=0.0) self.panel_opener.set_x(panel_opener_x) self.move_panel_and_controls_to_panel_opener() return self def close_panel(self): panel_opener_x = self.panel_opener.get_x() self.panel_opener.to_corner(UP + LEFT, buff=0.0) self.panel_opener.set_x(panel_opener_x) self.move_panel_and_controls_to_panel_opener() return self def panel_opener_on_mouse_drag(self, mob, event_data: dict[str, np.ndarray]) -> bool: point = event_data["point"] self.panel_opener.match_y(Dot(point)) self.move_panel_and_controls_to_panel_opener() return False def panel_on_mouse_scroll(self, mob, event_data: dict[str, np.ndarray]) -> bool: offset = event_data["offset"] factor = 10 * offset[1] self.controls.set_y(self.controls.get_y() + factor) return False
manim_3b1b/manimlib/mobject/changing.py
from __future__ import annotations import numpy as np from manimlib.constants import BLUE_B, BLUE_D, BLUE_E, GREY_BROWN, WHITE from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.rate_functions import smooth from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, List, Iterable from manimlib.typing import ManimColor, Vect3, Self class AnimatedBoundary(VGroup): def __init__( self, vmobject: VMobject, colors: List[ManimColor] = [BLUE_D, BLUE_B, BLUE_E, GREY_BROWN], max_stroke_width: float = 3.0, cycle_rate: float = 0.5, back_and_forth: bool = True, draw_rate_func: Callable[[float], float] = smooth, fade_rate_func: Callable[[float], float] = smooth, **kwargs ): super().__init__(**kwargs) self.vmobject: VMobject = vmobject self.colors = colors self.max_stroke_width = max_stroke_width self.cycle_rate = cycle_rate self.back_and_forth = back_and_forth self.draw_rate_func = draw_rate_func self.fade_rate_func = fade_rate_func self.boundary_copies: list[VMobject] = [ vmobject.copy().set_style( stroke_width=0, fill_opacity=0 ) for x in range(2) ] self.add(*self.boundary_copies) self.total_time: float = 0 self.add_updater( lambda m, dt: self.update_boundary_copies(dt) ) def update_boundary_copies(self, dt: float) -> Self: # Not actual time, but something which passes at # an altered rate to make the implementation below # cleaner time = self.total_time * self.cycle_rate growing, fading = self.boundary_copies colors = self.colors msw = self.max_stroke_width vmobject = self.vmobject index = int(time % len(colors)) alpha = time % 1 draw_alpha = self.draw_rate_func(alpha) fade_alpha = self.fade_rate_func(alpha) if self.back_and_forth and int(time) % 2 == 1: bounds = (1 - draw_alpha, 1) else: bounds = (0, draw_alpha) self.full_family_become_partial(growing, vmobject, *bounds) growing.set_stroke(colors[index], width=msw) if time >= 1: self.full_family_become_partial(fading, vmobject, 0, 1) fading.set_stroke( color=colors[index - 1], width=(1 - fade_alpha) * msw ) self.total_time += dt return self def full_family_become_partial( self, mob1: VMobject, mob2: VMobject, a: float, b: float ) -> Self: family1 = mob1.family_members_with_points() family2 = mob2.family_members_with_points() for sm1, sm2 in zip(family1, family2): sm1.pointwise_become_partial(sm2, a, b) return self class TracedPath(VMobject): def __init__( self, traced_point_func: Callable[[], Vect3], time_traced: float = np.inf, time_per_anchor: float = 1.0 / 15, stroke_width: float | Iterable[float] = 2.0, stroke_color: ManimColor = WHITE, fill_opacity: float = 0.0, **kwargs ): super().__init__( stroke_width=stroke_width, stroke_color=stroke_color, fill_opacity=fill_opacity, **kwargs ) self.traced_point_func = traced_point_func self.time_traced = time_traced self.time_per_anchor = time_per_anchor self.time: float = 0 self.traced_points: list[np.ndarray] = [] self.add_updater(lambda m, dt: m.update_path(dt)) def update_path(self, dt: float) -> Self: if dt == 0: return self point = self.traced_point_func().copy() self.traced_points.append(point) if self.time_traced < np.inf: n_relevant_points = int(self.time_traced / dt + 0.5) n_tps = len(self.traced_points) if n_tps < n_relevant_points: points = self.traced_points + [point] * (n_relevant_points - n_tps) else: points = self.traced_points[n_tps - n_relevant_points:] # Every now and then refresh the list if n_tps > 10 * n_relevant_points: self.traced_points = self.traced_points[-n_relevant_points:] else: points = self.traced_points if points: self.set_points_smoothly(points) self.time += dt return self class TracingTail(TracedPath): def __init__( self, mobject_or_func: Mobject | Callable[[], np.ndarray], time_traced: float = 1.0, stroke_width: float | Iterable[float] = (0, 3), stroke_opacity: float | Iterable[float] = (0, 1), stroke_color: ManimColor = WHITE, **kwargs ): if isinstance(mobject_or_func, Mobject): func = mobject_or_func.get_center else: func = mobject_or_func super().__init__( func, time_traced=time_traced, stroke_width=stroke_width, stroke_opacity=stroke_opacity, stroke_color=stroke_color, **kwargs )
manim_3b1b/manimlib/mobject/number_line.py
from __future__ import annotations import numpy as np from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import GREY_B from manimlib.constants import MED_SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import outer_interpolate from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.simple_functions import fdiv from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.typing import ManimColor, Vect3, Vect3Array, VectN, RangeSpecifier class NumberLine(Line): def __init__( self, x_range: RangeSpecifier = (-8, 8, 1), color: ManimColor = GREY_B, stroke_width: float = 2.0, # How big is one one unit of this number line in terms of absolute spacial distance unit_size: float = 1.0, width: float | None = None, include_ticks: bool = True, tick_size: float = 0.1, longer_tick_multiple: float = 1.5, tick_offset: float = 0.0, # Change name numbers_with_elongated_ticks: list[float] = [], include_numbers: bool = False, line_to_number_direction: Vect3 = DOWN, line_to_number_buff: float = MED_SMALL_BUFF, include_tip: bool = False, tip_config: dict = dict( width=0.25, length=0.25, ), decimal_number_config: dict = dict( num_decimal_places=0, font_size=36, ), numbers_to_exclude: list | None = None, **kwargs, ): self.x_range = x_range self.tick_size = tick_size self.longer_tick_multiple = longer_tick_multiple self.tick_offset = tick_offset self.numbers_with_elongated_ticks = list(numbers_with_elongated_ticks) self.line_to_number_direction = line_to_number_direction self.line_to_number_buff = line_to_number_buff self.include_tip = include_tip self.tip_config = dict(tip_config) self.decimal_number_config = dict(decimal_number_config) self.numbers_to_exclude = numbers_to_exclude self.x_min, self.x_max = x_range[:2] self.x_step = 1 if len(x_range) == 2 else x_range[2] super().__init__( self.x_min * RIGHT, self.x_max * RIGHT, color=color, stroke_width=stroke_width, **kwargs ) if width: self.set_width(width) else: self.scale(unit_size) self.center() if include_tip: self.add_tip() self.tip.set_stroke( self.stroke_color, self.stroke_width, ) if include_ticks: self.add_ticks() if include_numbers: self.add_numbers(excluding=self.numbers_to_exclude) def get_tick_range(self) -> np.ndarray: if self.include_tip: x_max = self.x_max else: x_max = self.x_max + self.x_step result = np.arange(self.x_min, x_max, self.x_step) return result[result <= self.x_max] def add_ticks(self) -> None: ticks = VGroup() for x in self.get_tick_range(): size = self.tick_size if np.isclose(self.numbers_with_elongated_ticks, x).any(): size *= self.longer_tick_multiple ticks.add(self.get_tick(x, size)) self.add(ticks) self.ticks = ticks def get_tick(self, x: float, size: float | None = None) -> Line: if size is None: size = self.tick_size result = Line(size * DOWN, size * UP) result.rotate(self.get_angle()) result.move_to(self.number_to_point(x)) result.match_style(self) return result def get_tick_marks(self) -> VGroup: return self.ticks def number_to_point(self, number: float | VectN) -> Vect3 | Vect3Array: start = self.get_points()[0] end = self.get_points()[-1] alpha = (number - self.x_min) / (self.x_max - self.x_min) return outer_interpolate(start, end, alpha) def point_to_number(self, point: Vect3 | Vect3Array) -> float | VectN: start = self.get_points()[0] end = self.get_points()[-1] vect = end - start proportion = fdiv( np.dot(point - start, vect), np.dot(end - start, vect), ) return interpolate(self.x_min, self.x_max, proportion) def n2p(self, number: float | VectN) -> Vect3 | Vect3Array: """Abbreviation for number_to_point""" return self.number_to_point(number) def p2n(self, point: Vect3 | Vect3Array) -> float | VectN: """Abbreviation for point_to_number""" return self.point_to_number(point) def get_unit_size(self) -> float: return self.get_length() / (self.x_max - self.x_min) def get_number_mobject( self, x: float, direction: Vect3 | None = None, buff: float | None = None, unit: float = 1.0, unit_tex: str = "", **number_config ) -> DecimalNumber: number_config = merge_dicts_recursively( self.decimal_number_config, number_config, ) if direction is None: direction = self.line_to_number_direction if buff is None: buff = self.line_to_number_buff if unit_tex: number_config["unit"] = unit_tex num_mob = DecimalNumber(x / unit, **number_config) num_mob.next_to( self.number_to_point(x), direction=direction, buff=buff ) if x < 0 and direction[0] == 0: # Align without the minus sign num_mob.shift(num_mob[0].get_width() * LEFT / 2) if x == unit and unit_tex: center = num_mob.get_center() num_mob.remove(num_mob[0]) num_mob.move_to(center) return num_mob def add_numbers( self, x_values: Iterable[float] | None = None, excluding: Iterable[float] | None = None, font_size: int = 24, **kwargs ) -> VGroup: if x_values is None: x_values = self.get_tick_range() kwargs["font_size"] = font_size if excluding is None: excluding = self.numbers_to_exclude numbers = VGroup() for x in x_values: if excluding is not None and x in excluding: continue numbers.add(self.get_number_mobject(x, **kwargs)) self.add(numbers) self.numbers = numbers return numbers class UnitInterval(NumberLine): def __init__( self, x_range: RangeSpecifier = (0, 1, 0.1), unit_size: float = 10, numbers_with_elongated_ticks: list[float] = [0, 1], decimal_number_config: dict = dict( num_decimal_places=1, ) ): super().__init__( x_range=x_range, unit_size=unit_size, numbers_with_elongated_ticks=numbers_with_elongated_ticks, decimal_number_config=decimal_number_config, )
manim_3b1b/manimlib/mobject/frame.py
from __future__ import annotations from manimlib.constants import BLACK, GREY_E from manimlib.constants import FRAME_HEIGHT from manimlib.mobject.geometry import Rectangle from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor class ScreenRectangle(Rectangle): def __init__( self, aspect_ratio: float = 16.0 / 9.0, height: float = 4, **kwargs ): super().__init__( width=aspect_ratio * height, height=height, **kwargs ) class FullScreenRectangle(ScreenRectangle): def __init__( self, height: float = FRAME_HEIGHT, fill_color: ManimColor = GREY_E, fill_opacity: float = 1, stroke_width: float = 0, **kwargs, ): super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, ) class FullScreenFadeRectangle(FullScreenRectangle): def __init__( self, stroke_width: float = 0.0, fill_color: ManimColor = BLACK, fill_opacity: float = 0.7, **kwargs, ): super().__init__( stroke_width=stroke_width, fill_color=fill_color, fill_opacity=fill_opacity, )
manim_3b1b/manimlib/mobject/functions.py
from __future__ import annotations from isosurfaces import plot_isoline import numpy as np from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import YELLOW from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, Tuple from manimlib.typing import ManimColor, Vect3 class ParametricCurve(VMobject): def __init__( self, t_func: Callable[[float], Sequence[float] | Vect3], t_range: Tuple[float, float, float] = (0, 1, 0.1), epsilon: float = 1e-8, # TODO, automatically figure out discontinuities discontinuities: Sequence[float] = [], use_smoothing: bool = True, **kwargs ): self.t_func = t_func self.t_range = t_range self.epsilon = epsilon self.discontinuities = discontinuities self.use_smoothing = use_smoothing super().__init__(**kwargs) def get_point_from_function(self, t: float) -> Vect3: return np.array(self.t_func(t)) def init_points(self): t_min, t_max, step = self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps > t_min) & (jumps < t_max)] boundary_times = [t_min, t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.use_smoothing: self.make_smooth(approx=True) if not self.has_points(): self.set_points(np.array([self.t_func(t_min)])) return self def get_t_func(self): return self.t_func def get_function(self): if hasattr(self, "underlying_function"): return self.underlying_function if hasattr(self, "function"): return self.function def get_x_range(self): if hasattr(self, "x_range"): return self.x_range class FunctionGraph(ParametricCurve): def __init__( self, function: Callable[[float], float], x_range: Tuple[float, float, float] = (-8, 8, 0.25), color: ManimColor = YELLOW, **kwargs ): self.function = function self.x_range = x_range def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) class ImplicitFunction(VMobject): def __init__( self, func: Callable[[float, float], float], x_range: Tuple[float, float] = (-FRAME_X_RADIUS, FRAME_X_RADIUS), y_range: Tuple[float, float] = (-FRAME_Y_RADIUS, FRAME_Y_RADIUS), min_depth: int = 5, max_quads: int = 1500, use_smoothing: bool = False, joint_type: str = 'no_joint', **kwargs ): super().__init__(joint_type=joint_type, **kwargs) p_min, p_max = ( np.array([x_range[0], y_range[0]]), np.array([x_range[1], y_range[1]]), ) curves = plot_isoline( fn=lambda u: func(u[0], u[1]), pmin=p_min, pmax=p_max, min_depth=min_depth, max_quads=max_quads, ) # returns a list of lists of 2D points curves = [ np.pad(curve, [(0, 0), (0, 1)]) for curve in curves if curve != [] ] # add z coord as 0 for curve in curves: self.start_new_path(curve[0]) self.add_points_as_corners(curve[1:]) if use_smoothing: self.make_smooth()
manim_3b1b/manimlib/mobject/numbers.py
from __future__ import annotations import numpy as np from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import WHITE from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import TypeVar from manimlib.typing import ManimColor, Vect3, Self T = TypeVar("T", bound=VMobject) class DecimalNumber(VMobject): def __init__( self, number: float | complex = 0, color: ManimColor = WHITE, stroke_width: float = 0, fill_opacity: float = 1.0, num_decimal_places: int = 2, include_sign: bool = False, group_with_commas: bool = True, digit_buff_per_font_unit: float = 0.001, show_ellipsis: bool = False, unit: str | None = None, # Aligned to bottom unless it starts with "^" include_background_rectangle: bool = False, edge_to_fix: Vect3 = LEFT, font_size: float = 48, text_config: dict = dict(), # Do not pass in font_size here **kwargs ): self.num_decimal_places = num_decimal_places self.include_sign = include_sign self.group_with_commas = group_with_commas self.digit_buff_per_font_unit = digit_buff_per_font_unit self.show_ellipsis = show_ellipsis self.unit = unit self.include_background_rectangle = include_background_rectangle self.edge_to_fix = edge_to_fix self.font_size = font_size self.text_config = dict(text_config) self.char_to_mob_map = dict() super().__init__( color=color, stroke_width=stroke_width, fill_opacity=fill_opacity, **kwargs ) self.set_submobjects_from_number(number) self.init_colors() def set_submobjects_from_number(self, number: float | complex) -> None: self.number = number self.set_submobjects([]) self.text_config["font_size"] = self.get_font_size() num_string = self.num_string = self.get_num_string(number) self.add(*map(self.char_to_mob, num_string)) # Add non-numerical bits if self.show_ellipsis: dots = self.char_to_mob("...") dots.arrange(RIGHT, buff=2 * dots[0].get_width()) self.add(dots) if self.unit is not None: self.unit_sign = Tex(self.unit, font_size=self.get_font_size()) self.add(self.unit_sign) self.arrange( buff=self.digit_buff_per_font_unit * self.get_font_size(), aligned_edge=DOWN ) # Handle alignment of parts that should be aligned # to the bottom for i, c in enumerate(num_string): if c == "–" and len(num_string) > i + 1: self[i].align_to(self[i + 1], UP) self[i].shift(self[i + 1].get_height() * DOWN / 2) elif c == ",": self[i].shift(self[i].get_height() * DOWN / 2) if self.unit and self.unit.startswith("^"): self.unit_sign.align_to(self, UP) if self.include_background_rectangle: self.add_background_rectangle() def get_num_string(self, number: float | complex) -> str: if isinstance(number, complex): formatter = self.get_complex_formatter() else: formatter = self.get_formatter() if self.num_decimal_places == 0 and isinstance(number, float): number = int(number) num_string = formatter.format(number) rounded_num = np.round(number, self.num_decimal_places) if num_string.startswith("-") and rounded_num == 0: if self.include_sign: num_string = "+" + num_string[1:] else: num_string = num_string[1:] num_string = num_string.replace("-", "–") return num_string def char_to_mob(self, char: str) -> Tex | Text: if char not in self.char_to_mob_map: self.char_to_mob_map[char] = Text(char, **self.text_config) result = self.char_to_mob_map[char].copy() result.scale(self.get_font_size() / result.font_size) return result def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["font_size"] = self.font_size def get_font_size(self) -> float: return float(self.uniforms["font_size"]) def get_formatter(self, **kwargs) -> str: """ Configuration is based first off instance attributes, but overwritten by any kew word argument. Relevant key words: - include_sign - group_with_commas - num_decimal_places - field_name (e.g. 0 or 0.real) """ config = dict([ (attr, getattr(self, attr)) for attr in [ "include_sign", "group_with_commas", "num_decimal_places", ] ]) config.update(kwargs) ndp = config["num_decimal_places"] return "".join([ "{", config.get("field_name", ""), ":", "+" if config["include_sign"] else "", "," if config["group_with_commas"] else "", f".{ndp}f" if ndp > 0 else "d", "}", ]) def get_complex_formatter(self, **kwargs) -> str: return "".join([ self.get_formatter(field_name="0.real"), self.get_formatter(field_name="0.imag", include_sign=True), "i" ]) def get_tex(self): return self.num_string def set_value(self, number: float | complex) -> Self: move_to_point = self.get_edge_center(self.edge_to_fix) style = self.family_members_with_points()[0].get_style() self.set_submobjects_from_number(number) self.move_to(move_to_point, self.edge_to_fix) self.set_style(**style) self.fix_in_frame(self._is_fixed_in_frame) return self def _handle_scale_side_effects(self, scale_factor: float) -> Self: self.uniforms["font_size"] = scale_factor * self.uniforms["font_size"] return self def get_value(self) -> float | complex: return self.number def increment_value(self, delta_t: float | complex = 1) -> Self: self.set_value(self.get_value() + delta_t) return self class Integer(DecimalNumber): def __init__( self, number: int = 0, num_decimal_places: int = 0, **kwargs, ): super().__init__(number, num_decimal_places=num_decimal_places, **kwargs) def get_value(self) -> int: return int(np.round(super().get_value()))
manim_3b1b/manimlib/mobject/probability.py
from __future__ import annotations import numpy as np from manimlib.constants import BLUE, BLUE_E, GREEN_E, GREY_B, GREY_D, MAROON_B, YELLOW from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import MED_LARGE_BUFF, MED_SMALL_BUFF, SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.brace import Brace from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.color import color_gradient from manimlib.utils.iterables import listify from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.typing import ManimColor EPSILON = 0.0001 class SampleSpace(Rectangle): def __init__( self, width: float = 3, height: float = 3, fill_color: ManimColor = GREY_D, fill_opacity: float = 1, stroke_width: float = 0.5, stroke_color: ManimColor = GREY_B, default_label_scale_val: float = 1, **kwargs, ): super().__init__( width, height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, stroke_color=stroke_color, ) self.default_label_scale_val = default_label_scale_val def add_title( self, title: str = "Sample space", buff: float = MED_SMALL_BUFF ) -> None: # TODO, should this really exist in SampleSpaceScene title_mob = TexText(title) if title_mob.get_width() > self.get_width(): title_mob.set_width(self.get_width()) title_mob.next_to(self, UP, buff=buff) self.title = title_mob self.add(title_mob) def add_label(self, label: str) -> None: self.label = label def complete_p_list(self, p_list: list[float]) -> list[float]: new_p_list = listify(p_list) remainder = 1.0 - sum(new_p_list) if abs(remainder) > EPSILON: new_p_list.append(remainder) return new_p_list def get_division_along_dimension( self, p_list: list[float], dim: int, colors: Iterable[ManimColor], vect: np.ndarray ) -> VGroup: p_list = self.complete_p_list(p_list) colors = color_gradient(colors, len(p_list)) last_point = self.get_edge_center(-vect) parts = VGroup() for factor, color in zip(p_list, colors): part = SampleSpace() part.set_fill(color, 1) part.replace(self, stretch=True) part.stretch(factor, dim) part.move_to(last_point, -vect) last_point = part.get_edge_center(vect) parts.add(part) return parts def get_horizontal_division( self, p_list: list[float], colors: Iterable[ManimColor] = [GREEN_E, BLUE_E], vect: np.ndarray = DOWN ) -> VGroup: return self.get_division_along_dimension(p_list, 1, colors, vect) def get_vertical_division( self, p_list: list[float], colors: Iterable[ManimColor] = [MAROON_B, YELLOW], vect: np.ndarray = RIGHT ) -> VGroup: return self.get_division_along_dimension(p_list, 0, colors, vect) def divide_horizontally(self, *args, **kwargs) -> None: self.horizontal_parts = self.get_horizontal_division(*args, **kwargs) self.add(self.horizontal_parts) def divide_vertically(self, *args, **kwargs) -> None: self.vertical_parts = self.get_vertical_division(*args, **kwargs) self.add(self.vertical_parts) def get_subdivision_braces_and_labels( self, parts: VGroup, labels: str, direction: np.ndarray, buff: float = SMALL_BUFF, ) -> VGroup: label_mobs = VGroup() braces = VGroup() for label, part in zip(labels, parts): brace = Brace( part, direction, buff=buff ) if isinstance(label, Mobject): label_mob = label else: label_mob = Tex(label) label_mob.scale(self.default_label_scale_val) label_mob.next_to(brace, direction, buff) braces.add(brace) label_mobs.add(label_mob) parts.braces = braces parts.labels = label_mobs parts.label_kwargs = { "labels": label_mobs.copy(), "direction": direction, "buff": buff, } return VGroup(parts.braces, parts.labels) def get_side_braces_and_labels( self, labels: str, direction: np.ndarray = LEFT, **kwargs ) -> VGroup: assert(hasattr(self, "horizontal_parts")) parts = self.horizontal_parts return self.get_subdivision_braces_and_labels(parts, labels, direction, **kwargs) def get_top_braces_and_labels( self, labels: str, **kwargs ) -> VGroup: assert(hasattr(self, "vertical_parts")) parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, UP, **kwargs) def get_bottom_braces_and_labels( self, labels: str, **kwargs ) -> VGroup: assert(hasattr(self, "vertical_parts")) parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, DOWN, **kwargs) def add_braces_and_labels(self) -> None: for attr in "horizontal_parts", "vertical_parts": if not hasattr(self, attr): continue parts = getattr(self, attr) for subattr in "braces", "labels": if hasattr(parts, subattr): self.add(getattr(parts, subattr)) def __getitem__(self, index: int | slice) -> VGroup: if hasattr(self, "horizontal_parts"): return self.horizontal_parts[index] elif hasattr(self, "vertical_parts"): return self.vertical_parts[index] return self.split()[index] class BarChart(VGroup): def __init__( self, values: Iterable[float], height: float = 4, width: float = 6, n_ticks: int = 4, include_x_ticks: bool = False, tick_width: float = 0.2, tick_height: float = 0.15, label_y_axis: bool = True, y_axis_label_height: float = 0.25, max_value: float = 1, bar_colors: list[ManimColor] = [BLUE, YELLOW], bar_fill_opacity: float = 0.8, bar_stroke_width: float = 3, bar_names: list[str] = [], bar_label_scale_val: float = 0.75, **kwargs ): super().__init__(**kwargs) self.height = height self.width = width self.n_ticks = n_ticks self.include_x_ticks = include_x_ticks self.tick_width = tick_width self.tick_height = tick_height self.label_y_axis = label_y_axis self.y_axis_label_height = y_axis_label_height self.max_value = max_value self.bar_colors = bar_colors self.bar_fill_opacity = bar_fill_opacity self.bar_stroke_width = bar_stroke_width self.bar_names = bar_names self.bar_label_scale_val = bar_label_scale_val if self.max_value is None: self.max_value = max(values) self.n_ticks_x = len(values) self.add_axes() self.add_bars(values) self.center() def add_axes(self) -> None: x_axis = Line(self.tick_width * LEFT / 2, self.width * RIGHT) y_axis = Line(MED_LARGE_BUFF * DOWN, self.height * UP) y_ticks = VGroup() heights = np.linspace(0, self.height, self.n_ticks + 1) values = np.linspace(0, self.max_value, self.n_ticks + 1) for y, value in zip(heights, values): y_tick = Line(LEFT, RIGHT) y_tick.set_width(self.tick_width) y_tick.move_to(y * UP) y_ticks.add(y_tick) y_axis.add(y_ticks) if self.include_x_ticks == True: x_ticks = VGroup() widths = np.linspace(0, self.width, self.n_ticks_x + 1) label_values = np.linspace(0, len(self.bar_names), self.n_ticks_x + 1) for x, value in zip(widths, label_values): x_tick = Line(UP, DOWN) x_tick.set_height(self.tick_height) x_tick.move_to(x * RIGHT) x_ticks.add(x_tick) x_axis.add(x_ticks) self.add(x_axis, y_axis) self.x_axis, self.y_axis = x_axis, y_axis if self.label_y_axis: labels = VGroup() for y_tick, value in zip(y_ticks, values): label = Tex(str(np.round(value, 2))) label.set_height(self.y_axis_label_height) label.next_to(y_tick, LEFT, SMALL_BUFF) labels.add(label) self.y_axis_labels = labels self.add(labels) def add_bars(self, values: Iterable[float]) -> None: buff = float(self.width) / (2 * len(values)) bars = VGroup() for i, value in enumerate(values): bar = Rectangle( height=(value / self.max_value) * self.height, width=buff, stroke_width=self.bar_stroke_width, fill_opacity=self.bar_fill_opacity, ) bar.move_to((2 * i + 0.5) * buff * RIGHT, DOWN + LEFT * 5) bars.add(bar) bars.set_color_by_gradient(*self.bar_colors) bar_labels = VGroup() for bar, name in zip(bars, self.bar_names): label = Tex(str(name)) label.scale(self.bar_label_scale_val) label.next_to(bar, DOWN, SMALL_BUFF) bar_labels.add(label) self.add(bars, bar_labels) self.bars = bars self.bar_labels = bar_labels def change_bar_values(self, values: Iterable[float]) -> None: for bar, value in zip(self.bars, values): bar_bottom = bar.get_bottom() bar.stretch_to_fit_height( (value / self.max_value) * self.height ) bar.move_to(bar_bottom, DOWN)
manim_3b1b/manimlib/mobject/geometry.py
from __future__ import annotations import math import numbers import numpy as np from manimlib.constants import DL, DOWN, DR, LEFT, ORIGIN, OUT, RIGHT, UL, UP, UR from manimlib.constants import GREY_A, RED, WHITE, BLACK from manimlib.constants import MED_SMALL_BUFF, SMALL_BUFF from manimlib.constants import DEGREES, PI, TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import DashedVMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import bezier from manimlib.utils.bezier import quadratic_bezier_points_for_arc from manimlib.utils.bezier import partial_quadratic_bezier_points from manimlib.utils.iterables import adjacent_n_tuples from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.simple_functions import clip from manimlib.utils.simple_functions import fdiv from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import find_intersection from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import normalize from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import rotation_matrix_transpose from manimlib.utils.space_ops import rotation_about_z from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, Optional from manimlib.typing import ManimColor, Vect3, Vect3Array, Self DEFAULT_DOT_RADIUS = 0.08 DEFAULT_SMALL_DOT_RADIUS = 0.04 DEFAULT_DASH_LENGTH = 0.05 DEFAULT_ARROW_TIP_LENGTH = 0.35 DEFAULT_ARROW_TIP_WIDTH = 0.35 # Deprecate? class TipableVMobject(VMobject): """ 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 the TipableVMobject instance's tip(s), its length etc """ tip_config: dict = dict( fill_opacity=1.0, stroke_width=0.0, tip_style=0.0, # triangle=0, inner_smooth=1, dot=2 ) # Adding, Creating, Modifying tips def add_tip(self, at_start: bool = False, **kwargs) -> 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. """ tip = self.create_tip(at_start, **kwargs) self.reset_endpoints_based_on_tip(tip, at_start) self.asign_tip_attr(tip, at_start) tip.set_color(self.get_stroke_color()) self.add(tip) return self def create_tip(self, at_start: bool = False, **kwargs) -> ArrowTip: """ Stylises the tip, positions it spacially, and returns the newly instantiated tip to the caller. """ tip = self.get_unpositioned_tip(**kwargs) self.position_tip(tip, at_start) return tip def get_unpositioned_tip(self, **kwargs) -> ArrowTip: """ Returns a tip that has been stylistically configured, but has not yet been given a position in space. """ config = dict() config.update(self.tip_config) config.update(kwargs) return ArrowTip(**config) def position_tip(self, tip: ArrowTip, at_start: bool = False) -> 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() tip.rotate(angle_of_vector(handle - anchor) - PI - tip.get_angle()) tip.shift(anchor - tip.get_tip_point()) return tip def reset_endpoints_based_on_tip(self, tip: 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: start = tip.get_base() end = self.get_end() else: start = self.get_start() end = tip.get_base() self.put_start_and_end_on(start, end) return self def asign_tip_attr(self, tip: 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 = VGroup() 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 = VGroup() if hasattr(self, "tip"): result.add(self.tip) if hasattr(self, "start_tip"): result.add(self.start_tip) return result def get_tip(self) -> ArrowTip: """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: return tips[0] def get_default_tip_length(self) -> float: return self.tip_length def get_first_handle(self) -> Vect3: return self.get_points()[1] def get_last_handle(self) -> Vect3: return self.get_points()[-2] def get_end(self) -> Vect3: if self.has_tip(): return self.tip.get_start() else: return VMobject.get_end(self) def get_start(self) -> Vect3: if self.has_start_tip(): return self.start_tip.get_start() else: return VMobject.get_start(self) def get_length(self) -> float: start, end = self.get_start_and_end() return get_norm(start - end) class Arc(TipableVMobject): def __init__( self, start_angle: float = 0, angle: float = TAU / 4, radius: float = 1.0, n_components: int = 8, arc_center: Vect3 = ORIGIN, **kwargs ): super().__init__(**kwargs) self.set_points(quadratic_bezier_points_for_arc(angle, n_components)) self.rotate(start_angle, about_point=ORIGIN) self.scale(radius, about_point=ORIGIN) self.shift(arc_center) def get_arc_center(self) -> Vect3: """ Looks at the normals to the first two anchors, and finds their intersection points """ # First two anchors and handles a1, h, a2 = self.get_points()[:3] # Tangent vectors t1 = h - a1 t2 = h - a2 # Normals n1 = rotate_vector(t1, TAU / 4) n2 = rotate_vector(t2, TAU / 4) return find_intersection(a1, n1, a2, n2) def get_start_angle(self) -> float: angle = angle_of_vector(self.get_start() - self.get_arc_center()) return angle % TAU def get_stop_angle(self) -> float: angle = angle_of_vector(self.get_end() - self.get_arc_center()) return angle % TAU def move_arc_center_to(self, point: Vect3) -> Self: self.shift(point - self.get_arc_center()) return self class ArcBetweenPoints(Arc): def __init__( self, start: Vect3, end: Vect3, angle: float = TAU / 4, **kwargs ): super().__init__(angle=angle, **kwargs) if angle == 0: self.set_points_as_corners([LEFT, RIGHT]) self.put_start_and_end_on(start, end) class CurvedArrow(ArcBetweenPoints): def __init__( self, start_point: Vect3, end_point: Vect3, **kwargs ): super().__init__(start_point, end_point, **kwargs) self.add_tip() class CurvedDoubleArrow(CurvedArrow): def __init__( self, start_point: Vect3, end_point: Vect3, **kwargs ): super().__init__(start_point, end_point, **kwargs) self.add_tip(at_start=True) class Circle(Arc): def __init__( self, start_angle: float = 0, stroke_color: ManimColor = RED, **kwargs ): super().__init__( start_angle, TAU, stroke_color=stroke_color, **kwargs ) def surround( self, mobject: Mobject, dim_to_match: int = 0, stretch: bool = False, buff: float = MED_SMALL_BUFF ) -> Self: self.replace(mobject, dim_to_match, stretch) self.stretch((self.get_width() + 2 * buff) / self.get_width(), 0) self.stretch((self.get_height() + 2 * buff) / self.get_height(), 1) return self def point_at_angle(self, angle: float) -> Vect3: start_angle = self.get_start_angle() return self.point_from_proportion( ((angle - start_angle) % TAU) / TAU ) def get_radius(self) -> float: return get_norm(self.get_start() - self.get_center()) class Dot(Circle): def __init__( self, point: Vect3 = ORIGIN, radius: float = DEFAULT_DOT_RADIUS, stroke_color: ManimColor = BLACK, stroke_width: float = 0.0, fill_opacity: float = 1.0, fill_color: ManimColor = WHITE, **kwargs ): super().__init__( arc_center=point, radius=radius, stroke_color=stroke_color, stroke_width=stroke_width, fill_opacity=fill_opacity, fill_color=fill_color, **kwargs ) class SmallDot(Dot): def __init__( self, point: Vect3 = ORIGIN, radius: float = DEFAULT_SMALL_DOT_RADIUS, **kwargs ): super().__init__(point, radius=radius, **kwargs) class Ellipse(Circle): def __init__( self, width: float = 2.0, height: float = 1.0, **kwargs ): super().__init__(**kwargs) self.set_width(width, stretch=True) self.set_height(height, stretch=True) class AnnularSector(VMobject): def __init__( self, angle: float = TAU / 4, start_angle: float = 0.0, inner_radius: float = 1.0, outer_radius: float = 2.0, arc_center: Vect3 = ORIGIN, fill_color: ManimColor = GREY_A, fill_opacity: float = 1.0, stroke_width: float = 0.0, **kwargs, ): super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) # Initialize points inner_arc, outer_arc = [ Arc( start_angle=start_angle, angle=angle, radius=radius, arc_center=arc_center, ) for radius in (inner_radius, outer_radius) ] self.set_points(inner_arc.get_points()[::-1]) # Reverse self.add_line_to(outer_arc.get_points()[0]) self.add_subpath(outer_arc.get_points()) self.add_line_to(inner_arc.get_points()[-1]) class Sector(AnnularSector): def __init__( self, angle: float = TAU / 4, radius: float = 1.0, **kwargs ): super().__init__( angle, inner_radius=0, outer_radius=radius, **kwargs ) class Annulus(VMobject): def __init__( self, inner_radius: float = 1.0, outer_radius: float = 2.0, fill_opacity: float = 1.0, stroke_width: float = 0.0, fill_color: ManimColor = GREY_A, center: Vect3 = ORIGIN, **kwargs, ): super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) self.radius = outer_radius outer_path = outer_radius * quadratic_bezier_points_for_arc(TAU) inner_path = inner_radius * quadratic_bezier_points_for_arc(-TAU) self.add_subpath(outer_path) self.add_subpath(inner_path) self.shift(center) class Line(TipableVMobject): def __init__( self, start: Vect3 | Mobject = LEFT, end: Vect3 | Mobject = RIGHT, buff: float = 0.0, path_arc: float = 0.0, **kwargs ): super().__init__(**kwargs) self.path_arc = path_arc self.buff = buff self.set_start_and_end_attrs(start, end) self.set_points_by_ends(self.start, self.end, buff, path_arc) def set_points_by_ends( self, start: Vect3, end: Vect3, buff: float = 0, path_arc: float = 0 ) -> Self: self.clear_points() self.start_new_path(start) self.add_arc_to(end, path_arc) # Apply buffer if buff > 0: length = self.get_arc_length() alpha = min(buff / length, 0.5) self.pointwise_become_partial(self, alpha, 1 - alpha) return self def set_path_arc(self, new_value: float) -> Self: self.path_arc = new_value self.init_points() return self def set_start_and_end_attrs(self, start: Vect3 | Mobject, end: Vect3 | Mobject): # 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 | Vect3, direction: Vect3 | None = None ) -> Vect3: """ Take an argument passed into Line (or subclass) and turn it into a 3d point. """ if isinstance(mob_or_point, Mobject): mob = mob_or_point if direction is None: return mob.get_center() else: return mob.get_continuous_bounding_box_point(direction) else: point = mob_or_point result = np.zeros(self.dim) result[:len(point)] = point return result def put_start_and_end_on(self, start: Vect3, end: Vect3) -> Self: curr_start, curr_end = self.get_start_and_end() if np.isclose(curr_start, curr_end).all(): # Handle null lines more gracefully self.set_points_by_ends(start, end, buff=0, path_arc=self.path_arc) return self return super().put_start_and_end_on(start, end) def get_vector(self) -> Vect3: return self.get_end() - self.get_start() def get_unit_vector(self) -> Vect3: return normalize(self.get_vector()) def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_projection(self, point: Vect3) -> Vect3: """ Return projection of a point onto the line """ unit_vect = self.get_unit_vector() start = self.get_start() return start + np.dot(point - start, unit_vect) * unit_vect def get_slope(self) -> float: return np.tan(self.get_angle()) def set_angle(self, angle: float, about_point: Optional[Vect3] = 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, **kwargs): self.scale(length / self.get_length(), **kwargs) return self def get_arc_length(self) -> float: arc_len = get_norm(self.get_vector()) if self.path_arc > 0: arc_len *= self.path_arc / (2 * math.sin(self.path_arc / 2)) return arc_len class DashedLine(Line): def __init__( self, start: Vect3 = LEFT, end: Vect3 = RIGHT, dash_length: float = DEFAULT_DASH_LENGTH, positive_space_ratio: float = 0.5, **kwargs ): super().__init__(start, end, **kwargs) num_dashes = self.calculate_num_dashes(dash_length, positive_space_ratio) dashes = DashedVMobject( self, num_dashes=num_dashes, positive_space_ratio=positive_space_ratio ) self.clear_points() self.add(*dashes) def calculate_num_dashes(self, dash_length: float, positive_space_ratio: float) -> int: try: full_length = dash_length / positive_space_ratio return int(np.ceil(self.get_length() / full_length)) except ZeroDivisionError: return 1 def get_start(self) -> Vect3: if len(self.submobjects) > 0: return self.submobjects[0].get_start() else: return Line.get_start(self) def get_end(self) -> Vect3: if len(self.submobjects) > 0: return self.submobjects[-1].get_end() else: return Line.get_end(self) def get_first_handle(self) -> Vect3: return self.submobjects[0].get_points()[1] def get_last_handle(self) -> Vect3: return self.submobjects[-1].get_points()[-2] class TangentLine(Line): def __init__( self, vmob: VMobject, alpha: float, length: float = 2, d_alpha: float = 1e-6, **kwargs ): a1 = clip(alpha - d_alpha, 0, 1) a2 = clip(alpha + d_alpha, 0, 1) super().__init__(vmob.pfp(a1), vmob.pfp(a2), **kwargs) self.scale(length / self.get_length()) class Elbow(VMobject): def __init__( self, width: float = 0.2, angle: float = 0, **kwargs ): super().__init__(**kwargs) self.set_points_as_corners([UP, UR, RIGHT]) self.set_width(width, about_point=ORIGIN) self.rotate(angle, about_point=ORIGIN) class Arrow(Line): def __init__( self, start: Vect3 | Mobject, end: Vect3 | Mobject, stroke_color: ManimColor = GREY_A, stroke_width: float = 5, buff: float = 0.25, tip_width_ratio: float = 5, tip_len_to_width: float = 0.0075, max_tip_length_to_length_ratio: float = 0.3, max_width_to_length_ratio: float = 8.0, **kwargs, ): self.tip_width_ratio = tip_width_ratio self.tip_len_to_width = tip_len_to_width self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_width_to_length_ratio = max_width_to_length_ratio self.n_tip_points = 3 self.original_stroke_width = stroke_width super().__init__( start, end, stroke_color=stroke_color, stroke_width=stroke_width, buff=buff, **kwargs ) def set_points_by_ends( self, start: Vect3, end: Vect3, buff: float = 0, path_arc: float = 0 ) -> Self: super().set_points_by_ends(start, end, buff, path_arc) self.insert_tip_anchor() self.create_tip_with_stroke_width() return self def insert_tip_anchor(self) -> Self: prev_end = self.get_end() arc_len = self.get_arc_length() tip_len = self.get_stroke_width() * self.tip_width_ratio * self.tip_len_to_width if tip_len >= self.max_tip_length_to_length_ratio * arc_len or arc_len == 0: alpha = self.max_tip_length_to_length_ratio else: alpha = tip_len / arc_len if self.path_arc > 0 and self.buff > 0: self.insert_n_curves(10) # Is this needed? self.pointwise_become_partial(self, 0.0, 1.0 - alpha) self.add_line_to(self.get_end()) self.add_line_to(prev_end) self.n_tip_points = 3 return self @Mobject.affects_data def create_tip_with_stroke_width(self) -> Self: if self.get_num_points() < 3: return self stroke_width = min( self.original_stroke_width, self.max_width_to_length_ratio * self.get_length(), ) tip_width = self.tip_width_ratio * stroke_width ntp = self.n_tip_points self.data['stroke_width'][:-ntp] = self.data['stroke_width'][0] self.data['stroke_width'][-ntp:, 0] = tip_width * np.linspace(1, 0, ntp) return self def reset_tip(self) -> Self: self.set_points_by_ends( self.get_start(), self.get_end(), path_arc=self.path_arc ) return self def set_stroke( self, color: ManimColor | Iterable[ManimColor] | None = None, width: float | Iterable[float] | None = None, *args, **kwargs ) -> Self: super().set_stroke(color=color, width=width, *args, **kwargs) self.original_stroke_width = self.get_stroke_width() if self.has_points(): self.reset_tip() return self def _handle_scale_side_effects(self, scale_factor: float) -> Self: if scale_factor != 1.0: self.reset_tip() return self class FillArrow(Line): def __init__( self, start: Vect3 | Mobject = LEFT, end: Vect3 | Mobject = LEFT, fill_color: ManimColor = GREY_A, fill_opacity: float = 1.0, stroke_width: float = 0.0, buff: float = MED_SMALL_BUFF, thickness: float = 0.05, tip_width_ratio: float = 5, tip_angle: float = PI / 3, max_tip_length_to_length_ratio: float = 0.5, max_width_to_length_ratio: float = 0.1, **kwargs, ): self.thickness = thickness self.tip_width_ratio = tip_width_ratio self.tip_angle = tip_angle self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_width_to_length_ratio = max_width_to_length_ratio super().__init__( start, end, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, buff=buff, **kwargs ) def set_points_by_ends( self, start: Vect3, end: Vect3, buff: float = 0, path_arc: float = 0 ) -> Self: # Find the right tip length and thickness vect = end - start length = max(get_norm(vect), 1e-8) thickness = self.thickness w_ratio = fdiv(self.max_width_to_length_ratio, fdiv(thickness, length)) if w_ratio < 1: thickness *= w_ratio tip_width = self.tip_width_ratio * thickness tip_length = tip_width / (2 * np.tan(self.tip_angle / 2)) t_ratio = fdiv(self.max_tip_length_to_length_ratio, fdiv(tip_length, length)) if t_ratio < 1: tip_length *= t_ratio tip_width *= t_ratio # Find points for the stem if path_arc == 0: points1 = (length - tip_length) * np.array([RIGHT, 0.5 * RIGHT, ORIGIN]) points1 += thickness * UP / 2 points2 = points1[::-1] + thickness * DOWN else: # Solve for radius so that the tip-to-tail length matches |end - start| a = 2 * (1 - np.cos(path_arc)) b = -2 * tip_length * np.sin(path_arc) c = tip_length**2 - length**2 R = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a) # Find arc points points1 = quadratic_bezier_points_for_arc(path_arc) points2 = np.array(points1[::-1]) points1 *= (R + thickness / 2) points2 *= (R - thickness / 2) if path_arc < 0: tip_length *= -1 rot_T = rotation_matrix_transpose(PI / 2 - path_arc, OUT) for points in points1, points2: points[:] = np.dot(points, rot_T) points += R * DOWN self.set_points(points1) # Tip self.add_line_to(tip_width * UP / 2) self.add_line_to(tip_length * LEFT) self.tip_index = len(self.get_points()) - 1 self.add_line_to(tip_width * DOWN / 2) self.add_line_to(points2[0]) # Close it out self.add_subpath(points2) self.add_line_to(points1[0]) if length > 0 and self.get_length() > 0: # Final correction super().scale(length / self.get_length()) self.rotate(angle_of_vector(vect) - self.get_angle()) self.rotate( PI / 2 - np.arccos(normalize(vect)[2]), axis=rotate_vector(self.get_unit_vector(), -PI / 2), ) self.shift(start - self.get_start()) return self def reset_points_around_ends(self) -> Self: self.set_points_by_ends( self.get_start().copy(), self.get_end().copy(), path_arc=self.path_arc ) return self def get_start(self) -> Vect3: points = self.get_points() return 0.5 * (points[0] + points[-3]) def get_end(self) -> Vect3: return self.get_points()[self.tip_index] def put_start_and_end_on(self, start: Vect3, end: Vect3) -> Self: self.set_points_by_ends(start, end, buff=0, path_arc=self.path_arc) return self def scale(self, *args, **kwargs) -> Self: super().scale(*args, **kwargs) self.reset_points_around_ends() return self def set_thickness(self, thickness: float) -> Self: self.thickness = thickness self.reset_points_around_ends() return self def set_path_arc(self, path_arc: float) -> Self: self.path_arc = path_arc self.reset_points_around_ends() return self class Vector(Arrow): def __init__( self, direction: Vect3 = RIGHT, buff: float = 0.0, **kwargs ): if len(direction) == 2: direction = np.hstack([direction, 0]) super().__init__(ORIGIN, direction, buff=buff, **kwargs) class CubicBezier(VMobject): def __init__( self, a0: Vect3, h0: Vect3, h1: Vect3, a1: Vect3, **kwargs ): super().__init__(**kwargs) self.add_cubic_bezier_curve(a0, h0, h1, a1) class Polygon(VMobject): def __init__( self, *vertices: Vect3, **kwargs ): super().__init__(**kwargs) self.set_points_as_corners([*vertices, vertices[0]]) def get_vertices(self) -> Vect3Array: return self.get_start_anchors() def round_corners(self, radius: Optional[float] = None) -> Self: if radius is None: verts = self.get_vertices() min_edge_length = min( get_norm(v1 - v2) for v1, v2 in zip(verts, verts[1:]) if not np.isclose(v1, v2).all() ) radius = 0.25 * min_edge_length vertices = self.get_vertices() arcs = [] for v1, v2, v3 in adjacent_n_tuples(vertices, 3): vect1 = normalize(v2 - v1) vect2 = normalize(v3 - v2) angle = angle_between_vectors(vect1, vect2) # Distance between vertex and start of the arc cut_off_length = radius * np.tan(angle / 2) # Negative radius gives concave curves sign = float(np.sign(radius * cross2d(vect1, vect2))) arc = ArcBetweenPoints( v2 - vect1 * cut_off_length, v2 + vect2 * cut_off_length, angle=sign * angle, n_components=2, ) arcs.append(arc) self.clear_points() # To ensure that we loop through starting with last arcs = [arcs[-1], *arcs[:-1]] for arc1, arc2 in adjacent_pairs(arcs): self.add_subpath(arc1.get_points()) self.add_line_to(arc2.get_start()) return self class Polyline(VMobject): def __init__( self, *vertices: Vect3, **kwargs ): super().__init__(**kwargs) self.set_points_as_corners(vertices) class RegularPolygon(Polygon): def __init__( self, n: int = 6, radius: float = 1.0, start_angle: float | None = None, **kwargs ): # Defaults to 0 for odd, 90 for even if start_angle is None: start_angle = (n % 2) * 90 * DEGREES start_vect = rotate_vector(radius * RIGHT, start_angle) vertices = compass_directions(n, start_vect) super().__init__(*vertices, **kwargs) class Triangle(RegularPolygon): def __init__(self, **kwargs): super().__init__(n=3, **kwargs) class ArrowTip(Triangle): def __init__( self, angle: float = 0, width: float = DEFAULT_ARROW_TIP_WIDTH, length: float = DEFAULT_ARROW_TIP_LENGTH, fill_opacity: float = 1.0, fill_color: ManimColor = WHITE, stroke_width: float = 0.0, tip_style: int = 0, # triangle=0, inner_smooth=1, dot=2 **kwargs ): super().__init__( start_angle=0, fill_opacity=fill_opacity, fill_color=fill_color, stroke_width=stroke_width, **kwargs ) self.set_height(width) self.set_width(length, stretch=True) if tip_style == 1: self.set_height(length * 0.9, stretch=True) self.data["point"][4] += np.array([0.6 * length, 0, 0]) elif tip_style == 2: h = length / 2 self.set_points(Dot().set_width(h).get_points()) self.rotate(angle) def get_base(self) -> Vect3: return self.point_from_proportion(0.5) def get_tip_point(self) -> Vect3: return self.get_points()[0] def get_vector(self) -> Vect3: return self.get_tip_point() - self.get_base() def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_length(self) -> float: return get_norm(self.get_vector()) class Rectangle(Polygon): def __init__( self, width: float = 4.0, height: float = 2.0, **kwargs ): super().__init__(UR, UL, DL, DR, **kwargs) self.set_width(width, stretch=True) self.set_height(height, stretch=True) def surround(self, mobject, buff=SMALL_BUFF) -> Self: target_shape = np.array(mobject.get_shape()) + 2 * buff self.set_shape(*target_shape) self.move_to(mobject) return self class Square(Rectangle): def __init__(self, side_length: float = 2.0, **kwargs): super().__init__(side_length, side_length, **kwargs) class RoundedRectangle(Rectangle): def __init__( self, width: float = 4.0, height: float = 2.0, corner_radius: float = 0.5, **kwargs ): super().__init__(width, height, **kwargs) self.round_corners(corner_radius)
manim_3b1b/manimlib/mobject/boolean_ops.py
from __future__ import annotations import numpy as np import pathops from manimlib.mobject.types.vectorized_mobject import VMobject # Boolean operations between 2D mobjects # Borrowed from from https://github.com/ManimCommunity/manim/ def _convert_vmobject_to_skia_path(vmobject: VMobject) -> pathops.Path: path = pathops.Path() subpaths = vmobject.get_subpaths_from_points(vmobject.get_all_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_equal(subpath[0], subpath[-1]): path.close() return path def _convert_skia_path_to_vmobject( path: pathops.Path, vmobject: VMobject ) -> VMobject: PathVerb = pathops.PathVerb current_path_start = np.array([0.0, 0.0, 0.0]) for path_verb, points in path: if path_verb == PathVerb.CLOSE: vmobject.add_line_to(current_path_start) else: points = np.hstack((np.array(points), np.zeros((len(points), 1)))) if path_verb == PathVerb.MOVE: for point in points: current_path_start = point vmobject.start_new_path(point) elif path_verb == PathVerb.CUBIC: vmobject.add_cubic_bezier_curve_to(*points) elif path_verb == PathVerb.LINE: vmobject.add_line_to(points[0]) elif path_verb == PathVerb.QUAD: vmobject.add_quadratic_bezier_curve_to(*points) else: raise Exception(f"Unsupported: {path_verb}") return vmobject.reverse_points() class Union(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Union.") super().__init__(**kwargs) outpen = pathops.Path() paths = [ _convert_vmobject_to_skia_path(vmobject) for vmobject in vmobjects ] pathops.union(paths, outpen.getPen()) _convert_skia_path_to_vmobject(outpen, self) class Difference(VMobject): def __init__(self, subject: VMobject, clip: VMobject, **kwargs): super().__init__(**kwargs) outpen = pathops.Path() pathops.difference( [_convert_vmobject_to_skia_path(subject)], [_convert_vmobject_to_skia_path(clip)], outpen.getPen(), ) _convert_skia_path_to_vmobject(outpen, self) class Intersection(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Intersection.") super().__init__(**kwargs) outpen = pathops.Path() pathops.intersection( [_convert_vmobject_to_skia_path(vmobjects[0])], [_convert_vmobject_to_skia_path(vmobjects[1])], outpen.getPen(), ) new_outpen = outpen for _i in range(2, len(vmobjects)): new_outpen = pathops.Path() pathops.intersection( [outpen], [_convert_vmobject_to_skia_path(vmobjects[_i])], new_outpen.getPen(), ) outpen = new_outpen _convert_skia_path_to_vmobject(outpen, self) class Exclusion(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Exclusion.") super().__init__(**kwargs) outpen = pathops.Path() pathops.xor( [_convert_vmobject_to_skia_path(vmobjects[0])], [_convert_vmobject_to_skia_path(vmobjects[1])], outpen.getPen(), ) new_outpen = outpen for _i in range(2, len(vmobjects)): new_outpen = pathops.Path() pathops.xor( [outpen], [_convert_vmobject_to_skia_path(vmobjects[_i])], new_outpen.getPen(), ) outpen = new_outpen _convert_skia_path_to_vmobject(outpen, self)
manim_3b1b/manimlib/mobject/shape_matchers.py
from __future__ import annotations from colour import Color from manimlib.constants import BLACK, RED, YELLOW, WHITE from manimlib.constants import DL, DOWN, DR, LEFT, RIGHT, UL, UR from manimlib.constants import SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.customization import get_customization from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Self class SurroundingRectangle(Rectangle): def __init__( self, mobject: Mobject, buff: float = SMALL_BUFF, color: ManimColor = YELLOW, **kwargs ): super().__init__(color=color, **kwargs) self.buff = buff self.surround(mobject) def surround(self, mobject, buff=None) -> Self: self.mobject = mobject self.buff = buff if buff is not None else self.buff super().surround(mobject, self.buff) return self def set_buff(self, buff) -> Self: self.buff = buff self.surround(self.mobject) return self class BackgroundRectangle(SurroundingRectangle): def __init__( self, mobject: Mobject, color: ManimColor = None, stroke_width: float = 0, stroke_opacity: float = 0, fill_opacity: float = 0.75, buff: float = 0, **kwargs ): if color is None: color = get_customization()['style']['background_color'] super().__init__( mobject, color=color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, fill_opacity=fill_opacity, buff=buff, **kwargs ) self.original_fill_opacity = fill_opacity def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self: self.set_fill(opacity=b * self.original_fill_opacity) return self def set_style( self, stroke_color: ManimColor | None = None, stroke_width: float | None = None, fill_color: ManimColor | None = None, fill_opacity: float | None = None, family: bool = True ) -> Self: # Unchangeable style, except for fill_opacity VMobject.set_style( self, stroke_color=BLACK, stroke_width=0, fill_color=BLACK, fill_opacity=fill_opacity ) return self def get_fill_color(self) -> Color: return Color(self.color) class Cross(VGroup): def __init__( self, mobject: Mobject, stroke_color: ManimColor = RED, stroke_width: float | Sequence[float] = [0, 6, 0], **kwargs ): super().__init__( Line(UL, DR), Line(UR, DL), ) self.insert_n_curves(20) self.replace(mobject, stretch=True) self.set_stroke(stroke_color, width=stroke_width) class Underline(Line): def __init__( self, mobject: Mobject, buff: float = SMALL_BUFF, stroke_color=WHITE, stroke_width: float | Sequence[float] = [0, 3, 3, 0], stretch_factor=1.2, **kwargs ): super().__init__( LEFT, RIGHT, stroke_color=stroke_color, stroke_width=stroke_width, **kwargs ) self.insert_n_curves(30) self.set_stroke(stroke_color, stroke_width) self.set_width(mobject.get_width() * stretch_factor) self.next_to(mobject, DOWN, buff=buff)
manim_3b1b/manimlib/mobject/vector_field.py
from __future__ import annotations import itertools as it import numpy as np from manimlib.constants import FRAME_HEIGHT, FRAME_WIDTH from manimlib.constants import WHITE from manimlib.animation.indication import VShowPassingFlash from manimlib.mobject.geometry import Arrow from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.color import get_colormap_list from manimlib.utils.color import rgb_to_color from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.rate_functions import linear from manimlib.utils.simple_functions import sigmoid from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, TypeVar, Tuple from manimlib.typing import ManimColor, Vect3, VectN, Vect3Array from manimlib.mobject.coordinate_systems import CoordinateSystem from manimlib.mobject.mobject import Mobject T = TypeVar("T") def get_vectorized_rgb_gradient_function( min_value: T, max_value: T, color_map: str ) -> Callable[[VectN], Vect3Array]: rgbs = np.array(get_colormap_list(color_map)) def func(values): alphas = inverse_interpolate( min_value, max_value, 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)) result = interpolate(rgbs[indices], rgbs[next_indices], inter_alphas) return result return func def get_rgb_gradient_function( min_value: T, max_value: T, color_map: str ) -> Callable[[float], Vect3]: vectorized_func = get_vectorized_rgb_gradient_function(min_value, max_value, color_map) return lambda value: vectorized_func(np.array([value]))[0] def move_along_vector_field( mobject: Mobject, func: Callable[[Vect3], Vect3] ) -> Mobject: mobject.add_updater( lambda m, dt: m.shift( func(m.get_center()) * dt ) ) return mobject def move_submobjects_along_vector_field( mobject: Mobject, func: Callable[[Vect3], Vect3] ) -> Mobject: def apply_nudge(mob, dt): for submob in mob: x, y = submob.get_center()[:2] if abs(x) < FRAME_WIDTH and abs(y) < FRAME_HEIGHT: submob.shift(func(submob.get_center()) * dt) mobject.add_updater(apply_nudge) return mobject def move_points_along_vector_field( mobject: Mobject, func: Callable[[float, float], Iterable[float]], coordinate_system: CoordinateSystem ) -> Mobject: cs = coordinate_system origin = cs.get_origin() def apply_nudge(self, dt): mobject.apply_function( lambda p: p + (cs.c2p(*func(*cs.p2c(p))) - origin) * dt ) mobject.add_updater(apply_nudge) return mobject def get_sample_points_from_coordinate_system( coordinate_system: CoordinateSystem, step_multiple: float ) -> it.product[tuple[Vect3, ...]]: ranges = [] for range_args in coordinate_system.get_all_ranges(): _min, _max, step = range_args step *= step_multiple ranges.append(np.arange(_min, _max + step, step)) return it.product(*ranges) # Mobjects class VectorField(VGroup): def __init__( self, func: Callable[[float, float], Sequence[float]], coordinate_system: CoordinateSystem, step_multiple: float = 0.5, magnitude_range: Tuple[float, float] = (0, 2), color_map: str = "3b1b_colormap", # 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 = dict(), **kwargs ): super().__init__(**kwargs) self.func = func self.coordinate_system = coordinate_system self.step_multiple = step_multiple self.magnitude_range = magnitude_range self.color_map = color_map self.length_func = length_func self.opacity = opacity self.vector_config = dict(vector_config) self.value_to_rgb = get_rgb_gradient_function( *self.magnitude_range, self.color_map, ) samples = get_sample_points_from_coordinate_system( coordinate_system, self.step_multiple ) self.add(*( self.get_vector(coords) for coords in samples )) def get_vector(self, coords: Iterable[float], **kwargs) -> Arrow: vector_config = merge_dicts_recursively( self.vector_config, kwargs ) output = np.array(self.func(*coords)) norm = get_norm(output) if norm > 0: output *= self.length_func(norm) / norm origin = self.coordinate_system.get_origin() _input = self.coordinate_system.c2p(*coords) _output = self.coordinate_system.c2p(*output) vect = Arrow( origin, _output, buff=0, **vector_config ) vect.shift(_input - origin) vect.set_color( rgb_to_color(self.value_to_rgb(norm)), opacity=self.opacity, ) return vect class StreamLines(VGroup): def __init__( self, func: Callable[[float, float], Sequence[float]], coordinate_system: CoordinateSystem, step_multiple: float = 0.5, n_repeats: int = 1, noise_factor: float | None = None, # Config for drawing lines dt: float = 0.05, arc_len: float = 3, max_time_steps: int = 200, n_samples_per_line: int = 10, cutoff_norm: float = 15, # Style info stroke_width: float = 1.0, stroke_color: ManimColor = WHITE, stroke_opacity: float = 1, color_by_magnitude: bool = True, magnitude_range: Tuple[float, float] = (0, 2.0), taper_stroke_width: bool = False, color_map: str = "3b1b_colormap", **kwargs ): super().__init__(**kwargs) self.func = func self.coordinate_system = coordinate_system self.step_multiple = step_multiple self.n_repeats = n_repeats self.noise_factor = noise_factor self.dt = dt self.arc_len = arc_len self.max_time_steps = max_time_steps self.n_samples_per_line = n_samples_per_line self.cutoff_norm = cutoff_norm self.stroke_width = stroke_width self.stroke_color = stroke_color self.stroke_opacity = stroke_opacity self.color_by_magnitude = color_by_magnitude self.magnitude_range = magnitude_range self.taper_stroke_width = taper_stroke_width self.color_map = color_map self.draw_lines() self.init_style() def point_func(self, point: Vect3) -> Vect3: in_coords = self.coordinate_system.p2c(point) out_coords = self.func(*in_coords) return self.coordinate_system.c2p(*out_coords) def draw_lines(self) -> None: lines = [] origin = self.coordinate_system.get_origin() for point in self.get_start_points(): points = [point] total_arc_len = 0 time = 0 for x in range(self.max_time_steps): time += self.dt last_point = points[-1] new_point = last_point + self.dt * (self.point_func(last_point) - origin) points.append(new_point) total_arc_len += get_norm(new_point - last_point) if get_norm(last_point) > self.cutoff_norm: break if total_arc_len > self.arc_len: break line = VMobject() line.virtual_time = time step = max(1, int(len(points) / self.n_samples_per_line)) line.set_points_as_corners(points[::step]) line.make_smooth(approx=True) lines.append(line) self.set_submobjects(lines) def get_start_points(self) -> Vect3Array: cs = self.coordinate_system sample_coords = get_sample_points_from_coordinate_system( cs, self.step_multiple, ) noise_factor = self.noise_factor if noise_factor is None: noise_factor = cs.x_range[2] * self.step_multiple * 0.5 return np.array([ cs.c2p(*coords) + noise_factor * np.random.random(3) for n in range(self.n_repeats) for coords in sample_coords ]) def init_style(self) -> None: if self.color_by_magnitude: values_to_rgbs = get_vectorized_rgb_gradient_function( *self.magnitude_range, self.color_map, ) cs = self.coordinate_system for line in self.submobjects: norms = [ get_norm(self.func(*cs.p2c(point))) for point in line.get_points() ] rgbs = values_to_rgbs(norms) rgbas = np.zeros((len(rgbs), 4)) rgbas[:, :3] = rgbs rgbas[:, 3] = self.stroke_opacity line.set_rgba_array(rgbas, "stroke_rgba") else: self.set_stroke(self.stroke_color, opacity=self.stroke_opacity) if self.taper_stroke_width: width = [0, self.stroke_width, 0] else: width = self.stroke_width self.set_stroke(width=width) class AnimatedStreamLines(VGroup): def __init__( self, stream_lines: StreamLines, lag_range: float = 4, line_anim_config: dict = dict( rate_func=linear, time_width=1.0, ), **kwargs ): super().__init__(**kwargs) self.stream_lines = stream_lines for line in stream_lines: line.anim = VShowPassingFlash( line, run_time=line.virtual_time, **line_anim_config, ) line.anim.begin() line.time = -lag_range * np.random.random() self.add(line.anim.mobject) self.add_updater(lambda m, dt: m.update(dt)) def update(self, dt: float) -> None: stream_lines = self.stream_lines for line in stream_lines: line.time += dt adjusted_time = max(line.time, 0) % line.anim.run_time line.anim.update(adjusted_time / line.anim.run_time)
manim_3b1b/manimlib/mobject/svg/svg_mobject.py
from __future__ import annotations import os from xml.etree import ElementTree as ET import numpy as np import svgelements as se import io from manimlib.constants import RIGHT from manimlib.logger import log from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Polyline from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RoundedRectangle from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.directories import get_mobject_data_dir from manimlib.utils.images import get_full_vector_image_path from manimlib.utils.iterables import hash_obj from manimlib.utils.simple_functions import hash_string from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Tuple from manimlib.typing import ManimColor, Vect3Array SVG_HASH_TO_MOB_MAP: dict[int, list[VMobject]] = {} PATH_TO_POINTS: dict[str, Vect3Array] = {} def _convert_point_to_3d(x: float, y: float) -> np.ndarray: return np.array([x, y, 0.0]) class SVGMobject(VMobject): file_name: str = "" height: float | None = 2.0 width: float | None = None def __init__( self, file_name: str = "", should_center: bool = True, height: float | None = None, width: float | None = None, # Style that overrides the original svg color: ManimColor = None, fill_color: ManimColor = None, fill_opacity: float | None = None, stroke_width: float | None = 0.0, stroke_color: ManimColor = None, stroke_opacity: float | None = None, # Style that fills only when not specified # If None, regarded as default values from svg standard svg_default: dict = dict( color=None, opacity=None, fill_color=None, fill_opacity=None, stroke_width=None, stroke_color=None, stroke_opacity=None, ), path_string_config: dict = dict(), **kwargs ): self.file_name = file_name or self.file_name self.svg_default = dict(svg_default) self.path_string_config = dict(path_string_config) super().__init__(**kwargs ) self.init_svg_mobject() self.ensure_positive_orientation() # Rather than passing style into super().__init__ # do it after svg has been taken in self.set_style( fill_color=color or fill_color, fill_opacity=fill_opacity, stroke_color=color or stroke_color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, ) # Initialize position height = height or self.height width = width or self.width if should_center: self.center() if height is not None: self.set_height(height) if width is not None: self.set_width(width) def init_svg_mobject(self) -> None: hash_val = hash_obj(self.hash_seed) if hash_val in SVG_HASH_TO_MOB_MAP: submobs = [sm.copy() for sm in SVG_HASH_TO_MOB_MAP[hash_val]] else: submobs = self.mobjects_from_file(self.get_file_path()) SVG_HASH_TO_MOB_MAP[hash_val] = [sm.copy() for sm in submobs] self.add(*submobs) self.flip(RIGHT) # Flip y @property def hash_seed(self) -> tuple: # Returns data which can uniquely represent the result of `init_points`. # The hashed value of it is stored as a key in `SVG_HASH_TO_MOB_MAP`. return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.file_name ) def mobjects_from_file(self, file_path: str) -> list[VMobject]: element_tree = ET.parse(file_path) new_tree = self.modify_xml_tree(element_tree) # New svg based on tree contents data_stream = io.BytesIO() new_tree.write(data_stream) data_stream.seek(0) svg = se.SVG.parse(data_stream) data_stream.close() return self.mobjects_from_svg(svg) def get_file_path(self) -> str: if self.file_name is None: raise Exception("Must specify file for SVGMobject") return get_full_vector_image_path(self.file_name) def modify_xml_tree(self, element_tree: ET.ElementTree) -> ET.ElementTree: config_style_attrs = self.generate_config_style_dict() style_keys = ( "fill", "fill-opacity", "stroke", "stroke-opacity", "stroke-width", "style" ) root = element_tree.getroot() style_attrs = { k: v for k, v in root.attrib.items() if k in style_keys } # Ignore other attributes in case that svgelements cannot parse them SVG_XMLNS = "{http://www.w3.org/2000/svg}" new_root = ET.Element("svg") config_style_node = ET.SubElement(new_root, f"{SVG_XMLNS}g", config_style_attrs) root_style_node = ET.SubElement(config_style_node, f"{SVG_XMLNS}g", style_attrs) root_style_node.extend(root) return ET.ElementTree(new_root) def generate_config_style_dict(self) -> dict[str, str]: keys_converting_dict = { "fill": ("color", "fill_color"), "fill-opacity": ("opacity", "fill_opacity"), "stroke": ("color", "stroke_color"), "stroke-opacity": ("opacity", "stroke_opacity"), "stroke-width": ("stroke_width",) } svg_default_dict = self.svg_default result = {} for svg_key, style_keys in keys_converting_dict.items(): for style_key in style_keys: if svg_default_dict[style_key] is None: continue result[svg_key] = str(svg_default_dict[style_key]) return result def mobjects_from_svg(self, svg: se.SVG) -> list[VMobject]: result = [] for shape in svg.elements(): if isinstance(shape, (se.Group, se.Use)): continue elif isinstance(shape, se.Path): mob = self.path_to_mobject(shape) elif isinstance(shape, se.SimpleLine): mob = self.line_to_mobject(shape) elif isinstance(shape, se.Rect): mob = self.rect_to_mobject(shape) elif isinstance(shape, (se.Circle, se.Ellipse)): mob = self.ellipse_to_mobject(shape) elif isinstance(shape, se.Polygon): mob = self.polygon_to_mobject(shape) elif isinstance(shape, se.Polyline): mob = self.polyline_to_mobject(shape) # elif isinstance(shape, se.Text): # mob = self.text_to_mobject(shape) elif type(shape) == se.SVGElement: continue else: log.warning("Unsupported element type: %s", type(shape)) continue if not mob.has_points(): continue if isinstance(shape, se.GraphicObject): self.apply_style_to_mobject(mob, shape) if isinstance(shape, se.Transformable) and shape.apply: self.handle_transform(mob, shape.transform) result.append(mob) return result @staticmethod def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject: mat = np.array([ [matrix.a, matrix.c], [matrix.b, matrix.d] ]) vec = np.array([matrix.e, matrix.f, 0.0]) mob.apply_matrix(mat) mob.shift(vec) return mob @staticmethod def apply_style_to_mobject( mob: VMobject, shape: se.GraphicObject ) -> VMobject: mob.set_style( stroke_width=shape.stroke_width, stroke_color=shape.stroke.hexrgb, stroke_opacity=shape.stroke.opacity, fill_color=shape.fill.hexrgb, fill_opacity=shape.fill.opacity ) return mob def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath: return VMobjectFromSVGPath(path, **self.path_string_config) def line_to_mobject(self, line: se.SimpleLine) -> Line: return Line( start=_convert_point_to_3d(line.x1, line.y1), end=_convert_point_to_3d(line.x2, line.y2) ) def rect_to_mobject(self, rect: se.Rect) -> Rectangle: if rect.rx == 0 or rect.ry == 0: mob = Rectangle( width=rect.width, height=rect.height, ) else: mob = RoundedRectangle( width=rect.width, height=rect.height * rect.rx / rect.ry, corner_radius=rect.rx ) mob.stretch_to_fit_height(rect.height) mob.shift(_convert_point_to_3d( rect.x + rect.width / 2, rect.y + rect.height / 2 )) return mob def ellipse_to_mobject(self, ellipse: se.Circle | se.Ellipse) -> Circle: mob = Circle(radius=ellipse.rx) mob.stretch_to_fit_height(2 * ellipse.ry) mob.shift(_convert_point_to_3d( ellipse.cx, ellipse.cy )) return mob def polygon_to_mobject(self, polygon: se.Polygon) -> Polygon: points = [ _convert_point_to_3d(*point) for point in polygon ] return Polygon(*points) def polyline_to_mobject(self, polyline: se.Polyline) -> Polyline: points = [ _convert_point_to_3d(*point) for point in polyline ] return Polyline(*points) def text_to_mobject(self, text: se.Text): pass class VMobjectFromSVGPath(VMobject): def __init__( self, path_obj: se.Path, **kwargs ): # Get rid of arcs path_obj.approximate_arcs_with_quads() self.path_obj = path_obj super().__init__(**kwargs) def init_points(self) -> None: # After a given svg_path has been converted into points, the result # will be saved so that future calls for the same pathdon't need to # retrace the same computation. path_string = self.path_obj.d() if path_string not in PATH_TO_POINTS: self.handle_commands() if not self._use_winding_fill: self.subdivide_intersections() # Save for future use PATH_TO_POINTS[path_string] = self.get_points().copy() else: points = PATH_TO_POINTS[path_string] self.set_points(points) def handle_commands(self) -> None: segment_class_to_func_map = { se.Move: (self.start_new_path, ("end",)), se.Close: (self.close_path, ()), se.Line: (self.add_line_to, ("end",)), se.QuadraticBezier: (self.add_quadratic_bezier_curve_to, ("control", "end")), se.CubicBezier: (self.add_cubic_bezier_curve_to, ("control1", "control2", "end")) } for segment in self.path_obj: segment_class = segment.__class__ func, attr_names = segment_class_to_func_map[segment_class] points = [ _convert_point_to_3d(*segment.__getattribute__(attr_name)) for attr_name in attr_names ] func(*points) # Get rid of the side effect of trailing "Z M" commands. if self.has_new_path_started(): self.resize_points(self.get_num_points() - 2)
manim_3b1b/manimlib/mobject/svg/text_mobject.py
from __future__ import annotations from contextlib import contextmanager import os from pathlib import Path import re import manimpango import pygments import pygments.formatters import pygments.lexers from manimlib.constants import DEFAULT_PIXEL_WIDTH, FRAME_WIDTH from manimlib.constants import NORMAL from manimlib.logger import log from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.utils.customization import get_customization from manimlib.utils.color import color_to_hex from manimlib.utils.color import int_to_hex from manimlib.utils.directories import get_downloads_dir from manimlib.utils.directories import get_text_dir from manimlib.utils.simple_functions import hash_string from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.typing import ManimColor, Span, Selector TEXT_MOB_SCALE_FACTOR = 0.0076 DEFAULT_LINE_SPACING_SCALE = 0.6 # Ensure the canvas is large enough to hold all glyphs. DEFAULT_CANVAS_WIDTH = 16384 DEFAULT_CANVAS_HEIGHT = 16384 # Temporary handler class _Alignment: VAL_DICT = { "LEFT": 0, "CENTER": 1, "RIGHT": 2 } def __init__(self, s: str): self.value = _Alignment.VAL_DICT[s.upper()] class MarkupText(StringMobject): # See https://docs.gtk.org/Pango/pango_markup.html MARKUP_TAGS = { "b": {"font_weight": "bold"}, "big": {"font_size": "larger"}, "i": {"font_style": "italic"}, "s": {"strikethrough": "true"}, "sub": {"baseline_shift": "subscript", "font_scale": "subscript"}, "sup": {"baseline_shift": "superscript", "font_scale": "superscript"}, "small": {"font_size": "smaller"}, "tt": {"font_family": "monospace"}, "u": {"underline": "single"}, } MARKUP_ENTITY_DICT = { "<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;", "'": "&apos;" } def __init__( self, text: str, font_size: int = 48, height: float | None = None, justify: bool = False, indent: float = 0, alignment: str = "", line_width: float | None = None, font: str = "", slant: str = NORMAL, weight: str = NORMAL, gradient: Iterable[ManimColor] | None = None, line_spacing_height: float | None = None, text2color: dict = {}, text2font: dict = {}, text2gradient: dict = {}, text2slant: dict = {}, text2weight: dict = {}, # For convenience, one can use shortened names lsh: float | None = None, # Overrides line_spacing_height t2c: dict = {}, # Overrides text2color if nonempty t2f: dict = {}, # Overrides text2font if nonempty t2g: dict = {}, # Overrides text2gradient if nonempty t2s: dict = {}, # Overrides text2slant if nonempty t2w: dict = {}, # Overrides text2weight if nonempty global_config: dict = {}, local_configs: dict = {}, disable_ligatures: bool = True, isolate: Selector = re.compile(r"\w+", re.U), **kwargs ): self.text = text self.font_size = font_size self.justify = justify self.indent = indent self.alignment = alignment or get_customization()["style"]["text_alignment"] self.line_width = line_width self.font = font or get_customization()["style"]["font"] self.slant = slant self.weight = weight self.lsh = line_spacing_height or lsh self.t2c = text2color or t2c self.t2f = text2font or t2f self.t2g = text2gradient or t2g self.t2s = text2slant or t2s self.t2w = text2weight or t2w self.global_config = global_config self.local_configs = local_configs self.disable_ligatures = disable_ligatures self.isolate = isolate if not isinstance(self, Text): self.validate_markup_string(text) super().__init__(text, height=height, **kwargs) if self.t2g: log.warning(""" Manim currently cannot parse gradient from svg. Please set gradient via `set_color_by_gradient`. """) if gradient: self.set_color_by_gradient(*gradient) if self.t2c: self.set_color_by_text_to_color_map(self.t2c) if height is None: self.scale(TEXT_MOB_SCALE_FACTOR) @property def hash_seed(self) -> tuple: return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.base_color, self.isolate, self.protect, self.text, self.font_size, self.lsh, self.justify, self.indent, self.alignment, self.line_width, self.font, self.slant, self.weight, self.t2c, self.t2f, self.t2s, self.t2w, self.global_config, self.local_configs, self.disable_ligatures ) def get_file_path_by_content(self, content: str) -> str: hash_content = str(( content, self.justify, self.indent, self.alignment, self.line_width )) svg_file = os.path.join( get_text_dir(), hash_string(hash_content) + ".svg" ) if not os.path.exists(svg_file): self.markup_to_svg(content, svg_file) return svg_file def markup_to_svg(self, markup_str: str, file_name: str) -> str: self.validate_markup_string(markup_str) # `manimpango` is under construction, # so the following code is intended to suit its interface alignment = _Alignment(self.alignment) if self.line_width is None: pango_width = -1 else: pango_width = self.line_width / FRAME_WIDTH * DEFAULT_PIXEL_WIDTH return manimpango.MarkupUtils.text2svg( text=markup_str, font="", # Already handled slant="NORMAL", # Already handled weight="NORMAL", # Already handled size=1, # Already handled _=0, # Empty parameter disable_liga=False, file_name=file_name, START_X=0, START_Y=0, width=DEFAULT_CANVAS_WIDTH, height=DEFAULT_CANVAS_HEIGHT, justify=self.justify, indent=self.indent, line_spacing=None, # Already handled alignment=alignment, pango_width=pango_width ) @staticmethod def validate_markup_string(markup_str: str) -> None: validate_error = manimpango.MarkupUtils.validate(markup_str) if not validate_error: return raise ValueError( f"Invalid markup string \"{markup_str}\"\n" + \ f"{validate_error}" ) # Toolkits @staticmethod def escape_markup_char(substr: str) -> str: return MarkupText.MARKUP_ENTITY_DICT.get(substr, substr) @staticmethod def unescape_markup_char(substr: str) -> str: return { v: k for k, v in MarkupText.MARKUP_ENTITY_DICT.items() }.get(substr, substr) # Parsing @staticmethod def get_command_matches(string: str) -> list[re.Match]: pattern = re.compile(r""" (?P<tag> < (?P<close_slash>/)? (?P<tag_name>\w+)\s* (?P<attr_list>(?:\w+\s*\=\s*(?P<quot>["']).*?(?P=quot)\s*)*) (?P<elision_slash>/)? > ) |(?P<passthrough> <\?.*?\?>|<!--.*?-->|<!\[CDATA\[.*?\]\]>|<!DOCTYPE.*?> ) |(?P<entity>&(?P<unicode>\#(?P<hex>x)?)?(?P<content>.*?);) |(?P<char>[>"']) """, flags=re.X | re.S) return list(pattern.finditer(string)) @staticmethod def get_command_flag(match_obj: re.Match) -> int: if match_obj.group("tag"): if match_obj.group("close_slash"): return -1 if not match_obj.group("elision_slash"): return 1 return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: if match_obj.group("tag"): return "" if match_obj.group("char"): return MarkupText.escape_markup_char(match_obj.group("char")) return match_obj.group() @staticmethod def replace_for_matching(match_obj: re.Match) -> str: if match_obj.group("tag") or match_obj.group("passthrough"): return "" if match_obj.group("entity"): if match_obj.group("unicode"): base = 10 if match_obj.group("hex"): base = 16 return chr(int(match_obj.group("content"), base)) return MarkupText.unescape_markup_char(match_obj.group("entity")) return match_obj.group() @staticmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match ) -> dict[str, str] | None: pattern = r""" (?P<attr_name>\w+) \s*\=\s* (?P<quot>["'])(?P<attr_val>.*?)(?P=quot) """ tag_name = open_command.group("tag_name") if tag_name == "span": return { match_obj.group("attr_name"): match_obj.group("attr_val") for match_obj in re.finditer( pattern, open_command.group("attr_list"), re.S | re.X ) } return MarkupText.MARKUP_TAGS.get(tag_name, {}) def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [ *( (span, {key: val}) for t2x_dict, key in ( (self.t2c, "foreground"), (self.t2f, "font_family"), (self.t2s, "font_style"), (self.t2w, "font_weight") ) for selector, val in t2x_dict.items() for span in self.find_spans_by_selector(selector) ), *( (span, local_config) for selector, local_config in self.local_configs.items() for span in self.find_spans_by_selector(selector) ) ] @staticmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: if is_end: return "</span>" if label_hex is not None: converted_attr_dict = {"foreground": label_hex} for key, val in attr_dict.items(): if key in ( "background", "bgcolor", "underline_color", "overline_color", "strikethrough_color" ): converted_attr_dict[key] = "black" elif key not in ("foreground", "fgcolor", "color"): converted_attr_dict[key] = val else: converted_attr_dict = attr_dict.copy() attrs_str = " ".join([ f"{key}='{val}'" for key, val in converted_attr_dict.items() ]) return f"<span {attrs_str}>" def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: global_attr_dict = { "foreground": color_to_hex(self.base_color), "font_family": self.font, "font_style": self.slant, "font_weight": self.weight, "font_size": str(round(self.font_size * 1024)), } # `line_height` attribute is supported since Pango 1.50. pango_version = manimpango.pango_version() if tuple(map(int, pango_version.split("."))) < (1, 50): if self.lsh is not None: log.warning( "Pango version %s found (< 1.50), " "unable to set `line_height` attribute", pango_version ) else: line_spacing_scale = self.lsh or DEFAULT_LINE_SPACING_SCALE global_attr_dict["line_height"] = str( ((line_spacing_scale) + 1) * 0.6 ) if self.disable_ligatures: global_attr_dict["font_features"] = "liga=0,dlig=0,clig=0,hlig=0" global_attr_dict.update(self.global_config) return tuple( self.get_command_string( global_attr_dict, is_end=is_end, label_hex=int_to_hex(0) if is_labelled else None ) for is_end in (False, True) ) # Method alias def get_parts_by_text(self, selector: Selector) -> VGroup: return self.select_parts(selector) def get_part_by_text(self, selector: Selector, **kwargs) -> VGroup: return self.select_part(selector, **kwargs) def set_color_by_text(self, selector: Selector, color: ManimColor): return self.set_parts_color(selector, color) def set_color_by_text_to_color_map( self, color_map: dict[Selector, ManimColor] ): return self.set_parts_color_by_dict(color_map) def get_text(self) -> str: return self.get_string() class Text(MarkupText): def __init__( self, text: str, # For backward compatibility isolate: Selector = (re.compile(r"\w+", re.U), re.compile(r"\S+", re.U)), use_labelled_svg: bool = True, path_string_config: dict = dict( use_simple_quadratic_approx=True, ), **kwargs ): super().__init__( text, isolate=isolate, use_labelled_svg=use_labelled_svg, path_string_config=path_string_config, **kwargs ) @staticmethod def get_command_matches(string: str) -> list[re.Match]: pattern = re.compile(r"""[<>&"']""") return list(pattern.finditer(string)) @staticmethod def get_command_flag(match_obj: re.Match) -> int: return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: return Text.escape_markup_char(match_obj.group()) @staticmethod def replace_for_matching(match_obj: re.Match) -> str: return match_obj.group() class Code(MarkupText): def __init__( self, code: str, font: str = "Consolas", font_size: int = 24, lsh: float = 1.0, fill_color: ManimColor = None, stroke_color: ManimColor = None, language: str = "python", # Visit https://pygments.org/demo/ to have a preview of more styles. code_style: str = "monokai", **kwargs ): lexer = pygments.lexers.get_lexer_by_name(language) formatter = pygments.formatters.PangoMarkupFormatter( style=code_style ) markup = pygments.highlight(code, lexer, formatter) markup = re.sub(r"</?tt>", "", markup) super().__init__( markup, font=font, font_size=font_size, lsh=lsh, stroke_color=stroke_color, fill_color=fill_color, **kwargs ) @contextmanager def register_font(font_file: str | Path): """Temporarily add a font file to Pango's search path. This searches for the font_file at various places. The order it searches it described below. 1. Absolute path. 2. Downloads dir. Parameters ---------- font_file : The font file to add. Examples -------- Use ``with register_font(...)`` to add a font file to search path. .. code-block:: python with register_font("path/to/font_file.ttf"): a = Text("Hello", font="Custom Font Name") Raises ------ FileNotFoundError: If the font doesn't exists. AttributeError: If this method is used on macOS. Notes ----- This method of adding font files also works with :class:`CairoText`. .. important :: This method is available for macOS for ``ManimPango>=v0.2.3``. Using this method with previous releases will raise an :class:`AttributeError` on macOS. """ input_folder = Path(get_downloads_dir()).parent.resolve() possible_paths = [ Path(font_file), input_folder / font_file, ] for path in possible_paths: path = path.resolve() if path.exists(): file_path = path break else: error = f"Can't find {font_file}." f"Tried these : {possible_paths}" raise FileNotFoundError(error) try: assert manimpango.register_font(str(file_path)) yield finally: manimpango.unregister_font(str(file_path))
manim_3b1b/manimlib/mobject/svg/__init__.py
manim_3b1b/manimlib/mobject/svg/drawings.py
from __future__ import annotations import numpy as np import itertools as it from manimlib.animation.composition import AnimationGroup from manimlib.animation.rotation import Rotating from manimlib.constants import BLACK from manimlib.constants import BLUE_A from manimlib.constants import BLUE_B from manimlib.constants import BLUE_C from manimlib.constants import BLUE_D from manimlib.constants import DOWN from manimlib.constants import DOWN from manimlib.constants import FRAME_WIDTH from manimlib.constants import GREEN from manimlib.constants import GREEN_SCREEN from manimlib.constants import GREEN_E from manimlib.constants import GREY from manimlib.constants import GREY_A from manimlib.constants import GREY_B from manimlib.constants import GREY_E from manimlib.constants import LEFT from manimlib.constants import LEFT from manimlib.constants import MED_LARGE_BUFF from manimlib.constants import MED_SMALL_BUFF from manimlib.constants import ORIGIN from manimlib.constants import OUT from manimlib.constants import PI from manimlib.constants import RED from manimlib.constants import RED_E from manimlib.constants import RIGHT from manimlib.constants import SMALL_BUFF from manimlib.constants import SMALL_BUFF from manimlib.constants import UP from manimlib.constants import UL from manimlib.constants import UR from manimlib.constants import DL from manimlib.constants import DR from manimlib.constants import WHITE from manimlib.constants import YELLOW from manimlib.constants import TAU from manimlib.mobject.boolean_ops import Difference from manimlib.mobject.geometry import Arc from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.mobject import Mobject from manimlib.mobject.numbers import Integer from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.special_tex import TexTextFromPresetString from manimlib.mobject.three_dimensions import Prismify from manimlib.mobject.three_dimensions import VCube from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.rate_functions import linear from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import rotate_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Tuple, Sequence, Callable from manimlib.typing import ManimColor, Vect3 class Checkmark(TexTextFromPresetString): tex: str = R"\ding{51}" default_color: ManimColor = GREEN class Exmark(TexTextFromPresetString): tex: str = R"\ding{55}" default_color: ManimColor = RED class Lightbulb(SVGMobject): file_name = "lightbulb" def __init__( self, height: float = 1.0, color: ManimColor = YELLOW, stroke_width: float = 3.0, fill_opacity: float = 0.0, **kwargs ): super().__init__( height=height, color=color, stroke_width=stroke_width, fill_opacity=fill_opacity, **kwargs ) self.insert_n_curves(25) class Speedometer(VMobject): def __init__( self, arc_angle: float = 4 * PI / 3, num_ticks: int = 8, tick_length: float = 0.2, needle_width: float = 0.1, needle_height: float = 0.8, needle_color: ManimColor = YELLOW, **kwargs, ): super().__init__(**kwargs) self.arc_angle = arc_angle self.num_ticks = num_ticks self.tick_length = tick_length self.needle_width = needle_width self.needle_height = needle_height self.needle_color = needle_color start_angle = PI / 2 + arc_angle / 2 end_angle = PI / 2 - arc_angle / 2 self.arc = Arc( start_angle=start_angle, angle=-self.arc_angle ) self.add(self.arc) tick_angle_range = np.linspace(start_angle, end_angle, num_ticks) for index, angle in enumerate(tick_angle_range): vect = rotate_vector(RIGHT, angle) tick = Line((1 - tick_length) * vect, vect) label = Integer(10 * index) label.set_height(tick_length) label.shift((1 + tick_length) * vect) self.add(tick, label) needle = Polygon( LEFT, UP, RIGHT, stroke_width=0, fill_opacity=1, fill_color=self.needle_color ) needle.stretch_to_fit_width(needle_width) needle.stretch_to_fit_height(needle_height) needle.rotate(start_angle - np.pi / 2, about_point=ORIGIN) self.add(needle) self.needle = needle self.center_offset = self.get_center() def get_center(self): result = VMobject.get_center(self) if hasattr(self, "center_offset"): result -= self.center_offset return result def get_needle_tip(self): return self.needle.get_anchors()[1] def get_needle_angle(self): return angle_of_vector( self.get_needle_tip() - self.get_center() ) def rotate_needle(self, angle): self.needle.rotate(angle, about_point=self.arc.get_arc_center()) return self def move_needle_to_velocity(self, velocity): max_velocity = 10 * (self.num_ticks - 1) proportion = float(velocity) / max_velocity start_angle = np.pi / 2 + self.arc_angle / 2 target_angle = start_angle - self.arc_angle * proportion self.rotate_needle(target_angle - self.get_needle_angle()) return self class Laptop(VGroup): def __init__( self, width: float = 3, body_dimensions: Tuple[float, float, float] = (4.0, 3.0, 0.05), screen_thickness: float = 0.01, keyboard_width_to_body_width: float = 0.9, keyboard_height_to_body_height: float = 0.5, screen_width_to_screen_plate_width: float = 0.9, key_color_kwargs: dict = dict( stroke_width=0, fill_color=BLACK, fill_opacity=1, ), fill_opacity: float = 1.0, stroke_width: float = 0.0, body_color: ManimColor = GREY_B, shaded_body_color: ManimColor = GREY, open_angle: float = np.pi / 4, **kwargs ): super().__init__(**kwargs) body = VCube(side_length=1) for dim, scale_factor in enumerate(body_dimensions): body.stretch(scale_factor, dim=dim) body.set_width(width) body.set_fill(shaded_body_color, opacity=1) body.sort(lambda p: p[2]) body[-1].set_fill(body_color) screen_plate = body.copy() keyboard = VGroup(*[ VGroup(*[ Square(**key_color_kwargs) for x in range(12 - y % 2) ]).arrange(RIGHT, buff=SMALL_BUFF) for y in range(4) ]).arrange(DOWN, buff=MED_SMALL_BUFF) keyboard.stretch_to_fit_width( keyboard_width_to_body_width * body.get_width(), ) keyboard.stretch_to_fit_height( keyboard_height_to_body_height * body.get_height(), ) keyboard.next_to(body, OUT, buff=0.1 * SMALL_BUFF) keyboard.shift(MED_SMALL_BUFF * UP) body.add(keyboard) screen_plate.stretch(screen_thickness / body_dimensions[2], dim=2) screen = Rectangle( stroke_width=0, fill_color=BLACK, fill_opacity=1, ) screen.replace(screen_plate, stretch=True) screen.scale(screen_width_to_screen_plate_width) screen.next_to(screen_plate, OUT, buff=0.1 * SMALL_BUFF) screen_plate.add(screen) screen_plate.next_to(body, UP, buff=0) screen_plate.rotate( open_angle, RIGHT, about_point=screen_plate.get_bottom() ) self.screen_plate = screen_plate self.screen = screen axis = Line( body.get_corner(UP + LEFT + OUT), body.get_corner(UP + RIGHT + OUT), color=BLACK, stroke_width=2 ) self.axis = axis self.add(body, screen_plate, axis) class VideoIcon(SVGMobject): file_name: str = "video_icon" def __init__( self, width: float = 1.2, color=BLUE_A, **kwargs ): super().__init__(color=color, **kwargs) self.set_width(width) class VideoSeries(VGroup): def __init__( self, num_videos: int = 11, gradient_colors: Sequence[ManimColor] = [BLUE_B, BLUE_D], width: float = FRAME_WIDTH - MED_LARGE_BUFF, **kwargs ): super().__init__( *(VideoIcon() for x in range(num_videos)), **kwargs ) self.arrange(RIGHT) self.set_width(width) self.set_color_by_gradient(*gradient_colors) class Clock(VGroup): def __init__( self, stroke_color: ManimColor = WHITE, stroke_width: float = 3.0, hour_hand_height: float = 0.3, minute_hand_height: float = 0.6, tick_length: float = 0.1, **kwargs, ): style = dict(stroke_color=stroke_color, stroke_width=stroke_width) circle = Circle(**style) ticks = [] for x, point in enumerate(compass_directions(12, UP)): length = tick_length if x % 3 == 0: length *= 2 ticks.append(Line(point, (1 - length) * point, **style)) self.hour_hand = Line(ORIGIN, hour_hand_height * UP, **style) self.minute_hand = Line(ORIGIN, minute_hand_height * UP, **style) super().__init__( circle, self.hour_hand, self.minute_hand, *ticks ) class ClockPassesTime(AnimationGroup): def __init__( self, clock: Clock, run_time: float = 5.0, hours_passed: float = 12.0, rate_func: Callable[[float], float] = linear, **kwargs ): rot_kwargs = dict( axis=OUT, about_point=clock.get_center() ) hour_radians = -hours_passed * 2 * PI / 12 super().__init__( Rotating( clock.hour_hand, angle=hour_radians, **rot_kwargs ), Rotating( clock.minute_hand, angle=12 * hour_radians, **rot_kwargs ), **kwargs ) class Bubble(SVGMobject): file_name: str = "Bubbles_speech.svg" def __init__( self, direction: Vect3 = LEFT, center_point: Vect3 = ORIGIN, content_scale_factor: float = 0.7, height: float = 4.0, width: float = 8.0, max_height: float | None = None, max_width: float | None = None, bubble_center_adjustment_factor: float = 0.125, fill_color: ManimColor = BLACK, fill_opacity: float = 0.8, stroke_color: ManimColor = WHITE, stroke_width: float = 3.0, **kwargs ): self.direction = LEFT # Possibly updated below by self.flip() self.bubble_center_adjustment_factor = bubble_center_adjustment_factor self.content_scale_factor = content_scale_factor super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, **kwargs ) self.center() self.set_height(height, stretch=True) self.set_width(width, stretch=True) if max_height: self.set_max_height(max_height) if max_width: self.set_max_width(max_width) if direction[0] > 0: self.flip() self.content = VMobject() def get_tip(self): # TODO, find a better way return self.get_corner(DOWN + self.direction) - 0.6 * self.direction def get_bubble_center(self): factor = self.bubble_center_adjustment_factor return self.get_center() + factor * self.get_height() * UP def move_tip_to(self, point): mover = VGroup(self) if self.content is not None: mover.add(self.content) mover.shift(point - self.get_tip()) return self def flip(self, axis=UP): super().flip(axis=axis) if abs(axis[1]) > 0: self.direction = -np.array(self.direction) return self def pin_to(self, mobject, auto_flip=False): mob_center = mobject.get_center() want_to_flip = np.sign(mob_center[0]) != np.sign(self.direction[0]) if want_to_flip and auto_flip: self.flip() boundary_point = mobject.get_bounding_box_point(UP - self.direction) vector_from_center = 1.0 * (boundary_point - mob_center) self.move_tip_to(mob_center + vector_from_center) return self def position_mobject_inside(self, mobject): mobject.set_max_width(self.content_scale_factor * self.get_width()) mobject.set_max_height(self.content_scale_factor * self.get_height() / 1.5) mobject.shift(self.get_bubble_center() - mobject.get_center()) return mobject def add_content(self, mobject): self.position_mobject_inside(mobject) self.content = mobject return self.content def write(self, *text): self.add_content(TexText(*text)) return self def resize_to_content(self, buff=0.75): width = self.content.get_width() height = self.content.get_height() target_width = width + min(buff, height) target_height = 1.35 * (self.content.get_height() + buff) tip_point = self.get_tip() self.stretch_to_fit_width(target_width, about_point=tip_point) self.stretch_to_fit_height(target_height, about_point=tip_point) self.position_mobject_inside(self.content) def clear(self): self.add_content(VMobject()) return self class SpeechBubble(Bubble): file_name: str = "Bubbles_speech.svg" class DoubleSpeechBubble(Bubble): file_name: str = "Bubbles_double_speech.svg" class ThoughtBubble(Bubble): file_name: str = "Bubbles_thought.svg" def __init__(self, **kwargs): Bubble.__init__(self, **kwargs) self.submobjects.sort( key=lambda m: m.get_bottom()[1] ) def make_green_screen(self): self.submobjects[-1].set_fill(GREEN_SCREEN, opacity=1) return self class VectorizedEarth(SVGMobject): file_name: str = "earth" def __init__( self, height: float = 2.0, **kwargs ): super().__init__(height=height, **kwargs) self.insert_n_curves(20) circle = Circle( stroke_width=3, stroke_color=GREEN, fill_opacity=1, fill_color=BLUE_C, ) circle.replace(self) self.add_to_back(circle) class Piano(VGroup): def __init__( self, n_white_keys = 52, black_pattern = [0, 2, 3, 5, 6], white_keys_per_octave = 7, white_key_dims = (0.15, 1.0), black_key_dims = (0.1, 0.66), key_buff = 0.02, white_key_color = WHITE, black_key_color = GREY_E, total_width = 13, **kwargs ): self.n_white_keys = n_white_keys self.black_pattern = black_pattern self.white_keys_per_octave = white_keys_per_octave self.white_key_dims = white_key_dims self.black_key_dims = black_key_dims self.key_buff = key_buff self.white_key_color = white_key_color self.black_key_color = black_key_color self.total_width = total_width super().__init__(**kwargs) self.add_white_keys() self.add_black_keys() self.sort_keys() self[:-1].reverse_points() self.set_width(self.total_width) def add_white_keys(self): key = Rectangle(*self.white_key_dims) key.set_fill(self.white_key_color, 1) key.set_stroke(width=0) self.white_keys = key.get_grid(1, self.n_white_keys, buff=self.key_buff) self.add(*self.white_keys) def add_black_keys(self): key = Rectangle(*self.black_key_dims) key.set_fill(self.black_key_color, 1) key.set_stroke(width=0) self.black_keys = VGroup() for i in range(len(self.white_keys) - 1): if i % self.white_keys_per_octave not in self.black_pattern: continue wk1 = self.white_keys[i] wk2 = self.white_keys[i + 1] bk = key.copy() bk.move_to(midpoint(wk1.get_top(), wk2.get_top()), UP) big_bk = bk.copy() big_bk.stretch((bk.get_width() + self.key_buff) / bk.get_width(), 0) big_bk.stretch((bk.get_height() + self.key_buff) / bk.get_height(), 1) big_bk.move_to(bk, UP) for wk in wk1, wk2: wk.become(Difference(wk, big_bk).match_style(wk)) self.black_keys.add(bk) self.add(*self.black_keys) def sort_keys(self): self.sort(lambda p: p[0]) class Piano3D(VGroup): def __init__( self, shading: Tuple[float, float, float] = (1.0, 0.2, 0.2), stroke_width: float = 0.25, stroke_color: ManimColor = BLACK, key_depth: float = 0.1, black_key_shift: float = 0.05, piano_2d_config: dict = dict( white_key_color=GREY_A, key_buff=0.001 ), **kwargs ): piano_2d = Piano(**piano_2d_config) super().__init__(*( Prismify(key, key_depth) for key in piano_2d )) self.set_stroke(stroke_color, stroke_width) self.set_shading(*shading) self.apply_depth_test() # Elevate black keys for i, key in enumerate(self): if piano_2d[i] in piano_2d.black_keys: key.shift(black_key_shift * OUT) key.set_color(BLACK) class DieFace(VGroup): def __init__( self, value: int, side_length: float = 1.0, corner_radius: float = 0.15, stroke_color: ManimColor = WHITE, stroke_width: float = 2.0, fill_color: ManimColor = GREY_E, dot_radius: float = 0.08, dot_color: ManimColor = WHITE, dot_coalesce_factor: float = 0.5 ): dot = Dot(radius=dot_radius, fill_color=dot_color) square = Square( side_length=side_length, stroke_color=stroke_color, stroke_width=stroke_width, fill_color=fill_color, fill_opacity=1.0, ) square.round_corners(corner_radius) if not (1 <= value <= 6): raise Exception("DieFace only accepts integer inputs between 1 and 6") edge_group = [ (ORIGIN,), (UL, DR), (UL, ORIGIN, DR), (UL, UR, DL, DR), (UL, UR, ORIGIN, DL, DR), (UL, UR, LEFT, RIGHT, DL, DR), ][value - 1] arrangement = VGroup(*( dot.copy().move_to(square.get_bounding_box_point(vect)) for vect in edge_group )) arrangement.space_out_submobjects(dot_coalesce_factor) super().__init__(square, arrangement) self.dots = arrangement self.value = value self.index = value class Dartboard(VGroup): radius = 3 n_sectors = 20 def __init__(self, **kwargs): super().__init__(**kwargs) n_sectors = self.n_sectors angle = TAU / n_sectors segments = VGroup(*[ VGroup(*[ AnnularSector( inner_radius=in_r, outer_radius=out_r, start_angle=n * angle, angle=angle, fill_color=color, ) for n, color in zip( range(n_sectors), it.cycle(colors) ) ]) for colors, in_r, out_r in [ ([GREY_B, GREY_E], 0, 1), ([GREEN_E, RED_E], 0.5, 0.55), ([GREEN_E, RED_E], 0.95, 1), ] ]) segments.rotate(-angle / 2) bullseyes = VGroup(*[ Circle(radius=r) for r in [0.07, 0.035] ]) bullseyes.set_fill(opacity=1) bullseyes.set_stroke(width=0) bullseyes[0].set_color(GREEN_E) bullseyes[1].set_color(RED_E) self.bullseye = bullseyes[1] self.add(*segments, *bullseyes) self.scale(self.radius)
manim_3b1b/manimlib/mobject/svg/old_tex_mobject.py
from __future__ import annotations from functools import reduce import operator as op import re from manimlib.constants import BLACK, WHITE from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.tex_file_writing import tex_content_to_svg_file from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, List, Dict from manimlib.typing import ManimColor SCALE_FACTOR_PER_FONT_POINT = 0.001 class SingleStringTex(SVGMobject): height: float | None = None def __init__( self, tex_string: str, height: float | None = None, fill_color: ManimColor = WHITE, fill_opacity: float = 1.0, stroke_width: float = 0, svg_default: dict = dict(fill_color=WHITE), path_string_config: dict = dict(), font_size: int = 48, alignment: str = R"\centering", math_mode: bool = True, organize_left_to_right: bool = False, template: str = "", additional_preamble: str = "", **kwargs ): self.tex_string = tex_string self.svg_default = dict(svg_default) self.path_string_config = dict(path_string_config) self.font_size = font_size self.alignment = alignment self.math_mode = math_mode self.organize_left_to_right = organize_left_to_right self.template = template self.additional_preamble = additional_preamble super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, path_string_config=path_string_config, **kwargs ) if self.height is None: self.scale(SCALE_FACTOR_PER_FONT_POINT * self.font_size) if self.organize_left_to_right: self.organize_submobjects_left_to_right() @property def hash_seed(self) -> tuple: return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.tex_string, self.alignment, self.math_mode, self.template, self.additional_preamble ) def get_file_path(self) -> str: content = self.get_tex_file_body(self.tex_string) file_path = tex_content_to_svg_file( content, self.template, self.additional_preamble, self.tex_string ) return file_path def get_tex_file_body(self, tex_string: str) -> str: new_tex = self.get_modified_expression(tex_string) if self.math_mode: new_tex = "\\begin{align*}\n" + new_tex + "\n\\end{align*}" return self.alignment + "\n" + new_tex def get_modified_expression(self, tex_string: str) -> str: return self.modify_special_strings(tex_string.strip()) def modify_special_strings(self, tex: str) -> str: tex = tex.strip() should_add_filler = reduce(op.or_, [ # Fraction line needs something to be over tex == "\\over", tex == "\\overline", # Makesure sqrt has overbar tex == "\\sqrt", tex == "\\sqrt{", # Need to add blank subscript or superscript tex.endswith("_"), tex.endswith("^"), tex.endswith("dot"), ]) if should_add_filler: filler = "{\\quad}" tex += filler should_add_double_filler = reduce(op.or_, [ tex == "\\overset", # TODO: these can't be used since they change # the latex draw order. # tex == "\\frac", # you can use \\over as a alternative # tex == "\\dfrac", # tex == "\\binom", ]) if should_add_double_filler: filler = "{\\quad}{\\quad}" tex += filler if tex == "\\substack": tex = "\\quad" if tex == "": tex = "\\quad" # To keep files from starting with a line break if tex.startswith("\\\\"): tex = tex.replace("\\\\", "\\quad\\\\") tex = self.balance_braces(tex) # Handle imbalanced \left and \right num_lefts, num_rights = [ len([ s for s in tex.split(substr)[1:] if s and s[0] in "(){}[]|.\\" ]) for substr in ("\\left", "\\right") ] if num_lefts != num_rights: tex = tex.replace("\\left", "\\big") tex = tex.replace("\\right", "\\big") for context in ["array"]: begin_in = ("\\begin{%s}" % context) in tex end_in = ("\\end{%s}" % context) in tex if begin_in ^ end_in: # Just turn this into a blank string, # which means caller should leave a # stray \\begin{...} with other symbols tex = "" return tex def balance_braces(self, tex: str) -> str: """ Makes Tex resiliant to unmatched braces """ num_unclosed_brackets = 0 for i in range(len(tex)): if i > 0 and tex[i - 1] == "\\": # So as to not count '\{' type expressions continue char = tex[i] if char == "{": num_unclosed_brackets += 1 elif char == "}": if num_unclosed_brackets == 0: tex = "{" + tex else: num_unclosed_brackets -= 1 tex += num_unclosed_brackets * "}" return tex def get_tex(self) -> str: return self.tex_string def organize_submobjects_left_to_right(self): self.sort(lambda p: p[0]) return self class OldTex(SingleStringTex): def __init__( self, *tex_strings: str, arg_separator: str = "", isolate: List[str] = [], tex_to_color_map: Dict[str, ManimColor] = {}, **kwargs ): self.tex_strings = self.break_up_tex_strings( tex_strings, substrings_to_isolate=[*isolate, *tex_to_color_map.keys()] ) full_string = arg_separator.join(self.tex_strings) super().__init__(full_string, **kwargs) self.break_up_by_substrings(self.tex_strings) self.set_color_by_tex_to_color_map(tex_to_color_map) if self.organize_left_to_right: self.organize_submobjects_left_to_right() def break_up_tex_strings(self, tex_strings: Iterable[str], substrings_to_isolate: List[str] = []) -> Iterable[str]: # Separate out any strings specified in the isolate # or tex_to_color_map lists. if len(substrings_to_isolate) == 0: return tex_strings patterns = ( "({})".format(re.escape(ss)) for ss in substrings_to_isolate ) pattern = "|".join(patterns) pieces = [] for s in tex_strings: if pattern: pieces.extend(re.split(pattern, s)) else: pieces.append(s) return list(filter(lambda s: s, pieces)) def break_up_by_substrings(self, tex_strings: Iterable[str]): """ Reorganize existing submojects one layer deeper based on the structure of tex_strings (as a list of tex_strings) """ if len(list(tex_strings)) == 1: submob = self.copy() self.set_submobjects([submob]) return self new_submobjects = [] curr_index = 0 for tex_string in tex_strings: tex_string = tex_string.strip() if len(tex_string) == 0: continue sub_tex_mob = SingleStringTex(tex_string, math_mode=self.math_mode) num_submobs = len(sub_tex_mob) if num_submobs == 0: continue new_index = curr_index + num_submobs sub_tex_mob.set_submobjects(self.submobjects[curr_index:new_index]) new_submobjects.append(sub_tex_mob) curr_index = new_index self.set_submobjects(new_submobjects) return self def get_parts_by_tex( self, tex: str, substring: bool = True, case_sensitive: bool = True ) -> VGroup: def test(tex1, tex2): if not case_sensitive: tex1 = tex1.lower() tex2 = tex2.lower() if substring: return tex1 in tex2 else: return tex1 == tex2 return VGroup(*filter( lambda m: isinstance(m, SingleStringTex) and test(tex, m.get_tex()), self.submobjects )) def get_part_by_tex(self, tex: str, **kwargs) -> SingleStringTex | None: all_parts = self.get_parts_by_tex(tex, **kwargs) return all_parts[0] if all_parts else None def set_color_by_tex(self, tex: str, color: ManimColor, **kwargs): self.get_parts_by_tex(tex, **kwargs).set_color(color) return self def set_color_by_tex_to_color_map( self, tex_to_color_map: dict[str, ManimColor], **kwargs ): for tex, color in list(tex_to_color_map.items()): self.set_color_by_tex(tex, color, **kwargs) return self def index_of_part(self, part: SingleStringTex, start: int = 0) -> int: return self.submobjects.index(part, start) def index_of_part_by_tex(self, tex: str, start: int = 0, **kwargs) -> int: part = self.get_part_by_tex(tex, **kwargs) return self.index_of_part(part, start) def slice_by_tex( self, start_tex: str | None = None, stop_tex: str | None = None, **kwargs ) -> VGroup: if start_tex is None: start_index = 0 else: start_index = self.index_of_part_by_tex(start_tex, **kwargs) if stop_tex is None: return self[start_index:] else: stop_index = self.index_of_part_by_tex(stop_tex, start=start_index, **kwargs) return self[start_index:stop_index] def sort_alphabetically(self) -> None: self.submobjects.sort(key=lambda m: m.get_tex()) def set_bstroke(self, color: ManimColor = BLACK, width: float = 4): self.set_stroke(color, width, background=True) return self class OldTexText(OldTex): def __init__( self, *tex_strings: str, math_mode: bool = False, arg_separator: str = "", **kwargs ): super().__init__( *tex_strings, math_mode=math_mode, arg_separator=arg_separator, **kwargs )
manim_3b1b/manimlib/mobject/svg/brace.py
from __future__ import annotations import math import copy import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER, SMALL_BUFF from manimlib.constants import DOWN, LEFT, ORIGIN, RIGHT, UP, DL, DR, UL from manimlib.constants import PI from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeIn from manimlib.animation.growing import GrowFromCenter from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.iterables import listify from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.animation.animation import Animation from manimlib.mobject.mobject import Mobject from manimlib.typing import Vect3 class Brace(Tex): def __init__( self, mobject: Mobject, direction: Vect3 = DOWN, buff: float = 0.2, tex_string: str = R"\underbrace{\qquad}", **kwargs ): super().__init__(tex_string, **kwargs) angle = -math.atan2(*direction[:2]) + PI mobject.rotate(-angle, about_point=ORIGIN) left = mobject.get_corner(DL) right = mobject.get_corner(DR) target_width = right[0] - left[0] self.tip_point_index = np.argmin(self.get_all_points()[:, 1]) self.set_initial_width(target_width) self.shift(left - self.get_corner(UL) + buff * DOWN) for mob in mobject, self: mob.rotate(angle, about_point=ORIGIN) def set_initial_width(self, width: float): width_diff = width - self.get_width() if width_diff > 0: for tip, rect, vect in [(self[0], self[1], RIGHT), (self[5], self[4], LEFT)]: rect.set_width( width_diff / 2 + rect.get_width(), about_edge=vect, stretch=True ) tip.shift(-width_diff / 2 * vect) else: self.set_width(width, stretch=True) return self def put_at_tip( self, mob: Mobject, use_next_to: bool = True, **kwargs ): if use_next_to: mob.next_to( self.get_tip(), np.round(self.get_direction()), **kwargs ) else: mob.move_to(self.get_tip()) buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_MOBJECT_BUFFER) shift_distance = mob.get_width() / 2.0 + buff mob.shift(self.get_direction() * shift_distance) return self def get_text(self, text: str, **kwargs) -> Text: buff = kwargs.pop("buff", SMALL_BUFF) text_mob = Text(text, **kwargs) self.put_at_tip(text_mob, buff=buff) return text_mob def get_tex(self, *tex: str, **kwargs) -> Tex: tex_mob = Tex(*tex) self.put_at_tip(tex_mob, **kwargs) return tex_mob def get_tip(self) -> np.ndarray: # Very specific to the LaTeX representation # of a brace, but it's the only way I can think # of to get the tip regardless of orientation. return self.get_all_points()[self.tip_point_index] def get_direction(self) -> np.ndarray: vect = self.get_tip() - self.get_center() return vect / get_norm(vect) class BraceLabel(VMobject): label_constructor: type = Tex def __init__( self, obj: VMobject | list[VMobject], text: str | Iterable[str], brace_direction: np.ndarray = DOWN, label_scale: float = 1.0, label_buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER, **kwargs ) -> None: super().__init__(**kwargs) self.brace_direction = brace_direction self.label_scale = label_scale self.label_buff = label_buff if isinstance(obj, list): obj = VGroup(*obj) self.brace = Brace(obj, brace_direction, **kwargs) self.label = self.label_constructor(*listify(text), **kwargs) self.label.scale(self.label_scale) self.brace.put_at_tip(self.label, buff=self.label_buff) self.set_submobjects([self.brace, self.label]) def creation_anim( self, label_anim: Animation = FadeIn, brace_anim: Animation = GrowFromCenter ) -> AnimationGroup: return AnimationGroup(brace_anim(self.brace), label_anim(self.label)) def shift_brace(self, obj: VMobject | list[VMobject], **kwargs): if isinstance(obj, list): obj = VMobject(*obj) self.brace = Brace(obj, self.brace_direction, **kwargs) self.brace.put_at_tip(self.label) self.submobjects[0] = self.brace return self def change_label(self, *text: str, **kwargs): self.label = self.label_constructor(*text, **kwargs) if self.label_scale != 1: self.label.scale(self.label_scale) self.brace.put_at_tip(self.label) self.submobjects[1] = self.label return self def change_brace_label(self, obj: VMobject | list[VMobject], *text: str): self.shift_brace(obj) self.change_label(*text) return self def copy(self): copy_mobject = copy.copy(self) copy_mobject.brace = self.brace.copy() copy_mobject.label = self.label.copy() copy_mobject.set_submobjects([copy_mobject.brace, copy_mobject.label]) return copy_mobject class BraceText(BraceLabel): label_constructor: type = TexText
manim_3b1b/manimlib/mobject/svg/string_mobject.py
from __future__ import annotations from abc import ABC, abstractmethod import itertools as it import re from scipy.optimize import linear_sum_assignment from scipy.spatial.distance import cdist from manimlib.constants import WHITE from manimlib.logger import log from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.color import color_to_hex from manimlib.utils.color import hex_to_int from manimlib.utils.color import int_to_hex from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor, Span, Selector class StringMobject(SVGMobject, ABC): """ An abstract base class for `Tex` and `MarkupText` This class aims to optimize the logic of "slicing submobjects via substrings". This could be much clearer and more user-friendly than slicing through numerical indices explicitly. Users are expected to specify substrings in `isolate` parameter if they want to do anything with their corresponding submobjects. `isolate` parameter can be either a string, a `re.Pattern` object, or a 2-tuple containing integers or None, or a collection of the above. Note, substrings specified cannot *partly* overlap with each other. Each instance of `StringMobject` may generate 2 svg files. The additional one is generated with some color commands inserted, so that each submobject of the original `SVGMobject` will be labelled by the color of its paired submobject from the additional `SVGMobject`. """ height = None def __init__( self, string: str, fill_color: ManimColor = WHITE, fill_border_width: float = 0.5, stroke_color: ManimColor = WHITE, stroke_width: float = 0, base_color: ManimColor = WHITE, isolate: Selector = (), protect: Selector = (), # When set to true, only the labelled svg is # rendered, and its contents are used directly # for the body of this String Mobject use_labelled_svg: bool = False, **kwargs ): self.string = string self.base_color = base_color or WHITE self.isolate = isolate self.protect = protect self.use_labelled_svg = use_labelled_svg self.parse() super().__init__(**kwargs) self.set_stroke(stroke_color, stroke_width) self.set_fill(fill_color, border_width=fill_border_width) self.note_changed_stroke() self.labels = [submob.label for submob in self.submobjects] def get_file_path(self, is_labelled: bool = False) -> str: is_labelled = is_labelled or self.use_labelled_svg return self.get_file_path_by_content(self.get_content(is_labelled)) @abstractmethod def get_file_path_by_content(self, content: str) -> str: return "" def assign_labels_by_color(self, mobjects: list[VMobject]) -> None: """ Assuming each mobject in the list `mobjects` has a fill color meant to represent a numerical label, this assigns those those numerical labels to each mobject as an attribute """ labels_count = len(self.labelled_spans) if labels_count == 1: for mob in mobjects: mob.label = 0 return unrecognizable_colors = [] for mob in mobjects: label = hex_to_int(color_to_hex(mob.get_fill_color())) if label >= labels_count: unrecognizable_colors.append(label) label = 0 mob.label = label if unrecognizable_colors: log.warning( "Unrecognizable color labels detected (%s). " + \ "The result could be unexpected.", ", ".join( int_to_hex(color) for color in unrecognizable_colors ) ) def mobjects_from_file(self, file_path: str) -> list[VMobject]: submobs = super().mobjects_from_file(file_path) if self.use_labelled_svg: # This means submobjects are colored according to spans self.assign_labels_by_color(submobs) return submobs # Otherwise, submobs are not colored, so generate a new list # of submobject which are and use those for labels unlabelled_submobs = submobs labelled_content = self.get_content(is_labelled=True) labelled_file = self.get_file_path_by_content(labelled_content) labelled_submobs = super().mobjects_from_file(labelled_file) self.labelled_submobs = labelled_submobs self.unlabelled_submobs = unlabelled_submobs self.assign_labels_by_color(labelled_submobs) self.rearrange_submobjects_by_positions(labelled_submobs, unlabelled_submobs) for usm, lsm in zip(unlabelled_submobs, labelled_submobs): usm.label = lsm.label if len(unlabelled_submobs) != len(labelled_submobs): log.warning( "Cannot align submobjects of the labelled svg " + \ "to the original svg. Skip the labelling process." ) for usm in unlabelled_submobs: usm.label = 0 return unlabelled_submobs return unlabelled_submobs def rearrange_submobjects_by_positions( self, labelled_submobs: list[VMobject], unlabelled_submobs: list[VMobject], ) -> None: """ Rearrange `labeleled_submobjects` so that each submobject is labelled by the nearest one of `unlabelled_submobs`. The correctness cannot be ensured, since the svg may change significantly after inserting color commands. """ if len(labelled_submobs) == 0: return labelled_svg = VGroup(*labelled_submobs) labelled_svg.replace(VGroup(*unlabelled_submobs)) distance_matrix = cdist( [submob.get_center() for submob in unlabelled_submobs], [submob.get_center() for submob in labelled_submobs] ) _, indices = linear_sum_assignment(distance_matrix) labelled_submobs[:] = [labelled_submobs[index] for index in indices] # Toolkits def find_spans_by_selector(self, selector: Selector) -> list[Span]: def find_spans_by_single_selector(sel): if isinstance(sel, str): return [ match_obj.span() for match_obj in re.finditer(re.escape(sel), self.string) ] if isinstance(sel, re.Pattern): return [ match_obj.span() for match_obj in sel.finditer(self.string) ] if isinstance(sel, tuple) and len(sel) == 2 and all( isinstance(index, int) or index is None for index in sel ): l = len(self.string) span = tuple( default_index if index is None else min(index, l) if index >= 0 else max(index + l, 0) for index, default_index in zip(sel, (0, l)) ) return [span] return None result = find_spans_by_single_selector(selector) if result is None: result = [] for sel in selector: spans = find_spans_by_single_selector(sel) if spans is None: raise TypeError(f"Invalid selector: '{sel}'") result.extend(spans) return list(filter(lambda span: span[0] <= span[1], result)) @staticmethod def span_contains(span_0: Span, span_1: Span) -> bool: return span_0[0] <= span_1[0] and span_0[1] >= span_1[1] # Parsing def parse(self) -> None: def get_substr(span: Span) -> str: return self.string[slice(*span)] configured_items = self.get_configured_items() isolated_spans = self.find_spans_by_selector(self.isolate) protected_spans = self.find_spans_by_selector(self.protect) command_matches = self.get_command_matches(self.string) def get_key(category, i, flag): def get_span_by_category(category, i): if category == 0: return configured_items[i][0] if category == 1: return isolated_spans[i] if category == 2: return protected_spans[i] return command_matches[i].span() index, paired_index = get_span_by_category(category, i)[::flag] return ( index, flag * (2 if index != paired_index else -1), -paired_index, flag * category, flag * i ) index_items = sorted([ (category, i, flag) for category, item_length in enumerate(( len(configured_items), len(isolated_spans), len(protected_spans), len(command_matches) )) for i in range(item_length) for flag in (1, -1) ], key=lambda t: get_key(*t)) inserted_items = [] labelled_items = [] overlapping_spans = [] level_mismatched_spans = [] label = 1 protect_level = 0 bracket_stack = [0] bracket_count = 0 open_command_stack = [] open_stack = [] for category, i, flag in index_items: if category >= 2: protect_level += flag if flag == 1 or category == 2: continue inserted_items.append((i, 0)) command_match = command_matches[i] command_flag = self.get_command_flag(command_match) if command_flag == 1: bracket_count += 1 bracket_stack.append(bracket_count) open_command_stack.append((len(inserted_items), i)) continue if command_flag == 0: continue pos, i_ = open_command_stack.pop() bracket_stack.pop() open_command_match = command_matches[i_] attr_dict = self.get_attr_dict_from_command_pair( open_command_match, command_match ) if attr_dict is None: continue span = (open_command_match.end(), command_match.start()) labelled_items.append((span, attr_dict)) inserted_items.insert(pos, (label, 1)) inserted_items.insert(-1, (label, -1)) label += 1 continue if flag == 1: open_stack.append(( len(inserted_items), category, i, protect_level, bracket_stack.copy() )) continue span, attr_dict = configured_items[i] \ if category == 0 else (isolated_spans[i], {}) pos, category_, i_, protect_level_, bracket_stack_ \ = open_stack.pop() if category_ != category or i_ != i: overlapping_spans.append(span) continue if protect_level_ or protect_level: continue if bracket_stack_ != bracket_stack: level_mismatched_spans.append(span) continue labelled_items.append((span, attr_dict)) inserted_items.insert(pos, (label, 1)) inserted_items.append((label, -1)) label += 1 labelled_items.insert(0, ((0, len(self.string)), {})) inserted_items.insert(0, (0, 1)) inserted_items.append((0, -1)) if overlapping_spans: log.warning( "Partly overlapping substrings detected: %s", ", ".join( f"'{get_substr(span)}'" for span in overlapping_spans ) ) if level_mismatched_spans: log.warning( "Cannot handle substrings: %s", ", ".join( f"'{get_substr(span)}'" for span in level_mismatched_spans ) ) def reconstruct_string( start_item: tuple[int, int], end_item: tuple[int, int], command_replace_func: Callable[[re.Match], str], command_insert_func: Callable[[int, int, dict[str, str]], str] ) -> str: def get_edge_item(i: int, flag: int) -> tuple[Span, str]: if flag == 0: match_obj = command_matches[i] return ( match_obj.span(), command_replace_func(match_obj) ) span, attr_dict = labelled_items[i] index = span[flag < 0] return ( (index, index), command_insert_func(i, flag, attr_dict) ) items = [ get_edge_item(i, flag) for i, flag in inserted_items[slice( inserted_items.index(start_item), inserted_items.index(end_item) + 1 )] ] pieces = [ get_substr((start, end)) for start, end in zip( [interval_end for (_, interval_end), _ in items[:-1]], [interval_start for (interval_start, _), _ in items[1:]] ) ] interval_pieces = [piece for _, piece in items[1:-1]] return "".join(it.chain(*zip(pieces, (*interval_pieces, "")))) self.labelled_spans = [span for span, _ in labelled_items] self.reconstruct_string = reconstruct_string def get_content(self, is_labelled: bool) -> str: content = self.reconstruct_string( (0, 1), (0, -1), self.replace_for_content, lambda label, flag, attr_dict: self.get_command_string( attr_dict, is_end=flag < 0, label_hex=int_to_hex(label) if is_labelled else None ) ) prefix, suffix = self.get_content_prefix_and_suffix( is_labelled=is_labelled ) return "".join((prefix, content, suffix)) @staticmethod @abstractmethod def get_command_matches(string: str) -> list[re.Match]: return [] @staticmethod @abstractmethod def get_command_flag(match_obj: re.Match) -> int: return 0 @staticmethod @abstractmethod def replace_for_content(match_obj: re.Match) -> str: return "" @staticmethod @abstractmethod def replace_for_matching(match_obj: re.Match) -> str: return "" @staticmethod @abstractmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match, ) -> dict[str, str] | None: return None @abstractmethod def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [] @staticmethod @abstractmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: return "" @abstractmethod def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: return "", "" # Selector def get_submob_indices_list_by_span( self, arbitrary_span: Span ) -> list[int]: return [ submob_index for submob_index, label in enumerate(self.labels) if self.span_contains(arbitrary_span, self.labelled_spans[label]) ] def get_specified_part_items(self) -> list[tuple[str, list[int]]]: return [ ( self.string[slice(*span)], self.get_submob_indices_list_by_span(span) ) for span in self.labelled_spans[1:] ] def get_specified_substrings(self) -> list[str]: substrs = [ self.string[slice(*span)] for span in self.labelled_spans[1:] ] # Use dict.fromkeys to remove duplicates while retaining order return list(dict.fromkeys(substrs).keys()) def get_group_part_items(self) -> list[tuple[str, list[int]]]: if not self.labels: return [] def get_neighbouring_pairs(vals): return list(zip(vals[:-1], vals[1:])) range_lens, group_labels = zip(*( (len(list(grouper)), val) for val, grouper in it.groupby(self.labels) )) submob_indices_lists = [ list(range(*submob_range)) for submob_range in get_neighbouring_pairs( [0, *it.accumulate(range_lens)] ) ] labelled_spans = self.labelled_spans start_items = [ (group_labels[0], 1), *( (curr_label, 1) if self.span_contains( labelled_spans[prev_label], labelled_spans[curr_label] ) else (prev_label, -1) for prev_label, curr_label in get_neighbouring_pairs( group_labels ) ) ] end_items = [ *( (curr_label, -1) if self.span_contains( labelled_spans[next_label], labelled_spans[curr_label] ) else (next_label, 1) for curr_label, next_label in get_neighbouring_pairs( group_labels ) ), (group_labels[-1], -1) ] group_substrs = [ re.sub(r"\s+", "", self.reconstruct_string( start_item, end_item, self.replace_for_matching, lambda label, flag, attr_dict: "" )) for start_item, end_item in zip(start_items, end_items) ] return list(zip(group_substrs, submob_indices_lists)) def get_submob_indices_lists_by_selector( self, selector: Selector ) -> list[list[int]]: return list(filter( lambda indices_list: indices_list, [ self.get_submob_indices_list_by_span(span) for span in self.find_spans_by_selector(selector) ] )) def build_parts_from_indices_lists( self, indices_lists: list[list[int]] ) -> VGroup: return VGroup(*( VGroup(*( self.submobjects[submob_index] for submob_index in indices_list )) for indices_list in indices_lists )) def build_groups(self) -> VGroup: return self.build_parts_from_indices_lists([ indices_list for _, indices_list in self.get_group_part_items() ]) def select_parts(self, selector: Selector) -> VGroup: specified_substrings = self.get_specified_substrings() if isinstance(selector, (str, re.Pattern)) and selector not in specified_substrings: return self.select_unisolated_substring(selector) indices_list = self.get_submob_indices_lists_by_selector(selector) return self.build_parts_from_indices_lists(indices_list) def __getitem__(self, value: int | slice | Selector) -> VMobject: if isinstance(value, (int, slice)): return super().__getitem__(value) return self.select_parts(value) def select_part(self, selector: Selector, index: int = 0) -> VMobject: return self.select_parts(selector)[index] def substr_to_path_count(self, substr: str) -> int: return len(re.sub(r"\s", "", substr)) def get_symbol_substrings(self): return list(re.sub(r"\s", "", self.string)) def select_unisolated_substring(self, pattern: str | re.Pattern) -> VGroup: if isinstance(pattern, str): pattern = re.compile(re.escape(pattern)) result = [] for match in re.finditer(pattern, self.string): index = match.start() start = self.substr_to_path_count(self.string[:index]) substr = match.group() end = start + self.substr_to_path_count(substr) result.append(self[start:end]) return VGroup(*result) def set_parts_color(self, selector: Selector, color: ManimColor): self.select_parts(selector).set_color(color) return self def set_parts_color_by_dict(self, color_map: dict[Selector, ManimColor]): for selector, color in color_map.items(): self.set_parts_color(selector, color) return self def get_string(self) -> str: return self.string
manim_3b1b/manimlib/mobject/svg/special_tex.py
from __future__ import annotations from manimlib.constants import MED_SMALL_BUFF, WHITE, GREY_C from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import FRAME_WIDTH from manimlib.constants import MED_LARGE_BUFF, SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.svg.tex_mobject import TexText from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 class BulletedList(VGroup): def __init__( self, *items: str, buff: float = MED_LARGE_BUFF, aligned_edge: Vect3 = LEFT, **kwargs ): labelled_content = [R"\item " + item for item in items] tex_string = "\n".join([ R"\begin{itemize}", *labelled_content, R"\end{itemize}" ]) tex_text = TexText(tex_string, isolate=labelled_content, **kwargs) lines = (tex_text.select_part(part) for part in labelled_content) super().__init__(*lines) self.arrange(DOWN, buff=buff, aligned_edge=aligned_edge) def fade_all_but(self, index: int, opacity: float = 0.25) -> None: for i, part in enumerate(self.submobjects): part.set_fill(opacity=(1.0 if i == index else opacity)) class TexTextFromPresetString(TexText): tex: str = "" default_color: ManimColor = WHITE def __init__(self, **kwargs): super().__init__( self.tex, color=kwargs.pop("color", self.default_color), **kwargs ) class Title(TexText): def __init__( self, *text_parts: str, font_size: int = 72, include_underline: bool = True, underline_width: float = FRAME_WIDTH - 2, # This will override underline_width match_underline_width_to_text: bool = False, underline_buff: float = SMALL_BUFF, underline_style: dict = dict(stroke_width=2, stroke_color=GREY_C), **kwargs ): super().__init__(*text_parts, font_size=font_size, **kwargs) self.to_edge(UP, buff=MED_SMALL_BUFF) if include_underline: underline = Line(LEFT, RIGHT, **underline_style) underline.next_to(self, DOWN, buff=underline_buff) if match_underline_width_to_text: underline.match_width(self) else: underline.set_width(underline_width) self.add(underline) self.underline = underline
manim_3b1b/manimlib/mobject/svg/tex_mobject.py
from __future__ import annotations import re from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.color import color_to_hex from manimlib.utils.color import hex_to_int from manimlib.utils.tex_file_writing import tex_content_to_svg_file from manimlib.utils.tex import num_tex_symbols from manimlib.logger import log from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Span, Selector SCALE_FACTOR_PER_FONT_POINT = 0.001 class Tex(StringMobject): tex_environment: str = "align*" def __init__( self, *tex_strings: str, font_size: int = 48, alignment: str = R"\centering", template: str = "", additional_preamble: str = "", tex_to_color_map: dict = dict(), t2c: dict = dict(), isolate: Selector = [], use_labelled_svg: bool = True, **kwargs ): # Combine multi-string arg, but mark them to isolate if len(tex_strings) > 1: if isinstance(isolate, (str, re.Pattern, tuple)): isolate = [isolate] isolate = [*isolate, *tex_strings] tex_string = (" ".join(tex_strings)).strip() # Prevent from passing an empty string. if not tex_string.strip(): tex_string = R"\\" self.tex_string = tex_string self.alignment = alignment self.template = template self.additional_preamble = additional_preamble self.tex_to_color_map = dict(**t2c, **tex_to_color_map) super().__init__( tex_string, use_labelled_svg=use_labelled_svg, isolate=isolate, **kwargs ) self.set_color_by_tex_to_color_map(self.tex_to_color_map) self.scale(SCALE_FACTOR_PER_FONT_POINT * font_size) @property def hash_seed(self) -> tuple: return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.base_color, self.isolate, self.protect, self.tex_string, self.alignment, self.tex_environment, self.tex_to_color_map, self.template, self.additional_preamble ) def get_file_path_by_content(self, content: str) -> str: return tex_content_to_svg_file( content, self.template, self.additional_preamble, self.tex_string ) # Parsing @staticmethod def get_command_matches(string: str) -> list[re.Match]: # Lump together adjacent brace pairs pattern = re.compile(r""" (?P<command>\\(?:[a-zA-Z]+|.)) |(?P<open>{+) |(?P<close>}+) """, flags=re.X | re.S) result = [] open_stack = [] for match_obj in pattern.finditer(string): if match_obj.group("open"): open_stack.append((match_obj.span(), len(result))) elif match_obj.group("close"): close_start, close_end = match_obj.span() while True: if not open_stack: raise ValueError("Missing '{' inserted") (open_start, open_end), index = open_stack.pop() n = min(open_end - open_start, close_end - close_start) result.insert(index, pattern.fullmatch( string, pos=open_end - n, endpos=open_end )) result.append(pattern.fullmatch( string, pos=close_start, endpos=close_start + n )) close_start += n if close_start < close_end: continue open_end -= n if open_start < open_end: open_stack.append(((open_start, open_end), index)) break else: result.append(match_obj) if open_stack: raise ValueError("Missing '}' inserted") return result @staticmethod def get_command_flag(match_obj: re.Match) -> int: if match_obj.group("open"): return 1 if match_obj.group("close"): return -1 return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: return match_obj.group() @staticmethod def replace_for_matching(match_obj: re.Match) -> str: if match_obj.group("command"): return match_obj.group() return "" @staticmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match ) -> dict[str, str] | None: if len(open_command.group()) >= 2: return {} return None def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [ (span, {}) for selector in self.tex_to_color_map for span in self.find_spans_by_selector(selector) ] @staticmethod def get_color_command(rgb_hex: str) -> str: rgb = hex_to_int(rgb_hex) rg, b = divmod(rgb, 256) r, g = divmod(rg, 256) return f"\\color[RGB]{{{r}, {g}, {b}}}" @staticmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: if label_hex is None: return "" if is_end: return "}}" return "{{" + Tex.get_color_command(label_hex) def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: prefix_lines = [] suffix_lines = [] if not is_labelled: prefix_lines.append(self.get_color_command( color_to_hex(self.base_color) )) if self.alignment: prefix_lines.append(self.alignment) if self.tex_environment: prefix_lines.append(f"\\begin{{{self.tex_environment}}}") suffix_lines.append(f"\\end{{{self.tex_environment}}}") return ( "".join([line + "\n" for line in prefix_lines]), "".join(["\n" + line for line in suffix_lines]) ) # Method alias def get_parts_by_tex(self, selector: Selector) -> VGroup: return self.select_parts(selector) def get_part_by_tex(self, selector: Selector, index: int = 0) -> VMobject: return self.select_part(selector, index) def set_color_by_tex(self, selector: Selector, color: ManimColor): return self.set_parts_color(selector, color) def set_color_by_tex_to_color_map( self, color_map: dict[Selector, ManimColor] ): return self.set_parts_color_by_dict(color_map) def get_tex(self) -> str: return self.get_string() # Specific to Tex def substr_to_path_count(self, substr: str) -> int: tex = self.get_tex() if len(self) != num_tex_symbols(tex): log.warning(f"Estimated size of {tex} does not match true size") return num_tex_symbols(substr) def get_symbol_substrings(self): pattern = "|".join(( # Tex commands r"\\[a-zA-Z]+", # And most single characters, with these exceptions r"[^\^\{\}\s\_\$\\\&]", )) return re.findall(pattern, self.string) def make_number_changable( self, value: float | int | str, index: int = 0, replace_all: bool = False, **config, ) -> VMobject: substr = str(value) parts = self.select_parts(substr) if len(parts) == 0: log.warning(f"{value} not found in Tex.make_number_changable call") return VMobject() if index > len(parts) - 1: log.warning(f"Requested {index}th occurance of {value}, but only {len(parts)} exist") return VMobject() if not replace_all: parts = [parts[index]] from manimlib.mobject.numbers import DecimalNumber decimal_mobs = [] for part in parts: if "." in substr: num_decimal_places = len(substr.split(".")[1]) else: num_decimal_places = 0 decimal_mob = DecimalNumber( float(value), num_decimal_places=num_decimal_places, **config, ) decimal_mob.replace(part) decimal_mob.match_style(part) if len(part) > 1: self.remove(*part[1:]) self.replace_submobject(self.submobjects.index(part[0]), decimal_mob) decimal_mobs.append(decimal_mob) # Replace substr with something that looks like a tex command. This # is to ensure Tex.substr_to_path_count counts it correctly. self.string = self.string.replace(substr, R"\decimalmob", 1) if replace_all: return VGroup(*decimal_mobs) return decimal_mobs[index] class TexText(Tex): tex_environment: str = ""
manim_3b1b/manimlib/mobject/types/surface.py
from __future__ import annotations import moderngl import numpy as np from manimlib.constants import GREY from manimlib.constants import OUT from manimlib.mobject.mobject import Mobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.images import get_full_raster_image_path from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.space_ops import normalize_along_axis from manimlib.utils.space_ops import cross from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, Tuple from manimlib.camera.camera import Camera from manimlib.typing import ManimColor, Vect3, Vect3Array, Self class Surface(Mobject): render_primitive: int = moderngl.TRIANGLES shader_folder: str = "surface" shader_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('normal', np.float32, (3,)), ('rgba', np.float32, (4,)), ]) def __init__( self, color: ManimColor = GREY, shading: Tuple[float, float, float] = (0.3, 0.2, 0.4), depth_test: bool = True, u_range: Tuple[float, float] = (0.0, 1.0), v_range: Tuple[float, float] = (0.0, 1.0), # Resolution counts number of points sampled, which for # each coordinate is one more than the the number of # rows/columns of approximating squares resolution: Tuple[int, int] = (101, 101), prefered_creation_axis: int = 1, # For du and dv steps. Much smaller and numerical error # can crop up in the shaders. epsilon: float = 1e-5, **kwargs ): self.u_range = u_range self.v_range = v_range self.resolution = resolution self.prefered_creation_axis = prefered_creation_axis self.epsilon = epsilon super().__init__( **kwargs, color=color, shading=shading, depth_test=depth_test, ) self.compute_triangle_indices() def init_uniforms(self): super().init_uniforms() self.uniforms["clip_plane"] = np.zeros(4) def uv_func(self, u: float, v: float) -> tuple[float, float, float]: # To be implemented in subclasses return (u, v, 0.0) @Mobject.affects_data def init_points(self): dim = self.dim nu, nv = self.resolution u_range = np.linspace(*self.u_range, nu) v_range = np.linspace(*self.v_range, nv) # Get three lists: # - Points generated by pure uv values # - Those generated by values nudged by du # - Those generated by values nudged by dv uv_grid = np.array([[[u, v] for v in v_range] for u in u_range]) uv_plus_du = uv_grid.copy() uv_plus_du[:, :, 0] += self.epsilon uv_plus_dv = uv_grid.copy() uv_plus_dv[:, :, 1] += self.epsilon points, du_points, dv_points = [ np.apply_along_axis( lambda p: self.uv_func(*p), 2, grid ).reshape((nu * nv, dim)) for grid in (uv_grid, uv_plus_du, uv_plus_dv) ] self.set_points(points) self.data["normal"] = normalize_along_axis(cross( (du_points - points) / self.epsilon, (dv_points - points) / self.epsilon, ), 1) def apply_points_function(self, *args, **kwargs) -> Self: super().apply_points_function(*args, **kwargs) self.get_unit_normals() return self def compute_triangle_indices(self) -> np.ndarray: # TODO, if there is an event which changes # the resolution of the surface, make sure # this is called. nu, nv = self.resolution if nu == 0 or nv == 0: self.triangle_indices = np.zeros(0, dtype=int) return self.triangle_indices index_grid = np.arange(nu * nv).reshape((nu, nv)) indices = np.zeros(6 * (nu - 1) * (nv - 1), dtype=int) indices[0::6] = index_grid[:-1, :-1].flatten() # Top left indices[1::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[2::6] = index_grid[:-1, +1:].flatten() # Top right indices[3::6] = index_grid[:-1, +1:].flatten() # Top right indices[4::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[5::6] = index_grid[+1:, +1:].flatten() # Bottom right self.triangle_indices = indices return self.triangle_indices def get_triangle_indices(self) -> np.ndarray: return self.triangle_indices def get_unit_normals(self) -> Vect3Array: nu, nv = self.resolution indices = np.arange(nu * nv) if len(indices) == 0: return np.zeros((3, 0)) left = indices - 1 right = indices + 1 up = indices - nv down = indices + nv left[0] = indices[0] right[-1] = indices[-1] up[:nv] = indices[:nv] down[-nv:] = indices[-nv:] points = self.get_points() crosses = cross( points[right] - points[left], points[up] - points[down], ) self.data["normal"] = normalize_along_axis(crosses, 1) return self.data["normal"] @Mobject.affects_data def pointwise_become_partial( self, smobject: "Surface", a: float, b: float, axis: int | None = None ) -> Self: assert(isinstance(smobject, Surface)) if axis is None: axis = self.prefered_creation_axis if a <= 0 and b >= 1: self.match_points(smobject) return self nu, nv = smobject.resolution self.data['point'][:] = self.get_partial_points_array( smobject.data['point'], a, b, (nu, nv, 3), axis=axis ) return self def get_partial_points_array( self, points: Vect3Array, a: float, b: float, resolution: Sequence[int], axis: int ) -> Vect3Array: if len(points) == 0: return points nu, nv = resolution[:2] points = points.reshape(resolution).copy() max_index = resolution[axis] - 1 lower_index, lower_residue = integer_interpolate(0, max_index, a) upper_index, upper_residue = integer_interpolate(0, max_index, b) if axis == 0: points[:lower_index] = interpolate( points[lower_index], points[lower_index + 1], lower_residue ) points[upper_index + 1:] = interpolate( points[upper_index], points[upper_index + 1], upper_residue ) else: shape = (nu, 1, resolution[2]) points[:, :lower_index] = interpolate( points[:, lower_index], points[:, lower_index + 1], lower_residue ).reshape(shape) points[:, upper_index + 1:] = interpolate( points[:, upper_index], points[:, upper_index + 1], upper_residue ).reshape(shape) return points.reshape((nu * nv, *resolution[2:])) @Mobject.affects_data def sort_faces_back_to_front(self, vect: Vect3 = OUT) -> Self: tri_is = self.triangle_indices points = self.get_points() dots = (points[tri_is[::3]] * vect).sum(1) indices = np.argsort(dots) for k in range(3): tri_is[k::3] = tri_is[k::3][indices] return self def always_sort_to_camera(self, camera: Camera) -> Self: def updater(surface: Surface): vect = camera.get_location() - surface.get_center() surface.sort_faces_back_to_front(vect) self.add_updater(updater) return self def set_clip_plane( self, vect: Vect3 | None = None, threshold: float | None = None ) -> Self: if vect is not None: self.uniforms["clip_plane"][:3] = vect if threshold is not None: self.uniforms["clip_plane"][3] = threshold return self def deactivate_clip_plane(self) -> Self: self.uniforms["clip_plane"][:] = 0 return self def get_shader_vert_indices(self) -> np.ndarray: return self.get_triangle_indices() class ParametricSurface(Surface): def __init__( self, uv_func: Callable[[float, float], Iterable[float]], u_range: tuple[float, float] = (0, 1), v_range: tuple[float, float] = (0, 1), **kwargs ): self.passed_uv_func = uv_func super().__init__(u_range=u_range, v_range=v_range, **kwargs) def uv_func(self, u, v): return self.passed_uv_func(u, v) class SGroup(Surface): def __init__( self, *parametric_surfaces: Surface, **kwargs ): super().__init__(resolution=(0, 0), **kwargs) self.add(*parametric_surfaces) def init_points(self): pass # Needed? class TexturedSurface(Surface): shader_folder: str = "textured_surface" shader_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('normal', np.float32, (3,)), ('im_coords', np.float32, (2,)), ('opacity', np.float32, (1,)), ] def __init__( self, uv_surface: Surface, image_file: str, dark_image_file: str | None = None, **kwargs ): if not isinstance(uv_surface, Surface): raise Exception("uv_surface must be of type Surface") # Set texture information if dark_image_file is None: dark_image_file = image_file self.num_textures = 1 else: self.num_textures = 2 texture_paths = { "LightTexture": get_full_raster_image_path(image_file), "DarkTexture": get_full_raster_image_path(dark_image_file), } self.uv_surface = uv_surface self.uv_func = uv_surface.uv_func self.u_range: Tuple[float, float] = uv_surface.u_range self.v_range: Tuple[float, float] = uv_surface.v_range self.resolution: Tuple[int, int] = uv_surface.resolution super().__init__( texture_paths=texture_paths, shading=tuple(uv_surface.shading), **kwargs ) @Mobject.affects_data def init_points(self): surf = self.uv_surface nu, nv = surf.resolution self.resize_points(surf.get_num_points()) self.resolution = surf.resolution self.data['point'][:] = surf.data['point'] self.data['normal'][:] = surf.data['normal'] self.data['opacity'][:, 0] = surf.data["rgba"][:, 3] self.data["im_coords"] = np.array([ [u, v] for u in np.linspace(0, 1, nu) for v in np.linspace(1, 0, nv) # Reverse y-direction ]) def init_uniforms(self): super().init_uniforms() self.uniforms["num_textures"] = self.num_textures @Mobject.affects_data def set_opacity(self, opacity: float | Iterable[float]) -> Self: op_arr = np.array(listify(opacity)) self.data["opacity"][:, 0] = resize_with_interpolation(op_arr, len(self.data)) return self def set_color( self, color: ManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float] | None = None, recurse: bool = True ) -> Self: if opacity is not None: self.set_opacity(opacity) return self def pointwise_become_partial( self, tsmobject: "TexturedSurface", a: float, b: float, axis: int = 1 ) -> Self: super().pointwise_become_partial(tsmobject, a, b, axis) im_coords = self.data["im_coords"] im_coords[:] = tsmobject.data["im_coords"] if a <= 0 and b >= 1: return self nu, nv = tsmobject.resolution im_coords[:] = self.get_partial_points_array( im_coords, a, b, (nu, nv, 2), axis ) return self
manim_3b1b/manimlib/mobject/types/__init__.py
manim_3b1b/manimlib/mobject/types/image_mobject.py
from __future__ import annotations import numpy as np from PIL import Image from manimlib.constants import DL, DR, UL, UR from manimlib.mobject.mobject import Mobject from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.images import get_full_raster_image_path from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Tuple from manimlib.typing import Vect3 class ImageMobject(Mobject): shader_folder: str = "image" shader_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('im_coords', np.float32, (2,)), ('opacity', np.float32, (1,)), ] def __init__( self, filename: str, height: float = 4.0, **kwargs ): self.height = height self.image_path = get_full_raster_image_path(filename) self.image = Image.open(self.image_path) super().__init__(texture_paths={"Texture": self.image_path}, **kwargs) def init_data(self) -> None: super().init_data(length=4) self.data["point"][:] = [UL, DL, UR, DR] self.data["im_coords"][:] = [(0, 0), (0, 1), (1, 0), (1, 1)] self.data["opacity"][:] = self.opacity def init_points(self) -> None: size = self.image.size self.set_width(2 * size[0] / size[1], stretch=True) self.set_height(self.height) @Mobject.affects_data def set_opacity(self, opacity: float, recurse: bool = True): self.data["opacity"][:, 0] = resize_with_interpolation( np.array(listify(opacity)), self.get_num_points() ) return self def set_color(self, color, opacity=None, recurse=None): return self def point_to_rgb(self, point: Vect3) -> Vect3: x0, y0 = self.get_corner(UL)[:2] x1, y1 = self.get_corner(DR)[:2] x_alpha = inverse_interpolate(x0, x1, point[0]) y_alpha = inverse_interpolate(y0, y1, point[1]) if not (0 <= x_alpha <= 1) and (0 <= y_alpha <= 1): # TODO, raise smarter exception raise Exception("Cannot sample color from outside an image") pw, ph = self.image.size rgb = self.image.getpixel(( int((pw - 1) * x_alpha), int((ph - 1) * y_alpha), )) return np.array(rgb) / 255
manim_3b1b/manimlib/mobject/types/vectorized_mobject.py
from __future__ import annotations from functools import wraps import moderngl import numpy as np from manimlib.constants import GREY_A, GREY_C, GREY_E from manimlib.constants import BLACK from manimlib.constants import DEFAULT_STROKE_WIDTH from manimlib.constants import DEGREES from manimlib.constants import JOINT_TYPE_MAP from manimlib.constants import ORIGIN, OUT from manimlib.constants import TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.mobject import Point from manimlib.utils.bezier import bezier from manimlib.utils.bezier import get_quadratic_approximation_of_cubic from manimlib.utils.bezier import approx_smooth_quadratic_bezier_handles from manimlib.utils.bezier import smooth_quadratic_path from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.bezier import find_intersection from manimlib.utils.bezier import outer_interpolate from manimlib.utils.bezier import partial_quadratic_bezier_points from manimlib.utils.bezier import quadratic_bezier_points_for_arc from manimlib.utils.color import color_gradient from manimlib.utils.color import rgb_to_hex from manimlib.utils.iterables import make_even from manimlib.utils.iterables import resize_array from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.iterables import resize_preserving_order from manimlib.utils.iterables import arrays_match from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import cross from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import earclip_triangulation from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import get_unit_normal from manimlib.utils.space_ops import line_intersects_path from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import normalize_along_axis from manimlib.utils.space_ops import rotation_between_vectors from manimlib.utils.space_ops import poly_line_length from manimlib.utils.space_ops import z_to_vector from manimlib.shader_wrapper import ShaderWrapper from manimlib.shader_wrapper import FillShaderWrapper from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Tuple, Any from manimlib.typing import ManimColor, Vect3, Vect4, Vect3Array, Vect4Array, Self from moderngl.context import Context DEFAULT_STROKE_COLOR = GREY_A DEFAULT_FILL_COLOR = GREY_C class VMobject(Mobject): fill_shader_folder: str = "quadratic_bezier_fill" stroke_shader_folder: str = "quadratic_bezier_stroke" shader_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('stroke_rgba', np.float32, (4,)), ('stroke_width', np.float32, (1,)), ('joint_product', np.float32, (4,)), ('fill_rgba', np.float32, (4,)), ('base_point', np.float32, (3,)), ('unit_normal', np.float32, (3,)), ('fill_border_width', np.float32, (1,)), ]) fill_data_names = ['point', 'fill_rgba', 'base_point', 'unit_normal'] stroke_data_names = ['point', 'stroke_rgba', 'stroke_width', 'joint_product'] fill_render_primitive: int = moderngl.TRIANGLES stroke_render_primitive: int = moderngl.TRIANGLES pre_function_handle_to_anchor_scale_factor: float = 0.01 make_smooth_after_applying_functions: bool = False # TODO, do we care about accounting for varying zoom levels? tolerance_for_point_equality: float = 1e-8 def __init__( self, color: ManimColor = None, # If set, this will override stroke_color and fill_color fill_color: ManimColor = None, fill_opacity: float | Iterable[float] | None = 0.0, stroke_color: ManimColor = None, stroke_opacity: float | Iterable[float] | None = 1.0, stroke_width: float | Iterable[float] | None = DEFAULT_STROKE_WIDTH, stroke_behind: bool = False, background_image_file: str | None = None, long_lines: bool = False, # Could also be "no_joint", "bevel", "miter" joint_type: str = "auto", flat_stroke: bool = True, use_simple_quadratic_approx: bool = False, # Measured in pixel widths anti_alias_width: float = 1.0, fill_border_width: float = 0.5, use_winding_fill: bool = True, **kwargs ): self.fill_color = fill_color or color or DEFAULT_FILL_COLOR self.fill_opacity = fill_opacity self.stroke_color = stroke_color or color or DEFAULT_STROKE_COLOR self.stroke_opacity = stroke_opacity self.stroke_width = stroke_width self.stroke_behind = stroke_behind self.background_image_file = background_image_file self.long_lines = long_lines self.joint_type = joint_type self.flat_stroke = flat_stroke self.use_simple_quadratic_approx = use_simple_quadratic_approx self.anti_alias_width = anti_alias_width self.fill_border_width = fill_border_width self._use_winding_fill = use_winding_fill self._has_fill = False self._has_stroke = False self.needs_new_triangulation = True self.triangulation = np.zeros(0, dtype='i4') self.needs_new_joint_products = True self.outer_vert_indices = np.zeros(0, dtype='i4') super().__init__(**kwargs) def get_group_class(self): return VGroup def init_uniforms(self): super().init_uniforms() self.uniforms["anti_alias_width"] = self.anti_alias_width self.uniforms["joint_type"] = JOINT_TYPE_MAP[self.joint_type] self.uniforms["flat_stroke"] = float(self.flat_stroke) def add(self, *vmobjects: VMobject) -> Self: if not all((isinstance(m, VMobject) for m in vmobjects)): raise Exception("All submobjects must be of type VMobject") return super().add(*vmobjects) # Colors def note_changed_fill(self) -> Self: for submob in self.get_family(): submob._has_fill = submob.has_fill() return self def note_changed_stroke(self) -> Self: for submob in self.get_family(): submob._has_stroke = submob.has_stroke() return self def init_colors(self): self.set_fill( color=self.fill_color, opacity=self.fill_opacity, border_width=self.fill_border_width, ) self.set_stroke( color=self.stroke_color, width=self.stroke_width, opacity=self.stroke_opacity, background=self.stroke_behind, ) self.set_shading(*self.shading) self.set_flat_stroke(self.flat_stroke) self.color = self.get_color() return self def set_rgba_array( self, rgba_array: Vect4Array, name: str = "stroke_rgba", recurse: bool = False ) -> Self: super().set_rgba_array(rgba_array, name, recurse) self.note_changed_fill() self.note_changed_stroke() return self def set_fill( self, color: ManimColor | Iterable[ManimColor] = None, opacity: float | Iterable[float] | None = None, border_width: float | None = None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color, opacity, 'fill_rgba', recurse) if border_width is not None: for mob in self.get_family(recurse): mob.data["fill_border_width"] = border_width self.note_changed_fill() return self def set_stroke( self, color: ManimColor | Iterable[ManimColor] = None, width: float | Iterable[float] | None = None, opacity: float | Iterable[float] | None = None, background: bool | None = None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color, opacity, 'stroke_rgba', recurse) if width is not None: for mob in self.get_family(recurse): data = mob.data if mob.get_num_points() > 0 else mob._data_defaults if isinstance(width, (float, int)): data['stroke_width'][:, 0] = width else: data['stroke_width'][:, 0] = resize_with_interpolation( np.array(width), len(data) ).flatten() if background is not None: for mob in self.get_family(recurse): mob.stroke_behind = background self.note_changed_stroke() return self def set_backstroke( self, color: ManimColor | Iterable[ManimColor] = BLACK, width: float | Iterable[float] = 3, background: bool = True ) -> Self: self.set_stroke(color, width, background=background) return self @Mobject.affects_family_data def set_style( self, fill_color: ManimColor | Iterable[ManimColor] | None = None, fill_opacity: float | Iterable[float] | None = None, fill_rgba: Vect4 | None = None, stroke_color: ManimColor | Iterable[ManimColor] | None = None, stroke_opacity: float | Iterable[float] | None = None, stroke_rgba: Vect4 | None = None, stroke_width: float | Iterable[float] | None = None, stroke_background: bool = False, shading: Tuple[float, float, float] | None = None, recurse: bool = True ) -> Self: for mob in self.get_family(recurse): if fill_rgba is not None: mob.data['fill_rgba'][:] = resize_with_interpolation(fill_rgba, len(mob.data['fill_rgba'])) else: mob.set_fill( color=fill_color, opacity=fill_opacity, recurse=False ) if stroke_rgba is not None: mob.data['stroke_rgba'][:] = resize_with_interpolation(stroke_rgba, len(mob.data['stroke_rgba'])) mob.set_stroke( width=stroke_width, background=stroke_background, recurse=False, ) else: mob.set_stroke( color=stroke_color, width=stroke_width, opacity=stroke_opacity, recurse=False, background=stroke_background, ) if shading is not None: mob.set_shading(*shading, recurse=False) self.note_changed_fill() self.note_changed_stroke() return self def get_style(self) -> dict[str, Any]: data = self.data if self.get_num_points() > 0 else self._data_defaults return { "fill_rgba": data['fill_rgba'].copy(), "stroke_rgba": data['stroke_rgba'].copy(), "stroke_width": data['stroke_width'].copy(), "stroke_background": self.stroke_behind, "shading": self.get_shading(), } def match_style(self, vmobject: VMobject, recurse: bool = True) -> Self: self.set_style(**vmobject.get_style(), recurse=False) if recurse: # Does its best to match up submobject lists, and # match styles accordingly submobs1, submobs2 = self.submobjects, vmobject.submobjects if len(submobs1) == 0: return self elif len(submobs2) == 0: submobs2 = [vmobject] for sm1, sm2 in zip(*make_even(submobs1, submobs2)): sm1.match_style(sm2) return self def set_color( self, color: ManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float] | None = None, recurse: bool = True ) -> Self: self.set_fill(color, opacity=opacity, recurse=recurse) self.set_stroke(color, opacity=opacity, recurse=recurse) return self def set_opacity( self, opacity: float | Iterable[float] | None, recurse: bool = True ) -> Self: self.set_fill(opacity=opacity, recurse=recurse) self.set_stroke(opacity=opacity, recurse=recurse) return self def set_anti_alias_width(self, anti_alias_width: float, recurse: bool = True) -> Self: self.set_uniform(recurse, anti_alias_width=anti_alias_width) return self def fade(self, darkness: float = 0.5, recurse: bool = True) -> Self: mobs = self.get_family() if recurse else [self] for mob in mobs: factor = 1.0 - darkness mob.set_fill( opacity=factor * mob.get_fill_opacity(), recurse=False, ) mob.set_stroke( opacity=factor * mob.get_stroke_opacity(), recurse=False, ) return self def get_fill_colors(self) -> list[str]: return [ rgb_to_hex(rgba[:3]) for rgba in self.data['fill_rgba'] ] def get_fill_opacities(self) -> np.ndarray: return self.data['fill_rgba'][:, 3] def get_stroke_colors(self) -> list[str]: return [ rgb_to_hex(rgba[:3]) for rgba in self.data['stroke_rgba'] ] def get_stroke_opacities(self) -> np.ndarray: return self.data['stroke_rgba'][:, 3] def get_stroke_widths(self) -> np.ndarray: return self.data['stroke_width'][:, 0] # TODO, it's weird for these to return the first of various lists # rather than the full information def get_fill_color(self) -> str: """ If there are multiple colors (for gradient) this returns the first one """ data = self.data if self.has_points() else self._data_defaults return rgb_to_hex(data["fill_rgba"][0, :3]) def get_fill_opacity(self) -> float: """ If there are multiple opacities, this returns the first """ data = self.data if self.has_points() else self._data_defaults return data["fill_rgba"][0, 3] def get_stroke_color(self) -> str: data = self.data if self.has_points() else self._data_defaults return rgb_to_hex(data["stroke_rgba"][0, :3]) def get_stroke_width(self) -> float: data = self.data if self.has_points() else self._data_defaults return data["stroke_width"][0, 0] def get_stroke_opacity(self) -> float: data = self.data if self.has_points() else self._data_defaults return data["stroke_rgba"][0, 3] def get_color(self) -> str: if self.has_fill(): return self.get_fill_color() return self.get_stroke_color() def get_anti_alias_width(self): return self.uniforms["anti_alias_width"] def has_stroke(self) -> bool: data = self.data if len(self.data) > 0 else self._data_defaults return any(data['stroke_width']) and any(data['stroke_rgba'][:, 3]) def has_fill(self) -> bool: data = self.data if len(self.data) > 0 else self._data_defaults return any(data['fill_rgba'][:, 3]) def get_opacity(self) -> float: if self.has_fill(): return self.get_fill_opacity() return self.get_stroke_opacity() def set_flat_stroke(self, flat_stroke: bool = True, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.uniforms["flat_stroke"] = float(flat_stroke) return self def get_flat_stroke(self) -> bool: return self.uniforms["flat_stroke"] == 1.0 def set_joint_type(self, joint_type: str, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.uniforms["joint_type"] = JOINT_TYPE_MAP[joint_type] return self def get_joint_type(self) -> float: return self.uniforms["joint_type"] def apply_depth_test( self, anti_alias_width: float = 0, fill_border_width: float = 0, recurse: bool = True ) -> Self: super().apply_depth_test(recurse) self.set_anti_alias_width(anti_alias_width) self.set_fill(border_width=fill_border_width) return self def deactivate_depth_test( self, anti_alias_width: float = 1.0, fill_border_width: float = 0.5, recurse: bool = True ) -> Self: super().deactivate_depth_test(recurse) self.set_anti_alias_width(anti_alias_width) self.set_fill(border_width=fill_border_width) return self @Mobject.affects_family_data def use_winding_fill(self, value: bool = True, recurse: bool = True) -> Self: for submob in self.get_family(recurse): submob._use_winding_fill = value if not value and submob.has_points(): submob.subdivide_intersections() return self # Points def set_anchors_and_handles( self, anchors: Vect3Array, handles: Vect3Array, ) -> Self: if len(anchors) == 0: self.clear_points() return self assert(len(anchors) == len(handles) + 1) points = resize_array(self.get_points(), 2 * len(anchors) - 1) points[0::2] = anchors points[1::2] = handles self.set_points(points) return self def start_new_path(self, point: Vect3) -> Self: # Path ends are signaled by a handle point sitting directly # on top of the previous anchor if self.has_points(): self.append_points([self.get_last_point(), point]) else: self.set_points([point]) return self def add_cubic_bezier_curve( self, anchor1: Vect3, handle1: Vect3, handle2: Vect3, anchor2: Vect3 ) -> Self: self.start_new_path(anchor1) self.add_cubic_bezier_curve_to(handle1, handle2, anchor2) return self def add_cubic_bezier_curve_to( self, handle1: Vect3, handle2: Vect3, anchor: Vect3, ) -> Self: """ Add cubic bezier curve to the path. """ self.throw_error_if_no_points() last = self.get_last_point() # Note, this assumes all points are on the xy-plane v1 = handle1 - last v2 = anchor - handle2 angle = angle_between_vectors(v1, v2) if self.use_simple_quadratic_approx and angle < 45 * DEGREES: quad_approx = [last, find_intersection(last, v1, anchor, -v2), anchor] else: quad_approx = get_quadratic_approximation_of_cubic( last, handle1, handle2, anchor ) if self.consider_points_equal(quad_approx[1], last): # This is to prevent subpaths from accidentally being marked closed quad_approx[1] = midpoint(*quad_approx[1:3]) self.append_points(quad_approx[1:]) return self def add_quadratic_bezier_curve_to(self, handle: Vect3, anchor: Vect3) -> Self: self.throw_error_if_no_points() last_point = self.get_last_point() if self.consider_points_equal(handle, last_point): # This is to prevent subpaths from accidentally being marked closed handle = midpoint(handle, anchor) self.append_points([handle, anchor]) return self def add_line_to(self, point: Vect3) -> Self: self.throw_error_if_no_points() last_point = self.get_last_point() alphas = np.linspace(0, 1, 5 if self.long_lines else 3) self.append_points(outer_interpolate(last_point, point, alphas[1:])) return self def add_smooth_curve_to(self, point: Vect3) -> Self: if self.has_new_path_started(): self.add_line_to(point) else: self.throw_error_if_no_points() new_handle = self.get_reflection_of_last_handle() self.add_quadratic_bezier_curve_to(new_handle, point) return self def add_smooth_cubic_curve_to(self, handle: Vect3, point: Vect3) -> Self: self.throw_error_if_no_points() if self.get_num_points() == 1: new_handle = handle else: new_handle = self.get_reflection_of_last_handle() self.add_cubic_bezier_curve_to(new_handle, handle, point) return self def add_arc_to(self, point: Vect3, angle: float, n_components: int | None = None, threshold: float = 1e-3) -> Self: self.throw_error_if_no_points() if abs(angle) < threshold: self.add_line_to(point) return self # Assign default value for n_components if n_components is None: n_components = int(np.ceil(8 * abs(angle) / TAU)) arc_points = quadratic_bezier_points_for_arc(angle, n_components) target_vect = point - self.get_end() curr_vect = arc_points[-1] - arc_points[0] arc_points = arc_points @ rotation_between_vectors(curr_vect, target_vect).T arc_points *= get_norm(target_vect) / get_norm(curr_vect) arc_points += (self.get_end() - arc_points[0]) self.append_points(arc_points[1:]) return self def has_new_path_started(self) -> bool: points = self.get_points() if len(points) == 0: return False elif len(points) == 1: return True return self.consider_points_equal(points[-3], points[-2]) def get_last_point(self) -> Vect3: return self.get_points()[-1] def get_reflection_of_last_handle(self) -> Vect3: points = self.get_points() return 2 * points[-1] - points[-2] def close_path(self, smooth: bool = False) -> Self: if self.is_closed(): return self last_path_start = self.get_subpaths()[-1][0] if smooth: self.add_smooth_curve_to(last_path_start) else: self.add_line_to(last_path_start) return self def is_closed(self) -> bool: points = self.get_points() return self.consider_points_equal(points[0], points[-1]) def subdivide_curves_by_condition( self, tuple_to_subdivisions: Callable, recurse: bool = True ) -> Self: for vmob in self.get_family(recurse): if not vmob.has_points(): continue new_points = [vmob.get_points()[0]] for tup in vmob.get_bezier_tuples(): n_divisions = tuple_to_subdivisions(*tup) if n_divisions > 0: alphas = np.linspace(0, 1, n_divisions + 2) new_points.extend([ partial_quadratic_bezier_points(tup, a1, a2)[1:] for a1, a2 in zip(alphas, alphas[1:]) ]) else: new_points.append(tup[1:]) vmob.set_points(np.vstack(new_points)) return self def subdivide_sharp_curves( self, angle_threshold: float = 30 * DEGREES, recurse: bool = True ) -> Self: def tuple_to_subdivisions(b0, b1, b2): angle = angle_between_vectors(b1 - b0, b2 - b1) return int(angle / angle_threshold) self.subdivide_curves_by_condition(tuple_to_subdivisions, recurse) return self def subdivide_intersections(self, recurse: bool = True, n_subdivisions: int = 1) -> Self: path = self.get_anchors() def tuple_to_subdivisions(b0, b1, b2): if line_intersects_path(b0, b1, path): return n_subdivisions return 0 self.subdivide_curves_by_condition(tuple_to_subdivisions, recurse) return self def add_points_as_corners(self, points: Iterable[Vect3]) -> Self: for point in points: self.add_line_to(point) return self def set_points_as_corners(self, points: Iterable[Vect3]) -> Self: anchors = np.array(points) handles = 0.5 * (anchors[:-1] + anchors[1:]) self.set_anchors_and_handles(anchors, handles) return self def set_points_smoothly( self, points: Iterable[Vect3], approx: bool = True ) -> Self: self.set_points_as_corners(points) self.make_smooth(approx=approx) return self def is_smooth(self) -> bool: dots = self.get_joint_products()[::2, 3] return bool((dots > 1 - 1e-3).all()) def change_anchor_mode(self, mode: str) -> Self: assert(mode in ("jagged", "approx_smooth", "true_smooth")) if self.get_num_points() == 0: return self subpaths = self.get_subpaths() self.clear_points() for subpath in subpaths: anchors = subpath[::2] new_subpath = np.array(subpath) if mode == "jagged": new_subpath[1::2] = 0.5 * (anchors[:-1] + anchors[1:]) elif mode == "approx_smooth": new_subpath[1::2] = approx_smooth_quadratic_bezier_handles(anchors) elif mode == "true_smooth": new_subpath = smooth_quadratic_path(anchors) # Shift any handles which ended up on top of # the previous anchor a0 = new_subpath[0:-1:2] h = new_subpath[1::2] a1 = new_subpath[2::2] false_ends = np.equal(a0, h).all(1) h[false_ends] = 0.5 * (a0[false_ends] + a1[false_ends]) self.add_subpath(new_subpath) return self def make_smooth(self, approx=False, recurse=True) -> Self: """ Edits the path so as to pass smoothly through all the current anchor points. If approx is False, this may increase the total number of points. """ mode = "approx_smooth" if approx else "true_smooth" for submob in self.get_family(recurse): if submob.is_smooth(): continue submob.change_anchor_mode(mode) return self def make_approximately_smooth(self, recurse=True) -> Self: self.make_smooth(approx=True, recurse=recurse) return self def make_jagged(self, recurse=True) -> Self: for submob in self.get_family(recurse): submob.change_anchor_mode("jagged") return self def add_subpath(self, points: Vect3Array) -> Self: assert(len(points) % 2 == 1 or len(points) == 0) if not self.has_points(): self.set_points(points) return self if not self.consider_points_equal(points[0], self.get_points()[-1]): self.start_new_path(points[0]) self.append_points(points[1:]) return self def append_vectorized_mobject(self, vmobject: VMobject) -> Self: self.add_subpath(vmobject.get_points()) n = vmobject.get_num_points() self.data[-n:] = vmobject.data return self # def consider_points_equal(self, p0: Vect3, p1: Vect3) -> bool: return get_norm(p1 - p0) < self.tolerance_for_point_equality # Information about the curve def get_bezier_tuples_from_points(self, points: Vect3Array) -> Iterable[Vect3Array]: n_curves = (len(points) - 1) // 2 return (points[2 * i : 2 * i + 3] for i in range(n_curves)) def get_bezier_tuples(self) -> Iterable[Vect3Array]: return self.get_bezier_tuples_from_points(self.get_points()) def get_subpath_end_indices_from_points(self, points: Vect3Array) -> np.ndarray: atol = self.tolerance_for_point_equality a0, h, a1 = points[0:-1:2], points[1::2], points[2::2] # An anchor point is considered the end of a path # if its following handle is sitting on top of it. # To disambiguate this from cases with many null # curves in a row, we also check that the following # anchor is genuinely distinct is_end = np.empty(len(points) // 2 + 1, dtype=bool) is_end[:-1] = (a0 == h).all(1) & (abs(h - a1) > atol).any(1) is_end[-1] = True # If the curve immediately after an end marker is also an # end marker, don't mark the second one is_end[:-1] = is_end[:-1] & ~is_end[1:] return np.array([2 * n for n, end in enumerate(is_end) if end]) def get_subpath_end_indices(self) -> np.ndarray: return self.get_subpath_end_indices_from_points(self.get_points()) def get_subpaths_from_points(self, points: Vect3Array) -> list[Vect3Array]: if len(points) == 0: return [] end_indices = self.get_subpath_end_indices_from_points(points) start_indices = [0, *(end_indices[:-1] + 2)] return [points[i1:i2 + 1] for i1, i2 in zip(start_indices, end_indices)] def get_subpaths(self) -> list[Vect3Array]: return self.get_subpaths_from_points(self.get_points()) def get_nth_curve_points(self, n: int) -> Vect3Array: assert n < self.get_num_curves() return self.get_points()[2 * n:2 * n + 3] def get_nth_curve_function(self, n: int) -> Callable[[float], Vect3]: return bezier(self.get_nth_curve_points(n)) def get_num_curves(self) -> int: return self.get_num_points() // 2 def quick_point_from_proportion(self, alpha: float) -> Vect3: # Assumes all curves have the same length, so is inaccurate num_curves = self.get_num_curves() n, residue = integer_interpolate(0, num_curves, alpha) curve_func = self.get_nth_curve_function(n) return curve_func(residue) def curve_and_prop_of_partial_point(self, alpha) -> Tuple[int, float]: """ If you want a point a proportion alpha along the curve, this gives you the index of the appropriate bezier curve, together with the proportion along that curve you'd need to travel """ if alpha == 0: return (0, 0.0) partials: list[float] = [0] for tup in self.get_bezier_tuples(): if self.consider_points_equal(tup[0], tup[1]): # Don't consider null curves arclen = 0 else: # Approximate length with straight line from start to end arclen = get_norm(tup[2] - tup[0]) partials.append(partials[-1] + arclen) full = partials[-1] if full == 0: return len(partials), 1.0 # First index where the partial length is more than alpha times the full length index = next( (i for i, x in enumerate(partials) if x >= full * alpha), len(partials) - 1 # Default ) residue = float(inverse_interpolate( partials[index - 1] / full, partials[index] / full, alpha )) return index - 1, residue def point_from_proportion(self, alpha: float) -> Vect3: if alpha <= 0: return self.get_start() elif alpha >= 1: return self.get_end() index, residue = self.curve_and_prop_of_partial_point(alpha) return self.get_nth_curve_function(index)(residue) def get_anchors_and_handles(self) -> list[Vect3]: """ returns anchors1, handles, anchors2, where (anchors1[i], handles[i], anchors2[i]) will be three points defining a quadratic bezier curve for any i in range(0, len(anchors1)) """ points = self.get_points() return [points[0:-1:2], points[1::2], points[2::2]] def get_start_anchors(self) -> Vect3Array: return self.get_points()[0:-1:2] def get_end_anchors(self) -> Vect3: return self.get_points()[2::2] def get_anchors(self) -> Vect3Array: return self.get_points()[::2] def get_points_without_null_curves(self, atol: float = 1e-9) -> Vect3Array: new_points = [self.get_points()[0]] for tup in self.get_bezier_tuples(): if get_norm(tup[1] - tup[0]) > atol or get_norm(tup[2] - tup[0]) > atol: new_points.append(tup[1:]) return np.vstack(new_points) def get_arc_length(self, n_sample_points: int | None = None) -> float: if n_sample_points is not None: points = np.array([ self.quick_point_from_proportion(a) for a in np.linspace(0, 1, n_sample_points) ]) return poly_line_length(points) points = self.get_points() inner_len = poly_line_length(points[::2]) outer_len = poly_line_length(points) return interpolate(inner_len, outer_len, 1 / 3) def get_area_vector(self) -> Vect3: # Returns a vector whose length is the area bound by # the polygon formed by the anchor points, pointing # in a direction perpendicular to the polygon according # to the right hand rule. if not self.has_points(): return np.zeros(3) p0 = self.get_anchors() p1 = np.vstack([p0[1:], p0[0]]) # Each term goes through all edges [(x0, y0, z0), (x1, y1, z1)] sums = p0 + p1 diffs = p1 - p0 return 0.5 * np.array([ (sums[:, 1] * diffs[:, 2]).sum(), # Add up (y0 + y1)*(z1 - z0) (sums[:, 2] * diffs[:, 0]).sum(), # Add up (z0 + z1)*(x1 - x0) (sums[:, 0] * diffs[:, 1]).sum(), # Add up (x0 + x1)*(y1 - y0) ]) def get_unit_normal(self) -> Vect3: if self.get_num_points() < 3: return OUT area_vect = self.get_area_vector() area = get_norm(area_vect) if area > 0: normal = area_vect / area else: points = self.get_points() normal = get_unit_normal( points[1] - points[0], points[2] - points[1], ) self.data["unit_normal"][:] = normal return normal def refresh_unit_normal(self) -> Self: self.get_unit_normal() return self def rotate( self, angle: float, axis: Vect3 = OUT, about_point: Vect3 | None = None, **kwargs ) -> Self: super().rotate(angle, axis, about_point, **kwargs) for mob in self.get_family(): mob.refresh_unit_normal() return self def ensure_positive_orientation(self, recurse=True) -> Self: for mob in self.get_family(recurse): if mob.get_unit_normal()[2] < 0: mob.reverse_points() return self # Alignment def align_points(self, vmobject: VMobject) -> Self: winding = self._use_winding_fill and vmobject._use_winding_fill if winding != self._use_winding_fill: self.use_winding_fill(winding) if winding != vmobject._use_winding_fill: vmobject.use_winding_fill(winding) if self.get_num_points() == len(vmobject.get_points()): # If both have fill, and they have the same shape, just # give them the same triangulation so that it's not recalculated # needlessly throughout an animation match_tris = not self._use_winding_fill and \ self.has_fill() and \ vmobject.has_fill() and \ self.has_same_shape_as(vmobject) if match_tris: vmobject.triangulation = self.triangulation for mob in [self, vmobject]: mob.get_joint_products() return self for mob in self, vmobject: # If there are no points, add one to # where the "center" is if not mob.has_points(): mob.start_new_path(mob.get_center()) # Figure out what the subpaths are, and align subpaths1 = self.get_subpaths() subpaths2 = vmobject.get_subpaths() for subpaths in [subpaths1, subpaths2]: subpaths.sort(key=lambda sp: -sum( get_norm(p2 - p1) for p1, p2 in zip(sp, sp[1:]) )) n_subpaths = max(len(subpaths1), len(subpaths2)) # Start building new ones new_subpaths1 = [] new_subpaths2 = [] def get_nth_subpath(path_list, n): if n >= len(path_list): return np.vstack([path_list[0][:-1], path_list[0][::-1]]) return path_list[n] for n in range(n_subpaths): sp1 = get_nth_subpath(subpaths1, n) sp2 = get_nth_subpath(subpaths2, n) diff1 = max(0, (len(sp2) - len(sp1)) // 2) diff2 = max(0, (len(sp1) - len(sp2)) // 2) sp1 = self.insert_n_curves_to_point_list(diff1, sp1) sp2 = self.insert_n_curves_to_point_list(diff2, sp2) if n > 0: # Add intermediate anchor to mark path end new_subpaths1.append(new_subpaths1[-1][-1]) new_subpaths2.append(new_subpaths2[-1][-1]) new_subpaths1.append(sp1) new_subpaths2.append(sp2) for mob, paths in [(self, new_subpaths1), (vmobject, new_subpaths2)]: new_points = np.vstack(paths) mob.resize_points(len(new_points), resize_func=resize_preserving_order) mob.set_points(new_points) mob.get_joint_products() return self def insert_n_curves(self, n: int, recurse: bool = True) -> Self: for mob in self.get_family(recurse): if mob.get_num_curves() > 0: new_points = mob.insert_n_curves_to_point_list(n, mob.get_points()) mob.set_points(new_points) return self def insert_n_curves_to_point_list(self, n: int, points: Vect3Array) -> Vect3Array: if len(points) == 1: return np.repeat(points, 2 * n + 1, 0) bezier_tuples = list(self.get_bezier_tuples_from_points(points)) atol = self.tolerance_for_point_equality norms = [ 0 if get_norm(tup[1] - tup[0]) < atol else get_norm(tup[2] - tup[0]) for tup in bezier_tuples ] # Calculate insertions per curve (ipc) ipc = np.zeros(len(bezier_tuples), dtype=int) for _ in range(n): index = np.argmax(norms) ipc[index] += 1 norms[index] *= ipc[index] / (ipc[index] + 1) new_points = [points[0]] for tup, n_inserts in zip(bezier_tuples, ipc): # What was once a single quadratic curve defined # by "tup" will now be broken into n_inserts + 1 # smaller quadratic curves alphas = np.linspace(0, 1, n_inserts + 2) for a1, a2 in zip(alphas, alphas[1:]): new_points.extend(partial_quadratic_bezier_points(tup, a1, a2)[1:]) return np.vstack(new_points) def interpolate( self, mobject1: VMobject, mobject2: VMobject, alpha: float, *args, **kwargs ) -> Self: super().interpolate(mobject1, mobject2, alpha, *args, **kwargs) self._has_stroke = mobject1._has_stroke or mobject2._has_stroke self._has_fill = mobject1._has_fill or mobject2._has_fill if self._has_fill and not self._use_winding_fill: tri1 = mobject1.get_triangulation() tri2 = mobject2.get_triangulation() if not arrays_match(tri1, tri2): self.refresh_triangulation() return self def pointwise_become_partial(self, vmobject: VMobject, a: float, b: float) -> Self: assert(isinstance(vmobject, VMobject)) vm_points = vmobject.get_points() self.data["joint_product"] = vmobject.data["joint_product"] if a <= 0 and b >= 1: self.set_points(vm_points, refresh_joints=False) return self num_curves = vmobject.get_num_curves() # Partial curve includes three portions: # - A start, which is some ending portion of an inner quadratic # - A middle section, which matches the curve exactly # - An end, which is the starting portion of a later inner quadratic lower_index, lower_residue = integer_interpolate(0, num_curves, a) upper_index, upper_residue = integer_interpolate(0, num_curves, b) i1 = 2 * lower_index i2 = 2 * lower_index + 3 i3 = 2 * upper_index i4 = 2 * upper_index + 3 new_points = vm_points.copy() if num_curves == 0: new_points[:] = 0 return self if lower_index == upper_index: tup = partial_quadratic_bezier_points(vm_points[i1:i2], lower_residue, upper_residue) new_points[:i1] = tup[0] new_points[i1:i4] = tup new_points[i4:] = tup[2] else: low_tup = partial_quadratic_bezier_points(vm_points[i1:i2], lower_residue, 1) high_tup = partial_quadratic_bezier_points(vm_points[i3:i4], 0, upper_residue) new_points[0:i1] = low_tup[0] new_points[i1:i2] = low_tup # Keep new_points i2:i3 as they are new_points[i3:i4] = high_tup new_points[i4:] = high_tup[2] self.data["joint_product"][:i1] = [0, 0, 0, 1] self.data["joint_product"][i4:] = [0, 0, 0, 1] self.set_points(new_points, refresh_joints=False) return self def get_subcurve(self, a: float, b: float) -> Self: vmob = self.copy() vmob.pointwise_become_partial(self, a, b) return vmob def resize_points( self, new_length: int, resize_func: Callable[[np.ndarray, int], np.ndarray] = resize_array ) -> Self: super().resize_points(new_length, resize_func) n_curves = self.get_num_curves() # Creates the pattern (0, 1, 2, 2, 3, 4, 4, 5, 6, ...) self.outer_vert_indices = (np.arange(1, 3 * n_curves + 1) * 2) // 3 return self def get_outer_vert_indices(self) -> np.ndarray: """ Returns the pattern (0, 1, 2, 2, 3, 4, 4, 5, 6, ...) """ return self.outer_vert_indices # Data for shaders that may need refreshing def refresh_triangulation(self) -> Self: for mob in self.get_family(): mob.needs_new_triangulation = True return self def get_triangulation(self) -> np.ndarray: # Figure out how to triangulate the interior to know # how to send the points as to the vertex shader. # First triangles come directly from the points if not self.needs_new_triangulation: return self.triangulation points = self.get_points() if len(points) <= 1: self.triangulation = np.zeros(0, dtype='i4') self.needs_new_triangulation = False return self.triangulation normal_vector = self.get_unit_normal() # Rotate points such that unit normal vector is OUT if not np.isclose(normal_vector, OUT).all(): points = np.dot(points, z_to_vector(normal_vector)) v01s = points[1::2] - points[0:-1:2] v12s = points[2::2] - points[1::2] curve_orientations = np.sign(cross2d(v01s, v12s)) concave_parts = curve_orientations < 0 # These are the vertices to which we'll apply a polygon triangulation indices = np.arange(len(points), dtype=int) inner_vert_indices = np.hstack([ indices[0::2], indices[1::2][concave_parts], ]) inner_vert_indices.sort() # Even indices correspond to anchors, and `end_indices // 2` # shows which anchors are considered end points end_indices = self.get_subpath_end_indices() counts = np.arange(1, len(inner_vert_indices) + 1) rings = counts[inner_vert_indices % 2 == 0][end_indices // 2] # Triangulate inner_verts = points[inner_vert_indices] inner_tri_indices = inner_vert_indices[ earclip_triangulation(inner_verts, rings) ] # Remove null triangles, coming from adjascent points iti = inner_tri_indices null1 = (iti[0::3] + 1 == iti[1::3]) & (iti[0::3] + 2 == iti[2::3]) null2 = (iti[0::3] - 1 == iti[1::3]) & (iti[0::3] - 2 == iti[2::3]) inner_tri_indices = iti[~(null1 | null2).repeat(3)] ovi = self.get_outer_vert_indices() tri_indices = np.hstack([ovi, inner_tri_indices]) self.triangulation = tri_indices self.needs_new_triangulation = False return tri_indices def refresh_joint_products(self) -> Self: for mob in self.get_family(): mob.needs_new_joint_products = True return self def get_joint_products(self, refresh: bool = False) -> np.ndarray: """ The 'joint product' is a 4-vector holding the cross and dot product between tangent vectors at a joint """ if not self.needs_new_joint_products and not refresh: return self.data["joint_product"] if "joint_product" in self.locked_data_keys: return self.data["joint_product"] self.needs_new_joint_products = False self._data_has_changed = True points = self.get_points() if(len(points) < 3): return self.data["joint_product"] # Find all the unit tangent vectors at each joint a0, h, a1 = points[0:-1:2], points[1::2], points[2::2] a0_to_h = h - a0 h_to_a1 = a1 - h vect_to_vert = np.zeros(points.shape) vect_from_vert = np.zeros(points.shape) vect_to_vert[1::2] = a0_to_h vect_to_vert[2::2] = h_to_a1 vect_from_vert[0:-1:2] = a0_to_h vect_from_vert[1::2] = h_to_a1 # Joint up closed loops, or mark unclosed paths as such ends = self.get_subpath_end_indices() starts = [0, *(e + 2 for e in ends[:-1])] for start, end in zip(starts, ends): if self.consider_points_equal(points[start], points[end]): vect_to_vert[start] = vect_from_vert[end - 1] vect_from_vert[end] = vect_to_vert[start + 1] else: vect_to_vert[start] = vect_from_vert[start] vect_from_vert[end] = vect_to_vert[end] # Compute dot and cross products cross( vect_to_vert, vect_from_vert, out=self.data["joint_product"][:, :3] ) self.data["joint_product"][:, 3] = (vect_to_vert * vect_from_vert).sum(1) return self.data["joint_product"] def lock_matching_data(self, vmobject1: VMobject, vmobject2: VMobject) -> Self: for mob in [self, vmobject1, vmobject2]: mob.get_joint_products() super().lock_matching_data(vmobject1, vmobject2) return self def triggers_refreshed_triangulation(func: Callable): @wraps(func) def wrapper(self, *args, refresh=True, **kwargs): func(self, *args, **kwargs) if refresh: self.refresh_triangulation() self.refresh_joint_products() return self return wrapper def set_points(self, points: Vect3Array, refresh_joints: bool = True) -> Self: assert(len(points) == 0 or len(points) % 2 == 1) super().set_points(points) self.refresh_triangulation() if refresh_joints: self.get_joint_products(refresh=True) self.get_unit_normal() return self @triggers_refreshed_triangulation def append_points(self, points: Vect3Array) -> Self: assert(len(points) % 2 == 0) super().append_points(points) return self @triggers_refreshed_triangulation def reverse_points(self, recurse: bool = True) -> Self: # This will reset which anchors are # considered path ends for mob in self.get_family(recurse): if not mob.has_points(): continue inner_ends = mob.get_subpath_end_indices()[:-1] mob.data["point"][inner_ends + 1] = mob.data["point"][inner_ends + 2] mob.data["unit_normal"] *= -1 super().reverse_points() return self @triggers_refreshed_triangulation def set_data(self, data: np.ndarray) -> Self: super().set_data(data) self.note_changed_fill() self.note_changed_stroke() return self # TODO, how to be smart about tangents here? @triggers_refreshed_triangulation def apply_function( self, function: Callable[[Vect3], Vect3], make_smooth: bool = False, **kwargs ) -> Self: super().apply_function(function, **kwargs) if self.make_smooth_after_applying_functions or make_smooth: self.make_smooth(approx=True) return self def apply_points_function(self, *args, **kwargs) -> Self: super().apply_points_function(*args, **kwargs) self.refresh_joint_products() return self def set_animating_status(self, is_animating: bool, recurse: bool = True): super().set_animating_status(is_animating, recurse) for submob in self.get_family(recurse): submob.get_joint_products(refresh=True) if not submob._use_winding_fill: submob.get_triangulation() return self # For shaders def init_shader_data(self, ctx: Context): dtype = self.shader_dtype fill_dtype, stroke_dtype = ( np.dtype([ (name, dtype[name].base, dtype[name].shape) for name in names ]) for names in [self.fill_data_names, self.stroke_data_names] ) fill_data = np.zeros(0, dtype=fill_dtype) stroke_data = np.zeros(0, dtype=stroke_dtype) self.fill_shader_wrapper = FillShaderWrapper( ctx=ctx, vert_data=fill_data, mobject_uniforms=self.uniforms, shader_folder=self.fill_shader_folder, render_primitive=self.fill_render_primitive, ) self.stroke_shader_wrapper = ShaderWrapper( ctx=ctx, vert_data=stroke_data, mobject_uniforms=self.uniforms, shader_folder=self.stroke_shader_folder, render_primitive=self.stroke_render_primitive, ) self.back_stroke_shader_wrapper = self.stroke_shader_wrapper.copy() self.shader_wrappers = [ self.back_stroke_shader_wrapper, self.fill_shader_wrapper, self.stroke_shader_wrapper, ] for sw in self.shader_wrappers: family = self.family_members_with_points() rep = family[0] if family else self for old, new in rep.shader_code_replacements.items(): sw.replace_code(old, new) def refresh_shader_wrapper_id(self) -> Self: if not self._shaders_initialized: return self for wrapper in self.shader_wrappers: wrapper.refresh_id() return self def get_shader_wrapper_list(self, ctx: Context) -> list[ShaderWrapper]: if not self._shaders_initialized: self.init_shader_data(ctx) self._shaders_initialized = True family = self.family_members_with_points() if not family: return [] fill_names = self.fill_data_names stroke_names = self.stroke_data_names fill_family = (sm for sm in family if sm._has_fill) stroke_family = (sm for sm in family if sm._has_stroke) # Build up fill data lists fill_datas = [] fill_indices = [] fill_border_datas = [] for submob in fill_family: indices = submob.get_outer_vert_indices() if submob._use_winding_fill: data = submob.data[fill_names] data["base_point"][:] = data["point"][0] fill_datas.append(data[indices]) else: fill_datas.append(submob.data[fill_names]) fill_indices.append(submob.get_triangulation()) if (not submob._has_stroke) or submob.stroke_behind: # Add fill border submob.get_joint_products() names = list(stroke_names) names[names.index('stroke_rgba')] = 'fill_rgba' names[names.index('stroke_width')] = 'fill_border_width' border_stroke_data = submob.data[names].astype( self.stroke_shader_wrapper.vert_data.dtype ) fill_border_datas.append(border_stroke_data[indices]) # Build up stroke data lists stroke_datas = [] back_stroke_datas = [] for submob in stroke_family: submob.get_joint_products() indices = submob.get_outer_vert_indices() if submob.stroke_behind: back_stroke_datas.append(submob.data[stroke_names][indices]) else: stroke_datas.append(submob.data[stroke_names][indices]) shader_wrappers = [ self.back_stroke_shader_wrapper.read_in([*back_stroke_datas, *fill_border_datas]), self.fill_shader_wrapper.read_in(fill_datas, fill_indices or None), self.stroke_shader_wrapper.read_in(stroke_datas), ] for sw in shader_wrappers: rep = family[0] # Representative family member sw.bind_to_mobject_uniforms(rep.get_uniforms()) sw.depth_test = rep.depth_test return [sw for sw in shader_wrappers if len(sw.vert_data) > 0] class VGroup(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): super().__init__(**kwargs) self.add(*vmobjects) if vmobjects: self.uniforms.update(vmobjects[0].uniforms) def __add__(self, other: VMobject) -> Self: assert(isinstance(other, VMobject)) return self.add(other) class VectorizedPoint(Point, VMobject): def __init__( self, location: np.ndarray = ORIGIN, color: ManimColor = BLACK, fill_opacity: float = 0.0, stroke_width: float = 0.0, **kwargs ): Point.__init__(self, location, **kwargs) VMobject.__init__( self, color=color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) self.set_points(np.array([location])) class CurvesAsSubmobjects(VGroup): def __init__(self, vmobject: VMobject, **kwargs): super().__init__(**kwargs) for tup in vmobject.get_bezier_tuples(): part = VMobject() part.set_points(tup) part.match_style(vmobject) self.add(part) class DashedVMobject(VMobject): def __init__( self, vmobject: VMobject, num_dashes: int = 15, positive_space_ratio: float = 0.5, **kwargs ): super().__init__(**kwargs) if num_dashes > 0: # End points of the unit interval for division alphas = np.linspace(0, 1, num_dashes + 1) # This determines the length of each "dash" full_d_alpha = (1.0 / num_dashes) partial_d_alpha = full_d_alpha * positive_space_ratio # Rescale so that the last point of vmobject will # be the end of the last dash alphas /= (1 - full_d_alpha + partial_d_alpha) self.add(*[ vmobject.get_subcurve(alpha, alpha + partial_d_alpha) for alpha in alphas[:-1] ]) # Family is already taken care of by get_subcurve # implementation self.match_style(vmobject, recurse=False) class VHighlight(VGroup): def __init__( self, vmobject: VMobject, n_layers: int = 5, color_bounds: Tuple[ManimColor] = (GREY_C, GREY_E), max_stroke_addition: float = 5.0, ): outline = vmobject.replicate(n_layers) outline.set_fill(opacity=0) added_widths = np.linspace(0, max_stroke_addition, n_layers + 1)[1:] colors = color_gradient(color_bounds, n_layers) for part, added_width, color in zip(reversed(outline), added_widths, colors): for sm in part.family_members_with_points(): sm.set_stroke( width=sm.get_stroke_width() + added_width, color=color, ) super().__init__(*outline)
manim_3b1b/manimlib/mobject/types/dot_cloud.py
from __future__ import annotations import moderngl import numpy as np from manimlib.constants import GREY_C, YELLOW from manimlib.constants import ORIGIN, NULL_POINTS from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.point_cloud_mobject import PMobject from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy.typing as npt from typing import Sequence, Tuple from manimlib.typing import ManimColor, Vect3, Vect3Array, Self DEFAULT_DOT_RADIUS = 0.05 DEFAULT_GLOW_DOT_RADIUS = 0.2 DEFAULT_GRID_HEIGHT = 6 DEFAULT_BUFF_RATIO = 0.5 class DotCloud(PMobject): shader_folder: str = "true_dot" render_primitive: int = moderngl.POINTS shader_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('radius', np.float32, (1,)), ('rgba', np.float32, (4,)), ] def __init__( self, points: Vect3Array = NULL_POINTS, color: ManimColor = GREY_C, opacity: float = 1.0, radius: float = DEFAULT_DOT_RADIUS, glow_factor: float = 0.0, anti_alias_width: float = 2.0, **kwargs ): self.radius = radius self.glow_factor = glow_factor self.anti_alias_width = anti_alias_width super().__init__( color=color, opacity=opacity, **kwargs ) self.set_radius(self.radius) if points is not None: self.set_points(points) def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["glow_factor"] = self.glow_factor self.uniforms["anti_alias_width"] = self.anti_alias_width def to_grid( self, n_rows: int, n_cols: int, n_layers: int = 1, buff_ratio: float | None = None, h_buff_ratio: float = 1.0, v_buff_ratio: float = 1.0, d_buff_ratio: float = 1.0, height: float = DEFAULT_GRID_HEIGHT, ) -> Self: n_points = n_rows * n_cols * n_layers points = np.repeat(range(n_points), 3, axis=0).reshape((n_points, 3)) points[:, 0] = points[:, 0] % n_cols points[:, 1] = (points[:, 1] // n_cols) % n_rows points[:, 2] = points[:, 2] // (n_rows * n_cols) self.set_points(points.astype(float)) if buff_ratio is not None: v_buff_ratio = buff_ratio h_buff_ratio = buff_ratio d_buff_ratio = buff_ratio radius = self.get_radius() ns = [n_cols, n_rows, n_layers] brs = [h_buff_ratio, v_buff_ratio, d_buff_ratio] self.set_radius(0) for n, br, dim in zip(ns, brs, range(3)): self.rescale_to_fit(2 * radius * (1 + br) * (n - 1), dim, stretch=True) self.set_radius(radius) if height is not None: self.set_height(height) self.center() return self @Mobject.affects_data def set_radii(self, radii: npt.ArrayLike) -> Self: n_points = self.get_num_points() radii = np.array(radii).reshape((len(radii), 1)) self.data["radius"][:] = resize_with_interpolation(radii, n_points) self.refresh_bounding_box() return self def get_radii(self) -> np.ndarray: return self.data["radius"] @Mobject.affects_data def set_radius(self, radius: float) -> Self: data = self.data if self.get_num_points() > 0 else self._data_defaults data["radius"][:] = radius self.refresh_bounding_box() return self def get_radius(self) -> float: return self.get_radii().max() def scale_radii(self, scale_factor: float) -> Self: self.set_radius(scale_factor * self.get_radii()) return self def set_glow_factor(self, glow_factor: float) -> Self: self.uniforms["glow_factor"] = glow_factor return self def get_glow_factor(self) -> float: return self.uniforms["glow_factor"] def compute_bounding_box(self) -> Vect3Array: bb = super().compute_bounding_box() radius = self.get_radius() bb[0] += np.full((3,), -radius) bb[2] += np.full((3,), radius) return bb def scale( self, scale_factor: float | npt.ArrayLike, scale_radii: bool = True, **kwargs ) -> Self: super().scale(scale_factor, **kwargs) if scale_radii: self.set_radii(scale_factor * self.get_radii()) return self def make_3d( self, reflectiveness: float = 0.5, gloss: float = 0.1, shadow: float = 0.2 ) -> Self: self.set_shading(reflectiveness, gloss, shadow) self.apply_depth_test() return self class TrueDot(DotCloud): def __init__(self, center: Vect3 = ORIGIN, **kwargs): super().__init__(points=np.array([center]), **kwargs) class GlowDots(DotCloud): def __init__( self, points: Vect3Array = NULL_POINTS, color: ManimColor = YELLOW, radius: float = DEFAULT_GLOW_DOT_RADIUS, glow_factor: float = 2.0, **kwargs, ): super().__init__( points, color=color, radius=radius, glow_factor=glow_factor, **kwargs, ) class GlowDot(GlowDots): def __init__(self, center: Vect3 = ORIGIN, **kwargs): super().__init__(points=np.array([center]), **kwargs)
manim_3b1b/manimlib/mobject/types/point_cloud_mobject.py
from __future__ import annotations import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.utils.color import color_gradient from manimlib.utils.color import color_to_rgba from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor, Vect3, Vect3Array, Vect4Array, Self class PMobject(Mobject): def set_points(self, points: Vect3Array): if len(points) == 0: points = np.zeros((0, 3)) super().set_points(points) self.resize_points(len(points)) return self def add_points( self, points: Vect3Array, rgbas: Vect4Array | None = None, color: ManimColor | None = None, opacity: float | None = None ) -> Self: """ points must be a Nx3 numpy array, as must rgbas if it is not None """ self.append_points(points) # rgbas array will have been resized with points if color is not None: if opacity is None: opacity = self.data["rgba"][-1, 3] rgbas = np.repeat( [color_to_rgba(color, opacity)], len(points), axis=0 ) if rgbas is not None: self.data["rgba"][-len(rgbas):] = rgbas return self def add_point(self, point: Vect3, rgba=None, color=None, opacity=None) -> Self: rgbas = None if rgba is None else [rgba] self.add_points([point], rgbas, color, opacity) return self @Mobject.affects_data def set_color_by_gradient(self, *colors: ManimColor) -> Self: self.data["rgba"][:] = np.array(list(map( color_to_rgba, color_gradient(colors, self.get_num_points()) ))) return self @Mobject.affects_data def match_colors(self, pmobject: PMobject) -> Self: self.data["rgba"][:] = resize_with_interpolation( pmobject.data["rgba"], self.get_num_points() ) return self @Mobject.affects_data def filter_out(self, condition: Callable[[np.ndarray], bool]) -> Self: for mob in self.family_members_with_points(): mob.data = mob.data[~np.apply_along_axis(condition, 1, mob.get_points())] return self @Mobject.affects_data def sort_points(self, function: Callable[[Vect3], None] = lambda p: p[0]) -> Self: """ function is any map from R^3 to R """ for mob in self.family_members_with_points(): indices = np.argsort( np.apply_along_axis(function, 1, mob.get_points()) ) mob.data[:] = mob.data[indices] return self @Mobject.affects_data def ingest_submobjects(self) -> Self: self.data = np.vstack([ sm.data for sm in self.get_family() ]) return self def point_from_proportion(self, alpha: float) -> np.ndarray: index = alpha * (self.get_num_points() - 1) return self.get_points()[int(index)] @Mobject.affects_data def pointwise_become_partial(self, pmobject: PMobject, a: float, b: float) -> Self: lower_index = int(a * pmobject.get_num_points()) upper_index = int(b * pmobject.get_num_points()) self.data = pmobject.data[lower_index:upper_index].copy() return self class PGroup(PMobject): def __init__(self, *pmobs: PMobject, **kwargs): if not all([isinstance(m, PMobject) for m in pmobs]): raise Exception("All submobjects must be of type PMobject") super().__init__(**kwargs) self.add(*pmobs)
manim_3b1b/manimlib/utils/directories.py
from __future__ import annotations import os from manimlib.utils.customization import get_customization from manimlib.utils.file_ops import guarantee_existence def get_directories() -> dict[str, str]: return get_customization()["directories"] def get_temp_dir() -> str: return get_directories()["temporary_storage"] def get_tex_dir() -> str: return guarantee_existence(os.path.join(get_temp_dir(), "Tex")) def get_text_dir() -> str: return guarantee_existence(os.path.join(get_temp_dir(), "Text")) def get_mobject_data_dir() -> str: return guarantee_existence(os.path.join(get_temp_dir(), "mobject_data")) def get_downloads_dir() -> str: return guarantee_existence(os.path.join(get_temp_dir(), "manim_downloads")) def get_output_dir() -> str: return guarantee_existence(get_directories()["output"]) def get_raster_image_dir() -> str: return get_directories()["raster_images"] def get_vector_image_dir() -> str: return get_directories()["vector_images"] def get_sound_dir() -> str: return get_directories()["sounds"] def get_shader_dir() -> str: return get_directories()["shaders"]
manim_3b1b/manimlib/utils/debug.py
from __future__ import annotations from manimlib.constants import BLACK from manimlib.logger import log from manimlib.mobject.numbers import Integer from manimlib.mobject.types.vectorized_mobject import VGroup from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.mobject.mobject import Mobject def print_family(mobject: Mobject, n_tabs: int = 0) -> None: """For debugging purposes""" log.debug("\t" * n_tabs + str(mobject) + " " + str(id(mobject))) for submob in mobject.submobjects: print_family(submob, n_tabs + 1) def index_labels( mobject: Mobject, label_height: float = 0.15 ) -> VGroup: labels = VGroup() for n, submob in enumerate(mobject): label = Integer(n) label.set_height(label_height) label.move_to(submob) label.set_stroke(BLACK, 5, background=True) labels.add(label) return labels
manim_3b1b/manimlib/utils/init_config.py
from __future__ import annotations import importlib import inspect import os import yaml from rich import box from rich.console import Console from rich.prompt import Confirm from rich.prompt import Prompt from rich.rule import Rule from rich.table import Table from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any def get_manim_dir() -> str: manimlib_module = importlib.import_module("manimlib") manimlib_dir = os.path.dirname(inspect.getabsfile(manimlib_module)) return os.path.abspath(os.path.join(manimlib_dir, "..")) def remove_empty_value(dictionary: dict[str, Any]) -> None: for key in list(dictionary.keys()): if dictionary[key] == "": dictionary.pop(key) elif isinstance(dictionary[key], dict): remove_empty_value(dictionary[key]) def init_customization() -> None: configuration = { "directories": { "mirror_module_path": False, "output": "", "raster_images": "", "vector_images": "", "sounds": "", "temporary_storage": "", }, "universal_import_line": "from manimlib import *", "style": { "tex_template": "", "font": "Consolas", "background_color": "", }, "window_position": "UR", "window_monitor": 0, "full_screen": False, "break_into_partial_movies": False, "camera_resolutions": { "low": "854x480", "medium": "1280x720", "high": "1920x1080", "4k": "3840x2160", "default_resolution": "", }, "fps": 30, } console = Console() console.print(Rule("[bold]Configuration Guide[/bold]")) # print("Initialize configuration") try: scope = Prompt.ask( " Select the scope of the configuration", choices=["global", "local"], default="local" ) console.print("[bold]Directories:[/bold]") dir_config = configuration["directories"] dir_config["output"] = Prompt.ask( " Where should manim [bold]output[/bold] video and image files place [prompt.default](optional, default is none)", default="", show_default=False ) dir_config["raster_images"] = Prompt.ask( " Which folder should manim find [bold]raster images[/bold] (.jpg .png .gif) in " + \ "[prompt.default](optional, default is none)", default="", show_default=False ) dir_config["vector_images"] = Prompt.ask( " Which folder should manim find [bold]vector images[/bold] (.svg .xdv) in " + \ "[prompt.default](optional, default is none)", default="", show_default=False ) dir_config["sounds"] = Prompt.ask( " Which folder should manim find [bold]sound files[/bold] (.mp3 .wav) in " + \ "[prompt.default](optional, default is none)", default="", show_default=False ) dir_config["temporary_storage"] = Prompt.ask( " Which folder should manim storage [bold]temporary files[/bold] " + \ "[prompt.default](recommended, use system temporary folder by default)", default="", show_default=False ) console.print("[bold]Styles:[/bold]") style_config = configuration["style"] tex_template = Prompt.ask( " Select a TeX template to compile a LaTeX source file", default="default" ) style_config["tex_template"] = tex_template style_config["background_color"] = Prompt.ask( " Which [bold]background color[/bold] do you want [italic](hex code)", default="#333333" ) console.print("[bold]Camera qualities:[/bold]") table = Table( "low", "medium", "high", "ultra_high", title="Four defined qualities", box=box.ROUNDED ) table.add_row("480p15", "720p30", "1080p60", "2160p60") console.print(table) configuration["camera_resolutions"]["default_resolution"] = Prompt.ask( " Which one to choose as the default rendering quality", choices=["low", "medium", "high", "ultra_high"], default="high" ) write_to_file = Confirm.ask( "\n[bold]Are you sure to write these configs to file?[/bold]", default=True ) if not write_to_file: raise KeyboardInterrupt global_file_name = os.path.join(get_manim_dir(), "manimlib", "default_config.yml") if scope == "global": file_name = global_file_name else: if os.path.exists(global_file_name): remove_empty_value(configuration) file_name = os.path.join(os.getcwd(), "custom_config.yml") with open(file_name, "w", encoding="utf-8") as f: yaml.dump(configuration, f) console.print(f"\n:rocket: You have successfully set up a {scope} configuration file!") console.print(f"You can manually modify it in: [cyan]`{file_name}`[/cyan]") except KeyboardInterrupt: console.print("\n[green]Exit configuration guide[/green]")
manim_3b1b/manimlib/utils/tex.py
from __future__ import annotations import re from manimlib.utils.tex_to_symbol_count import TEX_TO_SYMBOL_COUNT def num_tex_symbols(tex: str) -> int: """ This function attempts to estimate the number of symbols that a given string of tex would produce. Warning, it may not behave perfectly """ # First, remove patterns like \begin{align}, \phantom{thing}, # \begin{array}{cc}, etc. pattern = "|".join( rf"(\\{s})" + r"(\{\w+\})?(\{\w+\})?(\[\w+\])?" for s in ["begin", "end", "phantom"] ) tex = re.sub(pattern, "", tex) # Progressively count the symbols associated with certain tex commands, # and remove those commands from the string, adding the number of symbols # that command creates total = 0 # Start with the special case \sqrt[number] for substr in re.findall(r"\\sqrt\[[0-9]+\]", tex): total += len(substr) - 5 # e.g. \sqrt[3] is 3 symbols tex = tex.replace(substr, " ") general_command = r"\\[a-zA-Z!,-/:;<>]+" for substr in re.findall(general_command, tex): total += TEX_TO_SYMBOL_COUNT.get(substr, 1) tex = tex.replace(substr, " ") # Count remaining characters total += sum(map(lambda c: c not in "^{} \n\t_$\\&", tex)) return total
manim_3b1b/manimlib/utils/tex_file_writing.py
from __future__ import annotations from contextlib import contextmanager import os import re import yaml from manimlib.config import get_custom_config from manimlib.config import get_manim_dir from manimlib.logger import log from manimlib.utils.directories import get_tex_dir from manimlib.utils.simple_functions import hash_string SAVED_TEX_CONFIG = {} def get_tex_template_config(template_name: str) -> dict[str, str]: name = template_name.replace(" ", "_").lower() with open(os.path.join( get_manim_dir(), "manimlib", "tex_templates.yml" ), encoding="utf-8") as tex_templates_file: templates_dict = yaml.safe_load(tex_templates_file) if name not in templates_dict: log.warning( "Cannot recognize template '%s', falling back to 'default'.", name ) name = "default" return templates_dict[name] def get_tex_config() -> dict[str, str]: """ Returns a dict which should look something like this: { "template": "default", "compiler": "latex", "preamble": "..." } """ # Only load once, then save thereafter if not SAVED_TEX_CONFIG: template_name = get_custom_config()["style"]["tex_template"] template_config = get_tex_template_config(template_name) SAVED_TEX_CONFIG.update({ "template": template_name, "compiler": template_config["compiler"], "preamble": template_config["preamble"] }) return SAVED_TEX_CONFIG def tex_content_to_svg_file( content: str, template: str, additional_preamble: str, short_tex: str ) -> str: tex_config = get_tex_config() if not template or template == tex_config["template"]: compiler = tex_config["compiler"] preamble = tex_config["preamble"] else: config = get_tex_template_config(template) compiler = config["compiler"] preamble = config["preamble"] if additional_preamble: preamble += "\n" + additional_preamble full_tex = "\n\n".join(( "\\documentclass[preview]{standalone}", preamble, "\\begin{document}", content, "\\end{document}" )) + "\n" svg_file = os.path.join( get_tex_dir(), hash_string(full_tex) + ".svg" ) if not os.path.exists(svg_file): # If svg doesn't exist, create it with display_during_execution("Writing " + short_tex): create_tex_svg(full_tex, svg_file, compiler) return svg_file def create_tex_svg(full_tex: str, svg_file: str, compiler: str) -> None: if compiler == "latex": program = "latex" dvi_ext = ".dvi" elif compiler == "xelatex": program = "xelatex -no-pdf" dvi_ext = ".xdv" else: raise NotImplementedError( f"Compiler '{compiler}' is not implemented" ) # Write tex file root, _ = os.path.splitext(svg_file) with open(root + ".tex", "w", encoding="utf-8") as tex_file: tex_file.write(full_tex) # tex to dvi if os.system(" ".join(( program, "-interaction=batchmode", "-halt-on-error", f"-output-directory=\"{os.path.dirname(svg_file)}\"", f"\"{root}.tex\"", ">", os.devnull ))): log.error( "LaTeX Error! Not a worry, it happens to the best of us." ) error_str = "" with open(root + ".log", "r", encoding="utf-8") as log_file: error_match_obj = re.search(r"(?<=\n! ).*\n.*\n", log_file.read()) if error_match_obj: error_str = error_match_obj.group() log.debug( f"The error could be:\n`{error_str}`", ) raise LatexError(error_str) # dvi to svg os.system(" ".join(( "dvisvgm", f"\"{root}{dvi_ext}\"", "-n", "-v", "0", "-o", f"\"{svg_file}\"", ">", os.devnull ))) # Cleanup superfluous documents for ext in (".tex", dvi_ext, ".log", ".aux"): try: os.remove(root + ext) except FileNotFoundError: pass # TODO, perhaps this should live elsewhere @contextmanager def display_during_execution(message: str): # Merge into a single line to_print = message.replace("\n", " ") max_characters = os.get_terminal_size().columns - 1 if len(to_print) > max_characters: to_print = to_print[:max_characters - 3] + "..." try: print(to_print, end="\r") yield finally: print(" " * len(to_print), end="\r") class LatexError(Exception): pass
manim_3b1b/manimlib/utils/customization.py
import os import tempfile from manimlib.config import get_custom_config from manimlib.config import get_manim_dir CUSTOMIZATION = {} def get_customization(): if not CUSTOMIZATION: CUSTOMIZATION.update(get_custom_config()) directories = CUSTOMIZATION["directories"] # Unless user has specified otherwise, use the system default temp # directory for storing tex files, mobject_data, etc. if not directories["temporary_storage"]: directories["temporary_storage"] = tempfile.gettempdir() # Assumes all shaders are written into manimlib/shaders directories["shaders"] = os.path.join( get_manim_dir(), "manimlib", "shaders" ) return CUSTOMIZATION
manim_3b1b/manimlib/utils/__init__.py
manim_3b1b/manimlib/utils/iterables.py
from __future__ import annotations from colour import Color import numpy as np from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, TypeVar T = TypeVar("T") S = TypeVar("S") def remove_list_redundancies(lst: Sequence[T]) -> list[T]: """ Used instead of list(set(l)) to maintain order Keeps the last occurrence of each element """ return list(reversed(dict.fromkeys(reversed(lst)))) def list_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]: """ Used instead of list(set(l1).update(l2)) to maintain order, making sure duplicates are removed from l1, not l2. """ return remove_list_redundancies([*l1, *l2]) def list_difference_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]: return [e for e in l1 if e not in l2] def adjacent_n_tuples(objects: Sequence[T], n: int) -> zip[tuple[T, ...]]: return zip(*[ [*objects[k:], *objects[:k]] for k in range(n) ]) def adjacent_pairs(objects: Sequence[T]) -> zip[tuple[T, T]]: return adjacent_n_tuples(objects, 2) def batch_by_property( items: Iterable[T], property_func: Callable[[T], S] ) -> list[tuple[T, S]]: """ Takes in a list, and returns a list of tuples, (batch, prop) such that all items in a batch have the same output when put into property_func, and such that chaining all these batches together would give the original list (i.e. order is preserved) """ batch_prop_pairs = [] curr_batch = [] curr_prop = None for item in items: prop = property_func(item) if prop != curr_prop: # Add current batch if len(curr_batch) > 0: batch_prop_pairs.append((curr_batch, curr_prop)) # Redefine curr curr_prop = prop curr_batch = [item] else: curr_batch.append(item) if len(curr_batch) > 0: batch_prop_pairs.append((curr_batch, curr_prop)) return batch_prop_pairs def listify(obj: object) -> list: if isinstance(obj, str): return [obj] try: return list(obj) except TypeError: return [obj] def resize_array(nparray: np.ndarray, length: int) -> np.ndarray: if len(nparray) == length: return nparray return np.resize(nparray, (length, *nparray.shape[1:])) def resize_preserving_order(nparray: np.ndarray, length: int) -> np.ndarray: if len(nparray) == 0: return np.resize(nparray, length) if len(nparray) == length: return nparray indices = np.arange(length) * len(nparray) // length return nparray[indices] def resize_with_interpolation(nparray: np.ndarray, length: int) -> np.ndarray: if len(nparray) == length: return nparray if len(nparray) == 1 or array_is_constant(nparray): return nparray[:1].repeat(length, axis=0) if length == 0: return np.zeros((0, *nparray.shape[1:])) cont_indices = np.linspace(0, len(nparray) - 1, length) return np.array([ (1 - a) * nparray[lh] + a * nparray[rh] for ci in cont_indices for lh, rh, a in [(int(ci), int(np.ceil(ci)), ci % 1)] ]) def make_even( iterable_1: Sequence[T], iterable_2: Sequence[S] ) -> tuple[Sequence[T], Sequence[S]]: len1 = len(iterable_1) len2 = len(iterable_2) if len1 == len2: return iterable_1, iterable_2 new_len = max(len1, len2) return ( [iterable_1[(n * len1) // new_len] for n in range(new_len)], [iterable_2[(n * len2) // new_len] for n in range(new_len)] ) def arrays_match(arr1: np.ndarray, arr2: np.ndarray) -> bool: return arr1.shape == arr2.shape and (arr1 == arr2).all() def array_is_constant(arr: np.ndarray) -> bool: return len(arr) > 0 and (arr == arr[0]).all() def cartesian_product(*arrays: np.ndarray): """ Copied from https://stackoverflow.com/a/11146645 """ la = len(arrays) dtype = np.result_type(*arrays) arr = np.empty([len(a) for a in arrays] + [la], dtype=dtype) for i, a in enumerate(np.ix_(*arrays)): arr[..., i] = a return arr.reshape(-1, la) def hash_obj(obj: object) -> int: if isinstance(obj, dict): return hash(tuple(sorted([ (hash_obj(k), hash_obj(v)) for k, v in obj.items() ]))) if isinstance(obj, set): return hash(tuple(sorted(hash_obj(e) for e in obj))) if isinstance(obj, (tuple, list)): return hash(tuple(hash_obj(e) for e in obj)) if isinstance(obj, Color): return hash(obj.get_rgb()) return hash(obj)
manim_3b1b/manimlib/utils/tex_to_symbol_count.py
TEX_TO_SYMBOL_COUNT = { R"\!": 0, R"\,": 0, R"\-": 0, R"\/": 0, R"\:": 0, R"\;": 0, R"\>": 0, R"\aa": 0, R"\AA": 0, R"\ae": 0, R"\AE": 0, R"\arccos": 6, R"\arcsin": 6, R"\arctan": 6, R"\arg": 3, R"\author": 0, R"\bf": 0, R"\bibliography": 0, R"\bibliographystyle": 0, R"\big": 0, R"\Big": 0, R"\bigodot": 4, R"\bigoplus": 5, R"\bigskip": 0, R"\bmod": 3, R"\boldmath": 0, R"\bottomfraction": 2, R"\bowtie": 2, R"\cal": 0, R"\cdots": 3, R"\centering": 0, R"\cite": 2, R"\cong": 2, R"\contentsline": 0, R"\cos": 3, R"\cosh": 4, R"\cot": 3, R"\coth": 4, R"\csc": 3, R"\date": 0, R"\dblfloatpagefraction": 2, R"\dbltopfraction": 2, R"\ddots": 3, R"\deg": 3, R"\det": 3, R"\dim": 3, R"\displaystyle": 0, R"\div": 2, R"\doteq": 2, R"\dotfill": 0, R"\dots": 3, R"\emph": 0, R"\exp": 3, R"\fbox": 4, R"\floatpagefraction": 2, R"\flushbottom": 0, R"\footnotesize": 0, R"\footnotetext": 0, R"\frame": 2, R"\framebox": 4, R"\fussy": 0, R"\gcd": 3, R"\ghost": 0, R"\glossary": 0, R"\hfill": 0, R"\hom": 3, R"\hookleftarrow": 2, R"\hookrightarrow": 2, R"\hrulefill": 0, R"\huge": 0, R"\Huge": 0, R"\hyphenation": 0, R"\iff": 2, R"\Im": 2, R"\index": 0, R"\inf": 3, R"\it": 0, R"\ker": 3, R"\l": 0, R"\L": 0, R"\label": 0, R"\large": 0, R"\Large": 0, R"\LARGE": 0, R"\ldots": 3, R"\lefteqn": 0, R"\left": 0, R"\lg": 2, R"\lim": 3, R"\liminf": 6, R"\limsup": 6, R"\linebreak": 0, R"\ln": 2, R"\log": 3, R"\longleftarrow": 2, R"\Longleftarrow": 2, R"\longleftrightarrow": 2, R"\Longleftrightarrow": 2, R"\longmapsto": 3, R"\longrightarrow": 2, R"\Longrightarrow": 2, R"\makebox": 0, R"\mapsto": 2, R"\markright": 0, R"\mathds": 0, R"\max": 3, R"\mbox": 0, R"\medskip": 0, R"\min": 3, R"\mit": 0, R"\models": 2, R"\ne": 2, R"\neq": 2, R"\newline": 0, R"\noindent": 0, R"\nolinebreak": 0, R"\nonumber": 0, R"\nopagebreak": 0, R"\normalmarginpar": 0, R"\normalsize": 0, R"\notin": 2, R"\o": 0, R"\O": 0, R"\obeycr": 0, R"\oe": 0, R"\OE": 0, R"\overbrace": 4, R"\pagebreak": 0, R"\pagenumbering": 0, R"\pageref": 2, R"\pmod": 5, R"\Pr": 2, R"\protect": 0, R"\qquad": 0, R"\quad": 0, R"\raggedbottom": 0, R"\raggedleft": 0, R"\raggedright": 0, R"\Re": 2, R"\ref": 2, R"\restorecr": 0, R"\reversemarginpar": 0, R"\right": 0, R"\rm": 0, R"\sc": 0, R"\scriptscriptstyle": 0, R"\scriptsize": 0, R"\scriptstyle": 0, R"\sec": 3, R"\sf": 0, R"\shortstack": 0, R"\sin": 3, R"\sinh": 4, R"\sl": 0, R"\sloppy": 0, R"\small": 0, R"\Small": 0, R"\smallskip": 0, R"\sqrt": 2, R"\ss": 0, R"\sup": 3, R"\tan": 3, R"\tanh": 4, R"\text": 0, R"\textbf": 0, R"\textfraction": 2, R"\textstyle": 0, R"\thicklines": 0, R"\thinlines": 0, R"\thinspace": 0, R"\tiny": 0, R"\title": 0, R"\today": 15, R"\topfraction": 2, R"\tt": 0, R"\typeout": 0, R"\unboldmath": 0, R"\underbrace": 6, R"\underline": 0, R"\value": 0, R"\vdots": 3, R"\vline": 0 }
manim_3b1b/manimlib/utils/shaders.py
from __future__ import annotations import os import re from functools import lru_cache import moderngl from PIL import Image import numpy as np from manimlib.config import parse_cli from manimlib.config import get_configuration from manimlib.utils.directories import get_shader_dir from manimlib.utils.file_ops import find_file from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Optional, Tuple from manimlib.typing import UniformDict from moderngl.vertex_array import VertexArray from moderngl.framebuffer import Framebuffer # Global maps updated as textures are allocated ID_TO_TEXTURE: dict[int, moderngl.Texture] = dict() PROGRAM_UNIFORM_MIRRORS: dict[int, dict[str, float | tuple]] = dict() @lru_cache() def image_path_to_texture(path: str, ctx: moderngl.Context) -> moderngl.Texture: im = Image.open(path).convert("RGBA") return ctx.texture( size=im.size, components=len(im.getbands()), data=im.tobytes(), ) def get_texture_id(texture: moderngl.Texture) -> int: tid = 0 while tid in ID_TO_TEXTURE: tid += 1 ID_TO_TEXTURE[tid] = texture texture.use(location=tid) return tid def release_texture(texture_id: int): texture = ID_TO_TEXTURE.pop(texture_id, None) if texture is not None: texture.release() @lru_cache() def get_shader_program( ctx: moderngl.context.Context, vertex_shader: str, fragment_shader: Optional[str] = None, geometry_shader: Optional[str] = None, ) -> moderngl.Program: return ctx.program( vertex_shader=vertex_shader, fragment_shader=fragment_shader, geometry_shader=geometry_shader, ) def set_program_uniform( program: moderngl.Program, name: str, value: float | tuple | np.ndarray ) -> bool: """ Sets a program uniform, and also keeps track of a dictionary of previously set uniforms for that program so that it doesn't needlessly reset it, requiring an exchange with gpu memory, if it sees the same value again. Returns True if changed the program, False if it left it as is. """ pid = id(program) if pid not in PROGRAM_UNIFORM_MIRRORS: PROGRAM_UNIFORM_MIRRORS[pid] = dict() uniform_mirror = PROGRAM_UNIFORM_MIRRORS[pid] if type(value) is np.ndarray and value.ndim > 0: value = tuple(value) if uniform_mirror.get(name, None) == value: return False try: program[name].value = value except KeyError: return False uniform_mirror[name] = value return True @lru_cache() def get_shader_code_from_file(filename: str) -> str | None: if not filename: return None try: filepath = find_file( filename, directories=[get_shader_dir(), "/"], extensions=[], ) except IOError: return None with open(filepath, "r") as f: result = f.read() # To share functionality between shaders, some functions are read in # from other files an inserted into the relevant strings before # passing to ctx.program for compiling # Replace "#INSERT " lines with relevant code insertions = re.findall(r"^#INSERT .*\.glsl$", result, flags=re.MULTILINE) for line in insertions: inserted_code = get_shader_code_from_file( os.path.join("inserts", line.replace("#INSERT ", "")) ) result = result.replace(line, inserted_code) return result def get_colormap_code(rgb_list: Sequence[float]) -> str: data = ",".join( "vec3({}, {}, {})".format(*rgb) for rgb in rgb_list ) return f"vec3[{len(rgb_list)}]({data})" @lru_cache() def get_fill_canvas(ctx: moderngl.Context) -> Tuple[Framebuffer, VertexArray]: """ Because VMobjects with fill are rendered in a funny way, using alpha blending to effectively compute the winding number around each pixel, they need to be rendered to a separate texture, which is then composited onto the ordinary frame buffer. This returns a texture, loaded into a frame buffer, and a vao which can display that texture as a simple quad onto a screen, along with the rgb value which is meant to be discarded. """ cam_config = get_configuration(parse_cli())['camera_config'] size = (cam_config['pixel_width'], cam_config['pixel_height']) # Important to make sure dtype is floating point (not fixed point) # so that alpha values can be negative and are not clipped texture = ctx.texture(size=size, components=4, dtype='f2') depth_texture = ctx.depth_texture(size=size) texture_fbo = ctx.framebuffer(texture, depth_texture) simple_program = ctx.program( vertex_shader=''' #version 330 in vec2 texcoord; out vec2 uv; void main() { gl_Position = vec4((2.0 * texcoord - 1.0), 0.0, 1.0); uv = texcoord; } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; uniform sampler2D DepthTexture; in vec2 uv; out vec4 color; void main() { color = texture(Texture, uv); if(color.a == 0) discard; // Counteract scaling in fill frag color.a *= 1.06; gl_FragDepth = texture(DepthTexture, uv)[0]; } ''', ) simple_program['Texture'].value = get_texture_id(texture) simple_program['DepthTexture'].value = get_texture_id(depth_texture) verts = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) fill_texture_vao = ctx.simple_vertex_array( simple_program, ctx.buffer(verts.astype('f4').tobytes()), 'texcoord', mode=moderngl.TRIANGLE_STRIP ) return (texture_fbo, fill_texture_vao)
manim_3b1b/manimlib/utils/simple_functions.py
from __future__ import annotations from functools import lru_cache import hashlib import inspect import math import numpy as np from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, TypeVar from manimlib.typing import FloatArray Scalable = TypeVar("Scalable", float, FloatArray) def sigmoid(x: float | FloatArray): return 1.0 / (1 + np.exp(-x)) @lru_cache(maxsize=10) def choose(n: int, k: int) -> int: return math.comb(n, k) def gen_choose(n: int, r: int) -> int: return int(np.prod(range(n, n - r, -1)) / math.factorial(r)) def get_num_args(function: Callable) -> int: return len(get_parameters(function)) def get_parameters(function: Callable) -> list: return list(inspect.signature(function).parameters.keys()) # Just to have a less heavyweight name for this extremely common operation # # We may wish to have more fine-grained control over division by zero behavior # in the future (separate specifiable values for 0/0 and x/0 with x != 0), # but for now, we just allow the option to handle indeterminate 0/0. def clip(a: float, min_a: float, max_a: float) -> float: if a < min_a: return min_a elif a > max_a: return max_a return a def arr_clip(arr: np.ndarray, min_a: float, max_a: float) -> np.ndarray: arr[arr < min_a] = min_a arr[arr > max_a] = max_a return arr def fdiv(a: Scalable, b: Scalable, zero_over_zero_value: Scalable | None = None) -> Scalable: if zero_over_zero_value is not None: out = np.full_like(a, zero_over_zero_value) where = np.logical_or(a != 0, b != 0) else: out = None where = True return np.true_divide(a, b, out=out, where=where) def binary_search(function: Callable[[float], float], target: float, lower_bound: float, upper_bound: float, tolerance:float = 1e-4) -> float | None: lh = lower_bound rh = upper_bound mh = (lh + rh) / 2 while abs(rh - lh) > tolerance: lx, mx, rx = [function(h) for h in (lh, mh, rh)] if lx == target: return lx if rx == target: return rx if lx <= target and rx >= target: if mx > target: rh = mh else: lh = mh elif lx > target and rx < target: lh, rh = rh, lh else: return None mh = (lh + rh) / 2 return mh def hash_string(string: str) -> str: # Truncating at 16 bytes for cleanliness hasher = hashlib.sha256(string.encode()) return hasher.hexdigest()[:16]
manim_3b1b/manimlib/utils/color.py
from __future__ import annotations from colour import Color from colour import hex2rgb from colour import rgb2hex import numpy as np from manimlib.constants import COLORMAP_3B1B from manimlib.constants import WHITE from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, Sequence from manimlib.typing import ManimColor, Vect3, Vect4, Vect3Array def color_to_rgb(color: ManimColor) -> Vect3: if isinstance(color, str): return hex_to_rgb(color) elif isinstance(color, Color): return np.array(color.get_rgb()) else: raise Exception("Invalid color type") def color_to_rgba(color: ManimColor, alpha: float = 1.0) -> Vect4: return np.array([*color_to_rgb(color), alpha]) def rgb_to_color(rgb: Vect3 | Sequence[float]) -> Color: try: return Color(rgb=tuple(rgb)) except ValueError: return Color(WHITE) def rgba_to_color(rgba: Vect4) -> Color: return rgb_to_color(rgba[:3]) def rgb_to_hex(rgb: Vect3 | Sequence[float]) -> str: return rgb2hex(rgb, force_long=True).upper() def hex_to_rgb(hex_code: str) -> Vect3: return np.array(hex2rgb(hex_code)) def invert_color(color: ManimColor) -> Color: return rgb_to_color(1.0 - color_to_rgb(color)) def color_to_int_rgb(color: ManimColor) -> np.ndarray[int, np.dtype[np.uint8]]: return (255 * color_to_rgb(color)).astype('uint8') def color_to_int_rgba(color: ManimColor, opacity: float = 1.0) -> np.ndarray[int, np.dtype[np.uint8]]: alpha = int(255 * opacity) return np.array([*color_to_int_rgb(color), alpha], dtype=np.uint8) def color_to_hex(color: ManimColor) -> str: return Color(color).get_hex_l().upper() def hex_to_int(rgb_hex: str) -> int: return int(rgb_hex[1:], 16) def int_to_hex(rgb_int: int) -> str: return f"#{rgb_int:06x}".upper() def color_gradient( reference_colors: Iterable[ManimColor], length_of_output: int ) -> list[Color]: if length_of_output == 0: return [] rgbs = list(map(color_to_rgb, reference_colors)) alphas = np.linspace(0, (len(rgbs) - 1), length_of_output) floors = alphas.astype('int') alphas_mod1 = alphas % 1 # End edge case alphas_mod1[-1] = 1 floors[-1] = len(rgbs) - 2 return [ rgb_to_color(np.sqrt(interpolate(rgbs[i]**2, rgbs[i + 1]**2, alpha))) for i, alpha in zip(floors, alphas_mod1) ] def interpolate_color( color1: ManimColor, color2: ManimColor, alpha: float ) -> Color: rgb = np.sqrt(interpolate(color_to_rgb(color1)**2, color_to_rgb(color2)**2, alpha)) return rgb_to_color(rgb) def average_color(*colors: ManimColor) -> Color: rgbs = np.array(list(map(color_to_rgb, colors))) return rgb_to_color(np.sqrt((rgbs**2).mean(0))) def random_color() -> Color: return Color(rgb=tuple(np.random.random(3))) def random_bright_color() -> Color: color = random_color() return average_color(color, Color(WHITE)) def get_colormap_list( map_name: str = "viridis", n_colors: int = 9 ) -> Vect3Array: """ Options for map_name: 3b1b_colormap magma inferno plasma viridis cividis twilight twilight_shifted turbo """ from matplotlib.cm import get_cmap if map_name == "3b1b_colormap": rgbs = np.array([color_to_rgb(color) for color in COLORMAP_3B1B]) else: rgbs = get_cmap(map_name).colors # Make more general? return resize_with_interpolation(np.array(rgbs), n_colors)
manim_3b1b/manimlib/utils/space_ops.py
from __future__ import annotations from functools import reduce import math import operator as op import platform from mapbox_earcut import triangulate_float32 as earcut import numpy as np from scipy.spatial.transform import Rotation from tqdm.auto import tqdm as ProgressDisplay from manimlib.constants import DOWN, OUT, RIGHT, UP from manimlib.constants import PI, TAU from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, List, Tuple from manimlib.typing import Vect2, Vect3, Vect4, VectN, Matrix3x3, Vect3Array, Vect2Array def cross( v1: Vect3 | List[float], v2: Vect3 | List[float], out: np.ndarray | None = None ) -> Vect3 | Vect3Array: is2d = isinstance(v1, np.ndarray) and len(v1.shape) == 2 if is2d: x1, y1, z1 = v1[:, 0], v1[:, 1], v1[:, 2] x2, y2, z2 = v2[:, 0], v2[:, 1], v2[:, 2] else: x1, y1, z1 = v1 x2, y2, z2 = v2 if out is None: out = np.empty(np.shape(v1)) out.T[:] = [ y1 * z2 - z1 * y2, z1 * x2 - x1 * z2, x1 * y2 - y1 * x2, ] return out def get_norm(vect: VectN | List[float]) -> float: return sum((x**2 for x in vect))**0.5 def normalize( vect: VectN | List[float], fall_back: VectN | List[float] | None = None ) -> VectN: norm = get_norm(vect) if norm > 0: return np.array(vect) / norm elif fall_back is not None: return np.array(fall_back) else: return np.zeros(len(vect)) def poly_line_length(points): """ Return the sum of the lengths between adjacent points """ diffs = points[1:] - points[:-1] return np.sqrt((diffs**2).sum(1)).sum() # Operations related to rotation def quaternion_mult(*quats: Vect4) -> Vect4: """ Inputs are treated as quaternions, where the real part is the last entry, so as to follow the scipy Rotation conventions. """ if len(quats) == 0: return np.array([0, 0, 0, 1]) result = np.array(quats[0]) for next_quat in quats[1:]: x1, y1, z1, w1 = result x2, y2, z2, w2 = next_quat result[:] = [ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2, w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, ] return result def quaternion_from_angle_axis( angle: float, axis: Vect3, ) -> Vect4: return Rotation.from_rotvec(angle * normalize(axis)).as_quat() def angle_axis_from_quaternion(quat: Vect4) -> Tuple[float, Vect3]: rot_vec = Rotation.from_quat(quat).as_rotvec() norm = get_norm(rot_vec) return norm, rot_vec / norm def quaternion_conjugate(quaternion: Vect4) -> Vect4: result = np.array(quaternion) result[:3] *= -1 return result def rotate_vector( vector: Vect3, angle: float, axis: Vect3 = OUT ) -> Vect3: rot = Rotation.from_rotvec(angle * normalize(axis)) return np.dot(vector, rot.as_matrix().T) def rotate_vector_2d(vector: Vect2, angle: float) -> Vect2: # Use complex numbers...because why not z = complex(*vector) * np.exp(complex(0, angle)) return np.array([z.real, z.imag]) def rotation_matrix_transpose_from_quaternion(quat: Vect4) -> Matrix3x3: return Rotation.from_quat(quat).as_matrix() def rotation_matrix_from_quaternion(quat: Vect4) -> Matrix3x3: return np.transpose(rotation_matrix_transpose_from_quaternion(quat)) def rotation_matrix(angle: float, axis: Vect3) -> Matrix3x3: """ Rotation in R^3 about a specified axis of rotation. """ return Rotation.from_rotvec(angle * normalize(axis)).as_matrix() def rotation_matrix_transpose(angle: float, axis: Vect3) -> Matrix3x3: return rotation_matrix(angle, axis).T def rotation_about_z(angle: float) -> Matrix3x3: cos_a = math.cos(angle) sin_a = math.sin(angle) return np.array([ [cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1] ]) def rotation_between_vectors(v1: Vect3, v2: Vect3) -> Matrix3x3: atol = 1e-8 if get_norm(v1 - v2) < atol: return np.identity(3) axis = cross(v1, v2) if get_norm(axis) < atol: # v1 and v2 align axis = cross(v1, RIGHT) if get_norm(axis) < atol: # v1 and v2 _and_ RIGHT all align axis = cross(v1, UP) return rotation_matrix( angle=angle_between_vectors(v1, v2), axis=axis, ) def z_to_vector(vector: Vect3) -> Matrix3x3: return rotation_between_vectors(OUT, vector) def angle_of_vector(vector: Vect2 | Vect3) -> float: """ Returns polar coordinate theta when vector is project on xy plane """ return math.atan2(vector[1], vector[0]) def angle_between_vectors(v1: VectN, v2: VectN) -> float: """ Returns the angle between two 3D vectors. This angle will always be btw 0 and pi """ n1 = get_norm(v1) n2 = get_norm(v2) if n1 == 0 or n2 == 0: return 0 cos_angle = np.dot(v1, v2) / np.float64(n1 * n2) return math.acos(clip(cos_angle, -1, 1)) def project_along_vector(point: Vect3, vector: Vect3) -> Vect3: matrix = np.identity(3) - np.outer(vector, vector) return np.dot(point, matrix.T) def normalize_along_axis( array: np.ndarray, axis: int, ) -> np.ndarray: norms = np.sqrt((array * array).sum(axis)) norms[norms == 0] = 1 return array / norms[:, np.newaxis] def get_unit_normal( v1: Vect3, v2: Vect3, tol: float = 1e-6 ) -> Vect3: v1 = normalize(v1) v2 = normalize(v2) cp = cross(v1, v2) cp_norm = get_norm(cp) if cp_norm < tol: # Vectors align, so find a normal to them in the plane shared with the z-axis new_cp = cross(cross(v1, OUT), v1) new_cp_norm = get_norm(new_cp) if new_cp_norm < tol: return DOWN return new_cp / new_cp_norm return cp / cp_norm ### def thick_diagonal(dim: int, thickness: int = 2) -> np.ndarray: row_indices = np.arange(dim).repeat(dim).reshape((dim, dim)) col_indices = np.transpose(row_indices) return (np.abs(row_indices - col_indices) < thickness).astype('uint8') def compass_directions(n: int = 4, start_vect: Vect3 = RIGHT) -> Vect3: angle = TAU / n return np.array([ rotate_vector(start_vect, k * angle) for k in range(n) ]) def complex_to_R3(complex_num: complex) -> Vect3: return np.array((complex_num.real, complex_num.imag, 0)) def R3_to_complex(point: Vect3) -> complex: return complex(*point[:2]) def complex_func_to_R3_func(complex_func: Callable[[complex], complex]) -> Callable[[Vect3], Vect3]: def result(p: Vect3): return complex_to_R3(complex_func(R3_to_complex(p))) return result def center_of_mass(points: Sequence[Vect3]) -> Vect3: return np.array(points).sum(0) / len(points) def midpoint(point1: VectN, point2: VectN) -> VectN: return center_of_mass([point1, point2]) def line_intersection( line1: Tuple[Vect3, Vect3], line2: Tuple[Vect3, Vect3] ) -> Vect3: """ return intersection point of two lines, each defined with a pair of vectors determining the end points """ x_diff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) y_diff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(x_diff, y_diff) if div == 0: raise Exception("Lines do not intersect") d = (det(*line1), det(*line2)) x = det(d, x_diff) / div y = det(d, y_diff) / div return np.array([x, y, 0]) def find_intersection( p0: Vect3 | Vect3Array, v0: Vect3 | Vect3Array, p1: Vect3 | Vect3Array, v1: Vect3 | Vect3Array, threshold: float = 1e-5, ) -> Vect3: """ Return the intersection of a line passing through p0 in direction v0 with one passing through p1 in direction v1. (Or array of intersections from arrays of such points/directions). For 3d values, it returns the point on the ray p0 + v0 * t closest to the ray p1 + v1 * t """ d = len(p0.shape) if d == 1: is_3d = any(arr[2] for arr in (p0, v0, p1, v1)) else: is_3d = any(z for arr in (p0, v0, p1, v1) for z in arr.T[2]) if not is_3d: numer = np.array(cross2d(v1, p1 - p0)) denom = np.array(cross2d(v1, v0)) else: cp1 = cross(v1, p1 - p0) cp2 = cross(v1, v0) numer = np.array((cp1 * cp1).sum(d - 1)) denom = np.array((cp1 * cp2).sum(d - 1)) denom[abs(denom) < threshold] = np.inf ratio = numer / denom return p0 + (ratio * v0.T).T def line_intersects_path( start: Vect2 | Vect3, end: Vect2 | Vect3, path: Vect2Array | Vect3Array, ) -> bool: """ Tests whether the line (start, end) intersects a polygonal path defined by its vertices """ n = len(path) - 1 p1 = np.empty((n, 2)) q1 = np.empty((n, 2)) p1[:] = start[:2] q1[:] = end[:2] p2 = path[:-1, :2] q2 = path[1:, :2] v1 = q1 - p1 v2 = q2 - p2 mis1 = cross2d(v1, p2 - p1) * cross2d(v1, q2 - p1) < 0 mis2 = cross2d(v2, p1 - p2) * cross2d(v2, q1 - p2) < 0 return bool((mis1 * mis2).any()) def get_closest_point_on_line(a: VectN, b: VectN, p: VectN) -> VectN: """ It returns point x such that x is on line ab and xp is perpendicular to ab. If x lies beyond ab line, then it returns nearest edge(a or b). """ # x = b + t*(a-b) = t*a + (1-t)*b t = np.dot(p - b, a - b) / np.dot(a - b, a - b) if t < 0: t = 0 if t > 1: t = 1 return ((t * a) + ((1 - t) * b)) def get_winding_number(points: Sequence[Vect2 | Vect3]) -> float: total_angle = 0 for p1, p2 in adjacent_pairs(points): d_angle = angle_of_vector(p2) - angle_of_vector(p1) d_angle = ((d_angle + PI) % TAU) - PI total_angle += d_angle return total_angle / TAU ## def cross2d(a: Vect2 | Vect2Array, b: Vect2 | Vect2Array) -> Vect2 | Vect2Array: if len(a.shape) == 2: return a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0] else: return a[0] * b[1] - b[0] * a[1] def tri_area( a: Vect2, b: Vect2, c: Vect2 ) -> float: return 0.5 * abs( a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) ) def is_inside_triangle( p: Vect2, a: Vect2, b: Vect2, c: Vect2 ) -> bool: """ Test if point p is inside triangle abc """ crosses = np.array([ cross2d(p - a, b - p), cross2d(p - b, c - p), cross2d(p - c, a - p), ]) return bool(np.all(crosses > 0) or np.all(crosses < 0)) def norm_squared(v: VectN | List[float]) -> float: return sum(x * x for x in v) # TODO, fails for polygons drawn over themselves def earclip_triangulation(verts: Vect3Array | Vect2Array, ring_ends: list[int]) -> list[int]: """ Returns a list of indices giving a triangulation of a polygon, potentially with holes - verts is a numpy array of points - ring_ends is a list of indices indicating where the ends of new paths are """ rings = [ list(range(e0, e1)) for e0, e1 in zip([0, *ring_ends], ring_ends) ] epsilon = 1e-6 def is_in(point, ring_id): return abs(abs(get_winding_number([i - point for i in verts[rings[ring_id]]])) - 1) < epsilon def ring_area(ring_id): ring = rings[ring_id] s = 0 for i, j in zip(ring[1:], ring): s += cross2d(verts[i], verts[j]) return abs(s) / 2 # Points at the same position may cause problems for i in rings: if len(i) < 2: continue verts[i[0]] += (verts[i[1]] - verts[i[0]]) * epsilon verts[i[-1]] += (verts[i[-2]] - verts[i[-1]]) * epsilon # First, we should know which rings are directly contained in it for each ring right = [max(verts[rings[i], 0]) for i in range(len(rings))] left = [min(verts[rings[i], 0]) for i in range(len(rings))] top = [max(verts[rings[i], 1]) for i in range(len(rings))] bottom = [min(verts[rings[i], 1]) for i in range(len(rings))] area = [ring_area(i) for i in range(len(rings))] # The larger ring must be outside rings_sorted = list(range(len(rings))) rings_sorted.sort(key=lambda x: area[x], reverse=True) def is_in_fast(ring_a, ring_b): # Whether a is in b return reduce(op.and_, ( left[ring_b] <= left[ring_a] <= right[ring_a] <= right[ring_b], bottom[ring_b] <= bottom[ring_a] <= top[ring_a] <= top[ring_b], is_in(verts[rings[ring_a][0]], ring_b) )) chilren = [[] for i in rings] ringenum = ProgressDisplay( enumerate(rings_sorted), total=len(rings), leave=False, ascii=True if platform.system() == 'Windows' else None, dynamic_ncols=True, desc="SVG Triangulation", delay=3, ) for idx, i in ringenum: for j in rings_sorted[:idx][::-1]: if is_in_fast(i, j): chilren[j].append(i) break res = [] # Then, we can use earcut for each part used = [False] * len(rings) for i in rings_sorted: if used[i]: continue v = rings[i] ring_ends = [len(v)] for j in chilren[i]: used[j] = True v += rings[j] ring_ends.append(len(v)) res += [v[i] for i in earcut(verts[v, :2], ring_ends)] return res
manim_3b1b/manimlib/utils/paths.py
from __future__ import annotations import math import numpy as np from manimlib.constants import OUT from manimlib.utils.bezier import interpolate from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import rotation_matrix_transpose from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import Vect3, Vect3Array STRAIGHT_PATH_THRESHOLD = 0.01 def straight_path( start_points: np.ndarray, end_points: np.ndarray, alpha: float ) -> np.ndarray: """ Same function as interpolate, but renamed to reflect intent of being used to determine how a set of points move to another set. For instance, it should be a specific case of path_along_arc """ return interpolate(start_points, end_points, alpha) def path_along_arc( arc_angle: float, axis: Vect3 = OUT ) -> Callable[[Vect3Array, Vect3Array, float], Vect3Array]: """ If vect is vector from start to end, [vect[:,1], -vect[:,0]] is perpendicular to vect in the left direction. """ if abs(arc_angle) < STRAIGHT_PATH_THRESHOLD: return straight_path if get_norm(axis) == 0: axis = OUT unit_axis = axis / get_norm(axis) def path(start_points, end_points, alpha): vects = end_points - start_points centers = start_points + 0.5 * vects if arc_angle != np.pi: centers += np.cross(unit_axis, vects / 2.0) / math.tan(arc_angle / 2) rot_matrix_T = rotation_matrix_transpose(alpha * arc_angle, unit_axis) return centers + np.dot(start_points - centers, rot_matrix_T) return path def clockwise_path() -> Callable[[Vect3Array, Vect3Array, float], Vect3Array]: return path_along_arc(-np.pi) def counterclockwise_path() -> Callable[[Vect3Array, Vect3Array, float], Vect3Array]: return path_along_arc(np.pi)
manim_3b1b/manimlib/utils/rate_functions.py
from __future__ import annotations import numpy as np from manimlib.utils.bezier import bezier from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable def linear(t: float) -> float: return t def smooth(t: float) -> float: # Zero first and second derivatives at t=0 and t=1. # Equivalent to bezier([0, 0, 0, 1, 1, 1]) s = 1 - t return (t**3) * (10 * s * s + 5 * s * t + t * t) def rush_into(t: float) -> float: return 2 * smooth(0.5 * t) def rush_from(t: float) -> float: return 2 * smooth(0.5 * (t + 1)) - 1 def slow_into(t: float) -> float: return np.sqrt(1 - (1 - t) * (1 - t)) def double_smooth(t: float) -> float: if t < 0.5: return 0.5 * smooth(2 * t) else: return 0.5 * (1 + smooth(2 * t - 1)) def there_and_back(t: float) -> float: new_t = 2 * t if t < 0.5 else 2 * (1 - t) return smooth(new_t) def there_and_back_with_pause(t: float, pause_ratio: float = 1. / 3) -> float: a = 1. / pause_ratio if t < 0.5 - pause_ratio / 2: return smooth(a * t) elif t < 0.5 + pause_ratio / 2: return 1 else: return smooth(a - a * t) def running_start(t: float, pull_factor: float = -0.5) -> float: return bezier([0, 0, pull_factor, pull_factor, 1, 1, 1])(t) def overshoot(t: float, pull_factor: float = 1.5) -> float: return bezier([0, 0, pull_factor, pull_factor, 1, 1])(t) def not_quite_there( func: Callable[[float], float] = smooth, proportion: float = 0.7 ) -> Callable[[float], float]: def result(t): return proportion * func(t) return result def wiggle(t: float, wiggles: float = 2) -> float: return there_and_back(t) * np.sin(wiggles * np.pi * t) def squish_rate_func( func: Callable[[float], float], a: float = 0.4, b: float = 0.6 ) -> Callable[[float], float]: def result(t): if a == b: return a elif t < a: return func(0) elif t > b: return func(1) else: return func((t - a) / (b - a)) return result # Stylistically, should this take parameters (with default values)? # Ultimately, the functionality is entirely subsumed by squish_rate_func, # but it may be useful to have a nice name for with nice default params for # "lingering", different from squish_rate_func's default params def lingering(t: float) -> float: return squish_rate_func(lambda t: t, 0, 0.8)(t) def exponential_decay(t: float, half_life: float = 0.1) -> float: # The half-life should be rather small to minimize # the cut-off error at the end return 1 - np.exp(-t / half_life)
manim_3b1b/manimlib/utils/dict_ops.py
import itertools as it import numpy as np def merge_dicts_recursively(*dicts): """ Creates a dict whose keyset is the union of all the input dictionaries. The value for each key is based on the first dict in the list with that key. dicts later in the list have higher priority When values are dictionaries, it is applied recursively """ result = dict() all_items = it.chain(*[d.items() for d in dicts]) for key, value in all_items: if key in result and isinstance(result[key], dict) and isinstance(value, dict): result[key] = merge_dicts_recursively(result[key], value) else: result[key] = value return result def soft_dict_update(d1, d2): """ Adds key values pairs of d2 to d1 only when d1 doesn't already have that key """ for key, value in list(d2.items()): if key not in d1: d1[key] = value def dict_eq(d1, d2): if len(d1) != len(d2): return False for key in d1: value1 = d1[key] value2 = d2[key] if type(value1) != type(value2): return False if type(d1[key]) == np.ndarray: if any(d1[key] != d2[key]): return False elif d1[key] != d2[key]: return False return True
manim_3b1b/manimlib/utils/family_ops.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, List, Set, Tuple from manimlib.mobject.mobject import Mobject def extract_mobject_family_members( mobject_list: Iterable[Mobject], exclude_pointless: bool = False ) -> list[Mobject]: return [ sm for mob in mobject_list for sm in mob.get_family() if (not exclude_pointless) or sm.has_points() ] def recursive_mobject_remove(mobjects: List[Mobject], to_remove: Set[Mobject]) -> Tuple[List[Mobject], bool]: """ Takes in a list of mobjects, together with a set of mobjects to remove. The first component of what's removed is a new list such that any mobject with one of the elements from `to_remove` in its family is no longer in the list, and in its place are its family members which aren't in `to_remove` The second component is a boolean value indicating whether any removals were made """ result = [] found_in_list = False for mob in mobjects: if mob in to_remove: found_in_list = True continue # Recursive call sub_list, found_in_submobjects = recursive_mobject_remove( mob.submobjects, to_remove ) if found_in_submobjects: result.extend(sub_list) found_in_list = True else: result.append(mob) return result, found_in_list
manim_3b1b/manimlib/utils/images.py
from __future__ import annotations import numpy as np from PIL import Image from manimlib.utils.directories import get_raster_image_dir from manimlib.utils.directories import get_vector_image_dir from manimlib.utils.file_ops import find_file from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable def get_full_raster_image_path(image_file_name: str) -> str: return find_file( image_file_name, directories=[get_raster_image_dir()], extensions=[".jpg", ".jpeg", ".png", ".gif", ""] ) def get_full_vector_image_path(image_file_name: str) -> str: return find_file( image_file_name, directories=[get_vector_image_dir()], extensions=[".svg", ".xdv", ""], ) def invert_image(image: Iterable) -> Image.Image: arr = np.array(image) arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr return Image.fromarray(arr)
manim_3b1b/manimlib/utils/bezier.py
from __future__ import annotations import numpy as np from scipy import linalg from fontTools.cu2qu.cu2qu import curve_to_quadratic from manimlib.logger import log from manimlib.utils.simple_functions import choose from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import cross from manimlib.utils.space_ops import find_intersection from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import z_to_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, TypeVar, Tuple from manimlib.typing import VectN, FloatArray, VectNArray, Vect3Array Scalable = TypeVar("Scalable", float, FloatArray) CLOSED_THRESHOLD = 0.001 def bezier( points: Sequence[float | FloatArray] | VectNArray ) -> Callable[[float], float | FloatArray]: if len(points) == 0: raise Exception("bezier cannot be calld on an empty list") n = len(points) - 1 def result(t: float) -> float | FloatArray: return sum( ((1 - t)**(n - k)) * (t**k) * choose(n, k) * point for k, point in enumerate(points) ) return result def partial_bezier_points( points: Sequence[Scalable], a: float, b: float ) -> list[Scalable]: """ Given an list of points which define a bezier curve, and two numbers 0<=a<b<=1, return an list of the same size, which describes the portion of the original bezier curve on the interval [a, b]. This algorithm is pretty nifty, and pretty dense. """ if a == 1: return [points[-1]] * len(points) a_to_1 = [ bezier(points[i:])(a) for i in range(len(points)) ] end_prop = (b - a) / (1. - a) return [ bezier(a_to_1[:i + 1])(end_prop) for i in range(len(points)) ] # Shortened version of partial_bezier_points just for quadratics, # since this is called a fair amount def partial_quadratic_bezier_points( points: Sequence[VectN] | VectNArray, a: float, b: float ) -> list[VectN]: if a == 1: return 3 * [points[-1]] def curve(t): return points[0] * (1 - t) * (1 - t) + 2 * points[1] * t * (1 - t) + points[2] * t * t # bezier(points) h0 = curve(a) if a > 0 else points[0] h2 = curve(b) if b < 1 else points[2] h1_prime = (1 - a) * points[1] + a * points[2] end_prop = (b - a) / (1. - a) h1 = (1 - end_prop) * h0 + end_prop * h1_prime return [h0, h1, h2] # Linear interpolation variants def interpolate(start: Scalable, end: Scalable, alpha: float | VectN) -> Scalable: try: return (1 - alpha) * start + alpha * end except TypeError: log.debug(f"`start` parameter with type `{type(start)}` and dtype `{start.dtype}`") log.debug(f"`end` parameter with type `{type(end)}` and dtype `{end.dtype}`") log.debug(f"`alpha` parameter with value `{alpha}`") import sys sys.exit(2) def outer_interpolate( start: Scalable, end: Scalable, alpha: Scalable, ) -> np.ndarray: result = np.outer(1 - alpha, start) + np.outer(alpha, end) return result.reshape((*np.shape(alpha), *np.shape(start))) def set_array_by_interpolation( arr: np.ndarray, arr1: np.ndarray, arr2: np.ndarray, alpha: float, interp_func: Callable[[np.ndarray, np.ndarray, float], np.ndarray] = interpolate ) -> np.ndarray: arr[:] = interp_func(arr1, arr2, alpha) return arr def integer_interpolate( start: int, end: int, alpha: float ) -> tuple[int, float]: """ alpha is a float between 0 and 1. This returns an integer between start and end (inclusive) representing appropriate interpolation between them, along with a "residue" representing a new proportion between the returned integer and the next one of the list. For example, if start=0, end=10, alpha=0.46, This would return (4, 0.6). """ if alpha >= 1: return (end - 1, 1.0) if alpha <= 0: return (start, 0) value = int(interpolate(start, end, alpha)) residue = ((end - start) * alpha) % 1 return (value, residue) def mid(start: Scalable, end: Scalable) -> Scalable: return (start + end) / 2.0 def inverse_interpolate(start: Scalable, end: Scalable, value: Scalable) -> np.ndarray: return np.true_divide(value - start, end - start) def match_interpolate( new_start: Scalable, new_end: Scalable, old_start: Scalable, old_end: Scalable, old_value: Scalable ) -> Scalable: return interpolate( new_start, new_end, inverse_interpolate(old_start, old_end, old_value) ) def quadratic_bezier_points_for_arc(angle: float, n_components: int = 8): n_points = 2 * n_components + 1 angles = np.linspace(0, angle, n_points) points = np.array([np.cos(angles), np.sin(angles), np.zeros(n_points)]).T # Adjust handles theta = angle / n_components points[1::2] /= np.cos(theta / 2) return points def approx_smooth_quadratic_bezier_handles( points: FloatArray ) -> FloatArray: """ Figuring out which bezier curves most smoothly connect a sequence of points. Given three successive points, P0, P1 and P2, you can compute that by defining h = (1/4) P0 + P1 - (1/4)P2, the bezier curve defined by (P0, h, P1) will pass through the point P2. So for a given set of four successive points, P0, P1, P2, P3, if we want to add a handle point h between P1 and P2 so that the quadratic bezier (P1, h, P2) is part of a smooth curve passing through all four points, we calculate one solution for h that would produce a parbola passing through P3, call it smooth_to_right, and another that would produce a parabola passing through P0, call it smooth_to_left, and use the midpoint between the two. """ if len(points) == 2: return midpoint(*points) smooth_to_right, smooth_to_left = [ 0.25 * ps[0:-2] + ps[1:-1] - 0.25 * ps[2:] for ps in (points, points[::-1]) ] if np.isclose(points[0], points[-1]).all(): last_str = 0.25 * points[-2] + points[-1] - 0.25 * points[1] last_stl = 0.25 * points[1] + points[0] - 0.25 * points[-2] else: last_str = smooth_to_left[0] last_stl = smooth_to_right[0] handles = 0.5 * np.vstack([smooth_to_right, [last_str]]) handles += 0.5 * np.vstack([last_stl, smooth_to_left[::-1]]) return handles def smooth_quadratic_path(anchors: Vect3Array) -> Vect3Array: """ Returns a path defining a smooth quadratic bezier spline through anchors. """ if len(anchors) < 2: return anchors elif len(anchors) == 2: return np.array([anchors[0], anchors.mean(1), anchors[2]]) is_flat = (anchors[:, 2] == 0).all() if not is_flat: normal = cross(anchors[2] - anchors[1], anchors[1] - anchors[0]) rot = z_to_vector(normal) anchors = np.dot(anchors, rot) shift = anchors[0, 2] anchors[:, 2] -= shift h1s, h2s = get_smooth_cubic_bezier_handle_points(anchors) quads = [anchors[0, :2]] for cub_bs in zip(anchors[:-1], h1s, h2s, anchors[1:]): # Try to use fontTools curve_to_quadratic new_quads = curve_to_quadratic( [b[:2] for b in cub_bs], max_err=0.1 * get_norm(cub_bs[3] - cub_bs[0]) ) # Otherwise fall back on home baked solution if new_quads is None or len(new_quads) % 2 == 0: new_quads = get_quadratic_approximation_of_cubic(*cub_bs)[:, :2] quads.extend(new_quads[1:]) new_path = np.zeros((len(quads), 3)) new_path[:, :2] = quads if not is_flat: new_path[:, 2] += shift new_path = np.dot(new_path, rot.T) return new_path def get_smooth_cubic_bezier_handle_points( points: Sequence[VectN] | VectNArray ) -> tuple[FloatArray, FloatArray]: points = np.array(points) num_handles = len(points) - 1 dim = points.shape[1] if num_handles < 1: return np.zeros((0, dim)), np.zeros((0, dim)) # Must solve 2*num_handles equations to get the handles. # l and u are the number of lower an upper diagonal rows # in the matrix to solve. l, u = 2, 1 # diag is a representation of the matrix in diagonal form # See https://www.particleincell.com/2012/bezier-splines/ # for how to arrive at these equations diag = np.zeros((l + u + 1, 2 * num_handles)) diag[0, 1::2] = -1 diag[0, 2::2] = 1 diag[1, 0::2] = 2 diag[1, 1::2] = 1 diag[2, 1:-2:2] = -2 diag[3, 0:-3:2] = 1 # last diag[2, -2] = -1 diag[1, -1] = 2 # This is the b as in Ax = b, where we are solving for x, # and A is represented using diag. However, think of entries # to x and b as being points in space, not numbers b = np.zeros((2 * num_handles, dim)) b[1::2] = 2 * points[1:] b[0] = points[0] b[-1] = points[-1] def solve_func(b): return linalg.solve_banded((l, u), diag, b) use_closed_solve_function = is_closed(points) if use_closed_solve_function: # Get equations to relate first and last points matrix = diag_to_matrix((l, u), diag) # last row handles second derivative matrix[-1, [0, 1, -2, -1]] = [2, -1, 1, -2] # first row handles first derivative matrix[0, :] = np.zeros(matrix.shape[1]) matrix[0, [0, -1]] = [1, 1] b[0] = 2 * points[0] b[-1] = np.zeros(dim) def closed_curve_solve_func(b): return linalg.solve(matrix, b) handle_pairs = np.zeros((2 * num_handles, dim)) for i in range(dim): if use_closed_solve_function: handle_pairs[:, i] = closed_curve_solve_func(b[:, i]) else: handle_pairs[:, i] = solve_func(b[:, i]) return handle_pairs[0::2], handle_pairs[1::2] def diag_to_matrix( l_and_u: tuple[int, int], diag: np.ndarray ) -> np.ndarray: """ Converts array whose rows represent diagonal entries of a matrix into the matrix itself. See scipy.linalg.solve_banded """ l, u = l_and_u dim = diag.shape[1] matrix = np.zeros((dim, dim)) for i in range(l + u + 1): np.fill_diagonal( matrix[max(0, i - u):, max(0, u - i):], diag[i, max(0, u - i):] ) return matrix def is_closed(points: FloatArray) -> bool: return np.allclose(points[0], points[-1]) # Given 4 control points for a cubic bezier curve (or arrays of such) # return control points for 2 quadratics (or 2n quadratics) approximating them. def get_quadratic_approximation_of_cubic( a0: FloatArray, h0: FloatArray, h1: FloatArray, a1: FloatArray ) -> FloatArray: a0 = np.array(a0, ndmin=2) h0 = np.array(h0, ndmin=2) h1 = np.array(h1, ndmin=2) a1 = np.array(a1, ndmin=2) # Tangent vectors at the start and end. T0 = h0 - a0 T1 = a1 - h1 # Search for inflection points. If none are found, use the # midpoint as a cut point. # Based on http://www.caffeineowl.com/graphics/2d/vectorial/cubic-inflexion.html has_infl = np.ones(len(a0), dtype=bool) p = h0 - a0 q = h1 - 2 * h0 + a0 r = a1 - 3 * h1 + 3 * h0 - a0 a = cross2d(q, r) b = cross2d(p, r) c = cross2d(p, q) disc = b * b - 4 * a * c has_infl &= (disc > 0) sqrt_disc = np.sqrt(np.abs(disc)) settings = np.seterr(all='ignore') ti_bounds = [] for sgn in [-1, +1]: ti = (-b + sgn * sqrt_disc) / (2 * a) ti[a == 0] = (-c / b)[a == 0] ti[(a == 0) & (b == 0)] = 0 ti_bounds.append(ti) ti_min, ti_max = ti_bounds np.seterr(**settings) ti_min_in_range = has_infl & (0 < ti_min) & (ti_min < 1) ti_max_in_range = has_infl & (0 < ti_max) & (ti_max < 1) # Choose a value of t which starts at 0.5, # but is updated to one of the inflection points # if they lie between 0 and 1 t_mid = 0.5 * np.ones(len(a0)) t_mid[ti_min_in_range] = ti_min[ti_min_in_range] t_mid[ti_max_in_range] = ti_max[ti_max_in_range] m, n = a0.shape t_mid = t_mid.repeat(n).reshape((m, n)) # Compute bezier point and tangent at the chosen value of t mid = bezier([a0, h0, h1, a1])(t_mid) Tm = bezier([h0 - a0, h1 - h0, a1 - h1])(t_mid) # Intersection between tangent lines at end points # and tangent in the middle i0 = find_intersection(a0, T0, mid, Tm) i1 = find_intersection(a1, T1, mid, Tm) m, n = np.shape(a0) result = np.zeros((5 * m, n)) result[0::5] = a0 result[1::5] = i0 result[2::5] = mid result[3::5] = i1 result[4::5] = a1 return result def get_smooth_quadratic_bezier_path_through( points: Sequence[VectN] ) -> np.ndarray: # TODO h0, h1 = get_smooth_cubic_bezier_handle_points(points) a0 = points[:-1] a1 = points[1:] return get_quadratic_approximation_of_cubic(a0, h0, h1, a1)
manim_3b1b/manimlib/utils/file_ops.py
from __future__ import annotations import os import numpy as np import validators from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable def add_extension_if_not_present(file_name: str, extension: str) -> str: # This could conceivably be smarter about handling existing differing extensions if(file_name[-len(extension):] != extension): return file_name + extension else: return file_name def guarantee_existence(path: str) -> str: if not os.path.exists(path): os.makedirs(path) return os.path.abspath(path) def find_file( file_name: str, directories: Iterable[str] | None = None, extensions: Iterable[str] | None = None ) -> str: # Check if this is a file online first, and if so, download # it to a temporary directory if validators.url(file_name): import urllib.request from manimlib.utils.directories import get_downloads_dir stem, name = os.path.split(file_name) folder = get_downloads_dir() path = os.path.join(folder, name) urllib.request.urlretrieve(file_name, path) return path # Check if what was passed in is already a valid path to a file if os.path.exists(file_name): return file_name # Otherwise look in local file system directories = directories or [""] extensions = extensions or [""] possible_paths = ( os.path.join(directory, file_name + extension) for directory in directories for extension in extensions ) for path in possible_paths: if os.path.exists(path): return path raise IOError(f"{file_name} not Found") def get_sorted_integer_files( directory: str, min_index: float = 0, max_index: float = np.inf, remove_non_integer_files: bool = False, remove_indices_greater_than: float | None = None, extension: str | None = None, ) -> list[str]: indexed_files = [] for file in os.listdir(directory): if '.' in file: index_str = file[:file.index('.')] else: index_str = file full_path = os.path.join(directory, file) if index_str.isdigit(): index = int(index_str) if remove_indices_greater_than is not None: if index > remove_indices_greater_than: os.remove(full_path) continue if extension is not None and not file.endswith(extension): continue if index >= min_index and index < max_index: indexed_files.append((index, file)) elif remove_non_integer_files: os.remove(full_path) indexed_files.sort(key=lambda p: p[0]) return list(map(lambda p: os.path.join(directory, p[1]), indexed_files))
manim_3b1b/manimlib/utils/sounds.py
from __future__ import annotations from manimlib.utils.directories import get_sound_dir from manimlib.utils.file_ops import find_file def get_full_sound_file_path(sound_file_name: str) -> str: return find_file( sound_file_name, directories=[get_sound_dir()], extensions=[".wav", ".mp3", ""] )
manim_3b1b/manimlib/camera/__init__.py
manim_3b1b/manimlib/camera/camera_frame.py
from __future__ import annotations import math import numpy as np from scipy.spatial.transform import Rotation from pyrr import Matrix44 from manimlib.constants import DEGREES, RADIANS from manimlib.constants import FRAME_SHAPE from manimlib.constants import DOWN, LEFT, ORIGIN, OUT, RIGHT, UP from manimlib.mobject.mobject import Mobject from manimlib.utils.space_ops import normalize from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Vect3 class CameraFrame(Mobject): def __init__( self, frame_shape: tuple[float, float] = FRAME_SHAPE, center_point: Vect3 = ORIGIN, # Field of view in the y direction fovy: float = 45 * DEGREES, **kwargs, ): super().__init__(**kwargs) self.uniforms["orientation"] = Rotation.identity().as_quat() self.uniforms["fovy"] = fovy self.default_orientation = Rotation.identity() self.view_matrix = np.identity(4) self.camera_location = OUT # This will be updated by set_points self.set_points(np.array([ORIGIN, LEFT, RIGHT, DOWN, UP])) self.set_width(frame_shape[0], stretch=True) self.set_height(frame_shape[1], stretch=True) self.move_to(center_point) def set_orientation(self, rotation: Rotation): self.uniforms["orientation"][:] = rotation.as_quat() return self def get_orientation(self): return Rotation.from_quat(self.uniforms["orientation"]) def make_orientation_default(self): self.default_orientation = self.get_orientation() return self def to_default_state(self): self.set_shape(*FRAME_SHAPE) self.center() self.set_orientation(self.default_orientation) return self def get_euler_angles(self) -> np.ndarray: orientation = self.get_orientation() if all(orientation.as_quat() == [0, 0, 0, 1]): return np.zeros(3) return orientation.as_euler("zxz")[::-1] def get_theta(self): return self.get_euler_angles()[0] def get_phi(self): return self.get_euler_angles()[1] def get_gamma(self): return self.get_euler_angles()[2] def get_scale(self): return self.get_height() / FRAME_SHAPE[1] def get_inverse_camera_rotation_matrix(self): return self.get_orientation().as_matrix().T def get_view_matrix(self, refresh=False): """ Returns a 4x4 for the affine transformation mapping a point into the camera's internal coordinate system """ if self._data_has_changed: shift = np.identity(4) rotation = np.identity(4) scale_mat = np.identity(4) shift[:3, 3] = -self.get_center() rotation[:3, :3] = self.get_inverse_camera_rotation_matrix() scale = self.get_scale() if scale > 0: scale_mat[:3, :3] /= self.get_scale() self.view_matrix = np.dot(scale_mat, np.dot(rotation, shift)) return self.view_matrix def get_inv_view_matrix(self): return np.linalg.inv(self.get_view_matrix()) @Mobject.affects_data def interpolate(self, *args, **kwargs): super().interpolate(*args, **kwargs) @Mobject.affects_data def rotate(self, angle: float, axis: np.ndarray = OUT, **kwargs): rot = Rotation.from_rotvec(angle * normalize(axis)) self.set_orientation(rot * self.get_orientation()) return self def set_euler_angles( self, theta: float | None = None, phi: float | None = None, gamma: float | None = None, units: float = RADIANS ): eulers = self.get_euler_angles() # theta, phi, gamma for i, var in enumerate([theta, phi, gamma]): if var is not None: eulers[i] = var * units if all(eulers == 0): rot = Rotation.identity() else: rot = Rotation.from_euler("zxz", eulers[::-1]) self.set_orientation(rot) return self def reorient( self, theta_degrees: float | None = None, phi_degrees: float | None = None, gamma_degrees: float | None = None, ): """ Shortcut for set_euler_angles, defaulting to taking in angles in degrees """ self.set_euler_angles(theta_degrees, phi_degrees, gamma_degrees, units=DEGREES) return self def set_theta(self, theta: float): return self.set_euler_angles(theta=theta) def set_phi(self, phi: float): return self.set_euler_angles(phi=phi) def set_gamma(self, gamma: float): return self.set_euler_angles(gamma=gamma) def increment_theta(self, dtheta: float): self.rotate(dtheta, OUT) return self def increment_phi(self, dphi: float): self.rotate(dphi, self.get_inverse_camera_rotation_matrix()[0]) return self def increment_gamma(self, dgamma: float): self.rotate(dgamma, self.get_inverse_camera_rotation_matrix()[2]) return self @Mobject.affects_data def set_focal_distance(self, focal_distance: float): self.uniforms["fovy"] = 2 * math.atan(0.5 * self.get_height() / focal_distance) return self @Mobject.affects_data def set_field_of_view(self, field_of_view: float): self.uniforms["fovy"] = field_of_view return self def get_shape(self): return (self.get_width(), self.get_height()) def get_aspect_ratio(self): width, height = self.get_shape() return width / height def get_center(self) -> np.ndarray: # Assumes first point is at the center return self.get_points()[0] def get_width(self) -> float: points = self.get_points() return points[2, 0] - points[1, 0] def get_height(self) -> float: points = self.get_points() return points[4, 1] - points[3, 1] def get_focal_distance(self) -> float: return 0.5 * self.get_height() / math.tan(0.5 * self.uniforms["fovy"]) def get_field_of_view(self) -> float: return self.uniforms["fovy"] def get_implied_camera_location(self) -> np.ndarray: if self._data_has_changed: to_camera = self.get_inverse_camera_rotation_matrix()[2] dist = self.get_focal_distance() self.camera_location = self.get_center() + dist * to_camera return self.camera_location def to_fixed_frame_point(self, point: Vect3, relative: bool = False): view = self.get_view_matrix() point4d = [*point, 0 if relative else 1] return np.dot(point4d, view.T)[:3] def from_fixed_frame_point(self, point: Vect3, relative: bool = False): inv_view = self.get_inv_view_matrix() point4d = [*point, 0 if relative else 1] return np.dot(point4d, inv_view.T)[:3]
manim_3b1b/manimlib/camera/camera.py
from __future__ import annotations import moderngl import numpy as np import OpenGL.GL as gl from PIL import Image from manimlib.camera.camera_frame import CameraFrame from manimlib.constants import BLACK from manimlib.constants import DEFAULT_FPS from manimlib.constants import DEFAULT_PIXEL_HEIGHT, DEFAULT_PIXEL_WIDTH from manimlib.constants import FRAME_WIDTH from manimlib.mobject.mobject import Mobject from manimlib.mobject.mobject import Point from manimlib.utils.color import color_to_rgba from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Optional from manimlib.typing import ManimColor, Vect3 from manimlib.window import Window class Camera(object): def __init__( self, window: Optional[Window] = None, background_image: Optional[str] = None, frame_config: dict = dict(), pixel_width: int = DEFAULT_PIXEL_WIDTH, pixel_height: int = DEFAULT_PIXEL_HEIGHT, fps: int = DEFAULT_FPS, # Note: frame height and width will be resized to match the pixel aspect ratio background_color: ManimColor = BLACK, background_opacity: float = 1.0, # Points in vectorized mobjects with norm greater # than this value will be rescaled. max_allowable_norm: float = FRAME_WIDTH, image_mode: str = "RGBA", n_channels: int = 4, pixel_array_dtype: type = np.uint8, light_source_position: Vect3 = np.array([-10, 10, 10]), # Although vector graphics handle antialiasing fine # without multisampling, for 3d scenes one might want # to set samples to be greater than 0. samples: int = 0, ): self.background_image = background_image self.window = window self.default_pixel_shape = (pixel_width, pixel_height) self.fps = fps self.max_allowable_norm = max_allowable_norm self.image_mode = image_mode self.n_channels = n_channels self.pixel_array_dtype = pixel_array_dtype self.light_source_position = light_source_position self.samples = samples self.rgb_max_val: float = np.iinfo(self.pixel_array_dtype).max self.background_rgba: list[float] = list(color_to_rgba( background_color, background_opacity )) self.uniforms = dict() self.init_frame(**frame_config) self.init_context() self.init_fbo() self.init_light_source() def init_frame(self, **config) -> None: self.frame = CameraFrame(**config) def init_context(self) -> None: if self.window is None: self.ctx: moderngl.Context = moderngl.create_standalone_context() else: self.ctx: moderngl.Context = self.window.ctx self.ctx.enable(moderngl.PROGRAM_POINT_SIZE) self.ctx.enable(moderngl.BLEND) def init_fbo(self) -> None: # This is the buffer used when writing to a video/image file self.fbo_for_files = self.get_fbo(self.samples) # This is the frame buffer we'll draw into when emitting frames self.draw_fbo = self.get_fbo(samples=0) if self.window is None: self.window_fbo = None self.fbo = self.fbo_for_files else: self.window_fbo = self.ctx.detect_framebuffer() self.fbo = self.window_fbo self.fbo.use() def init_light_source(self) -> None: self.light_source = Point(self.light_source_position) def use_window_fbo(self, use: bool = True): assert(self.window is not None) if use: self.fbo = self.window_fbo else: self.fbo = self.fbo_for_files # Methods associated with the frame buffer def get_fbo( self, samples: int = 0 ) -> moderngl.Framebuffer: return self.ctx.framebuffer( color_attachments=self.ctx.texture( self.default_pixel_shape, components=self.n_channels, samples=samples, ), depth_attachment=self.ctx.depth_renderbuffer( self.default_pixel_shape, samples=samples ) ) def clear(self) -> None: self.fbo.clear(*self.background_rgba) def blit(self, src_fbo, dst_fbo): """ Copy blocks between fbo's using Blit """ gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, src_fbo.glo) gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, dst_fbo.glo) gl.glBlitFramebuffer( *src_fbo.viewport, *dst_fbo.viewport, gl.GL_COLOR_BUFFER_BIT, gl.GL_LINEAR ) def get_raw_fbo_data(self, dtype: str = 'f1') -> bytes: self.blit(self.fbo, self.draw_fbo) return self.draw_fbo.read( viewport=self.draw_fbo.viewport, components=self.n_channels, dtype=dtype, ) def get_image(self) -> Image.Image: return Image.frombytes( 'RGBA', self.get_pixel_shape(), self.get_raw_fbo_data(), 'raw', 'RGBA', 0, -1 ) def get_pixel_array(self) -> np.ndarray: raw = self.get_raw_fbo_data(dtype='f4') flat_arr = np.frombuffer(raw, dtype='f4') arr = flat_arr.reshape([*reversed(self.draw_fbo.size), self.n_channels]) arr = arr[::-1] # Convert from float return (self.rgb_max_val * arr).astype(self.pixel_array_dtype) # Needed? def get_texture(self) -> moderngl.Texture: texture = self.ctx.texture( size=self.fbo.size, components=4, data=self.get_raw_fbo_data(), dtype='f4' ) return texture # Getting camera attributes def get_pixel_size(self) -> float: return self.frame.get_width() / self.get_pixel_shape()[0] def get_pixel_shape(self) -> tuple[int, int]: return self.fbo.size def get_pixel_width(self) -> int: return self.get_pixel_shape()[0] def get_pixel_height(self) -> int: return self.get_pixel_shape()[1] def get_aspect_ratio(self): pw, ph = self.get_pixel_shape() return pw / ph def get_frame_height(self) -> float: return self.frame.get_height() def get_frame_width(self) -> float: return self.frame.get_width() def get_frame_shape(self) -> tuple[float, float]: return (self.get_frame_width(), self.get_frame_height()) def get_frame_center(self) -> np.ndarray: return self.frame.get_center() def get_location(self) -> tuple[float, float, float]: return self.frame.get_implied_camera_location() def resize_frame_shape(self, fixed_dimension: bool = False) -> 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. """ frame_height = self.get_frame_height() frame_width = self.get_frame_width() aspect_ratio = self.get_aspect_ratio() if not fixed_dimension: frame_height = frame_width / aspect_ratio else: frame_width = aspect_ratio * frame_height self.frame.set_height(frame_height, stretch=true) self.frame.set_width(frame_width, stretch=true) # Rendering def capture(self, *mobjects: Mobject) -> None: self.clear() self.refresh_uniforms() self.fbo.use() for mobject in mobjects: mobject.render(self.ctx, self.uniforms) if self.window is not None and self.fbo is not self.window_fbo: self.blit(self.fbo, self.window_fbo) def refresh_uniforms(self) -> None: frame = self.frame view_matrix = frame.get_view_matrix() light_pos = self.light_source.get_location() cam_pos = self.frame.get_implied_camera_location() self.uniforms.update( view=tuple(view_matrix.T.flatten()), focal_distance=frame.get_focal_distance() / frame.get_scale(), frame_scale=frame.get_scale(), pixel_size=self.get_pixel_size(), camera_position=tuple(cam_pos), light_position=tuple(light_pos), ) # Mostly just defined so old scenes don't break class ThreeDCamera(Camera): def __init__(self, samples: int = 4, **kwargs): super().__init__(samples=samples, **kwargs)
manim_3b1b/manimlib/shaders/inserts/NOTE.md
There seems to be no analog to #include in C++ for OpenGL shaders. While there are other options for sharing code between shaders, a lot of them aren't great, especially if the goal is to have all the logic for which specific bits of code to share handled in the shader file itself. So the way manim currently works is to replace any line which looks like #INSERT <file_name> with the code from one of the files in this folder. The functions in this file may include declarations of uniforms, so one should not re-declare those in the surrounding context.
manim_3b1b/manimlib/event_handler/__init__.py
from manimlib.event_handler.event_dispatcher import EventDispatcher # This is supposed to be a Singleton # i.e., during runtime there should be only one object of Event Dispatcher EVENT_DISPATCHER = EventDispatcher()
manim_3b1b/manimlib/event_handler/event_dispatcher.py
from __future__ import annotations import numpy as np from manimlib.event_handler.event_listner import EventListener from manimlib.event_handler.event_type import EventType class EventDispatcher(object): def __init__(self): self.event_listners: dict[ EventType, list[EventListener] ] = { event_type: [] for event_type in EventType } self.mouse_point = np.array((0., 0., 0.)) self.mouse_drag_point = np.array((0., 0., 0.)) self.pressed_keys: set[int] = set() self.draggable_object_listners: list[EventListener] = [] def add_listner(self, event_listner: EventListener): assert(isinstance(event_listner, EventListener)) self.event_listners[event_listner.event_type].append(event_listner) return self def remove_listner(self, event_listner: EventListener): assert(isinstance(event_listner, EventListener)) try: while event_listner in self.event_listners[event_listner.event_type]: self.event_listners[event_listner.event_type].remove(event_listner) except: # raise ValueError("Handler is not handling this event, so cannot remove it.") pass return self def dispatch(self, event_type: EventType, **event_data): if event_type == EventType.MouseMotionEvent: self.mouse_point = event_data["point"] elif event_type == EventType.MouseDragEvent: self.mouse_drag_point = event_data["point"] elif event_type == EventType.KeyPressEvent: self.pressed_keys.add(event_data["symbol"]) # Modifiers? elif event_type == EventType.KeyReleaseEvent: self.pressed_keys.difference_update({event_data["symbol"]}) # Modifiers? elif event_type == EventType.MousePressEvent: self.draggable_object_listners = [ listner for listner in self.event_listners[EventType.MouseDragEvent] if listner.mobject.is_point_touching(self.mouse_point) ] elif event_type == EventType.MouseReleaseEvent: self.draggable_object_listners = [] propagate_event = None if event_type == EventType.MouseDragEvent: for listner in self.draggable_object_listners: assert(isinstance(listner, EventListener)) propagate_event = listner.callback(listner.mobject, event_data) if propagate_event is not None and propagate_event is False: return propagate_event elif event_type.value.startswith('mouse'): for listner in self.event_listners[event_type]: if listner.mobject.is_point_touching(self.mouse_point): propagate_event = listner.callback( listner.mobject, event_data) if propagate_event is not None and propagate_event is False: return propagate_event elif event_type.value.startswith('key'): for listner in self.event_listners[event_type]: propagate_event = listner.callback(listner.mobject, event_data) if propagate_event is not None and propagate_event is False: return propagate_event return propagate_event def get_listners_count(self) -> int: return sum([len(value) for key, value in self.event_listners.items()]) def get_mouse_point(self) -> np.ndarray: return self.mouse_point def get_mouse_drag_point(self) -> np.ndarray: return self.mouse_drag_point def is_key_pressed(self, symbol: int) -> bool: return (symbol in self.pressed_keys) __iadd__ = add_listner __isub__ = remove_listner __call__ = dispatch __len__ = get_listners_count
manim_3b1b/manimlib/event_handler/event_listner.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.event_handler.event_type import EventType from manimlib.mobject.mobject import Mobject class EventListener(object): def __init__( self, mobject: Mobject, event_type: EventType, event_callback: Callable[[Mobject, dict[str]]] ): self.mobject = mobject self.event_type = event_type self.callback = event_callback def __eq__(self, o: object) -> bool: return_val = False try: return_val = self.callback == o.callback \ and self.mobject == o.mobject \ and self.event_type == o.event_type except: pass return return_val
manim_3b1b/manimlib/event_handler/event_type.py
from enum import Enum class EventType(Enum): MouseMotionEvent = 'mouse_motion_event' MousePressEvent = 'mouse_press_event' MouseReleaseEvent = 'mouse_release_event' MouseDragEvent = 'mouse_drag_event' MouseScrollEvent = 'mouse_scroll_event' KeyPressEvent = 'key_press_event' KeyReleaseEvent = 'key_release_event'
manim_3b1b/manimlib/animation/rotation.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.constants import ORIGIN, OUT from manimlib.constants import PI, TAU from manimlib.utils.rate_functions import linear from manimlib.utils.rate_functions import smooth from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from typing import Callable from manimlib.mobject.mobject import Mobject class Rotating(Animation): 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.0, rate_func: Callable[[float], float] = linear, suspend_mobject_updating: bool = False, **kwargs ): 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, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: pairs = zip( self.mobject.family_members_with_points(), self.starting_mobject.family_members_with_points(), ) for sm1, sm2 in pairs: for key in sm1.pointlike_data_keys: sm1.data[key][:] = sm2.data[key] self.mobject.rotate( self.rate_func(alpha) * self.angle, axis=self.axis, about_point=self.about_point, about_edge=self.about_edge, ) class Rotate(Rotating): def __init__( self, mobject: Mobject, angle: float = PI, axis: np.ndarray = OUT, run_time: float = 1, rate_func: Callable[[float], float] = smooth, about_edge: np.ndarray = ORIGIN, **kwargs ): super().__init__( mobject, angle, axis, run_time=run_time, rate_func=rate_func, about_edge=about_edge, **kwargs )
manim_3b1b/manimlib/animation/fading.py
from __future__ import annotations import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.transform import Transform from manimlib.constants import ORIGIN from manimlib.mobject.mobject import Group from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.bezier import interpolate from manimlib.utils.rate_functions import there_and_back from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene from manimlib.typing import Vect3 class Fade(Transform): def __init__( self, mobject: Mobject, shift: np.ndarray = ORIGIN, scale: float = 1, **kwargs ): self.shift_vect = shift self.scale_factor = scale super().__init__(mobject, **kwargs) class FadeIn(Fade): def create_target(self) -> Mobject: return self.mobject.copy() def create_starting_mobject(self) -> Mobject: start = super().create_starting_mobject() start.set_opacity(0) start.scale(1.0 / self.scale_factor) start.shift(-self.shift_vect) return start class FadeOut(Fade): def __init__( self, mobject: Mobject, shift: Vect3 = ORIGIN, remover: bool = True, final_alpha_value: float = 0.0, # Put it back in original state when done, **kwargs ): super().__init__( mobject, shift, remover=remover, final_alpha_value=final_alpha_value, **kwargs ) def create_target(self) -> Mobject: result = self.mobject.copy() result.set_opacity(0) result.shift(self.shift_vect) result.scale(self.scale_factor) return result class FadeInFromPoint(FadeIn): def __init__(self, mobject: Mobject, point: Vect3, **kwargs): super().__init__( mobject, shift=mobject.get_center() - point, scale=np.inf, **kwargs, ) class FadeOutToPoint(FadeOut): def __init__(self, mobject: Mobject, point: Vect3, **kwargs): super().__init__( mobject, shift=point - mobject.get_center(), scale=0, **kwargs, ) class FadeTransform(Transform): def __init__( self, mobject: Mobject, target_mobject: Mobject, stretch: bool = True, dim_to_match: int = 1, **kwargs ): self.to_add_on_completion = target_mobject self.stretch = stretch self.dim_to_match = dim_to_match mobject.save_state() super().__init__(Group(mobject, target_mobject.copy()), **kwargs) def begin(self) -> None: self.ending_mobject = self.mobject.copy() Animation.begin(self) # Both 'start' and 'end' consists of the source and target mobjects. # At the start, the traget 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: Mobject, target: Mobject) -> None: source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match) source.set_opacity(0) def get_all_mobjects(self) -> list[Mobject]: return [ self.mobject, self.starting_mobject, self.ending_mobject, ] def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return Animation.get_all_families_zipped(self) def clean_up_from_scene(self, scene: Scene) -> None: 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): def begin(self) -> None: self.mobject[0].align_family(self.mobject[1]) super().begin() def ghost_to(self, source: Mobject, target: Mobject) -> None: for sm0, sm1 in zip(source.get_family(), target.get_family()): super().ghost_to(sm0, sm1) class VFadeIn(Animation): """ VFadeIn and VFadeOut only work for VMobjects, """ def __init__(self, vmobject: VMobject, suspend_mobject_updating: bool = False, **kwargs): super().__init__( vmobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_submobject( self, submob: VMobject, start: VMobject, alpha: float ) -> None: submob.set_stroke( opacity=interpolate(0, start.get_stroke_opacity(), alpha) ) submob.set_fill( opacity=interpolate(0, start.get_fill_opacity(), alpha) ) class VFadeOut(VFadeIn): def __init__( self, vmobject: VMobject, remover: bool = True, final_alpha_value: float = 0.0, **kwargs ): super().__init__( vmobject, remover=remover, final_alpha_value=final_alpha_value, **kwargs ) def interpolate_submobject( self, submob: VMobject, start: VMobject, alpha: float ) -> None: super().interpolate_submobject(submob, start, 1 - alpha) class VFadeInThenOut(VFadeIn): def __init__( self, vmobject: VMobject, rate_func: Callable[[float], float] = there_and_back, remover: bool = True, final_alpha_value: float = 0.5, **kwargs ): super().__init__( vmobject, rate_func=rate_func, remover=remover, final_alpha_value=final_alpha_value, **kwargs )
manim_3b1b/manimlib/animation/composition.py
from __future__ import annotations import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.animation import prepare_animation from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Group from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import remove_list_redundancies from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Optional from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene DEFAULT_LAGGED_START_LAG_RATIO = 0.05 class AnimationGroup(Animation): def __init__(self, *animations: Animation | _AnimationBuilder, run_time: float = -1, # If negative, default to sum of inputed animation runtimes lag_ratio: float = 0.0, group: Optional[Mobject] = None, group_type: Optional[type] = None, **kwargs ): self.animations = [prepare_animation(anim) for anim in animations] self.build_animations_with_timings(lag_ratio) self.max_end_time = max((awt[2] for awt in self.anims_with_timings), default=0) self.run_time = self.max_end_time if run_time < 0 else run_time self.lag_ratio = lag_ratio mobs = remove_list_redundancies([a.mobject for a in self.animations]) if group is not None: self.group = group if group_type is not None: self.group = group_type(*mobs) elif all(isinstance(anim.mobject, VMobject) for anim in animations): self.group = VGroup(*mobs) else: self.group = Group(*mobs) super().__init__( self.group, run_time=self.run_time, lag_ratio=lag_ratio, **kwargs ) def get_all_mobjects(self) -> Mobject: return self.group def begin(self) -> None: self.group.set_animating_status(True) for anim in self.animations: anim.begin() # self.init_run_time() def finish(self) -> None: self.group.set_animating_status(False) for anim in self.animations: anim.finish() def clean_up_from_scene(self, scene: Scene) -> None: for anim in self.animations: anim.clean_up_from_scene(scene) def update_mobjects(self, dt: float) -> None: for anim in self.animations: anim.update_mobjects(dt) def calculate_max_end_time(self) -> None: self.max_end_time = max( (awt[2] for awt in self.anims_with_timings), default=0, ) if self.run_time < 0: self.run_time = self.max_end_time def build_animations_with_timings(self, lag_ratio: float) -> None: """ Creates a list of triplets of the form (anim, start_time, end_time) """ self.anims_with_timings = [] curr_time = 0 for anim in self.animations: start_time = curr_time end_time = start_time + anim.get_run_time() self.anims_with_timings.append( (anim, start_time, end_time) ) # Start time of next animation is based on the lag_ratio curr_time = interpolate( start_time, end_time, lag_ratio ) def interpolate(self, alpha: float) -> None: # Note, if the run_time of AnimationGroup has been # set to something other than its default, these # times might not correspond to actual times, # e.g. of the surrounding scene. Instead they'd # be a rescaled version. But that's okay! time = alpha * self.max_end_time for anim, start_time, end_time in self.anims_with_timings: anim_time = end_time - start_time if anim_time == 0: sub_alpha = 0 else: sub_alpha = clip((time - start_time) / anim_time, 0, 1) anim.interpolate(sub_alpha) class Succession(AnimationGroup): def __init__( self, *animations: Animation, lag_ratio: float = 1.0, **kwargs ): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) def begin(self) -> None: assert(len(self.animations) > 0) self.active_animation = self.animations[0] self.active_animation.begin() def finish(self) -> None: self.active_animation.finish() def update_mobjects(self, dt: float) -> None: self.active_animation.update_mobjects(dt) def interpolate(self, alpha: float) -> None: index, subalpha = integer_interpolate( 0, len(self.animations), alpha ) animation = self.animations[index] if animation is not self.active_animation: self.active_animation.finish() animation.begin() self.active_animation = animation animation.interpolate(subalpha) class LaggedStart(AnimationGroup): def __init__( self, *animations, lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO, **kwargs ): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) class LaggedStartMap(LaggedStart): def __init__( self, anim_func: Callable[[Mobject], Animation], group: Mobject, run_time: float = 2.0, lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO, **kwargs ): anim_kwargs = dict(kwargs) anim_kwargs.pop("lag_ratio", None) super().__init__( *(anim_func(submob, **anim_kwargs) for submob in group), run_time=run_time, lag_ratio=lag_ratio, )
manim_3b1b/manimlib/animation/__init__.py
manim_3b1b/manimlib/animation/transform_matching_parts.py
from __future__ import annotations import itertools as it from difflib import SequenceMatcher from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeInFromPoint from manimlib.animation.fading import FadeOutToPoint from manimlib.animation.transform import Transform from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.svg.string_mobject import StringMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.scene.scene import Scene class TransformMatchingParts(AnimationGroup): def __init__( self, source: Mobject, target: Mobject, matched_pairs: Iterable[tuple[Mobject, Mobject]] = [], match_animation: type = Transform, mismatch_animation: type = Transform, run_time: float = 2, lag_ratio: float = 0, **kwargs, ): self.source = source self.target = target self.match_animation = match_animation self.mismatch_animation = mismatch_animation self.anim_config = dict(**kwargs) # We will progressively build up a list of transforms # from pieces in source to those in target. These # two lists keep track of which pieces are accounted # for so far self.source_pieces = source.family_members_with_points() self.target_pieces = target.family_members_with_points() self.anims = [] for pair in matched_pairs: self.add_transform(*pair) # Match any pairs with the same shape for pair in self.find_pairs_with_matching_shapes(self.source_pieces, self.target_pieces): self.add_transform(*pair) # Finally, account for mismatches for source_piece in self.source_pieces: if any([source_piece in anim.mobject.get_family() for anim in self.anims]): continue self.anims.append(FadeOutToPoint( source_piece, target.get_center(), **self.anim_config )) for target_piece in self.target_pieces: if any([target_piece in anim.mobject.get_family() for anim in self.anims]): continue self.anims.append(FadeInFromPoint( target_piece, source.get_center(), **self.anim_config )) super().__init__( *self.anims, run_time=run_time, lag_ratio=lag_ratio, ) def add_transform( self, source: Mobject, target: Mobject, ): new_source_pieces = source.family_members_with_points() new_target_pieces = target.family_members_with_points() if len(new_source_pieces) == 0 or len(new_target_pieces) == 0: # Don't animate null sorces or null targets return source_is_new = all(char in self.source_pieces for char in new_source_pieces) target_is_new = all(char in self.target_pieces for char in new_target_pieces) if not source_is_new or not target_is_new: return transform_type = self.mismatch_animation if source.has_same_shape_as(target): transform_type = self.match_animation self.anims.append(transform_type(source, target, **self.anim_config)) for char in new_source_pieces: self.source_pieces.remove(char) for char in new_target_pieces: self.target_pieces.remove(char) def find_pairs_with_matching_shapes( self, chars1: list[Mobject], chars2: list[Mobject] ) -> list[tuple[Mobject, Mobject]]: result = [] for char1, char2 in it.product(chars1, chars2): if char1.has_same_shape_as(char2): result.append((char1, char2)) return result def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) scene.remove(self.mobject) scene.add(self.target) class TransformMatchingShapes(TransformMatchingParts): """Alias for TransformMatchingParts""" pass class TransformMatchingStrings(TransformMatchingParts): def __init__( self, source: StringMobject, target: StringMobject, matched_keys: Iterable[str] = [], key_map: dict[str, str] = dict(), matched_pairs: Iterable[tuple[VMobject, VMobject]] = [], **kwargs, ): matched_pairs = [ *matched_pairs, *self.matching_blocks(source, target, matched_keys, key_map), ] super().__init__( source, target, matched_pairs=matched_pairs, **kwargs, ) def matching_blocks( self, source: StringMobject, target: StringMobject, matched_keys: Iterable[str], key_map: dict[str, str] ) -> list[tuple[VMobject, VMobject]]: syms1 = source.get_symbol_substrings() syms2 = target.get_symbol_substrings() counts1 = list(map(source.substr_to_path_count, syms1)) counts2 = list(map(target.substr_to_path_count, syms2)) # Start with user specified matches blocks = [(source[key], target[key]) for key in matched_keys] blocks += [(source[key1], target[key2]) for key1, key2 in key_map.items()] # Nullify any intersections with those matches in the two symbol lists for sub_source, sub_target in blocks: for i in range(len(syms1)): if source[i] in sub_source.family_members_with_points(): syms1[i] = "Null1" for j in range(len(syms2)): if target[j] in sub_target.family_members_with_points(): syms2[j] = "Null2" # Group together longest matching substrings while True: matcher = SequenceMatcher(None, syms1, syms2) match = matcher.find_longest_match(0, len(syms1), 0, len(syms2)) if match.size == 0: break i1 = sum(counts1[:match.a]) i2 = sum(counts2[:match.b]) size = sum(counts1[match.a:match.a + match.size]) blocks.append((source[i1:i1 + size], target[i2:i2 + size])) for i in range(match.size): syms1[match.a + i] = "Null1" syms2[match.b + i] = "Null2" return blocks class TransformMatchingTex(TransformMatchingStrings): """Alias for TransformMatchingStrings""" pass
manim_3b1b/manimlib/animation/creation.py
from __future__ import annotations from abc import ABC, abstractmethod import numpy as np from manimlib.animation.animation import Animation from manimlib.constants import WHITE from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.rate_functions import linear from manimlib.utils.rate_functions import double_smooth from manimlib.utils.rate_functions import smooth from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene from manimlib.typing import ManimColor class ShowPartial(Animation, ABC): """ Abstract class for ShowCreation and ShowPassingFlash """ def __init__(self, mobject: Mobject, should_match_start: bool = False, **kwargs): self.should_match_start = should_match_start super().__init__(mobject, **kwargs) def interpolate_submobject( self, submob: VMobject, start_submob: VMobject, alpha: float ) -> None: submob.pointwise_become_partial( start_submob, *self.get_bounds(alpha) ) @abstractmethod def get_bounds(self, alpha: float) -> tuple[float, float]: raise Exception("Not Implemented") class ShowCreation(ShowPartial): def __init__(self, mobject: Mobject, lag_ratio: float = 1.0, **kwargs): super().__init__(mobject, lag_ratio=lag_ratio, **kwargs) def get_bounds(self, alpha: float) -> tuple[float, float]: return (0, alpha) class Uncreate(ShowCreation): def __init__( self, mobject: Mobject, rate_func: Callable[[float], float] = lambda t: smooth(1 - t), remover: bool = True, should_match_start: bool = True, **kwargs, ): super().__init__( mobject, rate_func=rate_func, remover=remover, should_match_start=should_match_start, **kwargs, ) class DrawBorderThenFill(Animation): def __init__( self, vmobject: VMobject, run_time: float = 2.0, rate_func: Callable[[float], float] = double_smooth, stroke_width: float = 2.0, stroke_color: ManimColor = None, draw_border_animation_config: dict = {}, fill_animation_config: dict = {}, **kwargs ): assert(isinstance(vmobject, VMobject)) self.sm_to_index = {hash(sm): 0 for sm in vmobject.get_family()} self.stroke_width = stroke_width self.stroke_color = stroke_color self.draw_border_animation_config = draw_border_animation_config self.fill_animation_config = fill_animation_config super().__init__( vmobject, run_time=run_time, rate_func=rate_func, **kwargs ) self.mobject = vmobject def begin(self) -> None: self.mobject.set_animating_status(True) self.outline = self.get_outline() super().begin() self.mobject.match_style(self.outline) def finish(self) -> None: super().finish() self.mobject.refresh_joint_products() def get_outline(self) -> VMobject: outline = self.mobject.copy() outline.set_fill(opacity=0) for sm in outline.family_members_with_points(): sm.set_stroke( color=self.stroke_color or sm.get_stroke_color(), width=self.stroke_width, ) return outline def get_all_mobjects(self) -> list[Mobject]: return [*super().get_all_mobjects(), self.outline] def interpolate_submobject( self, submob: VMobject, start: VMobject, outline: VMobject, alpha: float ) -> None: index, subalpha = integer_interpolate(0, 2, alpha) if index == 1 and self.sm_to_index[hash(submob)] == 0: # First time crossing over submob.set_data(outline.data) self.sm_to_index[hash(submob)] = 1 if index == 0: submob.pointwise_become_partial(outline, 0, subalpha) else: submob.interpolate(outline, start, subalpha) submob.note_changed_stroke() submob.note_changed_fill() class Write(DrawBorderThenFill): def __init__( self, vmobject: VMobject, run_time: float = -1, # If negative, this will be reassigned lag_ratio: float = -1, # If negative, this will be reassigned rate_func: Callable[[float], float] = linear, stroke_color: ManimColor = WHITE, **kwargs ): family_size = len(vmobject.family_members_with_points()) super().__init__( vmobject, run_time=self.compute_run_time(family_size, run_time), lag_ratio=self.compute_lag_ratio(family_size, lag_ratio), rate_func=rate_func, stroke_color=stroke_color, **kwargs ) def compute_run_time(self, family_size: int, run_time: float): if run_time < 0: return 1 if family_size < 15 else 2 return run_time def compute_lag_ratio(self, family_size: int, lag_ratio: float): if lag_ratio < 0: return min(4.0 / (family_size + 1.0), 0.2) return lag_ratio class ShowIncreasingSubsets(Animation): def __init__( self, group: Mobject, int_func: Callable[[float], float] = np.round, suspend_mobject_updating: bool = False, **kwargs ): self.all_submobs = list(group.submobjects) self.int_func = int_func super().__init__( group, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: n_submobs = len(self.all_submobs) alpha = self.rate_func(alpha) index = int(self.int_func(alpha * n_submobs)) self.update_submobject_list(index) def update_submobject_list(self, index: int) -> None: self.mobject.set_submobjects(self.all_submobs[:index]) class ShowSubmobjectsOneByOne(ShowIncreasingSubsets): def __init__( self, group: Mobject, int_func: Callable[[float], float] = np.ceil, **kwargs ): super().__init__(group, int_func=int_func, **kwargs) def update_submobject_list(self, index: int) -> None: index = int(clip(index, 0, len(self.all_submobs) - 1)) if index == 0: self.mobject.set_submobjects([]) else: self.mobject.set_submobjects([self.all_submobs[index - 1]]) class AddTextWordByWord(ShowIncreasingSubsets): def __init__( self, string_mobject: StringMobject, time_per_word: float = 0.2, run_time: float = -1.0, # If negative, it will be recomputed with time_per_word rate_func: Callable[[float], float] = linear, **kwargs ): assert isinstance(string_mobject, StringMobject) grouped_mobject = string_mobject.build_groups() if run_time < 0: run_time = time_per_word * len(grouped_mobject) super().__init__( grouped_mobject, run_time=run_time, rate_func=rate_func, **kwargs ) self.string_mobject = string_mobject def clean_up_from_scene(self, scene: Scene) -> None: scene.remove(self.mobject) if not self.is_remover(): scene.add(self.string_mobject)
manim_3b1b/manimlib/animation/movement.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.utils.rate_functions import linear from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VMobject class Homotopy(Animation): apply_function_config: dict = dict() def __init__( self, homotopy: Callable[[float, float, float, float], Sequence[float]], mobject: Mobject, run_time: float = 3.0, **kwargs ): """ Homotopy is a function from (x, y, z, t) to (x', y', z') """ self.homotopy = homotopy super().__init__(mobject, run_time=run_time, **kwargs) def function_at_time_t(self, t: float) -> Callable[[np.ndarray], Sequence[float]]: def result(p): return self.homotopy(*p, t) return result def interpolate_submobject( self, submob: Mobject, start: Mobject, alpha: float ) -> None: submob.match_points(start) submob.apply_function( self.function_at_time_t(alpha), **self.apply_function_config ) class SmoothedVectorizedHomotopy(Homotopy): apply_function_config: dict = dict(make_smooth=True) class ComplexHomotopy(Homotopy): def __init__( self, complex_homotopy: Callable[[complex, float], complex], mobject: Mobject, **kwargs ): """ Given a function form (z, t) -> w, where z and w are complex numbers and t is time, this animates the state over time """ def homotopy(x, y, z, t): 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 | None = None, suspend_mobject_updating: bool = False, rate_func: Callable[[float], float] = linear, run_time: float =3.0, **kwargs ): self.function = function self.virtual_time = virtual_time or run_time super().__init__( mobject, rate_func=rate_func, run_time=run_time, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: if hasattr(self, "last_alpha"): dt = self.virtual_time * (alpha - self.last_alpha) self.mobject.apply_function( lambda p: p + dt * self.function(p) ) self.last_alpha = alpha class MoveAlongPath(Animation): def __init__( self, mobject: Mobject, path: VMobject, suspend_mobject_updating: bool = False, **kwargs ): self.path = path super().__init__(mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs) def interpolate_mobject(self, alpha: float) -> None: point = self.path.quick_point_from_proportion(self.rate_func(alpha)) self.mobject.move_to(point)
manim_3b1b/manimlib/animation/update.py
from __future__ import annotations from manimlib.animation.animation import Animation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.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], Mobject | None], suspend_mobject_updating: bool = False, **kwargs ): 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) class UpdateFromAlphaFunc(Animation): def __init__( self, mobject: Mobject, update_function: Callable[[Mobject, float], Mobject | None], suspend_mobject_updating: bool = False, **kwargs ): 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, alpha) class MaintainPositionRelativeTo(Animation): def __init__( self, mobject: Mobject, tracked_mobject: Mobject, **kwargs ): self.tracked_mobject = tracked_mobject self.diff = 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)
manim_3b1b/manimlib/animation/growing.py
from __future__ import annotations from manimlib.animation.transform import Transform from manimlib.constants import PI from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from manimlib.mobject.geometry import Arrow from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor class GrowFromPoint(Transform): def __init__( self, mobject: Mobject, point: np.ndarray, point_color: ManimColor = None, **kwargs ): self.point = point self.point_color = point_color super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: return self.mobject.copy() def create_starting_mobject(self) -> Mobject: start = super().create_starting_mobject() start.scale(0) start.move_to(self.point) if self.point_color is not None: start.set_color(self.point_color) return start class GrowFromCenter(GrowFromPoint): def __init__(self, mobject: Mobject, **kwargs): point = mobject.get_center() super().__init__(mobject, point, **kwargs) class GrowFromEdge(GrowFromPoint): def __init__(self, mobject: Mobject, edge: np.ndarray, **kwargs): point = mobject.get_bounding_box_point(edge) super().__init__(mobject, point, **kwargs) class GrowArrow(GrowFromPoint): def __init__(self, arrow: Arrow, **kwargs): point = arrow.get_start() super().__init__(arrow, point, **kwargs)
manim_3b1b/manimlib/animation/numbers.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.mobject.numbers import DecimalNumber from manimlib.utils.bezier import interpolate from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable class ChangingDecimal(Animation): def __init__( self, decimal_mob: DecimalNumber, number_update_func: Callable[[float], float], suspend_mobject_updating: bool = False, **kwargs ): assert(isinstance(decimal_mob, DecimalNumber)) self.number_update_func = number_update_func super().__init__( decimal_mob, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) self.mobject = decimal_mob def interpolate_mobject(self, alpha: float) -> None: self.mobject.set_value( self.number_update_func(alpha) ) class ChangeDecimalToValue(ChangingDecimal): def __init__( self, decimal_mob: DecimalNumber, target_number: float | complex, **kwargs ): start_number = decimal_mob.number super().__init__( decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs ) class CountInFrom(ChangingDecimal): def __init__( self, decimal_mob: DecimalNumber, source_number: float | complex = 0, **kwargs ): start_number = decimal_mob.number super().__init__( decimal_mob, lambda a: interpolate(source_number, start_number, a), **kwargs )
manim_3b1b/manimlib/animation/specialized.py
from __future__ import annotations from manimlib.animation.composition import LaggedStart from manimlib.animation.transform import Restore from manimlib.constants import BLACK, WHITE from manimlib.mobject.geometry import Circle from manimlib.mobject.types.vectorized_mobject import VGroup from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from manimlib.typing import ManimColor class Broadcast(LaggedStart): def __init__( self, focal_point: np.ndarray, small_radius: float = 0.0, big_radius: float = 5.0, n_circles: int = 5, start_stroke_width: float = 8.0, color: ManimColor = WHITE, run_time: float = 3.0, lag_ratio: float = 0.2, remover: bool = True, **kwargs ): self.focal_point = focal_point self.small_radius = small_radius self.big_radius = big_radius self.n_circles = n_circles self.start_stroke_width = start_stroke_width self.color = color circles = VGroup() for x in range(n_circles): circle = Circle( radius=big_radius, stroke_color=BLACK, stroke_width=0, ) circle.add_updater(lambda c: c.move_to(focal_point)) circle.save_state() circle.set_width(small_radius * 2) circle.set_stroke(color, start_stroke_width) circles.add(circle) super().__init__( *map(Restore, circles), run_time=run_time, lag_ratio=lag_ratio, remover=remover, **kwargs )
manim_3b1b/manimlib/animation/transform.py
from __future__ import annotations import inspect import numpy as np from manimlib.animation.animation import Animation from manimlib.constants import DEGREES from manimlib.constants import OUT from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.utils.paths import path_along_arc from manimlib.utils.paths import straight_path from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable import numpy.typing as npt from manimlib.scene.scene import Scene from manimlib.typing import ManimColor class Transform(Animation): replace_mobject_with_target_in_scene: bool = False def __init__( self, mobject: Mobject, target_mobject: Mobject | None = None, path_arc: float = 0.0, path_arc_axis: np.ndarray = OUT, path_func: Callable | None = None, **kwargs ): self.target_mobject = target_mobject self.path_arc = path_arc self.path_arc_axis = path_arc_axis self.path_func = path_func super().__init__(mobject, **kwargs) self.init_path_func() def init_path_func(self) -> None: if self.path_func is not None: return elif self.path_arc == 0: self.path_func = straight_path else: self.path_func = path_along_arc( self.path_arc, self.path_arc_axis, ) def begin(self) -> None: self.target_mobject = self.create_target() self.check_target_mobject_validity() if self.mobject.is_aligned_with(self.target_mobject): self.target_copy = self.target_mobject else: # Use a copy of target_mobject for the align_data_and_family # call so that the actual target_mobject stays # preserved, since calling align_data will potentially # change the structure of both arguments self.target_copy = self.target_mobject.copy() self.mobject.align_data_and_family(self.target_copy) super().begin() if not self.mobject.has_updaters: self.mobject.lock_matching_data( self.starting_mobject, self.target_copy, ) def finish(self) -> None: super().finish() self.mobject.unlock_data() def create_target(self) -> Mobject: # Has no meaningful effect here, but may be useful # in subclasses return self.target_mobject def check_target_mobject_validity(self) -> None: if self.target_mobject is None: raise Exception( f"{self.__class__.__name__}.create_target not properly implemented" ) def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) if self.replace_mobject_with_target_in_scene: scene.remove(self.mobject) scene.add(self.target_mobject) def update_config(self, **kwargs) -> None: Animation.update_config(self, **kwargs) if "path_arc" in kwargs: self.path_func = path_along_arc( kwargs["path_arc"], kwargs.get("path_arc_axis", OUT) ) def get_all_mobjects(self) -> list[Mobject]: return [ self.mobject, self.starting_mobject, self.target_mobject, self.target_copy, ] def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return zip(*[ mob.get_family() for mob in [ self.mobject, self.starting_mobject, self.target_copy, ] ]) def interpolate_submobject( self, submob: Mobject, start: Mobject, target_copy: Mobject, alpha: float ): submob.interpolate(start, target_copy, alpha, self.path_func) return self class ReplacementTransform(Transform): replace_mobject_with_target_in_scene: bool = True class TransformFromCopy(Transform): replace_mobject_with_target_in_scene: bool = True def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs): super().__init__(mobject.copy(), target_mobject, **kwargs) class MoveToTarget(Transform): def __init__(self, mobject: Mobject, **kwargs): 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 Exception( "MoveToTarget called on mobject without attribute 'target'" ) class _MethodAnimation(MoveToTarget): def __init__(self, mobject: Mobject, methods: list[Callable], **kwargs): self.methods = methods super().__init__(mobject, **kwargs) class ApplyMethod(Transform): def __init__(self, method: Callable, *args, **kwargs): """ method is a method of Mobject, *args are arguments for that method. Key word arguments should be passed in as the last arg, as a dict, since **kwargs is for configuration of the transform itself Relies on the fact that mobject methods return the mobject """ 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 Exception( "Whoops, looks like you accidentally invoked " "the method you want to animate" ) assert(isinstance(method.__self__, Mobject)) 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): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, run_time: float = 3.0, **kwargs ): super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs) class ApplyPointwiseFunctionToCenter(Transform): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, **kwargs ): self.function = function super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: return self.mobject.copy().move_to(self.function(self.mobject.get_center())) class FadeToColor(ApplyMethod): def __init__( self, mobject: Mobject, color: ManimColor, **kwargs ): super().__init__(mobject.set_color, color, **kwargs) class ScaleInPlace(ApplyMethod): def __init__( self, mobject: Mobject, scale_factor: npt.ArrayLike, **kwargs ): super().__init__(mobject.scale, scale_factor, **kwargs) class ShrinkToCenter(ScaleInPlace): def __init__(self, mobject: Mobject, **kwargs): super().__init__(mobject, 0, **kwargs) class Restore(Transform): def __init__(self, mobject: Mobject, **kwargs): if not hasattr(mobject, "saved_state") or mobject.saved_state is None: raise Exception("Trying to restore without having saved") super().__init__(mobject, mobject.saved_state, **kwargs) class ApplyFunction(Transform): def __init__( self, function: Callable[[Mobject], Mobject], mobject: Mobject, **kwargs ): self.function = function super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: target = self.function(self.mobject.copy()) if not isinstance(target, Mobject): raise Exception("Functions passed to ApplyFunction must return object of type Mobject") return target class ApplyMatrix(ApplyPointwiseFunction): def __init__( self, matrix: npt.ArrayLike, mobject: Mobject, **kwargs ): matrix = self.initialize_matrix(matrix) def func(p): return np.dot(p, matrix.T) super().__init__(func, mobject, **kwargs) def initialize_matrix(self, matrix: npt.ArrayLike) -> 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 Exception("Matrix has bad dimensions") return matrix class ApplyComplexFunction(ApplyMethod): def __init__( self, function: Callable[[complex], complex], mobject: Mobject, **kwargs ): 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): def __init__(self, *mobjects: Mobject, path_arc=90 * DEGREES, **kwargs): super().__init__(Group(*mobjects), path_arc=path_arc, **kwargs) def create_target(self) -> Mobject: group = self.mobject target = group.copy() cycled_targets = [target[-1], *target[:-1]] for m1, m2 in zip(cycled_targets, group): m1.move_to(m2) return target class Swap(CyclicReplace): """Alternate name for CyclicReplace""" pass
manim_3b1b/manimlib/animation/animation.py
from __future__ import annotations from copy import deepcopy from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Mobject from manimlib.utils.rate_functions import smooth from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.scene.scene import Scene DEFAULT_ANIMATION_RUN_TIME = 1.0 DEFAULT_ANIMATION_LAG_RATIO = 0 class Animation(object): def __init__( self, mobject: Mobject, run_time: float = DEFAULT_ANIMATION_RUN_TIME, # Tuple of times, between which the animation will run time_span: tuple[float, float] | None = None, # If 0, the animation is applied to all submobjects at the same time # If 1, it is applied to each successively. # If 0 < lag_ratio < 1, its applied to each with lagged start times lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO, rate_func: Callable[[float], float] = smooth, name: str = "", # Does this animation add or remove a mobject form the screen remover: bool = False, # What to enter into the update function upon completion final_alpha_value: float = 1.0, suspend_mobject_updating: bool = True, ): self.mobject = mobject self.run_time = run_time self.time_span = time_span self.rate_func = rate_func self.name = name or self.__class__.__name__ + str(self.mobject) self.remover = remover self.final_alpha_value = final_alpha_value self.lag_ratio = lag_ratio self.suspend_mobject_updating = suspend_mobject_updating assert(isinstance(mobject, Mobject)) def __str__(self) -> str: return self.name def begin(self) -> None: # This is called right as an animation is being # played. As much initialization as possible, # especially any mobject copying, should live in # this method if self.time_span is not None: start, end = self.time_span self.run_time = max(end, self.run_time) self.rate_func = squish_rate_func( self.rate_func, start / self.run_time, end / self.run_time, ) self.mobject.set_animating_status(True) self.starting_mobject = self.create_starting_mobject() if self.suspend_mobject_updating: # All calls to self.mobject's internal updaters # during the animation, either from this Animation # or from the surrounding scene, should do nothing. # It is, however, okay and desirable to call # the internal updaters of self.starting_mobject, # or any others among self.get_all_mobjects() self.mobject_was_updating = not self.mobject.updating_suspended self.mobject.suspend_updating() self.families = list(self.get_all_families_zipped()) self.interpolate(0) def finish(self) -> None: self.interpolate(self.final_alpha_value) self.mobject.set_animating_status(False) if self.suspend_mobject_updating and self.mobject_was_updating: self.mobject.resume_updating() def clean_up_from_scene(self, scene: Scene) -> None: if self.is_remover(): scene.remove(self.mobject) def create_starting_mobject(self) -> Mobject: # Keep track of where the mobject starts return self.mobject.copy() def get_all_mobjects(self) -> tuple[Mobject, Mobject]: """ Ordering must match the ording of arguments to interpolate_submobject """ return self.mobject, self.starting_mobject def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return zip(*[ mob.get_family() for mob in self.get_all_mobjects() ]) def update_mobjects(self, dt: float) -> None: """ Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject. """ for mob in self.get_all_mobjects_to_update(): mob.update(dt) def get_all_mobjects_to_update(self) -> list[Mobject]: # The surrounding scene typically handles # updating of self.mobject. Besides, in # most cases its updating is suspended anyway return list(filter( lambda m: m is not self.mobject, self.get_all_mobjects() )) def copy(self): return deepcopy(self) def update_rate_info( self, run_time: float | None = None, rate_func: Callable[[float], float] | None = None, lag_ratio: float | None = None, ): self.run_time = run_time or self.run_time self.rate_func = rate_func or self.rate_func self.lag_ratio = lag_ratio or self.lag_ratio return self # Methods for interpolation, the mean of an Animation def interpolate(self, alpha: float) -> None: self.interpolate_mobject(alpha) def update(self, alpha: float) -> None: """ This method shouldn't exist, but it's here to keep many old scenes from breaking """ self.interpolate(alpha) def interpolate_mobject(self, alpha: float) -> None: for i, mobs in enumerate(self.families): sub_alpha = self.get_sub_alpha(alpha, i, len(self.families)) self.interpolate_submobject(*mobs, sub_alpha) def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float ): # Typically ipmlemented by subclass pass def get_sub_alpha( self, alpha: float, index: int, num_submobjects: int ) -> float: # TODO, make this more understanable, and/or combine # its functionality with AnimationGroup's method # build_animations_with_timings lag_ratio = self.lag_ratio full_length = (num_submobjects - 1) * lag_ratio + 1 value = alpha * full_length lower = index * lag_ratio raw_sub_alpha = clip((value - lower), 0, 1) return self.rate_func(raw_sub_alpha) # Getters and setters def set_run_time(self, run_time: float): self.run_time = run_time return self def get_run_time(self) -> float: if self.time_span: return max(self.run_time, self.time_span[1]) return self.run_time def set_rate_func(self, rate_func: Callable[[float], float]): self.rate_func = rate_func return self def get_rate_func(self) -> Callable[[float], float]: return self.rate_func def set_name(self, name: str): self.name = name return self def is_remover(self) -> bool: return self.remover def prepare_animation(anim: Animation | _AnimationBuilder): if isinstance(anim, _AnimationBuilder): return anim.build() if isinstance(anim, Animation): return anim raise TypeError(f"Object {anim} cannot be converted to an animation")
manim_3b1b/manimlib/animation/indication.py
from __future__ import annotations import math from os import remove import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.composition import AnimationGroup from manimlib.animation.composition import Succession from manimlib.animation.creation import ShowCreation from manimlib.animation.creation import ShowPartial from manimlib.animation.fading import FadeOut from manimlib.animation.fading import FadeIn from manimlib.animation.movement import Homotopy from manimlib.animation.transform import Transform from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import ORIGIN, RIGHT, UP from manimlib.constants import SMALL_BUFF from manimlib.constants import DEGREES from manimlib.constants import TAU from manimlib.constants import GREY, YELLOW from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.shape_matchers import SurroundingRectangle from manimlib.mobject.shape_matchers import Underline from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.bezier import interpolate from manimlib.utils.rate_functions import smooth from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from manimlib.utils.rate_functions import wiggle from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor from manimlib.mobject.mobject import Mobject class FocusOn(Transform): def __init__( self, focus_point: np.ndarray | Mobject, opacity: float = 0.2, color: ManimColor = GREY, run_time: float = 2, remover: bool = True, **kwargs ): self.focus_point = focus_point self.opacity = opacity self.color = color # Initialize with blank mobject, while create_target # and create_starting_mobject handle the meat super().__init__(VMobject(), 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 def create_starting_mobject(self) -> Dot: return Dot( radius=FRAME_X_RADIUS + FRAME_Y_RADIUS, stroke_width=0, fill_color=self.color, fill_opacity=0, ) class Indicate(Transform): def __init__( self, mobject: Mobject, scale_factor: float = 1.2, color: ManimColor = YELLOW, rate_func: Callable[[float], float] = there_and_back, **kwargs ): self.scale_factor = scale_factor self.color = color super().__init__(mobject, rate_func=rate_func, **kwargs) def create_target(self) -> Mobject: target = self.mobject.copy() target.scale(self.scale_factor) target.set_color(self.color) return target class Flash(AnimationGroup): def __init__( self, point: np.ndarray | Mobject, color: ManimColor = YELLOW, line_length: float = 0.2, num_lines: int = 12, flash_radius: float = 0.3, line_stroke_width: float = 3.0, run_time: float = 1.0, **kwargs ): self.point = 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.lines = self.create_lines() animations = self.create_line_anims() super().__init__( *animations, group=self.lines, run_time=run_time, **kwargs, ) def create_lines(self) -> VGroup: lines = VGroup() for angle in np.arange(0, TAU, TAU / self.num_lines): line = Line(ORIGIN, self.line_length * RIGHT) line.shift((self.flash_radius - self.line_length) * RIGHT) line.rotate(angle, about_point=ORIGIN) lines.add(line) lines.set_stroke( color=self.color, width=self.line_stroke_width ) lines.add_updater(lambda l: l.move_to(self.point)) return lines def create_line_anims(self) -> list[Animation]: return [ ShowCreationThenDestruction(line) for line in self.lines ] class CircleIndicate(Transform): def __init__( self, mobject: Mobject, scale_factor: float = 1.2, rate_func: Callable[[float], float] = there_and_back, stroke_color: ManimColor = YELLOW, stroke_width: float = 3.0, remover: bool = True, **kwargs ): circle = Circle(stroke_color=stroke_color, stroke_width=stroke_width) circle.surround(mobject) pre_circle = circle.copy().set_stroke(width=0) pre_circle.scale(1 / scale_factor) super().__init__( pre_circle, circle, rate_func=rate_func, remover=remover, **kwargs ) class ShowPassingFlash(ShowPartial): def __init__( self, mobject: Mobject, time_width: float = 0.1, remover: bool = True, **kwargs ): self.time_width = time_width super().__init__( mobject, remover=remover, **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 finish(self) -> None: super().finish() for submob, start in self.get_all_families_zipped(): submob.pointwise_become_partial(start, 0, 1) class VShowPassingFlash(Animation): def __init__( self, vmobject: VMobject, time_width: float = 0.3, taper_width: float = 0.05, remover: bool = True, **kwargs ): self.time_width = time_width self.taper_width = taper_width super().__init__(vmobject, remover=remover, **kwargs) self.mobject = vmobject def taper_kernel(self, x): if x < self.taper_width: return x elif x > 1 - self.taper_width: return 1.0 - x return 1.0 def begin(self) -> None: # Compute an array of stroke widths for each submobject # which tapers out at either end self.submob_to_widths = dict() for sm in self.mobject.get_family(): widths = sm.get_stroke_widths() self.submob_to_widths[hash(sm)] = np.array([ width * self.taper_kernel(x) for width, x in zip(widths, np.linspace(0, 1, len(widths))) ]) super().begin() def interpolate_submobject( self, submobject: VMobject, starting_sumobject: None, alpha: float ) -> None: widths = self.submob_to_widths[hash(submobject)] # Create a gaussian such that 3 sigmas out on either side # will equals time_width tw = self.time_width sigma = tw / 6 mu = interpolate(-tw / 2, 1 + tw / 2, alpha) xs = np.linspace(0, 1, len(widths)) zs = (xs - mu) / sigma gaussian = np.exp(-0.5 * zs * zs) gaussian[abs(xs - mu) > 3 * sigma] = 0 submobject.set_stroke(width=widths * gaussian) def finish(self) -> None: super().finish() for submob, start in self.get_all_families_zipped(): submob.match_style(start) class FlashAround(VShowPassingFlash): def __init__( self, mobject: Mobject, time_width: float = 1.0, taper_width: float = 0.0, stroke_width: float = 4.0, color: ManimColor = YELLOW, buff: float = SMALL_BUFF, n_inserted_curves: int = 100, **kwargs ): path = self.get_path(mobject, buff) if mobject.is_fixed_in_frame(): path.fix_in_frame() path.insert_n_curves(n_inserted_curves) path.set_points(path.get_points_without_null_curves()) path.set_stroke(color, stroke_width) super().__init__(path, time_width=time_width, taper_width=taper_width, **kwargs) def get_path(self, mobject: Mobject, buff: float) -> SurroundingRectangle: return SurroundingRectangle(mobject, buff=buff) class FlashUnder(FlashAround): def get_path(self, mobject: Mobject, buff: float) -> Underline: return Underline(mobject, buff=buff, stretch_factor=1.0) class ShowCreationThenDestruction(ShowPassingFlash): def __init__(self, vmobject: VMobject, time_width: float = 2.0, **kwargs): super().__init__(vmobject, time_width=time_width, **kwargs) class ShowCreationThenFadeOut(Succession): def __init__(self, mobject: Mobject, remover: bool = True, **kwargs): super().__init__( ShowCreation(mobject), FadeOut(mobject), remover=remover, **kwargs ) class AnimationOnSurroundingRectangle(AnimationGroup): RectAnimationType: type = Animation def __init__( self, mobject: Mobject, stroke_width: float = 2.0, stroke_color: ManimColor = YELLOW, buff: float = SMALL_BUFF, **kwargs ): rect = SurroundingRectangle( mobject, stroke_width=stroke_width, stroke_color=stroke_color, buff=buff, ) rect.add_updater(lambda r: r.move_to(mobject)) super().__init__(self.RectAnimationType(rect, **kwargs)) class ShowPassingFlashAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowPassingFlash class ShowCreationThenDestructionAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowCreationThenDestruction class ShowCreationThenFadeAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowCreationThenFadeOut class ApplyWave(Homotopy): def __init__( self, mobject: Mobject, direction: np.ndarray = UP, amplitude: float = 0.2, run_time: float = 1.0, **kwargs ): left_x = mobject.get_left()[0] right_x = mobject.get_right()[0] vect = amplitude * direction def homotopy(x, y, z, t): alpha = (x - left_x) / (right_x - left_x) power = np.exp(2.0 * (alpha - 0.5)) nudge = there_and_back(t**power) return np.array([x, y, z]) + nudge * vect super().__init__(homotopy, mobject, **kwargs) class WiggleOutThenIn(Animation): def __init__( self, mobject: Mobject, scale_value: float = 1.1, rotation_angle: float = 0.01 * TAU, n_wiggles: int = 6, scale_about_point: np.ndarray | None = None, rotate_about_point: np.ndarray | None = None, run_time: float = 2, **kwargs ): self.scale_value = scale_value self.rotation_angle = rotation_angle self.n_wiggles = n_wiggles self.scale_about_point = scale_about_point self.rotate_about_point = rotate_about_point super().__init__(mobject, run_time=run_time, **kwargs) def get_scale_about_point(self) -> np.ndarray: return self.scale_about_point or self.mobject.get_center() def get_rotate_about_point(self) -> np.ndarray: return self.rotate_about_point or self.mobject.get_center() def interpolate_submobject( self, submobject: Mobject, starting_sumobject: Mobject, alpha: float ) -> None: submobject.match_points(starting_sumobject) 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() ) class TurnInsideOut(Transform): def __init__(self, mobject: Mobject, path_arc: float = 90 * DEGREES, **kwargs): super().__init__(mobject, path_arc=path_arc, **kwargs) def create_target(self) -> Mobject: result = self.mobject.copy().reverse_points() if isinstance(result, VMobject): result.refresh_triangulation() return result class FlashyFadeIn(AnimationGroup): def __init__(self, vmobject: VMobject, stroke_width: float = 2.0, fade_lag: float = 0.0, time_width: float = 1.0, **kwargs ): outline = vmobject.copy() outline.set_fill(opacity=0) outline.set_stroke(width=stroke_width, opacity=1) rate_func = kwargs.get("rate_func", smooth) super().__init__( FadeIn(vmobject, rate_func=squish_rate_func(rate_func, fade_lag, 1)), VShowPassingFlash(outline, time_width=time_width), **kwargs )
manim_3b1b/.github/PULL_REQUEST_TEMPLATE.md
<!-- Thanks for contributing to manim! Please ensure that your pull request works with the latest version of manim. --> ## Motivation <!-- Outline your motivation: In what way do your changes improve the library? --> ## Proposed changes <!-- What you changed in those files --> - - - ## Test <!-- How do you test your changes --> **Code**: **Result**:
manim_3b1b/.github/workflows/docs.yml
name: docs on: push: paths: - 'docs/**' pull_request: paths: - 'docs/**' jobs: docs: runs-on: ubuntu-latest name: build up document and deploy steps: - name: Checkout uses: actions/checkout@master - name: Install sphinx and manim env run: | pip3 install --upgrade pip sudo apt install python3-setuptools libpango1.0-dev pip3 install -r docs/requirements.txt pip3 install -r requirements.txt - name: Build document with Sphinx run: | cd docs export PATH="$PATH:/home/runner/.local/bin" export SPHINXBUILD="python3 -m sphinx" make html - name: Deploy to GitHub pages if: ${{ github.event_name == 'push' }} uses: JamesIves/[email protected] with: ACCESS_TOKEN: ${{ secrets.DOC_DEPLOY_TOKEN }} BRANCH: gh-pages FOLDER: docs/build/html
manim_3b1b/.github/workflows/publish.yml
name: Upload Python Package on: release: types: [created] jobs: deploy: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python: ["py37", "py38", "py39", "py310"] steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine build - name: Build wheels run: python setup.py bdist_wheel --python-tag ${{ matrix.python }} - name: Upload wheels env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | twine upload dist/*
manim_3b1b/.github/ISSUE_TEMPLATE/bug_report.md
--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- ### Describe the bug <!-- A clear and concise description of what the bug is. --> **Code**: <!-- The code you run which reflect the bug. --> **Wrong display or Error traceback**: <!-- the wrong display result of the code you run, or the error Traceback --> ### Additional context <!-- Add any other context about the problem here. -->
manim_3b1b/.github/ISSUE_TEMPLATE/config.yml
blank_issues_enabled: true contact_links: - name: Ask A Question url: https://github.com/3b1b/manim/discussions/categories/q-a about: Please ask questions you encountered here.