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

21.9 KB
Raw Blame

forma-ue: Optional Unreal Engine 5.4–5.6 & OpenUSD Addon Specification

  • Status: Approved Technical Spec — Implementation Tracked in #87
  • Target Crate: crates/forma-ue (opt-in workspace member, excluded from default-members)
  • Core Impact: 0 bytes on core forma / forma.wasm, 0 tokens on core forma-mcp, 0 new external crates
  • Default Profile: classic (universal UE 5.4–5.6 compatibility: LOD chain + lightmap UV1 + collision + tangents), with --profile nanite and --profile mobile
  • Tracks: Milestone #3 · Proposal #87 · Bridges #65 (COLOR_0), #67 (box_uv), #68 (non-boolean merge & hierarchies)

[!IMPORTANT] Zero-Bloat Guarantee: crates/forma-ue sits in workspace.members but is excluded from default-members (the exact same pattern proven by crates/forma-print and crates/forma-server). When not built or enabled, it adds 0 bytes to core forma / forma-mcp / forma.wasm and 0 tokens to forma-mcp's <800-token schema.


1. Design Goals & Constraints

forma-ue is an opt-in, pure-Rust Unreal Engine 5.4–5.6 Static Mesh semantic compiler & offline preflight verifier built directly on forma-core and forma-lang.

Constraint Requirement
Workspace isolation Listed in root Cargo.toml under workspace.members, excluded from default-members. cargo build --release (default) adds 0 bytes.
Zero core edits (Tier 1) Zero edits to forma-core, forma-lang, forma-cli, forma-mcp, forma-wasm, or package.json in Tier 1.
Zero new external crates Only workspace-existing deps: forma-core, forma-lang, serde, serde_json, thiserror. No C++ USD SDK, no FBX SDK, no C/C++ FFI.
Deterministic & headless Pure-Rust, bit-reproducible .glb, .usda, and JSON manifests/reports in milliseconds without booting Unreal Editor.
Opt-in MCP budget forma-ue --mcp exposes 3 compact tools totaling <= 350 o200k tokens (0 tokens on core forma-mcp).
Honest verification boundary Offline verification guarantees portable container, geometry, UV, tangent, collision-hull, and policy correctness; final UE Interchange / DataValidation commandlet checks remain an optional studio CI stage.

2. Critical Format Contract: .glb (Interchange) vs. .usda (OpenUSD)

UE 5.4, 5.5, and 5.6 Interchange glTF and OpenUSD have different import contracts. forma-ue must never conflate them.

Capability .glb (UE 5.4–5.6 Interchange glTF 2.0) .usda (UE 5.4–5.6 USD Stage / Interchange USD)
Coordinate system & units Right-handed, +Y up, +Z forward, metres (Khronos spec). UE Interchange auto-applies 100× m → cm & basis remap (x,y,z)_m → 100*(z,-x,y)_cm. Never pre-scale .glb by 100×. upAxis = "Z", metersPerUnit = 0.01, coordinates in centimetres (Scene.unit → cm). Explicit subdivisionScheme = "none" and orientation = "rightHanded".
Multi-material single mesh Single glTF mesh with multiple primitives (one per mat_id), each referencing a named pbrMetallicRoughness material. Single UsdGeomMesh with UsdGeomSubset children (elementType = "face", familyName = "materialBind", face indices) + UsdPreviewSurface.
Simple collision Naming convention: sibling/child mesh nodes UBX_<Mesh>_00, UCP_<Mesh>_00, USP_<Mesh>_00, UCX_<Mesh>_00 (requires Interchange collision=true + import_collision_according_to_mesh_name=true). KHR_physics_rigid_bodies is not supported by stock UE glTF. OpenUSD Physics Schemas (UE 5.4+): prepend apiSchemas = ["PhysicsCollisionAPI", "PhysicsMeshCollisionAPI"], bool physics:collisionEnabled = 1, physics:approximation = "convexHull" | "boundingCube" | "none". Separate custom hulls use sibling Mesh with purpose = "guide" + physics:approximation = "none". Do not rely on UCX_/UBX_ names in USD.
Authored Static Mesh LODs Not reliably supported by stock UE 5.4–5.6 glTF translator (MSFT_lod and LOD0/LOD1 nodes are not confirmed stock glTF LODs). For .glb, emit Nanite LOD0 or split LOD files (--split-lods) + kit manifest for pipeline assembly. Supported (USD Stage importer): variantSet "LOD" with exact variant names "LOD0", "LOD1", "LOD2", ... and variants = { string LOD = "LOD0" } (enabled via interpret_lods = true).
Sockets Empty leaf nodes named SOCKET_<MeshName>_xx (Interchange import_sockets = true). Note: verify Bake Meshes vs. pivot preservation on target UE minor version. def Xform "SOCKET_<MeshName>_xx" emitted as spatial markers (documented as requiring post-import conversion or verified Interchange USD build to become UStaticMeshSocket).
UV0 & Lightmap UV1 TEXCOORD_0 (box/LSCM) + TEXCOORD_1 (lightmap, non-overlapping [0,1]²). Set Interchange src_lightmap_index=0, dst_lightmap_index=1 (or disable auto-generation when pre-authored). texCoord2f[] primvars:st + texCoord2f[] primvars:st1 (vertex or faceVarying + :indices at seams).
Tangents TANGENT (VEC4<f32>, normalized XYZ, W ∈ {-1, +1}, B = cross(N, T) * W). Computed via MikkTSpace in glTF right-handed space; never manually negate W. Omit custom tangent primvars (no standard UE USD Static Mesh tangent import contract); author accurate normals + primvars:st and let UE compute MikkTSpace tangents.
Vertex colors / masks COLOR_0 (VEC4 normalized u8 or f32, linear [0, 1], never sRGB-encoded). color3f[] primvars:displayColor + float[] primvars:displayOpacity (linear Rec.709), plus optional purpose-named float[] primvars (primvars:ao, primvars:edgeWear, primvars:height, primvars:blend).

[!WARNING] Runtime Packaged GLB Collision Caveat: Editor-time Interchange GLB collision works when enabled, while packaged/runtime GLB import has had known collision limitations across UE 5.4–5.6. forma-ue targets editor / CI asset ingestion (InterchangeGenericMeshPipeline / USD Stage).


3. Unit Conversion, Coordinate Frames & Pivots

3.1 Unit Normalization (units.rs)

Read Scene.unit via forma_core::units::Unit (default Meter, matching crates/forma-print/src/units.rs):

  • Convert coordinates to metres (scale_to_m) for .glb export and to centimetres (scale_to_cm = scale_to_m * 100.0) for .usda, collision tolerances, grid-snap checks, and manifest dimensions.
  • Warn in verify / export on suspicious physical extents (< 1 cm or > 100 m under default Meter).

3.2 Pivot Modes (pivot.rs)

Mode Anchor Point Intended Asset Class
bottom-center (default) ((min_x + max_x)/2, (min_y + max_y)/2, min_z) Freestanding props, furniture, machinery placed on floors and rotated in place.
corner (min_x, min_y, min_z) Modular architectural walls, floors, ceilings, trim (keeps one grid corner locked on-grid during 90° rotations).
origin (0, 0, 0) (preserve authored origin) Symmetric parts, wheels, doors with authored hinge origin, assemblies with explicit world offsets.

All pivot shifts are baked into vertex positions (and matching collision/socket transforms) so exported root transforms have identity translation, rotation, and scale ((1, 1, 1)).

3.3 Naming Grammar (naming.rs)

Configurable prefix policy defaulting to SM_ (supporting Allar's S_ via --prefix S_):

  • Render mesh: <Prefix><SanitizedName> (e.g., SM_Wall_A_01)
  • Materials: M_<MatName> (preserving names already prefixed M_ / MI_)
  • Collision hulls (.glb): UBX_<MeshName>_00, UCX_<MeshName>_00, UCX_<MeshName>_01, ...
  • Sockets: SOCKET_<MeshName>_<SocketName> (e.g., SOCKET_SM_Door_01_Handle)

4. Pure-Rust Geometry & Attribute Specifications

4.1 Non-Boolean Multi-Material Merge (merge.rs) — Bridges #68

  • Combines multiple Scene parts into one render asset without CSG booleans (preserving each part's mat_id, smooth normals, and watertight shells with zero seam corruption on touching architectural trim/frames/glass).
  • Supports both single merged Static Mesh mode (default) and modular kit split mode (--split-parts, one asset per named part + shared kit manifest).

4.2 World-Scale Box / Triplanar UV0 (uv_box.rs) — Bridges #67

  • Let p = (x, y, z) be UE Z-up position in centimetres, p_0 the pivot/world origin, and S the physical repeat period in cm (default S = 100.0 cm, i.e., 1 UV = 1 m = 10.24 px/cm on a 1024 px texture; configurable via --uv-scale / --uv-period-cm).
  • Normalized coordinates q = (p - p_0) / S, projected onto the dominant outward face normal plane (|n_x|, |n_y|, |n_z|):
    • |n_x| dominant (X-facing wall): u = sign_x * q_y, v = q_z (sign_x = +1 for +X, -1 for -X).
    • |n_y| dominant (Y-facing wall): u = sign_y * q_x, v = q_z (sign_y = -1 for +Y, +1 for -Y).
    • |n_z| dominant (floor/ceiling): u = q_x, v = q_y.
  • Keeps brick/wood grain upright on all four walls with zero upside-down flips.
  • Modes: --uv0 box, --uv0 lscm (reuses forma_core::uv), or --uv0 preserve (fallback to box if missing).

4.3 Lightmap UV1 (uv_lightmap.rs → TEXCOORD_1 / primvars:st1)

Required on classic (default) and mobile profiles; optional on nanite:

  • Every triangle maps to unique, non-overlapping, non-wrapping coordinates strictly inside [0, 1]².
  • Reuses forma_core::uv crease-split charting (angle_deg = 66° default) with uniform area normalization (A_uv / A_3 ≈ const) and deterministic packing.
  • Target lightmap resolution R ∈ {64, 128, 256, 512} (default 128), P = 4 texels minimum inter-chart gutter (margin >= 4 / R for DXT 4×4 blocks), and optional Epic usable-grid snapping g'_R = 1 / (R - 2) (1/62, 1/126, 1/254, 1/510).

4.4 MikkTSpace Tangents (tangent.rs → .glb TANGENT)

Pure-Rust implementation following Morten S. Mikkelsen's reference specification (mikktspace.c):

  • For triangle (p_0, p_1, p_2) with UV0 (s_i, t_i): e_1 = p_1 - p_0, e_2 = p_2 - p_0, D = (t_2 - t_0)(s_1 - s_0) - (s_2 - s_0)(t_1 - t_0). For |D| > 1e-12: S = [(t_2 - t_0) e_1 - (t_1 - t_0) e_2] / D, S_⊥ = S - N(N · S), T = normalize(S_⊥), W = sign(D) ∈ {-1, +1}.
  • Evaluated on unindexed face corners, angle-weighted (θ = acos(clamp(u · v, -1, 1))), grouping only corners sharing identical position, normal, UV0, and UV orientation sign sign(D).
  • Splits vertices cleanly at UV/normal/handedness seams before welding exact matching vertex tuples; degenerate UV triangles inherit a valid neighbor or deterministic orthonormal fallback.
  • Emitted as VEC4<f32> in .glb right-handed space; omitted in .usda.

4.5 Simple Collision (collision.rs → UBX_ / UCX_ / USD Physics)

  • Conservative Chaos contract: default <= 32 hulls, <= 16 vertices/hull (matching Epic's Auto Convex Collision baseline; configurable).
  • Tier 1 Modes:
    1. auto (default): Emit UBX_ AABB when component volume matches AABB within <= 2%; otherwise emit pure-Rust f64 3D QuickHull UCX_ (scale-aware epsilon ε_f = 1e-9 + 1e-6 * L, verified outward winding, vertex-budget simplification to <= max_hull_verts).
    2. box: Always emit UBX_ bounding box(es).
    3. hull: Always emit UCX_ per connected component.
    4. none: Emit no collision.
  • Tier 2 Concave Convex Decomposition (decomp):
    • Pure-Rust V-HACD-style recursive voxel plane-splitting (zero C++ deps) for concave assets (pipes, arches, doorways, brackets) using volume concavity C_vol(S) = [3 * (Vol(CH(S)) - Vol(S)) / (4 * π)]^(1/3).

4.6 Auto-LOD Chain (lod.rs) & Profiles

Reuses forma_core::ops::decimate_mesh() (Link-Condition QEM, preserving mat_id):

Profile Default? LOD Ratios Lightmap UV1 Collision Extra Checks
classic Yes (default) [1.0, 0.50, 0.25, 0.12] (skip < 64 tris) Required (R = 128, P = 4) auto (UBX_/UCX_) Full UV1 overlap + [0,1]² gate
nanite No (--profile nanite) [1.0] (LOD0 only) Optional (--lightmap-uv1) auto (UBX_/UCX_) Rejects translucent (opacity < 1.0) materials
mobile No (--profile mobile) [1.0, 0.40, 0.15] Required (R = 64, P = 4) auto (<= 8 hulls) Stricter material-slot (<= 2) & tri warnings
  • .usda writes native variantSet "LOD" ("LOD0", "LOD1", ...).
  • .glb writes LOD0 (with optional --split-lods writing <name>_LOD0.glb, <name>_LOD1.glb, ... indexed in the kit manifest).

4.7 Procedural Linear COLOR_0 Vertex Masks (color_mask.rs, Tier 2) — Bridges #65

  • Linear [0, 1] RGBA packing: R = AO/cavity, G = edge wear/curvature, B = Z height gradient, A = per-part blend/variation.
  • Encoded as linear normalized VEC4<u8> in .glb COLOR_0 and as linear color3f[] primvars:displayColor + purpose-named primvars:ao, primvars:edgeWear, primvars:height, primvars:blend in .usda.

5. Pure-Rust .usda Minimal Verified Output Schema

#usda 1.0
(
    defaultPrim = "SM_Wall_A_01"
    upAxis = "Z"
    metersPerUnit = 0.01
    doc = "Exported by forma-ue"
)

def Xform "SM_Wall_A_01" (
    kind = "component"
    variants = {
        string LOD = "LOD0"
    }
    prepend variantSets = "LOD"
)
{
    def Scope "Materials"
    {
        def Material "M_Brick"
        {
            token outputs:surface.connect = </SM_Wall_A_01/Materials/M_Brick/PreviewSurface.outputs:surface>
            def Shader "PreviewSurface"
            {
                uniform token info:id = "UsdPreviewSurface"
                color3f inputs:diffuseColor = (0.45, 0.16, 0.12)
                float inputs:metallic = 0.0
                float inputs:roughness = 0.78
                float inputs:opacity = 1.0
                color3f inputs:emissiveColor = (0, 0, 0)
                token outputs:surface
            }
        }
    }

    variantSet "LOD" = {
        "LOD0" {
            def Mesh "Render"
            {
                uniform token subdivisionScheme = "none"
                uniform token orientation = "rightHanded"
                uniform token family:materialBind:familyType = "partition"
                float3[] extent = [(-200, -10, 0), (200, 10, 300)]
                point3f[] points = [ ... ]
                int[] faceVertexCounts = [3, 3, ...]
                int[] faceVertexIndices = [ ... ]
                normal3f[] normals = [ ... ] (interpolation = "faceVarying")
                texCoord2f[] primvars:st = [ ... ] (interpolation = "faceVarying")
                texCoord2f[] primvars:st1 = [ ... ] (interpolation = "faceVarying")

                def GeomSubset "M_Brick_Faces"
                {
                    uniform token elementType = "face"
                    uniform token familyName = "materialBind"
                    int[] indices = [0, 1, ...]
                    rel material:binding = </SM_Wall_A_01/Materials/M_Brick>
                }
            }
        }
        "LOD1" {
            def Mesh "Render" { ... }
        }
    }

    def Mesh "Collision_00" (
        prepend apiSchemas = ["PhysicsCollisionAPI", "PhysicsMeshCollisionAPI"]
    )
    {
        uniform token purpose = "guide"
        uniform token subdivisionScheme = "none"
        uniform token physics:approximation = "none"
        bool physics:collisionEnabled = 1
        float3[] extent = [(-200, -10, 0), (200, 10, 300)]
        point3f[] points = [ ... ]
        int[] faceVertexCounts = [3, 3, ...]
        int[] faceVertexIndices = [ ... ]
    }

    def Xform "SOCKET_SM_Wall_A_01_SnapR"
    {
        double3 xformOp:translate = (200, 0, 0)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}

6. Offline Preflight Verifier (verify.rs) & Kit Manifest

forma-ue verify <asset.glb|asset.usda> [--profile classic|nanite|mobile] [--strict] [--json] runs deterministic offline QA checks and returns exit code 0 on pass or non-zero on hard errors:

Category Check Gate
Container / Syntax Valid GLB header/chunk alignment/JSON/accessor bounds OR valid .usda header (#usda 1.0, upAxis, metersPerUnit, balanced braces, in-bounds indices, subdivisionScheme = "none"). Error
Geometry Finite coordinates, zero degenerate/zero-area triangles, consistent outward winding, manifoldness report (NM, B). Error
Scale & Transforms Identity root scale (1,1,1) (no negative/zero/unapplied scale); warns on suspicious physical extent (< 1 cm or > 100 m). Error / Warn
UV0 & Tangents TEXCOORD_0 / primvars:st present, zero NaN/degenerate UV tris; .glb TANGENT unit-length XYZ (` len - 1
Lightmap UV1 Required on classic/mobile: TEXCOORD_1 / primvars:st1 present, all UVs in [0, 1]², zero overlapping triangles. Error
Collision Present unless --no-collision; .glb UBX_/UCX_ prefix matches target mesh name; .usda has PhysicsCollisionAPI + PhysicsMeshCollisionAPI; hulls closed, outward-wound, convex, and within (max_hulls, max_hull_verts). Error
Nanite Policy On nanite: flags translucent materials (opacity < 1.0). Error
Studio Budgets Material-slot count (warn > 4, configurable --max-materials), triangle budget, modular grid-snap check (--grid-cm 10|50|100), naming prefix check. Warn (--strict Error)

Optional --manifest <path.json> emits a versioned forma-ue.kit.v1 JSON sidecar listing profile, units: "cm", grid_cm, recommended_interchange flags, per-asset dimensions/pivots/LODs/material slots/collision/sockets, and sha256 hashes for UE Interchange Python automation.


7. CLI & Opt-In MCP Surface (main.rs, mcp.rs)

# Default profile (classic): LODs, lightmap UV1, MikkTSpace tangents, auto collision
forma-ue export model.forma --pivot bottom-center --uv0 box --uv-period-cm 100 \
  --collision auto --out SM_Crate_01.glb --usd SM_Crate_01.usda --manifest kit.json

# Modular kit split (Nanite profile, corner pivots snapped to 100 cm grid)
forma-ue export kit.forma --split-parts --profile nanite --pivot corner --grid-cm 100 \
  --out-dir ./ue_export --manifest ./ue_export/kit.json

# Offline preflight QA
forma-ue verify SM_Crate_01.glb --profile classic --json
forma-ue verify SM_Crate_01.usda --profile classic --strict --json

# Opt-in stdio MCP server (<= 350 o200k tokens; 0 tokens on core forma-mcp)
forma-ue --mcp

Opt-in MCP tools (forma-ue --mcp):

  1. ue_export — Compile .forma source/file → .glb and/or .usda + optional kit manifest.
  2. ue_verify — Offline UE5 preflight QA returning compact pass/fail diagnostics + metrics.
  3. ue_profiles — List profile presets (classic, nanite, mobile), defaults, and recommended UE Interchange pipeline flags.

8. Phased Implementation Plan

  1. PR 1 — Tier 1 MVP (crates/forma-ue, standalone CLI + library, 0 core edits):
    • Crate scaffold in workspace.members only (excluded from default-members, 0 new external crates).
    • units.rs, pivot.rs, naming.rs, merge.rs, uv_box.rs, uv_lightmap.rs, tangent.rs, collision.rs (UBX_ AABB + f64 3D QuickHull UCX_), lod.rs, export_glb.rs, export_usda.rs, verify.rs, manifest.rs, and unit/integration tests.
  2. PR 2 — Tier 2 Advanced & Opt-In MCP:
    • Concave V-HACD voxel convex decomposition (--collision decomp).
    • Procedural linear COLOR_0 / USD primvar vertex masks (color_mask.rs).
    • Modular kit split mode (--split-parts), SOCKET_ helpers, and grid-snap checks.
    • Opt-in forma-ue --mcp server with automated <= 350 o200k token-budget test.
  3. PR 3 (Optional Follow-Up) — CLI Dispatch & Validation Harness:
    • Optional forma ue ... subcommand dispatch in crates/forma-cli (or --features ue) once forma-ue is proven.
    • Optional CI fixture validation with Khronos glTF-Validator / OpenUSD usdchecker and sample UE5 Interchange Python import script.

9. Verification References