0
# Scene Management
1
2
Scene classes and animation orchestration system for managing the animation lifecycle, mobject placement, and rendering coordination. Scenes serve as the main canvas where mathematical objects are added, animated, and removed to create cohesive mathematical visualizations.
3
4
## Capabilities
5
6
### Base Scene
7
8
The fundamental scene class that provides the core animation framework, mobject management, and rendering coordination for all Manim animations.
9
10
```python { .api }
11
class Scene:
12
"""
13
Base scene class for all animations providing the main canvas and orchestration system.
14
15
Attributes:
16
- mobjects: list[Mobject] - Current mobjects on screen
17
- camera: Camera - Scene camera for rendering
18
- renderer: Renderer - Backend rendering engine
19
"""
20
21
def __init__(
22
renderer: str = None,
23
camera_class: type = Camera,
24
always_update_mobjects: bool = False,
25
random_seed: int = None,
26
skip_animations: bool = False
27
) -> None:
28
"""
29
Initialize scene with rendering and camera configuration.
30
31
Parameters:
32
- renderer: Rendering backend ('cairo' or 'opengl')
33
- camera_class: Camera class to use for the scene
34
- always_update_mobjects: Whether to update mobjects every frame
35
- random_seed: Seed for random number generation
36
- skip_animations: Skip animations for faster rendering
37
"""
38
39
def construct(self) -> None:
40
"""
41
Add content to the scene. Override this method with your animation code.
42
43
This is the main method where scene content is defined. All mobject
44
creation, positioning, and animation calls should be placed here.
45
"""
46
47
def setup(self) -> None:
48
"""
49
Setup code run before construct(). Override for initialization.
50
51
Used for common setup tasks that should run before the main
52
scene construction, such as configuring camera settings or
53
initializing reusable objects.
54
"""
55
56
def tear_down(self) -> None:
57
"""
58
Cleanup code run after construct(). Override for finalization.
59
60
Used for cleanup tasks that should run after scene construction
61
is complete, such as saving state or releasing resources.
62
"""
63
64
def render(preview: bool = False) -> None:
65
"""
66
Render the complete scene by calling setup(), construct(), and tear_down().
67
68
Parameters:
69
- preview: If true, opens scene in file viewer after rendering
70
"""
71
72
# Mobject Management
73
def add(*mobjects: Mobject) -> None:
74
"""
75
Add mobjects to the scene. Mobjects are displayed from background to foreground
76
in the order they are added.
77
78
Parameters:
79
- *mobjects: Variable number of mobjects to add to scene
80
"""
81
82
def remove(*mobjects: Mobject) -> None:
83
"""
84
Remove mobjects from the scene and stop displaying them.
85
86
Parameters:
87
- *mobjects: Variable number of mobjects to remove from scene
88
"""
89
90
def add_foreground_mobjects(*mobjects: Mobject) -> None:
91
"""
92
Add mobjects to foreground layer, ensuring they appear on top of all other objects.
93
94
Parameters:
95
- *mobjects: Variable number of mobjects to add to foreground
96
"""
97
98
def remove_foreground_mobjects(*mobjects: Mobject) -> None:
99
"""
100
Remove mobjects from the foreground layer.
101
102
Parameters:
103
- *mobjects: Variable number of mobjects to remove from foreground
104
"""
105
106
# Animation Control
107
def play(
108
*animations: Animation | Mobject,
109
subcaption: str = None,
110
subcaption_duration: float = None,
111
subcaption_offset: float = 0
112
) -> None:
113
"""
114
Play animations simultaneously with precise timing control.
115
116
Parameters:
117
- *animations: Animation objects or mobjects with .animate transformations
118
- subcaption: Text to display as subtitle during animation
119
- subcaption_duration: Duration to display subtitle
120
- subcaption_offset: Time offset for subtitle display
121
"""
122
123
def wait(
124
duration: float = 1.0,
125
stop_condition: Callable[[], bool] = None,
126
frozen_frame: bool = True
127
) -> None:
128
"""
129
Pause animation for specified duration or until condition is met.
130
131
Parameters:
132
- duration: Time to wait in seconds
133
- stop_condition: Function returning True when wait should end
134
- frozen_frame: Whether to continue updating during wait
135
"""
136
137
def wait_until(
138
stop_condition: Callable[[], bool],
139
max_time: float = 60
140
) -> None:
141
"""
142
Wait until condition is satisfied, up to maximum duration.
143
144
Parameters:
145
- stop_condition: Function returning True when wait should end
146
- max_time: Maximum time to wait in seconds
147
"""
148
149
# Scene State
150
def clear() -> None:
151
"""Remove all mobjects from the scene."""
152
153
def get_mobjects() -> list[Mobject]:
154
"""Get list of all mobjects currently in the scene."""
155
156
def get_mobject_family_members() -> list[Mobject]:
157
"""Get all mobjects including submobjects in flattened list."""
158
159
# Updaters
160
def add_updater(func: Callable[[float], None]) -> None:
161
"""
162
Add function to be called every frame with delta time.
163
164
Parameters:
165
- func: Function taking dt (delta time) parameter
166
"""
167
168
def remove_updater(func: Callable[[float], None]) -> None:
169
"""
170
Remove previously added updater function.
171
172
Parameters:
173
- func: Function to remove from updater list
174
"""
175
176
# Media Integration
177
def add_subcaption(
178
content: str,
179
duration: float = 1,
180
offset: float = 0
181
) -> None:
182
"""
183
Add subtitle text to be displayed during animation.
184
185
Parameters:
186
- content: Subtitle text content
187
- duration: Duration to display subtitle in seconds
188
- offset: Time offset from current animation time
189
"""
190
191
def add_sound(
192
sound_file: str,
193
time_offset: float = 0,
194
gain: float = None,
195
**kwargs
196
) -> None:
197
"""
198
Add audio file to be played during animation.
199
200
Parameters:
201
- sound_file: Path to audio file
202
- time_offset: Time offset from current animation time
203
- gain: Audio volume adjustment
204
"""
205
```
206
207
### Moving Camera Scene
208
209
Scene class with movable and zoomable camera for creating dynamic perspectives and following objects during animations.
210
211
```python { .api }
212
class MovingCameraScene(Scene):
213
"""
214
Scene with camera that can move, zoom, and change perspective dynamically.
215
216
The camera frame can be animated like any other mobject, allowing for
217
cinematic camera movements and focus changes during animations.
218
"""
219
220
def setup() -> None:
221
"""Initialize moving camera with appropriate camera class."""
222
223
# Camera frame is accessible as self.camera.frame
224
# Can be animated like: self.play(self.camera.frame.animate.move_to(target))
225
```
226
227
### Three-Dimensional Scene
228
229
Scene class optimized for 3D animations with camera controls for 3D perspective, rotation, and fixed-orientation objects.
230
231
```python { .api }
232
class ThreeDScene(Scene):
233
"""
234
Scene specialized for 3D animations with enhanced camera controls.
235
236
Provides methods for setting camera orientation, managing 3D perspective,
237
and handling objects that should maintain fixed orientation relative to camera.
238
"""
239
240
def set_camera_orientation(
241
phi: float = None,
242
theta: float = None,
243
gamma: float = None,
244
zoom: float = None
245
) -> None:
246
"""
247
Set 3D camera orientation using spherical coordinates.
248
249
Parameters:
250
- phi: Angle from z-axis (inclination) in radians
251
- theta: Angle from x-axis (azimuth) in radians
252
- gamma: Roll angle around camera's forward axis
253
- zoom: Camera zoom level
254
"""
255
256
def begin_ambient_camera_rotation(rate: float = 0.02) -> None:
257
"""
258
Start continuous camera rotation around the scene.
259
260
Parameters:
261
- rate: Rotation speed in radians per second
262
"""
263
264
def stop_ambient_camera_rotation() -> None:
265
"""Stop ambient camera rotation."""
266
267
def begin_3dillusion_camera_rotation(
268
rate: float = 1,
269
origin_theta: float = None,
270
origin_phi: float = None
271
) -> None:
272
"""
273
Start camera rotation that creates 3D illusion effect.
274
275
Parameters:
276
- rate: Rotation speed multiplier
277
- origin_theta: Starting theta angle
278
- origin_phi: Starting phi angle
279
"""
280
281
def stop_3dillusion_camera_rotation() -> None:
282
"""Stop 3D illusion camera rotation."""
283
284
def move_camera(
285
phi: float = None,
286
theta: float = None,
287
gamma: float = None,
288
zoom: float = None,
289
frame_center: np.ndarray = None,
290
**kwargs
291
) -> Animation:
292
"""
293
Animate camera to new orientation and position.
294
295
Parameters:
296
- phi: Target inclination angle
297
- theta: Target azimuth angle
298
- gamma: Target roll angle
299
- zoom: Target zoom level
300
- frame_center: Target center point for camera
301
302
Returns:
303
- Animation that moves camera to target state
304
"""
305
306
def get_moving_mobjects(*animations: Animation) -> list[Mobject]:
307
"""Get list of mobjects that will be moved by given animations."""
308
309
def add_fixed_orientation_mobjects(*mobjects: Mobject) -> None:
310
"""
311
Add mobjects that maintain fixed orientation relative to camera.
312
313
These mobjects will always face the camera regardless of camera rotation,
314
useful for text labels and 2D objects in 3D scenes.
315
316
Parameters:
317
- *mobjects: Mobjects to maintain fixed camera-relative orientation
318
"""
319
320
def add_fixed_in_frame_mobjects(*mobjects: Mobject) -> None:
321
"""
322
Add mobjects fixed in camera frame (like UI elements).
323
324
These mobjects remain in fixed screen positions regardless of
325
camera movement, useful for legends, titles, and UI elements.
326
327
Parameters:
328
- *mobjects: Mobjects to fix in camera frame
329
"""
330
331
def remove_fixed_orientation_mobjects(*mobjects: Mobject) -> None:
332
"""Remove mobjects from fixed orientation tracking."""
333
334
def remove_fixed_in_frame_mobjects(*mobjects: Mobject) -> None:
335
"""Remove mobjects from fixed frame positioning."""
336
```
337
338
### Vector Space Scene
339
340
Specialized scene for linear algebra visualizations with coordinate systems and vector operations.
341
342
```python { .api }
343
class VectorScene(Scene):
344
"""
345
Scene optimized for vector and linear algebra visualizations.
346
347
Includes coordinate system setup and utilities for vector operations,
348
transformations, and mathematical demonstrations.
349
"""
350
351
def setup() -> None:
352
"""Setup coordinate plane and vector visualization tools."""
353
354
def add_plane(animate: bool = False, **plane_config) -> NumberPlane:
355
"""
356
Add coordinate plane to scene.
357
358
Parameters:
359
- animate: Whether to animate plane creation
360
- **plane_config: Configuration options for NumberPlane
361
362
Returns:
363
- NumberPlane object added to scene
364
"""
365
366
def add_vector(
367
vector: np.ndarray,
368
color: str = YELLOW,
369
animate: bool = True,
370
**kwargs
371
) -> Arrow:
372
"""
373
Add vector arrow to scene.
374
375
Parameters:
376
- vector: Vector coordinates as numpy array
377
- color: Vector arrow color
378
- animate: Whether to animate vector creation
379
380
Returns:
381
- Arrow object representing the vector
382
"""
383
384
class LinearTransformationScene(VectorScene):
385
"""
386
Scene for demonstrating linear transformations with coordinate grids.
387
388
Provides tools for applying and visualizing matrix transformations
389
on coordinate systems and vector objects.
390
"""
391
392
def setup() -> None:
393
"""Setup transformation scene with basis vectors and grid."""
394
395
def apply_matrix(
396
matrix: np.ndarray,
397
run_time: float = 2,
398
**kwargs
399
) -> None:
400
"""
401
Apply linear transformation matrix to all scene objects.
402
403
Parameters:
404
- matrix: 2x2 transformation matrix
405
- run_time: Duration of transformation animation
406
"""
407
408
def apply_transposed_matrix(
409
matrix: np.ndarray,
410
run_time: float = 2,
411
**kwargs
412
) -> None:
413
"""
414
Apply transposed linear transformation.
415
416
Parameters:
417
- matrix: 2x2 matrix to transpose and apply
418
- run_time: Duration of transformation animation
419
"""
420
421
def apply_nonlinear_transformation(
422
function: Callable,
423
run_time: float = 3,
424
**kwargs
425
) -> None:
426
"""
427
Apply nonlinear transformation function to scene objects.
428
429
Parameters:
430
- function: Function mapping (x,y) coordinates to new positions
431
- run_time: Duration of transformation animation
432
"""
433
```
434
435
### Specialized Scene Types
436
437
Additional scene classes for specific use cases and advanced functionality.
438
439
```python { .api }
440
class ZoomedScene(MovingCameraScene):
441
"""
442
Scene with zoomed inset view capabilities.
443
444
Allows creating zoomed-in regions that display detailed views
445
of specific scene areas while maintaining the main view.
446
"""
447
448
def setup() -> None:
449
"""Setup zoomed scene with zoom camera and display."""
450
451
def get_zoomed_display_pop_out_animation(**kwargs) -> AnimationGroup:
452
"""Get animation for zoomed display appearing with pop-out effect."""
453
454
def get_zoomed_display_pop_in_animation(**kwargs) -> AnimationGroup:
455
"""Get animation for zoomed display disappearing with pop-in effect."""
456
457
class SpecialThreeDScene(ThreeDScene):
458
"""
459
Enhanced 3D scene with additional specialized features.
460
461
Extends ThreeDScene with extra utilities for complex 3D
462
visualizations and advanced camera behaviors.
463
"""
464
465
def setup() -> None:
466
"""Setup special 3D scene with enhanced capabilities."""
467
```
468
469
## Usage Examples
470
471
### Basic Scene Structure
472
473
```python
474
from manim import *
475
476
class MyScene(Scene):
477
def construct(self):
478
# Create objects
479
circle = Circle(radius=2, color=BLUE)
480
square = Square(side_length=3, color=RED)
481
482
# Add to scene
483
self.add(circle, square)
484
485
# Animate
486
self.play(Create(circle))
487
self.play(Transform(circle, square))
488
self.wait(2)
489
```
490
491
### Moving Camera Scene
492
493
```python
494
class CameraExample(MovingCameraScene):
495
def construct(self):
496
square = Square()
497
self.add(square)
498
499
# Move camera to focus on square
500
self.play(
501
self.camera.frame.animate.move_to(square).scale(0.5)
502
)
503
self.wait(1)
504
505
# Return to original view
506
self.play(
507
self.camera.frame.animate.move_to(ORIGIN).scale(2)
508
)
509
```
510
511
### 3D Scene with Camera Control
512
513
```python
514
class ThreeDExample(ThreeDScene):
515
def construct(self):
516
# Set initial camera angle
517
self.set_camera_orientation(phi=75*DEGREES, theta=45*DEGREES)
518
519
# Create 3D objects
520
cube = Cube(side_length=2, fill_color=BLUE)
521
sphere = Sphere(radius=1, fill_color=RED)
522
523
self.add(cube, sphere)
524
525
# Rotate camera around scene
526
self.begin_ambient_camera_rotation(rate=0.1)
527
self.wait(5)
528
self.stop_ambient_camera_rotation()
529
```