0
# Utilities and Constants
1
2
ManimGL provides extensive utilities and constants that support animation development, mathematical operations, and visual styling. These include mathematical constants, color definitions, rate functions, vector operations, and development tools.
3
4
## Capabilities
5
6
### Mathematical Constants
7
8
Fundamental mathematical constants for calculations and positioning.
9
10
```python { .api }
11
# Mathematical constants
12
PI = 3.141592653589793
13
TAU = 6.283185307179586 # 2 * PI
14
E = 2.718281828459045
15
16
# Angle conversion
17
DEGREES = PI / 180
18
RADIANS = 1
19
DEG = DEGREES
20
21
# Common angles
22
RIGHT_ANGLE = PI / 2
23
STRAIGHT_ANGLE = PI
24
FULL_ROTATION = TAU
25
```
26
27
### Directional Constants
28
29
Standard directional vectors for positioning and movement.
30
31
```python { .api }
32
# Cardinal directions (3D vectors)
33
ORIGIN = np.array([0.0, 0.0, 0.0])
34
UP = np.array([0.0, 1.0, 0.0])
35
DOWN = np.array([0.0, -1.0, 0.0])
36
LEFT = np.array([-1.0, 0.0, 0.0])
37
RIGHT = np.array([1.0, 0.0, 0.0])
38
IN = np.array([0.0, 0.0, -1.0])
39
OUT = np.array([0.0, 0.0, 1.0])
40
41
# Axis vectors
42
X_AXIS = np.array([1.0, 0.0, 0.0])
43
Y_AXIS = np.array([0.0, 1.0, 0.0])
44
Z_AXIS = np.array([0.0, 0.0, 1.0])
45
46
# Diagonal directions
47
UL = UP + LEFT # Up-Left
48
UR = UP + RIGHT # Up-Right
49
DL = DOWN + LEFT # Down-Left
50
DR = DOWN + RIGHT # Down-Right
51
52
# Normalized diagonal directions
53
normalize = lambda v: v / np.linalg.norm(v)
54
UL = normalize(UL)
55
UR = normalize(UR)
56
DL = normalize(DL)
57
DR = normalize(DR)
58
```
59
60
### Frame and Layout Constants
61
62
Constants for scene dimensions and spacing.
63
64
```python { .api }
65
# Frame dimensions
66
FRAME_HEIGHT = 8.0
67
FRAME_WIDTH = 14.222222222222221 # 16:9 aspect ratio
68
FRAME_SHAPE = (FRAME_HEIGHT, FRAME_WIDTH)
69
FRAME_X_RADIUS = FRAME_WIDTH / 2
70
FRAME_Y_RADIUS = FRAME_HEIGHT / 2
71
72
# Frame edges
73
TOP = FRAME_Y_RADIUS * UP
74
BOTTOM = FRAME_Y_RADIUS * DOWN
75
LEFT_SIDE = FRAME_X_RADIUS * LEFT
76
RIGHT_SIDE = FRAME_X_RADIUS * RIGHT
77
78
# Standard spacing
79
SMALL_BUFF = 0.1
80
MED_SMALL_BUFF = 0.25
81
MED_LARGE_BUFF = 0.5
82
LARGE_BUFF = 1.0
83
DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF
84
DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF
85
```
86
87
### Color Constants
88
89
Comprehensive color palette for styling objects and animations.
90
91
```python { .api }
92
# Primary colors
93
BLACK = "#000000"
94
WHITE = "#FFFFFF"
95
GREY = GRAY = "#888888"
96
RED = "#FC6255"
97
GREEN = "#58C4DD"
98
BLUE = "#5DEDE8"
99
YELLOW = "#F0F91A"
100
PURPLE = "#BC85FF"
101
ORANGE = "#FFAB00"
102
PINK = "#FF006E"
103
104
# Color intensity variants (A=darkest, E=lightest)
105
BLUE_A = "#0E4B99"
106
BLUE_B = "#2E74B5"
107
BLUE_C = "#5DEDE8" # Standard BLUE
108
BLUE_D = "#83C9E2"
109
BLUE_E = "#A8D8EA"
110
111
GREEN_A = "#2FA933"
112
GREEN_B = "#4CBB17"
113
GREEN_C = "#58C4DD" # Standard GREEN
114
GREEN_D = "#83DDDD"
115
GREEN_E = "#A8E6CF"
116
117
RED_A = "#8B0000"
118
RED_B = "#CD212A"
119
RED_C = "#FC6255" # Standard RED
120
RED_D = "#FF8080"
121
RED_E = "#FFA8A8"
122
123
YELLOW_A = "#E1A95F"
124
YELLOW_B = "#F4D03F"
125
YELLOW_C = "#F0F91A" # Standard YELLOW
126
YELLOW_D = "#FFFF7F"
127
YELLOW_E = "#FFFFCC"
128
129
PURPLE_A = "#644172"
130
PURPLE_B = "#7759A9"
131
PURPLE_C = "#BC85FF" # Standard PURPLE
132
PURPLE_D = "#D2A9F0"
133
PURPLE_E = "#E8D5FF"
134
135
# Special colors
136
MAROON = "#C32148"
137
TEAL = "#49A88F"
138
GOLD = "#C78D46"
139
GREY_BROWN = "#736357"
140
DARK_BROWN = "#8B4513"
141
LIGHT_BROWN = "#CD853F"
142
GREEN_SCREEN = "#00FF00"
143
144
# Color collections
145
MANIM_COLORS = [
146
BLUE_C, GREEN_C, RED_C, YELLOW_C, PURPLE_C,
147
ORANGE, PINK, TEAL, GOLD, MAROON
148
]
149
150
COLORMAP_3B1B = {
151
"BLUE": BLUE,
152
"GREEN": GREEN,
153
"RED": RED,
154
"YELLOW": YELLOW,
155
"PURPLE": PURPLE
156
}
157
```
158
159
### Rate Functions
160
161
Animation timing functions that control the pacing and easing of animations.
162
163
```python { .api }
164
def linear(t):
165
"""
166
Linear interpolation (constant speed).
167
168
Parameters:
169
- t: float, time parameter (0-1)
170
171
Returns:
172
float, interpolated value (0-1)
173
"""
174
return t
175
176
def smooth(t):
177
"""
178
Smooth ease in/out using cubic interpolation.
179
180
Parameters:
181
- t: float, time parameter (0-1)
182
183
Returns:
184
float, smoothed value (0-1)
185
"""
186
return 3*t**2 - 2*t**3
187
188
def rush_into(t):
189
"""
190
Slow start, accelerating finish.
191
192
Parameters:
193
- t: float, time parameter (0-1)
194
195
Returns:
196
float, eased value (0-1)
197
"""
198
return 2 * smooth(t / 2.0)
199
200
def rush_from(t):
201
"""
202
Fast start, decelerating finish.
203
204
Parameters:
205
- t: float, time parameter (0-1)
206
207
Returns:
208
float, eased value (0-1)
209
"""
210
return 2 * smooth(t / 2.0 + 0.5) - 1
211
212
def slow_into(t):
213
"""
214
Very slow start, normal finish.
215
216
Parameters:
217
- t: float, time parameter (0-1)
218
219
Returns:
220
float, eased value (0-1)
221
"""
222
return np.sqrt(t)
223
224
def double_smooth(t):
225
"""
226
Double smoothing for extra ease.
227
228
Parameters:
229
- t: float, time parameter (0-1)
230
231
Returns:
232
float, double-smoothed value (0-1)
233
"""
234
return smooth(smooth(t))
235
236
def there_and_back(t):
237
"""
238
Go to 1 and back to 0 (triangle wave).
239
240
Parameters:
241
- t: float, time parameter (0-1)
242
243
Returns:
244
float, triangle wave value (0-1)
245
"""
246
return 1 - abs(2*t - 1)
247
248
def wiggle(t, wiggles=2):
249
"""
250
Oscillating motion.
251
252
Parameters:
253
- t: float, time parameter (0-1)
254
- wiggles: float, number of oscillations
255
256
Returns:
257
float, oscillating value (0-1)
258
"""
259
return there_and_back(t) * np.sin(wiggles * TAU * t)
260
261
def overshoot(t):
262
"""
263
Overshoot and settle back.
264
265
Parameters:
266
- t: float, time parameter (0-1)
267
268
Returns:
269
float, overshoot curve (0-1)
270
"""
271
return smooth(t) * (1 + np.sin(PI * t))
272
273
def exponential_decay(t, half_life=0.1):
274
"""
275
Exponential decay curve.
276
277
Parameters:
278
- t: float, time parameter (0-1)
279
- half_life: float, decay rate
280
281
Returns:
282
float, decayed value (0-1)
283
"""
284
return np.exp(-t / half_life)
285
286
def lingering(t):
287
"""
288
Stay near 0, then rush to 1.
289
290
Parameters:
291
- t: float, time parameter (0-1)
292
293
Returns:
294
float, lingering curve (0-1)
295
"""
296
return np.clip(smooth(2*t - 1), 0, 1)
297
298
def running_start(t, pull_factor=-0.5):
299
"""
300
Go backward before moving forward.
301
302
Parameters:
303
- t: float, time parameter (0-1)
304
- pull_factor: float, how far to pull back
305
306
Returns:
307
float, running start curve
308
"""
309
return bezier([0, 0, pull_factor, pull_factor, 1, 1, 1])(t)
310
311
def not_quite_there(func=smooth, proportion=0.7):
312
"""
313
Modified function that doesn't quite reach 1.
314
315
Parameters:
316
- func: callable, base rate function
317
- proportion: float, maximum value to reach
318
319
Returns:
320
callable, modified rate function
321
"""
322
return lambda t: proportion * func(t)
323
```
324
325
### Vector Operations
326
327
Mathematical operations for 3D vectors and transformations.
328
329
```python { .api }
330
def get_norm(vector):
331
"""
332
Calculate vector magnitude/length.
333
334
Parameters:
335
- vector: np.array, input vector
336
337
Returns:
338
float, vector magnitude
339
"""
340
return np.linalg.norm(vector)
341
342
def normalize(vector, fall_back=None):
343
"""
344
Normalize vector to unit length.
345
346
Parameters:
347
- vector: np.array, input vector
348
- fall_back: np.array, fallback if vector is zero
349
350
Returns:
351
np.array, normalized vector
352
"""
353
norm = get_norm(vector)
354
if norm == 0:
355
return fall_back or np.array([1, 0, 0])
356
return vector / norm
357
358
def cross(v1, v2):
359
"""
360
Calculate cross product of two vectors.
361
362
Parameters:
363
- v1: np.array, first vector
364
- v2: np.array, second vector
365
366
Returns:
367
np.array, cross product vector
368
"""
369
return np.cross(v1, v2)
370
371
def dot(v1, v2):
372
"""
373
Calculate dot product of two vectors.
374
375
Parameters:
376
- v1: np.array, first vector
377
- v2: np.array, second vector
378
379
Returns:
380
float, dot product
381
"""
382
return np.dot(v1, v2)
383
384
def angle_between_vectors(v1, v2):
385
"""
386
Calculate angle between two vectors.
387
388
Parameters:
389
- v1: np.array, first vector
390
- v2: np.array, second vector
391
392
Returns:
393
float, angle in radians
394
"""
395
cos_angle = dot(normalize(v1), normalize(v2))
396
return np.arccos(np.clip(cos_angle, -1, 1))
397
398
def angle_of_vector(vector):
399
"""
400
Calculate angle of vector from positive x-axis.
401
402
Parameters:
403
- vector: np.array, input vector
404
405
Returns:
406
float, angle in radians
407
"""
408
return np.arctan2(vector[1], vector[0])
409
410
def rotate_vector(vector, angle, axis=OUT):
411
"""
412
Rotate vector around specified axis.
413
414
Parameters:
415
- vector: np.array, vector to rotate
416
- angle: float, rotation angle in radians
417
- axis: np.array, rotation axis
418
419
Returns:
420
np.array, rotated vector
421
"""
422
return np.dot(rotation_matrix(angle, axis), vector)
423
424
def rotation_matrix(angle, axis):
425
"""
426
Create rotation matrix for axis-angle rotation.
427
428
Parameters:
429
- angle: float, rotation angle in radians
430
- axis: np.array, rotation axis (will be normalized)
431
432
Returns:
433
np.array, 3x3 rotation matrix
434
"""
435
axis = normalize(axis)
436
cos_angle = np.cos(angle)
437
sin_angle = np.sin(angle)
438
439
return cos_angle * np.eye(3) + \
440
sin_angle * np.array([[0, -axis[2], axis[1]],
441
[axis[2], 0, -axis[0]],
442
[-axis[1], axis[0], 0]]) + \
443
(1 - cos_angle) * np.outer(axis, axis)
444
445
def project_along_vector(point, vector):
446
"""
447
Project point onto line defined by vector.
448
449
Parameters:
450
- point: np.array, point to project
451
- vector: np.array, line direction
452
453
Returns:
454
np.array, projected point
455
"""
456
return dot(point, normalize(vector)) * normalize(vector)
457
458
def perpendicular_bisector(line_start, line_end):
459
"""
460
Find perpendicular bisector of line segment.
461
462
Parameters:
463
- line_start: np.array, line start point
464
- line_end: np.array, line end point
465
466
Returns:
467
tuple, (midpoint, perpendicular_direction)
468
"""
469
midpoint = (line_start + line_end) / 2
470
direction = line_end - line_start
471
perp = np.array([-direction[1], direction[0], direction[2]])
472
return midpoint, normalize(perp)
473
```
474
475
### Color Operations
476
477
Functions for color manipulation and interpolation.
478
479
```python { .api }
480
def color_to_rgba(color, alpha=1):
481
"""
482
Convert color to RGBA tuple.
483
484
Parameters:
485
- color: str or tuple, color specification
486
- alpha: float, opacity (0-1)
487
488
Returns:
489
tuple, (r, g, b, a) values (0-1)
490
"""
491
# Implementation handles hex, named colors, RGB tuples
492
pass
493
494
def rgb_to_color(rgb):
495
"""
496
Convert RGB tuple to color string.
497
498
Parameters:
499
- rgb: tuple, (r, g, b) values (0-1 or 0-255)
500
501
Returns:
502
str, hex color string
503
"""
504
pass
505
506
def rgba_to_color(rgba):
507
"""
508
Convert RGBA tuple to color (ignoring alpha).
509
510
Parameters:
511
- rgba: tuple, (r, g, b, a) values
512
513
Returns:
514
str, hex color string
515
"""
516
pass
517
518
def interpolate_color(color1, color2, alpha):
519
"""
520
Interpolate between two colors.
521
522
Parameters:
523
- color1: str, first color
524
- color2: str, second color
525
- alpha: float, interpolation factor (0-1)
526
527
Returns:
528
str, interpolated color
529
"""
530
pass
531
532
def average_color(*colors):
533
"""
534
Calculate average of multiple colors.
535
536
Parameters:
537
- colors: Color arguments
538
539
Returns:
540
str, averaged color
541
"""
542
pass
543
544
def invert_color(color):
545
"""
546
Invert color (complement).
547
548
Parameters:
549
- color: str, input color
550
551
Returns:
552
str, inverted color
553
"""
554
pass
555
556
def color_gradient(colors, length):
557
"""
558
Create gradient of colors.
559
560
Parameters:
561
- colors: list, colors for gradient
562
- length: int, number of gradient steps
563
564
Returns:
565
list, gradient colors
566
"""
567
pass
568
```
569
570
### File and Path Operations
571
572
Utilities for file handling and path management.
573
574
```python { .api }
575
def guarantee_existence(path):
576
"""
577
Ensure directory exists, create if necessary.
578
579
Parameters:
580
- path: str, directory path
581
582
Returns:
583
str, normalized path
584
"""
585
pass
586
587
def get_full_raster_image_path(image_file_name):
588
"""
589
Get full path to raster image file.
590
591
Parameters:
592
- image_file_name: str, image filename
593
594
Returns:
595
str, full path to image
596
"""
597
pass
598
599
def get_full_vector_image_path(vector_file_name):
600
"""
601
Get full path to vector image file.
602
603
Parameters:
604
- vector_file_name: str, vector filename
605
606
Returns:
607
str, full path to vector file
608
"""
609
pass
610
611
def get_directories():
612
"""
613
Get standard ManimGL directories.
614
615
Returns:
616
dict, directory paths
617
"""
618
pass
619
```
620
621
### Development and Debug Utilities
622
623
Tools for development, debugging, and performance analysis.
624
625
```python { .api }
626
def get_time_progression(run_time, n_iterations, dt):
627
"""
628
Generate time progression for animations.
629
630
Parameters:
631
- run_time: float, total animation time
632
- n_iterations: int, number of steps
633
- dt: float, time step
634
635
Returns:
636
np.array, time values
637
"""
638
pass
639
640
def binary_search(function, target, lower_bound, upper_bound, tolerance=1e-4):
641
"""
642
Binary search for function root.
643
644
Parameters:
645
- function: callable, function to search
646
- target: float, target value
647
- lower_bound: float, search lower bound
648
- upper_bound: float, search upper bound
649
- tolerance: float, convergence tolerance
650
651
Returns:
652
float, found root
653
"""
654
pass
655
656
class DebugTeX:
657
"""
658
Debugging utilities for LaTeX rendering.
659
"""
660
@staticmethod
661
def debug_tex(tex_string):
662
"""Debug LaTeX compilation issues."""
663
pass
664
665
class PerformanceTimer:
666
"""
667
Context manager for timing code execution.
668
"""
669
def __enter__(self):
670
pass
671
672
def __exit__(self, *args):
673
pass
674
```
675
676
## Usage Examples
677
678
### Using Constants
679
680
```python
681
from manimgl import *
682
683
class ConstantsExample(Scene):
684
def construct(self):
685
# Using directional constants
686
circle = Circle().shift(UP * 2 + RIGHT * 3)
687
688
# Using color constants
689
square = Square(color=BLUE_B).shift(DOWN * 2)
690
691
# Using mathematical constants
692
arc = Arc(angle=PI/3, radius=2, color=YELLOW)
693
694
self.add(circle, square, arc)
695
self.wait()
696
```
697
698
### Custom Rate Functions
699
700
```python
701
class RateFunctionExample(Scene):
702
def construct(self):
703
square = Square()
704
705
# Use different rate functions
706
self.play(square.animate.shift(UP), rate_func=smooth)
707
self.play(square.animate.shift(RIGHT), rate_func=rush_into)
708
self.play(square.animate.shift(DOWN), rate_func=there_and_back)
709
self.play(square.animate.shift(LEFT), rate_func=wiggle)
710
self.wait()
711
```
712
713
### Vector Operations
714
715
```python
716
class VectorExample(Scene):
717
def construct(self):
718
# Create vectors
719
v1 = np.array([2, 1, 0])
720
v2 = np.array([1, 2, 0])
721
722
# Vector operations
723
v1_norm = normalize(v1)
724
cross_product = cross(v1, v2)
725
angle = angle_between_vectors(v1, v2)
726
727
# Visualize results
728
arrow1 = Arrow(ORIGIN, v1, color=RED)
729
arrow2 = Arrow(ORIGIN, v2, color=BLUE)
730
arrow3 = Arrow(ORIGIN, cross_product, color=GREEN)
731
732
angle_text = Text(f"Angle: {angle:.2f} rad").to_edge(UP)
733
734
self.add(arrow1, arrow2, arrow3, angle_text)
735
self.wait()
736
```
737
738
### Color Interpolation
739
740
```python
741
class ColorExample(Scene):
742
def construct(self):
743
circles = VGroup(*[
744
Circle(radius=0.5).shift(i*RIGHT - 3*RIGHT)
745
for i in range(7)
746
])
747
748
# Interpolate between colors
749
for i, circle in enumerate(circles):
750
alpha = i / (len(circles) - 1)
751
color = interpolate_color(RED, BLUE, alpha)
752
circle.set_color(color)
753
754
self.add(circles)
755
self.wait()
756
```
757
758
### File Operations
759
760
```python
761
class FileExample(Scene):
762
def construct(self):
763
# Ensure output directory exists
764
output_dir = "./my_animations"
765
guarantee_existence(output_dir)
766
767
# Load image
768
image_path = get_full_raster_image_path("my_image.png")
769
770
text = Text("File operations complete")
771
self.add(text)
772
self.wait()
773
```