text
stringlengths 2.1k
15.6k
|
|---|
`background_color` argument. * :pr:`1118`: Allow passing animation arguments with .animate syntax Users will now be able to do things like `obj.animate(run_time=2).method(arg)` if they want to specify animation arguments for an individual `.animate` call, and can still not specify any arguments like `obj.animate.method(arg)`. Passing animation arguments is only allowed directly after `.animate` is accessed, if passed elsewhere then a `ValueError` is raised. * :pr:`718`: Rotating the numbers in y axis In Axes, the y axis will be rotated 90deg but the numbers are also rotated and shouldn't be. Fixes this issue. * :pr:`1070`: Raise FileNotFoundError when unable to locate the .cfg file specified via ``--config_file`` Raising the error will stop script execution and let the user know that there are problems with the `--config_file` location instead of reverting back to the default configuration. Fixed bugs ---------- * :pr:`1224`: Fixed :class:`~.ShowIncreasingSubsets`, :class:`~.ShowSubmobjectsOneByOne`, and :class:`~.AddTextLetterByLetter` * :pr:`1201`: Prevent crash on :meth:`~.Scene.embed` for empty scenes * :pr:`1192`: Fixed issue when an animation is cached, manim can't merge the partial movie files. * :pr:`1193`: Fixed using :class:`~.Animation` without a child :class:`~.Mobject` in :class:`~.AnimationGroup` `AnimationGroup` may now take `Animation` objects which do not have a child `Mobject`, such as `Wait`. * :pr:`1170`: Fixed minor SVG parsing bugs * :pr:`1159`: Added support for multiple transforms in the same SVG element * :pr:`1156`: Fixed :class:`~.DrawBorderThenFill` to support OpenGL and improved type hints for some functions Fixed a bug in :class:`~.DrawBorderThenFill` that prevented :class:`~.Write` animations from working with :class:`~.OpenGLVMobjects` and slightly improved type hints for some animation functions to include :class:`~.OpenGLVMobject`. * :pr:`1134`: Fixed the `-a` flag. The ``-a`` / ``--write-all`` flag was broken. When used, it would cause Manim to crash just after beginning to render the second scene. * :pr:`1115`: Fixed bugs in :class:`~.OpenGLMobject` and added :class:`ApplyMethod` support Fixed undefined variables and converted :class:`Mobject` to :class:`OpenGLMobject`. Also, fixed assert statement in :class:`ApplyMethod`. * :pr:`1092`: Refactored coordinate_systems.py, fixed bugs, added :class:`~.NumberPlane` test The default behavior of :meth:`~.Mobject.rotate` is to rotate about the center of :class:`~.Mobject`. :class:`~.NumberLine` is symmetric about the point at the number 0 only when ``|x_min|`` == ``|x_max|``. Ideally, the rotation should coincide with the point at number 0 on the line. Added a regression test and additionally fixed some bugs introduced in :pr:`718`. * :pr:`1078`: Removed stray print statements from `__main__.py` Uses rich's print traceback instead and fixes an issue in printing the version twice when `manim --version` is called. * :pr:`1086`: Fixed broken line spacing in :class:`~.Text` The `line_spacing` kwarg was missing when creating :class:`Text` Mobjects; this adds it. * :pr:`1083`: Corrected the shape of :class:`~.Torus` :class:`Torus` draws a surface with an elliptical cross-section when `minor_radius` is different from 1. This PR ensures the cross-section is always a circle. Documentation-related changes ----------------------------- * :pr:`1217`: Copyedited the document on testing in our documentation * :pr:`1206`: Added Docstrings to :class:`~.Mobject` * :pr:`1218`: Removed BezierSpline from the example gallery * :pr:`1219`: Updated Dockerfile (include dependencies for building documentation), moved documentation to main README * :pr:`1209`: Added :ref_methods: to the manim directive This allows class methods to be
|
Copyedited the document on testing in our documentation * :pr:`1206`: Added Docstrings to :class:`~.Mobject` * :pr:`1218`: Removed BezierSpline from the example gallery * :pr:`1219`: Updated Dockerfile (include dependencies for building documentation), moved documentation to main README * :pr:`1209`: Added :ref_methods: to the manim directive This allows class methods to be linked in the documentation. Checkout the `example references <https://docs.manim.community/en/latest/examples.html#movingaround>`_ below the code to see how this is used! * :pr:`1204`: Added rotation example to example gallery * :pr:`1137`: Added GitHub Wiki pages on adding testing/documentation to Sphinx Docs * :pr:`1114`: Added examples for :class:`~.Ellipse`, :class:`~.Polygon`, :class:`~.RegularPolygon`, :class:`~.Triangle` and :class:`~.RoundedRectangle` * :pr:`1195`: Removed SmallDot from example * :pr:`1130`: Added pre-commit to run black and flake8, updated contributing documentation accordingly * :pr:`1138`: Moved previous version changelogs to separate files; Added a Script to generate future changelogs This script quickly generates a changelog for whoever is making the release. * :pr:`1190`: Added note in contributing guide to read the latest version of the documentation * :pr:`1188`: Added sounds example to docs * :pr:`1165`: Added documentation for installing Manim on Colab * :pr:`1128`: Added examples for :class:`~.DashedLine`, :class:`~.TangentLine`, :class:`~.Elbow`, :class:`~.Arrow`, :class:`~.Vector`, :class:`~.DoubleArrow` * :pr:`1177`: Replace links to the latest version of the documentation to the stable version * :pr:`1077`: Added details to :func:`~.Mobject.get_critical_point` * :pr:`1154`: Fixed some typing hints. (ints to floats) * :pr:`1036`: Added :class:`~.SurroundingRectangle` to the example gallery * :pr:`1103`: Added documentation and examples for Square, Dot, Circle and Rectangle * :pr:`1101`: Added documentation to :class:`~.Mobject` * :pr:`1088`: Added new svg files to documentation and imports In particular, SVGPathMobject, VMobjectFromPathstring, and the style_utils functions to manim's namespace. * :pr:`1076`: Improve documentation for GraphScene Updated `coords_to_point` and `point_to_coords` under `manim/scene/graph_scene.py` as the dosctring of each function confusingly described the opposite of what it is supposed to do. Changes concerning the testing system ------------------------------------- * :pr:`1160`: Enable CI testing for OpenGL * :pr:`1100`: Rewrote test cases to use sys.executable in the command instead of "python" Tests would fail due to `capture()` not spawning a subshell in the correct environment, so when python was called, the test would be unable to find necessary packages. * :pr:`1079`: Removed the hardcoded value, `manim`, in `test_version.py` Changes to our development infrastructure ----------------------------------------- * :pr:`1213`: Updated TinyTex dependencies * :pr:`1187`: Add CodeCov to Github Workflow * :pr:`1166`: CI: Use poetry's cache dir rather than pip * :pr:`1071`: Enable pytest-cov based code coverage - Include pytest-cov as a python module as part of developer dependencies - In updating poetry to include pytest-cov, manimpango moved from version 0.2.3 to 0.2.4, and libpango1.0-dev needed to be installed in Ubuntu. - Add to the CI workflow (`ci.yml`) to create and upload test coverage. * :pr:`1073`: Removed "one line summary" from PULL_REQUEST_TEMPLATE.md Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1167`: Merge :class:`~.OpenGLMobject` and :class:`~.Mobject` * :pr:`1164`: Fixed single PEP8 style in `cairo_renderer.py` * :pr:`1140`: Flake8 Compat & Code Cleanup * :pr:`1019`: Refactored :meth:`~.Scene.play` - Removed the _**three**_ decorators of :meth:`~.Scene.play`, in particular: caching logic and file writer logic are now included within :meth:`~.Scene.play`
|
improvements and similar refactors ----------------------------------------------- * :pr:`1167`: Merge :class:`~.OpenGLMobject` and :class:`~.Mobject` * :pr:`1164`: Fixed single PEP8 style in `cairo_renderer.py` * :pr:`1140`: Flake8 Compat & Code Cleanup * :pr:`1019`: Refactored :meth:`~.Scene.play` - Removed the _**three**_ decorators of :meth:`~.Scene.play`, in particular: caching logic and file writer logic are now included within :meth:`~.Scene.play` (it wasn't possible before, because `scene.wait` and `scene.play` were two different things). - Added `is_static_wait` attributes to Wait. (<=> if wait is a frozen frame). - Renamed and moved `scene.add_static_frame` to `renderer.freeze_current_frame`. - Now when calling play without animation, it raises `ValueError` instead of just a warning. - Fixed :pr:`874` by modifying `renderer.update_skipping_status` - `renderer` starts the animation with `scene.begin_animations` (`scene.compile_animation_data` used to do this) - The run time and the time progression generation is now done in `scene.play_internal` although it'd make more sense that renderer processes it later. - Added a bunch of cool tests thanks to mocks, and thanks to the new syntax `scene.render` ================================================ FILE: docs/source/changelog/0.6.0-changelog.rst ================================================ ****** v0.6.0 ****** :Date: May 02, 2021 Contributors ============ A total of 40 people contributed to this release. People with a '+' by their names authored a patch for the first time. * Abel Aebker * Abhijith Muthyala * Adam Ryczkowski + * Alex Lembcke + * Anton Ballmaier * Aron * Benjamin Hackl * Darylgolden * Deniz Hasler + * Devin Neal * Elisha Hollander + * Erik Tastepe + * Jan-Hendrik Müller * Jason Villanueva * Laith Bahodi * Mark Miller * Mohammad Al-Fetyani * Naveen M K * Newell Jensen + * Nidhal Baccouri + * Nikhil Garuda + * Peilonrayz + * Raghav Goel * Ricky Chon + * friedkeenan * kamilczerwinski22 + * sparshg The patches included in this release have been reviewed bythe following contributors. * Aathish Sivasubrahmanian * Abel Aebker * Abhijith Muthyala * Adam Ryczkowski * Alex Lembcke * Anton Ballmaier * Aron * Benjamin Hackl * Darylgolden * Deniz Hasler * Devin Neal * Elisha Hollander * GameDungeon * Hugues Devimeux * Jan-Hendrik Müller * Jason Villanueva * KingWampy * Laith Bahodi * Mark Miller * Mohammad Al-Fetyani * Naveen M K * Nidhal Baccouri * Nikhil Garuda * Oliver * Philipp Imhof * Raghav Goel * Ricky Chon * friedkeenan * sparshg Pull requests merged =================== A total of 112 pull requests were merged for this release. Breaking changes ---------------- * :pr:`1347`: Restructure vector_field module and add documentation :class`~.VectorField` is renamed to :class:`~.ArrowVectorField` and a new class :class:`~.VectorField` is added as a superclass for :class:`~.ArrowVectorField` and :class:`~.StreamLines`. :class:`~.AnimatedStreamLines` is removed. It's functionality is moved to :class:`~.StreamLines`. Added a lot of new options when working with vector fields. :class:`~.ShowPassingFlashWithThinningStrokeWidth` was moved to the indication module. * :pr:`1161`: Upgrades to CoordinateSystem and graphing. Breaking changes were introduced to :class:`~.Axes`, :class:`~.ThreeDAxes`, :class:`~.NumberPlane` and :class:`~.NumberLine` All the above now use lists to construct their ranges as opposed to explicitly defining these values. `x_range` has replaced `x_min`, `x_max` and defining the step is much easier with `x_step` --> ``x_range`` : ``[x_min, x_max, x_step]``. There were
|
graphing. Breaking changes were introduced to :class:`~.Axes`, :class:`~.ThreeDAxes`, :class:`~.NumberPlane` and :class:`~.NumberLine` All the above now use lists to construct their ranges as opposed to explicitly defining these values. `x_range` has replaced `x_min`, `x_max` and defining the step is much easier with `x_step` --> ``x_range`` : ``[x_min, x_max, x_step]``. There were also many upgrades to these classes which improve their functionality and appearance. ``NumberLineOld`` was introduced to continue support for :class:`~.GraphScene`, although we are moving away from GraphScene and intend to deprecate it in a future release. * :pr:`1013`: Refactored the Command Line Interface to use Click instead of Argparse This change breaks the CLI API to organize the structure of Manim Community's commands, options, and arguments. To be more in line with POSIX compliant CLI conventions, options for commands are given *BEFORE* their arguments. In Argparse: ``manim basic.py -p -ql`` With Click: ``manim -p -ql basic.py`` Although this is primarily a refactor and most of the common options are still there, some options have been added/removed. Use the ``manim`` command's ``--help`` option, or simply run the command without providing options/arguments to view the help page with the full list of subcommands/options/arguments. - Added a ``--fps``/``--frame_rate`` option which allows for custom fps that don't have to be integer (i.e. 29.97, 23.98, etc.). Users no longer have to specify the FPS from within a config file. Additionally, the ``--webgl_renderer_fps`` option has been removed. Use ``--fps`` or ``--frame_rate`` instead. - Added a ``--renderer`` option which you can use to select your choice of renderer (e.g. ``--renderer=opengl``). There are currently *THREE* renderers to choose from! - Removed the ``--background_color`` option. Reassigned the ``--background_color`` option's shorthand ``-c`` to ``--config_file``. - Removed the ``--leave_progress_bars`` option. Use ``--progress_bars=leave`` instead. - Removed the deprecated render quality flags, in particular: ``-l``, ``-m``, ``-h``, ``-k``. - Removed the ``--sound`` option. It lost support long ago with the removal of SoX. Deprecated classes and functions -------------------------------- * :pr:`1431`: Fix CLI bugs - Fixed conflict with ``-f`` which was previously assigned to both ``--show_in_file_browser`` and ``--format`` by removing ``-f`` from ``--format``. A warning is issued that ``-f`` will soon move to ``--format``. - Added back in flags to render the files as gif/last frame. Deprecated them in favor of ``--format``. - Fixed the broken ``--output_file``/``-o`` option. - Fixed an issue where the ``-qh`` quality option was interpreted as ``-q`` ``-h``, prompting the help page. * :pr:`1354`: Refactored a few functions in space_ops.py, deprecated :func:`~.angle_between` * :pr:`1370`: Remove TexMobject and TextMobject TexMobject and TextMobject have been deprecated for a while, they are now fully removed. Use Tex or MathTex instead. * :pr:`1349`: Removed the deprecated ``SmallDot`` mobject * :pr:`1259`: Removed deprecated CairoText class New features ------------ * :pr:`1386`: Implement utility methods for adding/removing vertices and edges of graphs; allow custom mobjects as vertices * :pr:`1385`: Added :meth:`~.Axes.get_line_graph` for plotting a line graph Added :meth:`~.Axes.get_line_graph` that returns a line graph from lists of points along x, y and z (optional) axes. * :pr:`1381`: Hot reloading for the OpenGL renderer Rerun scene when the input
|
vertices and edges of graphs; allow custom mobjects as vertices * :pr:`1385`: Added :meth:`~.Axes.get_line_graph` for plotting a line graph Added :meth:`~.Axes.get_line_graph` that returns a line graph from lists of points along x, y and z (optional) axes. * :pr:`1381`: Hot reloading for the OpenGL renderer Rerun scene when the input file is modified * :pr:`1383`: Overhaul of the :mod:`~.animation.indication` module interfaces - Added class `Circumscribe` combining functionality of `CircleIndicate`, `AnimationOnSurroundingRectangle`, `ShowPassingFlashAround`, `ShowCreationThenDestructionAround`, `ShowCreationThenFadeAround`, which have all been deprecated. - Changes to `Flash`: `flash_radius` parameter now defines inner radius of the animation. Added new parameter `time_width`. - `ShowCreationThenDestruction` has been deprecated in favor of `ShowPassingFlash` - Changes to `ApplyWave`: New implementation giving more flexibility with new parameters `wave_func`, `time_width` and`ripples` - Renamed `WiggleOutThenIn` to `Wiggle` (`WiggleOutThenIn` has been deprecated) - Added documentation and examples to all the above - Other minor enhancements and bug-fixes * :pr:`1348`: Added :class:`~.Polyhedron`, and platonic solids :class:`~.Tetrahedron`, :class:`~.Octahedron`, :class:`~.Icosahedron` and :class:`~.Dodecahedron` * :pr:`1285`: Add :meth:`~.Scene.interactive_embed` for OpenGL rendering :meth:`~.Scene.interactive_embed` allows interaction with Scene via mouse and keyboard as well as dynamic commands via an iPython terminal. * :pr:`1261`: Render image automatically if no animation is played in a scene - If no animations in scene and asked to preview/render a video, preview/render an image instead of raising a confusing error. * :pr:`1200`: Add text and SVG mobjects to OpenGL Added OpenGL-compatible text and SVG mobjects Enhancements ------------ * :pr:`1398`: Fix and enhance `Mobject.arrange_in_grid` `arrange_in_grid` now actually arranges submobjects in a grid. Added new parameters `buff`, `cell_alignment`, `row_alignments`, `col_alignments`, `row_heights`, `col_widths`, `flow_order`. * :pr:`1407`: Fix bug and rename :meth:`vector_coordinate_label` to :meth:`~.Vector.coordinate_label` and move it to :class:`geometry.py` * :pr:`1380`: Allow image objects as background images * :pr:`1391`: Add `path_arc` support to `.animate` syntax The parameter `path_arc` of :class:`~.Transform` now works with the `.animate` syntax * :pr:`1364`: Added :meth:`~.Mobject.match_points` - Added :func:`~.Mobject.match_points`, which transforms the points, positions and submobjects of a Mobject to match that of the other while keeping style unchanged. * :pr:`1363`: Change of TeX compiler and output file format * :pr:`1359`: Make FILE a required argument * Make `FILE` a required argument, `manim/cli/render/commands.py`:L30 * :pr:`1304`: Improve Tex string splitting at double braces: only split for double brace groups * :pr:`1340`: Add OpenGL support to the new transform animations Made `FadeTransform`, `FadeTransformPieces`, `TransformMatchingShapes` and `TransformMatchingTex` compatible with OpenGL rendering. * :pr:`1343`: Make TexTemplate() simple, but keep Tex()'s default template TexTemplate() now returns a simple tex template. * :pr:`1321`: Add OpenGL support to :class:`~.AnimationGroup` * :pr:`1302`: Raise appropriate errors in :meth:`~.VMobject.point_from_proportion` - Raise an error if the ``alpha`` argument is not between 0 and 1. - Raise an error if the :class:`~.VMobject` has no points. * :pr:`1315`: Fix performance issues with :meth:`~.VMobject.get_arc_length`, stemming from :pr:`1274` * :pr:`1320`: Add `jpeg` extension to the default image extensions * :pr:`1234`: Added new method :meth:`~.Mobject.get_midpoint` Implemented :meth:`~.Mobject.get_midpoint` to return the point that is the middle of the stroke line of an mobject. * :pr:`1237`: Notify user if they are using an outdated version of Manim * :pr:`1308`: Improved :class:`~.ManimBanner` animations * :pr:`1275`:
|
`jpeg` extension to the default image extensions * :pr:`1234`: Added new method :meth:`~.Mobject.get_midpoint` Implemented :meth:`~.Mobject.get_midpoint` to return the point that is the middle of the stroke line of an mobject. * :pr:`1237`: Notify user if they are using an outdated version of Manim * :pr:`1308`: Improved :class:`~.ManimBanner` animations * :pr:`1275`: Add SVG <line> element support to :class:`~.SVGMobject` * :pr:`1238`: Add parameter ``about_point`` for :meth:`~.Mobject.rotate` * :pr:`1260`: Change Brace from Tex to SVG (#1258) * :pr:`1122`: Support for specifying the interpolation algorithms for individual ImageMobjects * :pr:`1283`: Set default value of keyword ``random_seed`` in :class:`~.Scene` to ``None`` (was 0 and fixed before) * :pr:`1220`: Added sanity checks to :meth:`~.Mobject.add_to_back` for Mobjects Add Mobject `add_to_back` sanity checks: - Raises ValueError when Mobject tries to add itself - Raises TypeError when a non-Mobject is added - Filters out incoming duplicate submobjects if at least one instance of that submobject exists in the list * :pr:`1249`: Set corners of :class:`~.Rectangle` in counterclockwise direction This improves the look of transformations between rectangles and other simple mobjects. * :pr:`1248`: Add Copy function to TexTemplate Fixed bugs ---------- * :pr:`1368`: Added a check to ensure checking for the latest version was successful * :pr:`1413`: Prevent duplication of the same mobject when adding to submobjects via :meth:`~.Mobject.add_to_back` Fixes #1412 * :pr:`1395`: SVG transforms now handle exponent notation (6.02e23) * :pr:`1355`: Rewrite `put_start_and_end_on` to work in 3D * :pr:`1346`: Fixed errors introduced by stray print in :class:`~.MathTex` * :pr:`1305`: Automatically remove long tick marks not within the range of the :class:`~NumberLine` * :pr:`1296`: Fix random pipeline TeX failures * :pr:`1274`: Fix :meth:`~.VMobject.point_from_proportion` to account for the length of curves. - Add :meth:`~.VMobject.get_nth_curve_function_with_length` and associated functions. - Change :meth:`~.VMobject.point_from_proportion` to use these functions to account for curve length. Documentation-related changes ----------------------------- * :pr:`1430`: Un-deprecated GraphScene (will be deprecated later), fixed an old-style call to NumberPlane - More work is required in order to fully replace `GraphScene` via `Axes`, thus `GraphScene` is not deprecated yet. - Fixed one example in which the old `NumberPlane` syntax was used. * :pr:`1425`: Added a "How to Cite Manim" section to the Readme * :pr:`1387`: Added Guide to Contribute Examples from GitHub Wiki to Documentation Added a Guide * :pr:`1424`: Fixed all current docbuild warnings * :pr:`1389`: Adding Admonitions Tutorial to docs * :pr:`1341`: Reduce complexity of ThreeDSurfacePlot example * :pr:`1362`: Quick reference to modules * :pr:`1376`: Add flake8 and isort in docs added 'flake8' and 'isort' usages to docs * :pr:`1360`: Grammatical error corrections in documentation changed a few sentences in docs/source * :pr:`1351`: Some more typehints * :pr:`1358`: Fixed link to installation instructions for developers * :pr:`1338`: Added documentation guidelines for type hints * :pr:`1342`: Multiple ValueTracker example for docs * :pr:`1210`: Added tutorial chapter on coordinates of an mobject * :pr:`1335`: Added import statements to examples in documentation * :pr:`1245`: Added filled angle Example * :pr:`1328`: Docs: Update Brace example * :pr:`1326`: Improve documentation of :class:`~.ManimMagic` (in particular: fix documented order of CLI flags) * :pr:`1323`: Blacken Docs Strings * :pr:`1300`: Added
|
tutorial chapter on coordinates of an mobject * :pr:`1335`: Added import statements to examples in documentation * :pr:`1245`: Added filled angle Example * :pr:`1328`: Docs: Update Brace example * :pr:`1326`: Improve documentation of :class:`~.ManimMagic` (in particular: fix documented order of CLI flags) * :pr:`1323`: Blacken Docs Strings * :pr:`1300`: Added typehints for :class:`~.ValueTracker` * :pr:`1301`: Added further docstrings and typehints to :class:`~.Mobject` * :pr:`1298`: Add double backquotes for rst code samples (value_tracker.py) * :pr:`1297`: Change docs to use viewcode extension instead of linkcode Switched ``sphinx.ext.linkcode`` to ``sphinx.ext.viewcode`` and removed ``linkcode_resolve`` in ``conf.py``. * :pr:`1246`: Added docstrings for :class:`~.ValueTracker` * :pr:`1251`: Switch documentation from guzzle-sphinx-theme to furo * :pr:`1232`: Further docstrings and examples for :class:`~.Mobject` * :pr:`1291`: Grammar improvements in README.md * :pr:`1269`: Add documentation about :meth:`~.set_color_by_tex` * :pr:`1284`: Updated readme by providing the correct link to the example_scenes * :pr:`1029`: Added example jupyter notebook into the examples folders * :pr:`1279`: Added sphinx requirements to pyproject.toml New contributors who wanted to build the sphinx documentation had an extra step that could be removed by making use of ``poetry install``. This removes the developer's need for ``pip install -r requirements.txt``. * :pr:`1268`: Added documentation explaining the differences between manim versions * :pr:`1247`: Added warning for the usage of `animate` * :pr:`1242`: Added an example for the manim colormap * :pr:`1239`: Add TinyTex installation instructions * :pr:`1231`: Improve changelog generation script Changes concerning the testing system ------------------------------------- * :pr:`1299`: Red pixels (different value) now appear over green pixels (same value) in GraphicalUnitTest Changes to our development infrastructure ----------------------------------------- * :pr:`1436`: Cache poetry venv with `pyproject.toml` hash in key Cache poetry venv with `pyproject.toml` hash in key * :pr:`1435`: CI: Update poetry cache when new version is released Fix `test_version` failure in CI when using cached poetry venv * :pr:`1427`: Add URL's to pyproject.toml * :pr:`1421`: Updated changelog generator's labels and removed pre-commit bot from changelog * :pr:`1339`: CI: Fix macOS installation error from creating file in read-only file system * :pr:`1257`: CI: Caching ffmpeg, tinytex dependencies and poetry venv CI: Caching ffmpeg, tinytex dependencies and poetry venv * :pr:`1294`: Added mixed-line-ending to .pre-commit-config.yaml * :pr:`1278`: Fixed flake8 errors and removed linter/formatter workflows * :pr:`1270`: Added isort to pre_commit file * :pr:`1263`: CI: Turn off experimental installer for poetry to fix installation errors - Turn off experimental installer for poetry to prevent manim installation errors for packages. - Downgrade py39 to py38 for flake checks as `pip` does not enjoy py39, along with `poetry`. * :pr:`1255`: CI: Fix macOS pipeline failure Update `ci.yml` to update and upgrade brew if necessary before installing dependencies, and remove the unsupported `dvisvgm.86_64-darwin` package. * :pr:`1254`: Removed the comment warning that GitHub doesn't allow uploading video in the issue templates. * :pr:`1216`: Use actions/checkout for cloning repository; black-checks * :pr:`1235`: Fixed version of decorator at <5.0.0 Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1411`: Change `Union[float, int]` to just `float` according to PEP 484 * :pr:`1241`: Type Annotations: Fixing errors showing up in static type checking tool mypy
|
templates. * :pr:`1216`: Use actions/checkout for cloning repository; black-checks * :pr:`1235`: Fixed version of decorator at <5.0.0 Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1411`: Change `Union[float, int]` to just `float` according to PEP 484 * :pr:`1241`: Type Annotations: Fixing errors showing up in static type checking tool mypy * :pr:`1319`: Fix mean/meant typo Fix typo in docs * :pr:`1313`: Singular typo fix on the Quickstart page in documentation * :pr:`1292`: Remove unnecessary imports from files Imports reduced in a bunch of files * :pr:`1295`: Fix grammar and typos in the CODE OF CONDUCT * :pr:`1293`: Minor fixes - reduce lines Remove unnecessary lines * :pr:`1281`: Remove all Carriage Return characters in our files * :pr:`1178`: Format Imports using Isort * :pr:`1233`: Fix deprecation warning for ``--use_opengl_renderer`` and ``--use_webgl_renderer`` * :pr:`1282`: Fix typing hints in vectorized_mobject.py based on mypy New releases ------------ * :pr:`1434`: Prepare v0.6.0 ================================================ FILE: docs/source/changelog/0.7.0-changelog.rst ================================================ ****** v0.7.0 ****** :Date: June 01, 2021 Contributors ============ A total of 45 people contributed to this release. People with a '+' by their names authored a patch for the first time. * André + * Anton Ballmaier * Benjamin Hackl * Clar Fon * Darylgolden * Devin Neal * Hugues Devimeux * Iced-Tea3 + * Jan-Hendrik Müller * Jason Villanueva * Jerónimo Squartini + * KingWampy * Laith Bahodi * Max Stoumen + * Mohammad Al-Fetyani * Naveen M K * NeoPlato * Newell Jensen * Nikhil Garuda * Nikhil Sharma + * PaulCMurdoch + * Philipp Imhof * Rav Goel * Robert West + * Ryan McCauley + * Skaft + * SwiddisZwei + * e4coder + * friedkeenan * malte-v + * ralphieraccoon * sparshg The patches included in this release have been reviewed by the following contributors. * Aathish Sivasubrahmanian * Abhijith Muthyala * Anton Ballmaier * Aron * Benjamin Hackl * Darylgolden * Devin Neal * GameDungeon * Hugues Devimeux * Iced-Tea3 * Jan-Hendrik Müller * Jason Villanueva * Jerónimo Squartini * KingWampy * Laith Bahodi * Mark Miller * Mohammad Al-Fetyani * Naen M K * Nikhil Garuda * Oliver * Philipp Imhof * Raghav Goel * Ricky Chon * Ryan McCauley * Skaft * SwiddisZwei * e4coder * friedkeenan * ralphieraccoon * sparshg Pull requests merged ==================== A total of 87 pull requests were merged for this release. Breaking changes ---------------- * :pr:`1521`: Improve :class:`~.Animation` docs - Improve documentation of the :class:`~.Animation` class. - Unify the signature of ``get_all_mobjects``. Now it always returns a sequence of :class:`Mobjects <.Mobject>`. This breaks using ``FadeTransform.get_all_mobjects`` as ``Group``. * :pr:`1470`: Drop support for Python 3.6 Manim won't work on Python 3.6 anymore. Highlights ---------- * :pr:`1447`: Added :class:`~.PolarPlane` for polar coordinates. * :pr:`1490`: Added :class:`~.Polygram`, rework the polygon inheritance tree, and add :class:`~.Star` - Add :class:`~.Polygram`, a generalized :class:`~.Polygon` that allows for disconnected sets of edges. - Make :class:`~.Polygon` inherit from :class:`~.Polygram`. - Add :func:`~.regular_vertices` - Add :class:`~.RegularPolygram`. - Make :class:`~.RegularPolygon` inherit from :class:`~.RegularPolygram`. - Add :class:`~.Star`. * :pr:`1462`: OpenGL: Added :class:`~.Shader`, :class:`~.Mesh`, and :class:`~.FullScreenQuad` Add
|
the polygon inheritance tree, and add :class:`~.Star` - Add :class:`~.Polygram`, a generalized :class:`~.Polygon` that allows for disconnected sets of edges. - Make :class:`~.Polygon` inherit from :class:`~.Polygram`. - Add :func:`~.regular_vertices` - Add :class:`~.RegularPolygram`. - Make :class:`~.RegularPolygon` inherit from :class:`~.RegularPolygram`. - Add :class:`~.Star`. * :pr:`1462`: OpenGL: Added :class:`~.Shader`, :class:`~.Mesh`, and :class:`~.FullScreenQuad` Add Shader and Mesh objects * :pr:`1418`: Added project management commands - ``manim init`` - quickly sets up default files for a manim project. - ``manim new project`` - lets the user set project settings. It also creates the project inside a new folder of name <project_name> - ``manim new scene`` - used to quickly insert new scenes into files. If ``file name`` is not provided ``main.py`` is used as default. Deprecated classes and functions -------------------------------- * :pr:`1598`: Update examples to use :class:`~.Axes` and deprecate :class:`~.GraphScene` :class:`~.GraphScene` has been deprecated and its functionality has been shifted to :class:`~.Axes`. See the updated example gallery for sample usage. * :pr:`1454`: Fading module enhancements Moved functionality of all Fading classes to :class:`~.FadeIn` and :class:`~.FadeOut`. All other fading classes have been deprecated. * :pr:`1375`: Deleted the deprecated ``ShowCreation`` in favor of :class:`~.Create` New features ------------ * :pr:`1566`: Added the ability to add gridlines to a :class:`~.Rectangle` * :pr:`1548`: Added :class:`~.ArcBrace`, a subclass of :class:`~.Brace`. * :pr:`1559`: Update VGroup to support item assignment (#1530) Support indexed item-assignment for VGroup * :pr:`1518`: Allow fading multiple Mobjects in one Animation * :pr:`1422`: Added :func:`~.override_animation` decorator * :pr:`1504`: Color module enhancements - Replaced ``BLUE_E`` with what was previously ``DARK_BLUE`` and removed ``DARK_BLUE`` - Added alias ``LIGHTER_GRAY`` for ``GRAY_A`` - Added ``PURE_RED``, ``PURE_BLUE`` and renamed ``GREEN_SCREEN`` to ``PURE_GREEN`` - All gray colors are now also available using British spelling (including ``GREY_BROWN``) - Replaced color example in the docs. It can now be used as a quick reference for all color names. * :pr:`1272`: Implement metaclass approach in geometry module to make mobjects compatible with cairo and opengl rendering * :pr:`1404`: Added two deprecation decorators Added two function decorators ``deprecated`` and ``deprecated_params`` as a consistent way of deprecating code. Enhancements ------------ * :pr:`1572`: OpenGL compatibility via metaclass: :class:`~.TracedPath`, :class:`~.ParametricFunction`, :class:`~.Brace`, :class:`~.VGroup` * :pr:`1472`: Porting methods from :class:`~.GraphScene` to :class:`~.CoordinateSystem` * :pr:`1589`: OpenGL compatibility via metaclass: :class:`~.ValueTracker` * :pr:`1564`: Add extra notes for TeX compilation errors Add hint to use custom ``TexTemplate`` on TeX compilation errors * :pr:`1584`: Added a check for ``0`` in :meth:`~.round_corners` * :pr:`1586`: Add OpenGLMobject support to all ``isinstance`` occurrences This PR increases the support for OpenGL in the remaining animation classes and in other places where appropriate. * :pr:`1577`: Added new metaclass ConvertToOpenGL (replacing MetaVMobject), restore IntelliSense * :pr:`1562`: Improved VectorField's Nudge Accuracy Per Step Implemented the Runge-Kutta algorithm in VectorField's nudge function. This increases the accuracy as an object moves along a vector field. This also increases efficiency as the nudge function requires less loops to achieve accuracy than the previous implementation. * :pr:`1480`: Add logging info to tex errors * :pr:`1567`: Compatibility Fixes with ManimPango v0.3.0 - ManimPango v0.3.0+ is required for Manim now. -
|
as an object moves along a vector field. This also increases efficiency as the nudge function requires less loops to achieve accuracy than the previous implementation. * :pr:`1480`: Add logging info to tex errors * :pr:`1567`: Compatibility Fixes with ManimPango v0.3.0 - ManimPango v0.3.0+ is required for Manim now. - Show errors from Pango when Markup isn't correct * :pr:`1512`: OpenGL compatibility via metaclass: graph * :pr:`1511`: OpenGL compatibility via metaclass: svg_mobject, text_mobject, tex_mobject * :pr:`1502`: Added ``center`` parameter to :class:`~.Sphere` and ``point`` parameter to :class:`~.Dot3D` * :pr:`1486`: Update of ``rate_functions`` Changed the picture for the non standard rate functions. * :pr:`1495`: Ported value_tracker to OpenGL * :pr:`1382`: Expand documentation, testing, and functionality of ValueTrackers; remove ExponentialValueTracker Added more documentation and inline operators to ValueTracker and ComplexValueTracker. Brought coverage for value_tracker.py to 100%. Removed ExponentialValueTracker. * :pr:`1475`: Add SVG elliptical arc support Fixed bugs ---------- * :pr:`1574`: Fixed error when processing SVG with omitted elliptical arc command * :pr:`1596`: Fix indexing for non-whitespace tex arg separator Fixes #1568 Fix issue when setting the arg_separator of a Tex object as a non-whitespace character(s). The method `break_up_by_substrings(self)` was not accounting for the separator when setting the index. * :pr:`1588`: Fixed multiple animations being saved in the same file * :pr:`1571`: Fix tests after introducing parallelization * :pr:`1545`: Fix outdated parameters for :class:`LinearTransformationScene` and add an example + typing. * :pr:`1513`: Fixed rotation of gradients while rotating a VMobject - Fixed the direction of gradient which remained the same while rotating VMobjects - Added ``rotate_sheen_direction()`` method in VMobject * :pr:`1570`: Output errors to stderr * :pr:`1560`: Declare ``*.npz`` ``*.wav`` ``*.png`` as binary in ``.gitattributes`` * :pr:`1211`: Refactored scene caching and fixed issue when a different hash was produced when copying a mobject in the scene Refactored internal scene-caching mechanism and fixed bug when an inconsistent hash was produced when copying a mobject. * :pr:`1527`: Improved handling of substring isolation within sqrt, and fixed a bug with transform_mismatch for the matching shape transforms * :pr:`1526`: Fix fading * :pr:`1523`: Fix multiple FadeIn / Out only working on VMobjects Documentation-related changes ----------------------------- * :pr:`1599`: Added example for :class:`~.Annulus` * :pr:`1415`: New example for gallery and some docs refinements * :pr:`1509`: Copyedited Documentation Added a link to Manim Community GitHub page in ``for_dev.rst``. Fixed :meth:`~.Mobject.get_start` and added ``roll`` link in ``building_blocks-rst`` Added language to code blocks in ``configuration.rst`` * :pr:`1384`: Added typings to space_ops.py Added Typehints to most of the functions * :pr:`1500`: Example for :meth:`~.apply_complex_function` * :pr:`1551`: Fixed the typo for Admonitions * :pr:`1550`: Restructuring of Contribution Section * :pr:`1541`: Fixing broken links and other minor doc things * :pr:`1516`: Update docs to use ``t_range`` instead of ``t_min`` and ``t_max`` in :class:`~.ParametricFunction` * :pr:`1508`: Update troubleshooting docs * :pr:`1485`: Added :class:`~.Title` example for the docs * :pr:`1439`: Cleaning ``Sequence`` typehints * :pr:`1440`: Added Scoop installation docs (Windows) * :pr:`1452`: Refine typehints at :class:`~.Angle` * :pr:`1458`: Refine docs of :class:`~.Text` ( add ``disable_ligatures=True`` for t2c) * :pr:`1449`: Added :class:`~.PointCloudDot` example * :pr:`1473`: Added easy example for
|
troubleshooting docs * :pr:`1485`: Added :class:`~.Title` example for the docs * :pr:`1439`: Cleaning ``Sequence`` typehints * :pr:`1440`: Added Scoop installation docs (Windows) * :pr:`1452`: Refine typehints at :class:`~.Angle` * :pr:`1458`: Refine docs of :class:`~.Text` ( add ``disable_ligatures=True`` for t2c) * :pr:`1449`: Added :class:`~.PointCloudDot` example * :pr:`1473`: Added easy example for :meth:`~.arrange_in_grid` * :pr:`1402`: Added typestring parser checker * :pr:`1451`: Reduce complexity of AngleExample * :pr:`1441`: Add inheritance diagrams to reference page Added inheritance diagrams to the reference page as a quick navigation method. * :pr:`1457`: Fixing broken doc links * :pr:`1445`: Remove $ from tutorial commands Changes concerning the testing system ------------------------------------- * :pr:`1556`: Try pytest-xdist for parallelization in tests Changes to our development infrastructure ----------------------------------------- * :pr:`1505`: Add docs reference to PR template Added documentation link to the Pull Request Template. * :pr:`1499`: Updated Discord links in the docs to point towards a standardized redirect * :pr:`1461`: Build the docs - Logging * :pr:`1481`: pyproject.toml: poetry_core -> poetry-core * :pr:`1477`: Update RDT sphinx package to version 3.5.3 * :pr:`1460`: Create CONTRIBUTING.md * :pr:`1453`: manim_directive: fix image links in docs - Windows Use POSIX path on Windows to link images so documentation can build locally. Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1465`: Added typings and description to some functions in :mod:`~.coordinate_systems`. * :pr:`1552`: Removed unwanted parameters in geometry Removed ``anchors_span_full_range``, ``close_new_points``, ``anchors_span_full_range``, ``preserve_tip_size_when_scaling``, ``mark_paths_closed`` and ``close_new_points`` * :pr:`1597`: Removed hilite_me and insert_line_numbers_in_html from global name space * :pr:`1535`: Update dependencies and fix tests * :pr:`1544`: Adding spell checker as a pre-commit hook * :pr:`1542`: Swapping a pango markup link in docs * :pr:`1531`: Don't use deprecated methods in deprecation.py * :pr:`1492`: Remove stray print statements introduced in #1404 * :pr:`1471`: Fix Some Warnings from lgtm Changes that needed to be reverted again ---------------------------------------- * :pr:`1606`: Bring back ``DARK_BLUE`` New releases ------------ * :pr:`1601`: Preparation for v0.7.0: added changelog and bumped version number ================================================ FILE: docs/source/changelog/0.8.0-changelog.rst ================================================ ****** v0.8.0 ****** :Date: July 02, 2021 Contributors ============ A total of 37 people contributed to this release. People with a '+' by their names authored a patch for the first time. * Benjamin Hackl * Bill Shillito + * Darigov Research + * Darylgolden * Devin Neal * Iced-Tea3 * Jan-Hendrik Müller * Jason Villanueva * KingWampy * Laith Bahodi * MathInvariance + * Max Stoumen * Mehmet Ali Özer + * Michael Pilosov + * Mohammad Al-Fetyani * Naveen M K * Nikhil Garuda * Oliver * PaulCMurdoch * Philipp Imhof * PipedQuintes + * Raghav Goel * Ryan McCauley * Ujjayant+ * Vagrid + * andrehisatsuga + * friedkeenan * peaceheis + * yit6 + The patches included in this release have been reviewed by the following contributors. * Abhijith Muthyala * Anton Ballmaier * Aron * Benjamin Hackl * Clar Fon * Darylgolden * Devin Neal * Jan-Hendrik Müller * Jason Villanueva * KingWampy * Laith Bahodi * Mark Miller * MathInvariance * Mohammad Al-Fetyani * Naveen M K * Nikhil Garuda * Oliver * Philipp Imhof *
|
Abhijith Muthyala * Anton Ballmaier * Aron * Benjamin Hackl * Clar Fon * Darylgolden * Devin Neal * Jan-Hendrik Müller * Jason Villanueva * KingWampy * Laith Bahodi * Mark Miller * MathInvariance * Mohammad Al-Fetyani * Naveen M K * Nikhil Garuda * Oliver * Philipp Imhof * Raghav Goel * Ryan McCauley * Ujjayanta * Vagrid * friedkeenan Pull request merged ==================== A total of 76 pull requests were merged for this release. Deprecated classes and functions -------------------------------- * :pr:`1616`: Remove all functions and classes that were deprecated until ``v0.6.0`` New features ------------ * :pr:`1716`: Rewrite stroke and fill shaders Rewrite vectorized mobject shaders to be compatible with transformation matrices. * :pr:`1695`: Add option to justify text with :class:`~.MarkupText` A new parameter ``justify`` is added to :class:`~.MarkupText`. It can be used to justify a paragraph of text. * :pr:`1660`: Added support for ``.webm`` and transparency of videos in Jupyter notebooks - Added support for generating ``webm`` videos via the command line flag ``--format=webm`` - Added transparency support for Jupyter notebooks * :pr:`1553`: Add dearpygui integration Enhancements ------------ * :pr:`1728`: Improved positioning and size of the OpenGL window; added some configuration options * :pr:`1733`: Let OpenGLMobject.copy return a deep copy by default * :pr:`1735`: Metaclass compatibility for `coordinate_system.py`, `Code` and `ParametricSurface` * :pr:`1585`: OpenGL compatibility via metaclass for :class:`~.Matrix`, :class:`~.DecimalNumber`, :class:`~.Variable` * :pr:`1713`: Exit the command line interface gracefully if no scene was chosen * :pr:`1652`: Refactored :class:`~.Mobject` and :class:`~.Scene` to no longer inherit from the abstract base class ``Container`` - Moved tests in ``test_container.py`` for :class:`Container` that test :class:`~.Scene` and :class:`~.Mobject` to their own files. - Corrected various instances of incorrectly passed keyword arguments, or unused keyword arguments. * :pr:`1693`: Made the default arrowhead size for :class:`~.Arrow3D` smaller * :pr:`1678`: Allow some rate functions to assume values outside of [0, 1]; introduce clamping decorators - Fixed animations so that certain rate functions (``running_start``, ``wiggle``, ``ease_in_back``, ``ease_out_back``, ``ease_in_out_back``, ``ease_in_elastic``, ``ease_out_elastic``, and ``ease_out_elastic``) can go outside the range from 0 to 1. - Fixed lag ratios so that they're spaced out evenly within the time interval and the rate functions are applied to each animation individually, rather than having the rate function determine when the animation starts. - Fixed faulty code for ``ease_in_out_expo``, ``ease_in_bounce``, ``ease_out_bounce``, and ``ease_in_out_bounce``. * :pr:`1649`: Made video file names in Jupyter notebook more readable * :pr:`1667`: Determine the default number of decimal places for :class:`~.NumberLine` labels automatically from the step size As an example: If the step size is set to 0.5, labels will now show at least one decimal place. * :pr:`1608`: Color file paths in terminal; remove curly braces surrounding the file path in "Partial movie file written in..." messages * :pr:`1632`: OpenGL compatibility via metaclass: :class:`~.Group` Fixed bugs ---------- * :pr:`1740`: Fix pillow to <8.3.0 * :pr:`1729`: Fix bug when using :class:`~.Text` with the OpenGL renderer * :pr:`1675`: Fixed ignored fill and stroke colors for :class:`~.SVGMobject` * :pr:`1664`: Fixed accidental displacement in :class:`~.Axes` caused by ``include_numbers`` / ``numbers_to_include`` * :pr:`1670`: Fixed missing
|
compatibility via metaclass: :class:`~.Group` Fixed bugs ---------- * :pr:`1740`: Fix pillow to <8.3.0 * :pr:`1729`: Fix bug when using :class:`~.Text` with the OpenGL renderer * :pr:`1675`: Fixed ignored fill and stroke colors for :class:`~.SVGMobject` * :pr:`1664`: Fixed accidental displacement in :class:`~.Axes` caused by ``include_numbers`` / ``numbers_to_include`` * :pr:`1670`: Fixed missing ``numpy`` import in OpenGL shader example * :pr:`1636`: Fixed bugs and added examples to methods and classes in :mod:`manim.mobject.matrix` * :pr:`1614`: Fix tick issues and improve tick placement for :class:`~.NumberLine` * :pr:`1593`: Un-flip output of ``get_frame()`` when using the OpenGL renderer * :pr:`1619`: Fix output of automatically detected LaTeX errors * :pr:`1595`: Fixed a few CLI and rendering bugs - Corrected issue where gifs were being logged with an incorrect extension - Fixed issue where videos were output when format was set to png - Added logging for png output - Added precedence handling when the ``write_to_movie`` flag would conflict with ``--format`` - Fixed issue that caused png image output to be ignored when caching was enabled * :pr:`1635`: Added missing numpy import for :mod:`manim.mobject.probability` * :pr:`1634`: Fixed OpenGL examples for MacOS Renamed deprecated ``gl_FragColor`` to ``fragColor``. Documentation-related changes ----------------------------- * :pr:`1732`: Remove reference to ``--plugins`` flag * :pr:`1734`: Fix inheritance graph background color * :pr:`1698`: Added an example for :class:`~.PMobject` * :pr:`1690`: Added an example for :class:`~.CoordinateSystem` * :pr:`1510`: Add a tutorial for using :class:`~.Text` and :class:`~.Tex` * :pr:`1685`: Added an example and parameter description for :class:`~.AnnularSector` * :pr:`1687`: Updated imports in ``geometry.py`` and added example to :class:`~.Arrow` * :pr:`1681`: Added an example for :class:`~.NumberLine` * :pr:`1697`: Added an example for :class:`~.PGroup` * :pr:`1594`: Several improvements to the documentation design and layout * :pr:`1696`: Added an example for :class:`~.DashedVMobject` * :pr:`1637`: Added an example for :class:`~.FunctionGraph` * :pr:`1626`: Added an example for :class:`~.Prism` * :pr:`1712`: Added a second example for :class:`~.DoubleArrow` * :pr:`1710`: Update copyright year in documentation to 2020-2021 * :pr:`1708`: Fixed link to interactive example notebook * :pr:`1657`: Added an example for :class:`~.ParametricSurface` * :pr:`1642`: Added examples and docstrings for :class:`~.BarChart` * :pr:`1700`: Added an example for :meth:`~.Mobject.scale` * :pr:`1689`: Added an example for :class:`~.SurroundingRectangle` * :pr:`1627`: Added an example for :class:`~.Sphere` * :pr:`1569`: Added example to demonstrate differences between :class:`~.Transform` and :class:`~.ReplacementTransform` * :pr:`1647`: Added an example for :class:`~.Sector` * :pr:`1673`: Updated documentation examples for :class:`~.Text` and :class:`~.MarkupText`: set ``weight=BOLD`` instead of ``style`` * :pr:`1650`: Added an example for :class:`~.ArcBetweenPoints` * :pr:`1628`: Added an example for :class:`~.NumberPlane` * :pr:`1646`: Added an example for :class:`~.Underline` * :pr:`1659`: Added more details to the Google Colab installation instructions * :pr:`1658`: Updated python requirement in the documentation * :pr:`1639`: Added an example for :class:`~.SampleSpace` * :pr:`1640`: Added an example for :class:`~.Point` * :pr:`1643`: Fixed ``RightArcAngleExample`` for :class:`~.Angle` in documentation * :pr:`1617`: Visually improved an example in our tutorial * :pr:`1641`: Added an example for :class:`~.ComplexPlane` * :pr:`1644`: Added an example for :class:`~.BackgroundRectangle` * :pr:`1633`: Added an example for :class:`~.Integer` * :pr:`1630`: Added an example for :class:`~.Arc` * :pr:`1631`: Added an example for :class:`~.BulletedList` * :pr:`1620`: Fixed reference to command line
|
:pr:`1617`: Visually improved an example in our tutorial * :pr:`1641`: Added an example for :class:`~.ComplexPlane` * :pr:`1644`: Added an example for :class:`~.BackgroundRectangle` * :pr:`1633`: Added an example for :class:`~.Integer` * :pr:`1630`: Added an example for :class:`~.Arc` * :pr:`1631`: Added an example for :class:`~.BulletedList` * :pr:`1620`: Fixed reference to command line interface help command Changes to our development infrastructure ----------------------------------------- * :pr:`1623`: CI: branch rename: master -> main * :pr:`1621`: Revert default template and add new templates * :pr:`1573`: PR template for the manim hackathon Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1720`: Renamed incorrect references of ``master`` to ``main`` * :pr:`1692`: Removed redundant warning in CLI parsing * :pr:`1651`: Small code cleanup for :class:`~.Polygram` * :pr:`1610`: Changed one image extension to lowercase letters New releases ------------ * :pr:`1738`: Preparation for v0.8.0: added changelog and bumped version number ================================================ FILE: docs/source/changelog/0.9.0-changelog.rst ================================================ ****** v0.9.0 ****** :Date: August 02, 2021 Contributors ============ A total of 35 people contributed to this release. People with a '+' by their names authored a patch for the first time. * Alex Lembcke * Benjamin Hackl * Darylgolden * Devin Neal * Harivinay + * Hugues Devimeux * Jared Hughes + * Jason Villanueva * Kadatatlu Kishore + * KingWampy * LED Me Explain + * Laith Bahodi * Mohammad Al-Fetyani * Noam Zaks * Oliver * PaulCMurdoch * Raghav Prabhakar + * Ryan McCauley * Suhail Sherif + * Taektiek + * Udeshya Dhungana + * UraniumCronorum + * Vinh H. Pham (Vincent) + * ccn + * icedcoffeeee + * sahilmakhijani + * sparshg The patches included in this release have been reviewed by the following contributors. * Abhijith Muthyala * Alex Lembcke * Benjamin Hackl * Darylgolden * Devin Neal * Harivinay * Hugues Devimeux * Jan-Hendrik Müller * Jason Villanueva * KingWampy * Laith Bahodi * Lino * Mohammad Al-Fetyani * Oliver * Raghav Goel * Suhail Sherif * icedcoffeeee * sahilmakhijani * sparshg Pull requests merged ==================== A total of 55 pull requests were merged for this release. Highlights ---------- * :pr:`1677`: Added a new :class:`~.Table` mobject This brings easy-to-use and customizable tables to Manim. Several examples for this new mobject can be found at :mod:`te module documentation page <.mobject.table>` and its subpages. Deprecated classes and functions -------------------------------- * :pr:`1848`: Deprecated parameters for :class:`~.DashedLine` and :class:`~.DashedVMobject` - ``dash_spacing`` is an unused parameter - ``positive_space_ratio`` has been replaced with the shorter name ``dashed_ratio`` * :pr:`1773`: Remove all classes and functions that were deprecated until ``v0.7.0`` and ``v0.8.0`` The classes ``FadeInFrom``, ``FadeOutAndShift``, ``FadeOutToPoint``, ``FadeInFromPoint``, ``FadeInFromLarge``, ``VFadeIn``, ``VFadeOut``, ``VFadeInThenOut`` have been removed, use :class:`~.FadeIn` or :class:`~.FadeOut` with appropriate keyword arguments instead. The classes ``CircleIndicate``, ``ShowCreationThenDestruction``, ``AnimationOnSurroundingRectangle``, ``ShowPassingFlashAround``, ``ShowCreationThenDestructionAround``, ``ShowCreationThenFadeAround``, ``WiggleOutThenIn``, ``TurnInsideOut`` have been removed. Use :class:`~.Circumscribe`, :class:`~.ShowPassingFlash`, or :class:`~.Wiggle` instead. The classes ``OpenGLTexMobject`` and ``OpenGLTextMobject`` have been removed, use :class:`~.MathTex` and :class:`~.Tex` instead. Also, ``VMobjectFromSVGPathstring`` has been removed, use :class:`~.SVGPathMobject` instead. Finally, the utility functions ``get_norm`` and ``cross`` have been removed (use the corresponding Numpy methods instead), and the function ``angle_between`` has been replaced
|
Use :class:`~.Circumscribe`, :class:`~.ShowPassingFlash`, or :class:`~.Wiggle` instead. The classes ``OpenGLTexMobject`` and ``OpenGLTextMobject`` have been removed, use :class:`~.MathTex` and :class:`~.Tex` instead. Also, ``VMobjectFromSVGPathstring`` has been removed, use :class:`~.SVGPathMobject` instead. Finally, the utility functions ``get_norm`` and ``cross`` have been removed (use the corresponding Numpy methods instead), and the function ``angle_between`` has been replaced with ``angle_between_vectors``. * :pr:`1731`: Deprecated :class:`~.ParametricSurface` parameters - ``u_min`` and ``u_max`` have been replaced by ``u_range``. - ``v_min`` and ``v_max`` have been replaced by ``v_range``. New features ------------ * :pr:`1780`: Allow non-numerical values to be added to :class:`~.NumberLine` and :class:`~.Axes` - Added :meth:`.NumberLine.add_labels` method to :class:`~.NumberLine` which accepts a dictionary of positions/values. - :meth:`.CoordinateSystem.add_coordinates` now accepts a dictionary too. * :pr:`1719`: Added a :class:`~.Broadcast` animation * :pr:`1765`: Added a static method :meth:`.Circle.from_three_points` for defining a circle from three points - Added a new :func:`~.perpendicular_bisector` function in ``space_ops.py`` * :pr:`1686`: Added :meth:`.ParametricSurface.set_fill_by_value` This method enables a color gradient to be applied to a :class:`~.ParametricSurface`, including the ability to define at which points the colors should be centered. Enhancements ------------ * :pr:`1833`: Added OpenGL compatibility for :class:`~.VDict`, :meth:`~.Axes.get_line_graph` and :class:`~.FocusOn` * :pr:`1760`: Added ``window_size`` flag to manually adjust the size of the OpenGL window Accepts a tuple in the form: ``x,y``. * :pr:`1823`: Reworked :class:`~.DashedVMobject` Rewritten the logic to generate dashes * :pr:`1808`: OpenGL renderer updates - Adds model matrices to all OpenGLVMobjects - Improved performance on vectorized mobject shaders - Added updaters that are part of the scene rather than a mobject * :pr:`1787`: Made :class:`~.DecimalNumber` apply color to the ellipsis Made color apply to the dots when `show_ellipsis` is set to true in `DecimalNumber` * :pr:`1775`: Let :class:`~.Create` work on :class:`~.OpenGLSurface` * :pr:`1757`: Added warning when there is a large number of items to hash. * :pr:`1774`: Add the ``reverse`` parameter to :class:`~.Write` Fixed bugs ---------- * :pr:`1722`: Fixed ``remover=True`` for :class:`~.AnimationGroup` * :pr:`1727`: Fixed some hot reload issues and compatibility with IDEs - Fixed interactive embed issue where it would fail when running on non-tty terminals - Fixed issue where file observer would error after the second run as the first observer was not closed * :pr:`1844`: Fixed the oversized :class:`~.Code` window with the OpenGL renderer * :pr:`1821`: Fixed issues concerning ``frame_center`` in :class:`~.ThreeDScene` - Changing ``frame_center`` in a :class:`~.ThreeDScene` now actually changes the camera position. - An animation with only ``frame_center`` animated will now be rendered properly. - A black dot is not created at the origin once ``frame_center`` is animated. * :pr:`1826`: Fixed scaling issue with :meth:`.BarChart.change_bar_values` * :pr:`1839`: Allow passing arguments to ``.animate`` with the OpenGL renderer * :pr:`1791`: :meth:`~.Mobject.set_z_index` now sets all submobjects' ``z_index`` value * :pr:`1792`: Fixed bug that caused dry runs to fail when using the PNG format * :pr:`1790`: Fixed an import from ``manimlib`` * :pr:`1782`: Fixed :class:`~.Tex` not working properly with the OpenGL renderer * :pr:`1783`: Fixed :meth:`~.OpenGLMobject.shuffle` function and added :meth:`~.Mobject.invert` to OpenGL * :pr:`1786`: Fixed :class:`~.DecimalNumber` not working properly when the number of digits changes * :pr:`1763`: Fixed not being able to set some CLI flags in the configuration
|
from ``manimlib`` * :pr:`1782`: Fixed :class:`~.Tex` not working properly with the OpenGL renderer * :pr:`1783`: Fixed :meth:`~.OpenGLMobject.shuffle` function and added :meth:`~.Mobject.invert` to OpenGL * :pr:`1786`: Fixed :class:`~.DecimalNumber` not working properly when the number of digits changes * :pr:`1763`: Fixed not being able to set some CLI flags in the configuration file * :pr:`1776`: :meth:`.CoordinateSystem.get_riemann_rectangles` now uses the graph's range instead of the axes range If no range specified, `get_riemann_rectangles` generates the rectangles only where the area is correctly bounded * :pr:`1770`: Rewrote :meth:`.OpenGLMobject.put_start_and_end_on` to work correctly in 3D * :pr:`1736`: Fixed :class:`~.LinearTransformationScene` crashing on multiple animations Documentation-related changes ----------------------------- * :pr:`1852`: Fixed docs for :meth:`.Coordinate_system.add_coordinates` and moved :class: `~.Code` example * :pr:`1807`: Updated installation instructions - Added a warning about the incompatibility of different versions of Manim in the README - Modified the admonition warning in the documentation - Removed duplicated information from the README (``pip install manim`` is already covered in the docs) * :pr:`1739`: Added a section on creating a custom animation to the "Manim's building blocks" tutorial * :pr:`1835`: Updated documentation with information about reworked graphical unit test system * :pr:`1845`: Improve ``ThreeDSurfacePlot`` example in example gallery * :pr:`1842`: Removed instructions on installing Poetry from Developer Installation documentation, reference Poetry's documentation instead * :pr:`1829`: Switch the order of Scoop and Chocolatey in the docs for the Windows Installation * :pr:`1827`: Added ``robots.txt`` to prevent old versions of documentation from showing in search results * :pr:`1819`: Removed mention of ``-h`` CLI flag from documentation * :pr:`1813`: Removed unused variables from tutorial * :pr:`1815`: Added codespell to the list of used linters in the contribution guidelines * :pr:`1778`: Improve sidebar structure of the documentation's reference manual * :pr:`1749`: Added documentation and example for :meth:`.VMobject.set_fill` * :pr:`1743`: Edited the developer installation instructions to include information on cloning the repository * :pr:`1706`: Rework example for :class:`~.Variable` Changes concerning the testing system ------------------------------------- * :pr:`1836`: Converted all the graphical tests to the new syntax * :pr:`1802`: Refactored graphical unit testing system, and implemented multi frames tests This PR introduces a new ``@frames_comparison`` decorator which allows writing simple ``construct``-like functions as tests. Control data for new tests can be easily generated by calling ``pytest --set_test``. Changes to our development infrastructure ----------------------------------------- * :pr:`1830`: Be more concise about the documentation URL in the PR template Code quality improvements and similar refactors ----------------------------------------------- * :pr:`1851`: Renamed ``Tabular`` to :class:`~.Table` * :pr:`1817`: Remove pillow version requirement * :pr:`1806`: Fixed spelling mistake * :pr:`1745`: Updated the BibTeX template in the README to Manim v0.9.0 New releases ------------ * :pr:`1850`: Bump version number to ``v0.9.0`` and generate changelog ================================================ SYMLINK: docs/source/conduct.md -> CODE_OF_CONDUCT.md ================================================ ================================================ FILE: docs/source/contributing/development.md ================================================ # Manim Development Process ## For first-time contributors 1. Install git: For instructions see <https://git-scm.com/>. 2. Fork the project: Go to <https://github.com/ManimCommunity/manim> and click the "fork" button to create a copy of the project for you to work on. You will need a GitHub account. This will allow you to make a "Pull Request" (PR) to the ManimCommunity repo later
|
git: For instructions see <https://git-scm.com/>. 2. Fork the project: Go to <https://github.com/ManimCommunity/manim> and click the "fork" button to create a copy of the project for you to work on. You will need a GitHub account. This will allow you to make a "Pull Request" (PR) to the ManimCommunity repo later on. 3. Clone your fork to your local computer: ```shell git clone https://github.com/<your-username>/manim.git ``` GitHub will provide both a SSH (`git@github.com:<your-username>/manim.git`) and HTTPS (`https://github.com/<your-username>/manim.git`) URL for cloning. You can use SSH if you have SSH keys setup. :::{WARNING} Do not clone the ManimCommunity repository. You must clone your own fork. ::: 4. Change the directory to enter the project folder: ```shell cd manim ``` 5. Add the upstream repository, ManimCommunity: ```shell git remote add upstream https://github.com/ManimCommunity/manim.git ``` 6. Now, `git remote -v` should show two remote repositories named: - `origin`, your forked repository - `upstream` the ManimCommunity repository 7. Install the Python project management tool `uv`, as recommended in our {doc}`installation guide for users </installation/uv>`. 8. Let `uv` create a virtual environment for your development installation by running ```shell uv sync ``` In case you need (or want) to install some of the optional dependency groups defined in our [`pyproject.toml`](https://github.com/ManimCommunity/manim/blob/main/pyproject.toml), run `uv sync --all-extras`, or pass the `--extra` flag with the name of a group, for example `uv sync --extra jupyterhub`. 9. Install Pre-Commit: ```shell uv run pre-commit install ``` This will ensure during development that each of your commits is properly formatted against our linter and formatters. You are now ready to work on Manim! ## Develop your contribution 1. Checkout your local repository's main branch and pull the latest changes from ManimCommunity, `upstream`, into your local repository: ```shell git switch main git pull --rebase upstream main ``` 2. Create a branch for the changes you want to work on rather than working off of your local main branch: ```shell git switch -c <new branch name> upstream/main ``` This ensures you can easily update your local repository's main with the first step and switch branches to work on multiple features. 3. Write some awesome code! You're ready to make changes in your local repository's branch. You can add local files you've changed within the current directory with `git add .`, or add specific files with ```shell git add <file/directory> ``` and commit these changes to your local history with `git commit`. If you have installed pre-commit, your commit will succeed only if none of the hooks fail. :::{tip} When crafting commit messages, it is highly recommended that you adhere to [these guidelines](https://www.conventionalcommits.org/en/v1.0.0/). ::: 4. Add new or update existing tests. Depending on your changes, you may need to update or add new tests. For new features, it is required that you include tests with your PR. Details of our testing system are explained in the {doc}`testing guide <testing>`. 5. Update docstrings and documentation: Update the docstrings (the text in triple quotation marks) of any functions or classes you change and include them with any new functions you add. See
|
that you include tests with your PR. Details of our testing system are explained in the {doc}`testing guide <testing>`. 5. Update docstrings and documentation: Update the docstrings (the text in triple quotation marks) of any functions or classes you change and include them with any new functions you add. See the {doc}`documentation guide <docs/docstrings>` for more information about how we prefer our code to be documented. The content of the docstrings will be rendered in the {doc}`reference manual <../reference>`. :::{tip} Use the {mod}`manim directive for Sphinx <manim.utils.docbuild.manim_directive>` to add examples to the documentation! ::: As far as development on your local machine goes, these are the main steps you should follow. (polishing-changes-and-submitting-a-pull-request)= ## Polishing Changes and Submitting a Pull Request As soon as you are ready to share your local changes with the community so that they can be discussed, go through the following steps to open a pull request. A pull request signifies to the ManimCommunity organization, "Here are some changes I wrote; I think it's worthwhile for you to maintain them." :::{note} You do not need to have everything (code/documentation/tests) complete to open a pull request (PR). If the PR is still under development, please mark it as a draft. Community developers will still be able to review the changes, discuss yet-to-be-implemented changes, and offer advice; however, the more complete your PR, the quicker it will be merged. ::: 1. Update your fork on GitHub to reflect your local changes: ```shell git push -u origin <branch name> ``` Doing so creates a new branch on your remote fork, `origin`, with the contents of your local repository on GitHub. In subsequent pushes, this local branch will track the branch `origin` and `git push` is enough. 2. Make a pull request (PR) on GitHub. In order to make the ManimCommunity development team aware of your changes, you can make a PR to the ManimCommunity repository from your fork. :::{WARNING} Make sure to select `ManimCommunity/manim` instead of `3b1b/manim` as the base repository! ::: Choose the branch from your fork as the head repository - see the screenshot below. ```{image} /_static/pull-requests.png :align: center ``` Please make sure you follow the template (this is the default text you are shown when first opening the 'New Pull Request' page). Your changes are eligible to be merged if: 1. there are no merge conflicts 2. the tests in our pipeline pass 3. at least one (two for more complex changes) Community Developer approves the changes You can check for merge conflicts between the current upstream/main and your branch by executing `git pull upstream main` locally. If this generates any merge conflicts, you need to resolve them and push an updated version of the branch to your fork of the repository. Our pipeline consists of a series of different tests that ensure that Manim still works as intended and that the code you added sticks to our coding conventions. - **Code style**: We use the code style imposed by [Black](https://black.readthedocs.io/en/stable/), [isort](https://pycqa.github.io/isort/) and [flake8](https://flake8.pycqa.org/en/latest/). The GitHub pipeline
|
your fork of the repository. Our pipeline consists of a series of different tests that ensure that Manim still works as intended and that the code you added sticks to our coding conventions. - **Code style**: We use the code style imposed by [Black](https://black.readthedocs.io/en/stable/), [isort](https://pycqa.github.io/isort/) and [flake8](https://flake8.pycqa.org/en/latest/). The GitHub pipeline makes sure that the (Python) files changed in your pull request also adhere to this code style. If this step of the pipeline fails, fix your code formatting automatically by running `black <file or directory>` and `isort <file or directory>`. To fix code style problems, run `flake8 <file or directory>` for a style report, and then fix the problems manually that were detected by `flake8`. - **Tests**: The pipeline runs Manim's test suite on different operating systems (the latest versions of Ubuntu, macOS, and Windows) for different versions of Python. The test suite consists of two different kinds of tests: integration tests and doctests. You can run them locally by executing `uv run pytest` and `uv run pytest --doctest-modules manim`, respectively, from the root directory of your cloned fork. - **Documentation**: We also build a version of the documentation corresponding to your pull request. Make sure not to introduce any Sphinx errors, and have a look at the built HTML files to see whether the formatting of the documentation you added looks as you intended. You can build the documentation locally by running `make html` from the `docs` directory. Make sure you have [Graphviz](https://graphviz.org/) installed locally in order to build the inheritance diagrams. See {doc}`docs` for more information. Finally, if the pipeline passes and you are satisfied with your changes: wait for feedback and iterate over any requested changes. You will likely be asked to edit or modify your PR in one way or another during this process. This is not an indictment of your work, but rather a strong signal that the community wants to merge your changes! Once approved, your changes may be merged! ### Further useful guidelines 1. When submitting a PR, please mention explicitly if it includes breaking changes. 2. When submitting a PR, make sure that your proposed changes are as general as possible, and ready to be taken advantage of by all of Manim's users. In particular, leave out any machine-specific configurations, or any personal information it may contain. 3. If you are a maintainer, please label issues and PRs appropriately and frequently. 4. When opening a new issue, if there are old issues that are related, add a link to them in your new issue (even if the old ones are closed). 5. When submitting a code review, it is highly recommended that you adhere to [these general guidelines](https://conventionalcomments.org/). 6. If you find stale or inactive issues that seem to be irrelevant, please post a comment saying 'This issue should be closed', and a community developer will take a look. 7. Please do as much as possible to keep issues, PRs, and development in general as tidy as possible. You can find examples
|
stale or inactive issues that seem to be irrelevant, please post a comment saying 'This issue should be closed', and a community developer will take a look. 7. Please do as much as possible to keep issues, PRs, and development in general as tidy as possible. You can find examples for the `docs` in several places: the {doc}`Example Gallery <../examples>`, {doc}`Tutorials <../tutorials/index>`, and {doc}`Reference Classes <../reference>`. **Thank you for contributing!** ================================================ FILE: docs/source/contributing/docs.rst ================================================ ==================== Adding Documentation ==================== Building the documentation -------------------------- When you clone the Manim repository from GitHub, you can access the ``docs/`` folder which contains the necessary files to build the documentation. To build the docs locally, open a CLI, enter the ``docs/`` folder with the ``cd`` command and execute the following depending on your OS: - Windows: ``./make.bat html`` - macOS and Linux: ``make html`` The first time you build the docs, the process will take several minutes because it needs to generate all the ``.rst`` (reST: reStructured Text) files from scratch by reading and parsing all the Manim content. The process becomes much shorter the next time, as it rebuilds only the parts which have changed. Sphinx library and extensions ----------------------------- Manim uses `Sphinx <https://www.sphinx-doc.org>`_ for building the docs. It also makes use of Sphinx extensions such as: - `Autodoc: <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html>`_ imports Manim's Python source code, extracts its docstrings and generates documentation from them. - `Autosummary: <https://www.sphinx-doc.org/en/master/usage/extensions/autosummary.html>`_ a complement to Autodoc which adds a special directive ``autosummary``, used in Manim to automatically document classes, methods, attributes, functions, module-level variables and exceptions. Autosummary makes use of `Jinja templates <https://jinja.palletsprojects.com/templates/>`_, which Manim defines for autosummarizing classes and modules inside ``docs/source/_templates/``. - `Graphviz extension for Sphinx: <https://www.sphinx-doc.org/en/master/usage/extensions/graphviz.html>`_ embeds graphs generated by the `Graphviz <https://graphviz.org/>`_ module, which must be installed in order to render the inheritance diagrams in the :doc:`/reference`. - `Napoleon: <https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html>`_ enables Sphinx to read Google style docstrings and, in particular for Manim, `NumPy style docstrings <https://numpydoc.readthedocs.io/en/latest/format.html>`_ - see :doc:`docs/docstrings` for more information. Sphinx theme ------------ The theme used for this website is `Furo <https://sphinx-themes.org/sample-sites/furo/>`_. Custom Sphinx directives ------------------------ Manim implements **custom directives** for use with Autodoc and Autosummary, which are defined in :mod:`~.docbuild`: .. currentmodule:: manim.utils.docbuild .. autosummary:: :toctree: ../reference autoaliasattr_directive autocolor_directive manim_directive Index ----- .. toctree:: :maxdepth: 2 docs/admonitions docs/docstrings docs/examples docs/references docs/typings docs/types ================================================ FILE: docs/source/contributing/internationalization.rst ================================================ ==================== Internationalization ==================== Thank you for your interest in localizing Manim! Please read the instructions below to get started. You are also encouraged, though not required, to join our `Discord server <https://manim.community/discord>`__. Signing up ========== You will first need to create an account for our project. Go to our `project homepage <https://translate.manim.community/>`__ and click the sign up button at the top right hand corner. Follow the instructions to create an account. After creating an account, you should return back to our homepage. Click the Manim project to contribute translations for the main library. Contributing ============ .. important:: Keep in mind that Manim is still a work in progress. Tutorials and documentation are always subject to change. When
|
to create an account. After creating an account, you should return back to our homepage. Click the Manim project to contribute translations for the main library. Contributing ============ .. important:: Keep in mind that Manim is still a work in progress. Tutorials and documentation are always subject to change. When a developer implements a new feature, they are not forced to respect any translations. This means that parts of the translation might become outdated over time. That being said, improving the documentation and making it more accessible is still highly encouraged. And even if your work gets outdated and requires change, you or someone else can simply adjust the translation. Your efforts are not in vain! Voting ------ To ensure that our translations are of good quality, we use crowdsourcing and voting to approve good translations and reject bad ones. The current threshold for a translation being accepted is 3 votes; this may change as we gauge the level of activity in the community and the quality of translations. To vote on translations, first click on a language you would like to help with, then click the "translate all" button. You should then enter the translation editor. Next to the search bar, you will see a funnel-like icon - click it and select the "Need to Be Voted" option to see translations that need to be voted on. You can then select a string on the left sidebar, view the translations at the bottom and vote with the + and - icons for good and poor translations respectively. Translations ------------ You can also help with contributing translations directly. Follow the steps above to enter the translation editor (instead of clicking "Translate all", you may also choose to translate strings from a specific file by clicking them). Crowdin's on-screen tutorial should guide you through the process. Translation guidelines ====================== In general, follow the conventions for technical writing in your target language. You may want to refer to similar, high quality sources (eg. Python's documentation in your language) for guidance. Note that code blocks, code literals, names and pseudonyms should be left unchanged. Proofreading ============ For certain languages with a significant number of speakers within the Manim Community, an additional step of proofreading is used after crowdsourcing to further ensure the quality of our translations. Proofreaders are trusted community members who will look over and give the final approval on translations. If you would like to be a proofreader, please email translations@manim.community with the answers to the following questions: 1. What is your Crowdin username? 2. What is your Discord username (optional)? 3. What is your GitHub username (optional)? 4. List the languages you speak, and your level of fluency with them. 5. What language(s) are you applying to be a proofreader for? 6. Do you have any previous experience with translations? 7. If yes, give us more details. 8. How will you ensure the quality of translations, should you become a proofreader? Please note that you don't need to have prior
|
5. What language(s) are you applying to be a proofreader for? 6. Do you have any previous experience with translations? 7. If yes, give us more details. 8. How will you ensure the quality of translations, should you become a proofreader? Please note that you don't need to have prior translation experience to be a proofreader, just a commitment to maintaining a good quality of translations. Errors ====== Source errors ------------- If you spot an error with a source string, report it to us by opening an :issue:`issue <new/choose>` on GitHub. Refrain from translating the string until the issue is resolved. ================================================ FILE: docs/source/contributing/performance.rst ================================================ ===================== Improving performance ===================== One of Manim's main flaws as an animation library is its slow performance. As of time of writing (January 2022), the library is still very unoptimized. As such, we highly encourage contributors to help out in optimizing the code. Profiling ========= Before the library can be optimized, we first need to identify the bottlenecks in performance via profiling. There are numerous Python profilers available for this purpose; some examples include cProfile and Scalene. Running an animation as a script -------------------------------- Most instructions for profilers assume you can run the python file directly as a script from the command line. While Manim animations are usually run from the command-line, we can run them as scripts by adding something like the following to the bottom of the file: .. code-block:: python with tempconfig({"quality": "medium_quality", "disable_caching": True}): scene = SceneName() scene.render() Where ``SceneName`` is the name of the scene you want to run. You can then run the file directly, and can thus follow the instructions for most profilers. An example: profiling with cProfile and SnakeViz ------------------------------------------------- Install SnakeViz: .. code-block:: bash pip install snakeviz cProfile is included with in Python's standard library and does not need to be installed. Suppose we want to profile ``SquareToCircle``. Then we add and save the following code to ``square_to_circle.py``: .. code-block:: python from manim import * class SquareToCircle(Scene): def construct(self): s = Square() c = Circle() self.add(s) self.play(Transform(s, c)) with tempconfig({"quality": "medium_quality", "disable_caching": True}): scene = SquareToCircle() scene.render() Now run the following in the terminal: .. code-block:: bash python -m cProfile -o square_to_circle.txt square_to_circle.py This will create a file called ``square_to_circle.txt``. Now, we can run SnakeViz on the profile file: .. code-block:: bash snakeviz square_to_circle.txt A browser window or tab will open with a visualization of the profile, which should look something like this: .. image:: /_static/snakeviz.png ================================================ FILE: docs/source/contributing/testing.rst ================================================ ============ Adding Tests ============ If you are adding new features to manim, you should add appropriate tests for them. Tests prevent manim from breaking at each change by checking that no other feature has been broken and/or been unintentionally modified. .. warning:: The full tests suite requires Cairo 1.18 in order to run all tests. However, Cairo 1.18 may not be available from your package manager, like ``apt``, and it is very likely that you have an older version installed, e.g., 1.16. If you run tests
|
and/or been unintentionally modified. .. warning:: The full tests suite requires Cairo 1.18 in order to run all tests. However, Cairo 1.18 may not be available from your package manager, like ``apt``, and it is very likely that you have an older version installed, e.g., 1.16. If you run tests with a version prior to 1.18, many tests will be skipped. Those tests are not skipped in the online CI. If you want to run all tests locally, you need to install Cairo 1.18 or above. You can do so by compiling Cairo from source: 1. download ``cairo-1.18.0.tar.xz`` from `here <https://www.cairographics.org/releases/>`_. and uncompress it; 2. open the INSTALL file and follow the instructions (you might need to install ``meson`` and ``ninja``); 3. run the tests suite and verify that the Cairo version is correct. How Manim tests --------------- Manim uses pytest as its testing framework. To start the testing process, go to the root directory of the project and run pytest in your terminal. Any errors that occur during testing will be displayed in the terminal. Some useful pytest flags: - ``-x`` will make pytest stop at the first failure it encounters - ``-s`` will make pytest display all the print messages (including those during scene generation, like DEBUG messages) - ``--skip_slow`` will skip the (arbitrarily) slow tests - ``--show_diff`` will show a visual comparison in case a unit test is failing. How it Works ~~~~~~~~~~~~ At the moment there are three types of tests: #. Unit Tests: Tests for most of the basic functionalities of manim. For example, there a test for ``Mobject``, that checks if it can be added to a Scene, etc. #. Graphical unit tests: Because ``manim`` is a graphics library, we test frames. To do so, we create test scenes that render a specific feature. When pytest runs, it compares the result of the test to the control data, either at 6 fps or just the last frame. If it matches, the tests pass. If the test and control data differ, the tests fail. You can use ``--show_diff`` flag with ``pytest`` to visually see the differences. The ``extract_frames.py`` script lets you see all the frames of a test. #. Videos format tests: As Manim is a video library, we have to test videos as well. Unfortunately, we cannot directly test video content as rendered videos can differ slightly depending on the system (for reasons related to ffmpeg). Therefore, we only compare video configuration values, exported in .json. Architecture ------------ The ``manim/tests`` directory looks like this: :: . ├── conftest.py ├── control_data │ ├── graphical_units_data │ │ ├── creation │ │ │ ├── DrawBorderThenFillTest.npy │ │ │ ├── FadeInFromDownTest.npy │ │ │ ├── FadeInFromLargeTest.npy │ │ │ ├── FadeInFromTest.npy │ │ │ ├── FadeInTest.npy │ │ │ ├── ... │ │ ├── geometry │ │ │ ├── Annulanpy │ │ │ ├── AnnulusTest.npy │ │ │ ├── ArcBetweenPointsTest.npy │ │ │ ├── ArcTest.npy │ │ │ ├── CircleTest.npy │ │ │ ├── CoordinatesTest.npy │ │ │
|
│ ├── FadeInFromTest.npy │ │ │ ├── FadeInTest.npy │ │ │ ├── ... │ │ ├── geometry │ │ │ ├── Annulanpy │ │ │ ├── AnnulusTest.npy │ │ │ ├── ArcBetweenPointsTest.npy │ │ │ ├── ArcTest.npy │ │ │ ├── CircleTest.npy │ │ │ ├── CoordinatesTest.npy │ │ │ ├── ... │ │ ├── graph │ │ │ ├── ... | | | | ... │ └── videos_data │ ├── SquareToCircleWithDefaultValues.json │ └── SquareToCircleWit.json ├── helpers │ ├── graphical_units.py │ ├── __init__.py │ └── video_utils.py ├── __init__.py ├── test_camera.py ├── test_config.py ├── test_copy.py ├── test_vectorized_mobject.py ├── test_graphical_units │ ├── conftest.py │ ├── __init__.py │ ├── test_creation.py │ ├── test_geometry.py │ ├── test_graph.py │ ├──est_indication.py │ ├── test_movements.py │ ├── test_threed.py │ ├── test_transform.py │ └── test_updaters.py ├── test_logging │ ├── basic_scenes.py │ ├── expected.txt │ ├── testloggingconfig.cfg │ └── test_logging.py ├── test_scene_rendering │ ├── conftest.py │ ├── __init__.py │ ├── simple_scenes.py │ ├── standard_config.└── test_cli_flags.py └── utils ├── commands.py ├── __init__.py ├── testing_utils.py └── video_tester.py ... The Main Directories -------------------- - ``control_data/``: The directory containing control data. ``control_data/graphical_units_data/`` contains the expected and correct frame data for graphical tests, and ``control_data/videos_data/`` contains the .json files used to check videos. - ``test_graphical_units/``:Contains graphical tests. - ``test_scene_rendering/``: For tests that need to render a scene in some way, such as tests for CLI flags (end-to-end tests). - ``utils/``: Useful internal functions used by pytest. .. note:: fixtures are not contained here, they are in ``conftest.py``. - ``helpers/``: Helper functions for developers to setup graphical/video tests. Adding a New Test ----------------- Unit Tests ~~~~~~~~~~ Pytest determines which functions are tests by searching for files whose names begin with "test\_", and then within those files for functions beginning with "test" and classes beginning with "Test". These kinds of tests must be in ``tests/`` (e.g. ``tests/test_container.py``). Graphical Unit Test ~~~~~~~~~~~~~~~~~~~ The test must be written in the correct file (i.e. the file that corresponds to the appropriate category the feature belongs to) and follow the structure of unit tests. For example, to test the ``Circle`` VMobject which resides in ``manim/mobject/geometry.py``, add the CircleTest to ``test/test_geometry.py``. The name of the module is indicated by the variable __module_test__, that **must** be declared in any graphical test file. The module name is used to store the graphical control data. .. important:: You will need to use the ``frames_comparison`` decorator to create a test. The test function **must** accept a parameter named ``scene`` that will be used like ``self`` in a standard ``construct`` method. Here's an example in ``test_geometry.py``: .. code:: python from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "geometry" @frames_comparison def test_circle(scene): circle = Circle() scene.play(Animation(circle)) The decorator can be used with or without parentheses. **By default, the test only tests the last frame. To enable multi-frame testing, you have to set ``last_frame=False`` in the parameters.** .. code:: python @frames_comparison(last_frame=False) def test_circle(scene): circle = Circle() scene.play(Animation(circle)) You can also specify, when needed, which base scene you need (ThreeDScene, for example) : .. code:: python @frames_comparison(last_frame=False,
|
**By default, the test only tests the last frame. To enable multi-frame testing, you have to set ``last_frame=False`` in the parameters.** .. code:: python @frames_comparison(last_frame=False) def test_circle(scene): circle = Circle() scene.play(Animation(circle)) You can also specify, when needed, which base scene you need (ThreeDScene, for example) : .. code:: python @frames_comparison(last_frame=False, base_scene=ThreeDScene) def test_circle(scene): circle = Circle() scene.play(Animation(circle)) Feel free to check the documentation of ``@frames_comparison`` for more. Note that tests name must follow the syntax ``test_<thing_to_test>``, otherwise pytest will not recognize it as a test. .. warning:: If you run pytest now, you will get a ``FileNotFound`` error. This is because you have not created control data for your test. To create the control data for your test, you have to use the flag ``--set_test`` along with pytest. For the example above, it would be .. code-block:: bash pytest test_geometry.py::test_circle --set_test -s (``-s`` is here to see manim logs, so you can see what's going on). If you want to see all the control data frames (e.g. to make sure your test is doing what you want), use the ``extract_frames.py`` script. The first parameter is the path to a ``.npz`` file and the second parameter is the directory you want the frames created. The frames will be named ``frame0.png``, ``frame1.png``, etc. .. code-block:: bash python scripts/extract_frames.py tests/test_graphical_units/control_data/plot/axes.npz output Please make sure to add the control data to git as soon as it is produced with ``git add <your-control-data.npz>``. Videos tests ~~~~~~~~~~~~ To test videos generated, we use the decorator ``tests.utils.videos_tester.video_comparison``: .. code:: python @video_comparison( "SquareToCircleWithlFlag.json", "videos/simple_scenes/480p15/SquareToCircle.mp4" ) def test_basic_scene_l_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ "python", "-m", "manim", simple_scenes_path, scene_name, "-l", "--media_dir", str(tmp_path), ] out, err, exit_code = capture(command) assert exit_code == 0, err .. note:: ``assert exit*\ code == 0, err`` is used in case of the command fails to run. The decorator takes two arguments: json name and the path to where the video should be generated, starting from the ``media/`` dir. Note the fixtures here: - tmp_path is a pytest fixture to get a tmp_path. Manim will output here, according to the flag ``--media_dir``. - ``manim_cfg_file`` fixture that return a path pointing to ``test_scene_rendering/standard_config.cfg``. It's just to shorten the code, in the case multiple tests need to use this cfg file. - ``simple_scenes_path`` same as above, except for ``test_scene_rendering/simple_scene.py`` You have to generate a ``.json`` file first to be able to test your video. To do that, use ``helpers.save_control_data_from_video``. For instance, a test that will check if the l flag works properly will first require rendering a video using the -l flag from a scene. Then we will test (in this case, SquareToCircle), that lives in ``test_scene_rendering/simple_scene.py``. Change directories to ``tests/``, create a file (e.g. ``create\_data.py``) that you will remove as soon as you're done. Then run: .. code:: python save_control_data_from_video("<path-to-video>", "SquareToCircleWithlFlag.json") Running this will save ``control_data/videos_data/SquareToCircleWithlFlag.json``, which will look like this: .. code:: json { "name": "SquareToCircleWithlFlag", "config": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15" } } If
|
``create\_data.py``) that you will remove as soon as you're done. Then run: .. code:: python save_control_data_from_video("<path-to-video>", "SquareToCircleWithlFlag.json") Running this will save ``control_data/videos_data/SquareToCircleWithlFlag.json``, which will look like this: .. code:: json { "name": "SquareToCircleWithlFlag", "config": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15" } } If you have any questions, please don't hesitate to ask on `Discord <https://www.manim.community/discord/>`_, in your pull request, or in an issue. ================================================ FILE: docs/source/contributing/docs/admonitions.rst ================================================ ================== Adding Admonitions ================== Adding Blocks for Tip, Note, Important etc. (Admonitions) --------------------------------------------------------- The following directives are called Admonitions. You can use them to point out additional or important information. Here are some examples: See also ~~~~~~~~ .. code-block:: rest .. seealso:: Some ideas at :mod:`~.tex_mobject`, :class:`~.Mobject`, :meth:`~.Mobject.add_updater`, :attr:`~.Mobject.depth`, :func:`~.make_config_parser` .. seealso:: Some ideas at :mod:`~.tex_mobject`, :class:`~.Mobject`, :meth:`~.Mobject.add_updater`, :attr:`~.Mobject.depth`, :func:`~.make_config_parser` .. index:: reST directives; note Note ~~~~ .. code-block:: rest .. note:: A note .. note:: A note Tip ~~~ .. code-block:: rest .. tip:: A tip .. tip:: A tip You may also use the admonition **hint**, but this is very similar and **tip** is more commonly used in the documentation. Important ~~~~~~~~~ .. code-block:: rest .. important:: Some important information which should be considered. .. important:: Some important information which should be considered. Warning ~~~~~~~ .. code-block:: rest .. warning:: Some text pointing out something that people should be warned about. .. warning:: Some text pointing out something that people should be warned about. You may also use the admonitions **caution** or even **danger** if the severity of the warning must be stressed. Attention ~~~~~~~~~ .. code-block:: rest .. attention:: A attention .. attention:: A attention You can find further information about Admonitions here: https://pradyunsg.me/furo/reference/admonitions/ ================================================ FILE: docs/source/contributing/docs/docstrings.rst ================================================ ================= Adding Docstrings ================= A docstring is a string literal that is used right after the definition of a module, function, class, or method. They are used to document our code. This page will give you a set of guidelines to write efficient and correct docstrings. Formatting the Docstrings ------------------------- Please begin the description of the class/function in the same line as the 3 quotes: .. code:: py def do_this(): """This is correct. (...) """ def dont_do_this(): """ This is incorrect. (...) """ NumPy Format ------------ The Manim Community uses numpy format for the documentation. Use the numpy format for sections and formatting - see https://numpydoc.readthedocs.io/en/latest/format.html. This includes: 1. The usage of ``Attributes`` to specify ALL ATTRIBUTES that a class can have and a brief (or long, if needed) description. Also, ``__init__`` parameters should be specified as ``Parameters`` **on the class docstring**, *rather than under* ``__init__``. Note that this can be omitted if the parameters and the attributes are the same (i.e., dataclass) - priority should be given to the ``Attributes`` section, in this case, which must **always be present**, unless the class specifies no attributes at all. (See more on Parameters in number 2 of this list.) Example: .. code:: py class MyClass: """My cool class. Long or short (whatever is more appropriate) description
|
should be given to the ``Attributes`` section, in this case, which must **always be present**, unless the class specifies no attributes at all. (See more on Parameters in number 2 of this list.) Example: .. code:: py class MyClass: """My cool class. Long or short (whatever is more appropriate) description here. Parameters ---------- name The class's name. id The class's id. mobj The mobject linked to this instance. Defaults to `Mobject()` \ (is set to that if `None` is specified). Attributes ---------- name The user's name. id The user's id. singleton Something. mobj The mobject linked to this instance. """ def __init__(name: str, id: int, singleton: MyClass, mobj: Mobject = None): ... 2. The usage of ``Parameters`` on functions to specify how every parameter works and what it does. This should be excluded if the function has no parameters. Note that you **should not** specify the default value of the parameter on the type. On the documentation render, this is already specified on the function's signature. If you need to indicate a further consequence of value omission or simply want to specify it on the docs, make sure to **specify it in the parameter's DESCRIPTION**. See an example on list item 4. .. note:: When documenting varargs (args and kwargs), make sure to document them by listing the possible types of each value specified, like this: :: Parameters ---------- args The args specified can be either an int or a float. kwargs The kwargs specified can only be a float. Note that, if the kwargs expect specific values, those can be specified in a section such as ``Other Parameters``: :: Other Parameters ---------------- kwarg_param_1 Parameter documentation here (etc) 3. The usage of ``Returns`` to indicate what is the type of this function's return value and what exactly it returns (i.e., a brief - or long, if needed - description of what this function returns). Can be omitted if the function does not explicitly return (i.e., always returns ``None`` because ``return`` is never specified, and it is very clear why this function does not return at all). In all other cases, it should be specified. See an example on list item 4. 4. The usage of ``Examples`` in order to specify an example of usage of a function **is highly encouraged** and, in general, should be specified for *every function* unless its usage is **extremely obvious**, which can be debatable. Even if it is, it's always a good idea to add an example in order to give a better orientation to the documentation user. Use the following format for Python code: .. code:: rst :: # python code here .. note:: Also, if this is a video- or animation-related change, please try to add an example GIF or video if possible for demonstration purposes. Make sure to be as explicit as possible in your documentation. We all want the users to have an easier time using this library. Example: .. code:: py def my_function( thing: int, other: np.ndarray, name: str, *,
|
try to add an example GIF or video if possible for demonstration purposes. Make sure to be as explicit as possible in your documentation. We all want the users to have an easier time using this library. Example: .. code:: py def my_function( thing: int, other: np.ndarray, name: str, *, d: "SomeClassFromFarAway", test: Optional[int] = 45 ) -> "EpicClassInThisFile": # typings are optional for now """My cool function. Builds and modifies an :class:`EpicClassInThisFile` instance with the given parameters. Parameters ---------- thing Specifies the index of life. other Specifies something cool. name Specifies my name. d Sets thing D to this value. test Defines the number of times things should be tested. \ Defaults to 45, because that is almost the meaning of life. Returns ------- :class:`EpicClassInThisFile` The generated EpicClass with the specified attributes and modifications. Examples -------- Normal usage:: my_function(5, np.array([1, 2, 3]), "Chelovek", d=SomeClassFromFarAway(cool=True), test=5) """ # code... pass ================================================ FILE: docs/source/contributing/docs/examples.rst ================================================ =============== Adding Examples =============== This is a page for adding examples to the documentation. Here are some guidelines you should follow before you publish your examples. Guidelines for examples ----------------------- Everybody is welcome to contribute examples to the documentation. Since straightforward examples are a great resource for quickly learning manim, here are some guidelines. What makes a great example -------------------------- .. note:: As soon as a new version of manim is released, the documentation will be a snapshot of that version. Examples contributed after the release will only be shown in the latest documentation. * Examples should be ready to copy and paste for use. * Examples should be brief yet still easy to understand. * Examples don't require the ``from manim import *`` statement, this will be added automatically when the docs are built. * There should be a balance of animated and non-animated examples. - As manim makes animations, we can include lots of animated examples; however, our RTD has a maximum 20 minutes to build. Animated examples should only be used when necessary, as last frame examples render faster. - Lots of examples (e.g. size of a plot-axis, setting opacities, making texts, etc.) will also work as images. It is a lot more convenient to see the end product immediately instead of waiting for an animation to reveal it. * Please ensure the examples run on the current main branch when you contribute an example. * If the functions used are confusing for people, make sure to add comments in the example to explain what they do. How examples are structured --------------------------- * Examples can be organized into chapters and subchapters. - When you create examples, the beginning example chapter should focus on only one functionality. When the functionality is simple, multiple ideas can be illustrated under a single example. - As soon as simple functionalities are explained, the chapter may include more complex examples which build on the simpler ideas. Writing examples ~~~~~~~~~~~~~~~~ When you want to add/edit examples, they can be found in the ``docs/source/`` directory, or directly in the manim
|
can be illustrated under a single example. - As soon as simple functionalities are explained, the chapter may include more complex examples which build on the simpler ideas. Writing examples ~~~~~~~~~~~~~~~~ When you want to add/edit examples, they can be found in the ``docs/source/`` directory, or directly in the manim source code (e.g. ``manim/mobject/mobject.py``). The examples are written in ``rst`` format and use the manim directive (see :mod:`manim.utils.docbuild.manim_directive` ), ``.. manim::``. Every example is in its own block, and looks like this: .. code:: rst Formulas ======== .. manim:: Formula1 :save_last_frame: class Formula1(Scene): def construct(self): t = MathTex(r"\int_a^b f'(x) dx = f(b) - f(a)") self.add(t) self.wait(1) In the building process of the docs, all ``rst`` files are scanned, and the manim directive (``.. manim::``) blocks are identified as scenes that will be run by the current version of manim. Here is the syntax: * ``.. manim:: [SCENE_NAME]`` has no indentation and ``SCENE_NAME`` refers to the name of the class below. * The flags are followed in the next line (no blank line here!), with the indentation level of one tab. All possible flags can be found at :mod:`manim.utils.docbuild.manim_directive`. In the example above, the ``Formula1`` following ``.. manim::`` is the scene that the directive expects to render; thus, in the python code, the class has the same name: ``class Formula1(Scene)``. .. note:: Sometimes, when you reload an example in your browser, it has still the old website somewhere in its cache. If this is the case, delete the website cache, or open a new incognito tab in your browser, then the latest docs should be shown. **Only for locally built documentation:** If this still doesn't work, you may need to delete the contents of ``docs/source/references`` before rebuilding the documentation. ================================================ FILE: docs/source/contributing/docs/references.rst ================================================ ================= Adding References ================= Reference to types in documentation ----------------------------------- Always specify types with the correct **role** (see https://www.sphinx-doc.org/en/1.7/domains.html#python-roles) for the sake of proper rendering. E.g.: Use ``:class:`int``` to refer to an int type, and in general ``:class:`<path>``` to refer to a certain class (see ``Path specification`` below). See after for more specific instructions. Path specifications ~~~~~~~~~~~~~~~~~~~ 1. If it's on stdlib: Use ``<name>`` directly. If it's a class, st the name is enough. If it's a method (``:meth:``) or attribute (``:attr:``), dotted names may be used (e.g. ``:meth:`str.to_lower```). Example: ``:class:`int```, ``:class:`str```, ``:class:`float```, ``:class:`bool``` 2. If it's on the same file as the docstring or, for methods and attributes, under the same class, then the name may also be specified directly. Example: ``:class:`MyClass``` referring to a class in the same file; ``:meth:`push``` referring to a methodlass; ``:meth:`MyClass.push``` referring to a method in a different class in the same file; ``:attr:`color``` referring to an attribute in the same class; ``:attr:`MyClass.color``` referring to an attribute in a different class in the same file. 3. If it's on a different file, then you may either use the full dotted name (e.g. ``~manim.animations.Animation``) or simply use the shortened way (``~.Animation``). Note that, if there is ambiguity, then the full dotted name must
|
``:attr:`MyClass.color``` referring to an attribute in a different class in the same file. 3. If it's on a different file, then you may either use the full dotted name (e.g. ``~manim.animations.Animation``) or simply use the shortened way (``~.Animation``). Note that, if there is ambiguity, then the full dotted name must be used where tual class can't be deduced. Also, note the ``~`` before the path - this is so that it displays just ``Animation`` instead of the full location in the rendering. It can be removed for disambiguation purposes only. Example: ``:class:`~.Animation```, ``:meth:`~.VMobject.set_color```, ``:attr:`~.VMobject.color``` 4. If it's a class from a different module, specify the full dotted syntax. Example: ``:class:`numpy.ndarray``` for a numpy ndarray. Reference type specifications ~~~~~~~~~~~~~~~~~~~~~ **The following instructions refer to types of attributes, parameters, and return values.** When specifying a type mid-text, it does not necessarily have to be typeset. However, if it's a class name, a method, or an enum's attribute/variant, then it is recommended to be typeset at least on the first occurrence of the name so that the users can quickly jump to the related documentation. 1. Class names should be wrapped in ``:class:`path_goes_here```. See examples in the subsection above. Method names should be wrapped in ``:meth:`path_goes_here```. See examples in the subsection above. 3. Attribute names should be wrapped in ``:attr:`path_goes_here```. See examples in the subsection above. 4. If ``None`` can also be specified, use ``Optional[type]``, where ``type`` must follow the guidelines in the current section. Example: ``Optional[:class:`str`]`` means you can either specify a ``str`` or ``None``. 5. If more than one type is possible, use ``Union[type_1, type_2, (..type_n]``, where all the ``type_n`` must follow the guidelines in the current section. Note that, if one of these types is ``None``, then the Union should be wrapped with ``Optional`` instead. Example: ``Union[:class:`str`, :class:`int`]`` for either ``str`` or ``int``. ``Optional[Union[:class:`int`, :class:`bool`]]`` for either ``int``, ``bool`` or ``None``. 6. **Dictionaries:** Use ``Dict[key_type, value_type]``, where ``key_type`` and ``value_type`` must follow the guidelines in the current section. Example: ``Dict[:class:`str`, :class:`~.Mobject`]`` is a dictionary that maps strings to Mobjects. ``Dict[:class:`str`, Union[:class:`int`, :class:`MyClass`]]`` is a dictionary that maps a string to either an int or an instance of ``MyClass``. 7. **If the parameter is a list:** Note that it is very rare to require the parameter to be exactly a ``list`` type. One could usually specify a ``tuple`` instead, for example. So, in order to cover all cases, consider: 1. If the parameter only needs to be an ``Iterable``, i.e., if the function only requires being able to iterate over this parameter's value (e.g. can be a ``list``, ``tuple``, ``str``, but also ``zip()``, ``iter()`` and so on), then specify ``Iterable[type_here]``, where ``type_here`` is the type of the iterable's yielded elements and should follow the format in the present section (``Type specifications``). Example: ``Iterable[:class:`str`]`` for any iterable of strings; ``Iterable[:class:`~.Mobject`]`` for an iterable of Mobjects; etc. 2. If you require being able to index the parameter (i.e. ``x[n]``) or retrieve its length (i.e. ``len(x)``), or even just pass it to a function
|
should follow the format in the present section (``Type specifications``). Example: ``Iterable[:class:`str`]`` for any iterable of strings; ``Iterable[:class:`~.Mobject`]`` for an iterable of Mobjects; etc. 2. If you require being able to index the parameter (i.e. ``x[n]``) or retrieve its length (i.e. ``len(x)``), or even just pass it to a function that requires any of those, then specify ``Sequence``, which allows any list-like object to be specified (e.g. ``list``, ``tuple``...) Example: ``Sequence[:class:`str`]`` for a sequence of strings; ``Sequence[Union[:class:`str`, :class:`int`]]`` for a sequence of integers or strings. 3. If you EXPLICITLY REQUIRE it to be a ``list`` for some reason, then use ``List[type]``, where ``type`` is the type that any element in the list will have. It must follow the guidelines in the current section. 8. **If the return type is a list or tuple:** Specify ``List[type]`` for a list, ``Tuple[type_a, type_b, (...), type_n]`` for a tuple (if the elements are all different) or ``Tuple[type, ...]`` (if all elements have the same type). Each ``type_n`` on those representations corresponds to elements in the returned list/tuple and must follow the guidelines in the current section. Example: ``List[Optional[:class:`str`]]`` for a list that returns elements that are either a ``str`` or ``None``; ``Tuple[:class:`str`, :class:`int`]`` for a tuple of type ``(str, int)``; ``Tuple[:class:`int`, ...]`` for a tuple of variable length with only integers. ================================================ FILE: docs/source/contributing/docs/types.rst ================================================ =================== Choosing Type Hints =================== In order to provide the best user experience, it's important that type hints are chosen correctly. With the large variety of types provided by Manim, choosing which one to use can be difficult. This guide aims to aid you in the process of choosing the right type for the scenario. The first step is figuring out which category your type hint fits into. Coordinates ----------- Coordinates encompass two main categories: points, and vectors. Points ~~~~~~ The purpose of points is pretty straightforward: they represent a point in space. For example: .. code-block:: python def print_point2D(coord: Point2DLike) -> None: x, y = coord print(f"Point at {x=},{y=}") def print_point3D(coord: Point3DLike) -> None: x, y, z = coord print(f"Point at {x=},{y=},{z=}") def print_point_array(coords: Point2DLike_Array | Point3DLike_Array) -> None: for coord in coords: if len(coord) == 2: # it's a Point2DLike print_point2D(coord) else: # it's a Point3DLike print_point3D(coord) def shift_point_up(coord: Point3DLike) -> Point3D: result = np.asarray(coord) result += UP print(f"New point: {result}") return result Notice that the last function, ``shift_point_up()``, accepts a :class:`~.Point3DLike` as a parameter and returns a :class:`~.Point3D`. A :class:`~.Point3D` always represents a NumPy array consisting of 3 floats, whereas a :class:`~.Point3DLike` can represent anything resembling a 3D point: either a NumPy array or a tuple/list of 3 floats, hence the ``Like`` word. The same happens with :class:`~.Point2D`, :class:`~.Point2D_Array` and :class:`~.Point3D_Array`, and their ``Like`` counterparts :class:`~.Point2DLike`, :class:`~.Point2DLike_Array` and :class:`~.Point3DLike_Array`. The rule for typing functions is: **make parameter types as broad as possible, and return types as specific as possible.** Therefore, for functions which are intended to be called by users, **we should always, if possible, accept** ``Like`` **types as parameters and return NumPy, non-** ``Like`` **types.**
|
:class:`~.Point2DLike_Array` and :class:`~.Point3DLike_Array`. The rule for typing functions is: **make parameter types as broad as possible, and return types as specific as possible.** Therefore, for functions which are intended to be called by users, **we should always, if possible, accept** ``Like`` **types as parameters and return NumPy, non-** ``Like`` **types.** The main reason is to be more flexible with users who might want to pass tuples or lists as arguments rather than NumPy arrays, because it's more convenient. The last function, ``shift_point_up()``, is an example of it. Internal functions which are *not* meant to be called by users may accept non-``Like`` parameters if necessary. Vectors ~~~~~~~ Vectors share many similarities to points. However, they have a different connotation. Vectors should be used to represent direction. For example, consider this slightly contrived function: .. code-block:: python M = TypeVar("M", bound=Mobject) # allow any mobject def shift_mobject(mob: M, direction: Vector3D, scale_factor: float = 1) -> M: return mob.shift(direction * scale_factor) Here we see an important example of the difference. ``direction`` should not be typed as a :class:`~.Point3D`, because it represents a direction along which to shift a :class:`~.Mobject`, not a position in space. As a general rule, if a parameter is called ``direction`` or ``axis``, it should be type hinted as some form of :class:`~.VectorND` or :class:`~.VectorNDLike`. Colors ------ The interface Manim provides for working with colors is :class:`.ManimColor`. The main color types Manim supports are RGB, RGBA, and HSV. You will want to add type hints to a function depending on which type it uses. If any color will work, you will need something like: .. code-block:: python if TYPE_CHECKING: from manim.utils.color import ParsableManimColor # type hint stuff with ParsableManimColor Béziers ------- Manim internally represents a :class:`.Mobject` by a collection of points. In the case of :class:`.VMobject`, the most commonly used subclass of :class:`.Mobject`, these points represent Bézier curves, which are a way of representing a curve using a sequencef points. .. note:: To learn more about Béziers, take a look at https://pomax.github.io/bezierinfo/ Manim supports two different renderers, which each have different representations of Béziers: Cairo uses cubic Bézier curves, while OpenGL uses quadratic Bézier curves. Type hints like :class:`~.typing.BezierPoints` represent a single bezier curve, and :class:`~.typing.BezierPath` represents multiple Bézier curves. A :class:`~.typing.Spline` is when the Bézier curves in a :class:`~.typing.Bezierforms a single connected curve. Manim also provides more specific type aliases when working with quadratic or cubic curves, and they are prefixed with their respective type (e.g. :class:`~.typing.CubicBezierPoints`, is a :class:`~.typing.BezierPoints` consisting of exactly 4 points representing a cubic Bézier curve). Functions --------- Throughout the codebase, many different types of functions are used. The most obvious example is a rate function, which takes in a float and outputs a float (``Callable[[loat], float]``). Another example is for overriding animations. One will often need to map a :class:`.Mobject` to an overridden :class:`.Animation`, and for that we have the :class:`~.typing.FunctionOverride` type hint. :class:`~.typing.PathFuncType` and :class:`~.typing.MappingFunction` are more niche, but are related to moving objects along a path, or applying functions. If you need
|
(``Callable[[loat], float]``). Another example is for overriding animations. One will often need to map a :class:`.Mobject` to an overridden :class:`.Animation`, and for that we have the :class:`~.typing.FunctionOverride` type hint. :class:`~.typing.PathFuncType` and :class:`~.typing.MappingFunction` are more niche, but are related to moving objects along a path, or applying functions. If you need to use it, you'll know. Images ------ There are several representations of images in Manim. The most common is the representation as a NumPy array of floats representing the pixels of an image. This is especially common when it comes to the OpenGL renderer. This is the use case of the :class:`~.typing.PixelArray` type hint. Sometimes, Manim may use ``PIL.Image.Image``, which is not the same as :class:`~.typing.PixelArray`. In this case, use the ``PIL.Image.Image`` typehint. Of course, if a more specific type of image is needed, it can be annotated as such. ================================================ FILE: docs/source/contributing/docs/typings.rst ================================================ ================== Typing Conventions ================== .. warning:: This section is still a work in progress. Adding type hints to functions and parameters --------------------------------------------- Manim is currently in the process of adding type hints into the library. In this section, you will find information about the standards used and some general guidelines. If you've never used type hints before, this is a good place to get started: https://realpython.com/python-type-checking/#hello-types. Typing standards ~~~~~~~~~~~~~~~~ Manim uses `mypy`_ to type check its codebase. You will find a list of configuration values in the ``mypy.ini`` configuration file. To be able to use the newest typing features not available in the lowest supported Python version, make use of `typing_extensions`_. To be able to use the new Union syntax (``|``) and builtins subscripting, use the ``from __future__ import annotations`` import. .. _mypy: https://mypy-lang.org/ .. _typing_extensions: https://pypi.org/project/typing-extensions/ Typing guidelines ~~~~~~~~~~~~~~~~~ * Manim has a dedicated :mod:`~.typing` module where type aliases are provided. Most of them may seem redundant, in particular the ones related to ``numpy``. This is in anticipation of the support for shape type hinting (`related issue <https://github.com/numpy/numpy/issues/16544>`_). Besides the pending shape support, using the correct type aliases will help users understand which shape should be used. * For typings of generic collections, check out `this <https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes>`_ link. * Always use a type hint of ``None`` for functions that does not return a value (this also applies to ``__init__``), e.g.: .. code:: py def height(self, value) -> None: self.scale_to_fit_height(value) * For variables representing paths, use the ``StrPath`` or ``StrOrBytesPath`` type alias defined in the :mod:`~.typing` module. * ``*args`` and ``**kwargs`` shouldn't be left untyped (in most cases you can use ``Any``). * Following `PEP 484 <https://peps.python.org/pep-0484/#the-numeric-tower>`_, use ``float`` instead of ``int | float``. * Use ``x | y`` instead of ``Union[x, y]`` * Mobjects have the typehint ``Mobject``, e.g.: .. code:: py def match_color(self, mobject: "Mobject"): """Match the color with the color of another :class:`~.Mobject`.""" return self.set_color(mobject.get_color()) * Always parametrize generics (``list[int]`` instead of ``list``, ``type[Any]`` instead of ``type``, etc.). This also applies to callables. .. code:: py rate_func: Callable[[float], float] = lambda t: smooth(1 - t) * Use ``TypeVar`` when you want to "link"
|
"Mobject"): """Match the color with the color of another :class:`~.Mobject`.""" return self.set_color(mobject.get_color()) * Always parametrize generics (``list[int]`` instead of ``list``, ``type[Any]`` instead of ``type``, etc.). This also applies to callables. .. code:: py rate_func: Callable[[float], float] = lambda t: smooth(1 - t) * Use ``TypeVar`` when you want to "link" type hints as being the same type. Consider ``Mobject.copy``, which returns a new instance of the same class. It would be type-hinted as: .. code:: py T = TypeVar("T") def copy(self: T) -> T: ... * Use ``typing.Iterable`` whenever the function works with *any* iterable, not a specific type. * Prefer ``numpy.typing.NDArray`` over ``numpy.ndarray`` .. code:: py import numpy as np if TYPE_CHECKING: import numpy.typing as npt def foo() -> npt.NDArray[float]: return np.array([1, 0, 1]) * If a method returns ``self``, use ``typing_extensions.Self``. .. code:: py if TYPE_CHECKING: from typing_extensions import Self class CustomMobject: def set_color(self, color: ManimColor) -> Self: ... return self * If the function returns a container of a specific length each time, consider using ``tuple`` instead of ``list``. .. code:: py def foo() -> tuple[float, float, float]: return (0, 0, 0) * If a function works with a parameter as long as said parameter has a ``__getitem__``, ``__iter___`` and ``__len__`` method, the typehint of the parameter should be ``collections.abc.Mapping``. If it also supports ``__setitem__`` and/or ``__delitem__``, it should be marked as ``collections.abc.MutableMapping``. * Typehinting something as ``object`` means that only attributes available on every Python object should be accessed, like ``__str__`` and so on. On the other hand, literally any attribute can be accessed on a variable with the ``Any`` typehint - it's more freeing than the ``object`` typehint, and makes mypy stop typechecking the variable. Note that whenever possible, try to keep typehints as specific as possible. * If objects are imported purely for type hint purposes, keep it under an ``if typing.TYPE_CHECKING`` guard, to prevent them from being imported at runtime (helps library performance). Do not forget to use the ``from __future__ import annotations`` import to avoid having runtime ``NameError`` exceptions. .. code:: py from typing import TYPE_CHECKING if TYPE_CHECKING: from manim.typing import Vector3D # type stuff with Vector3D Missing Sections for typehints are: ----------------------------------- * Mypy and numpy import errors: https://realpython.com/python-type-checking/#running-mypy * Explain ``mypy.ini`` (see above link) ================================================ FILE: docs/source/faq/general.md ================================================ # FAQ: General Usage ## Why does Manim say that "there are no scenes inside that module"? There are two main reasons why this error appears: if you have edited the file containing your `Scene` class and forgot to save it, or if you have accidentally passed the name of a wrong file to `manim`, this is a likely outcome. Check that you have spelled everything correctly. Otherwise, you are likely mixing up Manim versions. See {ref}`this FAQ answer <different-versions>` for an explanation regarding why there are different versions. Under the assumption that you are trying to use the `manim` executable from the terminal to run a scene that has been written for the community version (i.e., there is `from manim import
|
up Manim versions. See {ref}`this FAQ answer <different-versions>` for an explanation regarding why there are different versions. Under the assumption that you are trying to use the `manim` executable from the terminal to run a scene that has been written for the community version (i.e., there is `from manim import *`, or more specifically `from manim import Scene`), then this error indicates that the `manim` executable has been overwritten by the one provided by `manimgl` (unfortunately, both `manim` and `manimgl` provide a `manim` executable). You can check whether this is the case by running `manim --version`, the output of the community maintained version starts with `Manim Community v...`. If this is not the case, you are running `manimgl`. You can resolve this by either of the following steps: - Un- and reinstalling `manim`, - using the `manimce` executable in place of the `manim` one, - or replacing the call to the executable with a direct call to the Python module via `python -m manim`. --- ## No matter what code I put in my file, Manim only renders a black frame! Why? If you are using the usual pattern to write a `Scene`, i.e., ```python class MyAwesomeScene(Scene): def construct(self): ... # your animation code ``` then double check whether you have spelled `construct` correctly. If the method containing your code is not called `construct` (or if you are not calling a different, custom method from `construct`), Manim will not call your method and simply output a black frame. --- ## What are the default measurements for Manim's scene? The scene measures 8 units in height and has a default ratio of 16:9, which means that it measures {math}`8 \cdot 16 / 9 = 14 + 2/9` units in width. The origin is in the center of the scene, which means that, for example, the upper left corner of the scene has coordinates `[-7-1/9, 4, 0]`. --- ## How do I find out which keyword arguments I can pass when creating a `Mobject`? Let us consider a specific example, like the {class}`.Circle` class. When looking at its documentation page, only two specific keyword arguments are listed (`radius`, and `color`). Besides these concrete arguments, there is also a catchall `**kwargs` argument which captures all other arguments that are passed to `Circle`, and passes them on to the base class of {class}`.Circle`, {class}`.Arc`. The same holds for {class}`.Arc`: some arguments are explicitly documented, and there is again a catchall `**kwargs` argument that passes unprocessed arguments to the next base class -- and so on. The most important keyword arguments relevant to styling your mobjects are the ones that are documented for the base classes {class}`.VMobject` and {class}`.Mobject`. --- ## Can Manim render a video with transparent background? Yes: simply pass the CLI flag `-t` (or its long form `--transparent`). Note that the default video file format does not support transparency, which is why Manim will output a `.mov` instead of a `.mp4` when rendering with a transparent background. Other movie file formats that
|
video with transparent background? Yes: simply pass the CLI flag `-t` (or its long form `--transparent`). Note that the default video file format does not support transparency, which is why Manim will output a `.mov` instead of a `.mp4` when rendering with a transparent background. Other movie file formats that support transparency can be obtained by passing `--format=webm` or `--format=gif`. --- ## I have watched a video where a creator ran command X, but it does not work for me. Why? The video you have been watching is likely outdated. If you want to follow along, you either need to use the same version used in the video, or modify the code (in many cases it is just a method having been renamed etc.) accordingly. Check the video description, in some cases creators point out whether changes need to be applied to the code shown in the video. --- ## When using `Tex` or `MathTex`, some letters are missing. How can I fix this? It is possible that you have to (re)build some fonts used by LaTeX. For some distributions, you can do this manually by running ```bash fmtutil -sys --all ``` We recommend consulting the documentation of your LaTeX distribution for more information. --- ## I want to translate some code from `manimgl` to `manim`, what do I do with `CONFIG` dictionaries? The community-maintained version has dropped the use of `CONFIG` dictionaries very early, with {doc}`version v0.2.0 </changelog/0.2.0-changelog>` released in January 2021. Before that, Manim's classes basically processed `CONFIG` dictionaries by mimicking inheritance (to properly process `CONFIG` dictionaries set by parent classes) and then assigning all of the key-value-pairs in the dictionary as attributes of the corresponding object. In situations where there is not much inheritance going on, or for any custom setting, you should set these attributes yourself. For example, for an old-style `Scene` with custom attributes like ```python class OldStyle(Scene): CONFIG = {"a": 1, "b": 2} ``` should be written as ```python class NewStyle(Scene): a = 1 b = 2 ``` In situations where values should be properly inherited, the arguments should be added to the initialization function of the class. An old-style mobject `Thing` could look like ```python class Thing(VMobject): CONFIG = { "stroke_color": RED, "fill_opacity": 0.7, "my_awesome_argument": 42, } ``` where `stroke_color` and `fill_opacity` are arguments that concern the parent class of `Thing`, and `my_awesome_argument` is a custom argument that only concerns `Thing`. A version without `CONFIG` could look like this: ```python class Thing(VMobject): def __init__( self, stroke_color=RED, fill_opacity=0.7, my_awesome_argument=42, **kwargs ): self.my_awesome_argument = my_awesome_argument super().__init__(stroke_color=stroke_color, fill_opacity=fill_opacity, **kwargs) ``` --- ## My installation does not support converting PDF to SVG, help? This is an issue with `dvisvgm`, the tool shipped with LaTeX that transforms LaTeX output to a `.svg` file that Manim can parse. First, make sure your ``dvisvgm`` version is at least 2.4 by checking the output of ```bash dvisvgm --version ``` If you do not know how to update `dvisvgm`, please refer to your LaTeX distributions documentation (or the documentation of your operating
|
output to a `.svg` file that Manim can parse. First, make sure your ``dvisvgm`` version is at least 2.4 by checking the output of ```bash dvisvgm --version ``` If you do not know how to update `dvisvgm`, please refer to your LaTeX distributions documentation (or the documentation of your operating system, if `dvisvgm` was installed as a system package). Second, check whether your ``dvisvgm`` supports PostScript specials. This is needed to convert from PDF to SVG. Run: ```bash dvisvgm -l ``` If the output to this command does **not** contain `ps dvips PostScript specials`, this is a bad sign. In this case, run ```bash dvisvgm -h ``` If the output does **not** contain `--libgs=filename`, this means your `dvisvgm` does not currently support PostScript. You must get another binary. If, however, `--libgs=filename` appears in the help, that means that your `dvisvgm` needs the Ghostscript library to support PostScript. Search for `libgs.so` (on Linux, probably in `/usr/local/lib` or `/usr/lib`) or `gsdll32.dll` (on 32-bit Windows, probably in `C:\windows\system32`) or `gsdll64.dll` (on 64-bit Windows, also probably in `C:\windows\system32`) or `libgsl.dylib` (on MacOS, probably in `/usr/local/lib` or `/opt/local/lib`). Please look carefully, as the file might be located elsewhere, e.g. in the directory where Ghostscript is installed. When you have found the library, try (on MacOS or Linux) ```bash export LIBGS=<path to your library including the file name> dvisvgm -l ``` or (on Windows) ```bat set LIBGS=<path to your library including the file name> dvisvgm -l ``` You should now see `ps dvips PostScript specials` in the output. Refer to your operating system's documentation to find out how you can set or export the environment variable ``LIBGS`` automatically whenever you open a shell. As a last check, you can run ```bash dvisvgm -V1 ``` (while still having `LIBGS` set to the correct path, of course.) If `dvisvgm` can find your Ghostscript installation, it will be shown in the output together with the version number. If you do not have the necessary library on your system, please refer to your operating system's documentation to find out where you can get it and how you have to install it. If you are unable to solve your problem, check out the [dvisvgm FAQ](https://dvisvgm.de/FAQ/). --- ## Where can I find more resources for learning Manim? In our [Discord server](https://manim.community/discord), we have the community-maintained `#beginner-resources` channel in which links to helpful learning resources are collected. You are welcome to join our Discord and take a look yourself! If you have found some guides or tutorials yourself that are not on our list yet, feel free to add them! ================================================ FILE: docs/source/faq/help.md ================================================ # FAQ: Getting Help ## How do I animate X? Why do I get error Y? Can someone help me? Before asking the community, please make sure that the issue you are having is not already discussed in our {doc}`FAQ section </faq/index>` sufficiently well so that you can resolve the problem yourself. You can also try to use you favorite search engine, if you are lucky you might find
|
me? Before asking the community, please make sure that the issue you are having is not already discussed in our {doc}`FAQ section </faq/index>` sufficiently well so that you can resolve the problem yourself. You can also try to use you favorite search engine, if you are lucky you might find a blog post, a question on [StackOverflow](https://stackoverflow.com/questions/tagged/manim), or a post in the [r/manim subreddit](https://reddit.com/r/manim). If this is not the case, please take a moment to properly prepare your question: the better you manage to explain what exactly it is you are struggling with, the more efficient people will be able to help you. Regardless of the platform you choose in the next step, StackOverflow has a good guide on [asking good questions](https://stackoverflow.com/help/how-to-ask). As soon as you have a good idea of what exactly you want to ask, pick one of the following communication channels: - The community is most active [in our Discord server](https://manim.community/discord/). Click the link to join, then pick one of the `#manim-help` channels in the sidebar, and post your question there. If you are comfortable with using Discord, try to search for your problem using the search function of our server; perhaps people have been talking about it before! - We are also monitoring questions on [StackOverflow](https://stackoverflow.com/questions/tagged/manim) that are tagged with `manim`. - Many people are also active in our [r/manim subreddit](https://reddit.com/r/manim), feel free to post there if you are an avid Redditor -- but be aware that Discord or StackOverflow might be better choices. - And finally, you can also start a new [discussion on GitHub](https://github.com/ManimCommunity/manim/discussions) if you dislike all other options. In all of these channels, please make sure to abide by Manim's {doc}`Code of Conduct </conduct>` -- in short, be *excellent* to one another: be friendly and patient, considerate, and respectful. --- ## What should I do if nobody answers my question? Try and see whether your question can be improved: did you include all relevant information (in case of errors: the full stack trace, the code that you were rendering, and the command you used to run Manim?). In case you used a very long example, is it possible to construct a more minimal version that has the same (faulty) behavior? If you posted in one of our help channels on Discord and your question got buried, you are allowed to ping the `@Manim Helper` role to bring it to the attention of the volunteers who are willing to take a look. Please refrain from pinging the role immediately when asking your question for the first time, this is considered impolite. You can also try to post your question to a different channel if you feel that you are not having any success with your initial choice -- but please do not spam your question in all of our communication channels (and in particular for Discord: please don't use multiple help channels at once). In the end, it is as for most open-source projects: our community members are volunteers. If you do not
|
with your initial choice -- but please do not spam your question in all of our communication channels (and in particular for Discord: please don't use multiple help channels at once). In the end, it is as for most open-source projects: our community members are volunteers. If you do not receive a quick answer to your question, it may be because nobody knows the answer, or because your question is not clear enough, or it could be that everyone who can help you with your problem is busy doing other things. --- ## The library does not behave as documented, or something broke in a new release. What should I do? Sounds like you have found a bug. One of the best ways of contributing to the development of Manim is by reporting it! Check our list of known issues and feature requests [in our GitHub repository](https://github.com/ManimCommunity/manim/issues). If the problem you have found is not listed there yet (use the search function; also check whether there is a corresponding closed issue, it is possible that your problem has already been resolved and will be fixed with the next release), please consider the following steps to submit a new issue. ```{note} If you are unsure whether or not you should file a new issue for some odd behavior that you found, feel free to ask the community developers, preferably in one of our `#manim-dev` channels in [our Discord](https://manim.community/discord/). ``` 1. Make sure you are running the latest released version of Manim, your problem might otherwise already be fixed in a more recent version. Check the {doc}`/changelog` for a full list of changes between Manim releases. 2. Choose the correct category for your report when [creating a new issue](https://github.com/ManimCommunity/manim/issues/new/choose). We have dedicated issue templates for *bug reports*, *feature requests*, and *installation issues*. If your report falls into one of these categories, read the issue template carefully! Instructions are given in the `<!-- ... -->` sections of the text field. If you want to suggest a new feature without concrete implementation details, see {ref}`the instructions given in this answer <creating-suggestions>`. 3. For bug reports: prepare a minimal example that can be used to illustrate the issue. Examples with hundreds of lines are very inefficient and tedious to debug. Your problem needs to be reproducible for others, so please make sure to prepare a suitable example. 4. This is mentioned in the bug report template as well, but it is very important: if you report that some code raises an error, make sure to include the full terminal output, from the command you used to run the library up to and including the last line with the error message. Read carefully: if the message mentions that there is another relevant log file, include this other file as well! --- (creating-suggestions)= ## I have an idea for a really cool feature that should be implemented, where should I share my idea? New suggestions and proposals should be made by [creating a new discussion](https://github.com/ManimCommunity/manim/discussions/new?category=suggestions-and-proposals) in the
|
mentions that there is another relevant log file, include this other file as well! --- (creating-suggestions)= ## I have an idea for a really cool feature that should be implemented, where should I share my idea? New suggestions and proposals should be made by [creating a new discussion](https://github.com/ManimCommunity/manim/discussions/new?category=suggestions-and-proposals) in the [*Suggestions and Proposals* category](https://github.com/ManimCommunity/manim/discussions/categories/suggestions-and-proposals) in our GitHub repository. Once the raw idea has been formed into a more concrete, implementable proposal that is supported by the community, and someone has expressed interest in working on the new feature, a corresponding [issue](https://github.com/ManimCommunity/manim/issues) will be created. Do **not** create issues for suggesting new features directly, they will be closed down. ================================================ FILE: docs/source/faq/index.rst ================================================ Frequently Asked Questions ========================== .. toctree:: :caption: Table of Contents :maxdepth: 2 :glob: * ================================================ FILE: docs/source/faq/installation.md ================================================ # FAQ: Installation (different-versions)= ## Why are there different versions of Manim? Manim was originally created by Grant Sanderson as a personal project and for use in his YouTube channel, [3Blue1Brown](https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw). As his channel gained popularity, many grew to like the style of his animations and wanted to use manim for their own projects. However, as manim was only intended for personal use, it was very difficult for other users to install and use it. In late 2019, Grant started working on faster OpenGL rendering in a new branch, known as the `shaders` branch. In mid-2020, a group of developers forked it into what is now the community edition; this is the version documented on this website. In early 2021, Grant merged the shaders branch back into master, making it the default branch in his repository -- and this is what `manimgl` is. The old version, before merging the `shaders` branch is sometimes referred to as `ManimCairo` and is, at this point, only useful for one singular purpose: rendering Grant's old videos locally on your machine. It is still available in his GitHub repository in form of the `cairo-backend` branch. To summarize: - [**Manim**, or **ManimCE**](https://manim.community) refers to the community maintained version of the library. This is the version documented on this website; the package name on PyPI is [`manim`](https://pypi.org/project/manim/). - [ManimGL](https://github.com/3b1b/manim) is the latest released version of the version of the library developed by Grant "3b1b" Sanderson. It has more experimental features and breaking changes between versions are not documented. Check out its documentation [here](https://3b1b.github.io/manim/index.html); on PyPI the package name is [`manimgl`](https://pypi.org/project/manimgl/). - [ManimCairo](https://github.com/3b1b/manim/tree/cairo-backend) is the name that is sometimes used for the old, pre-OpenGL version of `manimgl`. The latest version of it is available [on PyPI as `manimlib`](https://pypi.org/project/manimgl/), but note that if you intend to use it to compile some old project of Grant, you will likely have to install the exact version from the time the project was created from source. --- ## Which version should I use? We recommend the community maintained version especially for beginners. It has been developed to be more stable, better tested and documented (!), and quicker to respond to community contributions. It is also perfectly reasonable to start learning with the
|
was created from source. --- ## Which version should I use? We recommend the community maintained version especially for beginners. It has been developed to be more stable, better tested and documented (!), and quicker to respond to community contributions. It is also perfectly reasonable to start learning with the community maintained version and then switch to a different version later on. If you do not care so much about documentation or stability, and would like to use the exact same version that Grant is using, then use ManimGL. And as mentioned above, ManimCairo should only be used for (re)rendering old 3Blue1Brown projects (basically 2019 and before). --- ## What are the differences between Manim, ManimGL, ManimCairo? Can I tell for which version a scene was written for? You can! The thing that usually gives it away is the `import` statement at the top of the file; depending on how the code imports Manim you can tell for which version of the code it was written for: - If the code imports from `manim` (i.e., `from manim import *`, `import manim as mn`, etc.), then the code you are reading is supposed to be run with the community maintained version. - If the import reads `import manimlib` (or `from manimlib import *`), you are likely reading a file to be rendered with ManimGL. - And if the import reads `from manimlib.imports import *`, or perhaps even `from big_ol_pile_of_manim_imports import *` you are reading a snippet that is supposed to be rendered with an early, or very early version of ManimCairo, respectively. --- ## How do I know which version of Manim I have installed? Assuming you can run `manim` in your terminal and there is some output, check the first line of the text being produced. If you are using the community maintained version, the first line of any output will be `Manim Community <version number>`. If it does not say that, you are likely using ManimGL. You can also check the list of packages you have installed: if typing `python` in your terminal spawns the interpreter that corresponds to the Python installation you use (might also be `py`, or `python3`, depending on your operating system), running `python -m pip list` will print a list of all installed packages. Check whether `manim` or `manimgl` appear in that list. Similarly, you can use `python -m pip install <package name>` and `python -m pip uninstall <package name>` to install and uninstall packages from that list, respectively. --- ## I am following the video guide X to install Manim, but some step fails. What do I do? It is only natural that there are many video guides on installing Manim out there, given that Manim is a library used for creating videos. Unfortunately however, (YouTube) videos can't be updated easily (without uploading a new one, that is) when some step in the installation process changes, and so there are many **severely outdated** resources out there. This is why we strongly recommend following our
|
that Manim is a library used for creating videos. Unfortunately however, (YouTube) videos can't be updated easily (without uploading a new one, that is) when some step in the installation process changes, and so there are many **severely outdated** resources out there. This is why we strongly recommend following our {doc}`written installation guide </installation>` to guide you through the process. In case you prefer using a video guide regardless, please check whether the creator whose guide you have been watching has made a more recent version available, and otherwise please contact them directly. Asking for help in the community will likely lead to being suggested to follow our written guide. --- ## Why does ManimPango fail to install when running `pip install manim`? This most likely means that pip was not able to use our pre-built wheels of the `manimpango` dependency. Let us know (via [Discord](https://www.manim.community/discord/) or by opening a [new issue on GitHub](https://github.com/ManimCommunity/ManimPango/issues/new)) which architecture you would like to see supported, and we'll see what we can do about it. To fix errors when installing `manimpango`, you need to make sure you have all the necessary build requirements. Check out the detailed instructions given in [the BUILDING section](https://github.com/ManimCommunity/ManimPango#BUILDING) of [ManimPango's README](https://github.com/ManimCommunity/ManimPango). --- (not-on-path)= ## I am using Windows and get the error `X is not recognized as an internal or external command, operable program or batch file` If you have followed {doc}`our local installation instructions </installation/uv>` and have not activated the corresponding virtual environment, make sure to use `uv run manim ...` instead of just `manim` (or activate the virtual environment by following the instructions printed when running `uv venv`). Otherwise there is a problem with the directories where your system is looking for executables (the `PATH` variable). If `python` is recognized, you can try running commands by prepending `python -m`. That is, `manim` becomes `python -m manim`, and `pip` becomes `python -m pip`. Otherwise see [this StackExchange answer](https://superuser.com/questions/143119/how-do-i-add-python-to-the-windows-path/143121#143121) to get help with editing the `PATH` variable manually. --- ## I have tried using Chocolatey (`choco install manimce`) to install Manim, but it failed! Make sure that you were running the command with administrator permissions, otherwise there can be problems. If this is not the issue, read Chocolatey's output carefully, it should mention a `.log` file containing information why the process failed. You are welcome to take this file (and any other input you feel might be relevant) and submit it to Manim's community to ask for help with your problem. See the {doc}`FAQ on getting help </faq/help>` for instructions. --- ## On Windows, when typing `python` or `python3` the Windows store is opened, can I fix this? Yes: you can remove these aliases with these steps: 1. Go to the Windows Setting. 2. Under *Apps and Features* you will find application execution aliases. 3. Within this menu, disable the alias(es) that are causing the issue (`python` and/or `python3`). --- ## I am using Anaconda and get an `ImportError` mentioning that some Symbol is not found. This is because
|
to the Windows Setting. 2. Under *Apps and Features* you will find application execution aliases. 3. Within this menu, disable the alias(es) that are causing the issue (`python` and/or `python3`). --- ## I am using Anaconda and get an `ImportError` mentioning that some Symbol is not found. This is because Anaconda environments come with their own preinstalled version of `cairo` which is not compatible with the version of `pycairo` required by Manim. Usually it can be fixed by running ```bash conda install -c conda-forge pycairo ``` --- ## How can I fix the error that `manimpango/cmanimpango.c` could not be found when trying to install Manim? This occasionally happens when your system has to build a wheel for [ManimPango](https://github.com/ManimCommunity/ManimPango) locally because there is no compatible version for your architecture available on PyPI. Very often, the problem is resolved by installing Cython (e.g., via `pip3 install Cython`) and then trying to reinstall Manim. If this does not fix it: - Make sure that you have installed all build dependencies mentioned in [ManimPango's README](https://github.com/ManimCommunity/ManimPango), - and if you still run into troubles after that, please reach out to us as described in the {doc}`Getting Help FAQs </faq/help>`. ================================================ FILE: docs/source/faq/internals.md ================================================ # Where can I learn more about Manim's internal structure? Efforts to document the internal structure of Manim is ongoing on our [wiki](https://github.com/ManimCommunity/manim/wiki/Developer-documentation-(WIP)). Keep in mind that since this is a work in progress, the information you find may be incomplete, outdated or even wrong. Still, it should serve as a good starting point. The wiki is open for anyone to edit, feel free to add information or even questions directly on the wiki pages. ================================================ FILE: docs/source/faq/opengl.md ================================================ # FAQ: OpenGL rendering ## Are there any resources on how the OpenGL renderer in the community maintained version can be used? Yes. Unfortunately, at this point, the official online documentation does not contain the relevant base classes like `OpenGLMobject` and `OpenGLVMobject` or specific OpenGL classes like `OpenGLSurface`, but documentation for some of them is available in form of docstrings [in the source code](https://github.com/ManimCommunity/manim/tree/main/manim/mobject/opengl). Furthermore, [this user guide by *aquabeam*](https://www.aquabeam.me/manim/opengl_guide/) can be helpful to get started using the OpenGL renderer. --- ## I am trying to run an interactive scene with `--renderer=opengl` and `Scene.interactive_embed`, but an error (`sqlite3.ProgrammingError`) is raised. How can I fix this? This seems to be an issue with a recent IPython release, in our experience it helps to downgrade the installed `IPython` package to `8.0.1`: `pip install IPython==8.0.1`. ================================================ FILE: docs/source/guides/add_voiceovers.rst ================================================ ########################### Adding Voiceovers to Videos ########################### Creating a full-fledged video with voiceovers is a bit more involved than creating purely visual Manim scenes. One has to use `a video editing program <https://en.wikipedia.org/wiki/List_of_video_editing_software>`__ to add the voiceovers after the video has been rendered. This process can be difficult and time-consuming, since it requires a lot of planning and preparation. To ease the process of adding voiceovers to videos, we have created `Manim Voiceover <https://voiceover.manim.community>`__, a plugin that lets you add voiceovers to scenes directly in Python. To install
|
the video has been rendered. This process can be difficult and time-consuming, since it requires a lot of planning and preparation. To ease the process of adding voiceovers to videos, we have created `Manim Voiceover <https://voiceover.manim.community>`__, a plugin that lets you add voiceovers to scenes directly in Python. To install it, run .. code-block:: bash pip install "manim-voiceover[azure,gtts]" Visit `the installation page <https://voiceover.manim.community/en/latest/installation.html>`__ for more details on how to install Manim Voiceover. Basic Usage ########### Manim Voiceover lets you ... - Add voiceovers to Manim videos directly in Python, without having to use a video editor. - Record voiceovers with your microphone during rendering through a simple command line interface. - Develop animations with auto-generated AI voices from various free and proprietary services. It provides a very simple API that lets you specify your voiceover script and then record it during rendering: .. code-block:: python from manim import * from manim_voiceover import VoiceoverScene from manim_voiceover.services.recorder import RecorderService # Simply inherit from VoiceoverScene instead of Scene to get all the # voiceover functionality. class RecorderExample(VoiceoverScene): def construct(self): # You can choose from a multitude of TTS services, # or in this example, record your own voice: self.set_speech_service(RecorderService()) circle = Circle() # Surround animation sections with with-statements: with self.voiceover(text="This circle is drawn as I speak.") as tracker: self.play(Create(circle), run_time=tracker.duration) # The duration of the animation is received from the audio file # and passed to the tracker automatically. # This part will not start playing until the previous voiceover is finished. with self.voiceover(text="Let's shift it to the left 2 units.") as tracker: self.play(circle.animate.shift(2 * LEFT), run_time=tracker.duration) To get started with Manim Voiceover, visit the `Quick Start Guide <https://voiceover.manim.community/en/latest/quickstart.html>`__. Visit the `Example Gallery <https://voiceover.manim.community/en/latest/examples.html>`__ to see some examples of Manim Voiceover in action. ================================================ FILE: docs/source/guides/configuration.rst ================================================ Configuration ############# Manim provides an extensive configuration system that allows it to adapt to many different use cases. There are many configuration options that can be configured at different times during the scene rendering process. Each option can be configured programmatically via `the ManimConfig class`_, at the time of command invocation via `command-line arguments`_, or at the time the library is first imported via `the config files`_. The most common, simplest, and recommended way to configure Manim is via the command-line interface (CLI), which is described directly below. Command-line arguments ********************** By far the most commonly used command in the CLI is the ``render`` command, which is used to render scene(s) to an output file. It is used with the following arguments: .. program-output:: manim render --help :ellipsis: 9 However, since Manim defaults to the :code:`render` command whenever no command is specified, the following form is far more common and can be used instead: .. code-block:: bash manim [OPTIONS] FILE [SCENES] An example of using the above form is: .. code-block:: bash manim -qm file.py SceneOne This asks Manim to search for a Scene class called :code:`SceneOne` inside the file ``file.py`` and render it with medium quality (specified by the ``-qm`` flag). Another frequently used flag
|
bash manim [OPTIONS] FILE [SCENES] An example of using the above form is: .. code-block:: bash manim -qm file.py SceneOne This asks Manim to search for a Scene class called :code:`SceneOne` inside the file ``file.py`` and render it with medium quality (specified by the ``-qm`` flag). Another frequently used flag is ``-p`` ("preview"), which makes manim open the rendered video after it's done rendering. .. note:: The ``-p`` flag does not change any properties of the global ``config`` dict. The ``-p`` flag is only a command-line convenience. Advanced examples ================= To render a scene in high quality, but only output the last frame of the scene instead of the whole video, you can execute .. code-block:: bash manim -sqh <file.py> SceneName The following example specifies the output file name (with the :code:`-o` flag), renders only the first ten animations (:code:`-n` flag) with a white background (:code:`-c` flag), and saves the animation as a ``.gif`` instead of as a ``.mp4`` file (``--format=gif`` flag). It uses the default quality and does not try to open the file after it is rendered. .. code-block:: bash manim -o myscene --format=gif -n 0,10 -c WHITE <file.py> SceneName A list of all CLI flags ======================== .. command-output:: manim --help .. command-output:: manim render --help .. command-output:: manim cfg --help .. command-output:: manim plugins --help The ManimConfig class ********************* The most direct way of configuring Manim is through the global ``config`` object, which is an instance of :class:`.ManimConfig`. Each property of this class is a config option that can be accessed either with standard attribute syntax or with dict-like syntax: .. code-block:: pycon >>> from manim import * >>> config.background_color = WHITE >>> config["background_color"] = WHITE .. note:: The former is preferred; the latter is provided for backwards compatibility. Most classes, including :class:`.Camera`, :class:`.Mobject`, and :class:`.Animation`, read some of their default configuration from the global ``config``. .. code-block:: pycon >>> Camera({}).background_color <Color white> >>> config.background_color = RED # 0xfc6255 >>> Camera({}).background_color <Color #fc6255> :class:`.ManimConfig` is designed to keep internal consistency. For example, setting ``frame_y_radius`` will affect ``frame_height``: .. code-block:: pycon >>> config.frame_height 8.0 >>> config.frame_y_radius = 5.0 >>> config.frame_height 10.0 The global ``config`` object is meant to be the single source of truth for all config options. All of the other ways of setting config options ultimately change the values of the global ``config`` object. The following example illustrates the video resolution chosen for examples rendered in our documentation with a reference frame. .. manim:: ShowScreenResolution :save_last_frame: class ShowScreenResolution(Scene): def construct(self): pixel_height = config["pixel_height"] # 1080 is default pixel_width = config["pixel_width"] # 1920 is default frame_width = config["frame_width"] frame_height = config["frame_height"] self.add(Dot()) d1 = Line(frame_width * LEFT / 2, frame_width * RIGHT / 2).to_edge(DOWN) self.add(d1) self.add(Text(str(pixel_width)).next_to(d1, UP)) d2 = Line(frame_height * UP / 2, frame_height * DOWN / 2).to_edge(LEFT) self.add(d2) self.add(Text(str(pixel_height)).next_to(d2, RIGHT)) The config files **************** As the last example shows, executing Manim from the command line may involve using many flags simultaneously. This may become a nuisance if you must execute the same script many times
|
d2 = Line(frame_height * UP / 2, frame_height * DOWN / 2).to_edge(LEFT) self.add(d2) self.add(Text(str(pixel_height)).next_to(d2, RIGHT)) The config files **************** As the last example shows, executing Manim from the command line may involve using many flags simultaneously. This may become a nuisance if you must execute the same script many times in a short time period, for example, when making small incremental tweaks to your scene script. For this reason, Manim can also be configured using a configuration file. A configuration file is a file ending with the suffix ``.cfg``. To use a local configuration file when rendering your scene, you must create a file with the name ``manim.cfg`` in the same directory as your scene code. .. warning:: The config file **must** be named ``manim.cfg``. Currently, Manim does not support config files with any other name. The config file must start with the section header ``[CLI]``. The configuration options under this header have the same name as the CLI flags and serve the same purpose. Take, for example, the following config file. .. code-block:: ini [CLI] # my config file output_file = myscene save_as_gif = True background_color = WHITE Config files are parsed with the standard python library ``configparser``. In particular, they will ignore any line that starts with a pound symbol ``#``. Now, executing the following command .. code-block:: bash manim -o myscene -i -c WHITE <file.py> SceneName is equivalent to executing the following command, provided that ``manim.cfg`` is in the same directory as <file.py>, .. code-block:: bash manim <file.py> SceneName .. tip:: The names of the configuration options admissible in config files are exactly the same as the **long names** of the corresponding command- line flags. For example, the ``-c`` and ``--background_color`` flags are interchangeable, but the config file only accepts :code:`background_color` as an admissible option. Since config files are meant to replace CLI flags, all CLI flags can be set via a config file. Moreover, any config option can be set via a config file, whether or not it has an associated CLI flag. See the bottom of this document for a list of all CLI flags and config options. Manim will look for a ``manim.cfg`` config file in the same directory as the file being rendered, and **not** in the directory of execution. For example, .. code-block:: bash manim -o myscene -i -c WHITE <path/to/file.py> SceneName will use the config file found in ``path/to/file.py``, if any. It will **not** use the config file found in the current working directory, even if it exists. In this way, the user may keep different config files for different scenes or projects, and execute them with the right configuration from anywhere in the system. The file described here is called the **folder-wide** config file because it affects all scene scripts found in the same folder. The user config file ==================== As explained in the previous section, a :code:`manim.cfg` config file only affects the scene scripts in its same folder. However, the user may also create a special config file that
|
the **folder-wide** config file because it affects all scene scripts found in the same folder. The user config file ==================== As explained in the previous section, a :code:`manim.cfg` config file only affects the scene scripts in its same folder. However, the user may also create a special config file that will apply to all scenes rendered by that user. This is referred to as the **user-wide** config file, and it will apply regardless of where Manim is executed from, and regardless of where the scene script is stored. The user-wide config file lives in a special folder, depending on the operating system. * Windows: :code:`UserDirectory`/AppData/Roaming/Manim/manim.cfg * MacOS: :code:`UserDirectory`/.config/manim/manim.cfg * Linux: :code:`UserDirectory`/.config/manim/manim.cfg Here, :code:`UserDirectory` is the user's home folder. .. note:: A user may have many **folder-wide** config files, one per folder, but only one **user-wide** config file. Different users in the same computer may each have their own user-wide config file. .. warning:: Do not store scene scripts in the same folder as the user-wide config file. In this case, the behavior is undefined. Whenever you use Manim from anywhere in the system, Manim will look for a user-wide config file and read its configuration. Cascading config files ====================== What happens if you execute Manim and it finds both a folder-wide config file and a user-wide config file? Manim will read both files, but if they are incompatible, **the folder-wide file takes precedence**. For example, take the following user-wide config file .. code-block:: ini # user-wide [CLI] output_file = myscene save_as_gif = True background_color = WHITE and the following folder-wide file .. code-block:: ini # folder-wide [CLI] save_as_gif = False Then, executing :code:`manim <file.py> SceneName` will be equivalent to not using any config files and executing .. code-block:: bash manim -o myscene -c WHITE <file.py> SceneName Any command-line flags have precedence over any config file. For example, using the previous two config files and executing :code:`manim -c RED <file.py> SceneName` is equivalent to not using any config files and executing .. code-block:: bash manim -o myscene -c RED <file.py> SceneName There is also a **library-wide** config file that determines Manim's default behavior and applies to every user of the library. It has the least precedence, so any config options in the user-wide and any folder-wide files will override the library-wide file. This is referred to as the *cascading* config file system. .. warning:: **The user should not try to modify the library-wide file**. Contributors should receive explicit confirmation from the core developer team before modifying it. Order of operations ******************* .. raw:: html <div class="mxgraph" style="max-width:100%;border:1px solid transparent;" data-mxgraph="{"highlight":"#0000ff","nav":true,"resize":true,"toolbar":"zoom layers lightbox","edit":"_blank","url":"https://drive.google.com/uc?id=1WYVKKoRbXrumHEcyQKQ9s1yCnBvfU2Ui&export=download"}"></div> <script type="text/javascript" src="https://viewer.diagrams.net/embed2.js?&fetch=https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1WYVKKoRbXrumHEcyQKQ9s1yCnBvfU2Ui%26export%3Ddownload"></script> With so many different ways of configuring Manim, it can be difficult to know when each config option is being set. In fact, this will depend on how Manim is being used. If Manim is imported from a module, then the configuration system will follow these steps: 1. The library-wide config file is loaded. 2. The user-wide and folder-wide files are loaded if they exist. 3.
|
config option is being set. In fact, this will depend on how Manim is being used. If Manim is imported from a module, then the configuration system will follow these steps: 1. The library-wide config file is loaded. 2. The user-wide and folder-wide files are loaded if they exist. 3. All files found in the previous two steps are parsed in a single :class:`ConfigParser` object, called ``parser``. This is where *cascading* happens. 4. :class:`logging.Logger` is instantiated to create Manim's global ``logger`` object. It is configured using the "logger" section of the parser, i.e. ``parser['logger']``. 5. :class:`ManimConfig` is instantiated to create the global ``config`` object. 6. The ``parser`` from step 3 is fed into the ``config`` from step 5 via :meth:`ManimConfig.digest_parser`. 7. Both ``logger`` and ``config`` are exposed to the user. If Manim is being invoked from the command line, all of the previous steps happen, and are complemented by: 8. The CLI flags are parsed and fed into ``config`` via :meth:`~ManimConfig.digest_args`. 9. If the ``--config_file`` flag was used, a new :class:`ConfigParser` object is created with the contents of the library-wide file, the user-wide file if it exists, and the file passed via ``--config_file``. In this case, the folder-wide file, if it exists, is ignored. 10. The new parser is fed into ``config``. 11. The rest of the CLI flags are processed. To summarize, the order of precedence for configuration options, from lowest to highest precedence is: 1. Library-wide config file, 2. user-wide config file, if it exists, 3. folder-wide config file, if it exists OR custom config file, if passed via ``--config_file``, 4. other CLI flags, and 5. any programmatic changes made after the config system is set. A list of all config options **************************** .. code:: ['aspect_ratio', 'assets_dir', 'background_color', 'background_opacity', 'bottom', 'custom_folders', 'disable_caching', 'dry_run', 'ffmpeg_loglevel', 'flush_cache', 'frame_height', 'frame_rate', 'frame_size', 'frame_width', 'frame_x_radius', 'frame_y_radius', 'from_animation_number', `fullscreen`, 'images_dir', 'input_file', 'left_side', 'log_dir', 'log_to_file', 'max_files_cached', 'media_dir', 'media_width', 'movie_file_extension', 'notify_outdated_version', 'output_file', 'partial_movie_dir', 'pixel_height', 'pixel_width', 'plugins', 'preview', 'progress_bar', 'quality', 'right_side', 'save_as_gif', 'save_last_frame', 'save_pngs', 'scene_names', 'show_in_file_browser', 'sound', 'tex_dir', 'tex_template', 'tex_template_file', 'text_dir', 'top', 'transparent', 'upto_animation_number', 'use_opengl_renderer', 'verbosity', 'video_dir', 'window_position', 'window_monitor', 'window_size', 'write_all', 'write_to_movie', 'enable_wireframe', 'force_window'] Accessing CLI command options ***************************** Entering ``manim``, or ``manim --help``, will open the main help page. .. code:: Usage: manim [OPTIONS] COMMAND [ARGS]... Animation engine for explanatory math videos. Options: --version Show version and exit. --help Show this message and exit. Commands: cfg Manages Manim configuration files. init Sets up a new project in current working directory with default settings. It copies files from templates directory and pastes them in the current working dir. new Create a new project or insert a new scene. plugins Manages Manim plugins. render Render SCENE(S) from the input FILE. See 'manim <command>' to read about a specific subcommand. Made with <3 by Manim Community developers. Each of the subcommands has its own help page which can be accessed similarly: .. code:: manim render manim render --help ================================================ FILE: docs/source/guides/index.rst ================================================ Thematic Guides =============== .. toctree:: :caption: Table of Contents :maxdepth: 2 :glob: configuration deep_dive using_text add_voiceovers ================================================
|
subcommand. Made with <3 by Manim Community developers. Each of the subcommands has its own help page which can be accessed similarly: .. code:: manim render manim render --help ================================================ FILE: docs/source/guides/index.rst ================================================ Thematic Guides =============== .. toctree:: :caption: Table of Contents :maxdepth: 2 :glob: configuration deep_dive using_text add_voiceovers ================================================ FILE: docs/source/guides/using_text.rst ================================================ ########################### Rendering Text and Formulas ########################### There are two different ways by which you can render **Text** in videos: 1. Using Pango (:mod:`~.text_mobject`) 2. Using LaTeX (:mod:`~.tex_mobject`) If you want to render simple text, you should use either :class:`~.Text` or :class:`~.MarkupText`, or one of its derivatives like :class:`~.Paragraph`. See :ref:`using-text-objects` for more information. LaTeX should be used when you need mathematical typesetting. See :ref:`rendering-with-latex` for more information. .. _using-text-objects: Text Without LaTeX ****************** The simplest way to add text to your animations is to use the :class:`~.Text` class. It uses the `Pango library`_ to render text. With Pango, you can also render non-English alphabets like 你好 or こんにちは or 안녕하세요 or مرحبا بالعالم. Here is a simple *Hello World* animation. .. manim:: HelloWorld :save_last_frame: :ref_classes: Text class HelloWorld(Scene): def conct(self): text = Text("Hello world", font_size=144) self.add(text) You can also use :class:`~.MarkupText` which allows the use of PangoMarkup (see the documentation of :class:`~.MarkupText` for details) to render text. For example: .. manim:: SingleLineColor :save_last_frame: :ref_classes: MarkupText class SingleLineColor(Scene): def construct(self): text = MarkupText( f'all in red <span fgcolor="{YELLOW}">except this</span>', color=RED ) self.add(text) .. _Pango library: https://pango.org Working with :class:`~.Text` ============================ This section explains the properties of :class:`~.Text` and how can it be used in your animations. Using Fonts ----------- You can set a different font using :attr:`~.Text.font`. .. note:: The font used must be installed in your system, and Pango should know about it. You can get a list of fonts using :func:`manimpango.list_fonts`. >>> import manimpango >>> manimpango.list_fonts() [...] .. manim:: FontsExample :save_last_frame: class FontsExample(Scene): def construct(self): ft = Text("Noto Sans", font="Noto Sans") self.add(ft) Setting Slant and Weight ------------------------ Slant is the style of the Text, and it can be ``NORMAL`` (the default), ``ITALIC`` or ``OBLIQUE``. Usually, for many fonts both ``ITALIC`` and ``OBLIQUE`` look similar, but ``ITALIC`` uses **Roman Style**, whereas ``OBLIQUE`` uses **Italic Style**. Weight specifies the boldness of a font. You can see a list of weights in :class:`manimpango.Weight`. .. manim:: SlantsExample :save_last_frame: class SlantsExample(Scene): def construct(self): a = Text("Italic", slant=ITALIC) self.add(a) .. manim:: DifferentWeight :save_last_frame: class DifferentWeight(Scene): def construct(self): import manimpango g = VGroup() weight_list = dict( sorted( { weight: manimpango.Weight(weight).value for weight in manimpango.Weight }.items(), key=lambda x: x[1], ) ) for weight in weight_list: g += Text(weight.name, weight=weight.name, font="Open Sans") self.add(g.arrange(DOWN).scale(0.5)) .. _using-colors: Using Colors ------------ You can set the color of the text using :attr:`~.Text.color`: .. manim:: SimpleColor :save_last_frame: class SimpleColor(Scene): def construct(self): col = Text("RED COLOR", color=RED) self.add(col) You can use utilities like :attr:`~.Text.t2c` for coloring specific characters. This may be problematic if your text contains ligatures as explained in :ref:`iterating-text`. :attr:`~Text.t2c` accepts two types of dictionaries, * The keys can contain indices like ``[2:-1]`` or ``[4:8]``, this works similar to
|
construct(self): col = Text("RED COLOR", color=RED) self.add(col) You can use utilities like :attr:`~.Text.t2c` for coloring specific characters. This may be problematic if your text contains ligatures as explained in :ref:`iterating-text`. :attr:`~Text.t2c` accepts two types of dictionaries, * The keys can contain indices like ``[2:-1]`` or ``[4:8]``, this works similar to how `slicing <https://realpython.com/python-strings/#string-slicing>`_ works in Python. The values should be the color of the Text from :class:`~.Color`. * The keys contain words or characters which should be colored separately and the values should be the color from :class:`~.Color`: .. manim:: Textt2cExample :save_last_frame: class Textt2cExample(Scene): def construct(self): t2cindices = Text('Hello', t2c={'[1:-1]': BLUE}).move_to(LEFT) t2cwords = Text('World',t2c={'rl':RED}).next_to(t2cindices, RIGHT) self.add(t2cindices, t2cwords) If you want to avoid problems when using colors (due to ligatures), consider using :class:`MarkupText`. Using Gradients --------------- You can add a gradient using :attr:`~.Text.gradient`. The value must be an iterable of any length: .. manim:: GradientExample :save_last_frame: class GradientExample(Scene): def construct(self): t = Text("Hello", gradient=(RED, BLUE, GREEN), font_size=96) self.add(t) You can also use :attr:`~.Text.t2g` for gradients with specific characters of the text. It shares a similar syntax to :ref:`the interface for colors <using-colors>`: .. manim:: t2gExample :save_last_frame: class t2gExample(Scene): def construct(self): t2gindices = Text( 'Hello', t2g={ '[1:-1]': (RED,GREEN), }, ).move_to(LEFT) t2gwords = Text( 'World', t2g={ 'World':(RED,BLUE), }, ).next_to(t2gindices, RIGHT) self.add(t2gindices, t2gwords) Setting Line Spacing -------------------- You can set the line spacing using :attr:`~.Text.line_spacing`: .. manim:: LineSpacing :save_last_frame: class LineSpacing(Scene): def construct(self): a = Text("Hello\nWorld", line_spacing=1) b = Text("Hello\nWorld", line_spacing=4) self.add(Group(a,b).arrange(LEFT, buff=5)) .. _disable-ligatures: Disabling Ligatures ------------------- By disabling ligatures you would get a one-to-one mapping between characters and submobjects. This fixes the issues with coloring text. .. warning:: Be aware that using this method with text that heavily depends on ligatures (Arabic text) may yield unexpected results. You can disable ligatures by passing ``disable_ligatures`` to :class:`Text`. For example: .. manim:: DisableLigature :save_last_frame: class DisableLigature(Scene): def construct(self): li = Text("fl ligature",font_size=96) nli = Text("fl ligature", disable_ligatures=True, font_size=96) self.add(Group(li, nli).arrange(DOWN, buff=.8)) .. _iterating-text: Iterating :class:`~.Text` ------------------------- Text objects behave like :class:`VGroups <.VGroup>`. Therefore, you can slice and index the text. For example, you can set each letter to different color by iterating it. .. manim:: IterateColor :save_last_frame: class IterateColor(Scene): def construct(self): text = Text("Colors", font_size=96) for letter in text: letter.set_color(random_bright_color()) self.add(text) .. warning:: Please note that `Ligature`_ can cause problems here. If you need a one-to-one mapping of characters to submobjects you should pass the ``disable_ligatures`` parameter to :class:`~.Text`. See :ref:`disable-ligatures`. .. _Ligature: https://en.wikipedia.org/wiki/Ligature_(writing) Working with :class:`~.MarkupText` ================================== MarkupText is similar to :class:`~.Text`, the only difference between them is that this accepts and processes PangoMarkup (which is similar to html), instead of just rendering plain text. Consult the documentation of :class:`~.MarkupText` for more details and further references about PangoMarkup. .. manim:: MarkupTest :save_last_frame: class MarkupTest(Scene): def construct(self): text = MarkupText( f'<span underline="double" underline_color="green">double green underline</span> in red text<span fgcolor="{YELLOW}"> except this</span>', color=RED, font_size=34 ) self.add(text) .. _rendering-with-latex: Text With LaTeX *************** Just as you can use :class:`~.Text` to add text to your videos, you can use :class:`~.Tex` to insert LaTeX. For example, .. manim::
|
MarkupTest(Scene): def construct(self): text = MarkupText( f'<span underline="double" underline_color="green">double green underline</span> in red text<span fgcolor="{YELLOW}"> except this</span>', color=RED, font_size=34 ) self.add(text) .. _rendering-with-latex: Text With LaTeX *************** Just as you can use :class:`~.Text` to add text to your videos, you can use :class:`~.Tex` to insert LaTeX. For example, .. manim:: HelloLaTeX :save_last_frame: class HelloLaTeX(Scene): def construct(self): tex = Tex(r"\LaTeX", font_size=144) self.add(tex) .. note:: Note that we are using a raw string (``r'...'``) instead of a regular string (``'...'``). This is because TeX code uses a lot of special characters - like ``\`` for example - that have special meaning within a regular python string. An alternative would have been to write ``\\`` to escape the backslash: ``Tex('\\LaTeX')``. Working with :class:`~.MathTex` =============================== Everything passed to :class:`~.MathTex` is in math mode by default. To be more precise, :class:`~.MathTex` is processed within an ``align*`` environment. You can achieve a similar effect with :class:`~.Tex` by enclosing your formula with ``$`` symbols: ``$\xrightarrow{x^6y^8}$``: .. manim:: MathTeXDemo :save_last_frame: class MathTeXDemo(Scene): def construct(self): rtarrow0 = MathTex(r"\xrightarrow{x^6y^8}", font_size=96) rtarrow1 = Tex(r"$\xrightarrow{x^6y^8}$", font_size=96) self.add(VGroup(rtarrow0, rtarrow1).arrange(DOWN)) LaTeX commands and keyword arguments ==================================== We can use any standard LaTeX commands in the AMS maths packages. Such as the ``mathtt`` math-text type or the ``looparrowright`` arrow. .. manim:: AMSLaTeX :save_last_frame: class AMSLaTeX(Scene): def construct(self): tex = Tex(r'$\mathtt{H} \looparrowright$ \LaTeX', font_size=144) self.add(tex) On the Manim side, the :class:`~.Tex` class also accepts attributes to change the appearance of the output. This is very similar to the :class:`~.Text` class. For example, the ``color`` keyword changes the color of the TeX mobject. .. manim:: LaTeXAttributes :save_last_frame: class LaTeXAttributes(Scene): def construct(self): tex = Tex(r'Hello \LaTeX', color=BLUE, font_size=144) self.add(tex) Extra LaTeX Packages ==================== Some commands require special packages to be loaded into the TeX template. For example, to use the ``mathscr`` script, we need to add the ``mathrsfs`` package. Since this package isn't loaded into Manim's tex template by default, we have to add it manually. .. manim:: AddPackageLatex :save_last_frame: class AddPackageLatex(Scene): def construct(self): myTemplate = TexTemplate() myTemplate.add_to_preamble(r"\usepackage{mathrsfs}") tex = Tex( r"$\mathscr{H} \rightarrow \mathbb{H}$", tex_template=myTemplate, font_size=144, ) self.add(tex) Substrings and parts ==================== The TeX mobject can accept multiple strings as arguments. Afterwards you can refer to the individual parts either by their index (like ``tex[1]``), or by selecting parts of the tex code. In this example, we set the color of the ``\bigstar`` using :func:`~.set_color_by_tex`: .. manim:: LaTeXSubstrings :save_last_frame: class LaTeXSubstrings(Scene): def construct(self): tex = Tex('Hello', r'$\bigstar$', r'\LaTeX', font_size=144) tex.set_color_by_tex('igsta', RED) self.add(tex) Note that :func:`~.set_color_by_tex` colors the entire substring containing the Tex, not just the specific symbol or Tex expression. Consider the following example: .. manim:: IncorrectLaTeXSubstringColoring :save_last_frame: class IncorrectLaTeXSubstringColoring(Scene): def construct(self): equation = MathTex( r"e^x = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots" ) equation.set_color_by_tex("x", YELLOW) self.add(equation) As you can see, this colors the entire equation yellow, contrary to what may be expected. To color only ``x`` yellow, we have to do the following: .. manim:: CorrectLaTeXSubstringColoring :save_last_frame: class CorrectLaTeXSubstringColoring(Scene): def construct(self): equation = MathTex( r"e^x = x^0
|
+ \frac{1}{n!} x^n + \cdots" ) equation.set_color_by_tex("x", YELLOW) self.add(equation) As you can see, this colors the entire equation yellow, contrary to what may be expected. To color only ``x`` yellow, we have to do the following: .. manim:: CorrectLaTeXSubstringColoring :save_last_frame: class CorrectLaTeXSubstringColoring(Scene): def construct(self): equation = MathTex( r"e^x = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots", substrings_to_isolate="x" ) equation.set_color_by_tex("x", YELLOW) self.add(equation) By setting ``substrings_to_isolate`` to ``x``, we split up the :class:`~.MathTex` into substrings automatically and isolate the ``x`` components into individual substrings. Only then can :meth:`~.set_color_by_tex` be used to achieve the desired result. Note that Manim also supports a custom syntax that allows splitting a TeX string into substrings easily: simply enclose parts of your formula that you want to isolate with double braces. In the string ``MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}")``, the rendered mobject will consist of the substrings ``a^2``, ``+``, ``b^2``, ``=``, and ``c^2``. This makes transformations between similar text fragments easy to write uing :class:`~.TransformMatchingTex`. Using ``index_labels`` to work with complicated strings ======================================================= You might sometimes be working with a very complicated :class:`~.MathTex` mobject that makes it difficult to work with its individual components. This is where the debugging function :func:`.index_labels` is very useful. The method shows the index of a mobject's submobjects, allowing you to easily find the components of the mobject you would like to change. .. manim:: IndexLabelsMathTex :save_last_frame: class IndexLabelsMathTex(Scene): def construct(self): text = MathTex(r"\binom{2n}{n+2}", font_size=96) # index the first (and only) term of the MathTex mob self.add(index_labels(text[0])) text[0][1:3].set_color(YELLOW) text[0][3:6].set_color(RED) self.add(text) LaTeX Maths Fonts - The Template Library ======================================== Changing fonts in LaTeX when typesetting mathematical formulae is trickier than regular text. It requires changing the template that is used to compile the TeX. Manim comes with a collection of :class:`~.TexFontTemplates` ready for you to use. These templates will all work in math mode: .. manim:: LaTeXMathFonts :save_last_frame: class LaTeXMathFonts(Scene): def construct(self): tex = Tex( r"$x^2 + y^2 = z^2$", tex_template=TexFontTemplates.french_cursive, font_size=144, ) self.add(tex) Manim also has a :class:`~.TexTemplateLibrary` containing the TeX templates used by 3Blue1Brown. One example is the ctex template, used for typesetting Chinese script. For this to work, the ctex LaTeX package must be installed on your system. Furthermore, if you are only typesetting Text, you probably do not need :class:`~.Tex` at all, and should use :class:`~.Text` instead. .. manim:: LaTeXTemplateLibrary :save_last_frame: class LaTeXTemplateLibrary(Scene): def construct(self): tex = Tex('Hello 你好 \\LaTeX', tex_template=TexTemplateLibrary.ctex, font_size=144) self.add(tex) Aligning formulae ================= :class:`~.MathTex` mobject is typeset in the LaTeX ``align*`` environment. This means you can use the ``&`` alignment character when typesetting multiline formulae: .. manim:: LaTeXAlignEnvironment :save_last_frame: class LaTeXAlignEnvironment(Scene): def construct(self): tex = MathTex(r'f(x) &= 3 + 2 + 1\\ &= 5 + 1 \\ &= 6', font_size=96) self.add(tex) ================================================ FILE: docs/source/installation/conda.rst ================================================ Conda ===== Required Dependencies --------------------- There are several package managers that work with conda packages, namely `conda <https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html>`__, `mamba <https://mamba.readthedocs.io>`__ and `pixi <https://pixi.sh>`__. After installing your package manager, you can create a new environment and install
|
1\\ &= 5 + 1 \\ &= 6', font_size=96) self.add(tex) ================================================ FILE: docs/source/installation/conda.rst ================================================ Conda ===== Required Dependencies --------------------- There are several package managers that work with conda packages, namely `conda <https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html>`__, `mamba <https://mamba.readthedocs.io>`__ and `pixi <https://pixi.sh>`__. After installing your package manager, you can create a new environment and install ``manim`` inside by running .. tab-set:: .. tab-item:: conda / mamba .. code-block:: bash # if you want to use mamba, just replace conda below with mamba conda create -n my-manim-environment conda activate my-manim-environment conda install -c conda-forge manim .. tab-item:: pixi .. code-block:: bash pixi init pixi add manim Since all dependencies (except LaTeX) are handled by conda, you don't need to worry about needing to install additional dependencies. Optional Dependencies --------------------- In order to make use of Manim's interface to LaTeX to, for example, render equations, LaTeX has to be installed as well. Note that this is an optional dependency: if you don't intend to use LaTeX, you don't have to install it. Recommendations on how to install LaTeX on different operating systems can be found :doc:`in our local installation guide </installation/uv>`. Working with Manim ------------------ At this point, you should have a working installation of Manim, head over to our :doc:`Quickstart Tutorial <../tutorials/quickstart>` to learn how to make your own *Manimations*! ================================================ FILE: docs/source/installation/docker.rst ================================================ Docker ====== The community maintains a docker image, which can be found `on DockerHub <https://hub.docker.com/r/manimcommunity/manim>`__. For our image ``manimcommunity/manim``, there are the following tags: - ``latest``: the most recent version corresponding to `the main branch <https://github.com/ManimCommunity/manim>`__, - ``stable``: the latest released version (according to `the releases page <https://github.com/ManimCommunity/manim/releases>`__), - ``vX.Y.Z``: any particular released version (according to `the releases page <https://github.com/ManimCommunity/manim/releases>`__). .. note:: When using Manim's CLI within a Docker container, some flags like ``-p`` (preview file) and ``-f`` (show output file in the file browser) are not supported. Basic usage of the Docker container ----------------------------------- Assuming that you can access the docker installation on your system from a terminal (bash / PowerShell) via ``docker``, you can render a scene ``CircleToSquare`` in a file `test_scenes.py` with the following command. .. code-block:: bash docker run --rm -it -v "/full/path/to/your/directory:/manim" manimcommunity/manim manim -qm test_scenes.py CircleToSquare .. tip:: For Linux users there might be permission problems when letting the user in the container write to the mounted volume. Add ``--user="$(id -u):$(id -g)"`` to the ``docker`` CLI arguments to prevent the creation of output files not belonging to your user. Instead of using the "throwaway container" approach outlined above, you can also create a named container that you can modify to your liking. First, run .. code-block:: sh docker run -it --name my-manim-container -v "/full/path/to/your/directory:/manim" manimcommunity/manim bash to obtain an interactive shell inside your container allowing you to, e.g., install further dependencies (like texlive packages using ``tlmgr``). Exit the container as soon as you are satisfied. Then, before using it, start the container by running .. code-block:: sh docker start my-manim-container which starts the container in the background. Then, to render a scene ``CircleToSquare`` in a file
|
to, e.g., install further dependencies (like texlive packages using ``tlmgr``). Exit the container as soon as you are satisfied. Then, before using it, start the container by running .. code-block:: sh docker start my-manim-container which starts the container in the background. Then, to render a scene ``CircleToSquare`` in a file ``test_scenes.py``, run .. code-block:: sh docker exec -it my-manim-container manim -qm test_scenes.py CircleToSquare Running JupyterLab via Docker ----------------------------- Another alternative to using the Docker image is to spin up a local JupyterLab instance. To do that, simply run .. code-block:: sh docker run -it -p 8888:8888 manimcommunity/manim jupyter lab --ip=0.0.0.0 and then follow the instructions in the terminal. ================================================ FILE: docs/source/installation/jupyter.rst ================================================ Jupyter Notebooks ================= Binder ------ `Binder <https://mybinder.readthedocs.io/en/latest/>`__ is an online platform that hosts shareable and customizable computing environments in the form of Jupyter notebooks. Manim ships with a built-in ``%%manim`` Jupyter magic command which makes it easy to use in these notebooks. To see an example for such an environment, visit our interactive tutorial over at https://try.manim.community/. It is relatively straightforward to prepare your own notebooks in a way that allows them to be shared interactively via Binder as well: #. First, prepare a directory containing one or multiple notebooks which you would like to share in an interactive environment. You can create these notebooks by using Jupyter notebooks with a local installation of Manim, or also by working in our pre-existing `interactive tutorial environment <https://try.manim.community/>`__. #. In the same directory containing your notebooks, add a file named ``Dockerfile`` with the following content: .. code-block:: dockerfile FROM docker.io/manimcommunity/manim:v0.9.0 COPY --chown=manimuser:manimuser . /manim Don't forget to change the version tag ``v0.9.0`` to the version you were working with locally when creating your notebooks. #. Make the directory with your worksheets and the ``Dockerfile`` available to the public (and in particular: to Binder!). There are `several different options to do so <https://mybinder.readthedocs.io/en/latest/introduction.html#how-can-i-prepare-a-repository-for-binder>`__, within the community we usually work with GitHub repositories or gists. #. Once your material is publicly available, visit https://mybinder.org and follow the instructions there to generate an interactive environment for your worksheets. .. hint:: The repository containing our `interactive tutorial <https://try.manim.community>`__ can be found at https://github.com/ManimCommunity/jupyter_examples. Google Colaboratory ------------------- It is also possible to install Manim in a `Google Colaboratory <https://colab.research.google.com/>`__ environment. In contrast to Binder, where you can customize and prepare the environment beforehand (such that Manim is already installed and ready to be used), you will have to take care of that every time you start a new notebook in Google Colab. Fortunately, this is not particularly difficult. After creating a new notebook, paste the following code block in a cell, then execute it. .. code-block:: !sudo apt update !sudo apt install libcairo2-dev \ texlive texlive-latex-extra texlive-fonts-extra \ texlive-latex-recommended texlive-science \ tipa libpango1.0-dev !pip install manim !pip install IPython==8.21.0 You should start to see Colab installing all the dependencies specified in these commands. After the execution has completed, you will be prompted to restart the runtime. Click the "restart runtime" button at the bottom of
|
texlive-latex-extra texlive-fonts-extra \ texlive-latex-recommended texlive-science \ tipa libpango1.0-dev !pip install manim !pip install IPython==8.21.0 You should start to see Colab installing all the dependencies specified in these commands. After the execution has completed, you will be prompted to restart the runtime. Click the "restart runtime" button at the bottom of the cell output. You are now ready to use Manim in Colab! To check that everything works as expected, first import Manim by running .. code-block:: from manim import * in a new code cell. Then create another cell containing the following code:: %%manim -qm -v WARNING SquareToCircle class SquareToCircle(Scene): def construct(self): square = Square() circle = Circle() circle.set_fill(PINK, opacity=0.5) self.play(Create(square)) self.play(Transform(square, circle)) self.wait() Upon running this cell, a short animation transforming a square into a circle should be rendered and displayed. ================================================ FILE: docs/source/installation/uv.md ================================================ # Installing Manim locally The standard way of installing Manim is by using Python's package manager `pip` to install the latest release from [PyPI](https://pypi.org/project/manim/). To make it easier for you to follow best practices when it comes to setting up a Python project for your Manim animations, we strongly recommend using a tool for managing Python environments and dependencies. In particular, [we strongly recommend using `uv`](https://docs.astral.sh/uv/#getting-started). For the two main ways of installing Manim described below, we assume that `uv` is available; we think it is particularly helpful if you are new to Python or programming in general. It is not a hard requirement whatsoever; if you know what you are doing you can just use `pip` to install Manim directly. :::::{admonition} Installing the Python management tool `uv` :class: seealso One way to install `uv` is via the dedicated console installer supporting all large operating systems. Simply paste the following snippet into your terminal / PowerShell -- or [consult `uv`'s documentation](https://docs.astral.sh/uv/#getting-started) for alternative ways to install the tool. ::::{tab-set} :::{tab-item} MacOS and Linux ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ::: :::{tab-item} Windows ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` ::: :::: ::::: Of course, if you know what you are doing and prefer to setup a virtual environment yourself, feel free to do so! :::{important} If you run into issues when following our instructions below, do not worry: check our [installation FAQs](<project:/faq/installation.md>) to see whether the problem is already addressed there -- and otherwise go and check [how to contact our community](<project:/faq/help.md>) to get help. ::: ## Installation ### Step 1: Installing Python We first need to check that an appropriate version of Python is available on your machine. Open a terminal to run ```bash uv python install ``` to install the latest version of Python. If this is successful, continue to the next step. (installation-optional-latex)= ### Step 2 (optional): Installing LaTeX [LaTeX](https://en.wikibooks.org/wiki/LaTeX/Mathematics) is a very well-known and widely used typesetting system allowing you to write formulas like \begin{equation*} \frac{1}{2\pi i} \oint_{\gamma} \frac{f(z)}{(z - z_0)^{n+1}}~dz = \frac{f^{(n)}(z_0)}{n!}. \end{equation*} If rendering plain text is sufficient for your needs and you don't want to render any typeset formulas, you can technically skip
|
Installing LaTeX [LaTeX](https://en.wikibooks.org/wiki/LaTeX/Mathematics) is a very well-known and widely used typesetting system allowing you to write formulas like \begin{equation*} \frac{1}{2\pi i} \oint_{\gamma} \frac{f(z)}{(z - z_0)^{n+1}}~dz = \frac{f^{(n)}(z_0)}{n!}. \end{equation*} If rendering plain text is sufficient for your needs and you don't want to render any typeset formulas, you can technically skip this step. Otherwise select your operating system from the tab list below and follow the instructions. :::::{tab-set} ::::{tab-item} Windows For Windows we recommend installing LaTeX via the [MiKTeX distribution](https://miktex.org). Simply grab the Windows installer available from their download page, <https://miktex.org/download> and run it. :::: ::::{tab-item} MacOS If you are running MacOS, we recommend installing the [MacTeX distribution](https://www.tug.org/mactex/). The latest available PKG file can be downloaded from <https://www.tug.org/mactex/mactex-download.html>. Get it and follow the standard installation procedure. :::: ::::{tab-item} Linux Given the large number of Linux distributions with different ways of installing packages, we cannot give detailed instructions for all package managers. In general we recommend to install a *TeX Live* distribution (<https://www.tug.org/texlive/>). For most Linux distributions, TeX Live has already been packaged such that it can be installed easily with your system package manager. Search the internet and your usual OS resources for detailed instructions. For example, on Debian-based systems with the package manager `apt`, a full TeX Live distribution can be installed by running ```bash sudo apt install texlive-full ``` For Fedora (managed via `dnf`), the corresponding command is ```bash sudo dnf install texlive-scheme-full ``` As soon as LaTeX is installed, continue with actually installing Manim itself. :::: ::::: :::{dropdown} I know what I am doing and I would like to setup a minimal LaTeX installation You are welcome to use a smaller, more customizable LaTeX distribution like [TinyTeX](https://yihui.org/tinytex/). Manim overall requires the following LaTeX packages to be installed in your distribution: ```text amsmath babel-english cbfonts-fd cm-super count1to ctex doublestroke dvisvgm everysel fontspec frcursive fundus-calligra gnu-freefont jknapltx latex-bin mathastext microtype multitoc physics preview prelim2e ragged2e relsize rsfs setspace standalone tipa wasy wasysym xcolor xetex xkeyval ``` ::: ### Step 3: Installing Manim These steps again differ slightly between different operating systems. Make sure you select the correct one from the tab list below, then follow the instructions below. ::::::{tab-set} :::::{tab-item} Windows The following commands will - create a new directory for a Python project, - and add Manim as a dependency, which installs it into the corresponding local Python environment. The name for the Python project is *manimations*, which you can change to anything you like. ```bash uv init manimations cd manimations uv add manim ``` Manim is now installed in your local project environment! ::::: :::::{tab-item} MacOS Before we can install Manim, we need to make sure that the system utilities `cairo` and `pkg-config` are present. They are needed for the [`pycairo` Python package](https://pycairo.readthedocs.io/en/latest/), a dependency of Manim. The easiest way of installing these utilities is by using [Homebrew](https://brew.sh/), a fairly popular 3rd party package manager for MacOS. Check whether Homebrew is already installed by running ```bash brew --version ``` which will report something along the lines of `Homebrew
|
for the [`pycairo` Python package](https://pycairo.readthedocs.io/en/latest/), a dependency of Manim. The easiest way of installing these utilities is by using [Homebrew](https://brew.sh/), a fairly popular 3rd party package manager for MacOS. Check whether Homebrew is already installed by running ```bash brew --version ``` which will report something along the lines of `Homebrew 4.4.15-54-...` if it is installed, and a message `command not found: brew` otherwise. In this case, use the shell installer [as instructed on Homebrew's website](https://brew.sh/), or get a `.pkg`-installer from [their GitHub release page](https://github.com/Homebrew/brew/releases). Make sure to follow the instructions of the installer carefully, especially when prompted to modify your `.zprofile` to add Homebrew to your system's PATH. With Homebrew available, the required utilities can be installed by running ```bash brew install cairo pkg-config ``` With all of this preparation out of the way, now it is time to actually install Manim itself! The following commands will - create a new directory for a Python project, - and add Manim as a dependency, which installs it into the corresponding local Python environment. The name for the Python project is *manimations*, which you can change to anything you like. ```bash uv init manimations cd manimations uv add manim ``` Manim is now installed in your local project environment! ::::: :::::{tab-item} Linux Practically, the instructions given in the *Windows* tab also apply for Linux -- however, some additional dependencies are required as Linux users need to build [ManimPango](https://github.com/ManimCommunity/ManimPango) (and potentially [pycairo](https://pycairo.readthedocs.io/en/latest/)) from source. More specifically, this includes: - A C compiler, - Python's development headers, - the `pkg-config` tool, - Pango and its development headers, - and Cairo and its development headers. Instructions for popular systems / package managers are given below. ::::{tab-set} :::{tab-item} Debian-based / apt ```bash sudo apt update sudo apt install build-essential python3-dev libcairo2-dev libpango1.0-dev ``` ::: :::{tab-item} Fedora / dnf ```bash sudo dnf install python3-devel pkg-config cairo-devel pango-devel ``` ::: :::{tab-item} Arch Linux / pacman ```bash sudo pacman -Syu base-devel cairo pango ``` ::: :::: As soon as the required dependencies are installed, you can create a Python project (feel free to change the name *manimations* used below to some other name) with a local environment containing Manim by running ```bash uv init manimations cd manimations uv add manim ``` ::::: :::::: To verify that your local Python project is setup correctly and that Manim is available, simply run ```bash uv run manim checkhealth ``` At this point, you can also open your project folder with the IDE of your choice. All modern Python IDEs (for example VS Code with the Python extension, or PyCharm) should automatically detect the local environment created by `uv` such that if you put ```py import manim ``` into a new file `my-first-animation.py`, the import is resolved correctly and autocompletion is available. *Happy Manimating!* :::{dropdown} Alternative: Installing Manim as a global `uv`-managed tool If you have Manim projects in many different directories and you do not want to setup a local project environment for each of them, you could also install Manim as
|
the import is resolved correctly and autocompletion is available. *Happy Manimating!* :::{dropdown} Alternative: Installing Manim as a global `uv`-managed tool If you have Manim projects in many different directories and you do not want to setup a local project environment for each of them, you could also install Manim as a `uv`-managed tool. See [`uv`'s documentation for more information](https://docs.astral.sh/uv/concepts/tools/) on their tool mechanism. To install Manim as a global `uv` tool, simply run ```bash uv tool install manim ``` after which the `manim` executable will be available on your global system path, without the need to activate any virtual environment or prefixing your commands with `uv run`. Note that when using this approach, setting up your code editor to properly resolve `import manim` requires additional work, as the global tool environment is not automatically detected: the base path of all tool environments can be determined by running ``` uv tool dir ``` which should now contain a directory `manim` in which the appropriate virtual environment is located. Set the Python interpreter of your IDE to this environment to make imports properly resolve themselves. ::: :::{dropdown} Installing Manim for a different version of Python In case you would like to use a different version of Python (for example, due to compatibility issues with other packages), then `uv` allows you to do so in a fairly straightforward way. When initializing the local Python project, simply pass the Python version you want to use as an argument to the `init` command: ``` uv init --python 3.12 manimations cd manimations uv add manim ``` To change the version for an existing package, you will need to edit the `pyproject.toml` file. If you are downgrading the python version, the `requires-python` entry needs to be updated such that your chosen version satisfies the requirement. Change the line to, for example `requires-python = ">=3.12"`. After that, run `uv python pin 3.12` to pin the python version to `3.12`. Finally, run `uv sync`, and your environment is updated! ::: ================================================ FILE: docs/source/reference_index/animations.rst ================================================ Animations ========== .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~animation.animation ~animation.changing ~animation.composition ~animation.creation ~animation.fading ~animation.growing ~animation.indication ~animation.movement ~animation.numbers ~animation.rotation ~animation.specialized ~animation.speedmodifier ~animation.transform ~animation.transform_matching_parts ~animation.updaters ================================================ FILE: docs/source/reference_index/cameras.rst ================================================ Cameras ======= .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~camera.camera ~camera.mapping_camera ~camera.moving_camera ~camera.multi_camera ~camera.three_d_camera ================================================ FILE: docs/source/reference_index/configuration.rst ================================================ Configuration ============= Module Index ------------ .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~_config ~_config.utils ~_config.logger_utils ================================================ FILE: docs/source/reference_index/mobjects.rst ================================================ Mobjects ======== .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~mobject.frame ~mobject.geometry ~mobject.graph ~mobject.graphing ~mobject.logo ~mobject.matrix ~mobject.mobject ~mobject.svg ~mobject.table ~mobject.text ~mobject.three_d ~mobject.types ~mobject.utils ~mobject.value_tracker ~mobject.vector_field ================================================ FILE: docs/source/reference_index/scenes.rst ================================================ Scenes ====== .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~scene.moving_camera_scene ~scene.section ~scene.scene ~scene.scene_file_writer ~scene.three_d_scene ~scene.vector_space_scene ~scene.zoomed_scene ================================================ FILE: docs/source/reference_index/utilities_misc.rst ================================================ Utilities and other modules =========================== Module Index ------------ .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~utils.bezier cli ~utils.color ~utils.commands ~utils.config_ops constants data_structures ~utils.debug ~utils.deprecation ~utils.docbuild ~utils.hashing ~utils.images ~utils.ipython_magic ~utils.iterables ~utils.paths ~utils.rate_functions ~utils.simple_functions ~utils.sounds ~utils.space_ops ~utils.testing ~utils.tex ~utils.tex_file_writing ~utils.tex_templates typing ================================================ FILE: docs/source/tutorials/building_blocks.rst ================================================ ####################### Manim's building blocks ####################### This document explains the
|
other modules =========================== Module Index ------------ .. currentmodule:: manim .. autosummary:: :toctree: ../reference ~utils.bezier cli ~utils.color ~utils.commands ~utils.config_ops constants data_structures ~utils.debug ~utils.deprecation ~utils.docbuild ~utils.hashing ~utils.images ~utils.ipython_magic ~utils.iterables ~utils.paths ~utils.rate_functions ~utils.simple_functions ~utils.sounds ~utils.space_ops ~utils.testing ~utils.tex ~utils.tex_file_writing ~utils.tex_templates typing ================================================ FILE: docs/source/tutorials/building_blocks.rst ================================================ ####################### Manim's building blocks ####################### This document explains the building blocks of manim and will give you all the necessary tools to start producing your own videos. Essentially, manim puts at your disposal three different concepts that you can orchestrate together to produce mathematical animations: the **mathematical object** (or **mobject** for short), the **animation**, and the **scene**. As we will see in the following sections, each of these three concepts is implemented in manim as a separate class: the :class:`.Mobject`, :class:`.Animation`, and :class:`.Scene` classes. .. note:: It is recommended that you read the tutorials :doc:`quickstart` and :doc:`output_and_config` before reading this page. ******** Mobjects ******** Mobjects are the basic building blocks for all manim animations. Each class that derives from :class:`.Mobject` represents an object that can be displayed on the screen. For example, simple shapes such as :class:`.Circle`, :class:`.Arrow`, and :class:`.Rectangle` are all mobjects. More complicated constructs such as :class:`.Axes`, :class:`.FunctionGraph`, or :class:`.BarChart` are mobjects as well. If you try to display an instance of :class:`.Mobject` on the screen, you will only see an empty frame. The reason is that the :class:`.Mobject` class is an abstract base class of all other mobjects, i.e. it does not have any pre-determined visual shape that can be displayed on the screen. It is only the skeleton of a thing that *could* be displayed. Therefore, you will rarely need to use plain instances of :class:`.Mobject`; instead, you will most likely create instances of its derived classes. One of these derived classes is :class:`.VMobject`. The ``V`` stands for Vectorized Mobject. In essence, a vmobject is a mobject that uses `vector graphics <https://en.wikipedia.org/wiki/Vector_graphics>`_ to be displayed. Most of the time, you will be dealing with vmobjects, though we will continue to use the term "mobject" to refer to the class of shapes that can be displayed on the screen, as it is more general. .. note:: Any object that can be displayed on the screen is a ``mobject``, even if it is not necessarily *mathematical* in nature. .. tip:: To see examples of classes derived from :class:`.Mobject`, see the :mod:`.geometry` module. Most of these are in fact derived from :class:`.VMobject` as well. Creating and displaying mobjects ================================ As explained in :doc:`quickstart`, usually all of the code in a manim script is put inside the :meth:`.construct` method of a :class:`.Scene` class. To display a mobject on the screen, call the :meth:`~.Scene.add` method of the containing :class:`.Scene`. This is the principal way of displaying a mobject on the screen when it is not being animated. To remove a mobject from the screen, simply call the :meth:`~.Scene.remove` method from the containing :class:`.Scene`. .. manim:: CreatingMobjects class CreatingMobjects(Scene): def construct(self): circle = Circle() self.add(circle) self.wait(1) self.remove(circle) self.wait(1) Placing mobjects ================ Let's define a new :class:`.Scene` called ``Shapes`` and :meth:`~.Scene.add` some
|
screen when it is not being animated. To remove a mobject from the screen, simply call the :meth:`~.Scene.remove` method from the containing :class:`.Scene`. .. manim:: CreatingMobjects class CreatingMobjects(Scene): def construct(self): circle = Circle() self.add(circle) self.wait(1) self.remove(circle) self.wait(1) Placing mobjects ================ Let's define a new :class:`.Scene` called ``Shapes`` and :meth:`~.Scene.add` some mobjects to it. This script generates a static picture that displays a circle, a square, and a triangle: .. manim:: Shapes class Shapes(Scene): def construct(self): circle = Circle() square = Square() triangle = Triangle() circle.shift(LEFT) square.shift(UP) triangle.shift(RIGHT) self.add(circle, square, triangle) self.wait(1) By default, mobjects are placed at the center of coordinates, or *origin*, when they are first created. They are also given some default colors. Further, the ``Shapes`` scene places the mobjects by using the :meth:`.shift` method. The square is shifted one unit in the ``UP`` direction from the origin, while the circle and triangle are shifted one unit ``LEFT`` and ``RIGHT``, respectively. .. attention:: Unlike other graphics software, manim places the center of coordinates at the center of the screen. The positive vertical direction is up, and the positive horizontal direction is right. See also the constants ``ORIGIN``, ``UP``, ``DOWN``, ``LEFT``, ``RIGHT``, and others, defined in the :mod:`.constants` module. There are many other possible ways to place mobjects on the screen, for example :meth:`.move_to`, :meth:`.next_to`, and :meth:`.align_to`. The next scene ``MobjectPlacement`` uses all three. .. manim:: MobjectPlacement class MobjectPlacement(Scene): def construct(self): circle = Circle() square = Square() triangle = Triangle() # place the circle two units left from the origin circle.move_to(LEFT * 2) # place the square to the left of the circle square.next_to(circle, LEFT) # align the left border of the triangle to the left border of the circle triangle.align_to(circle, LEFT) self.add(circle, square, triangle) self.wait(1) The :meth:`.move_to` method uses absolute units (measured relative to the ``ORIGIN``), while :meth:`.next_to` uses relative units (measured from the mobject passed as the first argument). :meth:`align_to` uses ``LEFT`` not as measuring units but as a way to determine the border to use for alignment. The coordinates of the borders of a mobject are determined using an imaginary bounding box around it. .. tip:: Many methods in manim can be chained together. For example the two lines .. code-block:: python square = Square() square.shift(LEFT) can be replaced by .. code-block:: python square = Square().shift(LEFT) Technically, this is possible because most methods calls return the modified mobject. Styling mobjects ================ The following scene changes the default aesthetics of the mobjects. .. manim:: MobjectStyling class MobjectStyling(Scene): def construct(self): circle = Circle().shift(LEFT) square = Square().shift(UP) triangle = Triangle().shift(RIGHT) circle.set_stroke(color=GREEN, width=20) square.set_fill(YELLOW, opacity=1.0) triangle.set_fill(PINK, opacity=0.5) self.add(circle, square, triangle) self.wait(1) This scene uses two of the main functions that change the visual style of a mobject: :meth:`.set_stroke` and :meth:`.set_fill`. The former changes the visual style of the mobject's border while the latter changes the style of the interior. By default, most mobjects have a fully transparent interior so you must specify the ``opacity`` parameter to display the color. An opacity of ``1.0`` means fully opaque, while ``0.0`` means fully
|
The former changes the visual style of the mobject's border while the latter changes the style of the interior. By default, most mobjects have a fully transparent interior so you must specify the ``opacity`` parameter to display the color. An opacity of ``1.0`` means fully opaque, while ``0.0`` means fully transparent. Only instances of :class:`.VMobject` implement :meth:`.set_stroke` and :meth:`.set_fill`. Instances of :class:`.Mobject` implement :meth:`.~Mobject.set_color` instead. The vast majority of pre-defined classes are derived from :class:`.VMobject` so it is usually safe to assume that you have access to :meth:`.set_stroke` and :meth:`.set_fill`. Mobject on-screen order ======================= The next scene is exactly the same as the ``MobjectStyling`` scene from the previous section, except for exactly one line. .. manim:: MobjectZOrder class MobjectZOrder(Scene): def construct(self): circle = Circle().shift(LEFT) square = Square().shift(UP) triangle = Triangle().shift(RIGHT) circle.set_stroke(color=GREEN, width=20) square.set_fill(YELLOW, opacity=1.0) triangle.set_fill(PINK, opacity=0.5) self.add(triangle, square, circle) self.wait(1) The only difference here (besides the scene name) is the order in which the mobjects are added to the scene. In ``MobjectStyling``, we added them as ``add(circle, square, triangle)``, whereas in ``MobjectZOrder`` we add them as ``add(triangle, square, circle)``. As you can see, the order of the arguments of :meth:`~.Scene.add` determines the order that the mobjects are displayed on the screen, with the left-most arguments being put in the back. ********** Animations ********** At the heart of manim is animation. Generally, you can add an animation to your scene by calling the :meth:`~.Scene.play` method. .. manim:: SomeAnimations class SomeAnimations(Scene): def construct(self): square = Square() # some animations display mobjects, ... self.play(FadeIn(square)) # ... some move or rotate mobjects around... self.play(Rotate(square, PI/4)) # some animations remove mobjects from the screen self.play(FadeOut(square)) self.wait(1) Put simply, animations are procedures that interpolate between two mobjects. For example, :code:`FadeIn(square)` starts with a fully transparent version of :code:`square` and ends with a fully opaque version, interpolating between them by gradually increasing the opacity. :class:`.FadeOut` works in the opposite way: it interpolates from fully opaque to fully transparent. As another example, :class:`.Rotate` starts with the mobject passed to it as argument, and ends with the same object but rotated by a certain amount, this time interpolating the mobject's angle instead of its opacity. Animating methods ================= Any property of a mobject that can be changed can be animated. In fact, any method that changes a mobject's property can be used as an animation, through the use of :meth:`.animate`. .. manim:: AnimateExample :ref_classes: Animation class AnimateExample(Scene): def construct(self): square = Square().set_fill(RED, opacity=1.0) self.add(square) # animate the change of color self.play(square.animate.set_fill(WHITE)) self.wait(1) # animate the change of position and the rotation at the same time self.play(square.animate.shift(UP).rotate(PI / 3)) self.wait(1) :meth:`.animate` is a property of all mobjects that animates the methods that come afterward. For example, :code:`square.set_fill(WHITE)` sets the fill color of the square, while :code:`square.animate.set_fill(WHITE)` animates this action. Animation run time ================== By default, any animation passed to :meth:`play` lasts for exactly one second. Use the :code:`run_time` argument to control the duration. .. manim:: RunTime class RunTime(Scene): def construct(self): square = Square() self.add(square) self.play(square.animate.shift(UP), run_time=3) self.wait(1) Creating a custom
|
color of the square, while :code:`square.animate.set_fill(WHITE)` animates this action. Animation run time ================== By default, any animation passed to :meth:`play` lasts for exactly one second. Use the :code:`run_time` argument to control the duration. .. manim:: RunTime class RunTime(Scene): def construct(self): square = Square() self.add(square) self.play(square.animate.shift(UP), run_time=3) self.wait(1) Creating a custom animation =========================== Even though Manim has many built-in animations, you will find times when you need to smoothly animate from one state of a :class:`~.Mobject` to another. If you find yourself in that situation, then you can define your own custom animation. You start by extending the :class:`~.Animation` class and overriding its :meth:`~.Animation.interpolate_mobject`. The :meth:`~.Animation.interpolate_mobject` method receives alpha as a parameter that starts at 0 and changes throughout the animation. So, you just have to manipulate self.mobject inside Animation according to the alpha value in its interpolate_mobject method. Then you get all the benefits of :class:`~.Animation` such as playing it for different run times or using different rate functions. Let's say you start with a number and want to create a :class:`~.Transform` animation that transforms it to a target number. You can do it using :class:`~.FadeTransform`, which will fade out the starting number and fade in the target number. But when we think about transforming a number from one to another, an intuitive way of doing it is by incrementing or decrementing it smoothly. Manim has a feature that allows you to customize this behavior by defining your own custom animation. You can start by creating your own ``Count`` class that extends :class:`~.Animation`. The class can have a constructor with three arguments, a :class:`~.DecimalNumber` Mobject, start, and end. The constructor will pass the :class:`~.DecimalNumber` Mobject to the super constructor (in this case, the :class:`~.Animation` constructor) and will set start and end. The only thing that you need to do is to define how you want it to look at every step of the animation. Manim provides you with the alpha value in the :meth:`~.Animation.interpolate_mobject` method based on frame rate of video, rate function, and run time of animation played. The alpha parameter holds a value between 0 and 1 representing the step of the currently playing animation. For example, 0 means the beginning of the animation, 0.5 means halfway through the animation, and 1 means the end of the animation. In the case of the ``Count`` animation, you just have to figure out a way to determine the number to display at the given alpha value and then set that value in the :meth:`~.Animation.interpolate_mobject` method of the ``Count`` animation. Suppose you are starting at 50 and incrementing until the :class:`~.DecimalNumber` reaches 100 at the end of the animation. * If alpha is 0, you want the value to be 50. * If alpha is 0.5, you want the value to be 75. * If alpha is 1, you want the value to be 100. Generally, you start with the starting number and add only some part of the value to be increment according to the alpha value. So, the logic
|
* If alpha is 0.5, you want the value to be 75. * If alpha is 1, you want the value to be 100. Generally, you start with the starting number and add only some part of the value to be increment according to the alpha value. So, the logic of calculating the number to display at each step will be ``50 + alpha * (100 - 50)``. Once you set the calculated value for the :class:`~.DecimalNumber`, you are done. .. note:: If you're creating a custom animation and want to use a ``rate_func``, you must explicitly apply ``self.rate_func(alpha)`` to the parameter you're animating. For example, try switching the rate function to ``rate_functions.there_and_back`` to observe how it affects the counting behavior. Once you have defined your ``Count`` animation, you can play it in your :class:`~.Scene` for any duration you want for any :class:`~.DecimalNumber` with any rate function. .. manim:: CountingScene :ref_classes: Animation DecimalNumber :ref_methods: Animation.interpolate_mobject Scene.play class Count(Animation): def __init__(self, number: DecimalNumber, start: float, end: float, **kwargs) -> None: # Pass number as the mobject of the animation super().__init__(number, **kwargs) # Set start and end self.start = start self.end = end def interpolate_mobject(self, alpha: float) -> None: # Set value of DecimalNumber according to alpha value = self.start + (self.rate_func(alpha) * (self.end - self.start)) self.mobject.set_value(value) class CountingScene(Scene): def construct(self): # Create Decimal Number and add it to scene number = DecimalNumber().set_color(WHITE).scale(5) # Add an updater to keep the DecimalNumber centered as its value changes number.add_updater(lambda number: number.move_to(ORIGIN)) self.add(number) self.wait() # Play the Count Animation to count from 0 to 100 in 4 seconds self.play(Count(number, 0, 100), run_time=4, rate_func=linear) self.wait() Using coordinates of a mobject ============================== Mobjects contain points that define their boundaries. These points can be used to add other mobjects respectively to each other, e.g. by methods like :meth:`~.Mobject.get_center` , :meth:`~.Mobject.get_top` and :meth:`~.Mobject.get_start`. Here is an example of some important coordinates: .. manim:: MobjectExample :save_last_frame: class MobjectExample(Scene): def construct(self): p1 = [-1,-1, 0] p2 = [ 1,-1, 0] p3 = [ 1, 1, 0] p4 = [-1, 1, 0] a = Line(p1,p2).append_points(Line(p2,p3).points).append_points(Line(p3,p4).points) point_start = a.get_start() point_end = a.get_end() point_center = a.get_center() self.add(Text(f"a.get_start() = {np.round(point_start,2).tolist()}", font_size=24).to_edge(UR).set_color(YELLOW)) self.add(Text(f"a.get_end() = {np.round(point_end,2).tolist()}", font_size=24).next_to(self.mobjects[-1],DOWN).set_color(RED)) self.add(Text(f"a.get_center() = {np.round(point_center,2).tolist()}", font_size=24).next_to(self.mobjects[-1],DOWN).set_color(BLUE)) self.add(Dot(a.get_start()).set_color(YELLOW).scale(2)) self.add(Dot(a.get_end()).set_color(RED).scale(2)) self.add(Dot(a.get_top()).set_color(GREEN_A).scale(2)) self.add(Dot(a.get_bottom()).set_color(GREEN_D).scale(2)) self.add(Dot(a.get_center()).set_color(BLUE).scale(2)) self.add(Dot(a.point_from_proportion(0.5)).set_color(ORANGE).scale(2)) self.add(*[Dot(x) for x in a.points]) self.add(a) Transforming mobjects into other mobjects ========================================= It is also possible to transform a mobject into another mobject like this: .. manim:: ExampleTransform class ExampleTransform(Scene): def construct(self): self.camera.background_color = WHITE m1 = Square().set_color(RED) m2 = Rectangle().set_color(RED).rotate(0.2) self.play(Transform(m1,m2)) The Transform function maps points of the previous mobject to the points of the next mobject. This might result in strange behaviour, e.g. when the dots of one mobject are arranged clockwise and the other points are arranged counterclockwise. Here it might help to use the `flip` function and reposition the points via the `roll <https://numpy.org/doc/stable/reference/generated/numpy.roll.html>`_ function of numpy: .. manim:: ExampleRotation class ExampleRotation(Scene): def construct(self): self.camera.background_color = WHITE m1a = Square().set_color(RED).shift(LEFT) m1b = Circle().set_color(RED).shift(LEFT) m2a = Square().set_color(BLUE).shift(RIGHT) m2b = Circle().set_color(BLUE).shift(RIGHT) points = m2a.points points = np.roll(points, int(len(points)/4),
|
counterclockwise. Here it might help to use the `flip` function and reposition the points via the `roll <https://numpy.org/doc/stable/reference/generated/numpy.roll.html>`_ function of numpy: .. manim:: ExampleRotation class ExampleRotation(Scene): def construct(self): self.camera.background_color = WHITE m1a = Square().set_color(RED).shift(LEFT) m1b = Circle().set_color(RED).shift(LEFT) m2a = Square().set_color(BLUE).shift(RIGHT) m2b = Circle().set_color(BLUE).shift(RIGHT) points = m2a.points points = np.roll(points, int(len(points)/4), axis=0) m2a.points = points self.play(Transform(m1a,m1b),Transform(m2a,m2b), run_time=1) ****** Scenes ****** The :class:`.Scene` class is the connective tissue of manim. Every mobject has to be :meth:`added <.Scene.add>` to a scene to be displayed, or :meth:`removed <.Scene.remove>` from it to cease being displayed. Every animation has to be :meth:`played <.Scene.play>` by a scene, and every time interval where no animation occurs is determined by a call to :meth:`~.Scene.wait`. All of the code of your video must be contained in the :meth:`~.Scene.construct` method of a class that derives from :class:`.Scene`. Finally, a single file may contain multiple :class:`.Scene` subclasses if multiple scenes are to be rendered at the same time. ================================================ FILE: docs/source/tutorials/index.rst ================================================ Tutorials ========= .. toctree:: :caption: Table of Contents :maxdepth: 2 quickstart output_and_config building_blocks ================================================ FILE: docs/source/tutorials/output_and_config.rst ================================================ Manim's Output Settings ======================= This document will focus on understanding manim's output files and some of the main command-line flags available. .. note:: This tutorial picks up where :doc:`quickstart` left off, so please read that document before starting this one. Manim output folders ******************** At this point, you have just executed the following command. .. code-block:: bash manim -pql scene.py SquareToCircle Let's dissect what just happened step by step. First, this command executes manim on the file ``scene.py``, which contains our animation code. Further, this command tells manim exactly which ``Scene`` is to be rendered, in this case, it is ``SquareToCircle``. This is necessary because a single scene file may contain more than one scene. Next, the flag `-p` tells manim to play the scene once it's rendered, and the `-ql` flag tells manim to render the scene in low quality. After the video is rendered, you will see that manim has generated some new files and the project folder will look as follows. .. code-block:: bash project/ ├─scene.py └─media ├─videos | └─scene | └─480p15 | ├─SquareToCircle.mp4 | └─partial_movie_files ├─text └─Tex There are quite a few new files. The main output is in ``media/videos/scene/480p15/SquareToCircle.mp4``. By default, the ``media`` folder will contain all of manim's output files. The ``m/videos`` subfolder contains the rendered videos. Inside of it, you will find one folder for each different video quality. In our case, since we used the ``-l`` flag, the video was generated at 480 resolution at 15 frames per second from the ``scene.py`` file. Therefore, the output can be found inside ``media/videos/scene/480p15``. The additional folders ``media/videos/scene/480p15/partial_movie_files`` as well as ``media/text`` and ``media/Tex`` contain files that are used by manim internally. You can see how manim makes use of the generated folder structure by executing the following command, .. code-block:: bash manim -pqh scene.py SquareToCircle The ``-ql`` flag (for low quality) has been replaced by the ``-qh`` flag, for high quality. Manim will take considerably longer to
|
used by manim internally. You can see how manim makes use of the generated folder structure by executing the following command, .. code-block:: bash manim -pqh scene.py SquareToCircle The ``-ql`` flag (for low quality) has been replaced by the ``-qh`` flag, for high quality. Manim will take considerably longer to render this file, and it will play it once it's done since we are using the ``-p`` flag. The output should look like this: .. manim:: SquareToCircle3 :hide_source: :quality: high class SquareToCircle3(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set color and transparency square = Square() # create a square square.flip(RIGHT) # flip horizontally square.rotate(-3 * TAU / 8) # rotate a certain amount self.play(Create(square)) # animate the creation of the square self.play(Transform(square, circle)) # interpolate the square into the circle self.play(FadeOut(square)) # fade out animation And the folder structure should look as follows. .. code-block:: bash project/ ├─scene.py └─media ├─videos | └─scene | ├─480p15 | | ├─SquareToCircle.mp4 | | └─partial_movie_files | └─1080p60 | ├─SquareToCircle.mp4 | └─partial_movie_files ├─text └─Tex Manim has created a new folder ``media/videos/1080p60``, which corresponds to the high resolution and the 60 frames per second. Inside of it, you can find the new ``SquareToCircle.mp4``, as well as the corresponding ``partial_movie_files``. When working on a project with multiple scenes, and trying out multiple resolutions, the structure of the output directories will keep all your videos organized. Further, manim has the option to output the last frame of a scene, when adding the flag ``-s``. This is the fastest option to quickly get a preview of a scene. The corresponding folder structure looks like this: .. code-block:: bash project/ ├─scene.py └─media ├─images | └─scene | ├─SquareToCircle.png ├─videos | └─scene | ├─480p15 | | ├─SquareToCircle.mp4 | | └─partial_movie_files | └─1080p60 | ├─SquareToCircle.mp4 | └─partial_movie_files ├─text └─Tex Saving the last frame with ``-s`` can with the flags for different resolutions, e.g. ``-s -ql``, ``-s -qh`` Sections ******** In addition to the movie output file one can use sections. Each section produces its own output video. The cuts between two sections can be set like this: .. code-block:: python def construct(self): # play the first animations... # you don't need a section in the very beginning as it gets created automatically self.next_section() # play more animations... self.next_section("this is an optional name that doesn't have to be unique") # play even more animations... self.next_section("this is a section without any animations, it will be removed") All the animations between two of these cuts get concatenated into a single output video file. Be aware that you need at least one animation in each section. For example this wouldn't create an output video: .. code-block:: python def construct(self): self.next_section() # this section doesn't have any animations and will be removed # but no error will be thrown # feel free to tend your flock of empty sections if you so desire self.add(Circle()) self.next_section() One way of fixing this is to wait a little: .. code-block:: python def construct(self): self.next_section() self.add(Circle()) #
|
section doesn't have any animations and will be removed # but no error will be thrown # feel free to tend your flock of empty sections if you so desire self.add(Circle()) self.next_section() One way of fixing this is to wait a little: .. code-block:: python def construct(self): self.next_section() self.add(Circle()) # now we wait 1sec and have an animation to satisfy the section self.wait() self.next_section() For videos to be created for each section you have to add the ``--save_sections`` flag to the Manim call like this: .. code-block:: bash manim --save_sections scene.py If you do this, the ``media`` folder will look like this: .. code-block:: bash media ├── images │ └── simple_scenes └── videos └── simple_scenes └── 480p15 ├── ElaborateSceneWithSections.mp4 ├── partial_movie_files │ └── ElaborateSceneWithSectio │ ├── 2201830969_104169243_1331664314.mp4 │ ├── 2201830969_398514950_125983425.mp4 │ ├── 2201830969_398514950_3447021159.mp4 │ ├── 2201830969_398514950_4144009089.mp4 │ ├── 2201830969_4218360830_1789939690.mp4 │ ├── 3163782288_524160878_1793580042.mp4 │ └── partial_movie_file_list.txt âs ├── ElaborateSceneWithSections_0000.mp4 ├── ElaborateSceneWithSections_0001.mp4 ├── ElaborateSceneWithSections_0002.mp4 └── ElaborateSceneWithSections.json As you can see each section receives their own output video in the ``sections`` directory. The JSON file in here contains some useful information for each section: .. code-block:: json [ { "name": "create square", pe": "default.normal", "video": "ElaborateSceneWithSections_0000.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30" }, { "name": "transform to circle", "type": "default.normal", "video": "ElaborateSceneWithSections_0001.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30" }, { "name": "fade out", "type": "default.normal", "video": "ElaborateSceneWithSections_0002.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30" } ] This data can be used by third party applications, like a presentation system or automated video editing tool. You can also skip rendering all animations belonging to a section like this: .. code-block:: python def construct(self): self.next_section(skip_animations=True) # play some animations that shall be skipped... self.next_section() # play some animations that won't get skipped... Some command line flags *********************** When executing the command .. code-block:: bash manim -pql scene.py SquareToCircle it specifies the scene to render. This is not necessary now. When a single file contains only one ``Scene`` class, it will just render the ``Scene`` class. When a single file contains more than one ``Scene`` class, manim will let you choose a ``Scene`` class. If your file contains multiple ``Scene`` classes, and you want to render them all, you can use the ``-a`` flag. As discussed previously, the ``-ql`` specifies low render quality (854x480 15FPS). This does not look very good, but is very useful for rapid prototyping and testing. The other options that specify render quality are ``-qm``, ``-qh``, ``-qp`` and ``-qk`` for medium (1280x720 30FPS), high (1920x1080 60FPS), 2k (2560x1440 60FPS) and 4k quality (3840x2160 60FPS), respectively. The ``-p`` flag plays the animation once it is rendered. If you want to open the file browser at the location of the animation instead of playing it, you can use the ``-f`` flag. You can also omit these two flags. Finally, by default manim will output .mp4 files. If you want your animations in .gif format instead, use the
|
If you want to open the file browser at the location of the animation instead of playing it, you can use the ``-f`` flag. You can also omit these two flags. Finally, by default manim will output .mp4 files. If you want your animations in .gif format instead, use the ``--format gif`` flag. The output files will be in the same folder as the .mp4 files, and with the same name, but a different file extension. This was a quick review of some of the most frequent command-line flags. For a thorough review of all flags available, see the :doc:`thematic guide on Manim's configuration system </guides/configuration>`. ================================================ FILE: docs/source/tutorials/quickstart.rst ================================================ ========== Quickstart ========== .. note:: Before proceeding, install Manim and make sure it is running properly by following the steps in :doc:`../installation`. For information on using Manim with Jupyterlab or Jupyter notebook, go to the documentation for the :meth:`IPython magic command <manim.utils.ipython_magic.ManimMagic.manim>`, ``%%manim``. .. important:: If you installed Manim in the recommended way, using the Python management tool ``uv``, then you either need to make sure the corresponding virtual environment is activated (follow the instructions printed on running ``uv venv``), or you need to remember to prefix the ``manim`` command in the console with ``uv run``; that is, ``uv run manim ...``. Overview ******** This quickstart guide will lead you through creating a sample project using Manim: an animation engine for precise programmatic animations. First, you will use a command line interface to create a ``Scene``, the class through which Manim generates videos. In the ``Scene`` you will animate a circle. Then you will add another ``Scene`` showing a square transforming into a circle. This will be your introduction to Manim's animation ability. Afterwards, you will position multiple mathematical objects (``Mobject``\s). Finally, you will learn the ``.animate`` syntax, a powerful feature that animates the methods you use to modify ``Mobject``\s. Starting a new project ********************** Start by creating a new folder:: manim init project my-project --default The ``my-project`` folder is the root folder for your project. It contains all the files that Manim needs to function, as well as any output that your project produces. Animating a circle ****************** 1. Open a text editor, such as Notepad. Open the file ``main.py`` in the ``my-project`` folder. It should look something like this: .. code-block:: python from manim import * class CreateCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency self.play(Create(circle)) # show the circle on screen 2. Open the command line, navigate to your project folder, and execute the following command: .. code-block:: bash manim -pql main.py CreateCircle Manim will output rendering information, then create an MP4 file. Your default movie player will play the MP4 file, displaying the following animation. .. manim:: CreateCircle :hide_source: class CreateCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency self.play(Create(circle)) # show the circle on screen If you see an animation of a pink circle being drawn,
|
will play the MP4 file, displaying the following animation. .. manim:: CreateCircle :hide_source: class CreateCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency self.play(Create(circle)) # show the circle on screen If you see an animation of a pink circle being drawn, congratulations! You just wrote your first Manim scene from scratch. If you get an error message instead, you do not see a video, or if the video output does not look like the preceding animation, it is likely that Manim has not been installed correctly. Please refer to our :doc:`FAQ section </faq/index>` for help with the most common issues. *********** Explanation *********** Let's go over the script you just executed line by line to see how Manim was able to draw the circle. The first line imports all of the contents of the library: .. code-block:: python from manim import * This is the recommended way of using Manim, as a single script often uses multiple names from the Manim namespace. In your script, you imported and used ``Scene``, ``Circle``, ``PINK`` and ``Create``. Now let's look at the next two lines: .. code-block:: python class CreateCircle(Scene): def construct(self): [...] Most of the time, the code for scripting an animation is entirely contained within the :meth:`~.Scene.construct` method of a :class:`.Scene` class. Inside :meth:`~.Scene.construct`, you can create objects, display them on screen, and animate them. The next two lines create a circle and set its color and opacity: .. code-block:: python circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency Finally, the last line uses the animation :class:`.Create` to display the circle on your screen: .. code-block:: python self.play(Create(circle)) # show the circle on screen .. tip:: All animations must reside within the :meth:`~.Scene.construct` method of a class derived from :class:`.Scene`. Other code, such as auxiliary or mathematical functions, may reside outside the class. Transforming a square into a circle *********************************** With our circle animation complete, let's move on to something a little more complicated. 1. Open ``scene.py``, and add the following code snippet below the ``CreateCircle`` class: .. code-block:: python class SquareToCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set color and transparency square = Square() # create a square square.rotate(PI / 4) # rotate a certain amount self.play(Create(square)) # animate the creation of the square self.play(Transform(square, circle)) # interpolate the square into the circle self.play(FadeOut(square)) # fade out animation 2. Render ``SquareToCircle`` by running the following command in the command line: .. code-block:: bash manim -pql scene.py SquareToCircle The following animation will render: .. manim:: SquareToCircle2 :hide_source: class SquareToCircle2(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set color and transparency square = Square() # create a square square.rotate(PI / 4) # rotate a certain amount self.play(Create(square)) # animate the creation of the square self.play(Transform(square, circle)) # interpolate the square into the circle self.play(FadeOut(square)) # fade out animation This example shows one of the primary
|
opacity=0.5) # set color and transparency square = Square() # create a square square.rotate(PI / 4) # rotate a certain amount self.play(Create(square)) # animate the creation of the square self.play(Transform(square, circle)) # interpolate the square into the circle self.play(FadeOut(square)) # fade out animation This example shows one of the primary features of Manim: the ability to implement complicated and mathematically intensive animations (such as cleanly interpolating between two geometric shapes) with just a few lines of code. Positioning ``Mobject``\s ************************* Next, let's go over some basic techniques for positioning ``Mobject``\s. 1. Open ``scene.py``, and add the following code snippet below the ``SquareToCircle`` method: .. code-block:: python class SquareAndCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency square = Square() # create a square square.set_fill(BLUE, opacity=0.5) # set the color and transparency square.next_to(circle, RIGHT, buff=0.5) # set the position self.play(Create(circle), Create(square)) # show the shapes on screen 2. Render ``SquareAndCircle`` by running the following command in the command line: .. code-block:: bash manim -pql scene.py SquareAndCircle The following animation will render: .. manim:: SquareAndCircle2 :hide_source: class SquareAndCircle2(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set the color and transparency square = Square() # create a square square.set_fill(BLUE, opacity=0.5) # set the color and transparency square.next_to(circle, RIGHT, buff=0.5) # set the position self.play(Create(circle), Create(square)) # show the shapes on screen ``next_to`` is a ``Mobject`` method for positioning ``Mobject``\s. We first specified the pink circle as the square's reference point by passing ``circle`` as the method's first argument. The second argument is used to specify the direction the ``Mobject`` is placed relative to the reference point. In this case, we set the direction to ``RIGHT``, telling Manim to position the square to the right of the circle. Finally, ``buff=0.5`` applied a small distance buffer between the two objects. Try changing ``RIGHT`` to ``LEFT``, ``UP``, or ``DOWN`` instead, and see how that changes the position of the square. Using positioning methods, you can render a scene with multiple ``Mobject``\s, setting their locations in the scene using coordinates or positioning them relative to each other. For more information on ``next_to`` and other positioning methods, check out the list of :class:`.Mobject` methods in our reference manual. Using ``.animate`` syntax to animate methods ******************************************** The final lesson in this tutorial is using ``.animate``, a ``Mobject`` method which animates changes you make to a ``Mobject``. When you prepend ``.animate`` to any method call that modifies a ``Mobject``, the method becomes an animation which can be played using ``self.play``. Let's return to ``SquareToCircle`` to see the differences between using methods when creating a ``Mobject``, and animating those method calls with ``.animate``. 1. Open ``scene.py``, and add the following code snippet below the ``SquareAndCircle`` class: .. code-block:: python class AnimatedSquareToCircle(Scene): def construct(self): circle = Circle() # create a circle square = Square() # create a square self.play(Create(square)) # show the square on screen self.play(square.animate.rotate(PI / 4)) # rotate the square self.play(Transform(square, circle)) # transform the square
|
add the following code snippet below the ``SquareAndCircle`` class: .. code-block:: python class AnimatedSquareToCircle(Scene): def construct(self): circle = Circle() # create a circle square = Square() # create a square self.play(Create(square)) # show the square on screen self.play(square.animate.rotate(PI / 4)) # rotate the square self.play(Transform(square, circle)) # transform the square into a circle self.play( square.animate.set_fill(PINK, opacity=0.5) ) # color the circle on screen 2. Render ``AnimatedSquareToCircle`` by running the following command in the command line: .. code-block:: bash manim -pql scene.py AnimatedSquareToCircle The following animation will render: .. manim:: AnimatedSquareToCircle2 :hide_source: class AnimatedSquareToCircle2(Scene): def construct(self): circle = Circle() # create a circle square = Square() # create a square self.play(Create(square)) # show the square on screen self.play(square.animate.rotate(PI / 4)) # rotate the square self.play(Transform(square, circle)) # transform the square into a circle self.play(square.animate.set_fill(PINK, opacity=0.5)) # color the circle on screen The first ``self.play`` creates the square. The second animates rotating it 45 degrees. The third transforms the square into a circle, and the last colors the circle pink. Although the end result is the same as that of ``SquareToCircle``, ``.animate`` shows ``rotate`` and ``set_fill`` being applied to the ``Mobject`` dynamically, instead of creating them with the changes already applied. Try other methods, like ``flip`` or ``shift``, and see what happens. 3. Open ``scene.py``, and add the following code snippet below the ``AnimatedSquareToCircle`` class: .. code-block:: python class DifferentRotations(Scene): def construct(self): left_square = Square(color=BLUE, fill_opacity=0.7).shift(2 * LEFT) right_square = Square(color=GREEN, fill_opacity=0.7).shift(2 * RIGHT) self.play( left_square.animate.rotate(PI), Rotate(right_square, angle=PI), run_time=2 ) self.wait() 4. Render ``DifferentRotations`` by running the following command in the command line: .. code-block:: bash manim -pql scene.py DifferentRotations The following animation will render: .. manim:: DifferentRotations2 :hide_source: class DifferentRotations2(Scene): def construct(self): left_square = Square(color=BLUE, fill_opacity=0.7).shift(2*LEFT) right_square = Square(color=GREEN, fill_opacity=0.7).shift(2*RIGHT) self.play(left_square.animate.rotate(PI), Rotate(right_square, angle=PI), run_time=2) self.wait() This ``Scene`` illustrates the quirks of ``.animate``. When using ``.animate``, Manim actually takes a ``Mobject``'s starting state and its ending state and interpolates the two. In the ``AnimatedSquareToCircle`` class, you can observe this when the square rotates: the corners of the square appear to contract slightly as they move into the positions required for the first square to transform into the second one. In ``DifferentRotations``, the difference between ``.animate``'s interpretation of rotation and the ``Rotate`` method is far more apparent. The starting and ending states of a ``Mobject`` rotated 180 degrees are the same, so ``.animate`` tries to interpolate two identical objects and the result is the left square. If you find that your own usage of ``.animate`` is causing similar unwanted behavior, consider using conventional animation methods like the right square, which uses ``Rotate``. ``Transform`` vs ``ReplacementTransform`` ***************************************** The difference between ``Transform`` and ``ReplacementTransform`` is that ``Transform(mob1, mob2)`` transforms the points (as well as other attributes like color) of ``mob1`` into the points/attributes of ``mob2``. ``ReplacementTransform(mob1, mob2)`` on the other hand literally replaces ``mob1`` on the scene with ``mob2``. The use of ``ReplacementTransform`` or ``Transform`` is mostly up to personal preference. They can be used to accomplish the same effect, as shown below. .. code-block::
|
attributes like color) of ``mob1`` into the points/attributes of ``mob2``. ``ReplacementTransform(mob1, mob2)`` on the other hand literally replaces ``mob1`` on the scene with ``mob2``. The use of ``ReplacementTransform`` or ``Transform`` is mostly up to personal preference. They can be used to accomplish the same effect, as shown below. .. code-block:: python class TwoTransforms(Scene): def transform(self): a = Circle() b = Square() c = Triangle() self.play(Transform(a, b)) self.play(Transform(a, c)) self.play(FadeOut(a)) def replacement_transform(self): a = Circle() b = Square() c = Triangle() self.play(ReplacementTransform(a, b)) self.play(ReplacementTransform(b, c)) self.play(FadeOut(c)) def construct(self): self.transform() self.wait(0.5) # wait for 0.5 seconds self.replacement_transform() However, in some cases it is more beneficial to use ``Transform``, like when you are transforming several mobjects one after the other. The code below avoids having to keep a reference to the last mobject that was transformed. .. manim:: TransformCycle class TransformCycle(Scene): def construct(self): a = Circle() t1 = Square() t2 = Triangle() self.add(a) self.wait() for t in [t1,t2]: self.play(Transform(a,t)) ************ You're done! ************ With a working installation of Manim and this sample project under your belt, you're ready to start creating animations of your own. To learn more about what Manim is doing under the hood, move on to the next tutorial: :doc:`output_and_config`. For an overview of Manim's features, as well as its configuration and other settings, check out the other :doc:`Tutorials <../tutorials/index>`. For a list of all available features, refer to the :doc:`../reference` page. ================================================ FILE: example_scenes/advanced_tex_fonts.py ================================================ from manim import * # French Cursive LaTeX font example from http://jf.burnol.free.fr/showcase.html # Example 1 Manually creating a Template TemplateForFrenchCursive = TexTemplate( preamble=r""" \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage[T1]{fontenc} \usepackage[default]{frcursive} \usepackage[eulergreek,noplusnominus,noequal,nohbar,% nolessnomore,noasterisk]{mathastext} """, ) def FrenchCursive(*tex_strings, **kwargs): return Tex(*tex_strings, tex_template=TemplateForFrenchCursive, **kwargs) class TexFontTemplateManual(Scene): """An example scene that uses a manually defined TexTemplate() object to create LaTeX output in French Cursive font """ def construct(self): self.add(Tex("Tex Font Example").to_edge(UL)) self.play(Create(FrenchCursive("$f: A \\longrightarrow B$").shift(UP))) self.play(Create(FrenchCursive("Behold! We can write math in French Cursive"))) self.wait(1) self.play( Create( Tex( "See more font templates at \\\\ http://jf.burnol.free.fr/showcase.html", ).shift(2 * DOWN), ), ) self.wait(2) # Example 2, using a Template from the collection class TexFontTemplateLibrary(Scene): """An example scene that uses TexTemplate objects from the TexFontTemplates collection to create sample LaTeX output in every font that will compile on the local system. Please Note: Many of the in the TexFontTemplates collection require that specific fonts are installed on your local machine. For example, choosing the template TexFontTemplates.comic_sans will not compile if the Comic Sans Microsoft font is not installed. This scene will only render those Templates that do not cause a TeX compilation error on your system. Furthermore, some of the ones that do render, may still render incorrectly. This is beyond the scope of manim. Feel free to experiment. """ def construct(self): def write_one_line(template): x = Tex(template.description, tex_template=template).shift(UP) self.play(Create(x)) self.wait(1) self.play(FadeOut(x)) examples = [ TexFontTemplates.american_typewriter, # "American Typewriter" TexFontTemplates.antykwa, # "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)" TexFontTemplates.apple_chancery, # "Apple Chancery" TexFontTemplates.auriocus_kalligraphicus, # "Auriocus Kalligraphicus (Symbol Greek)" TexFontTemplates.baskervald_adf_fourier, # "Baskervald ADF with Fourier" TexFontTemplates.baskervillit, # "Baskerville (Italic)" TexFontTemplates.biolinum, # "Biolinum" TexFontTemplates.brushscriptx, #
|
x = Tex(template.description, tex_template=template).shift(UP) self.play(Create(x)) self.wait(1) self.play(FadeOut(x)) examples = [ TexFontTemplates.american_typewriter, # "American Typewriter" TexFontTemplates.antykwa, # "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)" TexFontTemplates.apple_chancery, # "Apple Chancery" TexFontTemplates.auriocus_kalligraphicus, # "Auriocus Kalligraphicus (Symbol Greek)" TexFontTemplates.baskervald_adf_fourier, # "Baskervald ADF with Fourier" TexFontTemplates.baskervillit, # "Baskerville (Italic)" TexFontTemplates.biolinum, # "Biolinum" TexFontTemplates.brushscriptx, # "BrushScriptX-Italic (PX math and Greek)" TexFontTemplates.chalkboard_se, # "Chalkboard SE" TexFontTemplates.chalkduster, # "Chalkduster" TexFontTemplates.comfortaa, # "Comfortaa" TexFontTemplates.comic_sans, # "Comic Sans MS" TexFontTemplates.droid_sans, # "Droid Sans" TexFontTemplates.droid_sans_it, # "Droid Sans (Italic)" TexFontTemplates.droid_serif, # "Droid Serif" TexFontTemplates.droid_serif_px_it, # "Droid Serif (PX math symbols) (Italic)" TexFontTemplates.ecf_augie, # "ECF Augie (Euler Greek)" TexFontTemplates.ecf_jd, # "ECF JD (with TX fonts)" TexFontTemplates.ecf_skeetch, # "ECF Skeetch (CM Greek)" TexFontTemplates.ecf_tall_paul, # "ECF Tall Paul (with Symbol font)" TexFontTemplates.ecf_webster, # "ECF Webster (with TX fonts)" TexFontTemplates.electrum_adf, # "Electrum ADF (CM Greek)" TexFontTemplates.epigrafica, # Epigrafica TexFontTemplates.fourier_utopia, # "Fourier Utopia (Fourier upright Greek)" TexFontTemplates.french_cursive, # "French Cursive (Euler Greek)" TexFontTemplates.gfs_bodoni, # "GFS Bodoni" TexFontTemplates.gfs_didot, # "GFS Didot (Italic)" TexFontTemplates.gfs_neoHellenic, # "GFS NeoHellenic" TexFontTemplates.gnu_freesans_tx, # "GNU FreeSerif (and TX fonts symbols)" TexFontTemplates.gnu_freeserif_freesans, # "GNU FreeSerif and FreeSans" TexFontTemplates.helvetica_fourier_it, # "Helvetica with Fourier (Italic)" TexFontTemplates.latin_modern_tw_it, # "Latin Modern Typewriter Proportional (CM Greek) (Italic)" TexFontTemplates.latin_modern_tw, # "Latin Modern Typewriter Proportional" TexFontTemplates.libertine, # "Libertine" TexFontTemplates.libris_adf_fourier, # "Libris ADF with Fourier" TexFontTemplates.minion_pro_myriad_pro, # "Minion Pro and Myriad Pro (and TX fonts symbols)" TexFontTemplates.minion_pro_tx, # "Minion Pro (and TX fonts symbols)" TexFontTemplates.new_century_schoolbook, # "New Century Schoolbook (Symbol Greek)" TexFontTemplates.new_century_schoolbook_px, # "New Century Schoolbook (Symbol Greek, PX math symbols)" TexFontTemplates.noteworthy_light, # "Noteworthy Light" TexFontTemplates.palatino, # "Palatino (Symbol Greek)" TexFontTemplates.papyrus, # "Papyrus" TexFontTemplates.romande_adf_fourier_it, # "Romande ADF with Fourier (Italic)" TexFontTemplates.slitex, # "SliTeX (Euler Greek)" TexFontTemplates.times_fourier_it, # "Times with Fourier (Italic)" TexFontTemplates.urw_avant_garde, # "URW Avant Garde (Symbol Greek)" TexFontTemplates.urw_zapf_chancery, # "URW Zapf Chancery (CM Greek)" TexFontTemplates.venturis_adf_fourier_it, # "Venturis ADF with Fourier (Italic)" TexFontTemplates.verdana_it, # "Verdana (Italic)" TexFontTemplates.vollkorn_fourier_it, # "Vollkorn with Fourier (Italic)" TexFontTemplates.vollkorn, # "Vollkorn (TX fonts for Greek and math symbols)" TexFontTemplates.zapf_chancery, # "Zapf Chancery" ] self.add(Tex("Tex Font Template Example").to_edge(UL)) for font in examples: try: write_one_line(font) except Exception: print("FAILURE on ", font.description, " - skipping.") self.play( Create( Tex( "See more font templates at \\\\ http://jf.burnol.free.fr/showcase.html", ).shift(2 * DOWN), ), ) self.wait(2) ================================================ FILE: example_scenes/basic.py ================================================ #!/usr/bin/env python from manim import * # To watch one of these scenes, run the following: # python --quality m manim -p example_scenes.py SquareToCircle # # Use the flag --quality l for a faster rendering at a lower quality. # Use -s to skip to the end and just save the final frame # Use the -p to have preview of the animation (or image, if -s was # used) pop up once done. # Use -n <number> to skip ahead to the nth animation of a scene. # Use -r <number> to specify a resolution (for example, -r 1920,1080 # for a 1920x1080 video) class OpeningManim(Scene): def construct(self): title = Tex(r"This is some \LaTeX") basel = MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}") VGroup(title, basel).arrange(DOWN) self.play( Write(title), FadeIn(basel, shift=DOWN), ) self.wait() transform_title = Tex("That was a transform") transform_title.to_corner(UP + LEFT) self.play( Transform(title, transform_title), LaggedStart(*(FadeOut(obj, shift=DOWN) for obj
|
resolution (for example, -r 1920,1080 # for a 1920x1080 video) class OpeningManim(Scene): def construct(self): title = Tex(r"This is some \LaTeX") basel = MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}") VGroup(title, basel).arrange(DOWN) self.play( Write(title), FadeIn(basel, shift=DOWN), ) self.wait() transform_title = Tex("That was a transform") transform_title.to_corner(UP + LEFT) self.play( Transform(title, transform_title), LaggedStart(*(FadeOut(obj, shift=DOWN) for obj in basel)), ) self.wait() grid = NumberPlane() grid_title = Tex("This is a grid", font_size=72) grid_title.move_to(transform_title) self.add(grid, grid_title) # Make sure title is on top of grid self.play( FadeOut(title), FadeIn(grid_title, shift=UP), Create(grid, run_time=3, lag_ratio=0.1), ) self.wait() grid_transform_title = Tex( r"That was a non-linear function \\ applied to the grid", ) grid_transform_title.move_to(grid_title, UL) grid.prepare_for_nonlinear_transform() self.play( grid.animate.apply_function( lambda p: p + np.array( [ np.sin(p[1]), np.sin(p[0]), 0, ], ), ), run_time=3, ) self.wait() self.play(Transform(grid_title, grid_transform_title)) self.wait() class SquareToCircle(Scene): def construct(self): circle = Circle() square = Square() square.flip(RIGHT) square.rotate(-3 * TAU / 8) circle.set_fill(PINK, opacity=0.5) self.play(Create(square)) self.play(Transform(square, circle)) self.play(FadeOut(square)) class WarpSquare(Scene): def construct(self): square = Square() self.play( ApplyPointwiseFunction( lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square, ), ) self.wait() class WriteStuff(Scene): def construct(self): example_text = Tex("This is a some text", tex_to_color_map={"text": YELLOW}) example_tex = MathTex( "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}", ) group = VGroup(example_text, example_tex) group.arrange(DOWN) group.width = config["frame_width"] - 2 * LARGE_BUFF self.play(Write(example_text)) self.play(Write(example_tex)) self.wait() class UpdatersExample(Scene): def construct(self): decimal = DecimalNumber( 0, show_ellipsis=True, num_decimal_places=3, include_sign=True, ) square = Square().to_edge(UP) decimal.add_updater(lambda d: d.next_to(square, RIGHT)) decimal.add_updater(lambda d: d.set_value(square.get_center()[1])) self.add(square, decimal) self.play( square.animate.to_edge(DOWN), rate_func=there_and_back, run_time=5, ) self.wait() class SpiralInExample(Scene): def construct(self): logo_green = "#81b29a" logo_blue = "#454866" logo_red = "#e07a5f" font_color = "#ece6e2" pi = MathTex(r"\pi").scale(7).set_color(font_color) pi.shift(2.25 * LEFT + 1.5 * UP) circle = Circle(color=logo_green, fill_opacity=0.7, stroke_width=0).shift(LEFT) square = Square(color=logo_blue, fill_opacity=0.8, stroke_width=0).shift(UP) triangle = Triangle(color=logo_red, fill_opacity=0.9, stroke_width=0).shift( RIGHT ) pentagon = Polygon( *[ [np.cos(2 * np.pi / 5 * i), np.sin(2 * np.pi / 5 * i), 0] for i in range(5) ], color=PURPLE_B, fill_opacity=1, stroke_width=0, ).shift(UP + 2 * RIGHT) shapes = VGroup(triangle, square, circle, pentagon, pi) self.play(SpiralIn(shapes, fade_in_fraction=0.9)) self.wait() self.play(FadeOut(shapes)) Triangle.set_default(stroke_width=20) class LineJoints(Scene): def construct(self): t1 = Triangle() t2 = Triangle(joint_type=LineJointType.ROUND) t3 = Triangle(joint_type=LineJointType.BEVEL) grp = VGroup(t1, t2, t3).arrange(RIGHT) grp.set(width=config.frame_width - 1) self.add(grp) # See many more examples at https://docs.manim.community/en/stable/examples.html ================================================ FILE: example_scenes/custom_template.tex ================================================ \documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage[f]{esvect} \begin{document} YourTextHere \end{document} ================================================ FILE: example_scenes/customtex.py ================================================ from manim import * class TexTemplateFromCLI(Scene): """This scene uses a custom TexTemplate file. The path of the TexTemplate _must_ be passed with the command line argument `--tex_template <path to template>`. For this scene, you can use the custom_template.tex file next to it. This scene will fail to render if a tex_template.tex that doesn't import esvect is passed, and will throw a LaTeX error in that case. """ def construct(self): text = MathTex(r"\vv{vb}") self.play(Write(text)) self.wait(1) class InCodeTexTemplate(Scene): """This example scene demonstrates how to modify the tex template for a particular scene from the code for the scene itself. """ def construct(self): # Create a new template myTemplate = TexTemplate() # Add packages to the template myTemplate.add_to_preamble(r"\usepackage{esvect}") # Set the compiler and output format (default: latex and .dvi) # possible tex compilers: "latex", "pdflatex", "xelatex", "lualatex", "luatex" # possible output
|
particular scene from the code for the scene itself. """ def construct(self): # Create a new template myTemplate = TexTemplate() # Add packages to the template myTemplate.add_to_preamble(r"\usepackage{esvect}") # Set the compiler and output format (default: latex and .dvi) # possible tex compilers: "latex", "pdflatex", "xelatex", "lualatex", "luatex" # possible output formats: ".dvi", ".pdf", and ".xdv" myTemplate.tex_compiler = "latex" myTemplate.output_format = ".dvi" # To use this template in a Tex() or MathTex() object # use the keyword argument tex_template text = MathTex(r"\vv{vb}", tex_template=myTemplate) self.play(Write(text)) self.wait(1) ================================================ FILE: example_scenes/manim.cfg ================================================ #This is some custom configuration just as an example [logger] logging_keyword = magenta logging_level_notset = dim logging_level_debug = yellow logging_level_info = dim green logging_level_warning = dim red logging_level_error = red logging_level_critical = red log_level = log_time = dim yellow log_message = green log_path = dim ================================================ FILE: example_scenes/manim_jupyter_example.ipynb ================================================ # Jupyter notebook converted to Python script. from manim import * %%manim -v WARNING --disable_caching -ql -s Example1 class Example1(Scene): def construct(self): self.add(Circle()) %%manim -v WARNING --disable_caching -qm HelloManim # set the maximum width for video outputs to a predefined value config.media_width = "20vw" # embed video config.media_embed = True class HelloManim(Scene): def construct(self): self.camera.background_color = "#ece6e2" banner_large = ManimBanner(dark_theme=False).scale(0.7) self.play(banner_large.create()) self.play(banner_large.expand()) ================================================ FILE: example_scenes/opengl.py ================================================ from pathlib import Path import manim.utils.opengl as opengl from manim import * from manim.opengl import * # Copied from https://3b1b.github.io/manim/getting_started/example_scenes.html#surfaceexample. # Lines that do not yet work with the Community Version are commented. def get_plane_mesh(context): shader = Shader(context, name="vertex_colors") attributes = np.zeros( 18, dtype=[ ("in_vert", np.float32, (4,)), ("in_color", np.float32, (4,)), ], ) attributes["in_vert"] = np.array( [ # xy plane [-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [-1, -1, 0, 1], [1, -1, 0, 1], [1, 1, 0, 1], # yz plane [0, -1, -1, 1], [0, -1, 1, 1], [0, 1, 1, 1], [0, -1, -1, 1], [0, 1, -1, 1], [0, 1, 1, 1], # xz plane [-1, 0, -1, 1], [-1, 0, 1, 1], [1, 0, 1, 1], [-1, 0, -1, 1], [1, 0, -1, 1], [1, 0, 1, 1], ], ) attributes["in_color"] = np.array( [ # xy plane [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], # yz plane [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], # xz plane [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], ], ) return Mesh(shader, attributes) class TextTest(Scene): def construct(self): import string text = Text(string.ascii_lowercase, stroke_width=4, stroke_color=BLUE).scale(2) text2 = ( Text(string.ascii_uppercase, stroke_width=4, stroke_color=BLUE) .scale(2) .next_to(text, DOWN) ) # self.add(text, text2) self.play(Write(text)) self.play(Write(text2)) self.interactive_embed() class GuiTest(Scene): def construct(self): mesh = get_plane_mesh(self.renderer.context) # mesh.attributes["in_vert"][:, 0] self.add(mesh) def update_mesh(mesh, dt): mesh.model_matrix = np.matmul( opengl.rotation_matrix(z=dt), mesh.model_matrix, ) mesh.add_updater(update_mesh) self.interactive_embed() class GuiTest2(Scene): def construct(self): mesh = get_plane_mesh(self.renderer.context) mesh.attributes["in_vert"][:, 0] -= 2 self.add(mesh) mesh2 = get_plane_mesh(self.renderer.context) mesh2.attributes["in_vert"][:, 0] += 2
|
.next_to(text, DOWN) ) # self.add(text, text2) self.play(Write(text)) self.play(Write(text2)) self.interactive_embed() class GuiTest(Scene): def construct(self): mesh = get_plane_mesh(self.renderer.context) # mesh.attributes["in_vert"][:, 0] self.add(mesh) def update_mesh(mesh, dt): mesh.model_matrix = np.matmul( opengl.rotation_matrix(z=dt), mesh.model_matrix, ) mesh.add_updater(update_mesh) self.interactive_embed() class GuiTest2(Scene): def construct(self): mesh = get_plane_mesh(self.renderer.context) mesh.attributes["in_vert"][:, 0] -= 2 self.add(mesh) mesh2 = get_plane_mesh(self.renderer.context) mesh2.attributes["in_vert"][:, 0] += 2 self.add(mesh2) def callback(sender, data): mesh2.attributes["in_color"][:, 3] = dpg.get_value(sender) self.widgets.append( { "name": "mesh2 opacity", "widget": "slider_float", "callback": callback, "min_value": 0, "max_value": 1, "default_value": 1, }, ) self.interactive_embed() class ThreeDMobjectTest(Scene): def construct(self): # config["background_color"] = "#333333" s = Square(fill_opacity=0.5).shift(2 * RIGHT) self.add(s) sp = Sphere().shift(2 * LEFT) self.add(sp) mesh = get_plane_mesh(self.renderer.context) self.add(mesh) def update_mesh(mesh, dt): mesh.model_matrix = np.matmul( opengl.rotation_matrix(z=dt), mesh.model_matrix, ) mesh.add_updater(update_mesh) self.interactive_embed() class NamedFullScreenQuad(Scene): def construct(self): surface = FullScreenQuad(self.renderer.context, fragment_shader_name="design_3") surface.shader.set_uniform( "u_resolution", (config["pixel_width"], config["pixel_height"], 0.0), ) surface.shader.set_uniform("u_time", 0) self.add(surface) t = 0 def update_surface(surface, dt): nonlocal t t += dt surface.shader.set_uniform("u_time", t / 4) surface.add_updater(update_surface) # self.wait() self.interactive_embed() class InlineFullScreenQuad(Scene): def construct(self): surface = FullScreenQuad( self.renderer.context, """ #version 330 #define TWO_PI 6.28318530718 uniform vec2 u_resolution; uniform float u_time; out vec4 frag_color; // Function from Iñigo Quiles // https://www.shadertoy.com/view/MsS3Wc vec3 hsb2rgb( in vec3 c ){ vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0), 6.0)-3.0)-1.0, 0.0, 1.0 ); rgb = rgb*rgb*(3.0-2.0*rgb); return c.z * mix( vec3(1.0), rgb, c.y); } void main(){ vec2 st = gl_FragCoord.xy/u_resolution; vec3 color = vec3(0.0); // Use polar coordinates instead of cartesian vec2 toCenter = vec2(0.5)-st; float angle = atan(toCenter.y,toCenter.x); angle += u_time; float radius = length(toCenter)*2.0; // Map the angle (-PI to PI) to the Hue (from 0 to 1) // and the Saturation to the radius color = hsb2rgb(vec3((angle/TWO_PI)+0.5,radius,1.0)); frag_color = vec4(color,1.0); } """, ) surface.shader.set_uniform( "u_resolution", (config["pixel_width"], config["pixel_height"]), ) shader_time = 0 def update_surface(surface): nonlocal shader_time surface.shader.set_uniform("u_time", shader_time) shader_time += 1 / 60.0 surface.add_updater(update_surface) self.add(surface) # self.wait(5) self.interactive_embed() class SimpleInlineFullScreenQuad(Scene): def construct(self): surface = FullScreenQuad( self.renderer.context, """ #version 330 uniform float v_red; uniform float v_green; uniform float v_blue; out vec4 frag_color; void main() { frag_color = vec4(v_red, v_green, v_blue, 1); } """, ) surface.shader.set_uniform("v_red", 0) surface.shader.set_uniform("v_green", 0) surface.shader.set_uniform("v_blue", 0) increase = True val = 0.5 surface.shader.set_uniform("v_red", val) surface.shader.set_uniform("v_green", val) surface.shader.set_uniform("v_blue", val) def update_surface(mesh, dt): nonlocal increase nonlocal val if increase: val += dt else: val -= dt if val >= 1: increase = False elif val <= 0: increase = True surface.shader.set_uniform("v_red", val) surface.shader.set_uniform("v_green", val) surface.shader.set_uniform("v_blue", val) surface.add_updater(update_surface) self.add(surface) self.wait(5) class InlineShaderExample(Scene): def construct(self): config["background_color"] = "#333333" c = Circle(fill_opacity=0.7).shift(UL) self.add(c) shader = Shader( self.renderer.context, source={ "vertex_shader": """ #version 330 in vec4 in_vert; in vec4 in_color; out vec4 v_color; uniform mat4 u_model_view_matrix; uniform mat4 u_projection_matrix; void main() { v_color = in_color; vec4 camera_space_vertex = u_model_view_matrix * in_vert; vec4 clip_space_vertex = u_projection_matrix * camera_space_vertex; gl_Position = clip_space_vertex; } """, "fragment_shader": """ #version 330 in vec4 v_color; out vec4 frag_color; void main() { frag_color = v_color; } """, }, ) shader.set_uniform("u_model_view_matrix", opengl.view_matrix()) shader.set_uniform( "u_projection_matrix", opengl.orthographic_projection_matrix(), ) attributes = np.zeros( 6, dtype=[ ("in_vert", np.float32, (4,)), ("in_color", np.float32, (4,)), ], ) attributes["in_vert"] = np.array( [ [-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [-1, -1, 0, 1], [1, -1, 0,
|
{ frag_color = v_color; } """, }, ) shader.set_uniform("u_model_view_matrix", opengl.view_matrix()) shader.set_uniform( "u_projection_matrix", opengl.orthographic_projection_matrix(), ) attributes = np.zeros( 6, dtype=[ ("in_vert", np.float32, (4,)), ("in_color", np.float32, (4,)), ], ) attributes["in_vert"] = np.array( [ [-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [-1, -1, 0, 1], [1, -1, 0, 1], [1, 1, 0, 1], ], ) attributes["in_color"] = np.array( [ [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], ], ) mesh = Mesh(shader, attributes) self.add(mesh) self.wait(5) # self.embed_2() class NamedShaderExample(Scene): def construct(self): shader = Shader(self.renderer.context, "manim_coords") shader.set_uniform("u_color", (0.0, 1.0, 0.0, 1.0)) view_matrix = self.camera.formatted_view_matrix shader.set_uniform("u_model_view_matrix", view_matrix) shader.set_uniform( "u_projection_matrix", opengl.perspective_projection_matrix(), ) attributes = np.zeros( 6, dtype=[ ("in_vert", np.float32, (4,)), ], ) attributes["in_vert"] = np.array( [ [-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [-1, -1, 0, 1], [1, -1, 0, 1], [1, 1, 0, 1], ], ) mesh = Mesh(shader, attributes) self.add(mesh) self.wait(5) 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(Create(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 SurfaceExample(Scene): 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(major_radius=1, minor_radius=1) torus2 = Torus(major_radius=3, minor_radius=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 script_location = Path(__file__).resolve().parent day_texture = ( script_location / "assets" / "1280px-Whole_world_-_land_and_oceans.jpg" ) night_texture = script_location
|
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 script_location = Path(__file__).resolve().parent day_texture = ( script_location / "assets" / "1280px-Whole_world_-_land_and_oceans.jpg" ) night_texture = script_location / "assets" / "1280px-The_earth_at_night.jpg" surfaces = [ OpenGLTexturedSurface(surface, day_texture, night_texture) for surface in [sphere, torus1, torus2] ] for mob in surfaces: mob.shift(IN) mob.mesh = OpenGLSurfaceMesh(mob) mob.mesh.set_stroke(BLUE, 1, opacity=0.5) # Set perspective frame = self.renderer.camera frame.set_euler_angles( theta=-30 * DEGREES, phi=70 * DEGREES, ) surface = surfaces[0] self.play( FadeIn(surface), Create(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 frame.animate.increment_phi(-10 * DEGREES), frame.animate.increment_theta(-20 * DEGREES), run_time=3, ) # Add ambient rotation 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 s") # drag_text.move_to(light_text) # drag_text.fix_in_frame() ================================================ FILE: manim/__init__.py ================================================ #!/usr/bin/env python from __future__ import annotations from importlib.metadata import PackageNotFoundError, version # Use installed distribution version if available; otherwise fall back to a # sensible default so that importing from a source checkout works without an # editable install (pip install -e .). try: __version__ = version(__name__) except PackageNotFoundError: # Package is not installed; provide a fallback version string. __version__ = "0.0.0+unknown" # isort: off # Importing the config module should be the first thing we do, since other # modules depend on the global config dict for initialization. from ._config import * # many scripts depend on this -> has to be loaded first from .utils.commands import * # isort: on import numpy as np from .animation.animation import * from .animation.changing import * from .animation.composition import * from .animation.creation import * from .animation.fading import * from .animation.growing import * from .animation.indication import * from .animation.movement import * from .animation.numbers import * from .animation.rotation import * from .animation.specialized import * from .animation.speedmodifier import * from .animation.transform import * from .animation.transform_matching_parts import * from .animation.updaters.mobject_update_utils import * from .animation.updaters.update import * from .camera.camera import * from .camera.mapping_camera import * from .camera.moving_camera import * from .camera.multi_camera import * from .camera.three_d_camera import * from .constants import * from .mobject.frame import * from .mobject.geometry.arc import * from .mobject.geometry.boolean_ops import * from .mobject.geometry.labeled import * from .mobject.geometry.line import * from .mobject.geometry.polygram import * from .mobject.geometry.shape_matchers import * from .mobject.geometry.tips import * from .mobject.graph import * from .mobject.graphing.coordinate_systems import * from .mobject.graphing.functions import * from .mobject.graphing.number_line import * from .mobject.graphing.probability import * from .mobject.graphing.scale import * from .mobject.logo import * from .mobject.matrix import * from .mobject.mobject import * from .mobject.opengl.dot_cloud import * from .mobject.opengl.opengl_point_cloud_mobject import * from .mobject.svg.brace import * from .mobject.svg.svg_mobject import * from .mobject.table import *
|
import * from .mobject.graphing.functions import * from .mobject.graphing.number_line import * from .mobject.graphing.probability import * from .mobject.graphing.scale import * from .mobject.logo import * from .mobject.matrix import * from .mobject.mobject import * from .mobject.opengl.dot_cloud import * from .mobject.opengl.opengl_point_cloud_mobject import * from .mobject.svg.brace import * from .mobject.svg.svg_mobject import * from .mobject.table import * from .mobject.text.code_mobject import * from .mobject.text.numbers import * from .mobject.text.tex_mobject import * from .mobject.text.text_mobject import * from .mobject.three_d.polyhedra import * from .mobject.three_d.three_d_utils import * from .mobject.three_d.three_dimensions import * from .mobject.types.image_mobject import * from .mobject.types.point_cloud_mobject import * from .mobject.types.vectorized_mobject import * from .mobject.value_tracker import * from .mobject.vector_field import * from .renderer.cairo_renderer import * from .scene.moving_camera_scene import * from .scene.scene import * from .scene.scene_file_writer import * from .scene.section import * from .scene.three_d_scene import * from .scene.vector_space_scene import * from .scene.zoomed_scene import * from .utils import color, rate_functions, unit from .utils.bezier import * from .utils.color import * from .utils.config_ops import * from .utils.debug import * from .utils.file_ops import * from .utils.images import * from .utils.iterables import * from .utils.paths import * from .utils.rate_functions import * from .utils.simple_functions import * from .utils.sounds import * from .utils.space_ops import * from .utils.tex import * from .utils.tex_templates import * try: from IPython import get_ipython from .utils.ipython_magic import ManimMagic except ImportError: pass else: ipy = get_ipython() if ipy is not None: ipy.register_magics(ManimMagic) from .plugins import * ================================================ FILE: manim/__main__.py ================================================ from __future__ import annotations import click import cloup from manim import __version__ from manim._config import cli_ctx_settings, console from manim.cli.cfg.group import cfg from manim.cli.checkhealth.commands import checkhealth from manim.cli.default_group import DefaultGroup from manim.cli.init.commands import init from manim.cli.plugins.commands import plugins from manim.cli.render.commands import render from manim.constants import EPILOG def show_splash(ctx: click.Context, param: click.Option, value: str | None) -> None: """When giving a value by console, show an initial message with the Manim version before executing any other command: ``Manim Community vA.B.C``. Parameters ---------- ctx The Click context. param A Click option. value A string value given by console, or None. """ if value: console.print(f"Manim Community [green]v{__version__}[/green]\n") def print_version_and_exit( ctx: click.Context, param: click.Option, value: str | None ) -> None: """Same as :func:`show_splash`, but also exit when giving a value by console. Parameters ---------- ctx The Click context. param A Click option. value A string value given by console, or None. """ show_splash(ctx, param, value) if value: ctx.exit() @cloup.group( context_settings=cli_ctx_settings, cls=DefaultGroup, default="render", no_args_is_help=True, help="Animation engine for explanatory math videos.", epilog="See 'manim <command>' to read about a specific subcommand.\n\n" "Note: the subcommand 'manim render' is called if no other subcommand " "is specified. Run 'manim render --help' if you would like to know what the " f"'-ql' or '-p' flags do, for example.\n\n{EPILOG}", ) @cloup.option( "--version", is_flag=True, help="Show version and exit.", callback=print_version_and_exit, is_eager=True, expose_value=False, ) @click.option( "--show-splash/--hide-splash", is_flag=True, default=True, help="Print splash message with version information.", callback=show_splash, is_eager=True, expose_value=False, ) @cloup.pass_context def main(ctx: click.Context) -> None: """The entry point for Manim. Parameters ---------- ctx The Click context. """ pass main.add_command(checkhealth) main.add_command(cfg) main.add_command(plugins) main.add_command(init) main.add_command(render) if __name__ == "__main__": main() ================================================ FILE: manim/constants.py ================================================ """Constant definitions.""" from __future__ import annotations from enum import Enum from
|
version information.", callback=show_splash, is_eager=True, expose_value=False, ) @cloup.pass_context def main(ctx: click.Context) -> None: """The entry point for Manim. Parameters ---------- ctx The Click context. """ pass main.add_command(checkhealth) main.add_command(cfg) main.add_command(plugins) main.add_command(init) main.add_command(render) if __name__ == "__main__": main() ================================================ FILE: manim/constants.py ================================================ """Constant definitions.""" from __future__ import annotations from enum import Enum from typing import TypedDict import numpy as np from cloup import Context from PIL.Image import Resampling from manim.typing import Vector3D __all__ = [ "SCENE_NOT_FOUND_MESSAGE", "CHOOSE_NUMBER_MESSAGE", "INVALID_NUMBER_MESSAGE", "NO_SCENE_MESSAGE", "NORMAL", "ITALIC", "OBLIQUE", "BOLD", "THIN", "ULTRALIGHT", "LIGHT", "SEMILIGHT", "BOOK", "MEDIUM", "SEMIBOLD", "ULTRABOLD", "HEAVY", "ULTRAHEAVY", "RESAMPLING_ALGORITHMS", "ORIGIN", "UP", "DOWN", "RIGHT", "LEFT", "IN", "OUT", "X_AXIS", "Y_AXIS", "Z_AXIS", "UL", "UR", "DL", "DR", "START_X", "START_Y", "DEFAULT_DOT_RADIUS", "DEFAULT_SMALL_DOT_RADIUS", "DEFAULT_DASH_LENGTH", "DEFAULT_ARROW_TIP_LENGTH", "SMALL_BUFF", "MED_SMALL_BUFF", "MED_LARGE_BUFF", "LARGE_BUFF", "DEFAULT_MOBJECT_TO_EDGE_BUFFER", "DEFAULT_MOBJECT_TO_MOBJECT_BUFFER", "DEFAULT_POINTWISE_FUNCTION_RUN_TIME", "DEFAULT_WAIT_TIME", "DEFAULT_POINT_DENSITY_2D", "DEFAULT_POINT_DENSITY_1D", "DEFAULT_STROKE_WIDTH", "DEFAULT_FONT_SIZE", "SCALE_FACTOR_PER_FONT_POINT", "PI", "TAU", "DEGREES", "QUALITIES", "DEFAULT_QUALITY", "EPILOG", "CONTEXT_SETTINGS", "SHIFT_VALUE", "CTRL_VALUE", "RendererType", "LineJointType", "CapStyleType", ] # Messages SCENE_NOT_FOUND_MESSAGE = """ {} is not in the script """ CHOOSE_NUMBER_MESSAGE = """ Choose number corresponding to desired scene/arguments. (Use comma separated list for multiple entries) Choice(s): """ INVALID_NUMBER_MESSAGE = "Invalid scene numbers have been specified. Aborting." NO_SCENE_MESSAGE = """ There are no scenes inside that module """ # Pango stuff NORMAL = "NORMAL" ITALIC = "ITALIC" OBLIQUE = "OBLIQUE" BOLD = "BOLD" # Only for Pango from below THIN = "THIN" ULTRALIGHT = "ULTRALIGHT" LIGHT = "LIGHT" SEMILIGHT = "SEMILIGHT" BOOK = "BOOK" MEDIUM = "MEDIUM" SEMIBOLD = "SEMIBOLD" ULTRABOLD = "ULTRABOLD" HEAVY = "HEAVY" ULTRAHEAVY = "ULTRAHEAVY" RESAMPLING_ALGORITHMS = { "nearest": Resampling.NEAREST, "none": Resampling.NEAREST, "lanczos": Resampling.LANCZOS, "antialias": Resampling.LANCZOS, "bilinear": Resampling.BILINEAR, "linear": Resampling.BILINEAR, "bicubic": Resampling.BICUBIC, "cubic": Resampling.BICUBIC, "box": Resampling.BOX, "hamming": Resampling.HAMMING, } # Geometry: directions ORIGIN: Vector3D = np.array((0.0, 0.0, 0.0)) """The center of the coordinate system.""" UP: Vector3D = np.array((0.0, 1.0, 0.0)) """One unit step in the positive Y direction.""" DOWN: Vector3D = np.array((0.0, -1.0, 0.0)) """One unit step in the negative Y direction.""" RIGHT: Vector3D = np.array((1.0, 0.0, 0.0)) """One unit step in the positive X direction.""" LEFT: Vector3D = np.array((-1.0, 0.0, 0.0)) """One unit step in the negative X direction.""" IN: Vector3D = np.array((0.0, 0.0, -1.0)) """One unit step in the negative Z direction.""" OUT: Vector3D = np.array((0.0, 0.0, 1.0)) """One unit step in the positive Z direction.""" # Geometry: axes X_AXIS: Vector3D = np.array((1.0, 0.0, 0.0)) Y_AXIS: Vector3D = np.array((0.0, 1.0, 0.0)) Z_AXIS: Vector3D = np.array((0.0, 0.0, 1.0)) # Geometry: useful abbreviations for diagonals UL: Vector3D = UP + LEFT """One step up plus one step left.""" UR: Vector3D = UP + RIGHT """One step up plus one step right.""" DL: Vector3D = DOWN + LEFT """One step down plus one step left.""" DR: Vector3D = DOWN + RIGHT """One step down plus one step right.""" # Geometry START_X = 30 START_Y = 20 DEFAULT_DOT_RADIUS = 0.08 DEFAULT_SMALL_DOT_RADIUS = 0.04 DEFAULT_DASH_LENGTH = 0.05 DEFAULT_ARROW_TIP_LENGTH = 0.35 # Default buffers (padding) SMALL_BUFF = 0.1 MED_SMALL_BUFF = 0.25 MED_LARGE_BUFF = 0.5 LARGE_BUFF = 1 DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF # Times in seconds DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0 DEFAULT_WAIT_TIME = 1.0 # Misc DEFAULT_POINT_DENSITY_2D = 25 DEFAULT_POINT_DENSITY_1D = 10
|
0.08 DEFAULT_SMALL_DOT_RADIUS = 0.04 DEFAULT_DASH_LENGTH = 0.05 DEFAULT_ARROW_TIP_LENGTH = 0.35 # Default buffers (padding) SMALL_BUFF = 0.1 MED_SMALL_BUFF = 0.25 MED_LARGE_BUFF = 0.5 LARGE_BUFF = 1 DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF # Times in seconds DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0 DEFAULT_WAIT_TIME = 1.0 # Misc DEFAULT_POINT_DENSITY_2D = 25 DEFAULT_POINT_DENSITY_1D = 10 DEFAULT_STROKE_WIDTH = 4 DEFAULT_FONT_SIZE = 48 SCALE_FACTOR_PER_FONT_POINT = 1 / 960 # Mathematical constants PI = np.pi """The ratio of the circumference of a circle to its diameter.""" TAU = 2 * PI """The ratio of the circumference of a circle to its radius.""" DEGREES = TAU / 360 """The exchange rate between radians and degrees.""" class QualityDict(TypedDict): flag: str | None pixel_height: int pixel_width: int frame_rate: int # Video qualities QUALITIES: dict[str, QualityDict] = { "fourk_quality": { "flag": "k", "pixel_height": 2160, "pixel_width": 3840, "frame_rate": 60, }, "production_quality": { "flag": "p", "pixel_height": 1440, "pixel_width": 2560, "frame_rate": 60, }, "high_quality": { "flag": "h", "pixel_height": 1080, "pixel_width": 1920, "frame_rate": 60, }, "medium_quality": { "flag": "m", "pixel_height": 720, "pixel_width": 1280, "frame_rate": 30, }, "low_quality": { "flag": "l", "pixel_height": 480, "pixel_width": 854, "frame_rate": 15, }, "example_quality": { "flag": None, "pixel_height": 480, "pixel_width": 854, "frame_rate": 30, }, } DEFAULT_QUALITY = "high_quality" EPILOG = "Made with <3 by Manim Community developers." SHIFT_VALUE = 65505 CTRL_VALUE = 65507 CONTEXT_SETTINGS = Context.settings( align_option_groups=True, align_sections=True, show_constraints=True, ) class RendererType(Enum): """An enumeration of all renderer types that can be assigned to the ``config.renderer`` attribute. Manim's configuration allows assigning string values to the renderer setting, the values are then replaced by the corresponding enum object. In other words, you can run:: config.renderer = "opengl" and checking the renderer afterwards reveals that the attribute has assumed the value:: <RendererType.OPENGL: 'opengl'> """ CAIRO = "cairo" #: A renderer based on the cairo backend. OPENGL = "opengl" #: An OpenGL-based renderer. class LineJointType(Enum): """Collection of available line joint types. See the example below for a visual illustration of the different joint types. Examples -------- .. manim:: LineJointVariants :save_last_frame: class LineJointVariants(Scene): def construct(self): mob = VMobject(stroke_width=20, color=GREEN).set_points_as_corners([ np.array([-2, 0, 0]), np.array([0, 0, 0]), np.array([-2, 1, 0]), ]) lines = VGroup(*[mob.copy() for _ in range(len(LineJointType))]) for line, joint_type in zip(lines, LineJointType): line.joint_type = joint_type lines.arrange(RIGHT, buff=1) self.add(lines) for line in lines: label = Text(line.joint_type.name).next_to(line, DOWN) self.add(label) """ AUTO = 0 ROUND = 1 BEVEL = 2 MITER = 3 class CapStyleType(Enum): """Collection of available cap styles. See the example below for a visual illustration of the different cap styles. Examples -------- .. manim:: CapStyleVariants :save_last_frame: class CapStyleVariants(Scene): def construct(self): arcs = VGroup(*[ Arc( radius=1, start_angle=0, angle=TAU / 4, stroke_width=20, color=GREEN, cap_style=cap_style, ) for cap_style in CapStyleType ]) arcs.arrange(RIGHT, buff=1) self.add(arcs) for arc in arcs: label = Text(arc.cap_style.name, font_size=24).next_to(arc, DOWN) self.add(label) """ AUTO = 0 ROUND = 1 BUTT = 2 SQUARE = 3 ================================================ FILE: manim/data_structures.py ================================================ """Data classes and other necessary data structures for use in Manim.""" from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from types import MethodType from typing import Any @dataclass class MethodWithArgs: """Object containing a :attr:`method` which
|
1 BUTT = 2 SQUARE = 3 ================================================ FILE: manim/data_structures.py ================================================ """Data classes and other necessary data structures for use in Manim.""" from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from types import MethodType from typing import Any @dataclass class MethodWithArgs: """Object containing a :attr:`method` which is intended to be called later with the positional arguments :attr:`args` and the keyword arguments :attr:`kwargs`. Attributes ---------- method : MethodType A callable representing a method of some class. args : Iterable[Any] Positional arguments for :attr:`method`. kwargs : dict[str, Any] Keyword arguments for :attr:`method`. """ __slots__ = ["method", "args", "kwargs"] method: MethodType args: Iterable[Any] kwargs: dict[str, Any] ================================================ FILE: manim/typing.py ================================================ """Custom type definitions used in Manim. .. admonition:: Note for developers :class: important Around the source code there are multiple strings which look like this: .. code-block:: ''' [CATEGORY] <category_name> ''' All type aliases defined under those strings will be automatically classified under that category. If you need to define a new category, respect the format described above. """ from __future__ import annotations from collections.abc import Callable, Sequence from os import PathLike from typing import Union import numpy as np import numpy.typing as npt from typing_extensions import TypeAlias __all__ = [ "ManimFloat", "ManimInt", "ManimColorDType", "FloatRGB", "FloatRGBLike", "FloatRGB_Array", "FloatRGBLike_Array", "IntRGB", "IntRGBLike", "FloatRGBA", "FloatRGBALike", "FloatRGBA_Array", "FloatRGBALike_Array", "IntRGBA", "IntRGBALike", "FloatHSV", "FloatHSVLike", "FloatHSL", "FloatHSLLike", "FloatHSVA", "FloatHSVALike", "ManimColorInternal", "PointDType", "Point2D", "Point2DLike", "Point2D_Array", "Point2DLike_Array", "Point3D", "Point3DLike", "Point3D_Array", "Point3DLike_Array", "PointND", "PointNDLike", "PointND_Array", "PointNDLike_Array", "Vector2D", "Vector2DLike", "Vector2D_Array", "Vector2DLike_Array", "Vector3D", "Vector3DLike", "Vector3D_Array", "Vector3DLike_Array", "VectorND", "VectorNDLike", "VectorND_Array", "VectorNDLike_Array", "RowVector", "ColVector", "MatrixMN", "Zeros", "QuadraticBezierPoints", "QuadraticBezierPointsLike", "QuadraticBezierPoints_Array", "QuadraticBezierPointsLike_Array", "QuadraticBezierPath", "QuadraticBezierPathLike", "QuadraticSpline", "QuadraticSplineLike", "CubicBezierPoints", "CubicBezierPointsLike", "CubicBezierPoints_Array", "CubicBezierPointsLike_Array", "CubicBezierPath", "CubicBezierPathLike", "CubicSpline", "CubicSplineLike", "BezierPoints", "BezierPointsLike", "BezierPoints_Array", "BezierPointsLike_Array", "BezierPath", "BezierPathLike", "Spline", "SplineLike", "FlatBezierPoints", "FunctionOverride", "PathFuncType", "MappingFunction", "MultiMappingFunction", "PixelArray", "GrayscalePixelArray", "RGBPixelArray", "RGBAPixelArray", "StrPath", "StrOrBytesPath", ] """ [CATEGORY] Primitive data types """ ManimFloat: TypeAlias = np.float64 """A double-precision floating-point value (64 bits, or 8 bytes), according to the IEEE 754 standard. """ ManimInt: TypeAlias = np.int64 r"""A long integer (64 bits, or 8 bytes). It can take values between :math:`-2^{63}` and :math:`+2^{63} - 1`, which expressed in base 10 is a range between around :math:`-9.223 \cdot 10^{18}` and :math:`+9.223 \cdot 10^{18}`. """ """ [CATEGORY] Color types """ ManimColorDType: TypeAlias = ManimFloat """Data type used in :class:`~.ManimColorInternal`: a double-precision float between 0 and 1. """ FloatRGB: TypeAlias = npt.NDArray[ManimColorDType] """``shape: (3,)`` A :class:`numpy.ndarray` of 3 floats between 0 and 1, representing a color in RGB format. Its components describe, in order, the intensity of Red, Green, and Blue in the represented color. """ FloatRGBLike: TypeAlias = Union[FloatRGB, tuple[float, float, float]] """``shape: (3,)`` An array of 3 floats between 0 and 1, representing a color in RGB format. This represents anything which can be converted to a :class:`.FloatRGB` NumPy array. """ FloatRGB_Array: TypeAlias = npt.NDArray[ManimColorDType] """``shape: (M, 3)`` A :class:`numpy.ndarray` of many rows of 3 floats representing RGB colors. """ FloatRGBLike_Array: TypeAlias = Union[FloatRGB_Array, Sequence[FloatRGBLike]] """``shape: (M, 3)`` An array of many rows of 3 floats representing RGB colors. This represents anything which can be converted to a :class:`.FloatRGB_Array`
|
array. """ FloatRGB_Array: TypeAlias = npt.NDArray[ManimColorDType] """``shape: (M, 3)`` A :class:`numpy.ndarray` of many rows of 3 floats representing RGB colors. """ FloatRGBLike_Array: TypeAlias = Union[FloatRGB_Array, Sequence[FloatRGBLike]] """``shape: (M, 3)`` An array of many rows of 3 floats representing RGB colors. This represents anything which can be converted to a :class:`.FloatRGB_Array` NumPy array. """ IntRGB: TypeAlias = npt.NDArray[ManimInt] """``shape: (3,)`` A :class:`numpy.ndarray` of 3 integers between 0 and 255, representing a color in RGB format. Its components describe, in order, the intensity of Red, Green, and Blue in the represented color. """ IntRGBLike: TypeAlias = Union[IntRGB, tuple[int, int, int]] """``shape: (3,)`` An array of 3 integers between 0 and 255, representing a color in RGB format. This represents anything which can be converted to an :class:`.IntRGB` NumPy array. """ FloatRGBA: TypeAlias = npt.NDArray[ManimColorDType] """``shape: (4,)`` A :class:`numpy.ndarray` of 4 floats between 0 and 1, representing a color in RGBA format. Its components describe, in order, the intensity of Red, Green, Blue and Alpha (opacity) in the represented color. """ FloatRGBALike: TypeAlias = Union[FloatRGBA, tuple[float, float, float, float]] """``shape: (4,)`` An array of 4 floats between 0 and 1, representing a color in RGBA format. This represents anything which can be converted to a :class:`.FloatRGBA` NumPy array. """ FloatRGBA_Array: TypeAlias = npt.NDArray[ManimColorDType] """``shape: (M, 4)`` A :class:`numpy.ndarray` of many rows of 4 floats representing RGBA colors. """ FloatRGBALike_Array: TypeAlias = Union[FloatRGBA_Array, Sequence[FloatRGBALike]] """``shape: (M, 4)`` An array of many rows of 4 floats representing RGBA colors. This represents anything which can be converted to a :class:`.FloatRGBA_Array` NumPy array. """ IntRGBA: TypeAlias = npt.NDArray[ManimInt] """``shape: (4,)`` A :class:`numpy.ndarray` of 4 integers between 0 and 255, representing a color in RGBA format. Its components describe, in order, the intensity of Red, Green, Blue and Alpha (opacity) in the represented color. """ IntRGBALike: TypeAlias = Union[IntRGBA, tuple[int, int, int, int]] """``shape: (4,)`` An array of 4 integers between 0 and 255, representing a color in RGBA format. This represents anything which can be converted to an :class:`.IntRGBA` NumPy array. """ FloatHSV: TypeAlias = FloatRGB """``shape: (3,)`` A :class:`numpy.ndarray` of 3 floats between 0 and 1, representing a color in HSV (or HSB) format. Its components describe, in order, the Hue, Saturation and Value (or Brightness) in the represented color. """ FloatHSVLike: TypeAlias = FloatRGBLike """``shape: (3,)`` An array of 3 floats between 0 and 1, representing a color in HSV (or HSB) format. This represents anything which can be converted to a :class:`.FloatHSV` NumPy array. """ FloatHSVA: TypeAlias = FloatRGBA """``shape: (4,)`` A :class:`numpy.ndarray` of 4 floats between 0 and 1, representing a color in HSVA (or HSBA) format. Its components describe, in order, the Hue, Saturation and Value (or Brightness) in the represented color. """ FloatHSVALike: TypeAlias = FloatRGBALike """``shape: (4,)`` An array of 4 floats between 0 and 1, representing a color in HSVA (or HSBA) format. This represents anything which can be converted to a :class:`.FloatHSVA` NumPy array. """ FloatHSL: TypeAlias = FloatRGB """``shape: (3,)`` A :class:`numpy.ndarray` of 3 floats between 0
|
""" FloatHSVALike: TypeAlias = FloatRGBALike """``shape: (4,)`` An array of 4 floats between 0 and 1, representing a color in HSVA (or HSBA) format. This represents anything which can be converted to a :class:`.FloatHSVA` NumPy array. """ FloatHSL: TypeAlias = FloatRGB """``shape: (3,)`` A :class:`numpy.ndarray` of 3 floats between 0 and 1, representing a color in HSL format. Its components describe, in order, the Hue, Saturation and Lightness in the represented color. """ FloatHSLLike: TypeAlias = FloatRGBLike """``shape: (3,)`` An array of 3 floats between 0 and 1, representing a color in HSL format. This represents anything which can be converted to a :class:`.FloatHSL` NumPy array. """ ManimColorInternal: TypeAlias = FloatRGBA """``shape: (4,)`` Internal color representation used by :class:`~.ManimColor`, following the RGBA format. It is a :class:`numpy.ndarray` consisting of 4 floats between 0 and 1, describing respectively the intensities of Red, Green, Blue and Alpha (opacity) in the represented color. """ """ [CATEGORY] Point types """ PointDType: TypeAlias = ManimFloat """Default type for arrays representing points: a double-precision floating point value. """ Point2D: TypeAlias = npt.NDArray[PointDType] """``shape: (2,)`` A NumPy array representing a 2-dimensional point: ``[float, float]``. """ Point2DLike: TypeAlias = Union[Point2D, tuple[float, float]] """``shape: (2,)`` A 2-dimensional point: ``[float, float]``. This represents anything which can be converted to a :class:`.Point2D` NumPy array. """ Point2D_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (M, 2)`` A NumPy array representing a sequence of :class:`.Point2D` objects: ``[[float, float], ...]``. """ Point2DLike_Array: TypeAlias = Union[Point2D_Array, Sequence[Point2DLike]] """``shape: (M, 2)`` An array of :class:`.Point2DLike` objects: ``[[float, float], ...]``. This represents anything which can be converted to a :class:`.Point2D_Array` NumPy array. Please refer to the documentation of the function you are using for further type information. """ Point3D: TypeAlias = npt.NDArray[PointDType] """``shape: (3,)`` A NumPy array representing a 3-dimensional point: ``[float, float, float]``. """ Point3DLike: TypeAlias = Union[Point3D, tuple[float, float, float]] """``shape: (3,)`` A 3-dimensional point: ``[float, float, float]``. This represents anything which can be converted to a :class:`.Point3D` NumPy array. """ Point3D_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (M, 3)`` A NumPy array representing a sequence of :class:`.Point3D` objects: ``[[float, float, float], ...]``. """ Point3DLike_Array: TypeAlias = Union[Point3D_Array, Sequence[Point3DLike]] """``shape: (M, 3)`` An array of :class:`.Point3DLike` objects: ``[[float, float, float], ...]``. This represents anything which can be converted to a :class:`.Point3D_Array` NumPy array. Please refer to the documentation of the function you are using for further type information. """ PointND: TypeAlias = npt.NDArray[PointDType] """``shape: (N,)`` A NumPy array representing an N-dimensional point: ``[float, ...]``. """ PointNDLike: TypeAlias = Union[PointND, Sequence[float]] """``shape: (N,)`` An N-dimensional point: ``[float, ...]``. This represents anything which can be converted to a :class:`.PointND` NumPy array. """ PointND_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (M, N)`` A NumPy array representing a sequence of :class:`.PointND` objects: ``[[float, ...], ...]``. """ PointNDLike_Array: TypeAlias = Union[PointND_Array, Sequence[PointNDLike]] """``shape: (M, N)`` An array of :class:`.PointNDLike` objects: ``[[float, ...], ...]``. This represents anything which can be converted to a :class:`.PointND_Array` NumPy array. Please refer to the documentation of the function you are using for further type information. """ """ [CATEGORY] Vector types """ Vector2D:
|
PointNDLike_Array: TypeAlias = Union[PointND_Array, Sequence[PointNDLike]] """``shape: (M, N)`` An array of :class:`.PointNDLike` objects: ``[[float, ...], ...]``. This represents anything which can be converted to a :class:`.PointND_Array` NumPy array. Please refer to the documentation of the function you are using for further type information. """ """ [CATEGORY] Vector types """ Vector2D: TypeAlias = npt.NDArray[PointDType] """``shape: (2,)`` A NumPy array representing a 2-dimensional vector: ``[float, float]``. .. caution:: Do not confuse with the :class:`~.Vector` or :class:`~.Arrow` VMobjects! """ Vector2DLike: TypeAlias = Union[npt.NDArray[PointDType], tuple[float, float]] """``shape: (2,)`` A 2-dimensional vector: ``[float, float]``. This represents anything which can be converted to a :class:`.Vector2D` NumPy array. .. caution:: Do not confuse with the :class:`~.Vector` or :class:`~.Arrow` VMobjects! """ Vector2D_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (M, 2)`` A NumPy array representing a sequence of :class:`.Vector2D` objects: ``[[float, float], ...]``. """ Vector2DLike_Array: TypeAlias = Union[Vector2D_Array, Sequence[Vector2DLike]] """``shape: (M, 2)`` An array of :class:`.Vector2DLike` objects: ``[[float, float], ...]``. This represents anything which can be converted to a :class:`.Vector2D_Array` NumPy array. """ Vector3D: TypeAlias = npt.NDArray[PointDType] """``shape: (3,)`` A NumPy array representing a 3-dimensional vector: ``[float, float, float]``. .. caution:: Do not confuse with the :class:`~.Vector` or :class:`~.Arrow3D` VMobjects! """ Vector3DLike: TypeAlias = Union[npt.NDArray[PointDType], tuple[float, float, float]] """``shape: (3,)`` A 3-dimensional vector: ``[float, float, float]``. This represents anything which can be converted to a :class:`.Vector3D` NumPy array. .. caution:: Do not confuse with the :class:`~.Vector` or :class:`~.Arrow3D` VMobjects! """ Vector3D_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (M, 3)`` An NumPy array representing a sequence of :class:`.Vector3D` objects: ``[[float, float, float], ...]``. """ Vector3DLike_Array: TypeAlias = Union[npt.NDArray[PointDType], Sequence[Vector3DLike]] """``shape: (M, 3)`` An array of :class:`.Vector3DLike` objects: ``[[float, float, float], ...]``. This represents anything which can be converted to a :class:`.Vector3D_Array` NumPy array. """ VectorND: TypeAlias = npt.NDArray[PointDType] """``shape (N,)`` A NumPy array representing an :math:`N`-dimensional vector: ``[float, ...]``. .. caution:: Do not confuse with the :class:`~.Vector` VMobject! This type alias is named "VectorND" instead of "Vector" to avoid potential name collisions. """ VectorNDLike: TypeAlias = Union[npt.NDArray[PointDType], Sequence[float]] """``shape (N,)`` An :math:`N`-dimensional vector: ``[float, ...]``. This represents anything which can be converted to a :class:`.VectorND` NumPy array. .. caution:: Do not confuse with the :class:`~.Vector` VMobject! This type alias is named "VectorND" instead of "Vector" to avoid potential name collisions. """ VectorND_Array: TypeAlias = npt.NDArray[PointDType] """``shape (M, N)`` A NumPy array representing a sequence of :class:`.VectorND` objects: ``[[float, ...], ...]``. """ VectorNDLike_Array: TypeAlias = Union[npt.NDArray[PointDType], Sequence[VectorNDLike]] """``shape (M, N)`` An array of :class:`.VectorNDLike` objects: ``[[float, ...], ...]``. This represents anything which can be converted to a :class:`.VectorND_Array` NumPy array. """ RowVector: TypeAlias = npt.NDArray[PointDType] """``shape: (1, N)`` A row vector: ``[[float, ...]]``. """ ColVector: TypeAlias = npt.NDArray[PointDType] """``shape: (N, 1)`` A column vector: ``[[float], [float], ...]``. """ """ [CATEGORY] Matrix types """ MatrixMN: TypeAlias = npt.NDArray[PointDType] """``shape: (M, N)`` A matrix: ``[[float, ...], [float, ...], ...]``. """ Zeros: TypeAlias = MatrixMN """``shape: (M, N)`` A :class:`.MatrixMN` filled with zeros, typically created with ``numpy.zeros((M, N))``. """ """ [CATEGORY] Bézier types """ QuadraticBezierPoints: TypeAlias = Point3D_Array """``shape: (3, 3)`` A :class:`.Point3D_Array` of three 3D ontrol points
|
= npt.NDArray[PointDType] """``shape: (M, N)`` A matrix: ``[[float, ...], [float, ...], ...]``. """ Zeros: TypeAlias = MatrixMN """``shape: (M, N)`` A :class:`.MatrixMN` filled with zeros, typically created with ``numpy.zeros((M, N))``. """ """ [CATEGORY] Bézier types """ QuadraticBezierPoints: TypeAlias = Point3D_Array """``shape: (3, 3)`` A :class:`.Point3D_Array` of three 3D ontrol points for a single quadratic Bézier curve: ``[[float, float, float], [float, float, float], [float, float, float]]``. """ QuadraticBezierPointsLike: TypeAlias = Union[ QuadraticBezierPoints, tuple[Point3DLike, Point3DLike, Point3DLike] ] """``shape: (3, 3)`` A :class:`.Point3DLike_Array` of three 3D control points for a single quadratic Bézier curve: ``[[float, float, float], [float, float, float], [float, float, float]]``. This represents anything which can be converted to a :class:`.QuadricBezierPoints` NumPy array. """ QuadraticBezierPoints_Array: TypeAlias = npt.NDArray[PointDType] """``shape: (N, 3, 3)`` A NumPy array containing :math:`N` :class:`.QuadraticBezierPoints` objects: ``[[[float, float, float], [float, float, float], [float, float, float]], ...]``. """ QuadraticBezierPointsLike_Array: TypeAlias = Union[ QuadraticBezierPoints_Array, Sequence[QuadraticBezierPointsLike] ] """``shape: (N, 3, 3)`` A sequence of :math:`N` :class:`.QuadraticBezierPointsLike` objects: ``[[[float, float, float], [float, float, float], [float, float, float]], ...]``. This represents anything which can be converted to a :class:`.QuadraticBezierPoints_Array` NumPy array. """ QuadraticBezierPath: TypeAlias = Point3D_Array """``shape: (3*N, 3)`` A :class:`.Point3D_Array` of :math:`3N` points, where each one of the :math:`N` consecutive blocks of 3 points represents a quadratic Bézier curve: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using forfurther type information. """ QuadraticBezierPathLike: TypeAlias = Point3DLike_Array """``shape: (3*N, 3)`` A :class:`.Point3DLike_Array` of :math:`3N` points, where each one of the :math:`N` consecutive blocks of 3 points represents a quadratic Bézier curve: ``[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.QuadraticBezierPath` NumPy array. Please refer to the documentation of the function you are using for further type information. """ QuadraticSplne: TypeAlias = QuadraticBezierPath """``shape: (3*N, 3)`` A special case of :class:`.QuadraticBezierPath` where all the :math:`N` quadratic Bézier curves are connected, forming a quadratic spline: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ QuadraticSplineLike: TypeAlias = QuadraticBezierPathLike """``shape: (3*N, 3)`` A special case of :class:`.QuadraticBezierPathLike` where all the :math:`N` quadratic Bézi curves are connected, forming a quadratic spline: ``[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.QuadraticSpline` NumPy array. Please refer to the documentation of the function you are using for further type information. """ CubicBezierPoints: TypeAlias = Point3D_Array """``shape: (4, 3)`` A :class:`.Point3D_Array` of four 3D control points for a single cubic Bézier curve: ``[[float, float, float], [float, float, float], [float, float, float], [flat, float, float]]``. """ CubicBezierPointsLike: TypeAlias = Union[ CubicBezierPoints, tuple[Point3DLike, Point3DLike, Point3DLike, Point3DLike] ] """``shape: (4, 3)`` A :class:`.Point3DLike_Array` of 4 control points for a single cubic Bézier curve: ``[[float, float, float], [float, float, float], [float, float, float], [float, float, float]]``. This represents anything which can be converted to a :class:`.CubicBezierPoints` NumPy array. """ CubicBezierPoints_Array: TypeAlias = npt.NDArray[PointDTpe] """``shape: (N, 4, 3)`` A NumPy array containing :math:`N` :class:`.CubicBezierPoints` objects: ``[[[float, float, float], [float, float, float], [float, float, float], [float,
|
``[[float, float, float], [float, float, float], [float, float, float], [float, float, float]]``. This represents anything which can be converted to a :class:`.CubicBezierPoints` NumPy array. """ CubicBezierPoints_Array: TypeAlias = npt.NDArray[PointDTpe] """``shape: (N, 4, 3)`` A NumPy array containing :math:`N` :class:`.CubicBezierPoints` objects: ``[[[float, float, float], [float, float, float], [float, float, float], [float, float, float]], ...]``. """ CubicBezierPointsLike_Array: TypeAlias = Union[ CubicBezierPoints_Array, Sequence[CubicBezierPointsLike] ] """``shape: (N, 4, 3)`` A sequence of :math:`N` :class:`.CubicBezierPointsLike` objects: ``[[[float, float, float], [float, float, float], [float, float, float], [float, float, float]], ...]``. This represents anything which can be converted to a :class:`.CubicBezierPoints_Array` NumPy array. """ CubicBezierPath: TypeAlias = Point3D_Array """``shape: (4*N, 3)`` A :class:`.Point3D_Array` of :math:`4N` points, where each one of the :math:`N` consecutive blocks of 4 points represents a cubic Bézier curve: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ CubicBezierPathLike: TypeAlias = Point3DLike_Arra """``shape: (4*N, 3)`` A :class:`.Point3DLike_Array` of :math:`4N` points, where each one of the :math:`N` consecutive blocks of 4 points represents a cubic Bézier curve: ``[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.CubicBezierPath` NumPy array. Please refer to the documentation of the function you are using for further type information. """ CubicSpline: TypeAlias = CubicBezierPath """``shape: (4*N, 3)`` A special case of :class:`.CubicBezierPah` where all the :math:`N` cubic Bézier curves are connected, forming a quadratic spline: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ CubicSplineLike: TypeAlias = CubicBezierPathLike """``shape: (4*N, 3)`` A special case of :class:`.CubicBezierPath` where all the :math:`N` cubic Bézier curves are connected, forming a quadratic spline: ``[[float, float, float], ...], ...]``. This represents anything which can converted to a :class:`.CubicSpline` NumPy array. Please refer to the documentation of the function you are using for further type information. """ BezierPoints: TypeAlias = Point3D_Array r"""``shape: (PPC, 3)`` A :class:`.Point3D_Array` of :math:`\text{PPC}` control points (:math:`\text{PPC: Points Per Curve} = n + 1`) for a single :math:`n`-th degree Bézier curve: ``[[float, float, float], ...]``. Please refer to the documentation of the function you are using for further type information. """ BezirPointsLike: TypeAlias = Point3DLike_Array r"""``shape: (PPC, 3)`` A :class:`.Point3DLike_Array` of :math:`\text{PPC}` control points (:math:`\text{PPC: Points Per Curve} = n + 1`) for a single :math:`n`-th degree Bézier curve: ``[[float, float, float], ...]``. This represents anything which can be converted to a :class:`.BezierPoints` NumPy array. Please refer to the documentation of the function you are using for further type information. """ BezierPoints_Array: TypeAlias = npt.NDArray[PointDType] r""``shape: (N, PPC, 3)`` A NumPy array of :math:`N` :class:`.BezierPoints` objects containing :math:`\text{PPC}` :class:`.Point3D` objects each (:math:`\text{PPC: Points Per Curve} = n + 1`): ``[[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ BezierPointsLike_Array: TypeAlias = Union[ BezierPoints_Array, Sequence[BezierPointsLike] ] r"""``shape: (N, PPC, 3)`` A sequence of :math:`N` :class:`.BezierPointsLike` objects containing :math:`\text{PPC}` :class:`.Point3DLike` objects each (:math:`\text{PPC: Points Per Curve} = n + 1`): ``[[[float, float, float],
|
...]``. Please refer to the documentation of the function you are using for further type information. """ BezierPointsLike_Array: TypeAlias = Union[ BezierPoints_Array, Sequence[BezierPointsLike] ] r"""``shape: (N, PPC, 3)`` A sequence of :math:`N` :class:`.BezierPointsLike` objects containing :math:`\text{PPC}` :class:`.Point3DLike` objects each (:math:`\text{PPC: Points Per Curve} = n + 1`): ``[[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.BezierPoints_Array` NumPy array. Please refer to the documentation of the function you are using for further type information. """ BezierPath: TypeAlias = Point3D_Array r"""``shape: (PPC*N, 3)`` A :class:`.Point3D_Array` of :math:`\text{PPC} \cdot N` points, where each one of the :math:`N` consecutive blocks of :math:`\text{PPC}` control points (:math:`\text{PPC: Points Per Curve} = n + 1`) represents a Bézier curve of :math:`n`-th degree: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ BezierPathLike: TypeAlias = Point3DLike_Array r"""``shape: (PPC*N, 3)`` A :class:`.Point3DLike_Array` of :math:`\text{PPC} \cdot N` points, where each one of the :math:`N` consecutive blocks of :math:`\text{PPC}` cntrol points (:math:`\text{PPC: Points Per Curve} = n + 1`) represents a Bézier curve of :math:`n`-th degree: ``[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.BezierPath` NumPy array. Please refer to the documentation of the function you are using for further type information. """ Spline: TypeAlias = BezierPath r"""``shape: (PPC*N, 3)`` A special case of :class:`.BezierPath` where all the :math:`N` Bézier curves consisting of :math:`\text{PPC}` :cla:`.Point3D` objects (:math:`\text{PPC: Points Per Curve} = n + 1`) are connected, forming an :math:`n`-th degree spline: ``[[float, float, float], ...], ...]``. Please refer to the documentation of the function you are using for further type information. """ SplineLike: TypeAlias = BezierPathLike r"""``shape: (PPC*N, 3)`` A special case of :class:`.BezierPathLike` where all the :math:`N` Bézier curves consisting of :math:`\text{PPC}` :class:`.Point3D` objects (:math:`\text{PPC: Points Per Curve} = n + 1) are connected, forming an :math:`n`-th degree spline: ``[[float, float, float], ...], ...]``. This represents anything which can be converted to a :class:`.Spline` NumPy array. Please refer to the documentation of the function you are using for further type information. """ FlatBezierPoints: TypeAlias = Union[npt.NDArray[PointDType], tuple[float, ...]] """``shape: (3*PPC*N,)`` A flattened array of Bézier control points: ``[float, ...]``. """ """ [CATEGORY] Function types """ # Due to current limittions # (see https://github.com/python/mypy/issues/14656 / 8263), # we don't specify the first argument type (Mobject). # Nor are we able to specify the return type (Animation) since we cannot import # that here. FunctionOverride: TypeAlias = Callable """Function type returning an :class:`~.Animation` for the specified :class:`~.Mobject`. """ PathFuncType: TypeAlias = Callable[[Point3DLike, Point3DLike, float], Point3DLike] """Function mapping two :class:`.Point3D` objects and an alpha value to a new :class:`.Point3D`. """ MappingFunction: TypeAlias = Callable[[Point3D], Point3D] """A function mapping a :class:`.Point3D` to another :class:`.Point3D`.""" MultiMappingFunction: TypeAlias = Callable[[Point3D_Array], Point3D_Array] """A function mapping a :class:`.Point3D_Array` to another :class:`.Point3D_Array`. """ """ [CATEGORY] Image types """ PixelArray: TypeAlias = npt.NDArray[ManimInt] """``shape: (height, width) | (height, width, 3) | (height, width, 4)`` A rasterized image with a height of ``height`` pixels and a width
|
:class:`.Point3D` to another :class:`.Point3D`.""" MultiMappingFunction: TypeAlias = Callable[[Point3D_Array], Point3D_Array] """A function mapping a :class:`.Point3D_Array` to another :class:`.Point3D_Array`. """ """ [CATEGORY] Image types """ PixelArray: TypeAlias = npt.NDArray[ManimInt] """``shape: (height, width) | (height, width, 3) | (height, width, 4)`` A rasterized image with a height of ``height`` pixels and a width of ``width`` pixels. Every value in the array is an integer from 0 to 255. Every pixel is represented either by a single integer indicating its lightness (for greyscale images), an :class:`.RGB_Array_Int` or an `RGBA_Array_Int`. """ GrayscalePixelArray: TypeAlias = PixelArray """``shape: (height, width)`` A 100% opaque grayscale :class:`.PixelArray`, where every pixel value is a `ManimInt` indicating its lightness (black -> gray -> white). """ RGBPixelArray: TypeAlias = PixelArray """``shape: (height, width, 3)`` A 100% opaque :class:`.PixelArray` in color, where every pixel value is an `RGB_Array_Int` object. """ RGBAPixelArray: TypeAlias = PixelArray """``shape: (height, width, 4)`` A :class:`.PixelArray` in color where pixels can be transparent. Every pixel value is an :class:`.RGBA_Array_Int` object. """ """ [CATEGORY] Path types """ StrPath: TypeAlias = Union[str, PathLike[str]] """A string or :class:`.os.PathLike` representing a path to a directory or file. """ StrOrBytesPath: TypeAlias = Union[str, bytes, PathLike[str], PathLike[bytes]] """A string, bytes or :class:`.os.PathLike` object representing a path to a directory or file. """ ================================================ FILE: manim/_config/__init__.py ================================================ """Set the global config and logger.""" from __future__ import annotations import logging from collections.abc import Generator from contextlib import contextmanager from typing import Any from .cli_colors import parse_cli_ctx from .logger_utils import make_logger from .utils import ManimConfig, ManimFrame, make_config_parser __all__ = [ "logger", "console", "error_console", "config", "frame", "tempconfig", "cli_ctx_settings", ] parser = make_config_parser() # Logger usage: accessible globally as `manim.logger` or via `logging.getLogger("manim")`. # For printing, use `manim.console.print()` instead of the built-in `print()`. # For error output, use `error_console`, which prints to stderr. logger, console, error_console = make_logger( parser["logger"], parser["CLI"]["verbosity"], ) cli_ctx_settings = parse_cli_ctx(parser["CLI_CTX"]) # TODO: temporary to have a clean terminal output when working with PIL or matplotlib logging.getLogger("PIL").setLevel(logging.INFO) logging.getLogger("matplotlib").setLevel(logging.INFO) config = ManimConfig().digest_parser(parser) # TODO: to be used in the future - see PR #620 # https://github.com/ManimCommunity/manim/pull/620 frame = ManimFrame(config) # This has to go here because it needs access to this module's config @contextmanager def tempconfig(temp: ManimConfig | dict[str, Any]) -> Generator[None, None, None]: """Temporarily modifies the global ``config`` object using a context manager. Inside the ``with`` statement, the modified config will be used. After context manager exits, the config will be restored to its original state. Parameters ---------- temp Object whose keys will be used to temporarily update the global ``config``. Examples -------- Use ``with tempconfig({...})`` to temporarily change the default values of certain config options. .. code-block:: pycon >>> config["frame_height"] 8.0 >>> with tempconfig({"frame_height": 100.0}): ... print(config["frame_height"]) 100.0 >>> config["frame_height"] 8.0 """ global config original = config.copy() temp = {k: v for k, v in temp.items() if k in original} # In order to change the config that every module has access to, use # update(), DO NOT use assignment. Assigning config = some_dict will just # make the local variable named config point to a
|
config.copy() temp = {k: v for k, v in temp.items() if k in original} # In order to change the config that every module has access to, use # update(), DO NOT use assignment. Assigning config = some_dict will just # make the local variable named config point to a new dictionary, it will # NOT change the dictionary that every module has a reference to. config.update(temp) try: yield finally: config.update(original) # update, not assignment! ================================================ FILE: manim/_config/cli_colors.py ================================================ """Parses CLI context settings from the configuration file and returns a Cloup Context settings dictionary. This module reads configuration values for help formatting, theme styles, and alignment options used when rendering command-line interfaces in Manim. """ from __future__ import annotations import configparser from typing import Any from cloup import Context, HelpFormatter, HelpTheme, Style __all__ = ["parse_cli_ctx"] def parse_cli_ctx(parser: configparser.SectionProxy) -> dict[str, Any]: formatter_settings: dict[str, str | int | None] = { "indent_increment": int(parser["indent_increment"]), "width": int(parser["width"]), "col1_max_width": int(parser["col1_max_width"]), "col2_min_width": int(parser["col2_min_width"]), "col_spacing": int(parser["col_spacing"]), "row_sep": parser["row_sep"] if parser["row_sep"] else None, } theme_settings = {} theme_keys = { "command_help", "invoked_command", "heading", "constraint", "section_help", "col1", "col2", "epilog", } # Extract and apply any style-related keys defined in the config section. for k, v in parser.items(): if k in theme_keys and v: theme_settings.update({k: Style(v)}) formatter = {} theme = parser["theme"] if parser["theme"] else None if theme is None: formatter = HelpFormatter.settings( theme=HelpTheme(**theme_settings), **formatter_settings, ) elif theme.lower() == "dark": formatter = HelpFormatter.settings( theme=HelpTheme.dark().with_(**theme_settings), **formatter_settings, ) elif theme.lower() == "light": formatter = HelpFormatter.settings( theme=HelpTheme.light().with_(**theme_settings), **formatter_settings, ) return_val: dict[str, Any] = Context.settings( align_option_groups=parser["align_option_groups"].lower() == "true", align_sections=parser["align_sections"].lower() == "true", show_constraints=True, formatter_settings=formatter, ) return return_val ================================================ FILE: manim/_config/default.cfg ================================================ # manim.cfg # Default configuration for manim # Configure how manim behaves when called from the command line without # specifying any flags [CLI] # Each of the following will be set to True if the corresponding CLI flag # is present when executing manim. If the flag is not present, they will # be set to the value found here. For example, running manim with the -w # flag will set WRITE_TO_MOVIE to True. However, since the default value # of WRITE_TO_MOVIE defined in this file is also True, running manim # without the -w value will also output a movie file. To change that, set # WRITE_TO_MOVIE = False so that running manim without the -w flag will not # generate a movie file. Note all of the following accept boolean values. # --notify_outdated_version notify_outdated_version = True # -w, --write_to_movie write_to_movie = True format = mp4 # -s, --save_last_frame # setting save_last_frame to True forces write_to_movie to False save_last_frame = False # -a, --write_all write_all = False # -g, --save_pngs save_pngs = False # -0, --zero_pad zero_pad = 4 # -i, --save_as_gif save_as_gif = False # --save_sections save_sections = False # -p, --preview preview = False # -f, --show_in_file_browser show_in_file_browser = False # -v, --verbosity verbosity = INFO # --progress_bar progress_bar = display # -o, --output_file output_file = # --log_to_file log_to_file = False # -c, --background_color background_color = BLACK # --background_opacity
|
--save_as_gif save_as_gif = False # --save_sections save_sections = False # -p, --preview preview = False # -f, --show_in_file_browser show_in_file_browser = False # -v, --verbosity verbosity = INFO # --progress_bar progress_bar = display # -o, --output_file output_file = # --log_to_file log_to_file = False # -c, --background_color background_color = BLACK # --background_opacity background_opacity = 1 # The following two are both set by the -n (or --from_animation_number) # flag. See manim -h for more information. from_animation_number = 0 # Use -1 to render all animations upto_animation_number = -1 # The following are meant to be paths relative to the point of execution. # Set them at the CLI with the corresponding flag, or set their default # values here. # --media_dir media_dir = ./media # --log_dir log_dir = {media_dir}/logs # --assets_dir assets_dir = ./ # the following do not have CLI arguments but depend on media_dir video_dir = {media_dir}/videos/{module_name}/{quality} sections_dir = {video_dir}/sections images_dir = {media_dir}/images/{module_name} tex_dir = {media_dir}/Tex text_dir = {media_dir}/texts partial_movie_dir = {video_dir}/partial_movie_files/{scene_name} # --renderer [cairo|opengl] renderer = cairo # --enable_gui enable_gui = False # --gui_location gui_location = 0,0 # --fullscreen fullscreen = False # "Set the position of preview window. You can use directions, e.g. UL/DR/LEFT/ORIGIN # or the position (pixel) of the upper left corner of the window, e.g. '960,540'", # --window_position window_position = UR # Manually adjust the size of the window, or use default to automatically scale the window based on # the dimensions of the monitor. # --window_size window_size = default # --window_monitor window_monitor = 0 # --force_window force_window = False # --use_projection_fill_shaders use_projection_fill_shaders = False # --use_projection_stroke_shaders use_projection_stroke_shaders = False movie_file_extension = .mp4 # These now override the --quality option. frame_rate = 60 pixel_height = 1080 pixel_width = 1920 # Use -1 to set max_files_cached to infinity. max_files_cached = 100 #Flush cache will delete all the cached partial-movie-files. flush_cache = False disable_caching = False # Disable the warning when there are too much submobjects to hash. disable_caching_warning = False # --enable_wireframe enable_wireframe = False # --dry_run dry_run = False # Default tex_template # --tex_template tex_template = # specify the plugins as comma separated values # manim will load that plugin if it specified here. plugins = # CLI Context/Formatter # Visit the cloup documentation to understand the formatting options available: # https://cloup.readthedocs.io/en/latest/index.html#a-simple-example [CLI_CTX] # CTX settings align_option_groups = True align_sections = True show_constraints = True # Formatter settings indent_increment = 2 width = 80 col1_max_width = 30 col2_min_width = 35 col_spacing = 2 row_sep = # Dark/Light, or leave empty theme = # Theme Settings - The following options override the theme colors. command_help = invoked_command = heading = constraint = section_help = col1 = col2 = epilog = # Overrides the default output folders, NOT the output file names. Note that # if the custom_folders flag is present, the Tex and text files will not be put # under media_dir, as is the default. [custom_folders] media_dir = videos video_dir = {media_dir} sections_dir = {media_dir} images_dir = {media_dir} text_dir = {media_dir}/temp_files tex_dir = {media_dir}/temp_files log_dir
|
NOT the output file names. Note that # if the custom_folders flag is present, the Tex and text files will not be put # under media_dir, as is the default. [custom_folders] media_dir = videos video_dir = {media_dir} sections_dir = {media_dir} images_dir = {media_dir} text_dir = {media_dir}/temp_files tex_dir = {media_dir}/temp_files log_dir = {media_dir}/temp_files partial_movie_dir = {media_dir}/partial_movie_files/{scene_name} # Rich settings [logger] logging_keyword = bold yellow logging_level_notset = dim logging_level_debug = green logging_level_info = green logging_level_warning = red logging_level_error = red bold logging_level_critical = red bold reverse log_level = log_time = cyan dim log_message = log_path = dim log_width = -1 log_height = -1 log_timestamps = True repr_number = green [ffmpeg] # Uncomment the following line to manually set the loglevel for ffmpeg. See # ffmpeg manpage for accepted values loglevel = ERROR [jupyter] media_embed = False media_width = 60%% ================================================ FILE: manim/_config/logger_utils.py ================================================ """Utilities to create and set the logger. Manim's logger can be accessed as ``manim.logger``, or as ``logging.getLogger("manim")``, once the library has been imported. Manim also exports a second object, ``console``, which should be used to print on screen messages that need not be logged. Both ``logger`` and ``console`` use the ``rich`` library to produce rich text format. """ from __future__ import annotations import configparser import copy import json import logging from typing import TYPE_CHECKING, Any from rich import color, errors from rich import print as printf from rich.console import Console from rich.logging import RichHandler from rich.theme import Theme if TYPE_CHECKING: from pathlib import Path __all__ = ["make_logger", "parse_theme", "set_file_logger", "JSONFormatter"] HIGHLIGHTED_KEYWORDS = [ # these keywords are highlighted specially "Played", "animations", "scene", "Reading", "Writing", "script", "arguments", "Invalid", "Aborting", "module", "File", "Rendering", "Rendered", ] WRONG_COLOR_CONFIG_MSG = """ [logging.level.error]Your colour configuration couldn't be parsed. Loading the default color configuration.[/logging.level.error] """ def make_logger( parser: configparser.SectionProxy, verbosity: str, ) -> tuple[logging.Logger, Console, Console]: """Make the manim logger and console. Parameters ---------- parser A parser containing any .cfg files in use. verbosity The verbosity level of the logger. Returns ------- :class:`logging.Logger`, :class:`rich.Console`, :class:`rich.Console` The manim logger and consoles. The first console outputs to stdout, the second to stderr. All use the theme returned by :func:`parse_theme`. See Also -------- :func:`~._config.utils.make_config_parser`, :func:`parse_theme` Notes ----- The ``parser`` is assumed to contain only the options related to configuring the logger at the top level. """ # Throughout the codebase, use console.print() instead of print() theme = parse_theme(parser) console = Console(theme=theme) error_console = Console(theme=theme, stderr=True) # set the rich handler rich_handler = RichHandler( console=console, show_time=parser.getboolean("log_timestamps", fallback=False), keywords=HIGHLIGHTED_KEYWORDS, ) # finally, the logger logger = logging.getLogger("manim") logger.addHandler(rich_handler) logger.setLevel(verbosity) logger.propagate = False if not (libav_logger := logging.getLogger()).hasHandlers(): libav_logger.addHandler(rich_handler) libav_logger.setLevel(verbosity) return logger, console, error_console def parse_theme(parser: configparser.SectionProxy) -> Theme | None: """Configure the rich style of logger and console output. Parameters ---------- parser A parser containing any .cfg files in use. Returns ------- :class:`rich.Theme` The rich theme to be used by the manim logger. See Also -------- :func:`make_logger`. """ theme: dict[str, Any] = {key.replace("_", "."): parser[key] for key in parser} theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"]) theme["log.height"] = (
|
parser A parser containing any .cfg files in use. Returns ------- :class:`rich.Theme` The rich theme to be used by the manim logger. See Also -------- :func:`make_logger`. """ theme: dict[str, Any] = {key.replace("_", "."): parser[key] for key in parser} theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"]) theme["log.height"] = ( None if theme["log.height"] == "-1" else int(theme["log.height"]) ) theme["log.timestamps"] = False try: custom_theme = Theme( { k: v for k, v in theme.items() if k not in ["log.width", "log.height", "log.timestamps"] }, ) except (color.ColorParseError, errors.StyleSyntaxError): printf(WRONG_COLOR_CONFIG_MSG) custom_theme = None return custom_theme def set_file_logger(scene_name: str, module_name: str, log_dir: Path) -> None: """Add a file handler to manim logger. The path to the file is built using ``config.log_dir``. Parameters ---------- scene_name The name of the scene, used in the name of the log file. module_name The name of the module, used in the name of the log file. log_dir Path to the folder where log files are stored. """ # Note: The log file name will be # <name_of_animation_file>_<name_of_scene>.log, gotten from config. So it # can differ from the real name of the scene. <name_of_scene> would only # appear if scene name was provided when manim was called. log_file_name = f"{module_name}_{scene_name}.log" log_file_path = log_dir / log_file_name file_handler = logging.FileHandler(log_file_path, mode="w") file_handler.setFormatter(JSONFormatter()) logger = logging.getLogger("manim") logger.addHandler(file_handler) logger.info("Log file will be saved in %(logpath)s", {"logpath": log_file_path}) class JSONFormatter(logging.Formatter): """A formatter that outputs logs in a custom JSON format. This class is used internally for testing purposes. """ def format(self, record: logging.LogRecord) -> str: """Format the record in a custom JSON format.""" record_c = copy.deepcopy(record) if record_c.args: if isinstance(record_c.args, dict): for arg in record_c.args: record_c.args[arg] = "<>" else: record_c.args = ("<>",) * len(record_c.args) return json.dumps( { "levelname": record_c.levelname, "module": record_c.module, "message": super().format(record_c), }, ) ================================================ FILE: manim/animation/__init__.py ================================================ [Empty file] ================================================ FILE: manim/animation/animation.py ================================================ """Animate mobjects.""" from __future__ import annotations from manim.mobject.opengl.opengl_mobject import OpenGLMobject from .. import config, logger from ..constants import RendererType from ..mobject import mobject from ..mobject.mobject import Group, Mobject from ..mobject.opengl import opengl_mobject from ..utils.rate_functions import linear, smooth __all__ = ["Animation", "Wait", "Add", "override_animation"] from collections.abc import Callable, Iterable, Sequence from copy import deepcopy from functools import partialmethod from typing import TYPE_CHECKING, Any from typing_extensions import Self if TYPE_CHECKING: from manim.scene.scene import Scene DEFAULT_ANIMATION_RUN_TIME: float = 1.0 DEFAULT_ANIMATION_LAG_RATIO: float = 0.0 class Animation: """An animation. Animations have a fixed time span. Parameters ---------- mobject The mobject to be animated. This is not required for all types of animations. lag_ratio Defines the delay after which the animation is applied to submobjects. This lag is relative to the duration of the animation. This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time. run_time The duration of the animation in seconds. rate_func The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) . For example ``rate_func(0.5)`` is the proportion of the animation that is done after half of the animations run time. reverse_rate_function Reverses
|
animation has the defined run time. run_time The duration of the animation in seconds. rate_func The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) . For example ``rate_func(0.5)`` is the proportion of the animation that is done after half of the animations run time. reverse_rate_function Reverses the rate function of the animation. Setting ``reverse_rate_function`` does not have any effect on ``remover`` or ``introducer``. These need to be set explicitly if an introducer-animation should be turned into a remover one and vice versa. name The name of the animation. This gets displayed while rendering the animation. Defaults to <class-name>(<Mobject-name>). remover Whether the given mobject should be removed from the scene after this animation. suspend_mobject_updating Whether updaters of the mobject should be suspended during the animation. .. NOTE:: In the current implementation of this class, the specified rate function is applied within :meth:`.Animation.interpolate_mobject` call as part of the call to :meth:`.Animation.interpolate_submobject`. For subclasses of :class:`.Animation` that are implemented by overriding :meth:`interpolate_mobject`, the rate function has to be applied manually (e.g., by passing ``self.rate_func(alpha)`` instead of just ``alpha``). Examples -------- .. manim:: LagRatios class LagRatios(Scene): def construct(self): ratios = [0, 0.1, 0.5, 1, 2] # demonstrated lag_ratios # Create dot groups group = VGroup(*[Dot() for _ in range(4)]).arrange_submobjects() groups = VGroup(*[group.copy() for _ in ratios]).arrange_submobjects(buff=1) self.add(groups) # Label groups self.add(Text("lag_ratio = ", font_size=36).next_to(groups, UP, buff=1.5)) for group, ratio in zip(groups, ratios): self.add(Text(str(ratio), font_size=36).next_to(group, UP)) #Animate groups with different lag_ratios self.play(AnimationGroup(*[ group.animate(lag_ratio=ratio, run_time=1.5).shift(DOWN * 2) for group, ratio in zip(groups, ratios) ])) # lag_ratio also works recursively on nested submobjects: self.play(groups.animate(run_time=1, lag_ratio=0.1).shift(UP * 2)) """ def __new__( cls, mobject=None, *args, use_override=True, **kwargs, ) -> Self: if isinstance(mobject, Mobject) and use_override: func = mobject.animation_override_for(cls) if func is not None: anim = func(mobject, *args, **kwargs) logger.debug( f"The {cls.__name__} animation has been overridden for " f"{type(mobject).__name__} mobjects. use_override = False can " f" be used as keyword argument to prevent animation overriding.", ) return anim return super().__new__(cls) def __init__( self, mobject: Mobject | OpenGLMobject | None, lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO, run_time: float = DEFAULT_ANIMATION_RUN_TIME, rate_func: Callable[[float], float] = smooth, reverse_rate_function: bool = False, name: str = None, remover: bool = False, # remove a mobject from the screen? suspend_mobject_updating: bool = True, introducer: bool = False, *, _on_finish: Callable[[], None] = lambda _: None, use_override: bool = True, # included here to avoid TypeError if passed from a subclass' constructor ) -> None: self._typecheck_input(mobject) self.run_time: float = run_time self.rate_func: Callable[[float], float] = rate_func self.reverse_rate_function: bool = reverse_rate_function self.name: str | None = name self.remover: bool = remover self.introducer: bool = introducer self.suspend_mobject_updating: bool = suspend_mobject_updating self.lag_ratio: float = lag_ratio self._on_finish: Callable[[Scene], None] = _on_finish if config["renderer"] == RendererType.OPENGL: self.starting_mobject: OpenGLMobject = OpenGLMobject() self.mobject: OpenGLMobject = ( mobject if mobject is not None else OpenGLMobject() ) else: self.starting_mobject: Mobject = Mobject() self.mobject: Mobject = mobject if mobject is not None else Mobject() if hasattr(self, "CONFIG"): logger.error( ( "CONFIG has been removed from ManimCommunity.", "Please use keyword arguments instead.", ), ) @property def run_time(self) ->
|
OpenGLMobject = ( mobject if mobject is not None else OpenGLMobject() ) else: self.starting_mobject: Mobject = Mobject() self.mobject: Mobject = mobject if mobject is not None else Mobject() if hasattr(self, "CONFIG"): logger.error( ( "CONFIG has been removed from ManimCommunity.", "Please use keyword arguments instead.", ), ) @property def run_time(self) -> float: return self._run_time @run_time.setter def run_time(self, value: float) -> None: if value < 0: raise ValueError( f"The run_time of {self.__class__.__name__} cannot be " f"negative. The given value was {value}." ) self._run_time = value def _typecheck_input(self, mobject: Mobject | None) -> None: if mobject is None: logger.debug("Animation with empty mobject") elif not isinstance(mobject, (Mobject, OpenGLMobject)): raise TypeError("Animation only works on Mobjects") def __str__(self) -> str: if self.name: return self.name return f"{self.__class__.__name__}({str(self.mobject)})" def __repr__(self) -> str: return str(self) def begin(self) -> None: """Begin the animation. This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method. """ 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.suspend_updating() self.interpolate(0) def finish(self) -> None: # TODO: begin and finish should require a scene as parameter. # That way Animation.clean_up_from_screen and Scene.add_mobjects_from_animations # could be removed as they fulfill basically the same purpose. """Finish the animation. This method gets called when the animation is over. """ self.interpolate(1) if self.suspend_mobject_updating and self.mobject is not None: self.mobject.resume_updating() def clean_up_from_scene(self, scene: Scene) -> None: """Clean up the :class:`~.Scene` after finishing the animation. This includes to :meth:`~.Scene.remove` the Animation's :class:`~.Mobject` if the animation is a remover. Parameters ---------- scene The scene the animation should be cleaned up from. """ self._on_finish(scene) if self.is_remover(): scene.remove(self.mobject) def _setup_scene(self, scene: Scene) -> None: """Setup up the :class:`~.Scene` before starting the animation. This includes to :meth:`~.Scene.add` the Animation's :class:`~.Mobject` if the animation is an introducer. Parameters ---------- scene The scene the animation should be cleaned up from. """ if scene is None: return if ( self.is_introducer() and self.mobject not in scene.get_mobject_family_members() ): scene.add(self.mobject) def create_starting_mobject(self) -> Mobject | OpenGLMobject: # Keep track of where the mobject starts return self.mobject.copy() def get_all_mobjects(self) -> Sequence[Mobject | OpenGLMobject]: """Get all mobjects involved in the animation. Ordering must match the ordering of arguments to interpolate_submobject Returns ------- Sequence[Mobject] The sequence of mobjects. """ return self.mobject, self.starting_mobject def get_all_families_zipped(self) -> Iterable[tuple]: if config["renderer"] == RendererType.OPENGL: return zip(*(mob.get_family() for mob in self.get_all_mobjects())) return zip( *(mob.family_members_with_points() 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]: """Get all mobjects to be updated during the animation. Returns ------- List[Mobject] The list of mobjects to be updated during the
|
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]: """Get all mobjects to be updated during the animation. Returns ------- List[Mobject] The list of mobjects to be updated during the animation. """ # 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) -> Animation: """Create a copy of the animation. Returns ------- Animation A copy of ``self`` """ return deepcopy(self) # Methods for interpolation, the mean of an Animation # TODO: stop using alpha as parameter name in different meanings. def interpolate(self, alpha: float) -> None: """Set the animation progress. This method gets called for every frame during an animation. Parameters ---------- alpha The relative time to set the animation to, 0 meaning the start, 1 meaning the end. """ self.interpolate_mobject(alpha) def interpolate_mobject(self, alpha: float) -> None: """Interpolates the mobject of the :class:`Animation` based on alpha value. Parameters ---------- alpha A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively. """ families = list(self.get_all_families_zipped()) for i, mobs in enumerate(families): sub_alpha = self.get_sub_alpha(alpha, i, len(families)) self.interpolate_submobject(*mobs, sub_alpha) def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, # target_copy: Mobject, #Todo: fix - signature of interpolate_submobject differs in Transform(). alpha: float, ) -> Animation: # Typically implemented by subclass pass def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float: """Get the animation progress of any submobjects subanimation. Parameters ---------- alpha The overall animation progress index The index of the subanimation. num_submobjects The total count of subanimations. Returns ------- float The progress of the subanimation. """ # TODO, make this more understandable, 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 if self.reverse_rate_function: return self.rate_func(1 - (value - lower)) else: return self.rate_func(value - lower) # Getters and setters def set_run_time(self, run_time: float) -> Animation: """Set the run time of the animation. Parameters ---------- run_time The new time the animation should take in seconds. .. note:: The run_time of an animation should not be changed while it is already running. Returns ------- Animation ``self`` """ self.run_time = run_time return self # TODO: is this getter even necessary? def get_run_time(self) -> float: """Get the run time of the animation. Returns ------- float The time the animation takes in seconds. """ return self.run_time def set_rate_func( self, rate_func: Callable[[float], float], ) -> Animation: """Set the rate function of the animation. Parameters ---------- rate_func The new function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`). Returns ------- Animation ``self`` """ self.rate_func = rate_func return self def get_rate_func( self, ) -> Callable[[float], float]: """Get the rate function of the animation.
|
-> Animation: """Set the rate function of the animation. Parameters ---------- rate_func The new function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`). Returns ------- Animation ``self`` """ self.rate_func = rate_func return self def get_rate_func( self, ) -> Callable[[float], float]: """Get the rate function of the animation. Returns ------- Callable[[float], float] The rate function of the animation. """ return self.rate_func def set_name(self, name: str) -> Animation: """Set the name of the animation. Parameters ---------- name The new name of the animation. Returns ------- Animation ``self`` """ self.name = name return self def is_remover(self) -> bool: """Test if the animation is a remover. Returns ------- bool ``True`` if the animation is a remover, ``False`` otherwise. """ return self.remover def is_introducer(self) -> bool: """Test if the animation is an introducer. Returns ------- bool ``True`` if the animation is an introducer, ``False`` otherwise. """ return self.introducer @classmethod def __init_subclass__(cls, **kwargs) -> None: super().__init_subclass__(**kwargs) cls._original__init__ = cls.__init__ _original__init__ = __init__ # needed if set_default() is called with no kwargs directly from Animation @classmethod def set_default(cls, **kwargs) -> None: """Sets the default values of keyword arguments. If this method is called without any additional keyword arguments, the original default values of the initialization method of this class are restored. Parameters ---------- kwargs Passing any keyword argument will update the default values of the keyword arguments of the initialization function of this class. Examples -------- .. manim:: ChangeDefaultAnimation class ChangeDefaultAnimation(Scene): def construct(self): Rotate.set_default(run_time=2, rate_func=rate_functions.linear) Indicate.set_default(color=None) S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25) self.add(S) self.play(Rotate(S, PI)) self.play(Indicate(S)) Rotate.set_default() Indicate.set_default() """ if kwargs: cls.__init__ = partialmethod(cls.__init__, **kwargs) else: cls.__init__ = cls._original__init__ def prepare_animation( anim: Animation | mobject._AnimationBuilder | opengl_mobject._AnimationBuilder, ) -> Animation: r"""Returns either an unchanged animation, or the animation built from a passed animation factory. Examples -------- :: >>> from manim import Square, FadeIn >>> s = Square() >>> prepare_animation(FadeIn(s)) FadeIn(Square) :: >>> prepare_animation(s.animate.scale(2).rotate(42)) _MethodAnimation(Square) :: >>> prepare_animation(42) Traceback (most recent call last): ... TypeError: Object 42 cannot be converted to an animation """ if isinstance(anim, mobject._AnimationBuilder): return anim.build() if isinstance(anim, opengl_mobject._AnimationBuilder): return anim.build() if isinstance(anim, Animation): return anim raise TypeError(f"Object {anim} cannot be converted to an animation") class Wait(Animation): """A "no operation" animation. Parameters ---------- run_time The amount of time that should pass. stop_condition A function without positional arguments that evaluates to a boolean. The function is evaluated after every new frame has been rendered. Playing the animation stops after the return value is truthy, or after the specified ``run_time`` has passed. frozen_frame Controls whether or not the wait animation is static, i.e., corresponds to a frozen frame. If ``False`` is passed, the render loop still progresses through the animation as usual and (among other things) continues to call updater functions. If ``None`` (the default value), the :meth:`.Scene.play` call tries to determine whether the Wait call can be static or not itself via :meth:`.Scene.should_mobjects_update`. kwargs Keyword arguments to be passed to the parent class, :class:`.Animation`. """ def __init__( self, run_time: float = 1, stop_condition: Callable[[], bool] | None = None, frozen_frame: bool | None =
|
value), the :meth:`.Scene.play` call tries to determine whether the Wait call can be static or not itself via :meth:`.Scene.should_mobjects_update`. kwargs Keyword arguments to be passed to the parent class, :class:`.Animation`. """ def __init__( self, run_time: float = 1, stop_condition: Callable[[], bool] | None = None, frozen_frame: bool | None = None, rate_func: Callable[[float], float] = linear, **kwargs, ): if stop_condition and frozen_frame: raise ValueError("A static Wait animation cannot have a stop condition.") self.duration: float = run_time self.stop_condition = stop_condition self.is_static_wait: bool = frozen_frame super().__init__(None, run_time=run_time, rate_func=rate_func, **kwargs) # quick fix to work in opengl setting: self.mobject.shader_wrapper_list = [] def begin(self) -> None: pass def finish(self) -> None: pass def clean_up_from_scene(self, scene: Scene) -> None: pass def update_mobjects(self, dt: float) -> None: pass def interpolate(self, alpha: float) -> None: pass class Add(Animation): """Add Mobjects to a scene, without animating them in any other way. This is similar to the :meth:`.Scene.add` method, but :class:`Add` is an animation which can be grouped into other animations. Parameters ---------- mobjects One :class:`~.Mobject` or more to add to a scene. run_time The duration of the animation after adding the ``mobjects``. Defaults to 0, which means this is an instant animation without extra wait time after adding them. **kwargs Additional arguments to pass to the parent :class:`Animation` class. Examples -------- .. manim:: DefaultAddScene class DefaultAddScene(Scene): def construct(self): text_1 = Text("I was added with Add!") text_2 = Text("Me too!") text_3 = Text("And me!") texts = VGroup(text_1, text_2, text_3).arrange(DOWN) rect = SurroundingRectangle(texts, buff=0.5) self.play( Create(rect, run_time=3.0), Succession( Wait(1.0), # You can Add a Mobject in the middle of an animation... Add(text_1), Wait(1.0), # ...or multiple Mobjects at once! Add(text_2, text_3), ), ) self.wait() .. manim:: AddWithRunTimeScene class AddWithRunTimeScene(Scene): def construct(self): # A 5x5 grid of circles circles = VGroup( *[Circle(radius=0.5) for _ in range(25)] ).arrange_in_grid(5, 5) self.play( Succession( # Add a run_time of 0.2 to wait for 0.2 seconds after # adding the circle, instead of using Wait(0.2) after Add! *[Add(circle, run_time=0.2) for circle in circles], rate_func=smooth, ) ) self.wait() """ def __init__( self, *mobjects: Mobject, run_time: float = 0.0, **kwargs: Any ) -> None: mobject = mobjects[0] if len(mobjects) == 1 else Group(*mobjects) super().__init__(mobject, run_time=run_time, introducer=True, **kwargs) def begin(self) -> None: pass def finish(self) -> None: pass def clean_up_from_scene(self, scene: Scene) -> None: pass def update_mobjects(self, dt: float) -> None: pass def interpolate(self, alpha: float) -> None: pass def override_animation( animation_class: type[Animation], ) -> Callable[[Callable], Callable]: """Decorator used to mark methods as overrides for specific :class:`~.Animation` types. Should only be used to decorate methods of classes derived from :class:`~.Mobject`. ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined them. They don't override subclasses of the ``Animation`` they override. See Also -------- :meth:`~.Mobject.add_animation_override` Parameters ---------- animation_class The animation to be overridden. Returns ------- Callable[[Callable], Callable] The actual decorator. This marks the method as overriding an animation. Examples -------- .. manim:: OverrideAnimationExample class MySquare(Square): @override_animation(FadeIn) def _fade_in_override(self, **kwargs): return Create(self, **kwargs) class OverrideAnimationExample(Scene): def construct(self): self.play(FadeIn(MySquare())) """ def decorator(func): func._override_animation = animation_class return func return decorator ================================================ FILE:
|
animation to be overridden. Returns ------- Callable[[Callable], Callable] The actual decorator. This marks the method as overriding an animation. Examples -------- .. manim:: OverrideAnimationExample class MySquare(Square): @override_animation(FadeIn) def _fade_in_override(self, **kwargs): return Create(self, **kwargs) class OverrideAnimationExample(Scene): def construct(self): self.play(FadeIn(MySquare())) """ def decorator(func): func._override_animation = animation_class return func return decorator ================================================ FILE: manim/animation/changing.py ================================================ """Animation of a mobject boundary and tracing of points.""" from __future__ import annotations __all__ = ["AnimatedBoundary", "TracedPath"] from collections.abc import Callable, Sequence from typing import Any from typing_extensions import Self from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.color import ( BLUE_B, BLUE_D, BLUE_E, GREY_BROWN, WHITE, ParsableManimColor, ) from manim.utils.rate_functions import RateFunction, smooth class AnimatedBoundary(VGroup): """Boundary of a :class:`.VMobject` with animated color change. Examples -------- .. manim:: AnimatedBoundaryExample class AnimatedBoundaryExample(Scene): def construct(self): text = Text("So shiny!") boundary = AnimatedBoundary(text, colors=[RED, GREEN, BLUE], cycle_rate=3) self.add(text, boundary) self.wait(2) """ def __init__( self, vmobject: VMobject, colors: Sequence[ParsableManimColor] = [BLUE_D, BLUE_B, BLUE_E, GREY_BROWN], max_stroke_width: float = 3, cycle_rate: float = 0.5, back_and_forth: bool = True, draw_rate_func: RateFunction = smooth, fade_rate_func: RateFunction = smooth, **kwargs: Any, ): super().__init__(**kwargs) 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.vmobject = vmobject self.boundary_copies = [ vmobject.copy().set_style(stroke_width=0, fill_opacity=0) for x in range(2) ] self.add(*self.boundary_copies) self.total_time = 0.0 self.add_updater(lambda m, dt: self.update_boundary_copies(dt)) def update_boundary_copies(self, dt: float) -> None: # 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.0 - draw_alpha, 1.0) else: bounds = (0.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 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, metaclass=ConvertToOpenGL): """Traces the path of a point returned by a function call. Parameters ---------- traced_point_func The function to be traced. stroke_width The width of the trace. stroke_color The color of the trace. dissipating_time The time taken for the path to dissipate. Default set to ``None`` which disables dissipation. Examples -------- .. manim:: TracedPathExample class TracedPathExample(Scene): def construct(self): circ = Circle(color=RED).shift(4*LEFT) dot = Dot(color=RED).move_to(circ.get_start()) rolling_circle = VGroup(circ, dot) trace = TracedPath(circ.get_start) rolling_circle.add_updater(lambda m: m.rotate(-0.3)) self.add(trace, rolling_circle) self.play(rolling_circle.animate.shift(8*RIGHT), run_time=4, rate_func=linear) .. manim:: DissipatingPathExample class DissipatingPathExample(Scene): def construct(self): a = Dot(RIGHT * 2) b = TracedPath(a.get_center, dissipating_time=0.5, stroke_opacity=[0, 1]) self.add(a, b) self.play(a.animate(path_arc=PI / 4).shift(LEFT * 2)) self.play(a.animate(path_arc=-PI / 4).shift(LEFT * 2)) self.wait() """ def __init__( self, traced_point_func: Callable, stroke_width: float = 2, stroke_color: ParsableManimColor | None = WHITE, dissipating_time: float | None = None, **kwargs: Any, ) -> None: super().__init__(stroke_color=stroke_color, stroke_width=stroke_width, **kwargs) self.traced_point_func = traced_point_func self.dissipating_time =
|
stroke_opacity=[0, 1]) self.add(a, b) self.play(a.animate(path_arc=PI / 4).shift(LEFT * 2)) self.play(a.animate(path_arc=-PI / 4).shift(LEFT * 2)) self.wait() """ def __init__( self, traced_point_func: Callable, stroke_width: float = 2, stroke_color: ParsableManimColor | None = WHITE, dissipating_time: float | None = None, **kwargs: Any, ) -> None: super().__init__(stroke_color=stroke_color, stroke_width=stroke_width, **kwargs) self.traced_point_func = traced_point_func self.dissipating_time = dissipating_time self.time = 1.0 if self.dissipating_time else None self.add_updater(self.update_path) def update_path(self, mob: Mobject, dt: float) -> None: new_point = self.traced_point_func() if not self.has_points(): self.start_new_path(new_point) self.add_line_to(new_point) if self.dissipating_time: assert self.time is not None self.time += dt if self.time - 1 > self.dissipating_time: nppcc = self.n_points_per_curve self.set_points(self.points[nppcc:]) ================================================ FILE: manim/animation/composition.py ================================================ """Tools for displaying multiple animations at once.""" from __future__ import annotations from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING, Any import numpy as np from manim._config import config from manim.animation.animation import Animation, prepare_animation from manim.constants import RendererType from manim.mobject.mobject import Group, Mobject from manim.mobject.opengl.opengl_mobject import OpenGLGroup, OpenGLMobject from manim.scene.scene import Scene from manim.utils.iterables import remove_list_redundancies from manim.utils.parameter_parsing import flatten_iterable_parameters from manim.utils.rate_functions import linear if TYPE_CHECKING: from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVGroup from manim.mobject.types.vectorized_mobject import VGroup __all__ = ["AnimationGroup", "Succession", "LaggedStart", "LaggedStartMap"] DEFAULT_LAGGED_START_LAG_RATIO: float = 0.05 class AnimationGroup(Animation): """Plays a group or series of :class:`~.Animation`. Parameters ---------- animations Sequence of :class:`~.Animation` objects to be played. group A group of multiple :class:`~.Mobject`. run_time The duration of the animation in seconds. rate_func The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) . lag_ratio Defines the delay after which the animation is applied to submobjects. A lag_ratio of ``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played. Defaults to 0.0, meaning that all animations will be played together. This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time. """ def __init__( self, *animations: Animation | Iterable[Animation], group: Group | VGroup | OpenGLGroup | OpenGLVGroup | None = None, run_time: float | None = None, rate_func: Callable[[float], float] = linear, lag_ratio: float = 0, **kwargs: Any, ): arg_anim = flatten_iterable_parameters(animations) self.animations = [prepare_animation(anim) for anim in arg_anim] self.rate_func = rate_func if group is None: mobjects = remove_list_redundancies( [anim.mobject for anim in self.animations if not anim.is_introducer()], ) if config["renderer"] == RendererType.OPENGL: self.group: Group | VGroup | OpenGLGroup | OpenGLVGroup = OpenGLGroup( *mobjects ) else: self.group = Group(*mobjects) else: self.group = group super().__init__( self.group, rate_func=self.rate_func, lag_ratio=lag_ratio, **kwargs ) self.run_time: float = self.init_run_time(run_time) def get_all_mobjects(self) -> Sequence[Mobject | OpenGLMobject]: return list(self.group) def begin(self) -> None: if not self.animations: raise ValueError( f"Trying to play {self} without animations, this is not supported. " "Please add at least one subanimation." ) self.anim_group_time = 0.0 if self.suspend_mobject_updating: self.group.suspend_updating() for anim in self.animations: anim.begin() def _setup_scene(self, scene: Scene) -> None: for anim in self.animations: anim._setup_scene(scene) def finish(self) -> None: for anim in self.animations: anim.finish() self.anims_begun[:] = True self.anims_finished[:] = True if self.suspend_mobject_updating: self.group.resume_updating() def clean_up_from_scene(self, scene: Scene) -> None: self._on_finish(scene) for anim in self.animations: if self.remover: anim.remover = self.remover anim.clean_up_from_scene(scene) def update_mobjects(self, dt: float) -> None:
|
scene: Scene) -> None: for anim in self.animations: anim._setup_scene(scene) def finish(self) -> None: for anim in self.animations: anim.finish() self.anims_begun[:] = True self.anims_finished[:] = True if self.suspend_mobject_updating: self.group.resume_updating() def clean_up_from_scene(self, scene: Scene) -> None: self._on_finish(scene) for anim in self.animations: if self.remover: anim.remover = self.remover anim.clean_up_from_scene(scene) def update_mobjects(self, dt: float) -> None: for anim in self.anims_with_timings["anim"][ self.anims_begun & ~self.anims_finished ]: anim.update_mobjects(dt) def init_run_time(self, run_time: float | None) -> float: """Calculates the run time of the animation, if different from ``run_time``. Parameters ---------- run_time The duration of the animation in seconds. Returns ------- run_time The duration of the animation in seconds. """ self.build_animations_with_timings() # Note: if lag_ratio < 1, then not necessarily the final animation's # end time will be the max end time! Therefore we must calculate the # maximum over all the end times, and not just take the last one. # Example: if you want to play 2 animations of 10s and 1s with a # lag_ratio of 0.1, the 1st one will end at t=10 and the 2nd one will # end at t=2, so the AnimationGroup will end at t=10. self.max_end_time = max(self.anims_with_timings["end"], default=0) return self.max_end_time if run_time is None else run_time def build_animations_with_timings(self) -> None: """Creates a list of triplets of the form (anim, start_time, end_time).""" run_times = np.array([anim.run_time for anim in self.animations]) num_animations = run_times.shape[0] dtype = [("anim", "O"), ("start", "f8"), ("end", "f8")] self.anims_with_timings: np.ndarray = np.zeros(num_animations, dtype=dtype) self.anims_begun: np.ndarray = np.zeros(num_animations, dtype=bool) self.anims_finished: np.ndarray = np.zeros(num_animations, dtype=bool) if num_animations == 0: return lags = run_times[:-1] * self.lag_ratio self.anims_with_timings["anim"] = self.animations self.anims_with_timings["start"][1:] = np.add.accumulate(lags) self.anims_with_timings["end"] = self.anims_with_timings["start"] + run_times 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! anim_group_time = self.rate_func(alpha) * self.max_end_time time_goes_back = anim_group_time < self.anim_group_time # Only update ongoing animations awt = self.anims_with_timings new_begun = anim_group_time >= awt["start"] new_finished = anim_group_time > awt["end"] to_update = awt[ (self.anims_begun | new_begun) & (~self.anims_finished | ~new_finished) ] run_times = to_update["end"] - to_update["start"] with_zero_run_time = run_times == 0 run_times[with_zero_run_time] = 1 sub_alphas = (anim_group_time - to_update["start"]) / run_times if time_goes_back: sub_alphas[(sub_alphas < 0) | with_zero_run_time] = 0 else: sub_alphas[(sub_alphas > 1) | with_zero_run_time] = 1 for anim_to_update, sub_alpha in zip(to_update["anim"], sub_alphas): anim_to_update.interpolate(sub_alpha) self.anim_group_time = anim_group_time self.anims_begun = new_begun self.anims_finished = new_finished class Succession(AnimationGroup): """Plays a series of animations in succession. Parameters ---------- animations Sequence of :class:`~.Animation` objects to be played. lag_ratio Defines the delay after which the animation is applied to submobjects. A lag_ratio of ``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played. Defaults to 1.0, meaning that the next animation will begin when 100% of the current animation has played. This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time. Examples --------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.