Animation engine for explanatory math videos.
—
Backend rendering engines and output management supporting multiple formats, quality settings, and both real-time preview and high-quality export. The rendering system converts mathematical descriptions into visual output through specialized engines optimized for different use cases.
Global configuration management controlling rendering parameters, output settings, and quality preferences.
# Global configuration access
from manim import config
# Core rendering settings
config.pixel_height: int # Vertical resolution in pixels
config.pixel_width: int # Horizontal resolution in pixels
config.frame_rate: float # Animation frame rate (fps)
config.frame_height: float # Scene height in Manim units
config.frame_width: float # Scene width in Manim units
# Quality presets
config.quality: str # Quality preset name
config.low_quality: bool # 480p15 (854x480, 15fps)
config.medium_quality: bool # 720p30 (1280x720, 30fps)
config.high_quality: bool # 1080p60 (1920x1080, 60fps)
config.production_quality: bool # 1440p60 (2560x1440, 60fps)
config.fourk_quality: bool # 4K60 (3840x2160, 60fps)
# Output settings
config.output_file: str # Output filename
config.scenes_names: list[str] # Scenes to render
config.output_dir: str # Output directory path
config.images_dir: str # Directory for image outputs
config.video_dir: str # Directory for video outputs
config.partial_movie_dir: str # Directory for partial renders
# Rendering behavior
config.preview: bool # Whether to preview after rendering
config.show_in_file_browser: bool # Open output folder when done
config.write_to_movie: bool # Generate video output
config.write_all: bool # Render all scenes in file
config.save_last_frame: bool # Save final frame as image
config.save_pngs: bool # Save individual frame images
config.save_as_gif: bool # Generate GIF output
config.transparent: bool # Use transparent background
# Performance settings
config.disable_caching: bool # Disable animation caching
config.flush_cache: bool # Clear existing cache
config.tex_template: str # LaTeX template for math rendering
config.verbosity: str # Logging level ("DEBUG", "INFO", "WARNING", "ERROR")
# Renderer selection
config.renderer: str # "cairo" or "opengl"
config.use_opengl_renderer: bool # Whether to use OpenGL
# Background and styling
config.background_color: str # Scene background color
config.background_opacity: float # Background opacityHigh-quality 2D renderer using Cairo graphics library for precise vector graphics and publication-quality output.
class CairoRenderer:
"""
2D renderer using Cairo graphics library for high-quality vector output.
Optimized for precise mathematical graphics, text rendering, and
publication-quality static images and animations.
"""
def __init__(
file_writer_class: type = SceneFileWriter,
camera_class: type = Camera,
skip_animations: bool = False,
**kwargs
) -> None:
"""
Parameters:
- file_writer_class: Class for handling file output
- camera_class: Camera class for viewport management
- skip_animations: Whether to skip animation rendering
"""
def init_scene(scene: Scene) -> None:
"""Initialize renderer for a specific scene."""
def play(
scene: Scene,
*animations: Animation,
**kwargs
) -> None:
"""
Render a play() call with given animations.
Handles animation caching, frame generation, and file output
for the specified animations.
Parameters:
- scene: Scene being rendered
- *animations: Animations to render
"""
def scene_finished(scene: Scene) -> None:
"""Clean up after scene rendering is complete."""
def render(
scene: Scene,
time: float,
moving_mobjects: list[Mobject]
) -> None:
"""
Render a single frame at specified time.
Parameters:
- scene: Scene to render
- time: Animation time for the frame
- moving_mobjects: Mobjects being animated
"""
def update_skipping_status(self) -> None:
"""Update animation skipping based on configuration."""
def get_frame(self) -> np.ndarray:
"""
Get current rendered frame as pixel array.
Returns:
- np.ndarray: Frame pixels in RGBA format
"""
def save_static_frame_data(
scene: Scene,
static_image: np.ndarray
) -> None:
"""Save frame data for static image output."""
@property
def camera() -> Camera:
"""Camera used by this renderer."""
@property
def file_writer() -> SceneFileWriter:
"""File writer for output generation."""
@property
def time() -> float:
"""Current animation time."""
@property
def num_plays() -> int:
"""Number of play() calls rendered so far."""Real-time 3D renderer using OpenGL for interactive preview and 3D scene rendering with hardware acceleration.
class OpenGLRenderer:
"""
Hardware-accelerated 3D renderer using OpenGL for real-time rendering.
Optimized for 3D scenes, real-time preview, and interactive development
with support for lighting, shading, and complex 3D transformations.
"""
def __init__(
file_writer_class: type = SceneFileWriter,
skip_animations: bool = False,
**kwargs
) -> None:
"""
Parameters:
- file_writer_class: Class for handling file output
- skip_animations: Whether to skip animation rendering
"""
def init_scene(scene: Scene) -> None:
"""Initialize OpenGL context and scene resources."""
def play(
scene: Scene,
*animations: Animation,
**kwargs
) -> None:
"""Render animations using OpenGL pipeline."""
def scene_finished(scene: Scene) -> None:
"""Clean up OpenGL resources after scene completion."""
def render(
scene: Scene,
time: float,
moving_mobjects: list[Mobject]
) -> None:
"""
Render frame using OpenGL shaders and buffers.
Parameters:
- scene: Scene to render
- time: Animation time
- moving_mobjects: Objects being animated
"""
def refresh_static_mobjects(self) -> None:
"""Refresh static mobjects in GPU buffers."""
def add_mobjects_to_buffer(
*mobjects: Mobject
) -> None:
"""Add mobjects to OpenGL rendering buffers."""
def clear_buffer(self) -> None:
"""Clear OpenGL rendering buffers."""
@property
def camera() -> Camera:
"""OpenGL camera for 3D rendering."""
@property
def window() -> Window:
"""OpenGL window for rendering context."""
class Window:
"""
OpenGL window management for interactive rendering and preview.
Handles window creation, event processing, and real-time display
for development and interactive exploration.
"""
def __init__(
scene: Scene,
**kwargs
) -> None:
"""
Parameters:
- scene: Scene to display in window
"""
def setup(self) -> None:
"""Initialize OpenGL window and context."""
def tear_down(self) -> None:
"""Clean up window and OpenGL resources."""
def capture_frame(self) -> np.ndarray:
"""
Capture current window contents as image.
Returns:
- np.ndarray: Window pixels in RGBA format
"""
def should_close(self) -> bool:
"""Check if window should be closed."""
def swap_buffers(self) -> None:
"""Swap front and back buffers for display."""
def poll_events(self) -> None:
"""Process window events and user input."""File writing and output management for various formats including video, images, and data export.
class SceneFileWriter:
"""
File output management for rendered scenes supporting multiple formats.
Handles video encoding, image export, caching, and file organization
with support for various output formats and quality settings.
"""
def __init__(
renderer: CairoRenderer | OpenGLRenderer,
scene_name: str,
**kwargs
) -> None:
"""
Parameters:
- renderer: Renderer producing the output
- scene_name: Name of scene being rendered
"""
def write_opengl_frame(
frame: np.ndarray,
num_frames: int = 1
) -> None:
"""
Write OpenGL-rendered frame to output.
Parameters:
- frame: Frame pixel data
- num_frames: Number of times to repeat frame
"""
def save_final_image(
image: np.ndarray
) -> None:
"""
Save final frame as static image.
Parameters:
- image: Final frame to save
"""
def finish(self) -> None:
"""Finalize output file and clean up resources."""
def add_partial_movie_file(
hash_animation: str
) -> None:
"""
Add cached animation segment to final output.
Parameters:
- hash_animation: Hash identifying cached animation
"""
def is_already_cached(
hash_animation: str
) -> bool:
"""
Check if animation is already cached.
Parameters:
- hash_animation: Animation hash to check
Returns:
- bool: True if animation is cached
"""
def combine_partial_movie_files(self) -> None:
"""Combine partial movie files into final output."""
def clean_cache(self, **kwargs) -> None:
"""Clean animation cache files."""
# Output format methods
def save_as_png(
frame: np.ndarray,
filename: str
) -> None:
"""Save frame as PNG image."""
def save_as_gif(
frames: list[np.ndarray],
filename: str,
fps: float = 15
) -> None:
"""Save frames as animated GIF."""
def init_audio(self) -> None:
"""Initialize audio processing for video output."""
def add_audio_segment(
audio_segment: AudioSegment
) -> None:
"""Add audio segment to video output."""
@property
def output_name() -> str:
"""Final output filename."""
@property
def partial_movie_files() -> list[str]:
"""List of partial movie files for combining."""Comprehensive quality presets and format options for different output requirements and use cases.
# Quality preset configurations
QUALITIES = {
"fourk_quality": {
"pixel_height": 2160,
"pixel_width": 3840,
"frame_rate": 60,
},
"production_quality": {
"pixel_height": 1440,
"pixel_width": 2560,
"frame_rate": 60,
},
"high_quality": {
"pixel_height": 1080,
"pixel_width": 1920,
"frame_rate": 60,
},
"medium_quality": {
"pixel_height": 720,
"pixel_width": 1280,
"frame_rate": 30,
},
"low_quality": {
"pixel_height": 480,
"pixel_width": 854,
"frame_rate": 15,
},
"example_quality": {
"pixel_height": 480,
"pixel_width": 854,
"frame_rate": 15,
}
}
# Configuration helper functions
def set_quality(quality_name: str) -> None:
"""
Set rendering quality using preset.
Parameters:
- quality_name: Name of quality preset
"""
def set_custom_quality(
pixel_width: int,
pixel_height: int,
frame_rate: float = 30
) -> None:
"""
Set custom quality parameters.
Parameters:
- pixel_width: Horizontal resolution
- pixel_height: Vertical resolution
- frame_rate: Animation frame rate
"""
def set_output_format(
format_type: str,
**kwargs
) -> None:
"""
Configure output format and settings.
Parameters:
- format_type: "mp4", "gif", "png", "mov", "webm"
"""
# Renderer selection
def use_cairo_renderer() -> None:
"""Switch to Cairo renderer for high-quality 2D output."""
def use_opengl_renderer() -> None:
"""Switch to OpenGL renderer for 3D and real-time rendering."""
# Background and styling
def set_background_color(color: str) -> None:
"""Set scene background color."""
def set_transparent_background(transparent: bool = True) -> None:
"""Enable/disable transparent background."""Animation caching system and performance optimization tools for faster rendering and development iteration.
# Cache management
def enable_caching() -> None:
"""Enable animation caching for faster re-rendering."""
def disable_caching() -> None:
"""Disable animation caching for fresh renders."""
def flush_cache() -> None:
"""Clear all cached animation data."""
def get_cache_dir() -> str:
"""Get path to animation cache directory."""
# Performance monitoring
class PerformanceMonitor:
"""
Performance monitoring and profiling for rendering optimization.
Tracks rendering times, memory usage, and bottlenecks
to help optimize scene performance.
"""
def start_profiling(self) -> None:
"""Begin performance profiling."""
def stop_profiling(self) -> dict:
"""
End profiling and get results.
Returns:
- dict: Performance statistics
"""
def get_render_stats(self) -> dict:
"""
Get rendering performance statistics.
Returns:
- dict: Timing and resource usage data
"""
# Memory management
def optimize_memory_usage() -> None:
"""Apply memory optimization settings."""
def get_memory_usage() -> dict:
"""
Get current memory usage statistics.
Returns:
- dict: Memory usage information
"""from manim import *
# Set quality and output preferences
config.quality = "high_quality" # 1080p60
config.output_file = "my_animation.mp4"
config.preview = True
class MyScene(Scene):
def construct(self):
circle = Circle()
self.play(Create(circle))# Custom resolution and frame rate
config.pixel_width = 1600
config.pixel_height = 900
config.frame_rate = 24
# Background settings
config.background_color = BLACK
config.background_opacity = 1.0
# Output format
config.save_as_gif = True
config.transparent = Falseclass MultiFormatExample(Scene):
def construct(self):
# Configure for multiple outputs
config.write_to_movie = True # Generate MP4
config.save_last_frame = True # Save final PNG
config.save_as_gif = True # Generate GIF
config.save_pngs = True # Save all frames
text = Text("Multi-format output")
self.play(Write(text))
self.wait(2)# Use Cairo for high-quality 2D
config.renderer = "cairo"
config.quality = "production_quality"
class HighQuality2D(Scene):
def construct(self):
equation = MathTex(r"\int_0^1 x^2 dx = \frac{1}{3}")
self.play(Write(equation))
# Use OpenGL for 3D and real-time
config.renderer = "opengl"
config.preview = True
class Interactive3D(ThreeDScene):
def construct(self):
cube = Cube()
self.add(cube)
self.interactive_embed() # Interactive mode# Optimize for faster rendering
config.low_quality = True # Lower resolution
config.disable_caching = False # Enable caching
config.skip_animations = False # Don't skip animations
# Memory optimization
config.max_files_cached = 100 # Limit cache size
config.flush_cache = False # Keep cache between runs
class OptimizedScene(Scene):
def construct(self):
# Use simpler objects for better performance
dots = VGroup(*[Dot() for _ in range(100)])
dots.arrange_in_grid(10, 10)
# Batch animations for efficiency
self.play(
LaggedStart(
*[FadeIn(dot) for dot in dots],
lag_ratio=0.01
)
)class AdvancedOutputExample(Scene):
def setup(self):
# Set up custom file writer
config.output_dir = "custom_output"
config.video_dir = "videos"
config.images_dir = "frames"
# Configure video encoding
config.video_codec = "libx264"
config.audio_codec = "aac"
def construct(self):
# Scene with custom output settings
title = Title("Advanced Output")
# Add background music (if available)
# self.add_sound("background.wav")
self.play(Write(title))
# Save specific frames
self.wait(1)
# Custom frame saving would be done through file_writer
self.play(FadeOut(title))# Development settings for faster iteration
config.preview = True # Auto-preview
config.low_quality = True # Faster rendering
config.save_last_frame = True # Quick feedback
config.verbosity = "INFO" # Detailed logging
# Debug rendering issues
config.disable_caching = True # Fresh renders
config.write_all = False # Single scene only
config.dry_run = True # Check without rendering
class DebugScene(Scene):
def construct(self):
# Add debugging information
config.show_in_file_browser = True
text = Text("Debug Scene")
self.add(text)
# Performance monitoring
import time
start_time = time.time()
self.play(Indicate(text))
render_time = time.time() - start_time
logger.info(f"Render time: {render_time:.2f}s")# Configuration for batch processing
config.write_all = True # Render all scenes
config.output_dir = "batch_output"
# Render multiple scenes with different settings
scenes_config = [
{"scene": "Scene1", "quality": "low_quality"},
{"scene": "Scene2", "quality": "high_quality"},
{"scene": "Scene3", "quality": "production_quality"}
]
for scene_cfg in scenes_config:
with tempconfig({"quality": scene_cfg["quality"]}):
# Render scene with specific quality
passInstall with Tessl CLI
npx tessl i tessl/pypi-manim