The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add renderer comparison benchmarks
apoogdk55d776991737
diff --git a/scripts/benchmark/README.md b/scripts/benchmark/README.mdnew file mode 100644index 00000000..ed2aaf16--- /dev/null+++ b/scripts/benchmark/README.md@@ -0,0 +1,108 @@+# Benchmarks++manimgx, [Manim Community Edition](https://www.manim.community),+[ManimGL](https://github.com/3b1b/manim) and [Blender](https://www.blender.org), rendering+the same scenes to the same videos: 1920 × 1080 at 60 frames per second, H.264 in an MP4.++<p align="center">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="https://manimgx.academa.ai/images/benchmark-dark.svg">+ <source media="(prefers-color-scheme: light)" srcset="https://manimgx.academa.ai/images/benchmark-light.svg">+ <img alt="A bar chart of the render times of the orbit scene" src="https://manimgx.academa.ai/images/benchmark-light.svg" width="100%">+ </picture>+</p>++## Results++The median time from launch to a finished MP4, and how many times manimgx's it is, on a+MacBook Pro with an Apple M4 Pro (12 CPU cores, 16 GPU cores, 24 GB) under macOS 15.7, on+2026-09-29, at commit 8e95dd39:++| | orbit (3D) | morph (3D) | explainer (2D) |+| --- | ---: | ---: | ---: |+| **manimgx** 0.1.0 | **0.85 s** | **9.0 s** | **0.58 s** |+| ManimGL 1.7.2 | 6.2 s (7.3×) | 73 s (8.1×) | 6.1 s (11×) |+| Blender 5.2, Workbench | 18 s (22×) | 18 s (2.1×) | |+| Blender 5.2, EEVEE | 3 min 59 s (281×) | 4 min 14 s (28×) | |+| Manim CE 0.21.0 | 4 min 03 s (286×) | 11 min 42 s (78×) | 4.0 s (7.0×) |++- **Its videos are larger.** manimgx encodes with x264's ultrafast preset at CRF 18: the+ orbit scene is 71.7 MB, where the other tools write 3 to 6 MB. Encoding as Manim CE and+ ManimGL do, with the medium preset at CRF 23, manimgx renders it in 3.2 s instead of+ 1.2 s (both measured in one session, on a busier machine than the table's), into 5.8 MB:+ still twice as fast as ManimGL, and six times as fast as Blender's Workbench.+- **The morph scene is its hardest.** A surface rebuilt every frame costs manimgx 15 ms a+ frame, most of it spent refining the new surface in Python; Blender moves its mesh's+ points in place.+- **Runs.** Manim CE's morph ran once (a run takes twelve minutes) and its orbit four+ times, Blender's EEVEE and ManimGL's morph three times, and everything else five times;+ `results.json` has every run, with its CPU time, peak memory and the load average it+ started at.++## The scenes++Each scene is written once per tool, in the tool's own idiom and as alike as the tools+allow: manimgx's are three of its timed benchmarks' workloads, in+[`tests/benchmarks/scenes/`](../../tests/benchmarks/scenes) (`<scene>.py`), so the scenes this+page times are the ones every change is checked against; the others are in [`scenes/`](scenes)+(`<scene>_<tool>.py`):++- **orbit** (3D, 10 s): a 48 × 48 checkerboard surface, z = sin(x) cos(y), on 3D axes; a+ curve drawn across it over six seconds with a ball riding its tip; and the camera circling+ the whole time, so every frame is new.+- **morph** (3D, 10 s): a 48 × 48 checkerboard ripple, z = 0.8 sin(2r − phase), rebuilt+ every frame, with the camera circling it. Manim's tools rebuild it with `always_redraw`;+ Blender moves its mesh's points from a frame-change handler with numpy.+- **explainer** (2D, 9.5 s): a sine curve drawn on axes with a dot riding it, the area under+ its first arch, `y = \sin x` turning into its integral, then a tangent line sliding along+ the curve. Blender has no math typesetting, so it renders the 3D scenes only.++The frames at 1, 3, 5, 7 and 9 seconds of each tool's video: the geometry, the camera and+the timing are the same; the shading is each renderer's own.++++++++## How it was measured++- A run is the tool's own command (`manimgx render`, `manim render -qh`, `manimgl -w --hd`,+ `blender -b`), in a fresh process and a fresh folder, with the tool's caches empty (Manim+ CE's and ManimGL's LaTeX, manimgx's Typst layouts): an agent's first render of a new scene.+- Its time runs from launch to exit, when the MP4 is written. Its CPU time and peak memory+ are recorded too, in [`results.json`](results.json), with every run.+- Each contender renders each scene once to warm up (a run of more than two minutes counts+ instead), then the contenders take turns until each has five runs: three if a run takes+ over a minute, one if it takes over ten. The table shows the medians.+- Each video is checked for its length, then deleted.+- Each tool encodes with its own defaults: manimgx with x264's ultrafast preset at CRF 18+ (larger files, a faster encoder), Manim CE and ManimGL with libx264's medium preset at+ CRF 23, and Blender with its H.264 "medium quality" at the "good" speed.+- Blender renders with EEVEE, its default renderer, at its default 64 samples, and with+ Workbench, its fastest. ManimGL typesets with its minimal LaTeX template, `basic`.+- The machine was shared with other work while the runs were timed; each run records the+ load average it started at.++## Installing++| | Installs | Needs besides |+| --- | --- | --- |+| manimgx | 140 MB with its dependencies (`pip install manimgx`) | nothing |+| Manim CE | 250 MB with its dependencies | LaTeX for math (a TeX distribution: 0.4 GB for a basic one, several GB for a full one); Cairo and Pango on Linux |+| ManimGL | 350 MB with its dependencies | LaTeX, FFmpeg |+| Blender | a 0.9 GB application | |++## Running it++```sh+uv sync --group ce # manimgx, and Manim CE (the `ce` group)+uv venv --python 3.12 /tmp/manimgl # ManimGL, in an environment of its own+uv pip install --python /tmp/manimgl manimgl==1.7.2 setuptools+uv run --frozen python scripts/benchmark/run.py --manimgl /tmp/manimgl --blender /path/to/blender+uv run --frozen python scripts/benchmark/chart.py # the README's chart, from results.json+```++`run.py --only orbit --tools manimgx,manimgl` runs a part of it. The numbers also stand in+the README: change them together.diff --git a/scripts/benchmark/chart.py b/scripts/benchmark/chart.pynew file mode 100644index 00000000..d5d1ddd6--- /dev/null+++ b/scripts/benchmark/chart.py@@ -0,0 +1,204 @@+"""The README's chart: the benchmark's 3D scene as a race of bars, a light SVG and a dark one.++ uv run --frozen python scripts/benchmark/chart.py++Reads `results.json` (`run.py` writes it) and writes `docs/content/images/benchmark-light.svg`+and `benchmark-dark.svg`, which the README shows from the docs site, each where its color+scheme is. Each bar grows as its tool renders: in real time until manimgx is done and a+moment more, then fast-forwarded (the chart says by how much) until the slowest is done;+the chart then holds, and starts again. Without motion (`prefers-reduced-motion`), it is+the finished chart.+"""++import json+import math+from pathlib import Path++HERE = Path(__file__).parent+IMAGES = HERE.parents[1] / "docs" / "content" / "images"+SCENE = "orbit"+FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"+THEMES = {+ "light": {+ "text": "#1f2328",+ "muted": "#59636e",+ "grid": "#d1d9e0",+ "bar": "#b8c0ca",+ },+ "dark": {+ "text": "#f0f6fc",+ "muted": "#9198a1",+ "grid": "#3d444d",+ "bar": "#4d5561",+ },+}+WIDTH, LEFT, RIGHT, TOP, ROW, BAR = 880, 180, 92, 44, 44, 22+LIVE, FORWARD, HOLD, RESET = (+ 1.2,+ 3.5,+ 8.0,+ 0.4,+) # s: real time after the fastest, … ends+SPEEDS = (2, 5, 10, 20, 50, 100, 200, 500) # the fast-forward factors the chart names+++class Race:+ """The race's clock: real time until the fastest is done and `LIVE` seconds more, then+ faster and faster (exponentially), so that the slowest is done `FORWARD` seconds+ later; then the finished chart holds for `HOLD` seconds, and `RESET` shrinks it away.+ """++ def __init__(self, fastest: float, slowest: float) -> None:+ self.live = fastest + LIVE+ self.growth = math.log(max(slowest / self.live, 1.0001)) / FORWARD+ self.end = self.live + FORWARD+ self.period = self.end + HOLD + RESET++ def seconds(self, t: float) -> float:+ """The time the tools have rendered for, at t seconds of the race."""+ if t <= self.live:+ return t+ return self.live * math.exp(self.growth * (min(t, self.end) - self.live))++ def at(self, seconds: float) -> float:+ """When the race reaches a time rendered for (the inverse of `seconds`)."""+ if seconds <= self.live:+ return seconds+ return self.live + math.log(seconds / self.live) / self.growth+++def duration(seconds: float) -> str:+ """A time as the chart labels it: 0.85s, 6.2s, 27s, 4m 17s."""+ if seconds < 1:+ return f"{seconds:.2f}s"+ if seconds < 10:+ return f"{seconds:.1f}s"+ if seconds < 100:+ return f"{seconds:.0f}s"+ minutes, rest = divmod(round(seconds), 60)+ return f"{minutes}m {rest:02d}s"+++def chart(rows: list[tuple[str, float]], theme: dict[str, str]) -> str:+ """The bars, fastest first, on a scale of whole minutes, racing."""+ slowest = max(seconds for _, seconds in rows)+ race = Race(min(seconds for _, seconds in rows), slowest)+ minutes = int(slowest // 60) + 1+ span = WIDTH - LEFT - RIGHT++ def x(seconds: float) -> float:+ """Where a time is on the chart."""+ return LEFT + span * seconds / (60 * minutes)++ def percent(t: float) -> str:+ return f"{100 * t / race.period:.3f}%"++ reset = race.period - RESET+ height = TOP + ROW * len(rows) + 34+ styles = [+ (+ ".bar{transform-box:fill-box;transform-origin:0 50%;"+ f"animation:{race.period:.3f}s linear infinite}}"+ ),+ f".done{{animation:{race.period:.3f}s step-end infinite}}",+ (+ "@media (prefers-reduced-motion:reduce){.bar,.done,.clock{animation:none}"+ ".clock{opacity:0}}"+ ),+ ]+ parts = []+ bottom = TOP + ROW * len(rows)+ for minute in range(minutes + 1):+ at = x(60 * minute)+ parts.append(+ f'<line x1="{at:.1f}" y1="{TOP - 6}" x2="{at:.1f}" y2="{bottom}"'+ f' stroke="{theme["grid"]}" stroke-width="1"/>'+ )+ label = "0s" if minute == 0 else f"{minute}min"+ parts.append(+ f'<text x="{at:.1f}" y="{bottom + 22}" fill="{theme["muted"]}"'+ f' font-size="13" text-anchor="middle">{label}</text>'+ )+ for i, (name, seconds) in enumerate(rows):+ y = TOP + ROW * i + (ROW - BAR) / 2+ ours = name == "manimgx"+ weight = ' font-weight="700"' if ours else ""+ fill = "url(#manimgx)" if ours else theme["bar"]+ width = max(x(seconds) - LEFT, 3)+ done = race.at(seconds)+ # the bar's length through the race: sampled every 0.05 s until it is done+ stops = [0.0, *(k * 0.05 for k in range(1, int(done / 0.05) + 1)), done]+ frames = ["0%{transform:scaleX(0)}"]+ frames += [+ f"{percent(t)}{{transform:scaleX({race.seconds(t) / seconds:.4f})}}"+ for t in stops[1:]+ ]+ frames += [+ f"{percent(reset)}{{transform:scaleX(1)}}",+ "100%{transform:scaleX(0)}",+ ]+ styles.append(f"@keyframes b{i}{{{''.join(frames)}}}")+ styles.append(f"#b{i}{{animation-name:b{i}}}")+ styles.append(+ f"@keyframes t{i}{{0%{{opacity:0}}{percent(done)}{{opacity:1}}"+ f"{percent(reset)}{{opacity:0}}}}#t{i}{{animation-name:t{i}}}"+ )+ parts.append(+ f'<text x="{LEFT - 16}" y="{y + BAR / 2 + 5:.1f}" fill="{theme["text"]}"'+ f' text-anchor="end"{weight}>{name}</text>'+ )+ parts.append(+ f'<rect id="b{i}" class="bar" x="{LEFT}" y="{y:.1f}" width="{width:.1f}"'+ f' height="{BAR}" rx="4" fill="{fill}"/>'+ )+ parts.append(+ f'<text id="t{i}" class="done" x="{LEFT + width + 10:.1f}"'+ f' y="{y + BAR / 2 + 5:.1f}"'+ f' fill="{theme["text"] if ours else theme["muted"]}"{weight}>'+ f"{duration(seconds)}</text>"+ )+ # the clock: in real time, then fast-forwarded, by how much+ captions = [("real time", 0.0)]+ for factor in SPEEDS:+ t = race.live + math.log(factor / (race.growth * race.live)) / race.growth+ if race.live < t < race.end:+ captions.append((f"fast-forward ×{factor}", t))+ captions.append(("", race.end))+ for k, (text, start) in enumerate(captions[:-1]):+ stop = captions[k + 1][1]+ styles.append(+ f"@keyframes c{k}{{0%{{opacity:0}}{percent(start)}{{opacity:1}}"+ f"{percent(stop)}{{opacity:0}}}}"+ f"#c{k}{{animation:c{k} {race.period:.3f}s step-end infinite}}"+ )+ parts.append(+ f'<text id="c{k}" class="clock" x="{WIDTH - 12}" y="18" opacity="0"'+ f' fill="{theme["muted"]}" font-size="13" text-anchor="end">{text}</text>'+ )+ return (+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{WIDTH}" height="{height}"'+ f' viewBox="0 0 {WIDTH} {height}" font-family="{FONT}" font-size="15">'+ f"<style>{''.join(styles)}</style>"+ '<defs><linearGradient id="manimgx" x1="0" x2="1">'+ '<stop offset="0" stop-color="#58c4dd"/><stop offset="0.5"'+ ' stop-color="#5cd0b3"/>'+ '<stop offset="1" stop-color="#f7d96f"/></linearGradient></defs>'+ + "".join(parts)+ + "</svg>\n"+ )+++def main() -> None:+ results = json.loads((HERE / "results.json").read_text(encoding="utf-8"))+ rows = sorted(+ ((row["label"], row["median"]) for row in results["scenes"][SCENE].values()),+ key=lambda row: row[1],+ )+ for name, theme in THEMES.items():+ path = IMAGES / f"benchmark-{name}.svg"+ path.write_text(chart(rows, theme), encoding="utf-8")+ print(f"{path}: {path.stat().st_size / 1e3:.0f} KB")+++if __name__ == "__main__":+ main()diff --git a/scripts/benchmark/frames-explainer.jpg b/scripts/benchmark/frames-explainer.jpgnew file mode 100644index 00000000..ad4a7145Binary files /dev/null and b/scripts/benchmark/frames-explainer.jpg differdiff --git a/scripts/benchmark/frames-morph.jpg b/scripts/benchmark/frames-morph.jpgnew file mode 100644index 00000000..e3c78d45Binary files /dev/null and b/scripts/benchmark/frames-morph.jpg differdiff --git a/scripts/benchmark/frames-orbit.jpg b/scripts/benchmark/frames-orbit.jpgnew file mode 100644index 00000000..26ec2446Binary files /dev/null and b/scripts/benchmark/frames-orbit.jpg differdiff --git a/scripts/benchmark/results.json b/scripts/benchmark/results.jsonnew file mode 100644index 00000000..4b23b365--- /dev/null+++ b/scripts/benchmark/results.json@@ -0,0 +1,480 @@+{+ "date": "2026-09-29",+ "commit": "8e95dd392ce176848a956b0da17bfe21dd560743",+ "machine": {+ "os": "macOS 15.7.2",+ "cpus": "12",+ "cpu": "Apple M4 Pro",+ "memory": "24 GB"+ },+ "versions": {+ "manimgx": "0.1.0",+ "manim_ce": "0.21.0",+ "manimgl": "1.7.2",+ "blender": "5.2.0 LTS"+ },+ "scenes": {+ "orbit": {+ "manimgx": {+ "label": "manimgx",+ "median": 0.85,+ "runs": [+ {+ "wall": 0.966,+ "cpu": 5.37,+ "memory_mb": 532,+ "video_mb": 71.7,+ "load": 34.14+ },+ {+ "wall": 0.858,+ "cpu": 5.1,+ "memory_mb": 520,+ "video_mb": 71.7,+ "load": 10.2+ },+ {+ "wall": 0.784,+ "cpu": 5.05,+ "memory_mb": 513,+ "video_mb": 71.7,+ "load": 15.59+ },+ {+ "wall": 0.854,+ "cpu": 5.17,+ "memory_mb": 504,+ "video_mb": 71.7,+ "load": 9.37+ },+ {+ "wall": 0.832,+ "cpu": 5.3,+ "memory_mb": 545,+ "video_mb": 71.7,+ "load": 9.31+ }+ ]+ },+ "manimgl": {+ "label": "ManimGL",+ "median": 6.21,+ "runs": [+ {+ "wall": 6.924,+ "cpu": 18.04,+ "memory_mb": 893,+ "video_mb": 2.8,+ "load": 34.14+ },+ {+ "wall": 6.213,+ "cpu": 16.44,+ "memory_mb": 854,+ "video_mb": 2.8,+ "load": 10.59+ },+ {+ "wall": 6.087,+ "cpu": 16.36,+ "memory_mb": 844,+ "video_mb": 2.8,+ "load": 15.59+ },+ {+ "wall": 6.093,+ "cpu": 16.7,+ "memory_mb": 857,+ "video_mb": 2.8,+ "load": 9.37+ },+ {+ "wall": 6.376,+ "cpu": 16.83,+ "memory_mb": 876,+ "video_mb": 2.8,+ "load": 9.31+ }+ ]+ },+ "blender_workbench": {+ "label": "Blender (Workbench)",+ "median": 18.45,+ "runs": [+ {+ "wall": 20.585,+ "cpu": 57.89,+ "memory_mb": 1124,+ "video_mb": 3.2,+ "load": 52.42+ },+ {+ "wall": 17.85,+ "cpu": 54.46,+ "memory_mb": 1165,+ "video_mb": 3.2,+ "load": 11.74+ },+ {+ "wall": 18.411,+ "cpu": 55.29,+ "memory_mb": 1149,+ "video_mb": 3.2,+ "load": 15.72+ },+ {+ "wall": 18.447,+ "cpu": 57.62,+ "memory_mb": 1211,+ "video_mb": 3.2,+ "load": 8.92+ },+ {+ "wall": 19.217,+ "cpu": 55.35,+ "memory_mb": 1182,+ "video_mb": 3.2,+ "load": 8.97+ }+ ]+ },+ "blender_eevee": {+ "label": "Blender (EEVEE)",+ "median": 238.9,+ "runs": [+ {+ "wall": 238.898,+ "cpu": 112.47,+ "memory_mb": 1070,+ "video_mb": 3.6,+ "load": 21.22+ },+ {+ "wall": 226.638,+ "cpu": 91.29,+ "memory_mb": 1131,+ "video_mb": 3.6,+ "load": 71.4+ },+ {+ "wall": 267.785,+ "cpu": 124.96,+ "memory_mb": 1227,+ "video_mb": 3.6,+ "load": 13.54+ }+ ]+ },+ "manim_ce": {+ "label": "Manim CE",+ "median": 243.46,+ "runs": [+ {+ "wall": 326.331,+ "cpu": 269.12,+ "memory_mb": 745,+ "video_mb": 5.5,+ "load": 9.81+ },+ {+ "wall": 223.805,+ "cpu": 237.8,+ "memory_mb": 952,+ "video_mb": 5.5,+ "load": 23.0+ },+ {+ "wall": 250.051,+ "cpu": 255.61,+ "memory_mb": 748,+ "video_mb": 5.5,+ "load": 8.0+ },+ {+ "wall": 236.86,+ "cpu": 250.72,+ "memory_mb": 798,+ "video_mb": 5.5,+ "load": 10.77+ }+ ]+ }+ },+ "morph": {+ "manimgx": {+ "label": "manimgx",+ "median": 8.98,+ "runs": [+ {+ "wall": 9.766,+ "cpu": 13.37,+ "memory_mb": 1790,+ "video_mb": 73.4,+ "load": 21.08+ },+ {+ "wall": 8.771,+ "cpu": 12.98,+ "memory_mb": 1796,+ "video_mb": 73.4,+ "load": 8.26+ },+ {+ "wall": 8.796,+ "cpu": 13.04,+ "memory_mb": 1836,+ "video_mb": 73.4,+ "load": 16.3+ },+ {+ "wall": 8.982,+ "cpu": 13.26,+ "memory_mb": 1738,+ "video_mb": 73.4,+ "load": 10.3+ },+ {+ "wall": 8.997,+ "cpu": 13.22,+ "memory_mb": 1792,+ "video_mb": 73.4,+ "load": 12.97+ }+ ]+ },+ "manimgl": {+ "label": "ManimGL",+ "median": 73.09,+ "runs": [+ {+ "wall": 75.11,+ "cpu": 85.76,+ "memory_mb": 870,+ "video_mb": 3.6,+ "load": 20.98+ },+ {+ "wall": 72.924,+ "cpu": 84.65,+ "memory_mb": 872,+ "video_mb": 3.6,+ "load": 9.75+ },+ {+ "wall": 73.088,+ "cpu": 84.73,+ "memory_mb": 875,+ "video_mb": 3.6,+ "load": 16.62+ }+ ]+ },+ "blender_workbench": {+ "label": "Blender (Workbench)",+ "median": 18.45,+ "runs": [+ {+ "wall": 20.987,+ "cpu": 58.0,+ "memory_mb": 1158,+ "video_mb": 3.9,+ "load": 18.14+ },+ {+ "wall": 22.597,+ "cpu": 55.7,+ "memory_mb": 1127,+ "video_mb": 3.9,+ "load": 6.58+ },+ {+ "wall": 17.827,+ "cpu": 58.28,+ "memory_mb": 1135,+ "video_mb": 3.9,+ "load": 9.42+ },+ {+ "wall": 18.275,+ "cpu": 58.18,+ "memory_mb": 1155,+ "video_mb": 3.9,+ "load": 9.41+ },+ {+ "wall": 18.448,+ "cpu": 55.64,+ "memory_mb": 1146,+ "video_mb": 3.9,+ "load": 18.89+ }+ ]+ },+ "blender_eevee": {+ "label": "Blender (EEVEE)",+ "median": 254.03,+ "runs": [+ {+ "wall": 254.035,+ "cpu": 103.79,+ "memory_mb": 1037,+ "video_mb": 4.3,+ "load": 8.83+ },+ {+ "wall": 244.75,+ "cpu": 110.85,+ "memory_mb": 1097,+ "video_mb": 4.3,+ "load": 17.03+ },+ {+ "wall": 265.86,+ "cpu": 119.06,+ "memory_mb": 986,+ "video_mb": 4.3,+ "load": 14.09+ }+ ]+ },+ "manim_ce": {+ "label": "Manim CE",+ "median": 701.95,+ "runs": [+ {+ "wall": 701.948,+ "cpu": 711.74,+ "memory_mb": 751,+ "video_mb": 7.1,+ "load": 11.26+ }+ ]+ }+ },+ "explainer": {+ "manimgx": {+ "label": "manimgx",+ "median": 0.58,+ "runs": [+ {+ "wall": 0.62,+ "cpu": 2.37,+ "memory_mb": 465,+ "video_mb": 1.5,+ "load": 10.97+ },+ {+ "wall": 0.643,+ "cpu": 2.33,+ "memory_mb": 489,+ "video_mb": 1.5,+ "load": 15.6+ },+ {+ "wall": 0.577,+ "cpu": 2.38,+ "memory_mb": 477,+ "video_mb": 1.5,+ "load": 9.83+ },+ {+ "wall": 0.556,+ "cpu": 2.38,+ "memory_mb": 485,+ "video_mb": 1.5,+ "load": 8.79+ },+ {+ "wall": 0.556,+ "cpu": 2.35,+ "memory_mb": 479,+ "video_mb": 1.5,+ "load": 23.24+ }+ ]+ },+ "manimgl": {+ "label": "ManimGL",+ "median": 6.13,+ "runs": [+ {+ "wall": 6.423,+ "cpu": 10.28,+ "memory_mb": 878,+ "video_mb": 0.3,+ "load": 10.97+ },+ {+ "wall": 6.385,+ "cpu": 10.02,+ "memory_mb": 875,+ "video_mb": 0.3,+ "load": 15.6+ },+ {+ "wall": 5.843,+ "cpu": 10.27,+ "memory_mb": 869,+ "video_mb": 0.3,+ "load": 9.83+ },+ {+ "wall": 5.863,+ "cpu": 10.27,+ "memory_mb": 869,+ "video_mb": 0.3,+ "load": 8.79+ },+ {+ "wall": 6.133,+ "cpu": 10.14,+ "memory_mb": 875,+ "video_mb": 0.3,+ "load": 23.24+ }+ ]+ },+ "manim_ce": {+ "label": "Manim CE",+ "median": 4.05,+ "runs": [+ {+ "wall": 4.052,+ "cpu": 9.64,+ "memory_mb": 1661,+ "video_mb": 0.4,+ "load": 10.2+ },+ {+ "wall": 4.05,+ "cpu": 9.44,+ "memory_mb": 1589,+ "video_mb": 0.4,+ "load": 15.55+ },+ {+ "wall": 3.853,+ "cpu": 9.47,+ "memory_mb": 1784,+ "video_mb": 0.4,+ "load": 9.92+ },+ {+ "wall": 3.873,+ "cpu": 9.53,+ "memory_mb": 1563,+ "video_mb": 0.4,+ "load": 9.6+ },+ {+ "wall": 4.665,+ "cpu": 10.23,+ "memory_mb": 2078,+ "video_mb": 0.4,+ "load": 22.18+ }+ ]+ }+ }+ }+}diff --git a/scripts/benchmark/run.py b/scripts/benchmark/run.pynew file mode 100644index 00000000..325d3c94--- /dev/null+++ b/scripts/benchmark/run.py@@ -0,0 +1,310 @@+"""Time manimgx, Manim Community Edition, ManimGL and Blender on the same scenes.++ uv run --frozen python scripts/benchmark/run.py [--runs 5] [--only orbit,morph] [--tools manimgx,blender_workbench]++Each scene is the same film in each tool's own idiom: 1920 x 1080 at 60 fps, written to an+H.264 MP4 with the tool's own encoder settings. manimgx's are the timed benchmarks' workloads+(`tests/benchmarks/scenes/<scene>.py`); the others are here (`scenes/<scene>_<tool>.py`). A+run is the tool's command, in a fresh process and a fresh folder (its caches with it: Manim+CE's and ManimGL's LaTeX, manimgx's Typst layouts), timed from launch to exit, when the MP4+is written. Each contender renders a scene once to warm up (unless that takes over two+minutes: it counts then), then again, the contenders taking turns, until it has five runs+(three if a run takes over a minute, one if over ten). The medians go to `results.json`,+with every run, the versions and the machine; each MP4 is checked for its length, then+deleted.++The tools:+- manimgx and Manim CE (0.21.0): this repository's environment, with the `ce` group+ (`uv sync --group ce`).+- ManimGL (1.7.2): its own environment, e.g. `uv venv --python 3.12 ENV` and+ `uv pip install --python ENV manimgl==1.7.2 setuptools` (`--manimgl ENV`); its LaTeX+ template is its minimal one, "basic".+- Blender (5.2 LTS), headless, twice: with EEVEE, its default renderer, and with Workbench,+ its fastest (`--blender PATH`). It has no math typesetting, so it renders the 3D scenes.+"""++import argparse+import json+import os+import platform+import shutil+import statistics+import subprocess+import sys+import tempfile+import time+from dataclasses import dataclass+from pathlib import Path++HERE = Path(__file__).parent+ROOT = HERE.parents[1]+SCENES = HERE / "scenes"+WORKLOADS = ROOT / "tests" / "benchmarks" / "scenes" # manimgx's scenes+BIN = ROOT / ".venv" / "bin"+SCENE_CLASSES = {"orbit": "Orbit", "morph": "Morph", "explainer": "Explainer"}+SECONDS = {"orbit": 10.0, "morph": 10.0, "explainer": 9.5}+WARM_LIMIT, SLOW, SLOWER = 120.0, 60.0, 600.0+++@dataclass(frozen=True)+class Contender:+ """A tool, as the chart names it, and how it renders a scene into a folder."""++ name: str+ label: str+ scenes: tuple[str, ...]++ def command(self, scene: str, folder: Path, args: argparse.Namespace) -> list[str]:+ """The command that renders `scene` into `folder`."""+ mine = self.tool == "manimgx"+ file = str(+ WORKLOADS / f"{scene}.py" if mine else SCENES / f"{scene}_{self.tool}.py"+ )+ cls = SCENE_CLASSES[scene]+ if mine:+ return [str(BIN / "manimgx"), "render", file, "-o", str(folder / "out.mp4")]+ if self.tool == "manim_ce":+ return [+ str(BIN / "manim"),+ "render",+ "-qh",+ "--disable_caching",+ "--media_dir",+ str(folder),+ file,+ cls,+ ]+ if self.tool == "manimgl":+ config = folder / "config.yml"+ config.write_text(+ f'directories:\n cache: "{folder / "cache"}"\n'+ 'camera:\n fps: 60\ntex:\n template: "basic"\n',+ encoding="utf-8",+ )+ return [+ str(Path(args.manimgl) / "bin" / "manimgl"),+ file,+ cls,+ "-w",+ "--hd", # 60 fps comes from the config (its --fps flag passes a string)+ "--video_dir",+ str(folder),+ "--config_file",+ str(config),+ ]+ engine = self.name.removeprefix("blender_").upper()+ return [+ args.blender,+ "-b",+ "--factory-startup",+ "--python-exit-code",+ "1",+ "-P",+ file,+ "--",+ "--engine",+ engine,+ "--out",+ str(folder / "out.mp4"),+ ]++ @property+ def tool(self) -> str:+ """The tool whose scene files it runs."""+ return "blender" if self.name.startswith("blender") else self.name+++CONTENDERS = [+ Contender("manimgx", "manimgx", ("orbit", "morph", "explainer")),+ Contender("manimgl", "ManimGL", ("orbit", "morph", "explainer")),+ Contender("blender_workbench", "Blender (Workbench)", ("orbit", "morph")),+ Contender("blender_eevee", "Blender (EEVEE)", ("orbit", "morph")),+ Contender("manim_ce", "Manim CE", ("orbit", "morph", "explainer")),+]+++def run(contender: Contender, scene: str, args: argparse.Namespace) -> dict[str, float]:+ """Render once, in a fresh folder, and measure it; the MP4 is checked, then deleted."""+ folder = Path(tempfile.mkdtemp(prefix=f"bench-{scene}-{contender.name}-"))+ # a TMPDIR of its own: manimgx caches Typst's layouts there+ env = os.environ | {"TMPDIR": str(folder)}+ load = os.getloadavg()[0]+ log = folder / "stderr.txt"+ with log.open("wb") as stderr:+ start = time.perf_counter()+ pid = subprocess.Popen(+ contender.command(scene, folder, args),+ cwd=folder,+ env=env,+ stdout=subprocess.DEVNULL,+ stderr=stderr,+ ).pid+ _, status, usage = os.wait4(pid, 0) # its CPU time, its children's included+ wall = time.perf_counter() - start+ if status:+ errors = log.read_text(encoding="utf-8", errors="replace")[-3000:]+ sys.exit(f"{contender.name} failed on {scene}:\n{errors}")+ unit = 1024 if platform.system() == "Darwin" else 1 # ru_maxrss: bytes, or KiB+ videos = [p for p in folder.rglob("*.mp4") if "partial_movie_files" not in p.parts]+ if len(videos) != 1:+ sys.exit(f"{contender.name} wrote {len(videos)} videos for {scene}")+ probe = json.loads(+ subprocess.run(+ [+ "ffprobe",+ "-v",+ "error",+ "-show_entries",+ "format=duration,size",+ "-of",+ "json",+ str(videos[0]),+ ],+ capture_output=True,+ check=True,+ ).stdout+ )["format"]+ duration = float(probe["duration"])+ if abs(duration - SECONDS[scene]) > 0.1:+ sys.exit(f"{contender.name}'s {scene} lasts {duration:.2f} s")+ if args.keep:+ kept = Path(args.keep) / f"{scene}_{contender.name}.mp4"+ kept.parent.mkdir(parents=True, exist_ok=True)+ if not kept.exists():+ shutil.copyfile(videos[0], kept)+ shutil.rmtree(folder)+ return {+ "wall": round(wall, 3),+ "cpu": round(usage.ru_utime + usage.ru_stime, 2),+ "memory_mb": round(usage.ru_maxrss / unit / 1024),+ "video_mb": round(int(probe["size"]) / 1e6, 1),+ "load": round(load, 2),+ }+++def versions(tools: list[str], args: argparse.Namespace) -> dict[str, str]:+ """The version of each tool that ran."""++ def output(*command: str) -> str:+ return subprocess.run(command, capture_output=True, text=True).stdout.strip()++ found = {}+ if "manimgx" in tools:+ found["manimgx"] = output(str(BIN / "manimgx"), "--version").split()[-1]+ if "manim_ce" in tools:+ found["manim_ce"] = output(+ str(BIN / "python"), "-c", "import manim; print(manim.__version__)"+ )+ if "manimgl" in tools:+ python = str(Path(args.manimgl) / "bin" / "python")+ found["manimgl"] = output(+ python, "-c", "import importlib.metadata as m; print(m.version('manimgl'))"+ )+ if any(tool.startswith("blender") for tool in tools):+ found["blender"] = (+ output(args.blender, "--version").splitlines()[0].removeprefix("Blender ")+ )+ return found+++def sysctl(key: str) -> str:+ """A value of macOS's kernel settings."""+ command = ["sysctl", "-n", key]+ return subprocess.run(command, capture_output=True, text=True).stdout.strip()+++def machine() -> dict[str, str]:+ """The machine the runs were on."""+ info = {+ "os": f"{platform.system()} {platform.release()}",+ "cpus": str(os.cpu_count()),+ }+ if platform.system() == "Darwin":+ info |= {+ "cpu": sysctl("machdep.cpu.brand_string"),+ "memory": f"{int(sysctl('hw.memsize')) // 2**30} GB",+ "os": f"macOS {platform.mac_ver()[0]}",+ }+ return info+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--runs", type=int, default=5)+ parser.add_argument("--only", default=",".join(SCENE_CLASSES))+ parser.add_argument("--tools", default=",".join(c.name for c in CONTENDERS))+ parser.add_argument("--manimgl", help="ManimGL's environment")+ parser.add_argument(+ "--blender",+ default=shutil.which("blender")+ or "/Applications/Blender.app/Contents/MacOS/Blender",+ )+ parser.add_argument("--keep", help="a folder to keep each contender's first MP4 in")+ parser.add_argument("--out", default=str(HERE / "results.json"))+ args = parser.parse_args()+ scenes, tools = args.only.split(","), args.tools.split(",")+ if "manimgl" in tools and not args.manimgl:+ parser.error(+ "ManimGL needs its environment: --manimgl ENV (or leave it out of --tools)"+ )+ pairs = [+ (c, s) for s in scenes for c in CONTENDERS if c.name in tools and s in c.scenes+ ]+ runs: dict[tuple[str, str], list[dict[str, float]]] = {+ (c.name, s): [] for c, s in pairs+ }+ wanted: dict[tuple[str, str], int] = {}+ commit = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True+ ).stdout.strip()+ for contender, scene in pairs: # the warm-up+ first = run(contender, scene, args)+ slow = first["wall"] > WARM_LIMIT+ wanted[contender.name, scene] = (+ args.runs if first["wall"] < SLOW else 3 if first["wall"] < SLOWER else 1+ )+ if slow:+ runs[contender.name, scene].append(first)+ print(+ f"warm-up {scene:9} {contender.label:20} {first['wall']:8.2f} s", flush=True+ )+ while any(len(runs[k]) < wanted[k] for k in runs):+ for contender, scene in pairs:+ if len(runs[contender.name, scene]) < wanted[contender.name, scene]:+ result = run(contender, scene, args)+ runs[contender.name, scene].append(result)+ print(+ f"{scene:9} {contender.label:20} {result['wall']:8.2f} s load"+ f" {result['load']}",+ flush=True,+ )+ medians = {+ key: statistics.median(r["wall"] for r in rows) for key, rows in runs.items()+ }+ results = {+ "date": time.strftime("%Y-%m-%d"),+ "commit": commit,+ "machine": machine(),+ "versions": versions(tools, args),+ "scenes": {+ scene: {+ c.name: {+ "label": c.label,+ "median": round(medians[c.name, scene], 2),+ "runs": runs[c.name, scene],+ }+ for c, s in pairs+ if s == scene+ }+ for scene in scenes+ },+ }+ Path(args.out).write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")+ for contender, scene in pairs:+ median, base = medians[contender.name, scene], medians.get(("manimgx", scene))+ times = f"×{median / base:.1f}" if base else ""+ print(f"{scene:9} {contender.label:20} {median:8.2f} s {times}")+++if __name__ == "__main__":+ main()diff --git a/scripts/benchmark/scenes/explainer_manim_ce.py b/scripts/benchmark/scenes/explainer_manim_ce.pynew file mode 100644index 00000000..ec23eb0d--- /dev/null+++ b/scripts/benchmark/scenes/explainer_manim_ce.py@@ -0,0 +1,27 @@+"""A classic explainer: a curve drawn on axes, its area and its integral, then a tangent+line sliding along it. (Manim Community Edition.)"""++from manim import *+++class Explainer(Scene):+ def construct(self) -> None:+ axes = Axes(x_range=[0, 2 * np.pi, np.pi / 2], y_range=[-1.5, 1.5, 1])+ sine = axes.plot(np.sin, color=BLUE, stroke_width=6)+ dot = Dot(axes.i2gp(0, sine), radius=0.12, color=YELLOW)+ area = axes.get_area(sine, x_range=(0, np.pi), color=BLUE, opacity=0.4)+ label = MathTex(r"y = \sin x", font_size=72).to_corner(UR)+ integral = MathTex(r"\int_0^\pi \sin x \, dx = 2", font_size=72).to_corner(UR)+ self.play(Create(axes), Write(label))+ self.play(Create(sine), MoveAlongPath(dot, sine), run_time=2.5)+ self.play(FadeIn(area), TransformMatchingTex(label, integral))+ along = ValueTracker(0)+ tangent = always_redraw(+ lambda: TangentLine(sine, alpha=along.get_value(), length=3, color=YELLOW)+ )+ dot.add_updater(+ lambda d: d.move_to(sine.point_from_proportion(along.get_value()))+ )+ self.add(tangent, dot)+ self.play(along.animate.set_value(1), run_time=4)+ self.wait()diff --git a/scripts/benchmark/scenes/explainer_manimgl.py b/scripts/benchmark/scenes/explainer_manimgl.pynew file mode 100644index 00000000..6c2a84a5--- /dev/null+++ b/scripts/benchmark/scenes/explainer_manimgl.py@@ -0,0 +1,46 @@+"""A classic explainer: a curve drawn on axes, its area and its integral, then a tangent+line sliding along it. (ManimGL.)"""++import numpy as np+from manimlib import *++YELLOW = "#F7D96F" # Manim CE's color, where ManimGL's differs+++class Explainer(Scene):+ default_camera_config = {"background_color": BLACK}++ def construct(self) -> None:+ axes = Axes(+ x_range=(0, 2 * np.pi, np.pi / 2),+ y_range=(-1.5, 1.5, 1),+ width=12,+ height=6,+ axis_config={"include_tip": True}, # Manim CE's defaults+ )+ # The graph's x_range is given without a step: get_area_under_graph fails on one+ # with a step (ManimGL 1.7.2).+ sine = axes.get_graph(+ np.sin, x_range=(0, 2 * np.pi), color=BLUE, stroke_width=6+ )+ dot = Dot(axes.i2gp(0, sine), radius=0.12, fill_color=YELLOW)+ area = axes.get_area_under_graph(+ sine, x_range=(0, np.pi), fill_color=BLUE, fill_opacity=0.4+ )+ label = Tex(r"y = \sin x", font_size=72).to_corner(UR)+ integral = Tex(r"\int_0^\pi \sin x \, dx = 2", font_size=72).to_corner(UR)+ self.play(ShowCreation(axes), Write(label))+ self.play(ShowCreation(sine), MoveAlongPath(dot, sine), run_time=2.5)+ self.play(+ FadeIn(area), TransformMatchingTex(label, integral, run_time=1)+ ) # 2 s by default+ along = ValueTracker(0)+ tangent = always_redraw(+ lambda: TangentLine(sine, alpha=along.get_value(), length=3, color=YELLOW)+ )+ dot.add_updater(+ lambda d: d.move_to(sine.point_from_proportion(along.get_value()))+ )+ self.add(tangent, dot)+ self.play(along.animate.set_value(1), run_time=4)+ self.wait()diff --git a/scripts/benchmark/scenes/morph_blender.py b/scripts/benchmark/scenes/morph_blender.pynew file mode 100644index 00000000..71189ea6--- /dev/null+++ b/scripts/benchmark/scenes/morph_blender.py@@ -0,0 +1,183 @@+"""A rippling surface, rebuilt every frame, with the camera circling it. (Blender, run+headless: `blender -b --factory-startup -P morph_blender.py -- --engine EEVEE|WORKBENCH+--out FILE`.)++The axes, camera, light and output are orbit_blender.py's. The surface's points are+recomputed with numpy on every frame by a frame-change handler and written with+foreach_set, the fastest way to move a mesh from Python.+"""++import argparse+import math+import sys++import bpy+import numpy as np++FPS, SECONDS = 60, 10+BLUE_D, BLUE_E, AXES = "#29ABCA", "#236B8E", "#FFFFFF"+# scene units per axis unit, as ThreeDAxes(x_length=7, z_length=4) has them+X, Z = 7 / 6, 1.0+N = 48+U, V = np.meshgrid(np.linspace(-3, 3, N + 1), np.linspace(-3, 3, N + 1), indexing="ij")+++def c2p(u: np.ndarray, v: np.ndarray, w: np.ndarray) -> np.ndarray:+ """Axis coordinates to scene points."""+ return np.stack([X * u, X * v, Z * w], -1)+++def material(name: str, color: str) -> bpy.types.Material:+ """A plain material of a color given in hex (sRGB)."""+ rgb = [int(color[i : i + 2], 16) / 255 for i in (1, 3, 5)]+ linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in rgb]+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*linear, 1) # Workbench's color+ mat.use_nodes = True+ mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (+ *linear,+ 1,+ )+ return mat+++def points(frame: int) -> np.ndarray:+ """The ripple's points at a frame, flat: z = 0.8 sin(2r - phase), the phase from 0 to+ 4 pi over the ten seconds."""+ phase = 4 * np.pi * (frame - 1) / (SECONDS * FPS)+ return c2p(U, V, 0.8 * np.sin(2 * np.hypot(U, V) - phase)).ravel()+++def surface() -> None:+ """The 48 x 48 checkerboard ripple, as one mesh whose points follow the frame."""+ i, j = np.meshgrid(np.arange(N), np.arange(N), indexing="ij")+ corner = (i * (N + 1) + j).ravel()+ quads = np.stack([corner, corner + N + 1, corner + N + 2, corner + 1], -1)+ mesh = bpy.data.meshes.new("surface")+ mesh.from_pydata(points(1).reshape(-1, 3).tolist(), [], quads.tolist())+ mesh.polygons.foreach_set("material_index", ((i + j) % 2).ravel().astype(np.int32))+ mesh.polygons.foreach_set("use_smooth", np.ones(N * N, bool))+ mesh.materials.append(material("blue_d", BLUE_D))+ mesh.materials.append(material("blue_e", BLUE_E))+ bpy.context.collection.objects.link(bpy.data.objects.new("surface", mesh))++ def move(scene: bpy.types.Scene, *_: object) -> None:+ mesh.vertices.foreach_set("co", points(scene.frame_current))+ mesh.update()++ bpy.app.handlers.frame_change_pre.append(move)+++def axes() -> None:+ """Three thin shafts with cone tips, from -3 to 3 (x, y) and -2 to 2 (z)."""+ white = material("axes", AXES)+ for axis, (low, high) in enumerate(+ [(-3 * X, 3 * X), (-3 * X, 3 * X), (-2 * Z, 2 * Z)]+ ):+ rotation = [(0, math.pi / 2, 0), (-math.pi / 2, 0, 0), (0, 0, 0)][axis]+ center = [0.0, 0.0, 0.0]+ center[axis] = (low + high) / 2+ bpy.ops.mesh.primitive_cylinder_add(+ radius=0.01,+ depth=high - low,+ location=center,+ rotation=rotation,+ vertices=12,+ )+ bpy.context.object.data.materials.append(white)+ tip = [0.0, 0.0, 0.0]+ tip[axis] = high+ bpy.ops.mesh.primitive_cone_add(+ radius1=0.06, depth=0.18, location=tip, rotation=rotation, vertices=16+ )+ bpy.context.object.data.materials.append(white)+++def camera() -> None:+ """Manim's camera: 20 units from the origin, 8 units of frame height there, at+ phi = 65 degrees, orbiting from theta = -45 degrees at 0.3 rad/s."""+ pivot = bpy.data.objects.new("pivot", None)+ bpy.context.collection.objects.link(pivot)+ data = bpy.data.cameras.new("camera")+ data.sensor_fit = "VERTICAL"+ data.angle = 2 * math.atan(4 / 20)+ data.clip_end = 100+ cam = bpy.data.objects.new("camera", data)+ bpy.context.collection.objects.link(cam)+ phi, theta = math.radians(65), math.radians(-45)+ cam.location = (+ 20 * math.sin(phi) * math.cos(theta),+ 20 * math.sin(phi) * math.sin(theta),+ 20 * math.cos(phi),+ )+ track = cam.constraints.new("TRACK_TO")+ track.target, track.track_axis, track.up_axis = pivot, "TRACK_NEGATIVE_Z", "UP_Y"+ cam.parent = pivot+ pivot.keyframe_insert("rotation_euler", index=2, frame=1)+ pivot.rotation_euler = (0, 0, 0.3 * SECONDS)+ pivot.keyframe_insert("rotation_euler", index=2, frame=1 + SECONDS * FPS)+ bpy.context.scene.camera = cam+++def light() -> None:+ """A sun from above the camera's side, for shading in EEVEE."""+ sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN"))+ sun.data.energy = 3+ sun.rotation_euler = (math.radians(40), 0, math.radians(-30))+ bpy.context.collection.objects.link(sun)+++def output(engine: str, path: str) -> None:+ """1920 x 1080 at 60 fps, 600 frames, straight to an H.264 MP4 with Blender's+ settings for it; black background and the Standard view (colors as sRGB)."""+ scene = bpy.context.scene+ scene.render.engine = {"EEVEE": "BLENDER_EEVEE", "WORKBENCH": "BLENDER_WORKBENCH"}[+ engine+ ]+ scene.render.resolution_x, scene.render.resolution_y = 1920, 1080+ scene.render.resolution_percentage = 100+ scene.render.fps = FPS+ scene.frame_start, scene.frame_end = 1, SECONDS * FPS+ scene.view_settings.view_transform = "Standard"+ scene.world = scene.world or bpy.data.worlds.new("world")+ scene.world.color = (0, 0, 0)+ scene.world.use_nodes = True+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (+ 0,+ 0,+ 0,+ 1,+ )+ scene.display.shading.light = "STUDIO"+ scene.display.shading.color_type = "MATERIAL"+ settings = scene.render.image_settings+ settings.media_type = "VIDEO"+ settings.file_format = "FFMPEG"+ scene.render.ffmpeg.format = "MPEG4"+ scene.render.ffmpeg.codec = "H264"+ scene.render.ffmpeg.constant_rate_factor = "MEDIUM"+ scene.render.ffmpeg.ffmpeg_preset = "GOOD"+ scene.render.filepath = path+ scene.render.use_file_extension = False+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--engine", choices=["EEVEE", "WORKBENCH"], default="EEVEE")+ parser.add_argument("--out", default="morph.mp4")+ parser.add_argument("--frames", type=int, default=SECONDS * FPS) # fewer, to try it+ args = parser.parse_args(+ sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []+ )+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.context.preferences.edit.keyframe_new_interpolation_type = "LINEAR"+ surface()+ axes()+ camera()+ light()+ output(args.engine, args.out)+ bpy.context.scene.frame_end = args.frames+ bpy.ops.render.render(animation=True)+++main()diff --git a/scripts/benchmark/scenes/morph_manim_ce.py b/scripts/benchmark/scenes/morph_manim_ce.pynew file mode 100644index 00000000..8cc65799--- /dev/null+++ b/scripts/benchmark/scenes/morph_manim_ce.py@@ -0,0 +1,32 @@+"""A rippling surface, rebuilt every frame, with the camera circling it. (Manim Community+Edition.)"""++from manim import *+++class Morph(ThreeDScene):+ def construct(self) -> None:+ axes = ThreeDAxes(+ x_range=[-3, 3, 1],+ y_range=[-3, 3, 1],+ z_range=[-2, 2, 1],+ x_length=7,+ y_length=7,+ z_length=4,+ )+ phase = ValueTracker(0)+ surface = always_redraw(+ lambda: Surface(+ lambda u, v: axes.c2p(+ u, v, 0.8 * np.sin(2 * np.hypot(u, v) - phase.get_value())+ ),+ u_range=[-3, 3],+ v_range=[-3, 3],+ resolution=(48, 48),+ checkerboard_colors=[BLUE_D, BLUE_E],+ )+ )+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)+ self.add(axes, surface)+ self.begin_ambient_camera_rotation(rate=0.3)+ self.play(phase.animate.set_value(4 * np.pi), run_time=10, rate_func=linear)diff --git a/scripts/benchmark/scenes/morph_manimgl.py b/scripts/benchmark/scenes/morph_manimgl.pynew file mode 100644index 00000000..d4305a45--- /dev/null+++ b/scripts/benchmark/scenes/morph_manimgl.py@@ -0,0 +1,55 @@+"""A rippling surface, rebuilt every frame, with the camera circling it. (ManimGL.)"""++import tempfile++import numpy as np+from manimlib import *+from PIL import Image++BLUE_E = "#236B8E" # Manim CE's color, where ManimGL's differs+++def checkerboard(colors: list[str], cells: int = 48, px: int = 16) -> str:+ """A PNG of `cells` x `cells` squares: ManimGL's surfaces take one color, so the+ checkerboard is painted on as a texture (face (i, j) gets colors[(i + j) % 2])."""+ a, b = (color_to_int_rgb(c) for c in colors)+ rows, cols = np.indices((cells, cells))+ image = np.where(((rows + cols + 1) % 2 == 0)[..., None], a, b).astype(np.uint8)+ path = f"{tempfile.gettempdir()}/checkerboard.png"+ Image.fromarray(image.repeat(px, 0).repeat(px, 1)).save(path)+ return path+++class Morph(ThreeDScene):+ default_camera_config = {"background_color": BLACK}++ def construct(self) -> None:+ axes = ThreeDAxes(+ x_range=(-3, 3, 1),+ y_range=(-3, 3, 1),+ z_range=(-2, 2, 1),+ width=7,+ height=7,+ depth=4,+ axis_config={"include_tip": True},+ )+ phase = ValueTracker(0)+ texture = checkerboard([BLUE_D, BLUE_E])+ surface = always_redraw(+ lambda: TexturedSurface(+ ParametricSurface(+ lambda u, v: axes.c2p(+ u, v, 0.8 * np.sin(2 * np.hypot(u, v) - phase.get_value())+ ),+ u_range=(-3, 3),+ v_range=(-3, 3),+ resolution=(49, 49), # sample points: 48 x 48 squares+ ),+ texture,+ )+ )+ self.frame.reorient(45, 65) # ManimGL's theta is Manim CE's plus 90 degrees+ self.frame.set_focal_distance(20) # Manim CE's camera distance+ self.add(axes, surface)+ self.frame.add_updater(lambda frame, dt: frame.increment_theta(0.3 * dt))+ self.play(phase.animate.set_value(4 * np.pi), run_time=10, rate_func=linear)diff --git a/scripts/benchmark/scenes/orbit_blender.py b/scripts/benchmark/scenes/orbit_blender.pynew file mode 100644index 00000000..8624ce89--- /dev/null+++ b/scripts/benchmark/scenes/orbit_blender.py@@ -0,0 +1,226 @@+"""A surface plot on 3D axes, a curve drawn across it with a ball riding its tip, and the+camera circling the whole time: every frame is new. (Blender, run headless:+`blender -b --factory-startup -P orbit_blender.py -- --engine EEVEE|WORKBENCH --out FILE`.)++Built the way Manim draws it: the axes' units (7 wide for x and y from -3 to 3, 4 tall for+z from -2 to 2), a 48 x 48 checkerboard surface, the curve drawn by its bevel's end, the+ball keyed along the curve, and Manim's camera: 20 units from the origin, a frame 8 units+tall there, at phi = 65 degrees, theta = -45 degrees + 0.3 rad/s.+"""++import argparse+import math+import sys++import bpy+import numpy as np++FPS, SECONDS, DRAW = 60, 10, 6 # the curve is drawn over the first six seconds+YELLOW, BLUE_D, BLUE_E, AXES = "#F7D96F", "#29ABCA", "#236B8E", "#FFFFFF"+# scene units per axis unit, as ThreeDAxes(x_length=7, z_length=4) has them+X, Z = 7 / 6, 1.0+++def c2p(u: np.ndarray, v: np.ndarray, w: np.ndarray) -> np.ndarray:+ """Axis coordinates to scene points."""+ return np.stack([X * u, X * v, Z * w], -1)+++def material(name: str, color: str) -> bpy.types.Material:+ """A plain material of a color given in hex (sRGB)."""+ rgb = [int(color[i : i + 2], 16) / 255 for i in (1, 3, 5)]+ linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in rgb]+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*linear, 1) # Workbench's color+ mat.use_nodes = True+ mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (+ *linear,+ 1,+ )+ return mat+++def surface() -> bpy.types.Object:+ """The 48 x 48 checkerboard surface z = sin(u) cos(v), as one mesh."""+ n = 48+ u, v = np.meshgrid(+ np.linspace(-3, 3, n + 1), np.linspace(-3, 3, n + 1), indexing="ij"+ )+ points = c2p(u, v, np.sin(u) * np.cos(v)).reshape(-1, 3)+ i, j = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")+ corner = (i * (n + 1) + j).ravel()+ quads = np.stack([corner, corner + n + 1, corner + n + 2, corner + 1], -1)+ mesh = bpy.data.meshes.new("surface")+ mesh.from_pydata(points.tolist(), [], quads.tolist())+ mesh.polygons.foreach_set("material_index", ((i + j) % 2).ravel().astype(np.int32))+ mesh.polygons.foreach_set("use_smooth", np.ones(n * n, bool))+ mesh.materials.append(material("blue_d", BLUE_D))+ mesh.materials.append(material("blue_e", BLUE_E))+ obj = bpy.data.objects.new("surface", mesh)+ bpy.context.collection.objects.link(obj)+ return obj+++def axes() -> None:+ """Three thin shafts with cone tips, from -3 to 3 (x, y) and -2 to 2 (z)."""+ white = material("axes", AXES)+ for axis, (low, high) in enumerate(+ [(-3 * X, 3 * X), (-3 * X, 3 * X), (-2 * Z, 2 * Z)]+ ):+ rotation = [(0, math.pi / 2, 0), (-math.pi / 2, 0, 0), (0, 0, 0)][axis]+ center = [0.0, 0.0, 0.0]+ center[axis] = (low + high) / 2+ bpy.ops.mesh.primitive_cylinder_add(+ radius=0.01,+ depth=high - low,+ location=center,+ rotation=rotation,+ vertices=12,+ )+ bpy.context.object.data.materials.append(white)+ tip = [0.0, 0.0, 0.0]+ tip[axis] = high+ bpy.ops.mesh.primitive_cone_add(+ radius1=0.06, depth=0.18, location=tip, rotation=rotation, vertices=16+ )+ bpy.context.object.data.materials.append(white)+++def curve_points(count: int = 629) -> np.ndarray:+ """The curve across the surface, as Manim samples it (t from 0 to 2 pi, step 0.01)."""+ t = np.linspace(0, 2 * np.pi, count)+ r = 2.4+ return c2p(+ r * np.cos(t),+ r * np.sin(t),+ np.sin(r * np.cos(t)) * np.cos(r * np.sin(t)) + 0.08,+ )+++def curve(points: np.ndarray) -> None:+ """The yellow curve, drawn by animating the end of its bevel over the first six+ seconds (a stroke 6 wide in Manim is 0.06 units: a tube of radius 0.03)."""+ data = bpy.data.curves.new("curve", "CURVE")+ data.dimensions = "3D"+ data.bevel_depth, data.bevel_resolution = 0.03, 2+ data.bevel_factor_mapping_end = "SPLINE"+ spline = data.splines.new("POLY")+ spline.points.add(len(points) - 1)+ spline.points.foreach_set(+ "co", np.hstack([points, np.ones((len(points), 1))]).ravel()+ )+ data.materials.append(material("yellow", YELLOW))+ obj = bpy.data.objects.new("curve", data)+ bpy.context.collection.objects.link(obj)+ data.bevel_factor_end = 0+ data.keyframe_insert("bevel_factor_end", frame=1)+ data.bevel_factor_end = 1+ data.keyframe_insert("bevel_factor_end", frame=1 + DRAW * FPS)+++def ball(points: np.ndarray) -> None:+ """The ball, keyed at the drawn tip of the curve on every frame of the drawing."""+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.12, segments=24, ring_count=12)+ obj = bpy.context.object+ obj.data.materials.append(bpy.data.materials["yellow"])+ lengths = np.concatenate(+ [[0], np.cumsum(np.linalg.norm(np.diff(points, axis=0), axis=1))]+ )+ for frame in range(DRAW * FPS + 1):+ at = frame / (DRAW * FPS) * lengths[-1]+ obj.location = [np.interp(at, lengths, points[:, k]) for k in range(3)]+ obj.keyframe_insert("location", frame=1 + frame)+++def camera() -> None:+ """Manim's camera: 20 units from the origin, 8 units of frame height there, at+ phi = 65 degrees, orbiting from theta = -45 degrees at 0.3 rad/s."""+ pivot = bpy.data.objects.new("pivot", None)+ bpy.context.collection.objects.link(pivot)+ data = bpy.data.cameras.new("camera")+ data.sensor_fit = "VERTICAL"+ data.angle = 2 * math.atan(4 / 20)+ data.clip_end = 100+ cam = bpy.data.objects.new("camera", data)+ bpy.context.collection.objects.link(cam)+ phi, theta = math.radians(65), math.radians(-45)+ cam.location = (+ 20 * math.sin(phi) * math.cos(theta),+ 20 * math.sin(phi) * math.sin(theta),+ 20 * math.cos(phi),+ )+ track = cam.constraints.new("TRACK_TO")+ track.target, track.track_axis, track.up_axis = pivot, "TRACK_NEGATIVE_Z", "UP_Y"+ cam.parent = pivot+ pivot.rotation_euler = (0, 0, 0)+ pivot.keyframe_insert("rotation_euler", index=2, frame=1)+ pivot.rotation_euler = (0, 0, 0.3 * SECONDS)+ pivot.keyframe_insert("rotation_euler", index=2, frame=1 + SECONDS * FPS)+ bpy.context.scene.camera = cam+++def light() -> None:+ """A sun from above the camera's side, and a dim world, for shading in EEVEE."""+ sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN"))+ sun.data.energy = 3+ sun.rotation_euler = (math.radians(40), 0, math.radians(-30))+ bpy.context.collection.objects.link(sun)+++def output(engine: str, path: str) -> None:+ """1920 x 1080 at 60 fps, 600 frames, straight to an H.264 MP4 with Blender's+ settings for it; black background and the Standard view (colors as sRGB)."""+ scene = bpy.context.scene+ scene.render.engine = {"EEVEE": "BLENDER_EEVEE", "WORKBENCH": "BLENDER_WORKBENCH"}[+ engine+ ]+ scene.render.resolution_x, scene.render.resolution_y = 1920, 1080+ scene.render.resolution_percentage = 100+ scene.render.fps = FPS+ scene.frame_start, scene.frame_end = 1, SECONDS * FPS+ scene.view_settings.view_transform = "Standard"+ scene.world = scene.world or bpy.data.worlds.new("world")+ scene.world.color = (0, 0, 0)+ scene.world.use_nodes = True+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (+ 0,+ 0,+ 0,+ 1,+ )+ scene.display.shading.light = "STUDIO"+ scene.display.shading.color_type = "MATERIAL"+ settings = scene.render.image_settings+ settings.media_type = "VIDEO"+ settings.file_format = "FFMPEG"+ scene.render.ffmpeg.format = "MPEG4"+ scene.render.ffmpeg.codec = "H264"+ scene.render.ffmpeg.constant_rate_factor = "MEDIUM"+ scene.render.ffmpeg.ffmpeg_preset = "GOOD"+ scene.render.filepath = path+ scene.render.use_file_extension = False+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--engine", choices=["EEVEE", "WORKBENCH"], default="EEVEE")+ parser.add_argument("--out", default="orbit.mp4")+ parser.add_argument("--frames", type=int, default=SECONDS * FPS) # fewer, to try it+ args = parser.parse_args(+ sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []+ )+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.context.preferences.edit.keyframe_new_interpolation_type = "LINEAR"+ points = curve_points()+ surface()+ axes()+ curve(points)+ ball(points)+ camera()+ light()+ output(args.engine, args.out)+ bpy.context.scene.frame_end = args.frames+ bpy.ops.render.render(animation=True)+++main()diff --git a/scripts/benchmark/scenes/orbit_manim_ce.py b/scripts/benchmark/scenes/orbit_manim_ce.pynew file mode 100644index 00000000..37b44c90--- /dev/null+++ b/scripts/benchmark/scenes/orbit_manim_ce.py@@ -0,0 +1,41 @@+"""A surface plot on 3D axes, a curve drawn across it with a ball riding its tip, and the+camera circling the whole time: every frame is new. (Manim Community Edition.)"""++from manim import *+++class Orbit(ThreeDScene):+ def construct(self) -> None:+ axes = ThreeDAxes(+ x_range=[-3, 3, 1],+ y_range=[-3, 3, 1],+ z_range=[-2, 2, 1],+ x_length=7,+ y_length=7,+ z_length=4,+ )+ surface = Surface(+ lambda u, v: axes.c2p(u, v, np.sin(u) * np.cos(v)),+ u_range=[-3, 3],+ v_range=[-3, 3],+ resolution=(48, 48),+ checkerboard_colors=[BLUE_D, BLUE_E],+ )+ curve = ParametricFunction(+ lambda t: axes.c2p(+ 2.4 * np.cos(t),+ 2.4 * np.sin(t),+ np.sin(2.4 * np.cos(t)) * np.cos(2.4 * np.sin(t)) + 0.08,+ ),+ t_range=[0, 2 * np.pi],+ color=YELLOW,+ stroke_width=6,+ )+ ball = Dot3D(curve.get_start(), radius=0.12, color=YELLOW)+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)+ self.add(axes, surface, ball)+ self.begin_ambient_camera_rotation(rate=0.3)+ self.play(+ Create(curve), MoveAlongPath(ball, curve), run_time=6, rate_func=linear+ )+ self.wait(4)diff --git a/scripts/benchmark/scenes/orbit_manimgl.py b/scripts/benchmark/scenes/orbit_manimgl.pynew file mode 100644index 00000000..073d7bd7--- /dev/null+++ b/scripts/benchmark/scenes/orbit_manimgl.py@@ -0,0 +1,71 @@+"""A surface plot on 3D axes, a curve drawn across it with a ball riding its tip, and the+camera circling the whole time: every frame is new. (ManimGL.)"""++import tempfile++import numpy as np+from manimlib import *+from PIL import Image++YELLOW, BLUE_E = "#F7D96F", "#236B8E" # Manim CE's colors, where ManimGL's differ+++def checkerboard(colors: list[str], cells: int = 48, px: int = 16) -> str:+ """A PNG of `cells` x `cells` squares: ManimGL's surfaces take one color, so the+ checkerboard is painted on as a texture (face (i, j) gets colors[(i + j) % 2])."""+ a, b = (color_to_int_rgb(c) for c in colors)+ rows, cols = np.indices((cells, cells))+ image = np.where(((rows + cols + 1) % 2 == 0)[..., None], a, b).astype(np.uint8)+ path = f"{tempfile.gettempdir()}/checkerboard.png"+ Image.fromarray(image.repeat(px, 0).repeat(px, 1)).save(path)+ return path+++class Orbit(ThreeDScene):+ default_camera_config = {"background_color": BLACK}++ def construct(self) -> None:+ axes = ThreeDAxes(+ x_range=(-3, 3, 1),+ y_range=(-3, 3, 1),+ z_range=(-2, 2, 1),+ width=7,+ height=7,+ depth=4,+ axis_config={"include_tip": True},+ )+ surface = TexturedSurface(+ ParametricSurface(+ lambda u, v: axes.c2p(u, v, np.sin(u) * np.cos(v)),+ u_range=(-3, 3),+ v_range=(-3, 3),+ resolution=(49, 49), # sample points: 48 x 48 squares+ ),+ checkerboard([BLUE_D, BLUE_E]),+ )+ curve = ParametricCurve(+ lambda t: axes.c2p(+ 2.4 * np.cos(t),+ 2.4 * np.sin(t),+ np.sin(2.4 * np.cos(t)) * np.cos(2.4 * np.sin(t)) + 0.08,+ ),+ t_range=(+ 0,+ TAU,+ 0.01,+ ), # Manim CE's sampling (ManimGL's default step is 0.1)+ color=YELLOW,+ stroke_width=6,+ )+ ball = Sphere(radius=0.12, color=YELLOW).move_to(curve.get_start())+ self.frame.reorient(45, 65) # ManimGL's theta is Manim CE's plus 90 degrees+ self.frame.set_focal_distance(20) # Manim CE's camera distance+ self.add(axes, surface, ball)+ self.frame.add_updater(lambda frame, dt: frame.increment_theta(0.3 * dt))+ self.play(+ ShowCreation(curve),+ MoveAlongPath(ball, curve),+ run_time=6,+ rate_func=linear,+ )+ self.wait(4)