A community-maintained Python framework for creating mathematical animations.
Move more stuff out of Scene
Devin Nealc74256ce2f4f
diff --git a/manim/renderer/cairo_renderer.py b/manim/renderer/cairo_renderer.pyindex b3696c40a..97a42931c 100644--- a/manim/renderer/cairo_renderer.py+++ b/manim/renderer/cairo_renderer.py@@ -1,14 +1,108 @@import numpy as np-from .. import file_writer_config+from .. import camera_config, file_writer_config, loggerfrom ..utils.iterables import list_updatefrom ..utils.exceptions import EndSceneEarlyException+from ..utils.hashing import get_hash_from_play_call, get_hash_from_wait_call+from ..constants import DEFAULT_WAIT_TIME+++def handle_caching_play(func):+ """+ Decorator that returns a wrapped version of func that will compute the hash of the play invocation.++ The returned function will act according to the computed hash: either skip the animation because it's already cached, or let the invoked function play normally.++ Parameters+ ----------+ func : Callable[[...], None]+ The play like function that has to be written to the video file stream. Take the same parameters as `scene.play`.+ """++ def wrapper(self, *args, **kwargs):+ self.revert_to_original_skipping_status()+ self.update_skipping_status()+ animations = self.scene.compile_play_args_to_animation_list(*args, **kwargs)+ self.scene.add_mobjects_from_animations(animations)+ if file_writer_config["skip_animations"]:+ logger.debug(f"Skipping animation {self.num_plays}")+ func(self, *args, **kwargs)+ return+ if not file_writer_config["disable_caching"]:+ mobjects_on_scene = self.scene.get_mobjects()+ hash_play = get_hash_from_play_call(+ self, self.camera, animations, mobjects_on_scene+ )+ self.play_hashes_list.append(hash_play)+ if self.file_writer.is_already_cached(hash_play):+ logger.info(+ f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)",+ {"hash_play": hash_play},+ )+ file_writer_config["skip_animations"] = True+ else:+ hash_play = "uncached_{:05}".format(self.num_plays)+ self.play_hashes_list.append(hash_play)+ func(self, *args, **kwargs)++ return wrapper+++def handle_play_like_call(func):+ """+ This method is used internally to wrap the+ passed function, into a function that+ actually writes to the video stream.+ Simultaneously, it also adds to the number+ of animations played.++ Parameters+ ----------+ func : function+ The play() like function that has to be+ written to the video file stream.++ Returns+ -------+ function+ The play() like function that can now write+ to the video file stream.+ """++ def wrapper(self, *args, **kwargs):+ allow_write = not file_writer_config["skip_animations"]+ self.file_writer.begin_animation(allow_write)+ func(self, *args, **kwargs)+ self.file_writer.end_animation(allow_write)+ self.num_plays += 1++ return wrapperclass CairoRenderer:+ """A renderer using Cairo.++ num_plays : Number of play() functions in the scene.+ time: time elapsed since initialisation of scene.+ """+def __init__(self, scene, camera, file_writer):- self.scene = sceneself.camera = cameraself.file_writer = file_writer+ self.scene = scene+ self.original_skipping_status = file_writer_config["skip_animations"]+ self.play_hashes_list = []+ self.num_plays = 0+ self.time = 0++ @handle_caching_play+ @handle_play_like_call+ def play(self, *args, **kwargs):+ self.scene.play_internal(*args, **kwargs)++ @handle_caching_play+ @handle_play_like_call+ def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):+ self.scene.wait_internal(duration=duration, stop_condition=stop_condition)def update_frame( # TODO Description in Docstringself,@@ -74,12 +168,20 @@ class CairoRenderer:The number of times to add frame."""dt = 1 / self.camera.frame_rate- self.scene.increment_time(num_frames * dt)+ self.time += num_frames * dtif file_writer_config["skip_animations"]:returnfor _ in range(num_frames):self.file_writer.write_frame(frame)+ def show_frame(self):+ """+ Opens the current frame in the Default Image Viewer+ of your system.+ """+ self.update_frame(ignore_skipping=True)+ self.camera.get_image().show()+def update_skipping_status(self):"""This method is used internally to check if the current@@ -89,17 +191,29 @@ class CairoRenderer:raises an EndSceneEarlyException if they don't correspond."""if file_writer_config["from_animation_number"]:- if self.scene.num_plays < file_writer_config["from_animation_number"]:+ if self.num_plays < file_writer_config["from_animation_number"]:file_writer_config["skip_animations"] = Trueif file_writer_config["upto_animation_number"]:- if self.scene.num_plays > file_writer_config["upto_animation_number"]:+ if self.num_plays > file_writer_config["upto_animation_number"]:file_writer_config["skip_animations"] = Trueraise EndSceneEarlyException()- def show_frame(self):+ def revert_to_original_skipping_status(self):"""- Opens the current frame in the Default Image Viewer- of your system.+ Forces the scene to go back to its original skipping status,+ by setting skip_animations to whatever it reads+ from original_skipping_status.++ Returns+ -------+ Scene+ The Scene, with the original skipping status."""- self.update_frame(ignore_skipping=True)- self.camera.get_image().show()+ if hasattr(self, "original_skipping_status"):+ file_writer_config["skip_animations"] = self.original_skipping_status+ return self++ def finish(self):+ file_writer_config["skip_animations"] = False+ self.file_writer.finish()+ logger.info(f"Rendered {str(self.scene)}\nPlayed {self.num_plays} animations")diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 0fff2f3c1..458dd2cd2 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -52,8 +52,6 @@ class Scene(Container):file_writer : The object that writes the animations in the scene to a video file.mobjects : The list of mobjects present in the scene.foreground_mobjects : List of mobjects explicitly in the foreground.- num_plays : Number of play() functions in the scene.- time: time elapsed since initialisation of scene.random_seed: The seed with which all random operations are done."""@@ -73,15 +71,10 @@ class Scene(Container):**file_writer_config,)self.renderer = CairoRenderer(self, self.camera, self.file_writer)- self.play_hashes_list = []self.mobjects = []- self.original_skipping_status = file_writer_config["skip_animations"]# TODO, remove need for foreground mobjectsself.foreground_mobjects = []- self.num_plays = 0- self.time = 0- self.original_skipping_status = file_writer_config["skip_animations"]if self.random_seed is not None:random.seed(self.random_seed)np.random.seed(self.random_seed)@@ -96,13 +89,8 @@ class Scene(Container):self.construct()except EndSceneEarlyException:pass-self.tear_down()- # We have to reset these settings in case of multiple renders.- file_writer_config["skip_animations"] = False-- self.file_writer.finish()- self.print_end_message()+ self.renderer.finish()def setup(self):"""@@ -130,15 +118,6 @@ class Scene(Container):def __str__(self):return self.__class__.__name__- def print_end_message(self):- """- Used internally to print the number of- animations played after the scene ends,- as well as the name of the scene rendered- (useful when using the `-a` option).- """- logger.info(f"Rendered {str(self)}\nPlayed {self.num_plays} animations")-def set_variables_as_attrs(self, *objects, **newly_named_objects):"""This method is slightly hacky, making it a little easier@@ -199,18 +178,6 @@ class Scene(Container):###- def increment_time(self, d_time):- """- Increments the time elapsed after intialisation of scene by- passed "d_time".-- Parameters- ----------- d_time : int or float- Time in seconds to increment by.- """- self.time += d_time-###def get_top_level_mobjects(self):@@ -646,7 +613,7 @@ class Scene(Container):time_progression.set_description("".join([- "Animation {}: ".format(self.num_plays),+ "Animation {}: ".format(self.renderer.num_plays),str(animations[0]),(", etc." if len(animations) > 1 else ""),]@@ -799,66 +766,10 @@ class Scene(Container):self.update_mobjects(0)def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):- self.play(duration=duration, stop_condition=stop_condition)+ self.renderer.wait(duration=duration, stop_condition=stop_condition)def play(self, *args, **kwargs):- self.cached_play(*args, **kwargs)- self.num_plays += 1-- def revert_to_original_skipping_status(self):- """- Forces the scene to go back to its original skipping status,- by setting skip_animations to whatever it reads- from original_skipping_status.-- Returns- -------- Scene- The Scene, with the original skipping status.- """- if hasattr(self, "original_skipping_status"):- file_writer_config["skip_animations"] = self.original_skipping_status- return self-- def cached_play(self, *args, **kwargs):- self.revert_to_original_skipping_status()- self.renderer.update_skipping_status()- animations = self.compile_play_args_to_animation_list(*args, **kwargs)- self.add_mobjects_from_animations(animations)- if file_writer_config["skip_animations"]:- logger.debug(f"Skipping animation {self.num_plays}")- self.file_writer_wrapped_play(*args, **kwargs)- return- if not file_writer_config["disable_caching"]:- mobjects_on_scene = self.get_mobjects()- hash_play = get_hash_from_play_call(- self, self.camera, animations, mobjects_on_scene- )- self.play_hashes_list.append(hash_play)- if self.file_writer.is_already_cached(hash_play):- logger.info(- f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)",- {"hash_play": hash_play},- )- file_writer_config["skip_animations"] = True- else:- hash_play = "uncached_{:05}".format(self.num_plays)- self.play_hashes_list.append(hash_play)- self.file_writer_wrapped_play(*args, **kwargs)-- def file_writer_wrapped_play(self, *args, **kwargs):- allow_write = not file_writer_config["skip_animations"]- self.file_writer.begin_animation(allow_write)-- self.play_or_wait(*args, **kwargs)-- self.file_writer.end_animation(allow_write)-- def play_or_wait(self, *args, **kwargs):- if "duration" in kwargs:- self.wait_internal(**kwargs)- else:- self.play_internal(*args, **kwargs)+ self.renderer.play(*args, **kwargs)def play_internal(self, *args, **kwargs):"""@@ -969,7 +880,9 @@ class Scene(Container):)else:time_progression = self.get_time_progression(duration)- time_progression.set_description("Waiting {}".format(self.num_plays))+ time_progression.set_description(+ "Waiting {}".format(self.renderer.num_plays)+ )return time_progressiondef wait_until(self, stop_condition, max_time=60):diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex bbe86b609..4c269a368 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -202,7 +202,7 @@ class SceneFileWriter(object):result = os.path.join(self.partial_movie_directory,"{}{}".format(- self.scene.play_hashes_list[self.index_partial_movie_file],+ self.scene.renderer.play_hashes_list[self.index_partial_movie_file],file_writer_config["movie_file_extension"],),)@@ -461,7 +461,7 @@ class SceneFileWriter(object):self.partial_movie_file_path,)logger.info(- f"Animation {self.scene.num_plays} : Partial movie file written in %(path)s",+ f"Animation {self.scene.renderer.num_plays} : Partial movie file written in %(path)s",{"path": {self.partial_movie_file_path}},)@@ -502,7 +502,7 @@ class SceneFileWriter(object):self.partial_movie_directory,"{}{}".format(hash_play, file_writer_config["movie_file_extension"]),)- for hash_play in self.scene.play_hashes_list+ for hash_play in self.scene.renderer.play_hashes_list]if len(partial_movie_files) == 0:logger.error("No animations in this scene")diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txtindex e7595ef9b..c0ae14ac5 100644--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt@@ -3,4 +3,4 @@{"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."}{"levelname": "INFO", "module": "scene_file_writer", "message": "Animation 0 : Partial movie file written in <>"}{"levelname": "INFO", "module": "scene_file_writer", "message": "\nFile ready at <>\n"}-{"levelname": "INFO", "module": "scene", "message": "Rendered SquareToCircle\nPlayed 1 animations"}+{"levelname": "INFO", "module": "cairo_renderer", "message": "Rendered SquareToCircle\nPlayed 1 animations"}