Metadata-Version: 2.4
Name: cocobrown
Version: 0.5.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Rust
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: Typing :: Typed
Requires-Dist: sympy>=1.12 ; extra == 'sympy'
Provides-Extra: sympy
License-File: LICENSE
Summary: Compiler-inspired mathematical & algorithmic animation engine with Rust core, native Typst math, and zero-FFmpeg media pipeline
Keywords: animation,math,manim,visualization,typst,rust,video,graphics,education,algorithms
Author: choroship357
License-Expression: Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/choroship357/cocobrown/blob/main/ROADMAP.md
Project-URL: Documentation, https://github.com/choroship357/cocobrown/blob/main/USAGE.md
Project-URL: Homepage, https://github.com/choroship357/cocobrown
Project-URL: Issues, https://github.com/choroship357/cocobrown/issues
Project-URL: Repository, https://github.com/choroship357/cocobrown

<div align="center">

# cocobrown

**Compiler-Inspired 2D & 3D Mathematical & Algorithmic Animation Engine**

*Zero LaTeX · Zero FFmpeg Required · Pure-Rust Timeline IR & Media Pipeline · CPU + Vello 2D GPU + Filament PBR 3D · Live Hot-Reload*

[![Version](https://img.shields.io/badge/version-0.5.0-blue.svg)](#)
[![Python](https://img.shields.io/badge/python-%E2%89%A53.9%20(abi3)-3776AB.svg)](#installation)
[![Rust](https://img.shields.io/badge/core-Rust%20%2B%20PyO3-DEA584.svg)](#architecture)
[![3D PBR](https://img.shields.io/badge/3D-Google%20Filament%20PBR-10B981.svg)](#3d-pbr-showcase)
[![Typst](https://img.shields.io/badge/math-Native%20Typst%20(Zero%20LaTeX)-239DAD.svg)](#highlights)
[![Zero-FFmpeg](https://img.shields.io/badge/media-Pure--Rust%20MP4%20%2F%20GIF%20%2F%20AAC-F97316.svg)](#highlights)
[![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](https://github.com/choroship357/cocobrown/blob/main/LICENSE)

**English** | [简体中文](https://github.com/choroship357/cocobrown/blob/main/README.zh-CN.md)

[2D Showcase](#showcase) · [3D PBR Showcase](#3d-pbr-showcase) · [3-Min Benchmark vs. Manim](#3-minute-benchmark-cocobrown-vs-manim) · [Quick Start](#quick-start) · [Usage Guide (USAGE.md)](https://github.com/choroship357/cocobrown/blob/main/USAGE.md) · [Architecture (DESIGN.md)](https://github.com/choroship357/cocobrown/blob/main/DESIGN.md) · [Roadmap (ROADMAP.md)](https://github.com/choroship357/cocobrown/blob/main/ROADMAP.md)

</div>

---

## Showcase

All four 1080p acts and the animated 24fps preview below are compiled directly from the single-file [demo.py](https://github.com/choroship357/cocobrown/blob/main/demo.py) — **zero LaTeX, zero FFmpeg required**:

<div align="center">

![cocobrown v0.5.0 2D Animated Showcase](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/showcase.gif)

</div>

| Act 1: Glowing SymPy Calculus, Gradients & Camera2D | Act 2: Graph, BinaryTree, Array & Syntax-Highlighted CodeBlock |
| :---: | :---: |
| ![Act 1: Glowing SymPy Calculus](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/act1_calculus.png) | ![Act 2: Graph, BinaryTree, Array & CodeBlock](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/act2_algorithms.png) |
| **Act 3: 2D Linear Algebra Shear, Vector Field & Matrix** | **Act 4: Native Vector SVG & Animated ClipPath Spotlight** |
| ![Act 3: Linear Algebra & Matrix](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/act3_linear_algebra.png) | ![Act 4: SVG & ClipPath Spotlight](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/act4_cinema_assets.png) |

Run the full 2D showcase locally to generate `demo.mp4` (auto-prefers system FFmpeg when available, seamlessly falling back to built-in pure-Rust H.264/MP4) or inspect it interactively:

```bash
python demo.py
# Or launch the persistent GPU live-preview window (editing demo.py hot-reloads in place)
cocobrown preview demo.py
```

---

## 3D PBR Showcase

`cocobrown v0.5.0` ships with an independent **Google Filament v1.81.0 PBR 3D engine** (`Scene3D`, `Mat`, `Anim3D`) featuring AgX / PBR Neutral tone mapping, PCSS+CSM soft shadows, GTAO, SSR, HDR Bloom, GPU morph targets, analytic math surfaces, refractive glass, 3D extruded Typst typography, and crisp 2D HUD compositing — rendered directly from [examples/showcase_3d_5s.py](https://github.com/choroship357/cocobrown/blob/main/examples/showcase_3d_5s.py):

<div align="center">

![cocobrown v0.5.0 3D PBR Animated Showcase](https://raw.githubusercontent.com/choroship357/cocobrown/main/docs/assets/showcase_3d.gif)

</div>

```bash
# Render the 5-second 1080p60 Cinema PBR showcase locally
python examples/showcase_3d_5s.py
```

---

## 3-Minute Benchmark: cocobrown vs. Manim

To measure real-world long-form production performance (not a toy 3-second clip), we built an apples-to-apples **180.0-second (3-minute, 5,400-frame @ `1920×1080`, `30fps`)** complex 2D mathematical animation across **6 dense acts** (**80.6% continuous active motion**, 19.4% teaching pauses, 580 timeline segments, peak 103 simultaneously animated entities):

1. **Act 1 (0–30s)**: Cubic calculus (`Axes`, Riemann sum, integral area, sliding tangent + live numeric readout)
2. **Act 2 (30–60s)**: Reactive `sin(kx)` wave sweep + Fourier square-wave `S₁ → S₃ → S₅ → S₉` morphs + `Brace`
3. **Act 3 (60–90s)**: `NumberPlane`, 25-arrow vector field, shear & rotation grid/basis transformations
4. **Act 4 (90–120s)**: 8-node `Graph` shortest-path animation + 7-node `BinaryTree` inorder traversal
5. **Act 5 (120–150s)**: 6-cell sorting `Array` + pointer swaps, 3×3 `Matrix` highlights & `TransformMatchingTex`
6. **Act 6 (150–180s)**: 12-shape geometry grid, 2D camera pan/zoom choreography, hero morphs & finale equation

### Measured Wall-Clock Results (`1920×1080 @ 30fps`, 180.0s / 5,400 frames)

| Mode / Configuration | Total Wall Time | Effective Throughput | Video Size | Speedup vs. Manim |
|---|---:|---:|---:|---:|
| **Manim CE 0.22.1** — Cold render (fresh media dir, MiKTeX + Cairo + FFmpeg) | **145.47 s** (2m 25s) | 37.1 fps | 7.24 MB | 1.00× *(cold baseline)* |
| **cocobrown** — CPU + Built-in Pure-Rust MP4 (**zero FFmpeg**, cold) | **56.47 s** | 95.6 fps | 26.62 MB | **2.58×** |
| **cocobrown** — CPU (`tiny-skia` + `rayon`) + FFmpeg `libx264` (cold) | **21.40 s** *(build: 0.21 s)* | 252.4 fps | 8.47 MB | **6.80×** |
| **cocobrown** — GPU (`vello` + `wgpu`) + FFmpeg `libx264` (cold) | **15.24 s** *(build: 0.13 s)* | **354.4 fps** | 8.12 MB | **9.55×** |
| **Manim CE 0.22.1** — Incremental 1-edit (change final 2s formula, Manim cache ON) | **51.86 s** | 104.1 fps | 7.26 MB | 1.00× *(inc. baseline)* |
| **cocobrown** — Incremental 1-edit (SHA-256 pure-Rust cache, `446/483` segs reused, `61` frames rendered) | **3.00 s** | **1,797.3 fps** | 45.69 MB | **17.3×** *(48.5× vs. Manim cold)* |

> **Hardware & Transparency Notes**: Measured on Windows 11 ARM64 · Qualcomm Snapdragon X Plus X1P64100 (10-core Oryon CPU) + Qualcomm Adreno X1-85 GPU. `cocobrown` ran as a native `--release` `win_arm64` extension (Python 3.13 ARM64); `Manim CE 0.22.1` ran on Python 3.12 `win_amd64` (Windows Prism emulation, as `manimpango` does not publish Windows ARM64 wheels) with MiKTeX (`latex` + `dvisvgm`) and `ffmpeg`. Both produced verified `180.00s` H.264 `.mp4` videos. Reproduce locally:
>
> ```bash
> python benchmarks/run_benchmark.py --size 1920x1080 --fps 30
> ```
>
> Full scripts & raw JSON: [benchmarks/bench_scene_cocobrown.py](https://github.com/choroship357/cocobrown/blob/main/benchmarks/bench_scene_cocobrown.py), [benchmarks/bench_scene_manim.py](https://github.com/choroship357/cocobrown/blob/main/benchmarks/bench_scene_manim.py), [benchmarks/run_benchmark.py](https://github.com/choroship357/cocobrown/blob/main/benchmarks/run_benchmark.py), [benchmarks/results_3min.json](https://github.com/choroship357/cocobrown/blob/main/benchmarks/results_3min.json).

---

## Highlights

- **Native 3D PBR Rendering Engine (`v0.5.0`, Google Filament v1.81.0)**:
  - **Independent `Scene3D`, `Mat`, `Anim3D` API**: 6 curated stage presets (`studio`, `dark_neon`, `paper_light`, `blueprint`, `dramatic`, `transparent`), 3 quality tiers (`draft`, `standard`, `cinema`), 13 PBR materials (lacquer, metal, anodized, velvet, refractive glass, emissive, hologram, analytic math-surface grid/contours, shadow catcher), AgX / PBR Neutral tone mapping, PCSS+CSM soft shadows, GTAO, SSR, Bloom, DoF, and height fog.
  - **3D Math Geometry & 2D/Typst Fusion**: Parametric & SymPy heightfield surfaces with GPU `MorphTarget` transitions, 3D tube curves, marching-cubes isosurfaces, instanced vector fields, 3D extruded Typst typography (`extrude_tex`), billboard `tex3d`, 2D-to-3D `card_from_2d`, crisp 2D `s.hud` overlays, and a native 60fps interactive 3D preview window.
- **Zero External Dependencies Out of the Box**:
  - **Zero LaTeX / Zero TeX Live**: Embeds `typst 0.15` + compact New Computer Modern Math fonts, walking `FrameItem` trees and extracting `skrifa` outlines directly into `kurbo::BezPath` with full `Glyph.span` preservation (`Write`, sub-expression coloring, `TransformMatchingTex`).
  - **Smart FFmpeg-First + Zero-FFmpeg Pure-Rust Fallback**: Default `encoder="auto"` automatically discovers a usable system `ffmpeg` (checking `PATH` and standard WinGet/Scoop/Homebrew/Linux install paths) for peak `libx264`/HW encoding throughput & compact MP4s — and **seamlessly falls back to built-in pure-Rust H.264/AAC MP4** (`rusty_h264-encoder` + `muxide` + `rusty_aac`) when `ffmpeg` is not installed. Animated GIF (`gif`), multi-format audio decoding/mixing (`symphonia` for WAV/MP3/OGG/FLAC/AAC), and SHA-256 incremental caching all work out of the box with zero external dependencies, while `encoder="builtin"` forces pure-Rust and `encoder="ffmpeg"` unlocks transparent VP9 `.webm` & 10-bit alpha ProRes 4444 `.mov`.
- **Pure-Data Compile-Time `Timeline` IR**: Python scripts declare entities, layouts, and choreography during build time (`~0.2s` even for a 3-minute scene). After `finish()`, `cocobrown` releases the Python GIL and renders with **zero per-frame Python callbacks**.
- **Audio & Voiceover Timeline Synchronization**: Schedule SFX/BGM via `s.add_sound(...)` (gain, fade-in/out, trim) or align animations automatically to narration clips via `with s.voiceover("narration.wav") as dur:`. Audio tracks are hashed independently from video segments — re-recording voiceover re-renders **0 video frames**.
- **Rich CS, Math & Presentation Widgets**:
  - **Graphs & Data Structures**: `Graph`, `DiGraph`, `BinaryTree` (deterministic spring/circular/grid/tree layouts, shortest-path & traversal animations), `Array` + `ArrayPointer`, `Stack`, `Queue`.
  - **Presentation Widgets**: `Matrix` (auto-fitted brackets, row/col/entry highlights, elementary row/col swaps), `Table`, and `CodeBlock` (pure-Python multi-language syntax highlighting + `highlight_line` / `focus_lines`).
  - **Cartesian & SymPy Bridge (`cocobrown[sympy]`)**: `NumberLine`, `Axes`, `NumberPlane`, automatic asymptote splitting, exact analytic derivatives/Taylor series, 2D vector fields, 2×2 matrix transforms, and automatic `Tracker` reactivity.
- **Cinema, Assets & Compositing**:
  - **Raster Images & Vector SVG**: `s.image(...)` (PNG/JPEG/RGBA deduplicated in `.timeline` v4) and `s.svg(...)` (native vector paths via `usvg` with Y-up flip, gradients, strokes, and `Draw`/`Write` support).
  - **ClipPath Masking**: `entity.clip_to(mask)` with parent-inherited hierarchical masks, animated mask invalidation, and exact CPU (`tiny-skia::Mask`) / GPU (`vello::push_clip_layer`) parity.
  - **2D Camera & Follow**: `Camera2D` pan/zoom/roll, `CameraFocus`, `CameraReset`, and `s.camera_follow` / `s.start_camera_follow` tracking moving entities.
  - **Gradients, Dual-Lobe HDR Bloom & Persistent GPU Live Preview**: `LinearGradient`, `RadialGradient`, optional `s.bloom(...)`, and `cocobrown preview` zero-readback `winit + wgpu + vello` window with millisecond IPC hot-reload preserving the playhead.

---

## Architecture

```text
Python Modular API (colors · anim · camera · entity · scene · coords · graph · structures · widgets · audio · assets · symbolic)
  │  build time (~0.2s): cursor choreography, auto-layout, lambdify & Tracker/CameraFollow baking
  ▼
Pure-Data Timeline IR (Camera2D + Bloom + AudioClips + SoA SceneArena + ResourceTable[Geom/Morph/Image] + Tracks)
  │  static validation: overlap conflict detection, parent/clip acyclicity
  ▼
Compile-Time Optimizer (RenderPlan)
  │  O(n log n) sweep-line → static-segment 1-frame reuse + static bg/fg layer cache + SHA-256 segment hashes
  ├───────────────────────────────┬───────────────────────────────┐
  ▼                               ▼                               ▼
CPU Backend (tiny-skia)     GPU Backend (vello + wgpu)     Live Preview (winit + wgpu)
rayon frame parallelism     3-slot async readback ring     zero-readback swapchain + IPC hot-reload
  └───────────────┬───────────────┘
                  ▼  (optional dual-lobe HDR Glow / Bloom + symphonia/rusty_aac audio mix)
Modular Media Subsystem (crates/cocobrown-core/src/media/)
  ├─ System FFmpeg (Auto-Preferred for MP4 when found): libx264 · NVENC/VideoToolbox/QSV/AMF · WebM Alpha · ProRes 4444 MOV
  └─ Built-in Pure-Rust (Auto-Fallback for MP4, Default for GIF/Audio/PNG): rusty_h264 + muxide + rusty_aac · gif · PNG Sequence
```

---

## Installation

### From PyPI

```bash
pip install cocobrown
# Optional: enable the SymPy symbolic math bridge
pip install "cocobrown[sympy]"
```

### Requirements
- **Python** ≥ 3.9 (`abi3` stable ABI wheel)
- **Zero external binaries required** for default MP4, GIF, AAC audio muxing, PNG sequences, or GPU live preview
- **FFmpeg** *(optional)* on `PATH` only if you want `libx264`/hardware encoders, transparent `.webm`, or ProRes 4444 `.mov`
- **Rust** stable toolchain + `maturin` when building from source

### Build from Source

```bash
# 1. Create a virtual environment and install build/test tools
uv venv
uv pip install maturin pytest

# 2. Build and install the Rust core + Python extension (--release for full throughput)
maturin develop --release

# 3. Optional: enable the SymPy symbolic math bridge
uv pip install sympy
```

Verify installation:

```bash
cocobrown --version
python -c "import cocobrown as cb; print(cb.__version__, 'gpu:', cb.gpu_available())"
```

---

## Quick Start

Create a glowing, camera-directed SymPy calculus animation with native Typst math, gradient typography, voiceover sync, and zero-FFmpeg MP4 export in ~25 lines:

```python
import sympy as sp
import cocobrown as cb

x = sp.Symbol("x")
f = sp.Rational(1, 4) * x**3 - x

s = cb.Scene(size=(1280, 720), fps=60.0, background="#0B0F17")
s.bloom(intensity=0.45, threshold=0.50, radius=10)

ax = s.axes(x_range=(-3, 3, 1), y_range=(-2, 2, 1), x_label="$x$", y_label="$y$")
curve = ax.plot(f, color=cb.BLUE, width=0.055)
formula = (
    s.tex(f"$ f(x) = {cb.sympy_to_typst(f, wrap=False)} $", size=0.75)
    .fill(cb.LinearGradient([cb.BLUE, cb.YELLOW]))
    .to_corner(cb.UL, buff=0.45)
)

x0 = s.tracker(-2.0)
tangent = ax.tangent_line(f, x0, color=cb.YELLOW)  # exact analytic derivative + reactive baking

s.play(cb.par([cb.FadeIn(ax), cb.Write(formula), cb.Draw(curve)]), dur=1.0)
s.play(cb.ShowPassingFlash(curve, color=cb.YELLOW), dur=0.7)
s.play(cb.FadeIn(tangent), dur=0.35)
s.play(cb.par([x0.to(2.0), cb.CameraZoomTo(1.15)]), dur=2.0, ease=cb.Ease.IN_OUT)
s.play(cb.CameraReset(), dur=0.6)
s.wait(0.6)

# Default encoder="auto" uses system FFmpeg when available, else built-in pure-Rust MP4!
stats = s.bake("hello_cocobrown.mp4", quality="fast")
print(stats)
```

---

## CLI Tools

```bash
# 1. Launch persistent GPU preview window with live hot-reload (preserves playhead)
cocobrown preview demo.py

# 2. Bake MP4 / GIF (auto-prefers system FFmpeg when installed, pure-Rust fallback otherwise) or pick encoder explicitly
cocobrown bake demo.py -o demo.mp4 --quality fast --cache-dir .cocobrown_cache
cocobrown bake demo.py -o demo_x264.mp4 --encoder ffmpeg --codec auto --backend auto
cocobrown bake demo.py -o demo.gif --encoder builtin
cocobrown bake demo.py -o overlay.mov --encoder ffmpeg
cocobrown bake demo.py -o frames_out --format png

# 3. Run pre-render static IR diagnostics (static reuse ratio, peak complexity, bandwidth)
cocobrown diagnose demo.py
```

Preview controls: `Space` Play/Pause · `←` / `→` Step 1 frame · `Home` / `End` Jump to start/end · `R` Restart · Click/Drag scrub bar for 60fps seeking · `Q` / `Esc` Quit.

---

## Documentation

- **[README.zh-CN.md](https://github.com/choroship357/cocobrown/blob/main/README.zh-CN.md)** — 简体中文版项目说明。
- **[USAGE.md](https://github.com/choroship357/cocobrown/blob/main/USAGE.md)** | **[USAGE.zh-CN.md](https://github.com/choroship357/cocobrown/blob/main/USAGE.zh-CN.md)** — Complete `v0.5.0` API & feature guide (English / 简体中文).
- **[DESIGN.md](https://github.com/choroship357/cocobrown/blob/main/DESIGN.md)** — Architecture whitepaper (Timeline IR, BlendMode, static layer caching, GPU async readback ring, and engineering trade-offs).
- **[ROADMAP.md](https://github.com/choroship357/cocobrown/blob/main/ROADMAP.md)** — Milestone progression (`v0.0.1` → `v0.5.0`, incl. the optional 3D extension).
- **[third_party/filament/README.md](https://github.com/choroship357/cocobrown/blob/main/third_party/filament/README.md)** — Prebuilt & custom Google Filament SDK setup (including the fast Ninja trimmed static build script [build-ninja.bat](https://github.com/choroship357/cocobrown/blob/main/third_party/filament/scripts/build-ninja.bat) for Windows ARM64 / x64).

---

## 3D Backend (`cocobrown-3d-gpu`) & Acknowledgements

`cocobrown v0.5.0` ships with the **Google Filament v1.81.0** PBR 3D backend (`cocobrown-3d-gpu`, Vulkan on Windows/Linux and Metal on macOS) integrated directly into the native `abi3` wheels (`linux-x86_64`, `windows-x64`, `windows-arm64`, `macos-arm64`).

For **Windows ARM64** source builds (not yet merged into upstream Filament), copy [third_party/filament/scripts/build-ninja.bat](https://github.com/choroship357/cocobrown/blob/main/third_party/filament/scripts/build-ninja.bat) into the community-patched Windows ARM64 fork [`nithin-aashik-mcw/filament`](https://github.com/nithin-aashik-mcw/filament) and run `build\windows\build-ninja.bat release arm64 md core` (see [third_party/filament/README.md](https://github.com/choroship357/cocobrown/blob/main/third_party/filament/README.md) for full steps and the Qualcomm Adreno `VK_LOADER_DRIVERS_DISABLE=*dzn*` note).

> **Acknowledgements**: Many thanks to **[nithin-aashik-mcw](https://github.com/nithin-aashik-mcw/filament)** for providing and maintaining the Windows ARM64 port of Google Filament!

---

## License

Licensed under the [Apache License, Version 2.0](https://github.com/choroship357/cocobrown/blob/main/LICENSE) — Copyright 2026 [choroship357](https://github.com/choroship357).

