Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

split config into two dicts

leotrs32f72a0d5931
diff --git a/example_scenes/basic.py b/example_scenes/basic.py
index 84f1e2b53..7d6f04c43 100644
--- a/example_scenes/basic.py
+++ b/example_scenes/basic.py
@@ -106,7 +106,7 @@ class WriteStuff(Scene):
)
group = VGroup(example_text, example_tex)
group.arrange(DOWN)
- group.set_width(FRAME_WIDTH - 2 * LARGE_BUFF)
+ group.set_width(config['frame_width'] - 2 * LARGE_BUFF)
self.play(Write(example_text))
self.play(Write(example_tex))
diff --git a/manim/__main__.py b/manim/__main__.py
index b14c2cad6..59d1529d3 100644
--- a/manim/__main__.py
+++ b/manim/__main__.py
@@ -1,12 +1,178 @@
-from .config import initialize_tex, config
-from . import extract_scene
+import inspect
+import itertools as it
+import os
+import platform
+import subprocess as sp
+import sys
+import traceback
+import importlib.util
+
+from .config import file_writer_config
+from .scene.scene import Scene
+from .utils.sounds import play_error_sound
+from .utils.sounds import play_finish_sound
from . import constants
+from .logger import logger
+
+
+def open_file_if_needed(file_writer):
+ if file_writer_config["quiet"]:
+ curr_stdout = sys.stdout
+ sys.stdout = open(os.devnull, "w")
+
+ open_file = any([
+ file_writer_config["preview"],
+ file_writer_config["show_file_in_finder"]
+ ])
+ if open_file:
+ current_os = platform.system()
+ file_paths = []
+
+ if file_writer_config["save_last_frame"]:
+ file_paths.append(file_writer.get_image_file_path())
+ if file_writer_config["write_to_movie"]:
+ file_paths.append(file_writer.get_movie_file_path())
+
+ for file_path in file_paths:
+ if current_os == "Windows":
+ os.startfile(file_path)
+ else:
+ commands = []
+ if current_os == "Linux":
+ commands.append("xdg-open")
+ elif current_os.startswith("CYGWIN"):
+ commands.append("cygstart")
+ else: # Assume macOS
+ commands.append("open")
+
+ if file_writer_config["show_file_in_finder"]:
+ commands.append("-R")
+
+ commands.append(file_path)
+
+ # commands.append("-g")
+ FNULL = open(os.devnull, 'w')
+ sp.call(commands, stdout=FNULL, stderr=sp.STDOUT)
+ FNULL.close()
+
+ if file_writer_config["quiet"]:
+ sys.stdout.close()
+ sys.stdout = curr_stdout
+
+
+def is_child_scene(obj, module):
+ if not inspect.isclass(obj):
+ return False
+ if not issubclass(obj, Scene):
+ return False
+ if obj == Scene:
+ return False
+ if not obj.__module__.startswith(module.__name__):
+ return False
+ return True
+
+
+def prompt_user_for_choice(scene_classes):
+ num_to_class = {}
+ for count, scene_class in zip(it.count(1), scene_classes):
+ name = scene_class.__name__
+ print("%d: %s" % (count, name))
+ num_to_class[count] = scene_class
+ try:
+ user_input = input(constants.CHOOSE_NUMBER_MESSAGE)
+ return [
+ num_to_class[int(num_str)]
+ for num_str in user_input.split(",")
+ ]
+ except KeyError:
+ logger.error(constants.INVALID_NUMBER_MESSAGE)
+ sys.exit(2)
+ user_input = input(constants.CHOOSE_NUMBER_MESSAGE)
+ return [
+ num_to_class[int(num_str)]
+ for num_str in user_input.split(",")
+ ]
+ except EOFError:
+ sys.exit(1)
+
+
+def get_scenes_to_render(scene_classes):
+ if not scene_classes:
+ logger.error(constants.NO_SCENE_MESSAGE)
+ return []
+ if file_writer_config["write_all"]:
+ return scene_classes
+ result = []
+ for scene_name in file_writer_config["scene_names"]:
+ found = False
+ for scene_class in scene_classes:
+ if scene_class.__name__ == scene_name:
+ result.append(scene_class)
+ found = True
+ break
+ if not found and (scene_name != ""):
+ logger.error(
+ constants.SCENE_NOT_FOUND_MESSAGE.format(
+ scene_name
+ )
+ )
+ if result:
+ return result
+ return [scene_classes[0]] if len(scene_classes) == 1 else prompt_user_for_choice(scene_classes)
+
+
+def get_scene_classes_from_module(module):
+ if hasattr(module, "SCENES_IN_ORDER"):
+ return module.SCENES_IN_ORDER
+ else:
+ return [
+ member[1]
+ for member in inspect.getmembers(
+ module,
+ lambda x: is_child_scene(x, module)
+ )
+ ]
+
+
+def get_module(file_name):
+ if file_name == "-":
+ module = types.ModuleType("input_scenes")
+ code = sys.stdin.read()
+ try:
+ exec(code, module.__dict__)
+ return module
+ except Exception as e:
+ logger.error(f"Failed to render scene: {str(e)}")
+ sys.exit(2)
+ else:
+ if os.path.exists(file_name):
+ module_name = file_name.replace(os.sep, ".").replace(".py", "")
+ spec = importlib.util.spec_from_file_location(module_name, file_name)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+ else:
+ raise FileNotFoundError(f'{file_name} not found')
def main():
- initialize_tex(config)
- extract_scene.main(config)
+ module = get_module(file_writer_config["input_file"])
+ all_scene_classes = get_scene_classes_from_module(module)
+ scene_classes_to_render = get_scenes_to_render(all_scene_classes)
+ for SceneClass in scene_classes_to_render:
+ try:
+ # By invoking, this renders the full scene
+ scene = SceneClass(**{})
+ open_file_if_needed(scene.file_writer)
+ if file_writer_config["sound"]:
+ play_finish_sound()
+ except Exception:
+ print("\n\n")
+ traceback.print_exc()
+ print("\n\n")
+ if file_writer_config["sound"]:
+ play_error_sound()
if __name__ == "__main__":
diff --git a/manim/camera/camera.py b/manim/camera/camera.py
index 405890f22..0216b5c71 100644
--- a/manim/camera/camera.py
+++ b/manim/camera/camera.py
@@ -10,6 +10,7 @@ import cairo
import numpy as np
from ..constants import *
+from ..config import config
from ..logger import logger
from ..mobject.types.image_mobject import AbstractImageMobject
from ..mobject.mobject import Mobject
@@ -767,7 +768,7 @@ class Camera(object):
width * self.cairo_line_width_multiple *
# This ensures lines have constant width
# as you zoom in on them.
- (self.get_frame_width() / FRAME_WIDTH)
+ (self.get_frame_width() / self.frame_width)
)
ctx.stroke_preserve()
return self
diff --git a/manim/camera/moving_camera.py b/manim/camera/moving_camera.py
index 9bc928c8a..a092db1da 100644
--- a/manim/camera/moving_camera.py
+++ b/manim/camera/moving_camera.py
@@ -1,8 +1,6 @@
from ..camera.camera import Camera
-from ..constants import FRAME_HEIGHT
-from ..constants import FRAME_WIDTH
-from ..constants import ORIGIN
-from ..constants import WHITE
+from ..config import config
+from ..constants import ORIGIN, WHITE
from ..mobject.frame import ScreenRectangle
from ..mobject.types.vectorized_mobject import VGroup
from ..utils.config_ops import digest_config
@@ -11,8 +9,8 @@ from ..utils.config_ops import digest_config
# TODO, think about how to incorporate perspective
class CameraFrame(VGroup):
CONFIG = {
- "width": FRAME_WIDTH,
- "height": FRAME_HEIGHT,
+ "width": config['frame_width'],
+ "height": config['frame_height'],
"center": ORIGIN,
}
@@ -153,4 +151,4 @@ class MovingCamera(Camera):
-------
list
"""
- return [self.frame]
\ No newline at end of file
+ return [self.frame]
diff --git a/manim/camera/three_d_camera.py b/manim/camera/three_d_camera.py
index c5e7dfc1c..339555c3a 100644
--- a/manim/camera/three_d_camera.py
+++ b/manim/camera/three_d_camera.py
@@ -2,6 +2,7 @@ import numpy as np
from ..camera.camera import Camera
from ..constants import *
+from ..config import config
from ..mobject.three_d_utils import get_3d_vmob_end_corner
from ..mobject.three_d_utils import get_3d_vmob_end_corner_unit_normal
from ..mobject.three_d_utils import get_3d_vmob_start_corner
@@ -26,7 +27,7 @@ class ThreeDCamera(Camera):
"frame_center": ORIGIN,
"should_apply_shading": True,
"exponential_projection": False,
- "max_allowable_norm": 3 * FRAME_WIDTH,
+ "max_allowable_norm": 3 * config['frame_width'],
}
def __init__(self, *args, **kwargs):
@@ -406,4 +407,4 @@ class ThreeDCamera(Camera):
"""
for mobject in self.extract_mobject_family_members(mobjects):
if mobject in self.fixed_in_frame_mobjects:
- self.fixed_in_frame_mobjects.remove(mobject)
\ No newline at end of file
+ self.fixed_in_frame_mobjects.remove(mobject)
diff --git a/manim/config.py b/manim/config.py
index e49c29976..922131469 100644
--- a/manim/config.py
+++ b/manim/config.py
@@ -14,97 +14,180 @@ import configparser
import colour
from .utils.tex import TexTemplateFromFile, TexTemplate
from .logger import logger
+from . import constants
__all__ = ["config", "register_tex_template", "initialize_tex"]
-def _parse_config(input_file, config_files):
- # This only loads the [CLI] section of the manim.cfg file. If using
- # CLI arguments, the _update_config_with_args function will take care
- # of overriding any of these defaults.
- config_parser = configparser.ConfigParser()
- successfully_read_files = config_parser.read(config_files)
- if not successfully_read_files:
- raise FileNotFoundError('Config file could not be read')
+def _parse_config(config_parser, args):
+ """Parse config files and CLI arguments into a single dictionary."""
+ # By default, use the CLI section of the digested .cfg files
+ default = config_parser['CLI']
- # Put everything in a dict
+ # This will be the final config dict exposed to the user
config = {}
- # Make sure we have an input file
- config['INPUT_FILE'] = input_file
-
- # ConfigParser options are all strings, so need to convert to the
- # appropriate type
-
- # booleans
- for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',
- 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',
- 'SAVE_LAST_FRAME', 'DRY_RUN', 'SAVE_PNGS', 'SAVE_AS_GIF']:
- config[opt] = config_parser['CLI'].getboolean(opt)
-
- # numbers
- for opt in ['FROM_ANIMATION_NUMBER', 'UPTO_ANIMATION_NUMBER',
- 'BACKGROUND_OPACITY']:
- config[opt] = config_parser['CLI'].getint(opt)
-
- # UPTO_ANIMATION_NUMBER is special because -1 actually means np.inf
- if config['UPTO_ANIMATION_NUMBER'] == -1:
- import numpy as np
- config['UPTO_ANIMATION_NUMBER'] = np.inf
-
- # strings
- for opt in ['PNG_MODE', 'MOVIE_FILE_EXTENSION', 'MEDIA_DIR',
- 'OUTPUT_FILE', 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR',
- 'BACKGROUND_COLOR']:
- config[opt] = config_parser['CLI'][opt]
-
- # streaming section -- all values are strings
- config['STREAMING'] = {}
- for opt in ['LIVE_STREAM_NAME', 'TWITCH_STREAM_KEY',
- 'STREAMING_PROTOCOL', 'STREAMING_PROTOCOL', 'STREAMING_IP',
- 'STREAMING_PORT', 'STREAMING_PORT', 'STREAMING_CLIENT',
- 'STREAMING_CONSOLE_BANNER']:
- config['STREAMING'][opt] = config_parser['streaming'][opt]
-
- # for internal use (no CLI flag)
- config['SKIP_ANIMATIONS'] = any([
- config['SAVE_LAST_FRAME'],
- config['FROM_ANIMATION_NUMBER'],
- ])
-
- # camera config -- all happen to be integers
- config['CAMERA_CONFIG'] = {}
- for opt in ['FRAME_RATE', 'PIXEL_HEIGHT', 'PIXEL_WIDTH']:
- config['CAMERA_CONFIG'][opt] = config_parser['CLI'].getint(opt)
-
- # file writer config -- just pull them from the overall config for now
- config['FILE_WRITER_CONFIG'] = {key: config[key] for key in [
- "WRITE_TO_MOVIE", "SAVE_LAST_FRAME", "SAVE_PNGS",
- "SAVE_AS_GIF", "PNG_MODE", "MOVIE_FILE_EXTENSION",
- "OUTPUT_FILE", "INPUT_FILE"]}
-
- return config, config_parser
-
-
-def _parse_cli():
+ # Handle the *_quality flags. These determine the section to read
+ # and are stored in 'camera_config'. Note the highest resolution
+ # passed as argument will be used.
+ for flag in ['fourk_quality', 'high_quality', 'medium_quality', 'low_quality']:
+ if getattr(args, flag):
+ section = config_parser[flag]
+ break
+ else:
+ section = config_parser['CLI']
+ config = {opt: section.getint(opt) for opt in config_parser[flag]}
+
+ # The -r, --resolution flag overrides the *_quality flags
+ if args.resolution is not None:
+ if "," in args.resolution:
+ height_str, width_str = args.resolution.split(",")
+ height, width = int(height_str), int(width_str)
+ else:
+ height, width = int(args.resolution), int(16 * height / 9)
+ config['camera_config'].update({'pixel_height': height,
+ 'pixel_width': width})
+
+ # Handle the -c (--color) flag
+ if args.color is not None:
+ try:
+ background_color = colour.Color(args.color)
+ except AttributeError as err:
+ logger.warning('Please use a valid color.')
+ logger.error(err)
+ sys.exit(2)
+ else:
+ background_color = colour.Color(default['background_color'])
+ config['background_color'] = background_color
+
+ # Set the rest of the frame properties
+ config['frame_height'] = 8.0
+ config['frame_width'] = (config['frame_height']
+ * config['pixel_width']
+ / config['pixel_height'])
+ config['frame_y_radius'] = config['frame_height'] / 2
+ config['frame_x_radius'] = config['frame_width'] / 2
+ config['top'] = config['frame_y_radius'] * constants.UP
+ config['bottom'] = config['frame_y_radius'] * constants.DOWN
+ config['left_side'] = config['frame_x_radius'] * constants.LEFT
+ config['right_side'] = config['frame_x_radius'] * constants.RIGHT
+
+ # Hangle the --tex_template flag. Note we accept None if the flag is absent
+ filename = (os.path.expanduser(args.tex_template)
+ if args.tex_template is not None
+ else None)
+
+ if filename is not None and not os.access(filename, os.R_OK):
+ # custom template not available, fallback to default
+ logger.warning(
+ f"Custom TeX template {filename} not found or not readable. "
+ "Falling back to the default template."
+ )
+ filename = None
+ config['tex_template_file'] = filename
+ config['tex_template'] = (TexTemplateFromFile(filename=filename)
+ if filename is not None
+ else TexTemplate())
+
+ return config
+
+
+def _parse_file_writer_config(config_parser, args):
+ """Parse config files and CLI arguments into a single dictionary."""
+ # By default, use the CLI section of the digested .cfg files
+ default = config_parser['CLI']
+
+ # This will be the final config dict exposed to the user
+ config = {}
+
+ # Handle input files and scenes. Note these cannot be set from
+ # the .cfg files, only from CLI arguments
+ config['input_file'] = args.file
+ config['scene_names'] = (args.scene_names
+ if args.scene_names is not None else [])
+
+ # Read some options that cannot be overriden by CLI arguments
+ for opt in ['gif_file_extension']:
+ config[opt] = default[opt]
+
+ # Handle all options that are directly overridden by CLI
+ # arguments. Note ConfigParser options are all strings and each
+ # needs to be converted to the appropriate type. Thus, we do this
+ # in batches, depending on their type: booleans and strings
+ for boolean_opt in ['preview', 'show_file_in_finder', 'quiet',
+ 'sound', 'leave_progress_bars']:
+ config[boolean_opt] = (default.getboolean(boolean_opt)
+ if getattr(args, boolean_opt) is None
+ else getattr(args, boolean_opt))
+ for str_opt in ['media_dir', 'video_dir', 'tex_dir',
+ 'text_dir']:
+ config[str_opt] = (default[str_opt]
+ if getattr(args, str_opt) is None
+ else getattr(args, str_opt))
+
+ # Handle the -t (--transparent) flag. This flag determines which
+ # section to use from the .cfg file.
+ section = config_parser['transparent'] if args.transparent else default
+ for opt in ['png_mode', 'movie_file_extension',
+ 'background_opacity']:
+ config[opt] = section[opt]
+
+ # Handle the -n flag. Read first from the cfg and then override with CLI.
+ # These two are integers -- use getint()
+ for opt in ['from_animation_number', 'upto_animation_number']:
+ config[opt] = default.getint(opt)
+ if config['upto_animation_number'] == -1:
+ config['upto_animation_number'] = float('inf')
+ nflag = args.from_animation_number
+ if nflag is not None:
+ if ',' in nflag:
+ start, end = nflag.split(',')
+ config['from_animation_number'] = int(start)
+ config['upto_animation_number'] = int(end)
+ else:
+ config['from_animation_number'] = int(nflag)
+
+ # Handle the --dry_run flag. This flag determines which section
+ # to use from the .cfg file. All options involved are boolean.
+ section = config_parser['dry_run'] if args.dry_run else default
+ for opt in ['write_to_movie', 'write_all', 'save_last_frame', 'save_pngs', 'save_as_gif']:
+ config[opt] = section.getboolean(opt)
+
+ # Read in the streaming section -- all values are strings
+ config['streaming'] = {opt: config_parser['streaming'][opt]
+ for opt in ['live_stream_name', 'twitch_stream_key',
+ 'streaming_protocol', 'streaming_ip',
+ 'streaming_protocol', 'streaming_client',
+ 'streaming_port', 'streaming_port',
+ 'streaming_console_banner']}
+
+ # For internal use (no CLI flag)
+ config['skip_animations'] = any([config['save_last_frame'],
+ config['from_animation_number']])
+
+ return config
+
+
+def _parse_cli(arg_list, input=True):
parser = argparse.ArgumentParser(
description='Animation engine for explanatory math videos',
epilog='Made with <3 by the manim community devs'
)
- parser.add_argument(
- "file",
- help="path to file holding the python code for the scene",
- )
- parser.add_argument(
- "--scene_names",
- nargs="*",
- help="Name of the Scene class you want to see",
- )
- parser.add_argument(
- "-o", "--output_file",
- help="Specify the name of the output file, if"
- "it should be different from the scene class name",
- )
+ if input:
+ parser.add_argument(
+ "file",
+ help="path to file holding the python code for the scene",
+ )
+ parser.add_argument(
+ "scene_names",
+ nargs="*",
+ help="Name of the Scene class you want to see",
+ )
+ parser.add_argument(
+ "-o", "--output_file",
+ help="Specify the name of the output file, if"
+ "it should be different from the scene class name",
+ )
# Note the following use (action='store_const', const=True),
# instead of using the built-in (action='store_true'). The reason
@@ -270,184 +353,77 @@ def _parse_cli():
help="Specify the configuration file",
)
- return parser.parse_args()
-
-
-def _update_config_with_args(config, config_parser, args):
- # Take care of options that do not have defaults in manim.cfg
- config['FILE'] = args.file
- config['SCENE_NAMES'] = (args.scene_names
- if args.scene_names is not None else [])
-
- # Flags that directly override config defaults.
- for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',
- 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',
- 'SAVE_LAST_FRAME', 'SAVE_PNGS', 'SAVE_AS_GIF', 'MEDIA_DIR',
- 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR', 'BACKGROUND_OPACITY',
- 'OUTPUT_FILE']:
- if getattr(args, opt.lower()) is not None:
- config[opt] = getattr(args, opt.lower())
-
- # Parse the -n flag.
- nflag = args.from_animation_number
- if nflag is not None:
- if ',' in nflag:
- start, end = nflag.split(',')
- config['FROM_ANIMATION_NUMBER'] = int(start)
- config['UPTO_ANIMATION_NUMBER'] = int(end)
- else:
- config['FROM_ANIMATION_NUMBER'] = int(nflag)
-
- # The following flags use the options in the corresponding manim.cfg
- # sections to override default options. For example, passing the -t
- # (--transparent) flag takes all of the options defined in the
- # [transparent] section of manim.cfg and uses their values to override
- # the values of those options defined in CLI.
-
- # -t, --transparent
- if args.transparent:
- config.update({
- 'PNG_MODE': config_parser['transparent']['PNG_MODE'],
- 'MOVIE_FILE_EXTENSION': config_parser['transparent']['MOVIE_FILE_EXTENSION'],
- 'BACKGROUND_OPACITY': config_parser['transparent'].getfloat('BACKGROUND_OPACITY')
- })
-
- # --dry_run happens to override options that are all booleans
- if args.dry_run:
- config.update({opt.upper(): config_parser['dry_run'].getboolean(opt)
- for opt in config_parser['dry_run']})
-
- # the *_quality arguments happen to override options that are all ints
- for flag in ['fourk_quality', 'high_quality', 'medium_quality',
- 'low_quality']:
- if getattr(args, flag) is not None:
- config['CAMERA_CONFIG'].update(
- {opt.upper(): config_parser[flag].getint(opt)
- for opt in config_parser[flag]})
-
- # Parse the -r (--resolution) flag. Note the -r flag does not
- # correspond to any section in manim.cfg, but overrides the same
- # options as the *_quality sections.
- if args.resolution is not None:
- if "," in args.resolution:
- height_str, width_str = args.resolution.split(",")
- height = int(height_str)
- width = int(width_str)
- else:
- height = int(args.resolution)
- width = int(16 * height / 9)
- config['CAMERA_CONFIG'].update({'pixel_height': height,
- 'pixel_width': width})
-
- # Parse the -c (--color) flag
- if args.color is not None:
- try:
- config['CAMERA_CONFIG']['BACKGROUND_COLOR'] = colour.Color(args.color)
- except AttributeError as err:
- logger.warning('Please use a valid color')
- logger.error(err)
- sys.exit(2)
-
- # As before, make FILE_WRITER_CONFIG by pulling form the overall
- config['FILE_WRITER_CONFIG'] = {key: config[key] for key in [
- "WRITE_TO_MOVIE", "SAVE_LAST_FRAME", "SAVE_PNGS",
- "SAVE_AS_GIF", "PNG_MODE", "MOVIE_FILE_EXTENSION",
- "OUTPUT_FILE", "INPUT_FILE"]}
-
- return config
+ return parser.parse_args(arg_list)
def _init_dirs(config):
- if not (config["VIDEO_DIR"] and config["TEX_DIR"]):
- if config["MEDIA_DIR"]:
- if not os.path.isdir(config["MEDIA_DIR"]):
- os.makedirs(config["MEDIA_DIR"])
- if not os.path.isdir(config["MEDIA_DIR"]):
- config["MEDIA_DIR"] = "./media"
+ if not (config["video_dir"] and config["tex_dir"]):
+ if config["media_dir"]:
+ if not os.path.isdir(config["media_dir"]):
+ os.makedirs(config["media_dir"])
+ if not os.path.isdir(config["media_dir"]):
+ config["media_dir"] = "./media"
else:
logger.warning(
f"Media will be written to {config['media_dir'] + os.sep}. You can change "
"this behavior with the --media_dir flag, or by adjusting manim.cfg."
)
else:
- if config["MEDIA_DIR"]:
+ if config["media_dir"]:
logger.warning(
"Ignoring --media_dir, since both --tex_dir and --video_dir were passed."
)
# Make sure all folders exist
- for folder in [config["VIDEO_DIR"], config["TEX_DIR"], config["TEXT_DIR"]]:
+ for folder in [config["video_dir"], config["tex_dir"], config["text_dir"]]:
if not os.path.exists(folder):
os.makedirs(folder)
-def register_tex_template(tpl):
- """Register the given LaTeX template for later use.
-
- Parameters
- ----------
- tpl : :class:`~.TexTemplate`
- The LaTeX template to register.
- """
- config['tex_template'] = tpl
+def _from_command_line():
+ """Determine if manim was called from the command line."""
+ # Manim can be called from the command line in three different
+ # ways. The first two involve using the manim or manimcm commands
+ prog = os.path.split(sys.argv[0])[-1]
+ from_cli_command = prog in ['manim', 'manimcm']
+ # The third way involves using `python -m manim ...`. In this
+ # case, the CLI arguments passed to manim do not include 'manim',
+ # 'manimcm', or even 'python'. However, the -m flag will always
+ # be the first argument.
+ from_python_m = sys.argv[0] == '-m'
-def initialize_tex(config):
- """Safely create a LaTeX template object from a file.
- If file is not readable, the default template file is used.
-
- Parameters
- ----------
- filename : :class:`str`
- The name of the file with the LaTeX template.
- """
- filename = ""
- if config["tex_template"]:
- filename = os.path.expanduser(config["tex_template"])
- if filename and not os.access(filename, os.R_OK):
- # custom template not available, fallback to default
- logger.warning(
- f"Custom TeX template {filename} not found or not readable. "
- "Falling back to the default template."
- )
- filename = ""
- if filename:
- # still having a filename -> use the file
- config['tex_template'] = TexTemplateFromFile(filename=filename)
- else:
- # use the default template
- config['tex_template'] = TexTemplate()
+ return from_cli_command or from_python_m
# Config files to be parsed, in ascending priority
-library_wide = os.path.join(os.path.dirname(__file__), 'default.cfg'),
+library_wide = os.path.join(os.path.dirname(__file__), 'default.cfg')
config_files = [
- # Lowest priority: library-wide defaults
library_wide,
- # Medium priority: look for a 'manim.cfg' in the user home
os.path.expanduser('~/.manim.cfg'),
- # Highest priority: look for a 'manim.cfg' in the current dir
os.path.join(os.getcwd(), 'manim.cfg'),
- ]
+]
-prog = os.path.split(sys.argv[0])[-1]
-if prog in ['manim', 'manimcm']:
- # If called as entrypoint, set default config, and override the
- # defaults using CLI arguments
- args = _parse_cli()
-
- # If the user specified a config file, only use that one and the
- # library-wide defaults.
+if _from_command_line():
+ args = _parse_cli(sys.argv)
if args.config_file is not None:
- config_files = [library_wide, args.config_file]
-
- config, config_parser = _parse_config(args.file, config_files)
- _update_config_with_args(config, config_parser, args)
+ config_files.append(args.config_file)
else:
- config, _ = _parse_config('', config_files)
+ # In this case, we still need an empty args object.
+ args = _parse_cli([], input=False)
+ # Need to populate the options left out
+ args.file, args.scene_names, args.output_file = '', '', ''
+
+config_parser = configparser.ConfigParser()
+successfully_read_files = config_parser.read(config_files)
+logger.info(f'Read configuration files: {successfully_read_files}')
+
+# this is for internal use when writing output files
+file_writer_config = _parse_file_writer_config(config_parser, args)
+
+# this is for the user
+config = _parse_config(config_parser, args)
+camera_config = config
-######### ########## ##########
-# make sure to set dirs.TEX_DIR somewhere
-######### ########## ##########
-_init_dirs(config)
+_init_dirs(file_writer_config)
diff --git a/manim/constants.py b/manim/constants.py
index f73f74a6e..45fe51bfe 100644
--- a/manim/constants.py
+++ b/manim/constants.py
@@ -1,7 +1,4 @@
import numpy as np
-import os
-from .config import config
-
# Messages
NOT_SETTING_FONT_MSG = '''
@@ -15,7 +12,6 @@ class MyText(Text):
'font': 'My Font'
}
'''
-
SCENE_NOT_FOUND_MESSAGE = """
{} is not in the script
"""
@@ -58,21 +54,6 @@ DR = DOWN + RIGHT
START_X = 30
START_Y = 20
-# Geometry: frame
-FRAME_HEIGHT = 8.0
-PIXEL_WIDTH = config['CAMERA_CONFIG']['PIXEL_WIDTH']
-PIXEL_HEIGHT = config['CAMERA_CONFIG']['PIXEL_HEIGHT']
-FRAME_RATE = config['CAMERA_CONFIG']['FRAME_RATE']
-FRAME_WIDTH = FRAME_HEIGHT * PIXEL_WIDTH / PIXEL_HEIGHT
-FRAME_Y_RADIUS = FRAME_HEIGHT / 2
-FRAME_X_RADIUS = FRAME_WIDTH / 2
-
-# Geometry: sides
-TOP = FRAME_Y_RADIUS * UP
-BOTTOM = FRAME_Y_RADIUS * DOWN
-LEFT_SIDE = FRAME_X_RADIUS * LEFT
-RIGHT_SIDE = FRAME_X_RADIUS * RIGHT
-
# Default buffers (padding)
SMALL_BUFF = 0.1
MED_SMALL_BUFF = 0.25
@@ -90,9 +71,6 @@ DEFAULT_POINT_DENSITY_2D = 25
DEFAULT_POINT_DENSITY_1D = 250
DEFAULT_STROKE_WIDTH = 4
-# Tex stuff
-TEX_TEMPLATE = None
-
# Mathematical constants
PI = np.pi
TAU = 2 * PI
diff --git a/manim/default.cfg b/manim/default.cfg
index 472df34d0..68996ad61 100644
--- a/manim/default.cfg
+++ b/manim/default.cfg
@@ -15,127 +15,130 @@
# generate a movie file. Note all of the following accept boolean values.
# -w, --write_to_movie
-WRITE_TO_MOVIE = True
+write_to_movie = True
# -a, --write_all
-WRITE_ALL = False
+write_all = False
# -s, --save_last_frame
-SAVE_LAST_FRAME = False
+save_last_frame = False
# -g, --save_pngs
-SAVE_PNGS = False
+save_pngs = False
# -i, --save_as_gif
-SAVE_AS_GIF = False
+save_as_gif = False
# -p, --preview
-PREVIEW = False
+preview = False
# -f, --show_file_in_finder
-SHOW_FILE_IN_FINDER = False
+show_file_in_finder = False
# -q, --quiet
-QUIET = False
+quiet = False
# --sound
-SOUND = False
+sound = False
# -o, --output_file
-OUTPUT_FILE =
+output_file =
# --leave_progress_bars
-LEAVE_PROGRESS_BARS = False
+leave_progress_bars = False
# -c, --color
-BACKGROUND_COLOR = BLACK
+background_color = BLACK
# --background_opacity
-BACKGROUND_OPACITY = 1
+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
+from_animation_number = 0
# Use -1 to render all animations
-UPTO_ANIMATION_NUMBER = -1
+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
+media_dir = ./media
# --video_dir
-VIDEO_DIR = %(MEDIA_DIR)s/videos
+video_dir = %(MEDIA_DIR)s/videos
# --tex_dir
-TEX_DIR = %(MEDIA_DIR)s/Tex
+tex_dir = %(MEDIA_DIR)s/Tex
# --text_dir
-TEXT_DIR = %(MEDIA_DIR)s/texts
+text_dir = %(MEDIA_DIR)s/texts
+
+# This value cannot be changed through CLI
+gif_file_extension = .gif
# If the -t (--transparent) flag is used, these will be replaced with the
# values specified in the [TRANSPARENT] section later in this file.
-PNG_MODE = RGB
-MOVIE_FILE_EXTENSION = .mp4
+png_mode = RGB
+movie_file_extension = .mp4
# These can be overriden with any of -l (--low_quality), -m
# (--medium_quality), -e (--high_quality), or -k (--fourk_quality). The
# overriding values are found in the corresponding sections.
-FRAME_RATE = 60
-PIXEL_HEIGHT = 1440
-PIXEL_WIDTH = 2560
+frame_rate = 60
+pixel_height = 1440
+pixel_width = 2560
# These override the previous by using -t, --transparent
[transparent]
-PNG_MODE = RGBA
-MOVIE_FILE_EXTENSION = .mov
-BACKGROUND_OPACITY = 0
+png_mode = RGBA
+movie_file_extension = .mov
+background_opacity = 0
# These override the previous by using -k, --four_k
[fourk_quality]
-PIXEL_HEIGHT = 2160
-PIXEL_WIDTH = 3840
-FRAME_RATE = 60
+pixel_height = 2160
+pixel_width = 3840
+frame_rate = 60
# These override the previous by using -e, --high_quality
[high_quality]
-PIXEL_HEIGHT = 1080
-PIXEL_WIDTH = 1920
-FRAME_RATE = 60
+pixel_height = 1080
+pixel_width = 1920
+frame_rate = 60
# These override the previous by using -m, --medium_quality
[medium_quality]
-PIXEL_HEIGHT = 720
-PIXEL_WIDTH = 1280
-FRAME_RATE = 30
+pixel_height = 720
+pixel_width = 1280
+frame_rate = 30
# These override the previous by usnig -l, --low_quality
[low_quality]
-PIXEL_HEIGHT = 480
-PIXEL_WIDTH = 854
-FRAME_RATE = 15
+pixel_height = 480
+pixel_width = 854
+frame_rate = 15
# These override the previous by using --dry_run
# Note --dry_run overrides all of -w, -a, -s, -g, -i
[dry_run]
-WRITE_TO_MOVIE = False
-WRITE_ALL = False
-SAVE_LAST_FRAME = False
-SAVE_PNGS = False
-SAVE_AS_GIF = False
+write_to_movie = False
+write_all = False
+save_last_frame = False
+save_pngs = False
+save_as_gif = False
# Streaming settings
[streaming]
-LIVE_STREAM_NAME = LiveStream
-TWITCH_STREAM_KEY = YOUR_STREAM_KEY
-STREAMING_PROTOCOL = tcp
-STREAMING_IP = 127.0.0.1
-STREAMING_PORT = 2000
-STREAMING_CLIENT = ffplay
-STREAMING_URL = %(STREAMING_PROTOCOL)s://%(STREAMING_IP)s:%(STREAMING_PORT)s?listen
-STREAMING_CONSOLE_BANNER = Manim is now running in streaming mode.
+live_stream_name = LiveStream
+twitch_stream_key = YOUR_STREAM_KEY
+streaming_protocol = tcp
+streaming_ip = 127.0.0.1
+streaming_port = 2000
+streaming_client = ffplay
+streaming_url = %(STREAMING_PROTOCOL)s://%(STREAMING_IP)s:%(STREAMING_PORT)s?listen
+streaming_console_banner = Manim is now running in streaming mode.
Stream animations by passing them to manim.play(), e.g.
>>> c = Circle()
>>> manim.play(ShowCreation(c))
diff --git a/manim/extract_scene.py b/manim/extract_scene.py
deleted file mode 100644
index 323833b3a..000000000
--- a/manim/extract_scene.py
+++ /dev/null
@@ -1,184 +0,0 @@
-import inspect
-import itertools as it
-import os
-import platform
-import subprocess as sp
-import sys
-import traceback
-import importlib.util
-
-from .scene.scene import Scene
-from .utils.sounds import play_error_sound
-from .utils.sounds import play_finish_sound
-from . import constants
-from .logger import logger
-
-
-def open_file_if_needed(file_writer, **config):
- if config["QUIET"]:
- curr_stdout = sys.stdout
- sys.stdout = open(os.devnull, "w")
-
- open_file = any([
- config["PREVIEW"],
- config["SHOW_FILE_IN_FINDER"]
- ])
- if open_file:
- current_os = platform.system()
- file_paths = []
-
- if config["FILE_WRITER_CONFIG"]["SAVE_LAST_FRAME"]:
- file_paths.append(file_writer.get_image_file_path())
- if config["FILE_WRITER_CONFIG"]["WRITE_TO_MOVIE"]:
- file_paths.append(file_writer.get_movie_file_path())
-
- for file_path in file_paths:
- if current_os == "Windows":
- os.startfile(file_path)
- else:
- commands = []
- if current_os == "Linux":
- commands.append("xdg-open")
- elif current_os.startswith("CYGWIN"):
- commands.append("cygstart")
- else: # Assume macOS
- commands.append("open")
-
- if config["SHOW_FILE_IN_FINDER"]:
- commands.append("-R")
-
- commands.append(file_path)
-
- # commands.append("-g")
- FNULL = open(os.devnull, 'w')
- sp.call(commands, stdout=FNULL, stderr=sp.STDOUT)
- FNULL.close()
-
- if config["QUIET"]:
- sys.stdout.close()
- sys.stdout = curr_stdout
-
-
-def is_child_scene(obj, module):
- if not inspect.isclass(obj):
- return False
- if not issubclass(obj, Scene):
- return False
- if obj == Scene:
- return False
- if not obj.__module__.startswith(module.__name__):
- return False
- return True
-
-
-def prompt_user_for_choice(scene_classes):
- num_to_class = {}
- for count, scene_class in zip(it.count(1), scene_classes):
- name = scene_class.__name__
- print("%d: %s" % (count, name))
- num_to_class[count] = scene_class
- try:
- user_input = input(constants.CHOOSE_NUMBER_MESSAGE)
- return [
- num_to_class[int(num_str)]
- for num_str in user_input.split(",")
- ]
- except KeyError:
- logger.error(constants.INVALID_NUMBER_MESSAGE)
- sys.exit(2)
- user_input = input(constants.CHOOSE_NUMBER_MESSAGE)
- return [
- num_to_class[int(num_str)]
- for num_str in user_input.split(",")
- ]
- except EOFError:
- sys.exit(1)
-
-
-def get_scenes_to_render(scene_classes, config):
- if not scene_classes:
- logger.error(constants.NO_SCENE_MESSAGE)
- return []
- if config["WRITE_ALL"]:
- return scene_classes
- result = []
- for scene_name in config["SCENE_NAMES"]:
- found = False
- for scene_class in scene_classes:
- if scene_class.__name__ == scene_name:
- result.append(scene_class)
- found = True
- break
- if not found and (scene_name != ""):
- logger.error(
- constants.SCENE_NOT_FOUND_MESSAGE.format(
- scene_name
- )
- )
- if result:
- return result
- return [scene_classes[0]] if len(scene_classes) == 1 else prompt_user_for_choice(scene_classes)
-
-
-def get_scene_classes_from_module(module):
- if hasattr(module, "SCENES_IN_ORDER"):
- return module.SCENES_IN_ORDER
- else:
- return [
- member[1]
- for member in inspect.getmembers(
- module,
- lambda x: is_child_scene(x, module)
- )
- ]
-
-
-def get_module(file_name):
- if file_name == "-":
- module = types.ModuleType("input_scenes")
- code = sys.stdin.read()
- try:
- exec(code, module.__dict__)
- return module
- except Exception as e:
- logger.error(f"Failed to render scene: {str(e)}")
- sys.exit(2)
- else:
- if os.path.exists(file_name):
- module_name = file_name.replace(os.sep, ".").replace(".py", "")
- spec = importlib.util.spec_from_file_location(module_name, file_name)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- else:
- raise FileNotFoundError(f'{file_name} not found')
-
-
-def main(config):
- module = get_module(config["FILE"])
- all_scene_classes = get_scene_classes_from_module(module)
- scene_classes_to_render = get_scenes_to_render(all_scene_classes, config)
-
- keys = [
- "CAMERA_CONFIG",
- "FILE_WRITER_CONFIG",
- "SKIP_ANIMATIONS",
- "FROM_ANIMATION_NUMBER",
- "UPTO_ANIMATION_NUMBER",
- "LEAVE_PROGRESS_BARS",
- ]
- scene_kwargs = {key: config[key] for key in keys}
-
- for SceneClass in scene_classes_to_render:
- try:
- # By invoking, this renders the full scene
- scene = SceneClass(**scene_kwargs)
- open_file_if_needed(scene.file_writer, **config)
- if config["SOUND"]:
- play_finish_sound()
- except Exception:
- print("\n\n")
- traceback.print_exc()
- print("\n\n")
- if config["SOUND"]:
- play_error_sound()
diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.py
index 10b2e2dca..a50998405 100644
--- a/manim/mobject/coordinate_systems.py
+++ b/manim/mobject/coordinate_systems.py
@@ -2,6 +2,7 @@ import numpy as np
import numbers
from ..constants import *
+from ..config import config
from ..mobject.functions import ParametricFunction
from ..mobject.geometry import Arrow
from ..mobject.geometry import Line
@@ -22,10 +23,10 @@ class CoordinateSystem():
"""
CONFIG = {
"dimension": 2,
- "x_min": -FRAME_X_RADIUS,
- "x_max": FRAME_X_RADIUS,
- "y_min": -FRAME_Y_RADIUS,
- "y_max": FRAME_Y_RADIUS,
+ "x_min": -config['frame_x_radius'],
+ "x_max": config['frame_x_radius'],
+ "y_min": -config['frame_y_radius'],
+ "y_max": config['frame_y_radius'],
}
def coords_to_point(self, *coords):
@@ -429,4 +430,4 @@ class ComplexPlane(NumberPlane):
def add_coordinates(self, *numbers):
self.add(self.get_coordinate_labels(*numbers))
- return self
\ No newline at end of file
+ return self
diff --git a/manim/mobject/frame.py b/manim/mobject/frame.py
index 7b45722d6..dfa096bd7 100644
--- a/manim/mobject/frame.py
+++ b/manim/mobject/frame.py
@@ -1,4 +1,5 @@
from ..constants import *
+from ..config import config
from ..mobject.geometry import Rectangle
from ..utils.config_ops import digest_config
@@ -19,7 +20,7 @@ class ScreenRectangle(Rectangle):
class FullScreenRectangle(ScreenRectangle):
CONFIG = {
- "height": FRAME_HEIGHT,
+ "height": config['frame_height'],
}
@@ -44,4 +45,4 @@ class PictureInPictureFrame(Rectangle):
width=self.aspect_ratio * self.height,
height=self.height,
**kwargs
- )
\ No newline at end of file
+ )
diff --git a/manim/mobject/functions.py b/manim/mobject/functions.py
index f31ad0d63..d6a5fd04c 100644
--- a/manim/mobject/functions.py
+++ b/manim/mobject/functions.py
@@ -1,4 +1,5 @@
from ..constants import *
+from ..config import config
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.config_ops import digest_config
import math
@@ -80,8 +81,8 @@ class ParametricFunction(VMobject):
class FunctionGraph(ParametricFunction):
CONFIG = {
"color": YELLOW,
- "x_min": -FRAME_X_RADIUS,
- "x_max": FRAME_X_RADIUS,
+ "x_min": -config['frame_x_radius'],
+ "x_max": config['frame_x_radius'],
}
def __init__(self, function, **kwargs):
@@ -101,4 +102,4 @@ class FunctionGraph(ParametricFunction):
return self.function
def get_point_from_function(self, x):
- return self.parametric_function(x)
\ No newline at end of file
+ return self.parametric_function(x)
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 52f6336bc..b992de86a 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -389,7 +389,7 @@ class Mobject(Container):
Direction just needs to be a vector pointing towards side or
corner in the 2d plane.
"""
- target_point = np.sign(direction) * (FRAME_X_RADIUS, FRAME_Y_RADIUS, 0)
+ target_point = np.sign(direction) * (config['frame_x_radius'], config['frame_y_radius'], 0)
point_to_align = self.get_critical_point(direction)
shift_val = target_point - point_to_align - buff * np.array(direction)
shift_val = shift_val * abs(np.sign(direction))
diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.py
index 1ae4dab2e..d2fe00503 100644
--- a/manim/mobject/number_line.py
+++ b/manim/mobject/number_line.py
@@ -1,6 +1,7 @@
import operator as op
from ..constants import *
+from ..config import config
from ..mobject.geometry import Line
from ..mobject.numbers import DecimalNumber
from ..mobject.types.vectorized_mobject import VGroup
@@ -14,8 +15,8 @@ from ..utils.space_ops import normalize
class NumberLine(Line):
CONFIG = {
"color": LIGHT_GREY,
- "x_min": -FRAME_X_RADIUS,
- "x_max": FRAME_X_RADIUS,
+ "x_min": -config['frame_x_radius'],
+ "x_max": config['frame_x_radius'],
"unit_size": 1,
"include_ticks": True,
"tick_size": 0.1,
@@ -198,4 +199,4 @@ class UnitInterval(NumberLine):
"decimal_number_config": {
"num_decimal_places": 1,
}
- }
\ No newline at end of file
+ }
diff --git a/manim/mobject/svg/drawings.py b/manim/mobject/svg/drawings.py
index a81639910..22e25e500 100644
--- a/manim/mobject/svg/drawings.py
+++ b/manim/mobject/svg/drawings.py
@@ -4,6 +4,7 @@ import string
from ...animation.animation import Animation
from ...animation.rotation import Rotating
from ...constants import *
+from ...config import config
from ...mobject.geometry import AnnularSector
from ...mobject.geometry import Arc
from ...mobject.geometry import Circle
@@ -279,7 +280,7 @@ class PatreonLogo(SVGMobject):
class VideoIcon(SVGMobject):
CONFIG = {
"file_name": "video_icon",
- "width": FRAME_WIDTH / 12.,
+ "width": config['frame_width'] / 12.,
}
def __init__(self, **kwargs):
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.py
index 321b689b7..adc3e6195 100644
--- a/manim/mobject/svg/svg_mobject.py
+++ b/manim/mobject/svg/svg_mobject.py
@@ -1,5 +1,6 @@
import itertools as it
import re
+import os
import string
import warnings
diff --git a/manim/mobject/svg/tex_mobject.py b/manim/mobject/svg/tex_mobject.py
index f016cba80..242f7bd41 100644
--- a/manim/mobject/svg/tex_mobject.py
+++ b/manim/mobject/svg/tex_mobject.py
@@ -2,6 +2,7 @@ from functools import reduce
import operator as op
from ...constants import *
+from ...config import config
from ...mobject.geometry import Line
from ...mobject.svg.svg_mobject import SVGMobject
from ...mobject.svg.svg_mobject import VMobjectFromSVGPathstring
@@ -15,11 +16,10 @@ TEX_MOB_SCALE_FACTOR = 0.05
class TexSymbol(VMobjectFromSVGPathstring):
- """
- Purely a renaming of VMobjectFromSVGPathstring
- """
+ """Purely a renaming of VMobjectFromSVGPathstring."""
pass
+
class SingleStringTexMobject(SVGMobject):
CONFIG = {
"stroke_width": 0,
@@ -304,7 +304,7 @@ class Title(TextMobject):
CONFIG = {
"scale_factor": 1,
"include_underline": True,
- "underline_width": FRAME_WIDTH - 2,
+ "underline_width": config['frame_width'] - 2,
# This will override underline_width
"match_underline_width_to_text": False,
"underline_buff": MED_SMALL_BUFF,
diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.py
index cc7735370..0903e54c5 100644
--- a/manim/mobject/vector_field.py
+++ b/manim/mobject/vector_field.py
@@ -5,6 +5,7 @@ from PIL import Image
import random
from ..constants import *
+from ..config import config
from ..logger import logger
from ..animation.composition import AnimationGroup
from ..animation.indication import ShowPassingFlash
@@ -27,12 +28,12 @@ DEFAULT_SCALAR_FIELD_COLORS = [BLUE_E, GREEN, YELLOW, RED]
def get_colored_background_image(scalar_field_func,
number_to_rgb_func,
- pixel_height=PIXEL_HEIGHT,
- pixel_width=PIXEL_WIDTH):
- ph = pixel_height
- pw = pixel_width
- fw = FRAME_WIDTH
- fh = FRAME_HEIGHT
+ pixel_height=config['pixel_height'],
+ pixel_width=config['pixel_width']):
+ ph = config['pixel_height']
+ pw = config['pixel_width']
+ fw = config['frame_width']
+ fh = config['frame_height']
points_array = np.zeros((ph, pw, 3))
x_array = np.linspace(-fw / 2, fw / 2, pw)
x_array = x_array.reshape((1, len(x_array)))
@@ -109,7 +110,7 @@ def move_submobjects_along_vector_field(mobject, func):
def apply_nudge(mob, dt):
for submob in mob:
x, y = submob.get_center()[:2]
- if abs(x) < FRAME_WIDTH and abs(y) < FRAME_HEIGHT:
+ if abs(x) < config['frame_width'] and abs(y) < config['frame_height']:
submob.shift(func(submob.get_center()) * dt)
mobject.add_updater(apply_nudge)
@@ -131,10 +132,10 @@ class VectorField(VGroup):
CONFIG = {
"delta_x": 0.5,
"delta_y": 0.5,
- "x_min": int(np.floor(-FRAME_WIDTH / 2)),
- "x_max": int(np.ceil(FRAME_WIDTH / 2)),
- "y_min": int(np.floor(-FRAME_HEIGHT / 2)),
- "y_max": int(np.ceil(FRAME_HEIGHT / 2)),
+ "x_min": int(np.floor(-config['frame_width'] / 2)),
+ "x_max": int(np.ceil(config['frame_width'] / 2)),
+ "y_min": int(np.floor(-config['frame_height'] / 2)),
+ "y_max": int(np.ceil(config['frame_height'] / 2)),
"min_magnitude": 0,
"max_magnitude": 2,
"colors": DEFAULT_SCALAR_FIELD_COLORS,
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index b69e2c3aa..7b6bd2574 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -10,6 +10,7 @@ from ..animation.animation import Animation
from ..animation.transform import MoveToTarget, ApplyMethod
from ..camera.camera import Camera
from ..constants import *
+from ..config import camera_config, file_writer_config
from ..container.container import Container
from ..logger import logger
from ..mobject.mobject import Mobject
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 3444fa162..1bfa7ed0e 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -9,7 +9,7 @@ import datetime
from PIL import Image
from ..constants import FFMPEG_BIN
-from ..config import config
+from ..config import file_writer_config
from ..logger import logger
from ..utils.config_ops import digest_config
from ..utils.file_ops import guarantee_existence
@@ -75,10 +75,10 @@ class SceneFileWriter(object):
add_extension_if_not_present(scene_name, ".png")
)
- if config['WRITE_TO_MOVIE']:
- if config['VIDEO_DIR']:
+ if file_writer_config['write_to_movie']:
+ if file_writer_config['video_dir']:
movie_dir = guarantee_existence(os.path.join(
- config['VIDEO_DIR'],
+ file_writer_config['video_dir'],
module_directory,
self.get_resolution_directory(),
))
diff --git a/manim/scene/vector_space_scene.py b/manim/scene/vector_space_scene.py
index 7839366bd..ac860857b 100644
--- a/manim/scene/vector_space_scene.py
+++ b/manim/scene/vector_space_scene.py
@@ -9,6 +9,7 @@ from ..animation.transform import ApplyFunction
from ..animation.transform import ApplyPointwiseFunction
from ..animation.transform import Transform
from ..constants import *
+from ..config import config
from ..mobject.coordinate_systems import Axes
from ..mobject.coordinate_systems import NumberPlane
from ..mobject.geometry import Arrow
@@ -488,8 +489,8 @@ class VectorScene(Scene):
vector = vector.get_end() - vector.get_start()
elif len(vector) == 2:
vector = np.append(np.array(vector), 0.0)
- x_max = int(FRAME_X_RADIUS + abs(vector[0]))
- y_max = int(FRAME_Y_RADIUS + abs(vector[1]))
+ x_max = int(config['frame_x_radius'] + abs(vector[0]))
+ y_max = int(config['frame_y_radius'] + abs(vector[1]))
dots = VMobject(*[
Dot(x * RIGHT + y * UP)
for x in range(-x_max, x_max)
@@ -517,10 +518,10 @@ class LinearTransformationScene(VectorScene):
"include_background_plane": True,
"include_foreground_plane": True,
"foreground_plane_kwargs": {
- "x_max": FRAME_WIDTH / 2,
- "x_min": -FRAME_WIDTH / 2,
- "y_max": FRAME_WIDTH / 2,
- "y_min": -FRAME_WIDTH / 2,
+ "x_max": config['frame_width'] / 2,
+ "x_min": -config['frame_width'] / 2,
+ "y_max": config['frame_width'] / 2,
+ "y_min": -config['frame_width'] / 2,
"faded_line_ratio": 0
},
"background_plane_kwargs": {
@@ -1083,4 +1084,4 @@ class LinearTransformationScene(VectorScene):
Animation(f_mob)
for f_mob in self.foreground_mobjects
] + added_anims
- self.play(*anims, **kwargs)
\ No newline at end of file
+ self.play(*anims, **kwargs)
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index a51f4b931..7b574f380 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -1,12 +1,12 @@
import os
import hashlib
-
from pathlib import Path
-from ..config import config
-from ..constants import TEX_TEXT_TO_REPLACE, TEX_USE_CTEX
+from .. import constants
+from ..config import file_writer_config, config
from ..logger import logger
+
def tex_hash(expression):
id_str = str(expression)
hasher = hashlib.sha256()
@@ -14,12 +14,14 @@ def tex_hash(expression):
# Truncating at 16 bytes for cleanliness
return hasher.hexdigest()[:16]
+
def tex_to_svg_file(expression, source_type):
- tex_template = constants.TEX_TEMPLATE
+ tex_template = config['tex_template']
tex_file = generate_tex_file(expression, tex_template, source_type)
dvi_file = tex_to_dvi(tex_file, tex_template.use_ctex)
return dvi_to_svg(dvi_file, use_ctex=tex_template.use_ctex)
+
def generate_tex_file(expression, tex_template, source_type):
if source_type == "text":
output = tex_template.get_text_for_text_mode(expression)
@@ -27,7 +29,7 @@ def generate_tex_file(expression, tex_template, source_type):
output = tex_template.get_text_for_tex_mode(expression)
result = os.path.join(
- config['TEX_DIR'],
+ file_writer_config['tex_dir'],
tex_hash(output)
) + ".tex"
if not os.path.exists(result):
@@ -39,11 +41,11 @@ def generate_tex_file(expression, tex_template, source_type):
return result
-def tex_to_dvi(tex_file, use_ctex = False):
+def tex_to_dvi(tex_file, use_ctex=False):
result = tex_file.replace(".tex", ".dvi" if not use_ctex else ".xdv")
result = Path(result).as_posix()
tex_file = Path(tex_file).as_posix()
- tex_dir = Path(config['TEX_DIR']).as_posix()
+ tex_dir = Path(file_writer_config['tex_dir']).as_posix()
if not os.path.exists(result):
commands = [
"latex",
@@ -67,9 +69,10 @@ def tex_to_dvi(tex_file, use_ctex = False):
if exit_code != 0:
log_file = tex_file.replace(".tex", ".log")
raise Exception(
- ("LaTeX error converting to dvi. " if not use_ctex
- else "XeLaTeX error converting to xdv. ") +
- "See log output above or the log file: %s" % log_file)
+ ("LaTeX error converting to dvi. "
+ if not use_ctex
+ else "XeLaTeX error converting to xdv. ") +
+ f"See log output above or the log file: {log_file}")
return result