Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Render videos while building documentation (#402)

Benjamin Hackl9c511502cc44
diff --git a/.readthedocs.yml b/.readthedocs.yml
new file mode 100644
index 000000000..fd96762ec
--- /dev/null
+++ b/.readthedocs.yml
@@ -0,0 +1,9 @@
+version: 2
+
+python:
+ version: 3.8
+ install:
+ - requirements: docs/rtd-requirements.txt
+ - requirements: docs/requirements.txt
+ - method: pip
+ path: .
diff --git a/docs/Makefile b/docs/Makefile
index 6e40bd731..1f5f413c9 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -14,10 +14,11 @@ help:
.PHONY: help Makefile
-# Like make clean but also remove files generated by autosummary
-cleanall:
- make clean
+# Like make clean but also remove files generated by autosummary and
+# rendered videos.
+cleanall: clean
rm source/reference/*
+ rm -rf source/media
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
diff --git a/docs/rtd-requirements.txt b/docs/rtd-requirements.txt
new file mode 100644
index 000000000..e46f52fd3
--- /dev/null
+++ b/docs/rtd-requirements.txt
@@ -0,0 +1 @@
+imageio-ffmpeg
diff --git a/docs/source/_static/custom.css b/docs/source/_static/custom.css
index 5dd7e814a..756de725c 100644
--- a/docs/source/_static/custom.css
+++ b/docs/source/_static/custom.css
@@ -7,3 +7,20 @@ img.align-center {
margin-bottom: 20px;
margin-top: 20px;
}
+
+.manim-video {
+ width: 100%;
+}
+
+.manim-example pre {
+ border-left: none;
+ margin: 0;
+ padding: 0 0 14px 0;
+}
+
+.manim-example {
+ border-left: 2px solid #eee;
+ border-radius: 4px;
+ padding: 14px 0 14px 20px;
+ margin: 20px 0;
+}
diff --git a/docs/source/_static/quickstart/first_scene.gif b/docs/source/_static/quickstart/first_scene.gif
deleted file mode 100644
index c23d42b29..000000000
Binary files a/docs/source/_static/quickstart/first_scene.gif and /dev/null differ
diff --git a/docs/source/_static/quickstart/high_quality.gif b/docs/source/_static/quickstart/high_quality.gif
deleted file mode 100644
index 60a48a6c0..000000000
Binary files a/docs/source/_static/quickstart/high_quality.gif and /dev/null differ
diff --git a/docs/source/_static/quickstart/second_scene.gif b/docs/source/_static/quickstart/second_scene.gif
deleted file mode 100644
index abefa7e3e..000000000
Binary files a/docs/source/_static/quickstart/second_scene.gif and /dev/null differ
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 0d9edc393..017ae0c05 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -9,10 +9,27 @@
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
-#
-# import os
-# import sys
-# sys.path.insert(0, os.path.abspath('.'))
+
+import os
+import sys
+from distutils.sysconfig import get_python_lib
+
+
+sys.path.insert(0, os.path.abspath("."))
+
+
+if os.environ.get("READTHEDOCS") == "True":
+ # we need to add ffmpeg to the path
+ site_path = get_python_lib()
+ ffmpeg_path = os.path.join(site_path, "imageio_ffmpeg", "binaries")
+ # the included binary is named ffmpeg-linux..., create a symlink
+ [ffmpeg_bin] = [
+ file for file in os.listdir(ffmpeg_path) if file.startswith("ffmpeg-")
+ ]
+ os.symlink(
+ os.path.join(ffmpeg_path, ffmpeg_bin), os.path.join(ffmpeg_path, "ffmpeg")
+ )
+ os.environ["PATH"] += os.pathsep + ffmpeg_path
# -- Project information -----------------------------------------------------
@@ -33,6 +50,7 @@ extensions = [
"sphinx.ext.napoleon",
"sphinx.ext.autosummary",
"sphinx.ext.doctest",
+ "manim_directive",
]
# Automatically generate stub pages when using the .. autosummary directive
@@ -68,7 +86,7 @@ extensions.append("guzzle_sphinx_theme")
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
+html_static_path = ["_static"]
# This specifies any additional css files that will override the theme's
-html_css_files = ['custom.css']
+html_css_files = ["custom.css"]
diff --git a/docs/source/manim_directive.py b/docs/source/manim_directive.py
new file mode 100644
index 000000000..484774b62
--- /dev/null
+++ b/docs/source/manim_directive.py
@@ -0,0 +1,244 @@
+r"""
+A directive for including Manim videos in a Sphinx document
+===========================================================
+
+When rendering the HTML documentation, the ``.. manim::`` directive
+implemented here allows to include rendered videos.
+
+Its basic usage that allows processing **inline content**
+looks as follows::
+
+ .. manim:: MyScene
+
+ class MyScene(Scene):
+ def construct(self):
+ ...
+
+It is required to pass the name of the class representing the
+scene to be rendered to the directive.
+
+As a second application, the directive can also be used to
+render scenes that are defined within doctests, for example::
+
+ .. manim:: DirectiveDoctestExample
+
+ >>> dot = Dot(color=RED)
+ >>> dot.color
+ <Color #fc6255>
+ >>> class DirectiveDoctestExample(Scene):
+ ... def construct(self):
+ ... self.play(ShowCreation(dot))
+
+
+Options
+-------
+
+Options can be passed as follows::
+
+ .. manim:: <Class name>
+ :<option name>: <value>
+
+The following configuration options are supported by the
+directive:
+
+ display_source
+ If this flag is present without argument,
+ the source code is displayed above the rendered video.
+
+ quality : {'low', 'medium', 'high', 'fourk'}
+ Controls render quality of the video, in analogy to
+ the corresponding command line flags.
+
+ save_as_gif
+ If this flag is present without argument,
+ the scene is rendered as a gif.
+
+ save_last_frame
+ If this flag is present without argument,
+ an image representing the last frame of the scene will
+ be rendered and displayed, instead of a video.
+
+"""
+from docutils.parsers.rst import directives, Directive
+from docutils.parsers.rst.directives.images import Image
+
+import jinja2
+import os
+from os.path import relpath
+
+import shutil
+
+
+class ManimDirective(Directive):
+ r"""The ``.. manim::`` directive.
+
+ See the module docstring for documentation.
+ """
+ has_content = True
+ required_arguments = 1
+ optional_arguments = 0
+ option_spec = {
+ "display_source": bool,
+ "quality": lambda arg: directives.choice(
+ arg, ("low", "medium", "high", "fourk")
+ ),
+ "save_as_gif": bool,
+ "save_last_frame": bool,
+ }
+ final_argument_whitespace = True
+
+ def run(self):
+ from manim import config
+
+ clsname = self.arguments[0]
+
+ display_source = "display_source" in self.options
+ save_as_gif = "save_as_gif" in self.options
+ save_last_frame = "save_last_frame" in self.options
+ assert not (save_as_gif and save_last_frame)
+
+ frame_rate = config["frame_rate"]
+ pixel_height = config["pixel_height"]
+ pixel_width = config["pixel_width"]
+
+ if "quality" in self.options:
+ quality = self.options["quality"]
+ if quality == "low":
+ pixel_height = 480
+ pixel_width = 854
+ frame_rate = 15
+ elif quality == "medium":
+ pixel_height = 720
+ pixel_width = 1280
+ frame_rate = 30
+ elif quality == "high":
+ pixel_height = 1440
+ pixel_width = 2560
+ frame_rate = 60
+ elif quality == "fourk":
+ pixel_height = 2160
+ pixel_width = 3840
+ frame_rate = 60
+
+ qualitydir = f"{pixel_height}p{frame_rate}"
+
+ state_machine = self.state_machine
+ document = state_machine.document
+
+ source_file_name = document.attributes["source"]
+ source_rel_name = relpath(source_file_name, setup.confdir)
+ source_rel_dir = os.path.dirname(source_rel_name)
+ while source_rel_dir.startswith(os.path.sep):
+ source_rel_dir = source_rel_dir[1:]
+
+ dest_dir = os.path.abspath(
+ os.path.join(setup.app.builder.outdir, source_rel_dir)
+ )
+ if not os.path.exists(dest_dir):
+ os.makedirs(dest_dir)
+
+ source_block = [
+ ".. code-block:: python",
+ "",
+ *[" " + line for line in self.content],
+ ]
+ source_block = "\n".join(source_block)
+
+ media_dir = os.path.join("source", "media")
+ images_dir = os.path.join(media_dir, "images")
+ video_dir = os.path.join(media_dir, "videos")
+
+ file_writer_config_code = [
+ f'config["frame_rate"] = {frame_rate}',
+ f'config["pixel_height"] = {pixel_height}',
+ f'config["pixel_width"] = {pixel_width}',
+ f'file_writer_config["media_dir"] = "{media_dir}"',
+ f'file_writer_config["images_dir"] = "{images_dir}"',
+ f'file_writer_config["video_dir"] = "{video_dir}"',
+ f'file_writer_config["save_last_frame"] = {save_last_frame}',
+ f'file_writer_config["save_as_gif"] = {save_as_gif}',
+ ]
+
+ user_code = self.content
+ if user_code[0].startswith(">>> "): # check whether block comes from doctest
+ user_code = [
+ line[4:] for line in user_code if line.startswith((">>> ", "... "))
+ ]
+
+ code = [
+ "from manim import *",
+ *file_writer_config_code,
+ *user_code,
+ f"{clsname}()",
+ ]
+ exec("\n".join(code), globals())
+
+ # copy video file to output directory
+ if not (save_as_gif or save_last_frame):
+ filename = f"{clsname}.mp4"
+ filesrc = os.path.join(video_dir, qualitydir, filename)
+ destfile = os.path.join(dest_dir, filename)
+ shutil.copyfile(filesrc, destfile)
+ elif save_as_gif:
+ filename = f"{clsname}.gif"
+ filesrc = os.path.join(video_dir, qualitydir, filename)
+ elif save_last_frame:
+ filename = f"{clsname}.png"
+ filesrc = os.path.join(images_dir, filename)
+ else:
+ raise ValueError("Invalid combination of render flags received.")
+
+ rendered_template = jinja2.Template(TEMPLATE).render(
+ clsname=clsname,
+ display_source=display_source,
+ filesrc=filesrc[6:],
+ save_last_frame=save_last_frame,
+ save_as_gif=save_as_gif,
+ source_block=source_block,
+ )
+ state_machine.insert_input(
+ rendered_template.split("\n"), source=document.attributes["source"]
+ )
+
+ return []
+
+
+def setup(app):
+ import manim
+
+ setup.app = app
+ setup.config = app.config
+ setup.confdir = app.confdir
+ app.add_directive("manim", ManimDirective)
+
+ metadata = {"parallel_read_safe": True, "parallel_write_safe": True}
+ return metadata
+
+
+TEMPLATE = r"""
+{% if display_source %}
+.. raw:: html
+
+ <div class="manim-example">
+
+{{ source_block }}
+{% endif %}
+
+{% if not (save_as_gif or save_last_frame) %}
+.. raw:: html
+
+ <video class="manim-video" controls loop autoplay src="./{{ clsname }}.mp4"></video>
+{% elif save_as_gif %}
+.. image:: {{ filesrc }}
+ :align: center
+{% elif save_last_frame %}
+.. image:: {{ filesrc }}
+ :align: center
+{% endif %}
+
+{% if display_source %}
+.. raw:: html
+
+ </div>
+{% endif %}
+"""
diff --git a/docs/source/tutorials/a_deeper_look.rst b/docs/source/tutorials/a_deeper_look.rst
index 8bb6e8014..f942f30dd 100644
--- a/docs/source/tutorials/a_deeper_look.rst
+++ b/docs/source/tutorials/a_deeper_look.rst
@@ -64,9 +64,21 @@ 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:
-.. image:: ../_static/quickstart/high_quality.gif
- :align: center
- :alt: high quality scene output
+.. manim:: SquareToCircle3
+ :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(ShowCreation(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.
diff --git a/docs/source/tutorials/quickstart.rst b/docs/source/tutorials/quickstart.rst
index 672b3bf93..8ac7a42ab 100644
--- a/docs/source/tutorials/quickstart.rst
+++ b/docs/source/tutorials/quickstart.rst
@@ -59,9 +59,14 @@ After showing some output, manim should render the scene into a .mp4 file,
and open that file with the default movie player application. You should see a
video playing the following animation.
-.. image:: ../_static/quickstart/first_scene.gif
- :align: center
- :alt: first scene output
+.. manim:: SquareToCircle
+ :quality: low
+
+ class SquareToCircle(Scene):
+ def construct(self):
+ circle = Circle() # create a circle
+ circle.set_fill(PINK, opacity=0.5) # set the color and transparency
+ self.play(ShowCreation(circle)) # show the circle on screen
If you see the video and it looks correct, congrats! You just wrote your first
manim scene from scratch. If you get an error message instead, or if do not
@@ -101,9 +106,21 @@ And render it using the following command:
The output should look as follows.
-.. image:: ../_static/quickstart/second_scene.gif
- :align: center
- :alt: second scene output
+.. manim:: SquareToCircle2
+ :quality: low
+
+ 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.flip(RIGHT) # flip horizontally
+ square.rotate(-3 * TAU / 8) # rotate a certain amount
+
+ self.play(ShowCreation(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 most basic features of manim: the ability to
implement complicated and mathematically-intensive animations (such as cleanly
diff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.py
index 989338430..a2ad4d1fd 100644
--- a/manim/mobject/geometry.py
+++ b/manim/mobject/geometry.py
@@ -892,17 +892,24 @@ class ArrowTip(VMobject):
NotImplementedError: Has to be implemented in inheriting subclasses.
Instead, use one of the pre-defined ones, or make
- a custom one like this::
+ a custom one like this:
+
+ .. manim:: CustomTipExample
+ :display_source:
>>> class MyCustomArrowTip(ArrowTip, RegularPolygon):
... def __init__(self, **kwargs):
... RegularPolygon.__init__(self, n=5, **kwargs)
... self.set_width(self.length)
... self.set_height(self.length, stretch=True)
- >>> arr = Arrow(np.array([0, 0, 0]), np.array([1, 1, 0]),
+ >>> arr = Arrow(np.array([-2, -2, 0]), np.array([2, 2, 0]),
... tip_shape=MyCustomArrowTip)
>>> isinstance(arr.tip, RegularPolygon)
True
+ >>> from manim import Scene
+ >>> class CustomTipExample(Scene):
+ ... def construct(self):
+ ... self.play(ShowCreation(arr))
Using a class inherited from :class:`ArrowTip` to get a non-filled
tip is a shorthand to manually specifying the arrow tip style as follows::
diff --git a/manim/utils/hashing.py b/manim/utils/hashing.py
index 1cdacab0e..e17e979d9 100644
--- a/manim/utils/hashing.py
+++ b/manim/utils/hashing.py
@@ -41,9 +41,15 @@ class CustomEncoder(json.JSONEncoder):
# NOTE : All module types objects are removed, because otherwise it throws ValueError: Circular reference detected if not. TODO
if isinstance(cvardict[i], ModuleType):
del cvardict[i]
- return self._check_iterable(
- {"code": inspect.getsource(obj), "nonlocals": cvardict}
- )
+ try:
+ code = inspect.getsource(obj)
+ except OSError:
+ # This happens when rendering videos included in the documentation
+ # within doctests and should be replaced by a solution avoiding
+ # hash collision (due to the same, empty, code strings) at some point.
+ # See https://github.com/ManimCommunity/manim/pull/402.
+ code = ""
+ return self._check_iterable({"code": code, "nonlocals": cvardict})
elif isinstance(obj, np.ndarray):
if obj.size > 1000:
obj = np.resize(obj, (100, 100))