Manim 不是录一整个视频,而是把每段动画单独渲成小片段再拼起来,这正是它能「改一段只重渲一段」的原因。这段代码把分帧渲染到缓存的链路画清楚,并说明三个缓存相关参数的区别。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from manim import *
class CachePipelineDemo(Scene):
"""--dry_run 与缓存:第二次渲染为什么秒过"""
def construct(self):
title = Text("缓存与 --dry_run:分帧渲染的复用机制", font_size=31).to_edge(UP, buff=0.4)
self.play(Write(title))
def step(text, color, w=3.0):
box = RoundedRectangle(corner_radius=0.1, width=w, height=0.95,
stroke_color=color, stroke_width=2,
fill_color=color, fill_opacity=0.12)
label = Text(text, font_size=19).move_to(box.get_center())
return VGroup(box, label)
s1 = step("逐段动画", BLUE)
s2 = step("partial_movie_files", YELLOW, 3.9)
s3 = step("拼接成 mp4", GREEN)
row = VGroup(s1, s2, s3).arrange(RIGHT, buff=0.85).next_to(title, DOWN, buff=0.75)
a1 = Arrow(s1.get_right(), s2.get_left(), buff=0.1, color=GREY_B)
a2 = Arrow(s2.get_right(), s3.get_left(), buff=0.1, color=GREY_B)
self.play(FadeIn(s1), FadeIn(a1), FadeIn(s2), FadeIn(a2), FadeIn(s3))
self.wait(0.4)
files = VGroup(*[Rectangle(width=0.52, height=0.34, stroke_color=YELLOW,
stroke_width=1.5, fill_color=YELLOW, fill_opacity=0.3)
for _ in range(6)]).arrange(RIGHT, buff=0.1)
files.next_to(s2, DOWN, buff=0.35)
self.play(LaggedStart(*[FadeIn(f, shift=DOWN * 0.15) for f in files],
lag_ratio=0.12))
hash_note = Text("每段动画按代码哈希命名", font_size=17, color=GREY_B)
hash_note.next_to(files, DOWN, buff=0.16)
self.play(FadeIn(hash_note))
self.wait(0.5)
# 第二次渲染:命中缓存
hit = VGroup(
Text("第二次运行:", font_size=20, color=GREEN),
Text("Animation 3 : Using cached", font="Consolas", font_size=19, color=GREEN),
).arrange(RIGHT, buff=0.18)
hit.next_to(hash_note, DOWN, buff=0.45)
self.play(FadeIn(hit, shift=UP * 0.2))
for f in files:
self.play(f.animate.set_fill(GREEN, opacity=0.55), run_time=0.12)
self.wait(0.4)
tips = VGroup(
Text("--disable_caching:关掉缓存,强制重渲", font_size=20, color=ORANGE),
Text("--flush_cache:先清空旧缓存再渲染", font_size=20, color=ORANGE),
Text("--dry_run:只走流程写日志,不真正出片", font_size=20, color=ORANGE),
).arrange(DOWN, buff=0.13, aligned_edge=LEFT)
tips.next_to(hit, DOWN, buff=0.42)
self.play(LaggedStart(*[FadeIn(t, shift=RIGHT * 0.15) for t in tips],
lag_ratio=0.22))
self.wait(2.0)

演示视频

下载 Python 脚本

要点

  • 每段动画落在 media/videos/{脚本名}/{画质}/partial_movie_files/{场景名}/ 下,文件名由代码内容哈希得到,代码不改就一直命中
  • 命中缓存时日志打印 Animation N : Using cached;--disable_caching 强制重渲,--flush_cache 先清缓存再渲
  • --dry_run 只把流程走一遍、不真正写视频,用来提前发现脚本报错

代码来源:Manim Community 官方文档 Guides / Configuration 与 CLI 参考(MIT),示例代码按 Manim CE 0.20.1 编写并实跑验证。