Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Added ``skip_animations`` argument to :meth:``.Scene.next_section`` (#2236)

Christopher Besch3a8b8625c751
diff --git a/docs/source/tutorials/a_deeper_look.rst b/docs/source/tutorials/a_deeper_look.rst
index 9d5eb7e48..d70427e34 100644
--- a/docs/source/tutorials/a_deeper_look.rst
+++ b/docs/source/tutorials/a_deeper_look.rst
@@ -254,6 +254,16 @@ The JSON file in here contains some useful information for each section:
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...
+
diff --git a/manim/renderer/cairo_renderer.py b/manim/renderer/cairo_renderer.py
index 574a384de..e20406efe 100644
--- a/manim/renderer/cairo_renderer.py
+++ b/manim/renderer/cairo_renderer.py
@@ -1,5 +1,6 @@
import time
import typing
+from typing import Any
import numpy as np
@@ -30,7 +31,6 @@ class CairoRenderer:
# All of the following are set to EITHER the value passed via kwargs,
# OR the value stored in the global config dict at the time of
# _instance construction_.
- self.file_writer = None
self._file_writer_class = file_writer_class
camera_cls = camera_class if camera_class is not None else Camera
self.camera = camera_cls()
@@ -42,7 +42,7 @@ class CairoRenderer:
self.static_image = None
def init_scene(self, scene):
- self.file_writer = self._file_writer_class(
+ self.file_writer: Any = self._file_writer_class(
self,
scene.__class__.__name__,
)
@@ -232,6 +232,9 @@ class CairoRenderer:
the number of animations that need to be played, and
raises an EndSceneEarlyException if they don't correspond.
"""
+ # there is always at least one section -> no out of bounds here
+ if self.file_writer.sections[-1].skip_animations:
+ self.skip_animations = True
if config["save_last_frame"]:
self.skip_animations = True
if (
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.py
index b3b506573..523eaba6a 100644
--- a/manim/renderer/opengl_renderer.py
+++ b/manim/renderer/opengl_renderer.py
@@ -1,5 +1,6 @@
import itertools as it
import time
+from typing import Any
import moderngl
import numpy as np
@@ -239,7 +240,7 @@ class OpenGLRenderer:
def init_scene(self, scene):
self.partial_movie_files = []
- self.file_writer = self._file_writer_class(
+ self.file_writer: Any = self._file_writer_class(
self,
scene.__class__.__name__,
)
@@ -388,6 +389,9 @@ class OpenGLRenderer:
the number of animations that need to be played, and
raises an EndSceneEarlyException if they don't correspond.
"""
+ # there is always at least one section -> no out of bounds here
+ if self.file_writer.sections[-1].skip_animations:
+ self.skip_animations = True
if (
config["from_animation_number"]
and self.num_plays < config["from_animation_number"]
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index f81f5d98f..afbfa73cf 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -295,11 +295,13 @@ class Scene:
self,
name: str = "unnamed",
type: str = DefaultSectionType.NORMAL,
+ skip_animations: bool = False,
) -> None:
"""Create separation here; the last section gets finished and a new one gets created.
+ ``skip_animations`` skips the rendering of all animations in this section.
Refer to :doc:`the documentation</tutorials/a_deeper_look>` on how to use sections.
"""
- self.renderer.file_writer.next_section(name, type)
+ self.renderer.file_writer.next_section(name, type, skip_animations)
def __str__(self):
return self.__class__.__name__
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 00c6888b8..2b04e2292 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -73,7 +73,10 @@ class SceneFileWriter:
self.partial_movie_files: List[str] = []
self.sections: List[Section] = []
# first section gets automatically created for convenience
- self.next_section("autocreated", DefaultSectionType.NORMAL)
+ # if you need the first section to be skipped, add a first section by hand, it will replace this one
+ self.next_section(
+ name="autocreated", type=DefaultSectionType.NORMAL, skip_animations=False
+ )
def init_output_directories(self, scene_name):
"""Initialise output directories.
@@ -153,13 +156,19 @@ class SceneFileWriter:
if len(self.sections) and self.sections[-1].is_empty():
self.sections.pop()
- def next_section(self, name: str, type: str) -> None:
+ def next_section(self, name: str, type: str, skip_animations: bool) -> None:
"""Create segmentation cut here."""
self.finish_last_section()
# images don't support sections
section_video: Optional[str] = None
- if not config.dry_run and write_to_movie() and config.save_sections:
+ # don't save when None
+ if (
+ not config.dry_run
+ and write_to_movie()
+ and config.save_sections
+ and not skip_animations
+ ):
# relative to index file
section_video = f"{self.output_name}_{len(self.sections):04}{config.movie_file_extension}"
@@ -168,6 +177,7 @@ class SceneFileWriter:
type,
section_video,
name,
+ skip_animations,
),
)
@@ -660,10 +670,10 @@ class SceneFileWriter:
os.path.join(self.sections_output_dir, section.video),
)
sections_index.append(section.get_dict(self.sections_output_dir))
- with open(
- os.path.join(self.sections_output_dir, f"{self.output_name}.json"), "w"
- ) as file:
- json.dump(sections_index, file, indent=4)
+ with open(
+ os.path.join(self.sections_output_dir, f"{self.output_name}.json"), "w"
+ ) as file:
+ json.dump(sections_index, file, indent=4)
def clean_cache(self):
"""Will clean the cache by removing the oldest partial_movie_files."""
diff --git a/manim/scene/section.py b/manim/scene/section.py
index 8a179ac17..62c9fb1b3 100644
--- a/manim/scene/section.py
+++ b/manim/scene/section.py
@@ -38,24 +38,31 @@ class Section:
----------
type
Can be used by a third party applications to classify different types of sections.
+ video
+ Path to video file with animations belonging to section relative to sections directory.
+ If ``None``, then the section will not be saved.
name
Human readable, non-unique name for this section.
+ skip_animations
+ Skip rendering the animations in this section when ``True``.
partial_movie_files
Animations belonging to this section.
- video
- Path to video file with animations belonging to section relative to sections directory.
- If ``None``, then the section will not be saved.
See Also
--------
:class:`.DefaultSectionType`
+ :meth:`.CairoRenderer.update_skipping_status`
+ :meth:`.OpenGLRenderer.update_skipping_status`
"""
- def __init__(self, type: str, video: Optional[str], name: str):
+ def __init__(
+ self, type: str, video: Optional[str], name: str, skip_animations: bool
+ ):
self.type = type
# None when not to be saved -> still keeps section alive
self.video: Optional[str] = video
self.name = name
+ self.skip_animations = skip_animations
self.partial_movie_files: List[Optional[str]] = []
def is_empty(self) -> bool:
diff --git a/tests/control_data/videos_data/SceneWithSections.json b/tests/control_data/videos_data/SceneWithSections.json
index 4b56d518e..289558d2c 100644
--- a/tests/control_data/videos_data/SceneWithSections.json
+++ b/tests/control_data/videos_data/SceneWithSections.json
@@ -9,11 +9,11 @@
"nb_frames": "105"
},
"section_dir_layout": [
+ "SceneWithSections.json",
"SceneWithSections_0004.mp4",
"SceneWithSections_0003.mp4",
"SceneWithSections_0002.mp4",
"SceneWithSections_0001.mp4",
- "SceneWithSections.json",
"SceneWithSections_0000.mp4",
"."
],
diff --git a/tests/control_data/videos_data/SceneWithSkipAnimations.json b/tests/control_data/videos_data/SceneWithSkipAnimations.json
new file mode 100644
index 000000000..2dbb670d8
--- /dev/null
+++ b/tests/control_data/videos_data/SceneWithSkipAnimations.json
@@ -0,0 +1,53 @@
+{
+ "name": "SceneWithSkipAnimations",
+ "movie_metadata": {
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "6.000000",
+ "nb_frames": "90"
+ },
+ "section_dir_layout": [
+ "ElaborateSceneWithSections.json",
+ "ElaborateSceneWithSections_0003.mp4",
+ "ElaborateSceneWithSections_0001.mp4",
+ "ElaborateSceneWithSections_0000.mp4",
+ "."
+ ],
+ "section_index": [
+ {
+ "name": "create square",
+ "type": "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_0003.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ }
+ ]
+}
diff --git a/tests/test_graphical_units/testing/_test_class_makers.py b/tests/test_graphical_units/testing/_test_class_makers.py
index 7d70fb958..771cb84c7 100644
--- a/tests/test_graphical_units/testing/_test_class_makers.py
+++ b/tests/test_graphical_units/testing/_test_class_makers.py
@@ -44,9 +44,6 @@ class DummySceneFileWriter(SceneFileWriter):
def init_output_directories(self, scene_name):
pass
- def next_section(self, type, name=None):
- pass
-
def add_partial_movie_file(self, hash_animation):
pass
diff --git a/tests/test_scene_rendering/simple_scenes.py b/tests/test_scene_rendering/simple_scenes.py
index a92423b3e..1b84e6f24 100644
--- a/tests/test_scene_rendering/simple_scenes.py
+++ b/tests/test_scene_rendering/simple_scenes.py
@@ -111,6 +111,12 @@ class ElaborateSceneWithSections(Scene):
self.play(Transform(square, circle))
self.wait()
+ # this section will be entirely skipped
+ self.next_section("skipped animations section", skip_animations=True)
+ circle = Circle()
+ self.play(Transform(square, circle))
+ self.wait()
+
self.next_section("fade out")
self.play(FadeOut(square))
self.wait()
diff --git a/tests/test_scene_rendering/test_play_logic.py b/tests/test_scene_rendering/test_play_logic.py
index a116b46cf..66572d39b 100644
--- a/tests/test_scene_rendering/test_play_logic.py
+++ b/tests/test_scene_rendering/test_play_logic.py
@@ -73,6 +73,7 @@ def test_t_values_with_cached_data(using_temp_config):
scene = SceneWithMultipleCalls()
# Mocking the file_writer will skip all the writing process.
scene.renderer.file_writer = Mock(scene.renderer.file_writer)
+ scene.renderer.update_skipping_status = Mock()
# Simulate that all animations are cached.
scene.renderer.file_writer.is_already_cached.return_value = True
scene.update_to_time = Mock()
diff --git a/tests/test_scene_rendering/test_sections.py b/tests/test_scene_rendering/test_sections.py
index 559e9c906..fb0044e9d 100644
--- a/tests/test_scene_rendering/test_sections.py
+++ b/tests/test_scene_rendering/test_sections.py
@@ -80,3 +80,25 @@ def test_many_sections(tmp_path, manim_cfg_file, simple_scenes_path):
]
_, err, exit_code = capture(command)
assert exit_code == 0, err
+
+
+@video_comparison(
+ "SceneWithSkipAnimations.json",
+ "videos/simple_scenes/480p15/ElaborateSceneWithSections.mp4",
+)
+def test_skip_animations(tmp_path, manim_cfg_file, simple_scenes_path):
+ scene_name = "ElaborateSceneWithSections"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--save_sections",
+ "--media_dir",
+ str(tmp_path),
+ simple_scenes_path,
+ scene_name,
+ ]
+ _, err, exit_code = capture(command)
+ assert exit_code == 0, err