Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

16.2 KB
Raw Blame

[!NOTE] Archived optimization log (v0.2–v0.4). Some historical sizes, token counts, and early WASM symbol names (such as eval_pipe_text) have since evolved (current WASM C-ABI uses forma_session_*). For current v0.4.5 APIs and specs, see docs/reference/apis.md.

forma v0.2 Autoresearch Hill-Climb & Universal Core Upgrade Log

1. Kernel Autoresearch Hill-Climb Progression (100% Pure Rust, Zero New Dependencies)

Every iteration was gated by strict automated assertions on all 8 macro-modeling pipelines (WT=true, NM=0, B=0, exact analytical volume within ±0.03), all 12 benchmark geometries, the 11,000-operation randomized fuzzer (0 panics, 0 NaNs, 95.1% unconstrained watertight, 100% strict transactional watertight), and byte-identical .glb determinism.

End-to-End 8-Pipeline Suite Progression (Apple Silicon, Release, Median of 3)

Iteration Core Algorithmic Breakthrough flange_plate l_bracket pipe_tee beveled_enc hex_nut subdiv_mug arched_bridge table_frame TOTAL SUITE Speedup vs Iter 0
Iter 0 (Baseline) Global recursive BSP CSG + HashMap adjacency/weld + BTreeMap cancel 439.24 ms 30.96 ms 587.36 ms 3.59 ms 12.03 ms 265.15 ms 3.06 ms 3.12 ms 1,344.51 ms 1.00×
Iter 1 Flat binary AABB-BVH + local plane subdivision + BVH ray-parity oracle + X-sorted T-junction sweep 132.64 ms 15.80 ms 103.36 ms 2.60 ms 24.42 ms 256.39 ms 7.64 ms 7.44 ms 550.29 ms 2.44×
Iter 2 Möller (1997) exact 3D tri-tri intersection interval filter + per-fragment segment overlap guard (eliminates $O(k^2)$ distant shattering!) + 2nd irrational ray fallback + sort-based cancel_opposing 37.97 ms 7.04 ms 23.66 ms 1.31 ms 6.23 ms 26.94 ms 2.44 ms 2.53 ms 108.14 ms 12.43×
Iter 3 Zero-HashMap X-sorted weld_and_clean + Zero-HashMap sort+DSU MeshInvariants::compute + Zero-HashMap sort+binary-search catmull_clark_step + direct glTF JSON formatting + fast count_bad_edges 10.69 ms 2.79 ms 14.07 ms 0.59 ms 1.54 ms 18.84 ms 0.82 ms 0.78 ms 50.11 ms 26.83×
Iter 4 Per-triangle coplanar/quad plane deduplication & interval merging + zero-copy move split_poly_by_plane_guarded + AABB pre-guard + zero-HashMap prune_folded_flaps 11.82 ms 2.18 ms 10.41 ms 0.47 ms 1.14 ms 13.20 ms 0.77 ms 0.67 ms 40.65 ms 33.08×
Iter 4 + Batch CSG Pairwise-disjoint multi-tool boolean_batch (cuts all 5 flange holes in 1 BVH pass instead of 5 sequential passes) 8.09–9.52 ms 2.18 ms 10.41 ms 0.47 ms 1.14 ms 13.20 ms 0.77 ms 0.67 ms ~37 ms ~36× (up to 56.4× on pipe_tee, 54× on flange_plate!)

Micro-Op Latency Progression (Median, Microseconds)

Kernel Operation Iter 0 (Baseline) Iter 4 (Optimized) Speedup
make_box 0.3 µs 0.3 µs 1.0× (300 ns)
make_cyl(32) 2.0 µs 1.8 µs 1.1×
inset 3.2 µs 1.0 µs 3.2×
subsurf(2) 62.8 µs 6.9 µs 9.1×
subsurf(3) 133.8 µs 28.1 µs 4.8×
invariants::compute 543.5 µs 39.1 µs 13.9×
shell_solid (beveled enclosure) 4,227.1 µs 210.5 µs 20.1×
render_512px (4-view studio PNG, pure Rust) N/A (30.7 ms initial) 3.92 ms (LUT CRC32 + Pineda + backface cull) 7.8×
11,000-op Fuzzer (fuzz_invariants) ~28,000 ms 4,575 ms (0.416 ms/op) ~6×

Why Each Breakthrough Worked

  1. Möller 1997 Interval-Guarded Local Splitting (Iter 2 — 5.1× jump): In naive local plane-splitting, a 32-segment cylinder cutting a large rectangular plate face shatters a single plate triangle into $\binom{32}{2}+1 \approx 497$ tiny convex polygons because each cylinder facet's infinite plane slices distant polygons across the whole face. Guarding split_poly_by_plane with the exact 1D intersection-line interval overlap [tb_lo, tb_hi] reduced output triangle count on pipe_tee from 4,304 → 1,822 F and flange_plate from 6,624 → 2,176 F.
  2. Eliminating SipHash HashMaps on Hot Inner Loops (Iter 3 — 2.2× jump): Replacing the 27-cell HashMap<(i64,i64,i64), Vec<usize>> vertex welder with an O(N log N) X-sorted spatial sweep, replacing MeshInvariants::compute's dual HashMap + BFS with a single flat sorted u64 half-edge array + Union-Find DSU, and replacing catmull_clark_step's HashMaps with sorted u64 edge keys + binary search cut invariants 13.9×, shell_solid 20.1×, and subsurf(2) 9.1×.
  3. Quad Plane Deduplication & Zero-Copy Moves (Iter 4): Merging coplanar/quad-pair CutPlane intervals halves plane splitting passes on every prism/cylinder; moving PolyVerts by value (scratch_a.drain(..)) eliminates clones on unsplit fragments.
  4. Fuzzer-Caught T-Junction Sliver Cascade Fix: The 11,000-op fuzzer immediately caught an exponential triangle cascade in eliminate_t_junctions on degenerate non-manifold fuzzed meshes when boundary vertices sat within seg_tol of edge endpoints. Rejecting near-endpoint T-junction candidates and capping max face expansion restored 4.5s execution with 0 panics, 0 NaNs.

2. Empirical Pass@1 Fixes & Universal Modeling Core Upgrades (v0.2)

  1. Fixed the #1 Empirical Pass@1 Bug (ops.rs::try_bevel_z_rims):
    • Root cause from the 254-trial audit: 10/29 Turn-1 failures occurred on hex_nut when models wrote cyl(1, 0.8, 6) | bevel(top_rim, 0.1) | bevel(bottom_rim, 0.1). The second bevel rebuilt the prism from top_faces[0] (already inset to R=0.885), shrinking the whole nut!
    • Fix: extract_z_prism_rings walks the existing horizontal ring stack and preserves any existing bevel on the opposite rim. Verified via unit test: top_rim → bottom_rim, bottom_rim → top_rim, and outer_rim now produce identical R=1.0, vol=1.3965 geometry.
  2. Forgiving Forma-Pipe Ergonomics & Batch CSG:
    • Automatic boolean_batch for multi-placement add/cut(..., at=[...]).
    • Multi-point at=[(x,y,z), ...] directly on primitives (box, cyl, cone, sphere, torus).
    • Forgiving keyword aliases (radius/r, height/h, width/w, thickness/t, segments/segs, start_deg/start, end_deg/end, center/at, levels/level/n).
  3. Semantic PBR Materials & Automatic Triplanar UVs (mesh.rs, export.rs, pipeline.rs):
    • Per-face mat_id + Material { name, color, metallic, roughness } preserved across booleans and subdivision.
    • glTF 2.0 .glb exports named materials (multi-primitive per material slot) + seamless triplanar TEXCOORD_0 UVs.
    • Pipe syntax: | mat("brushed_steel", color=(0.72, 0.76, 0.84), metallic=0.9, roughness=0.25, faces=...) and | color(r, g, b).
  4. Spatial Constraints & Geometric Inspection (spatial.rs):
    • | on(base, gap=0) (flush relational stacking), | align(x|y|z, min|center|max, val).
    • clearance(a, b) (exact 3D surface minimum distance + intersection check) and section(part, z) (exact 2D cross-section loop count, area, perimeter, XY bounds).
  5. Built-In Pure-Rust 3.9 ms Headless Software PNG Renderer (render.rs):
    • Zero-GPU, zero-Blender, zero-crate scanline Z-buffer rasterizer with Pineda incremental edge stepping, backface culling, hemisphere+key+rim lighting, sharp feature-edge wireframe overlays, and LUT-CRC32 PNG encoding.
    • Exposed via forma render --out preview.png, forma eval --render preview.png, and forma-mcp export(path="preview.png").
  6. Formal GBNF Constrained-Decoding Grammar (grammar/forma_pipe.gbnf & forma spec --gbnf):
    • Ready for llama.cpp, vLLM, and XGrammar for 0%-syntax-error constrained decoding, while keeping forma-mcp tools/list strictly < 800 o200k tokens (776 o200k tokens verified)!
  7. Reproducible Google Colab Notebook (notebooks/forma_autoresearch_colab.ipynb).

3. Verified v0.2 Independent Gate & 4-Model Re-Test Results

3.1 Independent Phase 3.6 Gate (bench/gate_verify.py)

  • 12/12 benchmark geometries PASSED (trimesh + scipy Chamfer/H99/Volumetric IoU 0.980–1.000, WT=True, NM=0, 16-layer planar slicer PASS, stock Blender 5.3 import PASS with triplanar TEXCOORD_0 UVs).
  • Median cold-start CLI + eval + .glb export latency: 14.66 ms (89× faster than stock Blender 5.3 bpy's 1,306.8 ms).
  • .blend bridge: PASS (stock Blender 5.3 manifold reload NM=0).
  • MCP stdio JSON-RPC 2.0 E2E: PASS, 776 o200k tokens < 800 (with PBR materials, spatial queries, on/align, and .png studio rendering included).
  • Static binary footprint: forma 1.1 MB, forma-mcp 1.1 MB.
  • Fuzz & Determinism (cargo test --release): 11,000 fuzzed ops in 4.00 s (0.364 ms/op), 0 panics, 0 NaNs, 95.0% unconstrained watertight, 100% strict transactional watertight, 100% byte-identical .glb replay.

3.2 Live 4-Model v0.2 Re-Test (SUITE_6, low reasoning, bench/results/v2_retest.json)

Model (low reasoning) v0.1 Pass@1 v0.2 Pass@1 v0.2 Pass@2 v0.2 hex_nut v0.2 Med Exec v0.2 Avg Tokens v0.2 Mean IoU
anthropic/claude-haiku-5.5 3/6 (50.0%) 6/6 (100.0%) 6/6 (100.0%) P@1 (IoU 1.000) 17.89 ms 1,820 (↓40% vs v0.1) 0.981
anthropic/claude-opus-5.5 6/6 (100.0%) 5/6 (83.3%) 6/6 (100.0%) P@1 (IoU 1.000) 18.64 ms 1,601 0.987
openai/gpt-6.2-sol 4/6 (66.7%) 4/6 (66.7%) 6/6 (100.0%) P@1 (IoU 1.000) 29.45 ms 1,326 0.972
google/gemini-4-hydrogen 5/6 (83.3%) 4/6 (66.7%) 6/6 (100.0%) P@1 (IoU 1.000) 19.41 ms 2,306 0.979
Aggregate (24 trials) 18/24 (75.0%) 19/24 (79.2%) 24/24 (100.0%) 4/4 (100%, IoU 1.000) 21.23 ms 1,763 0.980

Highlights:

  • hex_nut (formerly #1 Turn-1 failure at 10/29 errors) hit 4/4 (100%) Pass@1 with IoU = 1.000 in 12.4–16.7 ms across every model.
  • claude-haiku-5.5 doubled Pass@1 from 50% → 100% (6/6) while slashing total API tokens 40% (18,159 → 10,920, 3.32× fewer than stock Blender bpy).
  • 100% Pass@2 (24/24) across all 4 models with 0.980 Mean Volumetric IoU and 21.23 ms median execution latency.

4. Wave 2 Upgrades (forma v0.3)

  1. Kernel Micro-Optimizations & Autoresearch Finding:
    • Added root-AABB fast-path rejection (!t.aabb.overlaps(&root_bb) skips both BVH query and ray-parity oracle), cached per-fragment Aabb in subdivide_tri_local, and unique tag-set interning (tag_table shrunk from ~2,000 clones to ~6 entries). Result: flange_batch_5h dropped to 5.68 ms (77.3× faster than Iter 0's 439.24 ms)!
    • Empirical Negative Result (Reverted): Spawning std::thread::scope OS threads for medium booleans (>=192 tris) regressed suite latency due to macOS pthread_create wakeup jitter (40 ms → 251 ms); raised parallel threshold to >=8,000 tris so CAD booleans stay zero-overhead single-threaded.
  2. Renderer Compression & Studio Polish (render.rs):
    • Replaced stored PNG blocks with pure-Rust Sub-filtered RFC 1951 Fixed-Huffman LZ77/RLE Deflate (787 KB → 20.9 KB on flange_plate — 37.5× smaller, 68–74 KB on detailed helical bolts & copper ducts!).
    • Added a 3×3 depth-discontinuity silhouette + screen-space cavity AO (apply_ssao_and_silhouettes) post-pass so threads, bevels, and hollow cavities read crisply for VLMs and humans.
  3. Universal CAD & Organic Primitives + .3mf + forma-wasm:
    • pipe(r_out, r_in, h, segs=32, axis=z) (exact genus=1 hollow cylinder, zero booleans).
    • loft([(z, [(x,y),...]), ...], segs=24) (arc-length resampled, twist-free 2D-to-2D multi-section loft).
    • thread(r_minor, r_major, pitch, turns, segs=28) (watertight ISO trapezoidal helical screw threads with entry/exit runout tapers — full hex-head titanium bolt built + unioned + .3mf + 74 KB SSAO PNG in 9.78 ms!).
    • Crease-aware Catmull-Clark subsurf(levels, crease=true) (DeRose sharp crease/corner rules preserving exact bounding box on sharp solids) + Euler genus (g=...) in MeshInvariants & observe().
    • Pure-Rust .3mf export (OPC ZIP + XML 3D Manufacturing Format, zero crates).
    • crates/forma-wasm browser WebAssembly bindings (eval_pipe_text, eval_pipe_png).
  4. Autonomous Karpathy-Style Autoresearch Runner (bench/autoresearch_runner.py):
    • Turnkey CLI runner proposing targeted Rust kernel patches via OpenRouter, benchmarking perf_bench, gating on kernel_tests + 11,000-op fuzz_invariants, auto-reverting regressions, and logging every experiment to bench/results/autoresearch_log.jsonl.
  5. Prompt-Engineering Empirical Lesson (v0.3 4-Model Re-Test):
    • claude-opus-5.5 jumped to 6/6 (100.0%) Pass@1 (1,236 avg tokens, subdiv_mug IoU 0.954 → 0.991), and all 4 models stayed 24/24 (100.0%) Pass@2.
    • Dropping explicit at=, z0= inside box/cyl signatures in SPEC_PIPE temporarily hurt small-model (claude-haiku-5.5) Turn-1 accuracy (6/6 → 2/6 P@1, 6/6 P@2); restoring explicit box(sx,sy,sz, at=, z0=) & cyl(r,h, segs=32, axis=z, at=, z0=) while keeping the full MCP schema strictly < 800 o200k tokens resolves that cleanly.

5. Wave 3 Upgrades (forma v0.4) — Coplanar Collapse, STEP/SVG/Sweep/Text3D, Live Autonomous Hill-Climb & Launch Asset Pack

  1. Zero-Error Link-Condition Coplanar & Collinear-Ridge Edge Collapse (boolean.rs::simplify_coplanar_mesh):
    • Strictly enforces the Edelsbrunner Link Condition (|N(u) ∩ N(v)| == 2, shared_faces == 2), single-material / ≤2-plane zero-error constraints, and positive oriented area preservation.
    • Triangle reductions (0.0000 volume error, WT=ok NM=0): flange_plate 2,176 → 546 F (-75%), pipe_tee 1,822 → 524 F (-71%), l_bracket 838 → 222 F (-74%), hex_nut 578 → 176 F (-70%), arched_bridge 428 → 128 F (-70%), table_frame 154 → 76 F (-51%).
    • Speedups: Full 8-pipeline in-memory suite reached 27.20 ms (49.4× faster than Iter 0's 1,344.51 ms); flange_batch_5h hit 5.43 ms (80.9× faster); 11,000-op fuzzer dropped to 2.46 s (0.224 ms/op); all 12 benchmark meshes build + export in 61.22 ms (5.10 ms/mesh) (pipe_tee down to 7.51 ms, 78.2× faster than Iter 0!).
  2. Real Live Autonomous Autoresearch Run (bench/autoresearch_runner.py):
    • Upgraded to surgical <<<SEARCH / === / >>>REPLACE patches so large kernel files never hit output-token limits.
    • Live 2-iteration run on boolean.rs with anthropic/claude-opus-5.5: Iter 1 KEPT (39.19 → 37.41 ms, adding a cheap per-triangle AABB guard in point_inside BVH leaves, verified across all 8 kernel_tests + 11,000-op fuzzer + .glb determinism); Iter 2 auto-reverted (53.53 ms). Logged in bench/results/autoresearch_log.jsonl.
  3. Parametric CAD Interchange & Ops:
    • Pure-Rust ISO 10303-21 STEP AP214 manifold solid B-rep exporter (export::write_step, .step/.stp).
    • Pure-Rust 1200×900 Vector Technical Blueprint SVG exporter (render::write_blueprint_svg, forma draw --out blueprint.svg / forma eval --draw blueprint.svg) with automatic engineering dimension lines and ISO title block.
    • Added sweep(profile_2d, path_3d), text3d(text, size, depth), pattern_linear(n, step), and pattern_radial(n) in Forma-Pipe + grammar/forma_pipe.gbnf.
  4. Broadcast Launch Video Asset Pack (assets/launch/ & docs/showcase.html):
    • Generated 6× 1024×1024 pure-Rust SSAO+Deflate studio PNGs (43–169 KB), 3× SVG technical blueprints, .step/.3mf/.glb files, 3× 1920×1080 dark-mode PRISMATLAS broadcast charts, and standalone docs/showcase.html.
  5. Final Gate Verification (gate_verify.py): 12/12 PASS (WT=True, NM=0, BL=True, SLICE=True), 16.92 ms median cold-start CLI+eval+export, .blend bridge PASS, MCP stdio E2E PASS at 789 o200k tokens < 800.