# meshforge > meshforge is a pure-Rust, CPU-only 3D modelling and rigging kernel (MIT OR Apache-2.0) for native, wasm and AI agents. Agents drive it with JSON commands (create primitives, select, extrude, inset, bevel, booleans, modifiers, UV unwrap, decimate, auto-weights, glTF export) through the `meshforge` CLI or the Rust `meshforge::command::Session`; every reply is JSON with counts, bounding box and warnings, or an error with a hint saying how to fix it. Everything below, plus the full CLI guide and command reference, as one plain-text file: [llms-full.txt](llms-full.txt). ## Install - Rust toolchain: `cargo install meshforge-cli` (installs the `meshforge` binary; pure Rust, no C toolchain) - Homebrew (macOS, Linux): `brew tap partiigames/tap && brew trust partiigames/tap && brew install meshforge` - Prebuilt archives (Linux x86_64/aarch64, macOS x86_64/arm64, Windows x86_64) with SHA256SUMS: https://github.com/PartiiGames/meshforge/releases/latest - Rust library: `cargo add meshforge` - npm / npx: not published yet (coming soon) ## Command protocol - Send one JSON object with an `"op"` field, or a JSON array of them (applied in order): `meshforge apply --session NAME.mfs -e ''`. The session file keeps the state between calls; `-o file.glb` writes the asset. - Reply: one JSON object on stdout. Success `{"ok":true,...}`; failure `{"ok":false,"error":{"code","message","hint",...}}` and exit code 1. A failed command changes nothing. Usage errors exit 2. - CLI replies are brief by default (news, `applied`, and an `objects` summary: `tris`, `shells`, `boundary_loops`, `bbox`); `--full` gives every field. - Unknown fields are errors: never guess field names. `meshforge ops --text` lists every op; `meshforge ops OP1 OP2` prints each op's fields, types and defaults in one line; `meshforge ops --all` is the whole API as JSON; `--format json-schema|gbnf` gives grammars. - Select geometry by meaning, not ids: `{"op":"select","object":"crate","select":{"faces_facing":[0,1,0]}}`, `{"tag":"top"}`, `in_box`, edge selectors such as `{"sharper_than_deg":30}`. Edit commands without ids act on the selection. - Conventions: Y up, front faces +Z, metres, counter-clockwise winding. Ids are stable unless a reply says `"renumbered":true` (boolean, subdivide, decimate). - Look before you ship: `meshforge preview NAME.mfs -o view.png` renders four views; back faces show magenta hatching. With `--json`, the reply counts them in `back_faces_visible` (0 for a closed, correctly wound prop); the default text reply does not. - Ship: `export_glb` or `-o file.glb`, then `meshforge validate file.glb` (exit 1 on errors). - Budgets: every command predicts its face count first and fails with `budget_exceeded` instead of running away (`set_limits`). - There is no MCP server yet; agents call the CLI. Example: ```sh meshforge apply --session crate.mfs -e '[{"op":"create_primitive","kind":"cube","name":"crate"},{"op":"bevel","object":"crate","select":{"sharper_than_deg":30},"width":0.05,"segments":3}]' meshforge apply --session crate.mfs -o crate.glb meshforge validate crate.glb --text ``` ## Reference The reference documents main, which is ahead of the 0.4.0 release; features marked "since 0.5.0" are not in 0.4.0 yet. - [Command reference](commands.html): every JSON command, selectors, result fields, error codes (source: https://github.com/PartiiGames/meshforge/blob/main/docs/command-api.md) - [CLI guide](cli.html): apply, session files, preview, info, validate, ops, weights, transfer; a worked chair (source: https://github.com/PartiiGames/meshforge/blob/main/docs/cli.md) - [Quick start](quickstart.html): a real 30-second CLI session with its output - AGENTS.md, the agent loop and a complete example: https://github.com/PartiiGames/meshforge/blob/main/AGENTS.md - SKILL.md, the same as a drop-in agent skill: https://github.com/PartiiGames/meshforge/blob/main/SKILL.md - Browser and node runtime (wasm, three.js, workers): https://github.com/PartiiGames/meshforge/blob/main/docs/partii-runtime.md ## Optional - Benchmarks against headless Blender (speed, memory, quality per op): https://github.com/PartiiGames/meshforge/blob/main/bench-results/blender-568f752/board.md - Repository: https://github.com/PartiiGames/meshforge - Changelog: https://github.com/PartiiGames/meshforge/blob/main/CHANGELOG.md - Licence: MIT OR Apache-2.0; third-party notices: https://github.com/PartiiGames/meshforge/blob/main/NOTICE - meshforge is built with AI coding agents. ================================================================ FILE: AGENTS.md SOURCE: https://github.com/PartiiGames/meshforge/blob/main/AGENTS.md ================================================================ # Driving meshforge as an agent This file is for AI agents (and the people writing them) that build or edit 3D meshes with meshforge. It covers the loop, budgets, errors and a complete example. Contributors to this repository: see "Working on meshforge" at the end. ## Pick an interface | you have | use | state between calls | |---|---|---| | a shell | the `meshforge` CLI (`cargo install meshforge-cli`) | a session file: `--session NAME.mfs` | | Rust | `meshforge::command::Session::apply_json` | the `Session` value | | JavaScript (browser or node) | `web/runtime` (the npm package is coming soon) (`meshforge.session().apply(...)`) | the session object | All three take the same JSON commands and give the same replies, so a batch that works in one works in the others. Reference: [docs/command-api.md](docs/command-api.md); CLI details: [docs/cli.md](docs/cli.md). ## The loop 1. **Know the commands.** "Common ops" below covers a typical prop with exact field names. For anything else, `meshforge ops OP1 OP2` prints one line of fields, types and defaults per op plus an example; `meshforge ops OP` the full detail; plain `meshforge ops` an index of every op. Use the field names exactly: unknown fields are errors, never silently ignored. 2. **Make or load an object.** `create_primitive` (cube, grid, uv_sphere, cylinder, cone, torus, capsule), or `--in file.glb` / `import_gltf`. 3. **Select, then edit.** Select by meaning, not by id: `{"faces_facing":[0,1,0]}` (the upward faces), `in_box`, `grow`, `invert`, or `{"all":true}`. Edit commands without explicit ids act on the selection, and commands that create faces select them (extrude selects the caps, so the next `transform` moves them). 4. **Read every reply.** Check `ok`, then `warnings` (a no-op, an empty selection, a clamped width: "this did less than you think"). CLI replies are brief by default: a line only for commands with news (a payload such as `query`, a `select` count, `warnings`; a single command keeps its line), `applied` (how many commands ran) and a final `objects` summary (`tris`, `shells`, `boundary_loops`, `bbox`) of every object changed; floats to 5 significant digits. Pass `--full` (or `"reply":"full"`) when you need every line, counts and ids. 5. **Look.** `meshforge preview file.mfs -o shot.png` renders front, side, top and iso views into one PNG. This default `debug` style is for checking: back faces are hatched magenta; the reply's `back_faces_visible` should be 0 for a closed, correctly wound prop, and a depth cue darkens far surfaces and outlines depth jumps. `--highlight-selection` shows what is selected. For a picture to show someone, `--style beauty` draws back faces in their material colour, with soft key + fill + sky lighting, anti-aliasing and no depth cue (the reply still counts back faces). 6. **Undo instead of patching.** `{"op":"undo"}` (or `"steps":N`) returns to the last good state, selection included. 7. **Ship.** `export_glb` (or `-o file.glb` on the CLI), then `meshforge validate file.glb` (exit 1 on errors, each with a fix). Conventions: Y is up, the front of a model faces +Z, units are metres, faces wind counter-clockwise seen from the front. Ids are stable: deleting never renumbers; a reply with `"renumbered":true` (boolean, subdivide, decimate) voids old ids, so select again. ## Common ops `?` optional, `=` default. Everything else: `meshforge ops OP --sig`. | op | fields | |---|---| | `create_primitive` | `kind`, `name?`, `center?`=[0,0,0] (bbox centre). `cube`: `size?`=1, or [x,y,z] for a box. `cylinder`, `cone` (along Y): `radius?`=0.5, `height?`=1, `segments?`=16, `capped?`=true. `uv_sphere`: `radius?`=0.5, `segments?`=16, `rings?`=8. `torus`: `radius?`=0.5, `minor_radius?`=0.15, `segments?`=24, `rings?`=12. `capsule`: `radius?`=0.25, `height?`=1 tip to tip. `grid`: `nx`, `ny`, `size_x`, `size_y` (1 each; XY plane). Another kind's field is an error. | | `transform` | `object`, `target?`=`selection`\|`object`, `translate?`, `rotate_deg?` [x,y,z], `scale?` n or [x,y,z], `pivot?`=`centroid`\|`bbox_center`\|`origin`\|[x,y,z]. Scale, rotate, then translate. With nothing selected (a new object) the whole object moves, with a warning. | | `boolean` | `object`, `with`, `mode` `union`\|`difference`\|`intersection`. Both closed; `with` stays (delete a cutter). | | `delete_object` | `object` | | `duplicate` | `object`, `name?`, `translate?`, `rotate_deg?`, `scale?` | | `set_material` | `object`, `name?`, `color?` linear [r,g,b(,a)], `metallic?`=0, `roughness?`=0.8, `target?`=`object`\|`selection` | | `array` | `object`, `count`, `offset?`=[1,0,0]; radial: `axis` (`"y"`), `angle_deg?`=360, `center?`=[0,0,0], `rotate_copies?`=true. Copies stay in the object. | | `revolve` | `profile` [[r,y],...], `name?`, `segments?`=24, `axis?`=`y`, `caps?`=true, `center?`. Axis to axis, or capped: closed. | | `select` | `object`, `select`: one of `faces_facing` [x,y,z] (+`within_deg`=10), `in_box` {min,max}, `tag` (`top`, `side`, `cap`, `extruded`, ...), `all` true, `faces` [ids], `grow` n, `invert` true; `mode?`=`replace`\|`add`\|`subtract`\|`intersect` | | `extrude`, `inset`, `bevel` | on the selection: `distance`; `thickness`, `depth?`=0; `width`, `segments?`=1, `select?` {"sharper_than_deg":30} | | `query` | `object?`, `include?` [`counts`, `bbox`, `selection`, `faces`, `tags`, `volume` (adds volume, area, closed), `closed`, `validate`, ...] | | `export_glb` | `objects?` (all), `path?`, `normals?`=`auto`\|`flat`\|`smooth`\|`keep` | ```json [{"op":"create_primitive","kind":"cube","name":"top","size":[1.2,0.05,0.8],"center":[0,0.75,0]}, {"op":"create_primitive","kind":"cylinder","name":"leg","radius":0.03,"height":0.75,"center":[0.5,0.375,0.3]}, {"op":"array","object":"leg","count":2,"offset":[-1,0,0],"count2":2,"offset2":[0,0,-0.6]}, {"op":"set_material","object":"top","name":"wood","color":[0.55,0.36,0.18]}, {"op":"set_material","object":"leg","name":"wood"}] ``` ## Budgets Every command predicts the face count it will produce *before* allocating. Over the limit it fails with `budget_exceeded` and changes nothing: ```json {"ok":false,"error":{"code":"budget_exceeded","op":"create_primitive","estimated_faces":16777216,"limit":200000,"limit_kind":"object","field":"segments","hint":"lower segments/rings"}} ``` Defaults: 200,000 faces per object, 1,000,000 for the whole session. Change them with `{"op":"set_limits","max_faces":N,"max_total_faces":M}` or the CLI's `--max-faces` / `--max-total-faces`. For phone games stay near 5,000 faces per object. Lower the `field` the error names rather than raising the limit. ## Errors A failed command changes nothing. The reply is `{"ok":false,"error":{"code","message","hint",...}}`; in a batch, `results` holds what succeeded and `failed_index` the command that failed (earlier commands stay applied). Act on `hint`. The codes you will meet most: | code | what to do | |---|---| | `parse` | `field` is the bad key's full path and `expected` its type; fix the JSON (check `meshforge ops`) | | `unknown_object` | `available` lists the names | | `face_not_found`, `vertex_not_found`, `edge_not_found` | query or select again; the message gives the valid range | | `empty_selection` | select something first, or pass ids | | `invalid_argument` | `field`, `reason` and `valid_range` say what is accepted | | `budget_exceeded` | lower `field` (see above) | | `op_failed` | the kernel refused the edit; `reason` says why (e.g. a boolean operand that is open: `merge_by_distance` or `solidify` first) | CLI exit codes: 0 ok, 1 a command or file failed (JSON error on stdout), 2 usage error. Logs go to stderr; stdout is always one JSON object for `apply`, `info`, `validate` and `ops`. ## A complete example (shell) ```sh meshforge apply --session crate.mfs -e '[ {"op":"create_primitive","kind":"cube","name":"crate"}, {"op":"bevel","object":"crate","select":{"sharper_than_deg":30},"width":0.04,"segments":2}, {"op":"set_material","object":"crate","name":"wood","color":[0.55,0.38,0.2]} ]' meshforge apply --session crate.mfs -e '{"op":"select","object":"crate","select":{"faces_facing":[0,1,0]}}' meshforge apply --session crate.mfs -e '{"op":"inset","object":"crate","thickness":0.1}' meshforge apply --session crate.mfs -e '{"op":"extrude","object":"crate","distance":-0.05}' meshforge preview crate.mfs -o crate.png meshforge apply --session crate.mfs -o crate.glb meshforge validate crate.glb --text ``` More: the worked chair in [docs/cli.md](docs/cli.md), the props in [docs/img/hero.json](docs/img/hero.json), and the browser runtime guide [docs/partii-runtime.md](docs/partii-runtime.md) (sessions, three.js, workers, phone budgets). ## Rigging Skin weights are JSON commands: `create_skeleton`, `auto_weights`, `transfer_weights` and `pose` (see docs/command-api.md). They are also available from the CLI (`meshforge weights model.glb --skeleton-from rig.glb -o skinned.glb`, `meshforge transfer skinned.glb backpack.glb -o backpack_skinned.glb`), the library (`meshforge::weights::{auto_weights, transfer_weights}`) or the runtime (`meshforge.autoWeights`, `meshforge.transferWeights`). ## Working on meshforge - Rust workspace: `crates/meshforge` (library), `meshforge-cli`, `meshforge-wasm`; `meshforge-bench` and `meshforge-lab` are not published. - Before a change lands: `cargo test`, `cargo clippy --all-targets -- -D warnings`, `scripts/check-features.sh` (every feature set, native and wasm32). - Every new `Command` variant needs a budget arm in `crates/meshforge/src/command/budget.rs` (the compiler enforces it) and a section in `docs/command-api.md` (copied to `crates/meshforge-cli/command-api.md`; a test checks the two match). - Licences: MIT/Apache-2.0 compatible only, recorded in `NOTICE`. Blender is GPL: never copy, port or read its source; benchmark it only as an external program. - Test data: only synthetic and CC0 inputs are in the repository. ================================================================ FILE: SKILL.md SOURCE: https://github.com/PartiiGames/meshforge/blob/main/SKILL.md ================================================================ --- name: meshforge description: Build, edit, rig and preview 3D meshes (game props, glTF assets) with the meshforge CLI or library using JSON commands. Use when asked to model an object, modify a .glb/.gltf/.obj, boolean or bevel geometry, unwrap UVs, decimate for LODs, auto-weight a mesh to a skeleton, or render a quick preview image of a mesh. --- # meshforge JSON-command modelling kernel driven by a CLI session. More: AGENTS.md. ## Loop 1. `meshforge apply --session S.mfs -e '[,...]'`. A failed batch changes nothing: fix it from `error.hint`, resend. `{"op":"undo"}` undoes. 2. Replies list only news (payloads, select counts, `warnings`), `applied` and `objects`: `tris`, `shells`, `boundary_loops` (0 = closed), `bbox` per changed object. 3. Other ops: `meshforge ops OP1 OP2`; index: `meshforge ops`. Unknown fields are errors. 4. Look: `meshforge preview S.mfs -o v.png`. Magenta hatch = inside-out faces (`back_faces_visible` 0 when clean). `--style beauty`: a clean render; `--skeleton`: bones. Y up, front +Z, metres; props sit on y = 0. After `boolean`, `subdivide`, `decimate` ids change: select again. ## Common ops (`?` optional, `=` default) - `create_primitive` kind, name?, center?=[0,0,0]. `cube` size?=1 or [x,y,z]; `cylinder`/`cone` (along Y) radius?=0.5 height?=1 segments?=16 capped?=true; `uv_sphere` radius?=0.5; `torus` radius?=0.5 minor_radius?=0.15; `capsule` radius?=0.25 height?=1; `grid` nx?=1 ny?=1 size_x?=1 size_y?=1 (XY). `{"op":"create_primitive","kind":"cube","name":"top","size":[1.2,0.05,0.8],"center":[0,0.75,0]}` - `transform` object, target?=selection|object, translate?, rotate_deg? [x,y,z], scale? n or [x,y,z], pivot?=centroid|bbox_center|origin|[x,y,z]; nothing selected: the whole object. `{"op":"transform","object":"top","target":"object","rotate_deg":[0,30,0]}` - `boolean` object, with, mode union|difference|intersection; closed operands; `with` stays: delete it. - `delete_object` object. `duplicate` object, name?, translate?. - `set_material` object, name?, color? linear [r,g,b], target?=object|selection. - `array` object, count, offset?=[1,0,0]; radial: axis "y", angle_deg?=360, rotate_copies?=true. - `revolve` profile [[r,y],...], name?, segments?=24, axis?=y, caps?=true, center?. Axis to axis, or capped: closed. - `select` object, select: one of faces_facing [x,y,z], in_box {min,max}, tag ("top","side","cap"), all true, faces [ids], grow n, invert true; mode?=replace|add|subtract|intersect. `{"op":"select","object":"top","select":{"faces_facing":[0,1,0]}}` Then `extrude` object, distance; `inset` object, thickness, depth?; `bevel` object, width, segments?, select? {"sharper_than_deg":30} or `{"op":"bevel","object":"top","select":{"edges":"border","of":{"tag":"top"}},"width":0.02}` - `query` object or objects "*", include [counts,bbox,volume,closed, validate,selection,tags]. - `pipe` path [[x,y,z],...], radius, name?, inner_radius?, smooth? n. - `export_glb` path?, objects?. - Rig: `auto_weights` objects, skeleton? or joints [{name,parent,head,tail}]; `transfer_weights` object, from; `pose` object, rotations {"knee":[60,0,0]} or reset. - Fit: `shrinkwrap`/`snap_to_surface` object, target; `check_poke_through` object, against. - `place` object, on, at? [x,z], sink?, contact?=full|first; `align` object, to, axis, mode?/target_mode?. - Finish: `{"op":"check_contacts","require":{"floating":0}}` (ground: terrain). All objects export: delete cutters, helpers. ================================================================ FILE: docs/cli.md SOURCE: https://github.com/PartiiGames/meshforge/blob/main/docs/cli.md ================================================================ # meshforge CLI This page is for agents working in a shell (and the people writing them). The `meshforge` binary drives the same JSON command API as the Rust library and the wasm build (`docs/command-api.md`): a batch you write here runs unchanged in the browser. Install it with `cargo install meshforge-cli` (or build it from the repository with `cargo build --release -p meshforge-cli`; the binary is `target/release/meshforge`). It is pure Rust with no C dependencies. The npm package (coming soon) will run the same CLI as WebAssembly (`npx meshforge ...`, single-threaded, without the experimental subcommands). ## Quickstart ```sh meshforge ops --text # every op name; then: meshforge ops OP [OP...] [--sig] meshforge apply -e '{"op":"create_primitive","kind":"cube","name":"crate"}' -o crate.glb meshforge preview crate.glb -o crate.png # look at it meshforge info crate.glb # counts, bbox, skins, attributes (JSON; --text for humans) ``` To make many small edits, keep the state in a session file: ```sh meshforge apply --session crate.mfs -e '{"op":"create_primitive","kind":"cube","name":"crate"}' meshforge apply --session crate.mfs -e '{"op":"select","object":"crate","select":{"faces_facing":[0,1,0]}}' meshforge apply --session crate.mfs -e '{"op":"extrude","object":"crate","distance":0.1}' meshforge preview crate.mfs -o crate.png --wireframe meshforge apply --session crate.mfs -o crate.glb # write the asset when it looks right ``` ## Output and exit codes * `meshforge apply` always prints **one JSON object on stdout**: the reply of `Session::apply_json`, unchanged, except that exported files are written to disk and reported as `glb_path` (plus `glb_bytes`) instead of a base64 blob. Logs (one line per command, warnings) go to **stderr**. * `info`, `validate` and `ops` also print one JSON object by default; pass `--text` for a human-readable version. (`--json` is still accepted.) * `preview`, `weights` and `transfer` print text by default, or one JSON object with `--json`. * Every output path (`-o`, `export_glb` `"path"`, `--preview`, `--session`) gets its missing directories created; stderr says `created directory ...`. * On failure the JSON is `{"ok":false,"error":{"code","message","hint",...}}`, with the API's own error fields (`field`, `reason`, `available`, `face`, `faces`, ...) and, for a batch, `results` (what succeeded) and `failed_index`. stderr shows the same message and a `fix:` line. | exit | meaning | |---|---| | 0 | ok | | 1 | a command failed, or a file could not be read, decoded or written (`code` says which: `parse`, `face_not_found`, `io`, ...). The JSON error is on stdout. | | 2 | usage error: unknown flag, bad `--views`, wrong output extension, ... | Every error says how to fix it. Examples: ```text error: face 99 does not exist; mesh 'box' has 6 faces (ids 0..5) fix: Run 'meshforge apply - --in box.glb' with {"op":"query","object":"box","include":["faces"]} on stdin to list faces, or select by direction instead of ids: {"op":"select","object":"box","select":{"faces_facing":[0,1,0]}} error: invalid command: unknown variant `extrud`, expected one of `create_primitive`, ... fix: did you mean 'extrude'? Valid ops: create_primitive, delete_object, extrude, ... error: invalid command: unknown field `distanse`, expected one of `object`, `faces`, `distance` fix: did you mean 'distance'? Valid fields here: object, faces, distance. ... error: malformed JSON in at line 3, column 11: expected value at line 3 column 11 {"op": 'query'} ^ fix: JSON strings need double quotes ("), not single quotes ``` ## Commands ### apply (alias: run) ``` meshforge apply [FILE|-] [-e JSON]... [--in [NAME=]PATH]... [-o OUT.glb|OUT.obj|OUT.stl] [--session FILE.mfs] [--dry-run] [--object NAME] [--max-faces N] [--max-total-faces N] [--preview OUT.png [--wireframe] [--highlight-selection] [--style debug|beauty]] [--keep-base64] [--brief | --full] ``` * Commands come from `FILE`, `-` (stdin) and/or `-e ''` (repeatable, applied after FILE). Each is one command object or an array; together they run as one batch, which stops at the first failure. **A failed batch saves nothing**: the `--session` file is left as it was (the reply has `"session_saved":false`) and `-o` is not written, so fix the failing command and run the batch again. (`results` still shows what the commands before `failed_index` returned.) * `--in chair.glb` loads a file first, as object `chair` (the file stem); `--in seat=chair.glb` names it `seat`. A glTF with several meshes keeps its node names. `.glb`, `.gltf` (with its `.bin`), `.obj` and `.stl` (binary or ASCII, through `import_stl` with its defaults: corners welded within 1e-5, axes kept) are read. * A command that needs `"object"` and leaves it out gets `--object NAME`, or the session's only object if there is exactly one. (Asked from the API's deserializer, so this works for new ops too.) * `-o out.glb` writes every object after the batch (`export_glb` with its defaults: `normals` `auto`, hard edges above 30 degrees) and adds `glb_path`, `glb_bytes`, `triangles`, `vertices` (glTF vertices, split at hard edges and UV seams) and `bbox` to the reply. `-o out.obj` writes OBJ, which keeps quads (no skins or materials); `-o out.stl` writes binary STL (`export_stl` with its defaults: evaluated stacks, axes kept). Both report `out_path`, `out_bytes`, `triangles`, `vertices` and `bbox`. The GLB `bbox` is the evaluated modifier stacks (what the file holds); OBJ holds each object's own mesh (the cage, modifiers not written; stderr notes it), so its `bbox` is the cages'. * `{"op":"export_glb","path":"out/x.glb"}` writes that file; the result has `glb_path`, `glb_bytes` and the export's `stats`. An `export_glb` without `path` has its base64 elided unless `--keep-base64`. `export_stl` with a `path` works the same way, reporting `stl_path` and `stl_bytes`. * `{"op":"load_font","name":"sign","path":"fonts/MyFont.ttf"}` reads the font file and sends its bytes as `data`, so `create_text` can use `"font":"sign"` (a session file logs the bytes, so replays need no file). * `--dry-run` applies everything in memory and adds `"dry_run":{"objects":[{"name","counts","bbox"}]}` (plus `cage_bbox`, and `counts.evaluated` with the evaluated stack's counts, for objects with modifiers, see "Notes"); nothing is written (no `-o`, no export paths, no session save). * `--max-faces N` sets the session's per-object face budget and `--max-total-faces N` the budget for all objects together; both are stored in the session file. The check itself is done by the core before each op allocates (`"code":"budget_exceeded"`, imports with `--in` included); see "Notes". * **Every reply is brief by default** (batches since 0.3.0, a single command since the next release; pass `--full` for the old shape): in a batch, a short line only for commands with news (warnings, a payload such as `query`, a `select` count), with its `index`, and `"applied"` counting the commands that ran; a single command keeps its one short line (`result`); then a final `"objects"` summary of every object changed (`tris`, `shells`, `boundary_loops`, `bbox`; unchanged objects are left out), floats rounded (5 significant digits, 7 in a `query`, boxes outwards), see "Brief replies" in `docs/command-api.md`. Payloads stay: `query` (lists capped at 32 entries, with a marker), `export_glb`'s `glb_path`, `undo`'s `reverted`. A brief reply leaves out the undo depth and the `--session` path (errors too). `--full` (or `"reply":"full"` on one command) gives every field: counts, selection, stats, ids, `history`, and the `session` path. `--brief` is the default and kept for compatibility. `--full` also overrides a session file saved with `default_reply` brief. `export_glb` always gets its bytes, so the CLI can write `glb_path`. A failed batch replies only `failed_index`, a `note` and the `error` (`code`, `message`, `field`, `hint`): the CLI saves nothing on failure (the session file and `-o` are untouched), so what ran before it is not listed (`--full` lists it). * `--preview OUT.png` also renders the contact sheet with `preview`'s defaults: material colours, export shading, depth cue, no wireframe and no selection highlight. Add `--wireframe` and/or `--highlight-selection` to show them, `--no-materials` for a shape-only grey pass. The reply says what was drawn and how many back faces are visible (see `preview`): `"preview":{"path":"p.png","width":1024,"height":1024,"shading":"auto","angle_deg":30,"highlight":false,"wireframe":false,"depth_cue":true,"materials":true,"back_faces_visible":10,"back_face_pixels":202306,"back_faces_by_view":[{"view":"front","count":2,"pixels":70560},{"view":"side","count":2,"pixels":70560},{"view":"top","count":0,"pixels":0},{"view":"iso","count":6,"pixels":61186}]}` (that is a red box whose top was extruded inwards, `distance` -0.4; a clean box gives 0 in every view). Visible back faces also print a `warning:` on stderr. ```sh meshforge apply crate.json -o out/crate.glb meshforge apply crate.json --dry-run cat steps.json | meshforge apply - --session crate.mfs meshforge apply --session crate.mfs -e '{"op":"extrude","object":"crate","distance":0.1}' meshforge apply --in model.obj -o model.glb # convert, no commands meshforge apply --in part.stl -o part.glb # STL in (welded), glTF out ``` Reply (abridged): ```json {"ok":true,"results":[],"applied":2,"objects":[{"name":"crate","tris":12,"shells":1,"boundary_loops":0,"bbox":[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]]}],"glb_path":"out/crate.glb","glb_bytes":1716,"triangles":12,"vertices":24,"bbox":{"min":[-0.5,-0.5,-0.5],"max":[0.5,0.5,0.5],"center":[0,0,0],"size":[1,1,1]}} ``` ### Session files (`.mfs`) `--session crate.mfs` creates the file if it is missing and updates it after every successful batch, atomically (a temp file renamed over it). A failed batch leaves it untouched, and a missing session is only created once something was logged: a mistyped `--session typo.mfs` with a failing or read-only command creates no file (stderr says so). A GLB round trip triangulates (glTF stores triangles), so the session is meshforge's own format: a JSON log of every state-changing command (file imports embedded), replayed through the command API on load. The kernel is deterministic, so replay restores the exact state: quads, object names, face and vertex ids, selections and the undo/redo history. `undo` works across calls. `query` and `export_glb` are not logged. To check a whole build in one call, `{"op":"query","objects":"*","include":["volume","closed"]}` returns a row per object (see "query" in `docs/command-api.md`). Loading replays the whole log; that is fast for props (milliseconds for a few hundred commands). Snapshots every N steps (to skip the replay) are planned once the core can serialize a `Session` (objects, selections and the undo stack); the format's `version` field will mark the change. `meshforge info crate.mfs` reports the session's objects (counts, bbox, selection), limits (`max_faces`, `max_total_faces`, `total_faces`) and history. An object with modifiers also gets `modifiers`: the `stack`, per stage counts (`stages`) and the `evaluated` counts (vertices, edges, faces, triangles) next to the cage counts; `totals` adds `evaluated_faces` and `evaluated_triangles`. `--text` prints `modifiers: array -> evaluated (exported) 40 verts, 30 faces (60 tris); the counts above are the cage`. ```json {"format":"meshforge-session","version":1,"meshforge":"0.1.0","max_faces":null,"max_total_faces":null,"log":[{"op":"create_primitive","kind":"cube","name":"crate"}, ...]} ``` ### preview (alias: render-preview) ``` meshforge preview -o OUT.png [--views front,side,top,iso] [--size 512] [--wireframe] [--shading auto|flat|smooth|keep [--angle-deg N]] [--highlight-selection] [--cage] [--no-depth-cue] [--no-materials] [--uv [LAYER]] [--style debug|beauty] [--per-object] [--object NAME]... [--no-labels] [--commands JSON] [--pose JSON] [--skeleton] [--weights JOINT] ``` **Two styles.** `--style debug` (the default) is for checking a model, and is what agents should look at while building: back faces hatched, a depth cue, view-relative lighting; everything below describes it. `--style beauty` is for showing a finished model (a review sheet, a judge, a thumbnail): no hatch (back faces are drawn in their material colour, lit from the side the camera sees), a key light from the upper left, a fill from the camera and a sky/ground hemisphere ambient (a face turned towards the camera never reads black), material base colours, 2×2 supersampling, no depth cue. Its JSON reply has the same fields, `"style":"beauty"` and `"depth_cue":false`; `apply --preview OUT.png --style beauty` renders the same way. Back faces are still counted (`back_faces_visible`, ...) the same way, only not drawn. Use the debug style to find inside-out faces; a beauty sheet hides them. **Transparency:** the beauty style blends faces whose material alpha is below 1 (glass at 0.3) over what is behind them, back to front after every opaque face, so a candle shows through a lantern's panes; they hide nothing, so back faces behind them still count. The see-through faces' own back faces are not counted in beauty (flipped glass would read as normal glass there); the debug style draws them opaque, so flipped or open glass is hatched and counted like any other face. A CPU software renderer: orthographic views framed on the geometry, a rim light, labels, a world-axis gizmo (X red, Y green, Z blue), tiled into one PNG (2×2 for four views). Views: `front` (camera on +Z), `back`, `side`/`right` (+X), `left`, `iso`/`three-quarter`, `top` (+Y), `bottom`. Faces are drawn in their **material colour** (`set_material` base colour, times the lighting); faces without a material stay grey. A **depth cue** keeps stacked parts apart in the flat views (top, front, ...): faces farther from the camera fade toward the background, and a dark outline is drawn where the depth jumps (a lid seen from above on a larger crate); a surface that is merely steep (a roof slope or a seat seen at a grazing angle) is continuous, so it is not outlined. `--no-depth-cue` turns it off. **Back faces are hatched magenta and black**, on any material: the diagonal stripes cannot come from a material (materials are flat colours), so an inside-out part reads even when it is painted red. They mean flipped normals (an inward extrusion's walls, a mirrored part), or open geometry seen from inside. A back face lying exactly on a front face wins the tie, so it shows as clean stripes, not flicker; on a silhouette edge (where a back face meets a front face of the same surface, and the two tie exactly) the front face wins, so a closed mesh shows no specks along its outline or where parts touch. The reply counts them: `"back_faces_visible"` is the number of back-facing triangles with real visible area after the depth test, summed over the views (a triangle seen in two views counts twice); `"back_face_pixels"` is those triangles' visible pixels; `"back_faces_by_view"` gives `[{"view","count","pixels"}]` per tile (with `"object"` under `--per-object`). Real area: the triangle owns at least 4 interior pixels at the default 512 px tile (scaled with the tile's area, at least 1), an interior pixel being one whose 8 neighbours are back-face pixels too. That leaves out the specks a closed mesh shows along its silhouettes (a nearly edge-on triangle behind the rim winning a pixel or a 1-2 px sliver), which the hatch may still draw. A closed, consistently wound prop (box, sphere, torus, a kart of boxes and cylinders, a solidified bowl: its inner wall faces the camera) has 0; an inward extrusion's walls or an open bowl without thickness seen from above (the inside of its outward skin) count; the text output and `apply --preview`'s stderr warning add "N visible back faces (P px)" only then. `--no-materials` draws every face grey (shape only). `--highlight-selection` colours selected faces orange (selected vertices yellow); with a `.mfs` the session's selection is used, or set one with `--commands`. `--per-object` draws one row per object. Output is deterministic (same input, same PNG bytes). About 25 ms per 512×512 view for 100k triangles (release build). **Shading matches the export.** By default the sheet shades with the normals a plain `export_glb` writes (`auto`: hard edges where faces meet at more than 30 degrees, smooth elsewhere), so a crate looks crisp and a sphere round, as in the game. `--shading flat` shows every facet, `smooth` and `keep` (normals stored by an unedited import) match the export options of the same name, and `--angle-deg N` changes the `auto` threshold. A model file (`.glb`/`.gltf`/`.obj`) whose objects all carry normals is drawn with **the file's own normals** (`keep`), so an asset exported with `"normals":"flat"` previews faceted, as the game shows it; pass `--shading auto` (or `flat`, `smooth`) to recompute them instead. If any stored normal is NaN or zero length, the file's normals are not used (the default is the export's `auto`, and `--shading keep` falls back to `auto` for that object). The JSON reply (`--json`) says what was used: `"shading":"auto","angle_deg":30` (or `"shading":"keep"`). **Modifiers are drawn evaluated**, as `export_glb` writes them (its `apply_modifiers` default): an object with an `array` modifier shows every copy. `--cage` draws the objects' own meshes instead (the cage that edit commands and selection ids refer to); selection highlighting only applies to the cage, so an object with modifiers shows its selection with `--cage`. The reply says `"modifiers":"evaluated"` or `"cage"`. **Rigs.** A posed object (the `pose` op) is drawn in its pose. `--pose '{"knee":[60,0,0]}'` poses every drawn skinned object for this preview only (joint name -> `[rx, ry, rz]` Euler degrees about X, then Y, then Z, in the joint's frame; the session is not saved), so an agent can check a rig bends without changing anything. `--skeleton` draws the joints (dots) and bones (lines) over the mesh, in the pose, seen through the surface; skeletons no drawn object is bound to (made with `create_skeleton`, before `auto_weights`) are drawn in bind pose, to check the joints sit inside the mesh. `--weights JOINT` colours skinned faces by that joint's weight: blue 0, cyan, green, yellow, red 1 (materials are ignored). All three work with every view and shading. The reply adds `"posed"` (the objects drawn in a pose), `"skeleton":true` and `"weights":"JOINT"` when used. ```sh meshforge preview crate.mfs -o crate.png meshforge preview tree.glb -o tree.png --views front,side,top,iso --wireframe --size 512 meshforge preview creature.mfs -o bend.png --pose '{"knee_l":[50,0,0]}' --skeleton meshforge preview creature.mfs -o weights.png --weights knee_l --views side meshforge preview crate.mfs -o sel.png --highlight-selection --views iso meshforge preview crate.mfs -o uv.png --uv --object crate ``` **UV layout.** `--uv` (layer `uv0`, or `--uv uv1`) draws the UV layout instead of 3D views, one tile per object: the unit square with a quarter grid, every face filled in its chart's colour, chart borders (seams) dark, inner edges faint, and faces with mirrored UVs red. UVs are drawn as stored (glTF convention: v down, so the image reads like the texture). The reply lists the charts per object: `"uv":"uv0","objects":[{"object":"crate","layer":"uv0","charts":4}]`. An object without the layer fails with `no_uv_layer` and a `uv_unwrap` hint. ### ops (alias: commands) Shows the commands of the API, generated from the core's schema (`meshforge::command::schema::ops_schema()`), which its tests check against the parser: every op, every field the parser accepts with its type, whether it is required, default, range and allowed values; the full `select` selector; every error code with its fields. Prose and extra examples come from `docs/command-api.md`. ```sh meshforge ops # index: every op name, grouped (about 0.9 KB; JSON {"ops":{group:[names]},"aliases":{...},"usage":...}) meshforge ops extrude # one op in full (JSON; "select" adds the selector schema, modifier ops the modifier types) meshforge ops transform boolean revolve # several ops: signatures, one line of fields, types and defaults per op, then an example meshforge ops transform boolean --long # several ops in full: {"commands":[...]}, in the order asked meshforge ops extrude --sig # one op as a signature meshforge ops --sig # every op as a signature (about 11 KB) meshforge ops --all # the whole API: {"commands":[...],"selector":{...},"modifier":{...},"error_codes":[...],"types":{...},...} (takes no op names) meshforge ops --text # any of the above as plain text (--all --text: the full list for humans) meshforge ops --format json-schema # JSON Schema (2020-12) of one command or a batch meshforge ops extrude --format json-schema # one op's schema meshforge ops --format gbnf # GBNF grammar (llama.cpp) for constrained decoding ``` A signature reads `op: field: type, field?: type = default, ...`: `?` marks an optional field, an enum lists its values in place of the type (`mode: union|difference|intersection`), and `select` / bevel-style ops add one line with the selector's keys. For an agent: the index once (or the common ops in SKILL.md), then `meshforge ops A B` for the ops it needs in one call (signatures; `--long` for full entries); `meshforge ops OP` when a field's meaning or range matters. Op aliases (`lathe`, `tube`) resolve to their op. `--format json-schema` and `--format gbnf` are generated (`meshforge::command::schema_export`) from the same tables as `--all`'s JSON, never written by hand; the core's tests check that every example in `docs/command-api.md` validates against both. They print the document itself (no `"ok"` key). The JSON Schema lists every key of every op (other keys are invalid), types, enums, defaults, numeric ranges, the modifier and selector objects, and the `reply` key every command takes. The grammar has the same keys and types but expects each object's keys in schema order (`op`, then the fields as `meshforge ops` lists them, then `reply`), as GBNF has no unordered sets; it does not check numeric ranges. Size (tokens estimated as bytes / 4): JSON Schema about 40.8 KB (about 10,200 tokens), GBNF about 19.2 KB (about 4,800 tokens), the default `ops_schema` JSON (`ops --all`, without the docs' prose) about 42.6 KB (about 10,700 tokens). The largest ops are `create_primitive`, `bevel` and `uv_unwrap` (about 2.3 to 2.6 KB of schema each); most are 300 to 1,000 bytes. One entry: ```json {"op":"extrude","summary":"Region-extrudes faces along their normals by distance (negative = inwards) and selects the extruded caps.","fields":[{"name":"object","type":"string","required":true,"doc":"Object name."},{"name":"faces","type":"int[]","required":false,"doc":"Face ids (non-empty). Default: the object's current face selection."},{"name":"distance","type":"number","required":true,"doc":"Distance along the normals; negative extrudes inwards."}],"example":{"op":"extrude","object":"box","faces":[3],"distance":0.2},"examples":[...]} ``` Types: `string`, `number`, `int`, `bool`, `number[3]`, `int[]`, `int[2]`, `string[]`, `int[2][]`, `modifier`, `modifier[]` (see `"modifier"`), `number | number[3]`, `string | number[3]`, `number[3|4]`, `object` (keys under `fields`), `base64`, `selector` (see `"selector"`). `range` is `{"min","max","min_exclusive"}`. ### info ```sh meshforge info chair.glb [--text] meshforge info crate.mfs [--text] # a session: its objects, selections and history ``` With `--text`: ```text chair.glb (glb, 4236 bytes) 1 object(s): 56 vertices, 162 edges, 108 faces, 108 triangles; 0 material(s) bbox min [-0.5000, -0.8750, -0.5000] max [0.5000, 0.9750, 0.5000] size [1.0000, 1.8500, 1.0000] 'chair': 56 verts, 162 edges, 108 faces (108 tris); 1 shell(s), closed attributes: corner[normal, uv0] skeletons: none morph targets: none ``` JSON fields (the default output): `objects`, `totals` (vertices, edges, faces, triangles), `bbox` (what export writes: with modifiers, the evaluated stacks), `cage_bbox` (only when some object has modifiers: the objects' own meshes), `materials`, `skins`, `skeletons` (name, bones), `joints`, `morph_targets` (meshforge does not import them), `animations`, `object_details[]` (per object: counts, `shells`, `boundary_loops`, `boundary_edges`, `closed`, `bbox` and `cage_bbox` (null without modifiers), `attributes`, `skinned`, `max_influences`, `import` repairs: non-manifold edges cut, vertices split, degenerate faces dropped; `selection`: domain and count). For a `.mfs`, also `session` (`logged_commands`, `max_faces`, `history`). ### validate ```sh meshforge validate prop.glb [--text] # also takes a .mfs ``` Imports the file and lists problems, each with `severity` (error, warning, info), `kind`, `message` and `fix`: non-manifold geometry cut on import, degenerate or zero-area faces, zero-length edges, isolated vertices, NaN positions, open meshes, faces of one connected surface passing through each other (`self_intersection`, an error: an unclamped bevel, a folded inset, an over-thick solidify; the fix names `clamp`, `boolean` and solidify `thickness`), separate parts of one object overlapping (`overlapping_parts`, a warning: normal for kitbashed game props, the file stays valid; boolean union them only if they must be one watertight surface), vertices of one surface touching without sharing an edge (`touching_vertices`, a warning: the surface pinches onto itself, typically a zero-thickness wall left by a boolean of parts that only touch along a face; fine for rendering, but tools that weld by distance count non-manifold edges there), broken connectivity (`invalid_topology`, a meshforge bug: report the file), suspicious scale, skin problems (no skeleton, joints out of range, unweighted vertices, weights not summing to 1), and morph targets/animations that a meshforge re-export would drop. Exit 1 if there is any error. With `--text`: ```text fin.obj: valid (0 error(s), 1 warning(s)) warning: 'fin' is non-manifold: 1 edges were shared by 3+ faces or had inconsistent winding (cut on import), 4 vertices split fix: in the source, remove duplicate/internal faces, make face winding (normals) consistent, ... info: 'fin' is open: 3 boundary loop(s) (holes or open edges) fix: fine for planes, cloth and cards; a solid prop should be closed (fill the holes in the source) ``` A box bevelled with `"width":0.8,"clamp":false`, exported and validated: ```text block.glb: INVALID (1 error(s), 0 warning(s)) error: 252 face pairs of one connected surface of 'block' pass through each other (e.g. faces [[12,15],[12,16],...]) fix: an unclamped bevel or a folded inset does this: redo it with clamp: true or a smaller width. Parts welded into one surface that overlap: boolean union them instead. A solidify thicker than the gaps folds the inner shell: use a smaller thickness. query {"include":["faces"],"faces":[ids]} shows where those faces are ``` A crate with a smaller lid box overlapping it, joined into one object (exit 0): ```text crate.glb: valid (0 error(s), 1 warning(s)) warning: 8 face pairs of separate parts of 'crate' overlap (e.g. faces [[6,14],[6,15],...]) fix: fine for games (overlapping kitbashed parts render correctly); boolean union them if they must be one watertight surface (3D printing, booleans, solidify) ``` ### weights ```sh meshforge weights robot.glb --skeleton-from rig.glb --out robot_skinned.glb [--skin N] [--json] ``` Automatic skin weights (bone heat) for every mesh of the first file, against the skeleton of a glTF skin in `--skeleton-from` (default: the same file). Prints the weights report (shells and how each was weighted, unattached vertices, fallback, timings, warnings) and the number of vertices dominated by each joint. Without `--out` nothing is written. ### transfer ```sh meshforge transfer robot_skinned.glb backpack.glb --out backpack_skinned.glb [--exclude-joints antenna_] [--json] ``` Copies skin weights from a skinned source onto every object of the destination (robust closest-point transfer with inpainting). The output is bound to the source's skeleton. `--exclude-joints` takes joint-name prefixes (repeatable or comma-separated). ## Worked example: a chair from a cube Every step below is a real command run against meshforge 0.1.0. No vertex or face ids are needed: the cube's faces are tagged (`top`, `bottom`, `front`, ...; see "Tags" in `docs/command-api.md`), and edges are named by rule. `chair.json`: ```json [ {"op":"create_primitive","kind":"cube","name":"chair"}, {"op":"transform","object":"chair","target":"object","scale":[1,0.15,1]}, {"op":"loop_cut","object":"chair","select":{"edges":"horizontal"},"cuts":2}, {"op":"select","object":"chair","select":{"tag":"bottom"}}, {"op":"select","object":"chair","select":{"in_box":{"min":[-0.17,-1,-1],"max":[0.17,1,1]}},"mode":"subtract"}, {"op":"select","object":"chair","select":{"in_box":{"min":[-1,-1,-0.17],"max":[1,1,0.17]}},"mode":"subtract"}, {"op":"extrude","object":"chair","distance":0.8}, {"op":"select","object":"chair","select":{"tag":"top"}}, {"op":"select","object":"chair","select":{"in_box":{"min":[-1,-1,-1],"max":[1,1,-0.17]}},"mode":"intersect"}, {"op":"extrude","object":"chair","distance":0.9} ] ``` ```sh # 1. A cube flattened into a seat (1 x 0.15 x 1); one loop_cut with # "edges":"horizontal" cuts both horizontal rings, so the seat is a 3x3 # grid; the four bottom corner cells are extruded down into legs, the # back row of the top up into a backrest. meshforge apply chair.json --session chair.mfs # 2. Look at it, then write the asset. meshforge preview chair.mfs -o chair.png --wireframe meshforge apply --session chair.mfs -o chair.glb meshforge validate chair.glb --text ``` stderr of step 1 (with `--full`; the default brief reply prints only the lines with news, without counts or ids): ```text [0] create_primitive 'chair'; created: chair; 8 verts, 12 edges, 6 faces; selection: 0 faces [] [1] transform 'chair'; moved 8 vertices; 8 verts, 12 edges, 6 faces; selection: 0 faces [] [2] loop_cut 'chair'; new faces: 24; new vertices: 24; 32 verts, 60 edges, 30 faces; selection: 0 faces [] [3] select 'chair'; 32 verts, 60 edges, 30 faces; selection: 9 faces [2,8,9,14,15,16,17,18,19] [4] select 'chair'; 32 verts, 60 edges, 30 faces; selection: 6 faces [2,8,14,15,18,19] [5] select 'chair'; 32 verts, 60 edges, 30 faces; selection: 4 faces [2,8,14,18] [6] extrude 'chair'; new tags: extrude_wall, extruded; new faces: 16; new vertices: 16; 48 verts, 92 edges, 46 faces; selection: 4 faces [2,8,14,18] [7] select 'chair'; 48 verts, 92 edges, 46 faces; selection: 9 faces [3,12,13,22,23,24,25,26,27] [8] select 'chair'; 48 verts, 92 edges, 46 faces; selection: 3 faces [3,12,13] [9] extrude 'chair'; new faces: 8; new vertices: 8; 56 verts, 108 edges, 54 faces; selection: 3 faces [3,12,13] ``` Before tags this took three calls: create and flatten the cube, `query` its faces to look up vertex ids, then two loop cuts named by vertex pairs (`"edge":[0,1]`, `"edge":[0,4]`) and the rest of the batch. The commands shrink from 892 to 778 bytes and the replies the agent reads from 5520 to 4172 bytes (full replies), in one call instead of three, for the same chair (the test `chair_example_with_tags_matches_the_id_version` checks it). If something goes wrong, `{"op":"undo"}` (or `{"op":"undo","steps":3}`) against the same session steps back. ## Experimental commands `face-corner-metrics`, `hair-cards`, `hair-metrics`, `hair-synth`, `hair-bench` and `hair-coverage` serve one character pipeline (heads and hair cards). They are hidden from `meshforge --help`, may change in any release, and are built only with the `experimental` cargo feature (on by default; `cargo install meshforge-cli --no-default-features` leaves them out). `meshforge --help` still documents each; see [face-corner-target.md](face-corner-target.md) and [hair-coverage.md](hair-coverage.md). ## Notes * **Face budget.** Every op predicts its output face count from its arguments *before* allocating, failing with `{"code":"budget_exceeded","estimated_faces":N,"limit":200000,"limit_kind":"object","field":"segments","hint":"lower segments/rings"}` (exit code 1, nothing changed). The default limit is 200000; `--max-faces N` (or `{"op":"set_limits","max_faces":N}`) changes it, and the session file stores it so later calls (and the replay) use the same limit. The session as a whole has `max_total_faces` (default 1000000; `--max-total-faces N`); going over it says `"limit_kind":"total"` (the per-object limit says `"limit_kind":"object"`). A file imported with `--in` that is too big fails the same way, with `fix:` naming the flag to raise. * **Error fields.** A malformed command names the bad key by its full path and the type it takes: `{"code":"parse","field":"noise.seed","expected":"int",...}`, and stderr says `fix: 'noise.seed' takes int. ...`. A number outside the field's bound says the bound: `{"op":"array","count":-3}` gives `"field":"count","expected":"int, count >= 1"`, and `set_modifier` `"set":{"count":-1}` gives `{"code":"invalid_argument","field":"set.count","reason":"must be a whole number with count >= 1, got -1","valid_range":"count >= 1"}`. An unknown modifier type lists the modifier types (`subdivide, mirror, bevel, ...`). * **Bounding boxes.** `bbox` everywhere (`info`, result `stats`, `query`, `--dry-run`, `-o` replies) is what export writes: for an object with a modifier stack, the evaluated mesh. Such objects also report `cage_bbox`, the box of their own mesh, which edits and selectors (`faces_in_box`, ...) act on. A radial fence (one 0.2 post at x=2, `array` count 8 around Y) reports `"bbox":{"min":[-2.1,-0.1,-2.1],"max":[2.1,0.1,2.1],...}` and `"cage_bbox":{"min":[1.9,-0.1,-0.1],"max":[2.1,0.1,0.1],...}`. Result `stats` counts follow the same rule: `tris`, `vertices`, `faces` are what export writes (the fence: 96 tris, 64 vertices, 48 faces) and `cage_tris`, `cage_vertices`, `cage_faces` the post itself (12, 8, 6). The result's `counts` and `query` `counts` stay the cage's (their ids are what edits take); `query` adds `counts.evaluated` for the stack. * **Skinning** subcommands (`weights`, `transfer`) call `meshforge::weights` directly; the same work is also available as JSON commands (`create_skeleton`, `auto_weights`, `transfer_weights`). * **Memory (native Linux builds).** The CLI keeps freed heap pages for reuse (glibc `mallopt`, the same policy as Blender's jemalloc), so repeated ops do not fault their arrays in again; a long session stays near its peak resident memory. Since 0.5.0: `MESHFORGE_MALLOC_RETAIN=0` keeps glibc's defaults; `MESHFORGE_REPORT_RSS=1` prints `rss_end_kib` and `rss_peak_kib` on stderr at exit. See bench-blender/README.md "Allocator". * Units are metres, Y is up, the front of a model faces +Z. ================================================================ FILE: docs/command-api.md SOURCE: https://github.com/PartiiGames/meshforge/blob/main/docs/command-api.md ================================================================ # meshforge command API This page is for agents (and the people writing them) that drive meshforge through JSON commands. The same contract works natively (`meshforge::command::Session::apply_json`) and in the browser (`meshforge-wasm`, `Session.apply_json`). ## How it works * A **session** holds named **objects** (polygon meshes) and **skeletons**. Each object has its own **selection** (a set of face ids or vertex ids). * Send one command as a JSON object with an `"op"` field, or several as a JSON array (applied in order; it stops at the first failure, and earlier commands stay applied). * Every reply is JSON: * success: `{"ok":true,"result":{...}}`, or for an array `{"ok":true,"results":[...]}`; * failure: `{"ok":false,"error":{"code":"...","message":"...", ...}}`. For an array, `results` holds the results that succeeded and `failed_index` names the command that failed. * **A failed command changes nothing.** Read `error.message`: it says what is wrong and what to do (for example `face 12 does not exist; mesh 'a' has 6 faces (ids 0..5)`). * Unknown fields are errors, so a misspelled argument never silently falls back to a default. ### Conventions * **Y is up.** The front of a face is the side its normal points to; faces are wound counter-clockwise seen from the front. Units are whatever your engine uses (glTF assumes metres). * **Ids are stable.** Face and vertex ids are slot numbers. Deleting never renumbers anything, and new elements always get fresh ids, so ids from an earlier result stay valid. A fresh primitive or import has ids `0..faces-1` and `0..vertices-1`. (If a result ever says `"renumbered":true`, old ids are void; query again.) * **You do not need ids.** Use `select` to name geometry by tag, direction, region or topology (`{"tag":"top"}` = the faces tagged top, `{"faces_facing":[0,1,0]}` = the upward-facing faces), then run edit commands without `faces` / `vertices`; they act on the current selection. Name edges with an edge selector instead of vertex pairs (`{"edges":"border","of":{"tag":"top"}}` = the top rim). See "Tags". * Commands that create faces select the new ones where it makes sense (extrude selects the extruded caps), so the next `transform` moves them. * **Undo** covers every command that changes geometry or objects. `select` and `query` are not recorded. Undo restores the selection that went with the geometry. * Stored normals are dropped when geometry changes. `export_glb` writes normals per its `normals` option (default `auto`: hard edges where faces meet at more than 30 degrees, so a crate stays crisp and a sphere stays round). `"normals":"keep"` writes the normals of an unedited import. * **Face budget.** Every command that adds faces predicts the face count of the object it will produce from its arguments, *before* allocating anything. Over the session's `max_faces` (default 200000, see `set_limits`) it fails with `budget_exceeded` and changes nothing: `{"code":"budget_exceeded","op":"create_primitive","estimated_faces":16777216,"limit":200000,"field":"segments","hint":"lower segments/rings","message":"..."}`. Commands that do not add faces (transform, delete, merge, ...) never hit it. Imports are checked from the file header before decoding, and fail with `budget_exceeded` (field `data`) too. * **Session face budget.** `max_total_faces` (default 1000000, at most 67108864) caps the faces of all objects together, counting each object's evaluated modifier stack. A command that would push the total over it fails with the same `budget_exceeded`, with `"limit_kind":"total"` (the per-object limit says `"limit_kind":"object"`): `{"code":"budget_exceeded","op":"duplicate","limit_kind":"total","estimated_faces":6400,"limit":5000,"field":"object","hint":"delete_object or decimate objects you no longer need, or make this one smaller","message":"..."}`. An edit counts only the change to its object (subdividing one object counts its growth), `join` without `keep_sources` replaces its sources, and a command that leaves the total no higher than it was always runs. * **Coordinate limit** (since 0.5.0). Sizes, radii, distances, offsets, scales and positions must be finite and within ±1e9 (`meshforge::MAX_COORDINATE`); beyond that `f32` positions lose all precision and products of two of them overflow. Most larger arguments are an `invalid_argument` naming them (e.g. `size_y`, `center`, `distance`, `noise.frequency`); the rest come back as field `result` (below). A command whose result would put any coordinate of an object (its mesh or its evaluated modifier stack) outside ±1e9, or make one not a number (a scale applied twice, many array copies far apart, noise on a huge grid), fails with `invalid_argument`, field `result`, and changes nothing: `{"code":"invalid_argument","field":"result","valid_range":"every coordinate within -1e9..=1e9","hint":"sizes, offsets, scales and positions are in scene units ...","message":"..."}`. * **Warnings.** A command that does nothing, or leaves something you probably did not want, still succeeds but says so in `warnings`: a selection that matched nothing, extruding a whole closed surface, a zero distance or amplitude, a merge that merged nothing, an identity transform, a mirroring negative scale. ### What every result contains | field | when | |---|---| | `op` | always | | `object` | the object acted on | | `created_objects`, `deleted_objects` | objects added / removed | | `changed_objects` | objects whose geometry changed (a viewer redraws these) | | `new_faces`, `new_vertices` | ids created by this command | | `deleted_faces`, `deleted_vertices` | ids deleted by this command | | `ids_truncated` | an id list above was cut at 50 entries; `id_counts` gives each cut list's full length (e.g. `{"new_faces":80}`) | | `id_counts` | with `ids_truncated`: the full length of each list that was cut | | `moved_vertices` | `transform`, `displace`, `shrinkwrap`, `snap_to_surface`, `place`, `align`: how many vertices moved | | `counts` | `{vertices, edges, faces}` of `object` afterwards | | `selection` | `{domain, count, ids}` of `object` afterwards; over 50 ids, `ids` holds the first 50 and `"truncated":true` (`count` stays exact) | | `stats` | `{tris, vertices, faces, bbox}` of `object` afterwards, all of what export writes: the evaluated stack when `object` has modifiers, and then `cage_tris`, `cage_vertices`, `cage_faces` and `cage_bbox` describe its own mesh (the cage, which edits and selectors act on; `counts` above are the cage's too); for `export_glb` `{tris, vertices, bbox, glb_bytes}` of the file (vertices after splitting at seams and hard edges) | | `path` | `export_glb`: the `path` you passed (the CLI writes the file there) | | `limits` | `set_limits`: `{max_faces, max_total_faces, total_faces}` | | `material`, `assigned_faces` | `set_material`: `{name, index, color, metallic, roughness}` and how many faces got it | | `text` | `create_text`: `{glyphs, lines, width, height, drawn, missing, font, bevel, bevel_reduced}` | | `font` | `load_font`: `{name, family, glyphs, units_per_em, cap_height_em, bytes, loaded}` | | `modifiers` | modifier commands: the stack, per-stage reports, evaluated counts | | `query`, `glb_base64`, `glb_bytes` | output of `query` / `export_glb` | | `uv` | `uv_unwrap`: charts, seams and quality numbers | | `reverted`, `reapplied` | `undo`: labels of the steps reverted; `redo`: labels of the steps re-applied | | `history` | `{undo, redo}`: steps available | | `new_tags` | face tags `object` has now that it did not have before (`extrude`: `["extrude_wall","extruded"]`; a new user tag). `create_primitive` does not list its positional tags (see "Tags") | | `fit` | `shrinkwrap`: `{target, moved, max_displacement, flipped, flipped_faces, missed}` | | `snap` | `snap_to_surface`: `{target, point, normal, translate, rotation_deg}` | | `poke_through` | `check_poke_through`: `{against, clean, vertices, inside, max_depth, samples, crossings, crossing_points}` | | `placement` | `place`, `align`: `{on, moved}`; `place` adds `gap_closed`, `sink`, `contact_points`, `embed_max`, `missed`, `rotation_deg` | | `contacts` | `check_contacts`: `{objects, ground, tolerance, contact, intersecting, gap, floating, pairs}` (brief replies leave `pairs` out) | | `face_groups` | `sweep`, `pipe`: face id ranges `[first, count]` by part: `side`, `inner` (a hollow pipe's inner wall), and on open paths `cap_start`, `cap_end` | | `objects`, `applied`, `redo` | brief replies only, at the top level: see "Brief replies" | | `warnings` | non-fatal notes: no-ops (a zero-width bevel, an empty selection), a clamped bevel width, repairs on import, ... | Fields that do not apply are left out. ### Brief replies Full results repeat counts, selection, stats and history for every command, which adds up in a batch. For agent loops, add `"reply":"brief"` to a command (or set it for the session with `{"op":"set_limits","default_reply":"brief"}`; the CLI uses brief replies for every command by default, `--full` or a command's `"reply":"full"` opting out; the Rust and JS `Session` APIs stay full by default). Then: * each command's result is **one short line**: `op`, `object`, `"ok":true`, `new` / `deleted` (object names), `selected` (a count only, such as `{"faces":4}`, when the selection is not empty), `new_tags` (when non-empty), `closed`, `warnings`, `renumbered`, and the payload the command exists for: `query`, `uv`, `edges` (bevel), `limits`, `checkpoints`, `import`, `points`, `path_length`, `text`, `font`, `material`, `assigned_faces`, `tagged_faces`, `fit`, `snap`, `poke_through`, `glb_bytes`, `stl_bytes`, `path`, `stats` (`export_glb` only), `reverted`, `reapplied`. `glb_base64` and `stl_base64` read `"elided: reply full"`: ask with `"reply":"full"` for the bytes `face_groups` (sweep, pipe, revolve, loft) is left out: select parts by tag; a `points` path over 64 points reads `"elided (N): reply full"` (`path_length` stays); * in a batch, **lines that only echo the request are left out**: a line is kept only when it has news, that is `warnings`, a payload (`query`, `uv`, `limits`, `checkpoints`, `import`, `points`, `text`, `font`, `glb_bytes`, `path`, `stats`, `reverted`, `reapplied`, `tagged_faces`, ...), the count of a `select`, `closed: false` or `assigned_faces: 0`. A line carrying only `new`, `deleted`, `material`, `assigned_faces`, `closed: true`, `new_tags` or (for ops other than `select`) `selected` is dropped; `renumbered` (old ids are void) keeps it, and so do `new` / `deleted` names the `objects` summary leaves out. Then `"applied":n` counts the commands that ran and each kept line carries its `index` in the batch. A batch where every line has news keeps them all, without `applied` or indices. Results a command asked in full (`"reply":"full"`) are never dropped; * the reply ends with **one summary per object** the command or batch changed, as it is afterwards: `"objects":[{"name","tris","shells", "boundary_loops","bbox":[min,max]}]` (of what export writes, so with modifiers evaluated), or `{"name","deleted":true}`. An object whose mesh and modifiers did not change (a `query`, a `select`, a `tag`) is left out; one made and deleted in the same call is listed as deleted only when a command gave it its `"name"`; with nothing changed there is no `objects`. Then `redo` when there are steps to redo. The undo depth is not in brief replies (full results carry `history`); * **floats are rounded**: 5 significant digits on a line (`0.96282`), 7 in a `query` payload; a box (`bbox`, or `min` / `max`) is rounded outwards (min down, max up) to the digits of its own extent, so a 1.2 m part at x = 12345 reads `12345.0727..12346.2671`; a value is written as an integer only when it is whole; a component of a named vector (`position`, `normal`, `centroid`, `center`, `size`, `min`, `max`, `bbox`, `points`) under 1e-6 reads `0`. Full results keep every digit. Id lists, counts and selections are left out: chain with selections (an edit selects its result) or `query` when you need them. A **failed batch** in a `Session` keeps what ran before the failing command (`undo` reverts it): its brief reply has the lines, `applied` and `objects` of that, `failed_index`, the `error` and `"rolled_back": false`. The CLI saves nothing on failure, so there the batch is rolled back and the reply is only `failed_index`, the `error` and a `note`. The error keeps `code`, `message`, `field` and the fix in `hint`; a parse error names the field and lists what it takes once, in `message` (the parser's `detail` and a `one of ...` `expected` are left out, as they repeated it). `"reply":"full"` on a command overrides a brief session. Brief replies stay small however long the batch: * a batch keeps its **last 50 lines**, plus every line with `warnings`; when lines are left out, the list starts with `{"truncated":n,"hint":"reply full, or query"}` and each kept line carries its `index` in the batch; * `objects` keeps the **last 32 summaries**, after the same marker; * each list in a `query` payload (`objects`, `skeletons`, `faces`, `vertices`, `selection.ids`) keeps its first 32 entries, and the payload gets `"brief_truncated":{"truncated":n,"hint":"reply full, or query"}`; * a brief `query` is lean: `counts` has `vertices`, `faces`, `triangles`, `shells` and `boundary_loops` (no `edges`; `vertex_slots` / `face_slots` only when deleted ids leave holes, that is when they differ from the live counts; `evaluated` without `edges`), and `bbox` is left out when the reply's `objects` summary carries the same box for that object (a box that changed after the query stays). `error` and `warnings` are never cut. ```json {"op":"create_primitive","kind":"cube","name":"probe","reply":"brief"} ``` Reply: `{"ok":true,"result":{"op":"create_primitive","object":"probe","ok":true,"new":["probe"]},"objects":[{"name":"probe","tris":12,"shells":1,"boundary_loops":0,"bbox":[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]]}]}` A batch (a single command keeps its line): ```json [ {"op":"create_primitive","kind":"cube","name":"step_demo"}, {"op":"select","object":"step_demo","select":{"faces_facing":[0,1,0]}}, {"op":"extrude","object":"step_demo","distance":0.5} ] ``` Reply (the CLI's default): `{"ok":true,"results":[{"op":"select","object":"step_demo","ok":true,"selected":{"faces":1},"index":1}],"applied":3,"objects":[{"name":"step_demo","tris":20,"shells":1,"boundary_loops":0,"bbox":[[-0.5,-0.5,-0.5],[0.5,1,0.5]]}]}` A 10-command chair batch (seat, bevel, four legs, back, join) replies in 4,663 bytes in full and 330 bytes brief (about 1,170 vs 80 tokens, estimated as bytes / 4): every line only echoed its command, so the reply is `applied`, an empty `results` and the summary. ## Commands Every `json` block below is a complete, valid command. Optional fields show their default in the description. ### create_primitive Adds an object. `kind`: `cube` (`size` 1, or `[x, y, z]` for a box of that extent), `grid` (`nx` 1, `ny` 1, `size_x` 1, `size_y` 1; lies in XY facing +Z), `uv_sphere` (`radius` 0.5, `segments` 16, `rings` 8), `cylinder` along Y (`radius` 0.5, `height` 1, `segments` 16, `capped` true), `cone` along Y with the apex up (`radius` 0.5, `height` 1, `segments` 16, `capped` true), `torus` around Y (`radius` 0.5 to the tube centre, `minor_radius` 0.15 tube radius, below `radius`; `segments` 24 around Y, `rings` 12 around the tube), `capsule` along Y (`radius` 0.25, `height` 1 tip to tip, at least 2 x radius; `segments` 16, `rings` 4 per rounded end). Every shape is centred on its bounding box and has UVs. `center` moves it (default origin). `name` defaults to the kind, made unique (`cube`, `cube.1`, ...). Passing a parameter the kind does not take is an error. Face counts: cube 6, grid nx x ny, uv_sphere segments x rings, cylinder segments + 2, cone segments + 1, torus segments x rings, capsule segments x (2 rings + 1). ```json {"op":"create_primitive","kind":"cube","name":"box","size":2} ``` ```json {"op":"create_primitive","kind":"cube","name":"plank","size":[1.2,0.05,0.3],"center":[0,0.5,0]} ``` ```json {"op":"create_primitive","kind":"cylinder","name":"pillar","radius":0.25,"height":3,"segments":24,"center":[2,1.5,0]} ``` ```json {"op":"create_primitive","kind":"cone","name":"leaves","radius":0.6,"height":1.4,"segments":8,"center":[0,1.4,0]} ``` ```json {"op":"create_primitive","kind":"torus","name":"tyre","radius":0.4,"minor_radius":0.12,"segments":24,"rings":12,"center":[3,0,0]} ``` ```json {"op":"create_primitive","kind":"capsule","name":"post","radius":0.1,"height":1.2,"segments":12,"rings":3} ``` Result: `{"op":"create_primitive","object":"box","created_objects":["box"],"changed_objects":["box"],"counts":{"vertices":8,"edges":12,"faces":6},"selection":{"domain":"faces","count":0,"ids":[]},"stats":{"tris":12,"vertices":8,"faces":6,"bbox":{"min":[-1,-1,-1],"max":[1,1,1],"center":[0,0,0],"size":[2,2,2]}},"history":{"undo":1,"redo":0}}` A cube's faces are 0: -Z, 1: +Z, 2: -Y (bottom), 3: +Y (top), 4: -X, 5: +X. Rather than relying on that, select by tag: every primitive tags its faces (`top`, `bottom`, `side`, `cap`, `front`, `back`, `left`, `right`; see "Tags"; the reply does not list them, to stay short). ### rename_object Renames an object; its geometry, selection, modifiers, materials, tags and skin stay as they are, and later commands use the new name. Undoable (`undo` brings the old name back). The new `name` must not be empty, and no other object may have it (`object_exists`: pick another name); renaming to the name the object already has changes nothing and adds a warning. Nothing else holds an object's name: ops that take a second object (`boolean` `with`, `transfer_weights` `from`, `join`) read it when they run, and a skinned object keeps its skeleton (the skin names the skeleton, not the object). A checkpoint keeps the name the object had when it was made: `restore` brings that name back. ```json {"op":"rename_object","object":"pillar","name":"column"} ``` Result: `{"op":"rename_object","object":"column","created_objects":["column"],"deleted_objects":["pillar"],"changed_objects":["column"],"counts":{...},...}` (the new name in `created_objects`, the old one in `deleted_objects`, so a viewer redraws the object under its new name); brief: `{"op":"rename_object","object":"column","ok":true,"new":["column"],"deleted":["pillar"]}`. ### delete_object ```json {"op":"delete_object","object":"column"} ``` ### select Sets the object's selection. `select` holds exactly one of: | key | selects | |---|---| | `faces_facing: [x,y,z]`, optional `within_deg` (10) | faces whose normal is within the angle of the direction | | `in_box: {min, max}`, optional `domain` (`faces`) | faces whose centroid, or vertices (`"domain":"vertices"`) whose position, is inside the box | | `faces: [ids]` | these faces | | `vertices: [ids]` | these vertices | | `all: true`, optional `domain` (`faces`) | everything | | `none: true` | nothing | | `invert: true` | everything not selected (same domain) | | `grow: n` | n more rings: faces sharing a vertex with the selection / neighbouring vertices | | `shrink: n` | n rings fewer | | `tag: name` | faces carrying the tag (see "Tags"), e.g. `{"tag":"top"}` | `mode` combines a new set with the current one: `replace` (default), `add`, `subtract`, `intersect` (same domain only). ```json {"op":"select","object":"box","select":{"faces_facing":[0,1,0],"within_deg":10}} ``` ```json {"op":"select","object":"box","select":{"faces":[0,1]},"mode":"add"} ``` ```json {"op":"select","object":"box","select":{"grow":1}} ``` ```json {"op":"select","object":"box","select":{"in_box":{"min":[-2,0.9,-2],"max":[2,2,2]},"domain":"vertices"}} ``` ```json {"op":"select","object":"box","select":{"tag":"side"}} ``` Result: `{"op":"select","object":"box","counts":{...},"selection":{"domain":"faces","count":1,"ids":[3]},...}` A `tag` no face carries selects nothing, with a warning listing the tags the object has; a name that is not a tag at all (`"tops"`) is an `invalid_argument` (`field` `select.tag`) whose `valid_range` lists them. ### Tags Faces carry tags: names that say what a face is, so you can select it without ids or boxes. A face can have several. Tags follow their faces through every edit: faces split by `subdivide`, `loop_cut`, `bevel` or a boolean keep their parent's tags, `mirror`, `array`, `merge_by_distance`, `join` and `duplicate` keep them, and `decimate` keeps them on the faces that survive. Tags never change geometry or the exported file. | tag | written by | |---|---| | `top`, `bottom` | cube +Y / -Y face; cylinder, cone, capsule ends; sphere and torus faces facing up / down | | `side` | `create_text`'s walls; cube's four vertical faces; cylinder, cone and capsule walls; sphere and torus faces facing level; `sweep` / `pipe` walls (outer wall of a hollow pipe) | | `cap` | cylinder and cone end discs, capsule hemispheres, `sweep` / `pipe` end caps | | `front`, `back`, `left`, `right` | cube faces facing +Z / -Z / -X / +X (the front of a model faces +Z); a grid is `front`; `create_text`'s letter faces (+Z) and their backs (-Z) | | `extruded` | `extrude`: the caps (they keep their other tags, so an extruded top is still `top`) | | `extrude_wall` | `extrude`: the new side walls (no other built-in tags) | | `inset` | `inset`: the inset faces (keeping their tags) | | `inset_wall` | `inset`: the ring around them (keeping position tags such as `top`) | | `bevel` | `bevel`: the new strips and corner patches (no other built-in tags); `create_text`'s bevel rings | | `cut_wall` | `boolean` `difference` / `intersection`: faces that came from `with` (a drilled hole's walls; the cutter's own tags, built-in and user, are dropped). A `union` keeps `with`'s tags. | | `inner` | `revolve`: sides hidden from outside along the radius (the inside of a mug, bowl or ring); `pipe`: the inner wall of a hollow pipe | | `cap_start`, `cap_end` | `loft`: the first / last section's cap; `sweep` / `pipe` on an open path: the start / end cap (both also `cap`) | | `side`, `cap`, `cap_start`, `cap_end` | `helix` tube: the tube wall is `side`; its start and end discs are `cap` plus `cap_start` / `cap_end` | | `side`, `top`, `bottom`, `cap` | `thread`: the threaded wall is `side`; the end discs are `cap` plus `top` / `bottom` | `revolve` also writes `side`, and `top` + `cap` / `bottom` + `cap` on its caps. The selector names `cap_top` and `cap_bottom` match faces that are both `cap` and `top` (or `bottom`): a revolved vase's lid, a cylinder's or thread's end disc. Add your own with `tag` / `untag` (e.g. `handle`; at most 64 per object). Edit replies list tags the object did not have before in `new_tags`, and `query` reports `tags` (each tag present with its face count) with `"include":["tags"]` and each face's `tags` in `faces`. Modifiers keep tags on the faces they copy or split but do not add op tags (a bevel modifier's strips are not tagged `bevel`). ```json [ {"op":"create_primitive","kind":"cylinder","name":"mug","segments":24}, {"op":"select","object":"mug","select":{"tag":"top"}}, {"op":"inset","object":"mug","thickness":0.05}, {"op":"extrude","object":"mug","distance":-0.8}, {"op":"bevel","object":"mug","select":{"edges":"border","of":{"tag":"inset_wall"}},"width":0.01} ] ``` **Edge selectors** name edges by rule wherever a command takes edges: `bevel` and `loop_cut` (`select`) and `uv_unwrap` (`seams_select`). Exactly one of: | selector | edges | |---|---| | `{"edges":"border","of":}` | the outline of a face region (edges with one side in it); without `of`, the current face selection's outline (an error if the selection is vertices). Open boundary edges of the region count too (an open grid's rim is its border). `{"edges":"border","of":{"tag":"top"}}` is a cube's top rim. | | `{"edges":"between","a":,"b":}` | edges with an `a` face on one side and a `b` face on the other, the two sides differing (an edge inside a region in both `a` and `b` is not between them): `"a":{"tag":"top"},"b":{"tag":"cut_wall"}` is the rim of a drilled hole | | `{"edges":"vertical"}`, optional `within_deg` (10) | edges within the angle of the Y axis (a box's upright corners) | | `{"edges":"horizontal"}`, optional `within_deg` (10) | edges within the angle of the XZ plane (zero-length edges are neither vertical nor horizontal) | | `{"edges":"boundary"}` | open edges (with one face) | | `{"sharper_than_deg":30}` | edges whose faces meet at more than 30 degrees | | `{"all":true}` | every edge | `of`, `a` and `b` take any `select` key (`{"tag":"top"}`, `{"faces_facing":[0,1,0]}`, `{"in_box":{...}}`, `{"faces":[3]}`, ...). A bad key inside names its path (`field` `select.of.tag`). ### transform Scales, then rotates (Euler degrees, X then Y then Z), then translates vertices about a `pivot`: `centroid` (default; mean of the moved vertices), `bbox_center`, `origin`, or a point `[x,y,z]`. What moves: `faces` (their vertices) or `vertices` if given, else `target`: `selection` (default) or `object`. Without `target` and with nothing selected (a new object), the whole object moves and the result carries a warning saying so; an explicit `"target":"selection"` with nothing selected is an `empty_selection` error. `scale` is a number or `[x,y,z]`; a 0 on any axis is an `invalid_argument` (it would collapse faces to zero area; use 0.001 to flatten). ```json {"op":"transform","object":"box","translate":[0,0.5,0]} ``` ```json {"op":"transform","object":"box","target":"object","rotate_deg":[0,45,0],"scale":[1,2,1],"pivot":"origin"} ``` ```json {"op":"transform","object":"box","faces":[3],"scale":0.5} ``` Result adds `moved_vertices`. ### extrude Region-extrudes faces (default: the face selection) along their normals by `distance` (negative = inwards). Selects the extruded caps. Selecting every face of a closed surface leaves no outline to extrude: nothing changes and a warning suggests `inset` or a scale. `distance` 0 works (the caps are meant to be moved next) but warns. ```json {"op":"extrude","object":"box","faces":[3],"distance":0.2} ``` Result: `new_faces` (caps and sides), `new_vertices`, `selection` = caps. ### loop_cut Inserts `cuts` (default 1, up to 64) edge loops across the ring of quads through an edge. Name the edge by two vertex ids that are consecutive in a face (`query` with `"include":["faces"]` lists each face's vertices), or give `select`, an edge selector (see "Tags"): every ring of quads its edges lie on is cut once, so `{"edges":"horizontal"}` on a box cuts both horizontal rings (a 3 x 3 top with `"cuts":2`) and `{"edges":"vertical"}` adds horizontal loops around the sides. Give `edge` or `select`. A selector that matches no edge on a quad ring is a no-op with a warning. ```json {"op":"loop_cut","object":"box","edge":[0,2],"cuts":2} ``` ```json {"op":"loop_cut","object":"box","select":{"edges":"vertical"},"cuts":1} ``` ### subdivide Catmull-Clark subdivision of the whole object, `levels` 1..=4 (default 1). Each level multiplies the face count by about 4. ```json {"op":"subdivide","object":"box","levels":2} ``` ### mirror Mirrors across the plane through the origin normal to `axis` (`x`, `y`, `z`) and joins the halves, welding vertices on the plane within `merge_distance` (default 0.0001). The mirrored faces swap their `left` / `right` tags (`x`), `top` / `bottom` (`y`) or `front` / `back` (`z`). ```json {"op":"mirror","object":"box","axis":"x","merge_distance":0.001} ``` ### merge_by_distance Welds vertices closer than `distance`. Restricted to `vertices` if given, else to the current selection's vertices, else applies to all vertices. ```json {"op":"merge_by_distance","object":"box","distance":0.0001} ``` ### decimate Simplifies the object by quadric edge collapse (`meshforge::ops::decimate`). Give exactly one target: `ratio` (fraction of the triangles to keep, in (0, 1]), `triangles` (keep at most this many) or `error` (stop when the collapse error would exceed this fraction of the bounding-box diagonal). Quads and n-gons are triangulated first; the result is all triangles and every id changes (the result reports the renumbering like `subdivide`). UVs, normals, colours and skin weights are carried across; UV seams and open boundaries only collapse along themselves. Optional: `lock_vertices` (ids that must not move; their faces are kept), `lock_selection` (also lock the current selection's vertices, e.g. a selected face or hands region), `feature_angle` (degrees; sharper edges are kept like seams), `lock_boundary`, `keep_shells` (never remove a small disconnected piece entirely), `preserve_seams` (default `true`; `false` lets UV seams move like any edge: lower shape error, UVs next to a seam may stretch). A `warnings` entry says if the target could not be reached. Every collapse is bounded by a measured Hausdorff guard, so the maximum error stays below Blender's on character meshes. The guard runs at roughly Blender's speed (0.8-0.9x on the bench sphere on the latest farm node) and is meant for offline LOD builds; the library's `hausdorff_guard: false` (quadric only, 4-6x Blender) is the speed path (see `bench-blender/README.md`). ```json {"op":"decimate","object":"box","ratio":0.5,"feature_angle":40} ``` For a phone tier: `{"op":"decimate","object":"body","triangles":7700}`. ### delete_faces Deletes faces (default: the face selection). Edges left without faces go too, and so do vertices left without edges unless `keep_isolated_vertices` is true. ```json {"op":"delete_faces","object":"box","faces":[3]} ``` Result: `deleted_faces`, `deleted_vertices` (ids of everything removed). ### bevel Rounds or chamfers edges: each edge becomes a strip of `segments` faces (default 1 = a flat chamfer) shaped by `profile` (0.5 = circular, the default; 0.25 = straight; towards 1 = boxy), and corners where bevelled edges meet get a patch of quads. Name the edges with exactly one of: * `edges`: `[[a,b],...]`, each edge by two vertex ids (as for `loop_cut`); * `faces`: face ids; the border edges of that face region are bevelled (bevelling a face's outline); * `vertices`: vertex ids; the edges between two of them, or with `"affect":"vertices"` the vertices themselves are cut off; * `select`: an edge selector (see "Tags"): `{"sharper_than_deg":30}` (edges whose faces meet at more than 30 degrees), `{"all":true}`, `{"edges":"border","of":{"tag":"top"}}` (the top rim), `{"edges":"between","a":{"tag":"top"},"b":{"tag":"side"}}`, `{"edges":"vertical"}`, `{"edges":"horizontal"}` or `{"edges":"boundary"}`; * nothing: the current selection (a face selection bevels its border). `width` (0 to 1000000) is the bevel size, measured per `width_mode`: `offset` (default: from the old edge along each face), `width` (across the new strip), `depth` (from the old edge in to the strip) or `percent` (of the neighbouring edge lengths). `clamp` (default true) shrinks the width where bevels would overlap, with a warning. Only edges that can meet are shrunk together (a chain of bevelled edges and the faces between them): a tight spot such as the tiny facets of a hole's rim clamps that rim, and the other bevelled edges keep the full width (the warning then says `on 8 of the 16 bevelled edges`; when clamped parts got different widths, `clamped to as little as X%`). Only new vertices on a shared edge are compared: offsets that cross inside one face with no such edge between them (an hourglass-shaped n-gon bevelled on both sides of a narrow waist) are not clamped. With `"clamp":false` a width past what fits is kept and the bevels overlap, so the mesh crosses itself; the result then warns `"clamp is false and the width is 162% of what fits: the bevels overlap, so the mesh crosses itself (query validate reports self_intersections); use clamp: true, or width <= 0.4950"`, and `query` `validate` reports the crossings. `harden_normals` (default false) stores normals that keep the big faces flat-shaded. Open boundary edges cannot be bevelled and are skipped with a warning. A zero width or a target that matches nothing is a no-op with a warning, not an error. Original faces keep their ids; the new faces are selected. ```json [ {"op":"create_primitive","kind":"cube","name":"chest"}, {"op":"bevel","object":"chest","select":{"sharper_than_deg":30},"width":0.05,"segments":3} ] ``` ```json {"op":"bevel","object":"chest","faces":[3],"width":0.02,"segments":2,"profile":0.25} ``` ```json {"op":"bevel","object":"chest","select":{"edges":"border","of":{"tag":"top"}},"width":0.02,"segments":2} ``` Result: `edges` (how many edges the target matched and bevelled, also in brief replies: check it when a selector may catch more than you meant), `new_faces` (strips and corner patches), `new_vertices`, `deleted_vertices` (the bevelled corners), `selection` = new faces, `warnings`. ### array Repeats the whole object `count` times (including the original). Linear: copy *k* is moved by *k* x `offset` (default `[1,0,0]`). Radial: give `axis` (`"x"`, `"y"`, `"z"` or a direction), `angle_deg` (default 360) and `center` (default origin); a full turn spaces the copies `360/count` degrees apart, a partial angle puts the last copy at `angle_deg`. `merge_distance` (default 0 = off) welds coincident vertices where copies touch. The original keeps its ids; the copies' faces are selected. Radial copies turn with their position (spokes, a crown's points). With `"rotate_copies": false` they stay upright: only the object's bounding-box centre travels around the axis (stool legs, a ring of posts). Grids: `count2` with `offset2` repeats the whole row (linear or radial) that many times, and `count3` with `offset3` repeats all rows again: a 2D or 3D grid of tiles, or radial rings stacked along the axis. Copy *i + count (j + count2 l)* is row copy *i* moved by *j* x `offset2` + *l* x `offset3`. `count * count2 * count3` is at most 10000. ```json {"op":"array","object":"chest","count":3,"offset":[1.5,0,0]} ``` ```json [ {"op":"create_primitive","kind":"cube","name":"tooth","size":0.2,"center":[1,0,0]}, {"op":"array","object":"tooth","count":12,"axis":"y","angle_deg":360,"center":[0,0,0]} ] ``` ```json [ {"op":"create_primitive","kind":"cylinder","name":"leg","radius":0.04,"height":0.6,"center":[0.25,0,0]}, {"op":"array","object":"leg","count":4,"axis":"y","rotate_copies":false}, {"op":"create_primitive","kind":"cube","name":"tile","size":0.9}, {"op":"array","object":"tile","count":4,"offset":[1,0,0],"count2":3,"offset2":[0,0,1]} ] ``` ### solidify Gives a surface thickness: every face gets a reversed copy moved `thickness` against the normals, and open boundaries are closed with rim quads (`fill_rim`, default true). `offset` places the wall: -1 grows inwards (default), 1 outwards, 0 centred on the surface. `even_thickness` keeps the wall thickness at corners. The inner shell (the new reversed faces) is selected, whatever was selected before and also after earlier deletes. ```json [ {"op":"create_primitive","kind":"grid","name":"sheet","nx":2,"ny":2}, {"op":"solidify","object":"sheet","thickness":0.05} ] ``` ### Modifiers Every object has a **modifier stack**: an ordered list of operations that is evaluated on top of the object's mesh without changing it. The preview and `export_glb` show the evaluated result; edit commands (`extrude`, `transform`, `select` ids, ...) keep acting on the object's own mesh, the *cage*. Changing the cage or a modifier re-evaluates only what changed (each stage is cached). A modifier that fails is skipped (its input passes through) and the result says why in `warnings` and `modifiers.stages`. A modifier is a JSON object with a `"type"` and its parameters, plus optional `"enabled"` (default true): | type | parameters (defaults) | |---|---| | `subdivide` | `levels` (1, up to 4) | | `mirror` | `axis`; `merge_distance` (0.0001) | | `bevel` | `width`; `segments` (1), `profile` (0.5), `angle_deg` (all edges; else edges sharper than this), `width_mode` (`offset`), `clamp` (true), `harden_normals` (false) | | `merge` | `distance` | | `transform` | `translate` ([0,0,0]), `rotate_deg` ([0,0,0], X then Y then Z), `scale` ([1,1,1]); about the origin | | `array` | `count`; linear `offset` ([1,0,0]) or radial `axis`, `angle_deg` (360), `center` ([0,0,0]), `rotate_copies` (true); grid `count2`+`offset2`, `count3`+`offset3`; `merge_distance` (0) | | `solidify` | `thickness`; `offset` (-1), `even_thickness` (false), `fill_rim` (true) | Modifier commands return `modifiers`: `stack` (the definitions; pass them to `set_modifiers` to restore the stack later), `stages` (per modifier: `type`, `enabled`, `faces`, `vertices` after it, and any `error` or `warnings`) and `evaluated` (counts of the final mesh). They are undoable. ### add_modifier Adds `modifier` at `index` (default: the end). ```json [ {"op":"create_primitive","kind":"cube","name":"rounded"}, {"op":"add_modifier","object":"rounded","modifier":{"type":"bevel","width":0.05,"segments":3,"angle_deg":30}}, {"op":"add_modifier","object":"rounded","modifier":{"type":"array","count":4,"offset":[1.2,0,0]}} ] ``` ### set_modifier Changes the modifier at `index`: `set` changes only the keys you give (merged into the current definition and validated as a whole; `type` cannot change), `modifier` replaces the whole definition, and `enabled` switches it on or off. Give `set` or `modifier`, not both. A bad key names itself: `{"code":"parse","field":"set.cont",...}`. ```json {"op":"set_modifier","object":"rounded","index":0,"set":{"segments":4}} ``` ```json {"op":"set_modifier","object":"rounded","index":0,"modifier":{"type":"bevel","width":0.1,"segments":4,"angle_deg":30}} ``` ```json {"op":"set_modifier","object":"rounded","index":1,"enabled":false} ``` ### move_modifier Moves the modifier at `from` to position `to`. ```json {"op":"move_modifier","object":"rounded","from":1,"to":0} ``` ### set_modifiers Replaces the whole stack (an empty list clears it), e.g. with a `stack` saved from an earlier result or `query`. ```json {"op":"set_modifiers","object":"rounded","modifiers":[{"type":"bevel","width":0.05,"segments":2,"angle_deg":30},{"type":"subdivide","levels":1},{"type":"solidify","thickness":0.02,"enabled":false}]} ``` ### remove_modifier ```json {"op":"remove_modifier","object":"rounded","index":2} ``` ### apply_modifier Bakes a modifier into the object's mesh and removes it from the stack: the one at `index` (default 0) on its own (if it is not the first, the ones before it are not baked in; a warning says so), or with `"all":true` the whole evaluated stack. Ids may be renumbered (`renumbered`); query again. ```json {"op":"apply_modifier","object":"rounded","index":0} ``` ```json {"op":"apply_modifier","object":"rounded","all":true} ``` ### uv_unwrap UV-unwraps the whole object into a corner UV layer (default `uv0`; glTF convention, v down) and packs the charts into the unit square. Seams are corners with different UVs; `export_glb` splits vertices there, so ids do not change. * `method`: `auto` (default) cuts the mesh into low-distortion charts automatically and also cuts the given `seams`; `seams` cuts only along `seams` (plus mesh boundaries; charts that are not disks are still cut); `project` groups faces by normal direction and projects each group flat (no solve: several times faster than `auto`, with a little more stretch and more charts; like Blender's Smart UV Project, but with less stretch). * `seams`: edges to cut, each as two vertex ids (`[[0,2],[2,3]]`). * `seams_select`: more edges to cut, by an edge selector (see "Tags"): `{"edges":"border","of":{"tag":"cap"}}` cuts a cylinder's rims. * `keep_seams`: also keep the seams already in `layer` (default false). * `margin`: gap between charts and to the border, UV units (default 0.005, max 0.2). The packer cannot keep a margin of `1 / (1 + sqrt(n))` or more between `n` charts (0.075 for 152 charts); a margin it cannot keep is lowered, and a warning gives the margin used, which is a margin that works. * `flatten`: `isometric` (default: least stretch) or `conformal` (least angle distortion). * `rotate`: `arbitrary` (default), `ninety` or `none`. * `max_deviation_deg`: auto-chart tolerance (default 12; smaller gives more, flatter charts). * `angle_limit_deg`: project charts: the largest angle between the normals of faces in one chart (default 66, range (0, 180]). Each face is within about half of it of its chart's projection direction, so the worst stretch is about `1 / cos(angle_limit_deg / 2)`; smaller gives more charts and less stretch. * `area_weight`: project charts: 0 (default) lets every face count the same when choosing projection directions, 1 weights them by area. * `quality` (since 0.5.0): auto and seam charts. `standard` (default) is fast and no worse than Blender's Smart UV Project on stretch (L2 and worst triangle), packing efficiency, flips and overlap on every `uv_quality` input except one (`cylinder_256x96` packs below Smart UV): it also cuts edges sharper than 60 degrees, runs the stretch-minimising (ARAP) refinement only on charts whose conformal map stretches noticeably, and segments meshes of 2048 faces or more on small patches of faces. `high` gives the least stretch and fewest seams (no sharp-edge cuts, ARAP on every chart, face-level segmentation) and is slower. * `layer`: the corner layer to write (`uv0`, `uv1`, ...). ```json {"op":"uv_unwrap","object":"box","method":"auto","margin":0.01} ``` ```json {"op":"uv_unwrap","object":"box","method":"project","angle_limit_deg":66,"margin":0.005} ``` Result: `uv` = `{layer, charts, seam_edges, flipped, pack_efficiency, l2_stretch, max_stretch, angle_distortion_deg}`. `flipped` is 0: a chart that would fold is split. `l2_stretch` is 1.0 for a distortion-free unwrap. `warnings` says when `layer` already had UVs (replaced, or its seams kept with `keep_seams`), except for the UVs a primitive was created with: `create_primitive`'s `uv0` (kept through edits, `duplicate`, and `join` / `boolean` of primitives) is replaced quietly. Imported UVs and an earlier `uv_unwrap` still warn. It also warns when `method: "seams"` gave a single chart. The face count does not change, so `max_faces` never blocks it. ### query Reads information without changing anything. `include` lists any of: `counts` (live and slot counts, triangles, shells, boundary loops; 0 loops = closed; these are the object's own mesh, whose ids edits use, and for an object with modifiers `counts.evaluated` adds `{vertices, edges, faces, triangles}` of the evaluated stack, matching `bbox`), `bbox` (what export writes; for an object with modifiers the evaluated stack, plus `cage_bbox` for its own mesh; always the bind pose: a posed object adds `pose` with its rotations and the posed `bbox`, `volume` and `closed`), `selection`, `faces` (id, centroid, normal, area, vertex ids, tags), `vertices` (id, position), `validate` (topology, plus `zero_area_faces` / `degenerate_edges` counts with example ids, and `self_intersections`: the number of face pairs of one connected shell that pass through each other (the surface crosses itself), with up to 16 `self_intersection_pairs`; `valid` is false if there are any. `touching_vertices` counts vertex pairs of one surface (a connected shell; vertices on a boundary are left out) within the weld tolerance (1e-6 of the bbox diagonal) that share no edge: the surface pinches onto itself (a boolean of parts that only touch along a face can leave such a zero-thickness wall), with up to 16 `touching_vertex_pairs` and a note in `warnings`; it leaves `valid` true. The count stops at 10000 (or after a bounded number of tests on a mesh with many vertices in one spot), and `touching_vertices_capped` is then true: read it as "10000+". `overlapping_parts` counts pairs from different shells (separate parts overlapping in one object, normal for kitbashed props), with up to 16 `overlapping_part_pairs` and a note in `warnings`; they leave `valid` true. On meshes over 20000 triangles an even sample of 20000 is probed and `self_intersections_sampled` says so), `objects` (every object and skeleton), `modifiers` (the modifier stack, see above), `tags` (each face tag present with its face count, `{"side":4,"top":1,...}`), `volume` (or its synonym `area`: adds `volume`, the enclosed volume, signed so it is negative when the faces point inwards and meaningful only when closed; `area`, the surface area; and `closed`, true when there are no boundary loops; all of what export writes, in bind pose (the posed values are under `bbox`'s `pose`); `volume` is left out of an open mesh, and the shells of one object are summed, so overlapping shells count their shared space twice), `closed` (only `closed`), `valid` (the same as `validate`). `faces` entries also list each face's `tags`. Default: `["counts","bbox","selection"]`, or `["objects"]` when no `object` is given. `faces` / `vertices` details cover the given ids, else the selection, else everything, up to `limit` (256). ```json {"op":"query","object":"box","include":["counts","bbox","faces"],"limit":50} ``` **Scene table.** Without `object` (or with `"objects":"*"` or a list of names), `query` returns one row per object in `query.scene`: `name` and what `include` asks for, of what export writes: `bbox` as `[min, max]`, `counts` as `tris` and `shells`, `volume` (when closed), `area`, `closed`, `validate` as `valid`. The default is `["bbox","closed"]`; `selection`, `faces`, `vertices`, `modifiers` and `tags` need one object. One call checks a whole build. A brief reply rounds the rows like any query and keeps the first 32 (then `brief_truncated`). Skeletons have no rows (a session holding only skeletons gets an empty `scene`): `["objects"]` without an object lists the objects and skeletons (counts, selection size). ```json {"op":"query"} ``` ```json {"op":"query","objects":"*","include":["volume","closed"]} ``` Result for a 2 m cube and an open grid: `"query":{"scene":[{"name":"box","volume":8,"area":24,"closed":true},{"name":"sheet","area":1,"closed":false}]}`. ```json {"op":"query","object":"chest","include":["modifiers"]} ``` ```json {"op":"query","object":"box","include":["volume"]} ``` Result for the 2 m cube: `"query":{"volume":8,"area":24,"closed":true}`. Result: `{"op":"query","object":"box","counts":{...},"query":{"counts":{"vertices":8,"edges":12,"faces":6,"triangles":12,"vertex_slots":8,"face_slots":6,"shells":1,"boundary_loops":0},"bbox":{"min":[-1,-1,-1],"max":[1,1,1],"center":[0,0,0],"size":[2,2,2]},"faces":[{"id":0,"centroid":[0,0,-1],"normal":[0,0,-1],"area":4,"vertices":[0,2,3,1]},...]},...}` ### import_gltf Imports `.glb` or `.gltf` (embedded buffers) given as base64 (a `data:...;base64,` prefix is fine). Each mesh node becomes an object, each skin a skeleton. `name` names a single object, or prefixes several (`name/node`); default: the node names. ```json {"op":"import_gltf","data":"Z2xURgIAAAA...","name":"hero"} ``` Result: `created_objects`, and `counts` for a single object; `warnings` list repairs (non-manifold edges cut, vertices split). ### import_obj Imports Wavefront OBJ text given as base64, as one object (default name `obj`). ```json {"op":"import_obj","data":"diAwIDAgMAp2IDEgMCAwCnYgMSAxIDAKdiAwIDEgMApmIDEgMiAzIDQK","name":"quad"} ``` ### export_glb Exports `objects` (default all) with their skeletons as binary glTF, with their modifier stacks evaluated (`"apply_modifiers":false` exports the cages instead). ```json {"op":"export_glb","objects":["box"]} ``` Options: `normals` `auto` (default; hard edges sharper than `angle_deg`, default 30), `flat` (faceted), `smooth`, or `keep` (normals stored by an unedited import). Vertices are split wherever normals or UVs differ, so hard edges stay hard in any engine. `path` is echoed back in the result: the core never touches the filesystem, the CLI writes the file there. Faces with a material (`set_material`) export as one glTF primitive per material, with PBR `baseColorFactor`, `metallicFactor` and `roughnessFactor`. ```json {"op":"export_glb","objects":["box"],"normals":"flat","path":"out/box.glb"} ``` ```json {"op":"export_glb","normals":"auto","angle_deg":40} ``` Skinned objects export in bind pose with their skin, whatever their `pose`. `"pose_clip":true` also writes the pose as a one-key animation clip named `pose` (time 0, one rotation channel per posed joint; those joint nodes carry `translation`/`rotation`/`scale` instead of `matrix`), so three.js (`AnimationMixer`) or Blender show the posed rig. It needs a posed object among the exported ones (else `invalid_argument`, field `pose_clip`); objects sharing a skeleton with different poses give a warning, and the clip uses the first one's (example under `pose`). A posed joint whose bind is scaled unevenly gets a warning: glTF applies the clip's rotation after that scale, so viewers show the pose only approximately. Result: `{"op":"export_glb","glb_base64":"Z2xURgIAAAA...","glb_bytes":1684,"path":"out/box.glb","stats":{"tris":12,"vertices":24,"bbox":{...},"glb_bytes":1684},...}` ### helix A helix rising along +Y, starting at `(radius, 0, 0)`: `turns` turns of `pitch` rise each (default 3 of 0.25 at radius 0.5), the radius scaled linearly to `radius * taper` at the end (default 1). `handedness` `right` (default) turns counter-clockwise seen from above while rising, like a standard screw; `left` the other way. `segments_per_turn` (default 32) sets the path resolution. By default a tube of `tube_radius` (0.05) with `tube_segments` (8) is swept along the helix (rotation-minimising frames, so it does not twist) and closed with flat caps (`capped`, default true): a spring, a coil, a spiral handle. The tube must stay clear of the axis (`tube_radius` below the smallest helix radius) and of the next turn (`2 * tube_radius` below `pitch`); otherwise the command fails and says which to change. The result also has `path_length`. ```json {"op":"helix","name":"spring","radius":0.3,"pitch":0.15,"turns":6,"tube_radius":0.03} ``` With `"output":"path"` no object is made: the result holds the path as `points` (`[[x,y,z],...]`, start to end, `center` added) and `path_length`, ready to pass to a sweep as its path. (This tube is a minimal built-in sweep; it will share the general sweep op's code once that lands.) ```json {"op":"helix","radius":0.5,"pitch":0.2,"turns":2,"segments_per_turn":16,"output":"path"} ``` ### thread A threaded rod along Y, centred on the origin (a bolt shaft): a closed, manifold shell whose surface follows a trapezoid screw thread between the root radius `radius - depth` and the crest `radius` (default 0.25), with `pitch` (0.1) between crests over `length` (1). `depth` defaults to 0.6 x pitch. `runout` (default true) fades the thread out over one pitch at each end, so the ends are plain discs. `segments` (32) vertices around and `rows_per_pitch` (12) rows per pitch set the resolution; `handedness` `right` (default) or `left`. Join a head on top for a bolt: ```json [ {"op":"thread","name":"bolt","radius":0.1,"length":0.6,"pitch":0.05}, {"op":"create_primitive","kind":"cylinder","name":"head","radius":0.18,"height":0.1,"segments":6,"center":[0,0.35,0]}, {"op":"join","objects":["bolt","head"]} ] ``` ### import_stl Imports an STL file (binary or ASCII) given as base64, as one object (default name `stl`). STL repeats every corner per triangle; corners closer than `weld_distance` (default 1e-5; 0 = identical corners only) become one vertex, so the result is a proper half-edge mesh that edit ops, booleans and UV unwrap can use. `"z_up":true` turns a Z-up file (3D printing, CAD) to meshforge's Y-up. A binary file whose header starts with `solid` is still read as binary. ```json {"op":"import_stl","data":"c29saWQgdApmYWNldCBub3JtYWwgMCAwIDEKb3V0ZXIgbG9vcAp2ZXJ0ZXggMCAwIDAKdmVydGV4IDEgMCAwCnZlcnRleCAwIDEgMAplbmRsb29wCmVuZGZhY2V0CmVuZHNvbGlkIHQK","name":"tri"} ``` The result's `import` block says what was read and repaired: `{"format":"ascii","triangles":1,"vertices":3,"watertight":false,"degenerate":0,"nonmanifold_edges":0,"split_vertices":0,"boundary_edges":3}`. Non-manifold input is never rejected: edges used by 3+ triangles or with flipped winding are cut, shells touching at one vertex are split, and collapsed triangles are dropped, each counted there and in a warning. A closed result (`watertight` true) is ready for `boolean`; for an open one try a larger `weld_distance`. ### export_stl Exports `objects` (default all) as one binary STL: every face triangulated, facet normals from the triangles, no materials or UVs. Modifier stacks are evaluated unless `"apply_modifiers":false`. `"z_up":true` writes Z-up for slicers and CAD. Posed objects (`pose`) are written in bind pose unless `"posed":true` (a 3D print of a posed figure). `path` is echoed back; the CLI writes the file there. ```json {"op":"export_stl","objects":["tri"],"z_up":true,"path":"out/tri.stl"} ``` Result: `{"op":"export_stl","stl_base64":"bWVzaGZvcmdl...","stl_bytes":134,"path":"out/tri.stl","stats":{"tris":1,"vertices":3,"bbox":{...}},...}` ### set_limits Sets the face budget `max_faces` (1..=16777216, default 200000): the largest face count one object may reach through any command, and `max_total_faces` (1..=67108864, default 1000000): the most faces all objects may have together (evaluated stacks included). Without fields it only reports the limits and the current `total_faces`. Lowering a limit below what the session already holds succeeds with a warning. Not recorded in undo history. The CLI's `--max-faces` and `--max-total-faces` set the same values. ```json {"op":"set_limits","max_faces":500000} ``` ```json {"op":"set_limits"} ``` ```json {"op":"set_limits","max_total_faces":2000000} ``` Result: `{"op":"set_limits","limits":{"max_faces":500000,"max_total_faces":2000000,"total_faces":1234},...}` ### inset Shrinks faces (default: the face selection) inside their own outline by `thickness` (>= 0), joined to the old outline by a ring of quads, then moves them `depth` along their normals (default 0; negative = into the surface, for panels and recesses). By default the faces inset together as one region; `"individual":true` insets each face on its own (a panel per crate side). Selects the inset faces. A thickness that would fold a face over itself is an `invalid_argument` whose `valid_range` gives the largest that fits. ```json [ {"op":"create_primitive","kind":"cube","name":"crate"}, {"op":"select","object":"crate","select":{"all":true}}, {"op":"inset","object":"crate","thickness":0.08,"depth":-0.03,"individual":true} ] ``` ```json {"op":"inset","object":"crate","faces":[3],"thickness":0.1} ``` ### displace Moves vertices along their normals by seeded fractal noise: rocks, lumpy foliage, terrain. `noise`: `seed` (0), `amplitude` (0.1, world units, the peak offset), `frequency` (1, bumps per unit), `octaves` (1, up to 8; more = finer detail), `lacunarity` (2), `gain` (0.5). Acts on the whole object, or only on `faces` / `vertices` if given. The noise is gradient noise with an integer hash and only exact float arithmetic, so the same seed gives the same shape on every platform, wasm included. ```json {"op":"displace","object":"leaves","noise":{"seed":7,"amplitude":0.08,"frequency":2,"octaves":3}} ``` ### set_material Creates or updates a named material and assigns it. `name` defaults to the object name; an existing material of that name is reused, and the `color` / `metallic` / `roughness` you give update it (every face using it changes). `color` is linear `[r,g,b]` or `[r,g,b,a]` in 0..=1 (new materials: 0.8 grey, `metallic` 0, `roughness` 0.8). By default every face of the object gets it; `"target":"selection"` assigns the face selection, `faces` explicit ids. Materials stay on their faces through every edit, `duplicate` and `join`. ```json {"op":"set_material","object":"crate","name":"wood","color":[0.55,0.38,0.2],"metallic":0,"roughness":0.8} ``` ```json {"op":"set_material","object":"crate","name":"panel","color":[0.4,0.27,0.14],"target":"selection"} ``` ### duplicate Copies an object (geometry, materials, selection) to a new object, `name` defaulting to the source name made unique (`crate.1`). Optional `translate`, `rotate_deg`, `scale` and `pivot` transform the copy as `transform` with `"target":"object"` would. ```json {"op":"duplicate","object":"crate","name":"crate2","translate":[1.5,0,0],"rotate_deg":[0,30,0]} ``` ### join Merges two or more `objects` into one object `name` (default: the first one's name). The parts stay separate shells (nothing is welded) and keep their materials, UVs and other attributes. The sources are removed unless `keep_sources` is true. ```json {"op":"join","objects":["crate","crate2"],"name":"crates"} ``` Result: `created_objects` `["crates"]`, `deleted_objects` (the sources), `counts` of the result. When some parts have a material and others have none, `warnings` names the unpainted ones: they stay grey in the joined object. `set_material` them before joining (a `set_material` on the joined object without `faces` repaints every part). ### undo / redo Reverts or re-applies the last `steps` (default 1) recorded steps. Each command is one step; a session made with `batch_undo_step` (the browser runtime's sessions) records a whole batch (a JSON array) as one step, labelled after its first command (`"create_primitive drill (+2 more)"`). The history is bounded (256 steps and about 256 MB of snapshots by default; the oldest steps are dropped first). ```json {"op":"undo"} ``` ```json {"op":"redo","steps":1} ``` Result: `reverted` for undo, `reapplied` for redo (labels such as `"transform box"`), `changed_objects`. With nothing to undo or redo the error code is `nothing_to_undo` / `nothing_to_redo`. ### boolean Replaces `object` by `object` `mode` `with`: `union`, `difference` (`object` minus `with`) or `intersection`. Both objects must be closed (watertight); `with` is left unchanged (delete it with `delete_object` if it was only a cutter). The result is closed and manifold, robust to coplanar faces, shared edges and touching solids (exact arithmetic). Faces the other object does not cut keep their polygons; cut faces are triangulated. UVs and other corner layers are interpolated on cut faces, face layers such as `material` are copied from the source face. Faces of `with` that have no material take `object`'s most used material, so a drilled hole's walls match the object (`set_material` on the cutter first to give them their own). Every id of `object` is renumbered and its selection is cleared. ```json {"op":"create_primitive","kind":"cube","name":"plate","size":1} ``` ```json {"op":"create_primitive","kind":"cylinder","name":"drill","radius":0.2,"height":2,"segments":24} ``` ```json {"op":"boolean","object":"plate","with":"drill","mode":"difference"} ``` Result: `renumbered: true`, `warnings` when the result is a no-op (e.g. `"boolean difference: the operands do not overlap; B misses A, so the result is A unchanged"`, or an intersection of disjoint objects, which is empty). The exact result is rounded to 32-bit floats, which can leave slivers (zero-length edges, zero-area faces) where surfaces nearly touch; a clean-up pass collapses and flips them away, so the result passes `validate` (`stats` counts `slivers_collapsed`, `slivers_flipped`, `films_removed`). Errors: `invalid_argument` with `field` `object` or `with` if that operand is open (has boundary edges), with a hint: `merge_by_distance` welds cracks, `solidify` gives a sheet thickness, or rebuild the part from closed primitives. `op_failed` if an operand intersects itself; `invalid_argument` (field `with`) if the result could exceed the face limit. ### checkpoint / restore / list_checkpoints / drop_checkpoint Named save points for trying things: `checkpoint` saves the whole scene (every object with its selection and modifier stack, skeletons, materials) under `name`; `restore` puts it back. Use them instead of counting undo steps: checkpoint, try an edit, look, then keep it or restore. * **Cheap.** Objects are shared, not copied: making a checkpoint copies one pointer per object, and the first edit of an object afterwards copies only that object. `restore` costs nothing for objects that did not change since the checkpoint. (100k-triangle numbers: see the cost note below.) * **`restore` is undoable**: it is one undo step, and `undo` returns to the scene before the restore. The checkpoint is kept, so you can restore it again. If the scene already matches, `restore` changes nothing and warns. * `checkpoint` with an existing name replaces it (with a warning). Making and dropping checkpoints is not an undo step. * **Bounded, never silently evicted.** All checkpoints together may hold about 512 MB and at most 64 checkpoints (`SessionOptions::checkpoint_memory_cap`, `max_checkpoints`). Going over fails with `checkpoint_limit` and nothing changes; drop one with `drop_checkpoint` and try again. The cap counts the **whole scene** each checkpoint holds (geometry, attributes, selections and cached modifier outputs), not only what changed: an object shared between checkpoints, or still unchanged in the live scene, counts once. So a checkpoint of a 100k-triangle scene counts about 6 MB even though making it copied nothing. * `restore` warns when the restored scene is over `max_total_faces`. * Checkpoints live in the session (and replay from a CLI `.mfs` session file); they are not written to exported files. ```json {"op":"checkpoint","name":"before_bevel"} ``` ```json {"op":"restore","name":"before_bevel"} ``` ```json {"op":"list_checkpoints"} ``` ```json {"op":"drop_checkpoint","name":"before_bevel"} ``` Result (all four): `checkpoints`: `{"list":[{"name":"before_bevel","objects":3,"bytes":5120}],"bytes":5120,"memory_cap":536870912,"max_checkpoints":64}`, where a checkpoint's `bytes` is what only it holds (what `drop_checkpoint` frees). `restore` also lists `changed_objects`, `created_objects` (objects the checkpoint has and the scene had lost) and `deleted_objects` (objects made after the checkpoint). Errors: `unknown_checkpoint` (`name`, `available`); `checkpoint_limit` (`limit_kind` `"memory"` or `"count"`, `would_hold`, `limit`, and `checkpoints` largest first, to pick one to drop). ### tag Adds a tag to faces (`faces`, default: the face selection), so `{"tag":name}` selects them later. Use your own names (`handle`, `seat`, `left_leg`: 1 to 32 of a-z, 0-9, `_` and `-`, starting with a letter) or a built-in one. Your tags follow their faces like the built-in ones (extrude walls, subdivided and boolean pieces keep them; `join` keeps each part's). Result: `tagged_faces` (how many faces gained it) and `new_tags`. At most 64 user tags per object (`invalid_argument`, field `name`, past that). ```json [ {"op":"select","object":"plate","select":{"tag":"cut_wall"}}, {"op":"tag","object":"plate","name":"hole"} ] ``` ### untag Removes a tag from faces (`faces`, default: the face selection). To remove it everywhere, select `{"tag":name}` first. `tagged_faces` says how many faces lost it; a name no face carries is an `invalid_argument`. ```json {"op":"untag","object":"plate","name":"hole"} ``` ### sweep Adds an object: a closed 2D `profile` swept along a 3D `path`. Use it for railings, sword guards, handles, horns, frames and trims: one command instead of a chain of extrudes. - `profile`: the outline `[[x, y], ...]`, 3+ points, either winding (do not repeat the first point). x runs across the path, y along `up`. It must not cross itself. - `path`: points `[[x, y, z], ...]` in order. As given it is a polyline with mitred corners (the ring at a corner is stretched so the bar keeps its thickness). `"smooth": N` rounds it into a Catmull-Rom curve through the same points with N samples per segment (centripetal, so no loops or cusps). The curve passes through every point, so at a sharp corner it bulges a little past it (about a tenth of the shorter leg; the 1 m rail below reaches x = 1.10): to keep a corner exact, leave `smooth` off or add points either side of it. Repeated points are dropped; a turn over 175 degrees is an error. - `closed: true` (or a last point equal to the first) makes a loop: the end joins the start with no seam and no caps. A last point equal to the first with a `[start, end]` scale or a twist that is not a multiple of 360 stays open (with a warning), since those ends cannot meet. - The profile is carried by rotation-minimizing frames, so it does not spin around the path on its own. `up` sets where the profile's +y points at the start (default +Y, or +Z if the path starts along Y). `twist_deg` adds a twist from start to end (on a closed path, a multiple of 360). - `scale`: one number, or `[start, end]` for a taper (a horn: `[1, 0.05]`). - `caps` (default true) closes the ends of an open path: one n-gon each. - `tight_turns`: where the profile reaches further across a bend than the turn radius, neighbouring rings would cross and fold the surface. `clamp` (default) shrinks the profile at those points just enough to stop it; `warn` keeps the size. Both add a warning naming the path point and the fix (smooth the path, space its points out, or make the profile smaller). The shrink tapers over 3 rings each side, so the bar narrows into the bend instead of notching. - Not checked: a path that comes back near itself (an S that touches, a coil with too little pitch) can make the surface pass through itself. `query` `validate` reports self-intersections; keep the path's loops at least twice the profile's size apart. Faces: path segments x `smooth` x profile points, plus 2 caps. The budget is checked from these numbers before anything is built. UVs: U around the profile, V along the path; caps mapped flat. ```json {"op":"sweep","name":"rail","profile":[[-0.03,-0.02],[0.03,-0.02],[0.03,0.02],[-0.03,0.02]],"path":[[0,1,0],[1,1,0],[1,1,1]],"smooth":8} ``` ```json {"op":"sweep","name":"horn","profile":[[0.1,0],[0,0.1],[-0.1,0],[0,-0.1]],"path":[[0,0,0],[0,0.3,0.1],[0.1,0.5,0.4]],"smooth":8,"scale":[1,0.05],"twist_deg":90} ``` Result: `created_objects`, `counts`, `stats`, and `face_groups`, e.g. `{"side":[0,64],"cap_start":[64,1],"cap_end":[65,1]}` (face ids `first .. first+count`), so you can `select` `{"faces":[65]}` to inset or extrude an end. The faces also carry tags: `side` (walls), `cap` plus `cap_start` / `cap_end` (ends), and `inner` (a hollow pipe's inner wall; its range is `face_groups.inner`), so `{"select":{"tag":"cap_end"}}` works without ids. Warnings for dropped repeated points, an inferred closed path, `caps` on a closed path, and tight turns. Errors (`invalid_argument`, each with a hint): `profile` with fewer than 3 distinct points, no area, or crossing edges; `path` with fewer than 2 distinct points (3 when closed) or a turn over 175 degrees (the point is named); `twist_deg` not a multiple of 360 or a `[start, end]` `scale` on a closed path; `up` along the path's first segment; `smooth` over 64. ### pipe Adds an object: a circle of `radius` (`segments` around, default 16) swept along `path`, like `sweep`. `inner_radius` makes it hollow; the caps are then rings of quads. Also accepted as `"op":"tube"`. `path`, `closed`, `smooth`, `scale`, `caps`, `tight_turns`, the result's `face_groups` and the errors are as for `sweep`. Use it for mug handles, pipe runs, chair frames, cables and hoops. ```json {"op":"pipe","name":"handle","path":[[0.5,0.2,0],[0.75,0.2,0],[0.75,0.8,0],[0.5,0.8,0]],"radius":0.04,"segments":12,"smooth":6} ``` ```json {"op":"tube","name":"hoop","path":[[1,0,0],[0,0,1],[-1,0,0],[0,0,-1]],"closed":true,"smooth":8,"radius":0.05,"inner_radius":0.04} ``` Faces: path segments x `smooth` x `segments` (twice when hollow), plus caps (2 solid, 2 x `segments` hollow). Errors as for `sweep`, plus `radius` not positive and `inner_radius` not between 0 and `radius`. For `sweep` with a hole through the library (`ops::sweep`, `inner`), the hole must have the profile's points in the same order and lie strictly inside it. ### revolve Spins a 2D `profile` around an axis into a new object (a lathe; `"op":"lathe"` works too): vases, mugs, lamp posts, chess pawns, barrels. Each point is `[r, y]`: `r` is the distance from the axis (>= 0), `y` the position along it. Options: `segments` (24) steps around; `angle_deg` (360) sweep, below 360 the two ends stay open (warning, `closed: false`); `axis` (`y`; `x` or `z` lay it down); `closed` (false) when the profile is a loop; `caps` (true) closes open ends that are off the axis with a flat n-gon (full turns only); `sharp` (none) lists profile point indices with a hard crease and stores normals for them (`export_glb` with `"normals":"keep"` writes them; the default `auto` picks creases by angle); `center` moves the result; `name` defaults to `revolve`, made unique. When `closed` is not given, a profile whose last point repeats its first (within 1e-6 of its largest coordinate; an outline drawn back to its start) loses the repeat, with a warning: off the axis it is read as closed (`closed` set), on the axis (r = 0) it stays open, from the axis back to the axis. An explicit `"closed": false` keeps the old error. * Points with `r = 0` become a single pole vertex with a triangle fan (no degenerate faces). Only the first and last point of an open profile may lie on the axis. A closed profile may touch the axis along exactly one segment (two consecutive points): that segment collapses. * The profile's direction does not matter: faces always point out of the solid. A profile from the axis back to the axis, or with capped ends, or a closed loop, gives a closed manifold. * Faces carry built-in tags (see `tag`): `side`, `inner` (sides hidden from outside along the radius: the inside of a mug, bowl or ring), and `top` + `cap` / `bottom` + `cap` on the caps, so `{"tag":"inner"}`, `{"tag":"cap_top"}` (a cap facing up the axis), `{"tag":"cap_bottom"}` or `{"tag":"cap"}` select them without ids. Tags follow their faces through edits (inset faces keep their cap's tags). * Face count (checked against the budget first): segments x profile segments, plus one per cap. * UVs: sides `u` around, `v` along the profile's length; caps a disk. ```json {"op":"revolve","name":"vase","profile":[[0,0],[0.3,0],[0.4,0.3],[0.15,0.8],[0.2,1]],"segments":24} ``` ```json {"op":"lathe","name":"cup","profile":[[0,0],[0.4,0],[0.4,1],[0.35,1],[0.35,0.1],[0,0.1]],"segments":32,"sharp":[1,2,3,4],"center":[1.5,0,0]} ``` ```json {"op":"revolve","name":"tyre_ring","profile":[[0.3,0],[0.5,0],[0.5,0.2],[0.3,0.2]],"closed":true,"segments":32,"center":[-1.5,0,0]} ``` Result (vase): `{"op":"revolve","object":"vase","created_objects":["vase"],"closed":true,"counts":{"vertices":97,"edges":192,"faces":97},...}`. The vase's top end is off the axis, so it is capped; select `{"tag":"cap_top"}`, then inset and extrude it downwards to hollow it. Errors (`invalid_argument`, `field` names the point): fewer than 2 points (3 closed); `r < 0` (`profile[i]`); a repeated point; an interior point on the axis (split the shape into two revolves and `join` them, or use r = 0.001); a closed profile touching the axis anywhere but one segment; a profile that encloses no area with the axis (a flat line such as `[[0,0],[0.5,0]]`: give it a thickness); an open profile whose last point repeats the first (use `closed: true`); both open ends off the axis at the same height with caps on (the caps would overlap: `caps: false` for an open channel, or `closed: true`); a coordinate beyond 1e6; more than 1024 points; `angle_deg` outside [0.01, 360]; `segments` below 3 on a full turn or above 4096; a `sharp` index past the end. Caps are tagged by the way they face: `cap_top` faces up the axis, `cap_bottom` down. A profile whose outline crosses itself is built with a warning (the surface intersects itself). ### loft Skins two or more closed cross-sections into a new object: sword blades, tree trunks, bottles, table legs. `sections` lists them in order; each is `{points?, y?, offset?, scale?, rotate_deg?}`: * `points`: the closed outline as `[x, z]` points in the section's plane (the last point joins the first by itself). Omitted: the previous section's outline, so a taper is one outline plus a `scale` per section. The first section must give it. * `y`: height (default the section's index: 0, 1, 2, ...); `offset`: `[x, y, z]` added (bend a trunk sideways). * `scale`: a number or `[sx, sz]` in the section's plane (default 1; not 0: taper to a point with 0.01). * `rotate_deg`: a number twists the section around Y (degrees); `[rx, ry, rz]` (Euler, X then Y then Z) tilts it. Sections with fewer points are resampled to the largest count by splitting their longest edges, so corners stay corners. Point 0 of each section joins point 0 of the next, and every outline is wound the same way first, so the direction you list points in does not matter, and a mirrored section (`scale` `[-1, 1]`, `rotate_deg` `[180, 0, 0]`) is turned to match its neighbour instead of twisting the skin. Faces always point out. `caps` (true) closes both ends with flat polygons (closed manifold); `false` leaves a tube open at both ends. `name` defaults to `loft`, made unique. Faces are tagged `side`, `cap_start` (first section) and `cap_end` (last section), both caps also `cap`: select them with `{"tag":"cap_end"}`. Face count (checked against the budget first): points x (sections - 1), plus 2 caps. ```json {"op":"loft","name":"blade","sections":[{"points":[[-0.04,0],[0,-0.008],[0.04,0],[0,0.008]],"y":0},{"y":0.7,"scale":0.8},{"y":0.85,"scale":0.05}],"caps":true} ``` ```json {"op":"loft","name":"trunk","sections":[{"points":[[0.3,0],[0.21,0.21],[0,0.3],[-0.21,0.21],[-0.3,0],[-0.21,-0.21],[0,-0.3],[0.21,-0.21]],"y":0,"scale":1.2},{"y":0.3},{"y":1.5,"scale":0.8,"offset":[0.1,0,0]},{"y":2.5,"scale":0.5,"offset":[0.25,0,0],"rotate_deg":[0,0,-10]}]} ``` Result (blade): `{"op":"loft","object":"blade","created_objects":["blade"],"closed":true,"counts":{"faces":10,...},...}`. Errors (`invalid_argument`, `field` names the section): fewer than 2 sections; a first section without `points`; an outline with fewer than 3 points, a repeated point, or no area (`sections[k].points`); a scale of 0 (`sections[k]`); a section at the same place as the previous one (`sections[k]`); sections that enclose no volume (`sections`). A key of the wrong shape is a `parse` error naming it (`sections[2].offset`: offset takes 3 numbers `[x, y, z]`, not `[x, z]`); its hint shows a correct section. ### create_text Adds 3D text for signs, shop fronts, labels and titles: the string, extruded along Z into closed, manifold solids. The text reads along +X with Y up; the front faces +Z at `z = depth/2`, the back faces -Z (rotate it with `transform`, e.g. `"rotate_deg":[-90,0,0]` to lay it flat facing up). Glyphs come from the built-in font, a blocky geometric face drawn for meshforge (`A-Z a-z 0-9` and `. , ! ? - + = : ; ' " / ( ) _`), or from a TrueType font you load with `load_font` (`"font":""`). Holes (`o`, `a`, `8`, `A`) are real holes, dots (`i`, `!`, `:`) are separate shells, overlapping contours in a font are merged (nonzero fill), and every glyph is closed and manifold. Glyphs are not merged with each other: when letters touch or overlap (a tight `letter_spacing`, a script font, a kerning pair), each glyph is still its own closed solid, so one object holds solids that intersect. That renders fine; for one clean solid (e.g. for 3D printing), use `per_glyph` and join the parts with `boolean` `"mode":"union"`. * `text` (required): `\n` starts a new line, a tab is 4 spaces. A character the font lacks is left out (it advances like a space) with a warning. At most 10000 characters. * `size` (1): cap height, the height of a capital letter. Lowercase x-height is 5/7 of it, descenders reach 2/7 below the baseline, and lines are 11/7 x `size` apart. * `depth` (0.2): extrusion along Z, centred on z = 0. * `align` (`center`): each line `left` (starts at x = 0), `center` or `right` (ends at x = 0). * `valign` (`center`): `baseline` (first baseline at y = 0), `top` (first cap top at 0), `center` (first cap top to last baseline, centred) or `bottom` (last baseline at 0). * `letter_spacing` (0, -1..=10): extra space between letters as a fraction of `size`; negative tightens (below -1/7, letters can touch; a warning says so). `line_spacing` (1) scales the line distance. * `per_glyph` (false): one object per glyph, named `name/0`, `name/1`, ... in the order of the drawn characters (the text without whitespace, or `text.drawn` when some are missing), so each letter can be moved, coloured or animated alone. The names are listed once, in `created_objects`. Default: one object. * `center` ([0,0,0]) moves the laid-out text; `name` defaults to `text`, made unique. * `font` (`builtin`): or the `name` of a `load_font`. `size` is the font's cap height (from its OS/2 table, else the height of `H`); its own advances and `kern` pairs space the letters. * `bevel` (0): rounds or chamfers the front and back edges by this width (and depth); at most 0.45 x `depth` (wider is narrowed, with a warning). Where a glyph's strokes are too thin for it the bevel is narrowed for that glyph (`text.bevel_reduced` lists them, with a warning). `bevel_segments` (2, 1..=16): rings across it, 1 = a flat chamfer. Text is built on a fine grid (7168 steps per cap height in the built-in font, 16 per font unit in a loaded one): a bevel narrower than one step is left out, and a narrow bevel gets fewer rings, so that no two rings fall on the same grid point. Each warns (`bevel ... left out on ...`, `bevel_segments N lowered to M`). * `curve_segments` (8, 1..=64): straight pieces per curve of a loaded font's outlines (flat curves get 1). A glyph may have at most 50000 points once flattened (composite glyphs count every part they use), a text's distinct glyphs at most 1000000 points together, and its outlines at most a fixed amount of work (about a second of CPU); past any of these, the command fails (field `curve_segments`, "too complex"), so a damaged or hostile font cannot stall a session. Every face carries one built-in tag (see "Tags"): `front`, `back`, `side` or `bevel`, so `{"select":{"tag":"front"}}` then `set_material` paints the letter faces and leaves the sides alone. Built-in glyphs without a bevel have caps made of the font's cells (quads and half-cell triangles); otherwise caps are triangulated. The object has generated UVs (front and back planar in units of `size`, sides along each edge). The face count is known from the text before anything is built (the face budget checks it exactly; with `per_glyph` all glyphs together count against `max_faces`). ```json {"op":"create_text","text":"OPEN","name":"sign","size":0.5,"depth":0.1} ``` ```json {"op":"create_text","text":"Bakery\nfresh daily","name":"shopfront","size":0.3,"depth":0.06,"align":"left","valign":"top","center":[-1.5,2.4,0.26]} ``` ```json {"op":"create_text","text":"WIN!","name":"title","per_glyph":true,"letter_spacing":0.1} ``` ```json {"op":"create_text","text":"Gift Shop","name":"plaque","size":0.2,"depth":0.04,"bevel":0.008,"bevel_segments":3} ``` Result (582 bytes): `{"op":"create_text","object":"sign","created_objects":["sign"],"changed_objects":["sign"],"counts":{"vertices":288,"edges":576,"faces":292},"stats":{"tris":568,"vertices":288,"faces":292,"bbox":{"min":[-0.821,-0.25,-0.05],"max":[0.821,0.25,0.05],...}},"text":{"glyphs":4,"lines":1,"width":1.643,"height":0.5,"font":"builtin"},...}`. `text.drawn` (the drawn characters in order) is sent only when it differs from the text without whitespace, i.e. when some characters are missing. Errors: `invalid_argument` (field `text`) for text with nothing to draw (only spaces, or no character the font has) or over 10000 characters; (field `size`, `depth`) outside 0.0001..=10000, (field `line_spacing`) for values that are not > 0; `object_exists` if `name` (or one of `name/0`, `name/1`, ...) is taken; `budget_exceeded` (field `text`) when the text has more faces than `max_faces`; `invalid_argument` (field `font`) for a font that is not loaded (the hint shows `load_font`), (field `bevel`) for a negative bevel, (field `letter_spacing`) outside -1..=10; (field `curve_segments`) for a glyph that is too complex, and (field `font`) for a font whose outlines make no valid mesh (both name the character). ### load_font Loads a TrueType font (`.ttf`, or an `.otf` with TrueType `glyf` outlines) for `create_text`'s `font`. Fonts with CFF (PostScript) outlines are not supported yet; convert them to TrueType outlines first (e.g. with fonttools). `data` is the file's bytes, base64; the meshforge CLI also takes `"path"` and reads the file for you (the library and wasm never touch files). `name` defaults to `font`; loading a name again replaces that font (with a warning). Fonts stay in the session and are not undo steps; a session holds at most 8 fonts of at most 32 MB each (reusing a name replaces that font). No fonts ship with meshforge: bring one whose licence lets you use it in your game. A server that hosts sessions for others must keep refusing `path` (the library does): only a local tool such as the CLI should turn a path into `data`, or a client could make the server read its files. ```json {"op":"load_font","name":"sign","data":"AAEAAAAIAIAAAwAA..."} ``` ```json {"op":"load_font","name":"sign","path":"fonts/MyFont.ttf"} ``` Then `{"op":"create_text","text":"Old Mill","font":"sign","size":0.4,"depth":0.08,"bevel":0.01}` sets text in it. Result: `{"op":"load_font","font":{"name":"sign","family":"My Font","glyphs":412,"units_per_em":1000,"cap_height_em":0.7,"bytes":81234,"loaded":["sign"]},...}` Errors: `invalid_argument` (field `data`) for bytes that are not a font (WOFF / WOFF2 must be decompressed first) or a font without outlines; (field `font`) for a font with CFF / CFF2 outlines (the hint says how to convert it); (field `path`) when `path` reaches the library instead of the CLI; (field `name`) for an empty name or `builtin`, or a ninth font; (field `data`) for data over 32 MB. Builds without the `ttf` cargo feature answer `unsupported_op`. ### create_skeleton / auto_weights / transfer_weights Rigging: rig a model inside the session, and re-rig it after editing it. A **skeleton** is a named list of joints; objects bound to one carry skin weights, and `export_glb` writes them as a glTF skin (three.js, Godot, Unity and Blender read it). `import_gltf` of a rigged `.glb` keeps its skeleton, named like the import (`name`, else `skeleton`, made unique); `query` lists skeletons with their joint counts. `create_skeleton` makes one from joints `{name, parent?, head, tail?}`, parents first. `head` is where the joint sits; a joint with children ends at the child it points to, and a joint without children ends at its `tail` (a `_end` tip joint is added there; tips never take weight). Binds have no rotation. Joints named like helpers (`root`, `ik_*`, `socket_*`) take no weight: the result warns. ```json {"op":"create_skeleton","name":"leg_rig","joints":[{"name":"thigh","head":[0,1,0]},{"name":"shin","parent":"thigh","head":[0,0.5,0],"tail":[0,0,0]}]} ``` Result: `"skeleton":{"name":"leg_rig","joints":3,"tips":["shin_end"]}`. A bone of zero length (a `tail` at its own `head`, or a child at its parent's `head`) is an error. A joint named like a tip marker (a name ending in `end`, such as `legend`, or a hand finger 4 such as `LeftHandIndex4`) takes no weight, and the result warns. `auto_weights` solves bone-heat weights for `objects` together (a body and its separate parts) against a skeleton: `skeleton` names one in the session, or inline `joints` make a new one, which `skeleton` names (default: `skeleton`, made unique). Without either, the session's only skeleton is used. The objects are bound to the skeleton and earlier weights are replaced, so run it again after editing (new vertices from `extrude`, `subdivide` and the like start without weights). Up to 4 influences per vertex, summing to 1. With several objects (or one object of several pieces), each piece is sorted first. Large pieces and pieces that enclose a joint of their own (hands, a head, trousers around the legs) are solved as the body; a joint on another piece's surface (a wrist at a sleeve's end cap) belongs to the piece it sits inside. Those pieces get the same weights as when weighted alone, unless one hides a bone from another. Small pieces that enclose no joint (shoes, a collar, buttons) copy the weights of the body surface nearest them, so they move with it; weighted alone, such a piece is its own body. A mirror-built figure weights symmetrically. Each joint's weight stays near its bone: it fades out along the surface within about one limb radius of the joint's own region, and a joint gives no weight where its bone cannot be seen through the body (no arm weight on the torso below the armpit, none from one finger on the next). Options: `profile` (`default`; `correctives_runtime` for runtimes that apply pose-driven corrective shapes; `hlab` for the pre-0.4 default, tuned to MakeHuman's weights, with the hip crease, clavicle and face passes and no reach cap) and `shoulder_style` (`heat`, or `correctives`). It is one undo step (with the skeleton it made). Builds without the `weights` cargo feature answer `unsupported_op`. ```json [ {"op":"create_primitive","kind":"cylinder","name":"arm","radius":0.2,"height":2,"segments":12,"center":[0,1,0]}, {"op":"loop_cut","object":"arm","select":{"edges":"vertical"},"cuts":7}, {"op":"create_skeleton","name":"arm_rig","joints":[{"name":"upper","head":[0,0,0]},{"name":"lower","parent":"upper","head":[0,1,0],"tail":[0,2,0]}]}, {"op":"auto_weights","objects":["arm"],"skeleton":"arm_rig"} ] ``` Brief result line: `{"op":"auto_weights","object":"arm","ok":true,"skin":{"skeleton":"arm_rig","objects":1,"vertices":108,"weighted":108,"unweighted":0,"max_influences":2,"joints":3,"joints_used":2}}`. `unweighted` is 0, or a warning says how many vertices will not move. A full reply adds `skin.detail`: `dominant` (per joint, the vertices whose largest weight is on it), `objects` (`name`, `vertices`) and `fallback_used`. Inline joints, for a quick rig of a new prop (a bending pole): ```json [ {"op":"create_primitive","kind":"cylinder","name":"pole","radius":0.05,"height":2,"segments":8,"center":[2,1,0]}, {"op":"loop_cut","object":"pole","select":{"edges":"vertical"},"cuts":5}, {"op":"auto_weights","objects":["pole"],"skeleton":"pole_rig","joints":[{"name":"base","head":[2,0,0]},{"name":"top","parent":"base","head":[2,1,0],"tail":[2,2,0]}]} ] ``` `transfer_weights` copies weights from a skinned object (`from`, here the arm weighted above) onto `object` (a sleeve, a prop held in a hand, an edited copy) by the closest source surface, filling the rest by inpainting, and binds it to the same skeleton. `exclude_joints` lists joint name prefixes the result must not use (`hair_` on a shirt). Full replies add `matched` and `inpainted` vertex counts to `skin.detail.objects`. ```json [ {"op":"duplicate","object":"arm","name":"sleeve","scale":[1.1,1,1.1],"pivot":[0,1,0]}, {"op":"transfer_weights","object":"sleeve","from":"arm"} ] ``` ```json {"op":"transfer_weights","object":"sleeve","from":"arm","exclude_joints":["lower"]} ``` Errors: `invalid_argument` with a hint: field `joints` (a parent listed after its child, missing, or the joint itself; a repeated or empty name; a zero-length bone; over 1024 joints), `skeleton` (no such skeleton, a new skeleton's name already taken, several skeletons and none named, over 1024 joints, or no joint that can take weight), `objects` (empty, repeated, or an object without faces), `from` (not skinned, or the same object), `exclude_joints` (a prefix that matches no joint; the hint lists them). `budget_exceeded` (`"limit_kind":"weights"`) when live vertices x deforming joints is over 67108864: decimate first, or use fewer joints. ### shrinkwrap / snap_to_surface / check_poke_through Fitting one object onto another: a garment or hair onto a body, a part onto a surface. The target is read as export writes it (its modifier stack evaluated); the object's own vertices move. These commands never add faces. `shrinkwrap` moves the object's vertices onto `target`'s surface, plus `offset` along the target's normal (negative goes inside), keeping the topology. `mode`: `nearest` (default) takes each vertex's closest surface point; `project` follows the vertex's own normal line, either way, to the nearest hit (vertices whose line misses stay, counted as `missed`). `select` (a selector, see `select`) wraps only those faces' vertices; without it the whole object wraps (the current selection is not used). `smooth` (0 to 100 passes) then evens out vertices the wrap bunched up: each pass moves every wrapped interior vertex halfway to its neighbours' mean and back onto the offset surface (border vertices of an open object stay put). The offset follows smooth normals (faces meeting at more than 60 degrees keep their own), so a shell over a body is smooth and one over a box keeps flat sides; a vertex whose closest point is on an edge or corner of the target is offset along the direction from that point towards it, so the shell rounds the target's creases instead of bunching vertices on them or leaving gaps. Give the tube enough rings (`loop_cut`) to follow the body between them. ```json [ {"op":"create_primitive","kind":"capsule","name":"doll","radius":0.15,"height":0.8,"segments":24,"rings":6,"center":[5,0.4,0]}, {"op":"create_primitive","kind":"cylinder","name":"jacket","radius":0.12,"height":0.3,"segments":24,"capped":false,"center":[5,0.4,0]}, {"op":"loop_cut","object":"jacket","select":{"edges":"vertical"},"cuts":5}, {"op":"shrinkwrap","object":"jacket","target":"doll","offset":0.01,"smooth":2}, {"op":"check_poke_through","object":"jacket","against":"doll","clearance":0.009} ] ``` Brief result lines: `{"op":"shrinkwrap","object":"jacket","ok":true,"fit":{"target":"doll","moved":168,"max_displacement":0.040004,"flipped":0}}` and `{"op":"check_poke_through","object":"jacket","ok":true,"poke_through":{"against":"doll","clean":true,"vertices":168,"inside":0,"max_depth":0,"crossings":0}}`. `fit` says how many vertices `moved`, the largest move (`max_displacement`), and how many faces turned over (`flipped`, with up to 8 ids in `flipped_faces` and a warning): a fold where the wrap pulled a face inside out. `degenerate` (faces left with zero area) and `self_intersections` (face pairs of the object the wrap made cross) appear, with a warning, when they are not 0. Fix it with `smooth`, a larger `offset`, or by wrapping only the part near the body with `select`. `snap_to_surface` places a whole part: it moves the object so its `anchor` lands on the closest point of `target`'s surface (plus `offset` along the normal). `anchor`: `min_y` (default: the centre of the bounding box's bottom, where a part stands), `center`, `origin` (the world origin, for parts modelled around it) or a point `[x, y, z]`. `align_normal` also turns the object about the anchor so its `axis` (default `y`) points along the surface normal: a hair clump grows out of the scalp, a button lies flat on a coat. Result: `snap` `{target, point, normal, translate, rotation_deg}`; for the clump below, brief: `"snap":{"target":"doll","point":[5.1358,0.67386,0.052687],"normal":[0.91627,0.1848,0.35537],"translate":[-0.11422,-0.016138,-0.047313],"rotation_deg":79.35}`. ```json [ {"op":"create_primitive","kind":"cone","name":"clump","radius":0.03,"height":0.12,"segments":8,"center":[5.25,0.75,0.1]}, {"op":"snap_to_surface","object":"clump","target":"doll","anchor":"min_y","align_normal":true} ] ``` `check_poke_through` reports where `object` (a garment) and `against` (a body, closed) pass through each other, and changes nothing (no undo step). Two measures: * `inside`: garment vertices inside the body, or closer to its surface than `clearance` (default 0; pass the `offset` you wrapped with, a little less). Inside/outside is decided by the body's surface orientation, so the body must be closed (a warning says when it is not). `samples` lists the deepest `limit` (default 5, at most 64) as `{vertex, position, depth}`, deepest first; `depth` is how far past the allowed surface the vertex is, and `max_depth` the largest. * `crossings`: garment triangles that pass through body triangles (skin poking out between garment vertices shows here even when every garment vertex is outside). `crossing_points` lists up to `limit` places where they cross, spread over all of them. Touching surfaces do not count. The count stops after 20 million triangle-pair tests (a huge garment, or one large triangle over a dense body): then `"complete":false` and a warning say `crossings` is a lower bound. The garment is read as its own mesh (its cage, so `samples` ids are its vertex ids), the body as export writes it (modifiers applied). `clean` is true when both are 0. To fix a dirty fit, `shrinkwrap` again with a larger `offset` (or `select` the region around the samples), or add rings so the garment follows the body more closely. ```json {"op":"check_poke_through","object":"jacket","against":"doll","clearance":0.009,"limit":3} ``` Errors: `invalid_argument` with a hint: `target` / `against` (the object itself, or an object without faces), `offset` (not finite), `smooth` (over 100), `clearance` (negative), `limit` (outside 1..64); `parse` for an unknown `mode`, `anchor` or `axis`. ### place / align / check_contacts Putting parts on other parts, and a check that fails a build with floating parts. Geometry is read as export writes it (modifier stacks evaluated); the moved objects' own vertices move. None of these add faces. `place` drops `object` along `direction` (default `[0,-1,0]`, straight down) until it rests on `on` (one object or a list: `["bank_l","bank_r"]`). `contact`: * `full` (default): the object's base reaches the lowest surface under its whole footprint, so no corner floats; where the ground rises, it goes into the object (`embed_max` says how deep). For buildings on terrain, props on floors, rails on a deck. Exact on triangle meshes: the footprint's corners, the surface's vertices inside it and every surface edge crossing its outline are measured. * `first`: stops at the first touch, like a lid set down, or a deck across two banks of different height (with `full` a span over a valley would drop into it). `sink` (default 0) then pushes it that much further in: houses on terrain want a few centimetres so no gap shows at the walls. A negative sink leaves a gap of that size (a warning says so; `check_contacts` then sees the part floating unless the gap is within its tolerance). `full` measures under the footprint's outline (the convex hull of the base): a table's legs over a dip go down to the dip, so the high side buries them. When the ground under the footprint rises more than half the object's height, a warning says so and suggests `"contact":"first"`. `at` `[x, z]` first moves the centre of `object`'s box there (vertical directions only). `align_normal` tilts it so its up side follows the surface under its footprint (a rock on a slope). `with` lists objects moved (and tilted) the same way: rails riding on their deck. `snap_to_surface` is the other way to put one part on another: it moves one anchor point to the *closest* surface point, in any direction (a button on a curved chest); `place` rests a whole footprint along a direction. ```json [ {"op":"create_primitive","kind":"grid","name":"hill","nx":8,"ny":8,"size_x":20,"size_y":20}, {"op":"transform","object":"hill","target":"object","rotate_deg":[-90,0,0]}, {"op":"displace","object":"hill","noise":{"seed":3,"amplitude":0.4,"frequency":0.2}}, {"op":"create_primitive","kind":"cube","name":"cottage","size":[3,2.5,3],"center":[-5,6,-5]}, {"op":"place","object":"cottage","on":"hill","sink":0.05} ] ``` Result `placement`: `on`, `moved` (the translation), `gap_closed` (how far it moved to reach the surface, before `sink`; positive: it floated that high), `sink`, `contact_points` (up to 4: where the base meets the lowest ground, or the first touch), `embed_max` (`full`: how deep the highest ground under the footprint goes into it, the sink included), `missed` (`full`: footprint corners with nothing under them: an overhang, also a warning) and `rotation_deg` (`align_normal`). `align` moves `object` (and `with`) along one `axis` so its box's `mode` side (`min`, `center` (default), `max`) lines up with `to`'s `target_mode` side (default: the same as `mode`), plus `offset`: ```json [ {"op":"create_primitive","kind":"cube","name":"toybox","size":1,"center":[8,0.5,0]}, {"op":"create_primitive","kind":"cube","name":"toybox_lid","size":[1.1,0.1,1.1],"center":[9,3,1]}, {"op":"align","object":"toybox_lid","to":"toybox","axis":"y","mode":"min","target_mode":"max"}, {"op":"align","object":"toybox_lid","to":"toybox","axis":"x"}, {"op":"align","object":"toybox_lid","to":"toybox","axis":"z"} ] ``` `check_contacts` is the lint that ends a build. It changes nothing (no undo step). `objects` (default `"*"`, every object; the ground is always added), `ground` (the terrain object; default the plane y = 0), `tolerance` (default 0.002: surfaces closer than this touch). Every pair whose boxes come within the tolerance is one of: * `contact`: the surfaces are within `tolerance` (a part sunk less than that into another counts too); * `intersecting`: the surfaces cross, or one is inside the other by more than the tolerance. Containment needs a **closed** container: an open mesh (a terrain sheet, a tube without caps) cannot hold anything "inside", so a part within an open mesh's box counts as a gap, with a warning; * `gap`: near boxes, but `distance` apart. Contact pairs also carry `support` (vertices of either object within the tolerance of the other; 1 when an edge rests across an edge) and `spread` (how far apart those points are: 0 for a single point, about the base's diagonal for a box on a floor). An object floats when no chain of contacts or intersections links it to the ground (an object whose lowest point is within the tolerance of y = 0 and whose top is not buried below it, or the `ground` object): a deck and its rails hanging together above the banks all float. `floating` lists them: `{object, gap, below, group, fix}`: how far its group must drop to touch `below`, the group's base (`group`, on the other members) and, on the base, a `fix`: a `place` command (with `with` for the group), or `transform`s down to y = 0. `require` `{"floating":0}` (or any count, and `"intersecting":n`, where pairs with the ground do not count) makes the command fail with `check_failed` when more are found. Put it last in a build batch. CLI (`meshforge apply`): nothing lands, the session stays as it was until the check passes. Runtime (`meshforge.js`): the build stays (the reply says `rolled_back: false`): `s.undo()` it, or run the fixes and check again. `"min_support": s` (world units, e.g. 0.05) also requires each contact that holds a part up to spread at least `s` (see `spread` below), so a part balanced on a single vertex or a sliver floats; intersecting pairs always hold. ```json {"op":"check_contacts","objects":["cottage"],"ground":"hill","require":{"floating":0}} ``` A floating rail fails like this: `{"code":"check_failed","reason":"1 floating object (allowed 0)","failures":[{"object":"rail_left","problem":"floating","detail":"rail_left floats 0.04 above deck: place it on deck","fix":{"op":"place","object":"rail_left","on":"deck"}}],"message":"check_contacts failed: 1 floating object (allowed 0): rail_left floats 0.04 above deck: place it on deck",...}`. Run the `fix`, then check again. Result `contacts`: `objects`, `ground`, `tolerance`, the pair counts `contact`, `intersecting`, `gap`, `floating`, and in full replies `pairs` (`{a, b, kind, distance, support, spread}`, the first `limit`, default 64). Errors: `invalid_argument` with a hint: `on` (the object itself, `"*"`, an object without faces), `at` (nothing of `on` under the object: `valid_range` gives the surface's extent; or `at` with a sideways `direction`), `direction` (zero), `sink` / `offset` (not finite), `with` (the object or a target), `to` (the object itself), `tolerance` (negative), `limit` (outside 1..1024). ### pose Bends a skinned object so you can see the rig work. `rotations` maps joint names to `[rx, ry, rz]`: Euler angles applied about X, then Y, then Z, in the joint's own bind frame (for `create_skeleton` joints, whose binds have no rotation, that is the world axes), about the joint, on top of its bind pose; children follow. Degrees by default (`"degrees":false`: radians). Joints not named stay in bind pose. Give `object` for one object, or `"skeleton":"rig"` instead to pose every object bound to that skeleton (a body and its clothes) in one undo step; the result's `pose.objects` lists them. The pose is stored on the object and is non-destructive: the object's mesh (the bind pose, which edits and selectors act on) and its weights do not change. Selectors and edits always use the bind pose, so `faces_facing`, `in_box`, ids and directions refer to the rest shape, not the bent one. The preview (CLI `preview`, the browser runtime's buffers), `query`'s `pose` (with `include` `bbox`), `export_glb`'s `pose_clip` and `export_stl`'s `posed` show it; everything else (`bbox`, `volume`, the objects summary, which adds `"posed":true`) stays the bind pose, as plain `export_glb` writes it. The posed mesh is linear blend skinning of the evaluated stack (`p' = sum w_j * posed_j * bind_j^-1 * p`); the trigonometry is portable, so native and wasm give the same bits. A pose is one undo step, it survives edits (it applies to the edited mesh), and `"reset":true` returns to the bind pose exactly. `"merge":true` keeps the joints already posed and sets only the ones given; otherwise the rotations replace the whole pose. `join` keeps the pose when every part has the same one (else it warns and the result is in bind pose); `auto_weights` / `transfer_weights` onto another skeleton clear it, with a warning. Bending the arm weighted above at its elbow: ```json {"op":"pose","object":"arm","rotations":{"lower":[60,0,0]}} ``` Result: `"pose":{"skeleton":"arm_rig","rotations":{"lower":[60,0,0]},"bbox":{...},"bind_bbox":{...},"max_offset":1.02,"volume":0.24,"closed":true}`: `bbox` is the posed box, `bind_bbox` the rest pose's, `max_offset` the farthest any vertex moved (0 means the pose moved nothing), and `volume` / `closed` the posed mesh's. ```json {"op":"pose","object":"arm","rotations":{"upper":[0,0,15]},"merge":true} ``` ```json {"op":"export_glb","objects":["arm"],"pose_clip":true,"path":"out/arm_posed.glb"} ``` ```json {"op":"pose","skeleton":"arm_rig","rotations":{"lower":[30,0,0]}} ``` ```json {"op":"pose","skeleton":"arm_rig","reset":true} ``` Warnings: a posed joint that moves no vertex (no weight on it or below it: tips and helpers; rotate the parent), other objects bound to the same skeleton that are not in the same pose (pose a body's clothes too, or pose by `skeleton`), and a pose that cannot show because a modifier dropped the skin weights (also in `query`). Errors: `invalid_argument` with a hint: field `object` (not skinned: run `auto_weights` first; or neither `object` nor `skeleton`), `skeleton` (both given, no such skeleton, or nothing bound to it), `rotations` (a joint the skeleton does not have: the hint lists the joints and the nearest names; no joints given; a non-finite angle), `reset` (with rotations or merge). ## Batches ```json [ {"op":"create_primitive","kind":"cube","name":"a"}, {"op":"select","object":"a","select":{"faces_facing":[0,1,0]}}, {"op":"transform","object":"a","translate":[0,0.5,0]} ] ``` ## Error codes `meshforge ops --all` (or `meshforge::command::schema::ops_schema()`) gives every op's fields with types, defaults and ranges, the selector keys and these codes with their fields, generated from the parser. | code | meaning | |---|---| | `parse` | not JSON, unknown `op`, unknown or missing field, wrong type; `field` is the full path of the bad key (`noise.seed`, `modifier.count`, `select.max_angle_deg`) and `expected` its type (`int`, `number[3]`, or for an unknown modifier type `one of subdivide, mirror, ...`; a number outside the field's bound adds it: `"expected":"int, count >= 1"` for `"count":-3`): `{"code":"parse","field":"noise.seed","expected":"int","message":"invalid command: noise.seed: invalid type: string \"x\", expected u32 (expected int)"}` | | `unknown_object` | no such object; `available` lists the names | | `object_exists` | the name is taken; `free_name` is one that is free (`"crate.1"`, `"crate.2"`, ...) | | `face_not_found`, `vertex_not_found` | a bad id; the message gives the valid range | | `edge_not_found` | the two vertices are not joined by an edge | | `empty_selection` | the command needs a selection (or explicit ids) | | `invalid_argument` | a value is out of range; `field` and `reason` say which, `valid_range` what is accepted (from the field's own bound where it has one: `set_modifier` `"set":{"count":-1}` gives `"field":"set.count","reason":"must be a whole number with count >= 1, got -1","valid_range":"count >= 1"`), `hint` what to do | | `budget_exceeded` | the command (or import) would make more than `max_faces` faces in one object (`"limit_kind":"object"`), or with `"limit_kind":"total"` push all objects past `max_total_faces`; `estimated_faces`, `limit`, `field` (the argument to lower) and `hint`; nothing was allocated. `auto_weights` / `transfer_weights` use `"limit_kind":"weights"`: live vertices x deforming joints over a fixed cap of 67108864 (`estimated_faces` holds that product) | | `not_implemented` | the op is part of the API but not in this build yet | | `unsupported_op` | this meshforge build was compiled without the cargo feature the op needs (`boolean` needs `boolean`, `uv_unwrap` needs `uv`, `decimate` needs `decimate`); `op`, `feature` and `hint` say which; nothing changed | | `op_failed` | the kernel refused the edit; `reason` says why | | `check_failed` | a check's `require` was not met (`check_contacts`); `reason` says what, `failures` lists `{object, problem, detail, fix}` per object (`fix`: a ready command or batch); nothing changed, and a batch that ends in the check changes nothing either | | `import`, `export` | file decoding / encoding failed | | `unknown_checkpoint` | no checkpoint has that name; `available` lists them | | `checkpoint_limit` | a new checkpoint would go over the checkpoint memory cap (`"limit_kind":"memory"`) or count (`"count"`); `would_hold`, `limit`, `checkpoints` (largest first); nothing changed, drop one with `drop_checkpoint` | | `nothing_to_undo`, `nothing_to_redo` | the undo / redo history is empty | | `internal` | a kernel bug; the command was rolled back | ================================================================ FILE: docs/partii-runtime.md SOURCE: https://github.com/PartiiGames/meshforge/blob/main/docs/partii-runtime.md ================================================================ # meshforge in Partii games (runtime) For Lindii and other agents writing Partii games. meshforge is a modelling kernel (Rust compiled to wasm, CPU only, MIT OR Apache-2.0). In a game it builds and edits meshes while the game runs and hands them to three.js. This page documents **meshforge 0.4.0**. ## Changes in 0.4.0 (upgrading from 0.3.1) New: `pose` (bend a rigged object), placement (`place`, `align`, `check_contacts`), fitting (`shrinkwrap`, `snap_to_surface`, `check_poke_through`), `rename_object`, a scene `query` (`objects: "*"`), and faster shape ops (lathe, sweep, helix, text, arrays). What can break a 0.3.1 game: * **`auto_weights` default output changed:** each joint's weight now stays local (a reach cap along the surface plus bone visibility), so weights differ from 0.3.1. `profile: "hlab"` gives the 0.3.1 result exactly. * **`{"op":"query"}` with no object** returns the scene table (`query.scene`, one row per object); `include: ["objects"]` gives the old object/skeleton listing. * **Brief `query` replies are leaner:** `counts` drops `edges`, and a `bbox` already in that reply's `objects` summary is left out. * **Limits:** `create_text` `size`/`depth` must be 0.0001 to 10000; bevel `width` 0 to 1000000. * **`revolve`** reads a profile whose last point repeats the first as closed (on the axis: dropped, profile stays open). * **Versions:** `info.version` and `info.crateVersion` are both `"0.4.0"`. ## Changes in 0.3.1 (upgrading from 0.3.0) New: rigging commands (`create_skeleton`, `auto_weights`, `transfer_weights`; see `docs/command-api.md`), cube `size: [x, y, z]`, `query` `include: ["volume"]` (area, closed, volume) and `"valid"`. What can break a 0.3.0 game: * **Brief replies changed shape** (only with `reply: "brief"` or `default_reply: "brief"`; runtime replies stay full by default). Floats are rounded (5 digits; 7 in `query`; boxes outwards); `objects` lists only objects the call changed (none after a `query` or `select`); in a batch, lines that only echo the request are dropped, `applied` counts the commands that ran and each kept line has its `index`; `undo` (the undo depth) is gone. Fix: compare floats with a tolerance, read sizes from `query`, find lines by `index`. * **A failed brief batch keeps what ran before the failing command** and says `rolled_back: false` (see "Short replies"). Fix: `s.undo()` it if you want none of it. * **`transform` with nothing selected** (no `target`, `faces` or `vertices`) moves the whole object and warns, where it failed with `empty_selection`. * **Versions:** `info.version` and `info.crateVersion` were both `"0.3.1"`. ## Changes in 0.3.0 (upgrading from 0.2.0) New ops: see "New in 0.3.0". What can break a 0.2.0 game: * **bevel's `select` is an `EdgeSelector`** (meshforge.d.ts; also `loop_cut`'s `select` and `uv_unwrap`'s `seams_select`): exactly one of `sharper_than_deg`, `all: true` or `edges` (see "Tags and edge selectors"). 0.2.0 JSON (`{ sharper_than_deg: 30 }`, `{ all: true }`) still works; a bad selector (no key, two keys, `all: false`) now fails with `parse` (was `invalid_argument`), `field` `"select"`. Fix: type selectors as `EdgeSelector` and handle `parse`. * **Versions:** `info.version` and `info.crateVersion` are both `"0.3.0"`. * **Bigger download:** the full wasm is 1.09 MB gzip (0.2.0: 892 KB); load it once at start-up. * **Runtime replies stay full** (only CLI batches went brief; see "Short replies"), with one exception: a parse error leaves out `detail` (the parser's text) and an `expected` that lists the allowed values, as `message` carries both. ## Runtime or CLI? * **Runtime (this page):** geometry that changes while someone plays: building toys, level editors, procedural props, cutting holes, LODs. * **CLI (`meshforge apply`, docs/cli.md):** props you can make once, offline: ship the .glb (no wasm download for players), and preview and check it there. ## Import and init Partii hosts each release in its own folder, `https://api.partii.games/_partii/meshforge//`: `meshforge.js` (the API, full build) and `meshforge-weights.js` (weights-only, see the last section), plus the files they load, `meshforge.d.ts` (types for every command and reply) and `PIN.json` (sha256 and size of every file). The import map maps the bare specifier `"meshforge"` to a release's `meshforge.js`. Partii's import map has `three` but **no `three/addons/`** (no OrbitControls or GLTFLoader; see `examples/partii-jam/game.js`). **Pinning a version:** the folder name is the pin. A version folder never changes (it is served `immutable`) and there is no `latest` alias, so a game keeps its version until you change the URL; to upgrade, change the folder, read "Changes in ..." above and re-test. Check at start-up which one you got (`meshforge.version` is known before `init()`; `info.crateVersion` is the Rust crate inside, the same for 0.4.0): ```js import * as THREE from "three"; import meshforge from "meshforge"; const info = await meshforge.init(); // fetches and compiles the .wasm once; safe to call again console.log(info.version, info.crateVersion); // "0.4.0" "0.4.0" console.log(meshforge.version === "0.4.0"); // true ``` The import-map entries Partii uses: ```text "meshforge": "https://api.partii.games/_partii/meshforge/0.4.0/meshforge.js", "meshforge-weights": "https://api.partii.games/_partii/meshforge/0.4.0/meshforge-weights.js" ``` ### If init fails A failed static `import` takes the whole game down. If the game can run without live modelling, import dynamically and fall back to prebuilt .glb files; `init()` rejects with `init_failed` and can be retried. ```js let live = null; // the meshforge API, or null: use prebuilt .glb files for (let attempt = 1; attempt <= 2 && !live; attempt++) { try { const m = (await import("meshforge")).default; await m.init(); live = m; } catch (err) { console.warn(`meshforge init attempt ${attempt} failed:`, err.code ?? err.message); } } if (!live) { // Load the prebuilt .glb files with three's GLTFLoader instead. } console.log(live === meshforge); // true ``` ## Sessions and commands A session holds named objects. `s.apply(command)` runs one command (or an array) and returns the reply. **It never throws on a bad command:** check `ok`; a failed command changes nothing. All commands: `docs/command-api.md`, `meshforge.schema()`, `meshforge.d.ts`. ```js const s = meshforge.session({ maxFaces: 5000, maxTotalFaces: 20000 }); // phone budgets, see "Budgets" const r = s.apply({ op: "create_primitive", kind: "cube", name: "crate", size: 1 }); if (!r.ok) throw new Error(`${r.error.message} (${r.error.hint})`); console.log(r.result.counts); // {vertices: 8, edges: 12, faces: 6} ``` **Undo:** `s.undo()` / `s.redo()`; **a batch (`s.apply([...])`) is one undo step**. ## The 10 commands you will use most Y is up; place shapes with `center`. `select` picks geometry by direction, region or tag, and edits act on the selection. **Check `ok` on every call:** `check` below throws so a mistake shows at once. ```js const check = (r) => { if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message} Fix: ${r.error.hint}`); return r; }; // 1. create_primitive: cube, grid, uv_sphere, cylinder, cone, torus, capsule; `center` places it check(s.apply({ op: "create_primitive", kind: "cylinder", name: "post", radius: 0.1, height: 1, segments: 16, center: [1, 0, 0] })); // 2. select + 3. extrude: pull the crate's top up into a lid check(s.apply({ op: "select", object: "crate", select: { faces_facing: [0, 1, 0] } })); check(s.apply({ op: "extrude", object: "crate", distance: 0.1 })); // 4. transform: moves, turns or scales the selection (or the whole object with target "object") check(s.apply({ op: "transform", object: "post", target: "object", rotate_deg: [0, 0, 10] })); // 5. inset: a panel on the front face (thickness must fit inside the face) check(s.apply({ op: "select", object: "crate", select: { faces_facing: [0, 0, 1] } })); check(s.apply({ op: "inset", object: "crate", thickness: 0.04, depth: -0.03 })); // 6. bevel: round the crate's hard edges check(s.apply({ op: "bevel", object: "crate", select: { sharper_than_deg: 60 }, width: 0.03, segments: 2 })); // 7. boolean: drill a hole (both objects must be closed). One batch, so one undo step. check(s.apply([ { op: "create_primitive", kind: "cylinder", name: "drill", radius: 0.15, height: 3, segments: 24 }, { op: "transform", object: "drill", target: "object", rotate_deg: [90, 0, 0] }, { op: "boolean", object: "crate", with: "drill", mode: "difference" }, { op: "delete_object", object: "drill" }, ])); // 8. set_material: colours are linear RGB(A), 0..1 check(s.apply({ op: "set_material", object: "crate", name: "wood", color: [0.55, 0.38, 0.2], roughness: 0.8 })); check(s.apply({ op: "set_material", object: "post", name: "metal", color: [0.6, 0.6, 0.65], metallic: 1, roughness: 0.3 })); // 9. add_modifier: non-destructive (subdivide, array, mirror, bevel, solidify, ...) check(s.apply({ op: "add_modifier", object: "post", modifier: { type: "array", count: 4, offset: [0.3, 0, 0] } })); // 10. undo / redo: every geometry command is undoable check(s.apply({ op: "create_primitive", kind: "torus", name: "oops" })); check(s.undo()); console.log(s.objects()); // ["crate", "post"] ``` Other handy ones: `duplicate`, `join`, `mirror`, `subdivide`, `uv_unwrap`, `decimate`, `query` (counts, bbox, faces, validate), `export_glb`. A boolean's walls take the cutter's material, or the target's if the cutter has none. ## Checking what you made The runtime has **no preview**: check with numbers. `query` returns counts, the bounding box and a validation report; replies can carry `warnings`. ```js const reply = check(s.apply({ op: "query", object: "crate", include: ["counts", "bbox", "validate"] })); const q = reply.result.query; console.log(q.validate.valid, q.counts.boundary_loops, q.counts.triangles); // true 0 348 console.log(q.bbox.size.map((x) => +x.toFixed(2))); // [1, 1.1, 0.99] console.log(reply.result.warnings ?? []); // [] ``` `validate.valid` false, open boundary loops on a closed prop, or a box of the wrong size mean: stop and fix the commands. End a build with the contact lint, so no part floats (a bridge, its rails and a house must stand on something; `place` puts them there). Unlike the CLI, where a failed batch lands nothing, the runtime keeps what ran before the failing check (`rolled_back: false`): `s.undo()` it, or run each failure's `fix` and check again. ```js // This block fails on purpose: a rail floats 4 cm above its deck. const site = meshforge.session({ maxFaces: 5000 }); const lint = { op: "check_contacts", require: { floating: 0 } }; const built = site.apply([ { op: "create_primitive", kind: "cube", name: "deck", size: [4, 0.2, 1.5], center: [0, 0.1, 0] }, { op: "create_primitive", kind: "cube", name: "rail", size: [4, 0.5, 0.05], center: [0, 0.49, 0.7] }, lint, ]); console.log(built.error.code); // "check_failed" for (const f of built.error.failures) if (f.fix) site.apply(f.fix); console.log(site.apply(lint).ok); // true site.free(); ``` For props made ahead of time, use the CLI (`meshforge preview`, `meshforge validate`). ## New in 0.3.0 ### The new ops at a glance Shape ops (`helix` to `create_text`) make new, tagged, closed objects (unless `caps: false` or a partial `revolve`) and check the face budget first. Geometry ops are one undo step each; `load_font` and checkpoints are not. All fields: `meshforge.schema()` or `docs/command-api.md`. | op | makes | key fields | |---|---|---| | `tag` / `untag` | your own face tags | `object`, `name`, `faces` | | `array` | row, grid or ring of copies | `count`, `offset`; `count2`/`offset2`, `count3`/`offset3`; ring: `axis`, `angle_deg`, `rotate_copies` | | `helix` | a spring, or a path | `radius`, `pitch`, `turns`, `tube_radius`; `output: "path"` | | `thread` | a threaded rod along Y | `radius`, `length`, `pitch`, `depth` | | `sweep` | an outline along a path | `profile` `[[x,y]]`, `path` `[[x,y,z]]`, `closed`, `smooth`, `twist_deg`, `scale` | | `pipe` (`tube`) | a rod or hollow tube | `path`, `radius`, `inner_radius`, `smooth` | | `revolve` (`lathe`) | a profile spun round an axis | `profile` `[[r,y]]`, `segments`, `angle_deg`, `axis` | | `loft` | a skin over sections | `sections: [{ points, y, scale, offset, rotate_deg }]` | | `create_text` | 3D letters | `text`, `size`, `depth`, `bevel`, `align`, `font`, `per_glyph` | | `load_font` | a TrueType font | `name`, `data` (base64) | | `import_stl` / `export_stl` | STL (base64) | `data` / `objects`, `z_up` | | `checkpoint` / `restore` / `list_checkpoints` / `drop_checkpoint` | save points | `name` | The examples below run in one session with phone budgets. ```js const p = meshforge.session({ maxFaces: 5000, maxTotalFaces: 20000 }); ``` ### Tags and edge selectors: name faces, not ids Faces carry **tags** that follow them through edits: `top`, `bottom`, `side`, `front`, `back`, `left`, `right`, `cap`, `extruded`, `extrude_wall`, `inset`, `inset_wall`, `bevel`, `cut_wall` (a hole's walls), `inner`, `cap_start` / `cap_end`, and `cap_top` / `cap_bottom` (both `cap` and `top` / `bottom`). Select with `{ tag: "top" }`; add your own with `tag`; `query` `include: ["tags"]` counts them. **Edge selectors** (`bevel`, `loop_cut`, `uv_unwrap` seams), exactly one of: `{ edges: "border", of: }`, `{ edges: "between", a, b }`, `{ edges: "vertical" | "horizontal", within_deg? }`, `{ edges: "boundary" }`, `{ sharper_than_deg: 30 }`, `{ all: true }`. ```js // This block fails on purpose: an edge selector takes exactly one key. check(p.apply({ op: "create_primitive", kind: "cube", name: "probe", size: 0.2, center: [-2, 0, 0] })); const twoKeys = p.apply({ op: "bevel", object: "probe", select: { sharper_than_deg: 30, all: true }, width: 0.01 }); console.log(twoKeys.ok, twoKeys.error.code, twoKeys.error.field); // false "parse" "select" check(p.apply({ op: "delete_object", object: "probe" })); ``` ### Example: a vase (revolve, tags, bevel by rule) ```js // [r, y] points: r is the distance from the Y axis. r = 0 at the start closes the bottom. check(p.apply({ op: "revolve", name: "vase", profile: [[0, 0], [0.3, 0], [0.4, 0.3], [0.22, 0.8], [0.25, 1]], segments: 24 })); // Hollow it: the lid face is tagged cap_top. Inset it, push it down, round the rim. check(p.apply({ op: "select", object: "vase", select: { tag: "cap_top" } })); check(p.apply({ op: "inset", object: "vase", thickness: 0.06 })); check(p.apply({ op: "extrude", object: "vase", distance: -0.85 })); check(p.apply({ op: "bevel", object: "vase", select: { edges: "border", of: { tag: "inset_wall" } }, width: 0.008, segments: 2 })); check(p.apply({ op: "set_material", object: "vase", name: "clay", color: [0.7, 0.35, 0.2], roughness: 0.9 })); const vase = check(p.apply({ op: "query", object: "vase", include: ["validate", "tags", "counts"] })).result.query; console.log(vase.validate.valid, vase.counts.boundary_loops, vase.tags.extruded, vase.tags.inset_wall); // true 0 1 24 ``` ### Example: a fence (pipe, array grid, sweep) ```js // Posts: one cylinder, then a grid of 5 x 2 copies. check(p.apply({ op: "create_primitive", kind: "cylinder", name: "post", radius: 0.04, height: 1, segments: 12, center: [0, 0.5, 0] })); check(p.apply({ op: "array", object: "post", count: 5, offset: [0.5, 0, 0], count2: 2, offset2: [0, 0, 1.5] })); // A rail along the posts' tops that turns the corner, rounded with smooth. check(p.apply({ op: "pipe", name: "rail", path: [[0, 1, 0], [2, 1, 0], [2, 1, 1.5], [0, 1, 1.5]], radius: 0.03, segments: 12, smooth: 6 })); // A flat board along the bottom: a rectangle swept along a path. check(p.apply({ op: "sweep", name: "plank", profile: [[-0.01, -0.06], [0.01, -0.06], [0.01, 0.06], [-0.01, 0.06]], path: [[0, 0.2, 0], [2, 0.2, 0], [2, 0.2, 1.5], [0, 0.2, 1.5]] })); const fence = check(p.apply({ op: "query", object: "post", include: ["counts"] })).result.query; console.log(fence.counts.shells); // 10 ``` `array` with `axis` makes a ring (`rotate_copies: false`: stool legs). Springs and bolts: ```js check(p.apply({ op: "helix", name: "spring", radius: 0.1, pitch: 0.05, turns: 5, tube_radius: 0.01, center: [3, 0, 0] })); check(p.apply({ op: "thread", name: "bolt", radius: 0.05, length: 0.3, pitch: 0.03, segments: 16, rows_per_pitch: 6, center: [3.5, 0.15, 0] })); check(p.apply({ op: "create_primitive", kind: "cylinder", name: "head", radius: 0.08, height: 0.06, segments: 6, center: [3.5, 0.33, 0] })); check(p.apply({ op: "join", objects: ["bolt", "head"] })); ``` ### Example: a sign (create_text, load_font, loft) `create_text`'s built-in blocky font has A-Z a-z 0-9 and basic punctuation; letters face +Z, `size` is the capital height. ```js check(p.apply({ op: "create_primitive", kind: "cube", name: "board", size: 1, center: [0, 1.2, 0] })); check(p.apply({ op: "transform", object: "board", target: "object", scale: [1.4, 0.5, 0.06] })); check(p.apply({ op: "create_text", name: "word", text: "OPEN", size: 0.25, depth: 0.04, bevel: 0.005, center: [0, 1.2, 0.04] })); check(p.apply({ op: "set_material", object: "word", name: "paint", color: [0.95, 0.8, 0.2] })); // A tapered post: two square sections, the top one smaller. check(p.apply({ op: "loft", name: "signpost", sections: [{ points: [[-0.05, -0.05], [0.05, -0.05], [0.05, 0.05], [-0.05, 0.05]], y: 0 }, { scale: 0.6, y: 0.95 }] })); const word = check(p.apply({ op: "query", object: "word", include: ["bbox"] })).result.query; console.log(word.bbox.size.map((x) => +x.toFixed(2))); // [0.82, 0.25, 0.04] ``` Your own font: `load_font` takes a **TrueType** font (`.ttf`, or `.otf` with TrueType outlines) as base64 `data`. None ship with meshforge: use one whose licence lets you ship it. ```js const fetchBytes = async (url) => new Uint8Array(await (await fetch(url)).arrayBuffer()); const toBase64 = (bytes) => { let bin = ""; for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(bin); }; const font = check(p.apply({ op: "load_font", name: "sign", data: toBase64(await fetchBytes("assets/sign.ttf")) })).result.font; console.log(font.family, font.loaded); // "Syncopate" ["sign"] check(p.apply({ op: "create_text", name: "title", text: "Mill", font: "sign", size: 0.2, depth: 0.03, center: [0, 1.6, 0] })); ``` **CFF (PostScript) fonts** (most `.otf`) are refused; convert them to TrueType (e.g. with fonttools) or pick a `.ttf`. ```js // This block fails on purpose: a font with CFF outlines is refused. const cff = p.apply({ op: "load_font", name: "fancy", data: toBase64(await fetchBytes("assets/fancy-cff.otf")) }); console.log(cff.ok, cff.error.code, cff.error.field); // false "invalid_argument" "font" console.log(cff.error.hint.includes("convert with fonttools")); // true ``` ### STL in and out `export_stl` returns a binary STL as base64; `import_stl` reads binary or ASCII STL and welds it into an editable mesh. `z_up: true` converts for 3D printing and CAD. ```js const stl = check(p.apply({ op: "export_stl", objects: ["vase"] })).result; const stlBytes = Uint8Array.from(atob(stl.stl_base64), (c) => c.charCodeAt(0)); // e.g. to download console.log(stlBytes.length === stl.stl_bytes); // true const back = check(p.apply({ op: "import_stl", name: "vase_copy", data: stl.stl_base64 })).result; console.log(back.import.watertight, back.import.triangles === stl.stats.tris); // true true check(p.apply({ op: "delete_object", object: "vase_copy" })); ``` ### Short replies `reply: "brief"` on a command (or `{ op: "set_limits", default_reply: "brief" }` for the session) makes each command answer in one short line, and the reply end with a summary per object changed (`tris`, `shells`, `boundary_loops`, `bbox`; floats rounded, boxes outwards). A failed brief batch keeps what ran before the failing command and says `rolled_back: false` (`s.undo()` reverts it); `check` works on both; base64 payloads are elided (use `exportGlb()` for bytes). ```js const lamp = [ { op: "create_primitive", kind: "cylinder", name: "lamp", radius: 0.05, height: 0.6, segments: 12, center: [5, 0.3, 0] }, { op: "select", object: "lamp", select: { tag: "top" } }, { op: "extrude", object: "lamp", distance: 0.1 }, ]; const full = check(p.apply(lamp)); check(p.undo()); const brief = check(p.apply(lamp.map((c) => ({ ...c, reply: "brief" })))); console.log(brief.objects[0].name, brief.objects[0].shells, brief.objects[0].bbox); // "lamp" 1 [[4.95, 0, -0.05], [5.05, 0.7, 0.05]] console.log(JSON.stringify(brief).length * 4 < JSON.stringify(full).length); // true ``` ### Checkpoints: try an edit, keep it or go back `checkpoint` saves the whole scene by name; `restore` brings it back (one undo step; the checkpoint stays). Cheap (unchanged objects are shared) and bounded (512 MB, 64; over fails with `checkpoint_limit`). Use them instead of counting undo steps. ```js check(p.apply({ op: "set_limits", default_reply: "brief" })); // every reply short from here on check(p.apply({ op: "create_primitive", kind: "cube", name: "chest", size: 0.6, center: [6, 0.3, 0] })); check(p.apply({ op: "checkpoint", name: "plain_chest" })); // Try a big round bevel ... const tryRound = check(p.apply({ op: "bevel", object: "chest", select: { all: true }, width: 0.2, segments: 4 })); console.log(tryRound.objects[0].tris > 100); // true // ... too soft for a chest: go back and bevel only the upright corners. check(p.apply({ op: "restore", name: "plain_chest" })); const kept = check(p.apply({ op: "bevel", object: "chest", select: { edges: "vertical" }, width: 0.03, segments: 2 })); console.log(kept.objects[0].tris, kept.objects[0].boundary_loops); // 44 0 console.log(check(p.apply({ op: "list_checkpoints" })).result.checkpoints.list.map((c) => c.name)); // ["plain_chest"] check(p.apply({ op: "drop_checkpoint", name: "plain_chest" })); p.free(); // done with this session (see "Dispose what you are done with") ``` An unknown name fails with `unknown_checkpoint` (`available` lists the names). ### The schema, for tool definitions `meshforge.schema()` returns every op with its typed fields (type, required, default, range, enum, doc), an example and a summary, plus the selector, edge selector, modifier and error-code tables. ```js const schema = meshforge.schema(); const revolveSpec = schema.ops.find((o) => o.op === "revolve"); console.log(revolveSpec.fields.filter((f) => f.required).map((f) => f.name)); // ["profile"] console.log(schema.edge_selector.edges_rules); // ["border", "between", "vertical", "horizontal", "boundary"] ``` JSON Schema or GBNF for tool definitions: `meshforge ops --format json-schema|gbnf` (CLI, docs/cli.md). ## Show it in three.js `meshData` returns indexed triangles (normals as in a glb export, grouped by material, modifiers applied; `unknown_object` throws). `toThree` makes a `THREE.Mesh` with one `MeshStandardMaterial` per group, from the THREE you pass in. Light the scene from every side, or faces seen from below render black: a `HemisphereLight` with a light ground colour (e.g. `0xe6ebf5, 0x8c8a84`), a sun, a soft fill `DirectionalLight` from below and behind, and for metals an environment (`RoomEnvironment` through `PMREMGenerator`, where `three/addons/` is available), as `examples/partii-jam/game.js` and `web/app.js` do. ```js const scene = new THREE.Scene(); let crateMesh = meshforge.toThree(THREE, s.meshData("crate")); scene.add(crateMesh); // After more edits, update the same mesh in place (old geometry and materials are disposed): check(s.apply({ op: "select", object: "crate", select: { faces_facing: [0, 1, 0] } })); check(s.apply({ op: "extrude", object: "crate", distance: 0.05 })); meshforge.toThree(THREE, s.meshData("crate"), { mesh: crateMesh }); ``` **Picking a face:** `mesh.userData.triFaces[hit.faceIndex]` is the meshforge face id. With modifiers, pick on `s.meshData(name, { cage: true })`. ```js const ray = new THREE.Raycaster(new THREE.Vector3(0, 5, 0), new THREE.Vector3(0, -1, 0)); crateMesh.updateMatrixWorld(); const hit = ray.intersectObject(crateMesh)[0]; const faceId = crateMesh.userData.triFaces[hit.faceIndex]; check(s.apply({ op: "extrude", object: "crate", faces: [faceId], distance: 0.05 })); ``` ## Heavy work in a Worker Big booleans, bevels, decimate and auto-weights can take longer than a frame. `meshforge.worker()` runs the same API in a Worker, every method returning a Promise; write `await` everywhere and the code works on both. ```js const mf = await meshforge.worker(); const ws = await mf.session({ maxFaces: 5000 }); check(await ws.apply([ { op: "create_primitive", kind: "uv_sphere", name: "ball", segments: 32, rings: 16 }, { op: "create_primitive", kind: "cube", name: "cutter", size: 1, center: [0.6, 0.6, 0] }, { op: "boolean", object: "ball", with: "cutter", mode: "difference" }, ])); const ballMesh = meshforge.toThree(THREE, await ws.meshData("ball")); scene.add(ballMesh); const glb = await ws.exportGlb("ball"); // Uint8Array, e.g. to save await ws.free(); mf.terminate(); ``` The worker starts as a same-origin `blob:` module, so it works from Partii's shared origin; if a CSP blocks `blob:` workers, `worker()` rejects with `worker_error`: use the main-thread API. ## Dispose what you are done with The garbage collector frees neither meshforge memory nor three.js GPU buffers. Dispose a removed mesh's geometry and materials (`toThree(..., { mesh })` does it when it replaces them), `s.free()` sessions (using one afterwards throws `freed`), `mf.terminate()` workers. Wasm memory never shrinks but freed memory is reused; `meshforge.memoryBytes()` shows leaks. ```js scene.remove(ballMesh); ballMesh.geometry.dispose(); for (const m of ballMesh.material) m.dispose(); const scratch = meshforge.session({ maxFaces: 5000 }); check(scratch.apply({ op: "create_primitive", kind: "cube", name: "tmp" })); scratch.free(); try { scratch.apply({ op: "query" }); } catch (err) { console.log(err.code); // "freed" } ``` ## Budgets Sessions cap faces per object (`maxFaces`, default 200000) and in all (`maxTotalFaces`, default 1000000). Going over fails **before** allocating, with `budget_exceeded`, and changes nothing. **On phones** use `{ maxFaces: 5000, maxTotalFaces: 20000 }` (faces, not triangles: read `stats.tris`). Bad options throw `invalid_argument`; they never fall back silently. ```js // This block fails on purpose: it shows the budget error. const small = meshforge.session({ maxFaces: 2000 }); const b = small.apply({ op: "create_primitive", kind: "uv_sphere", name: "huge", segments: 256, rings: 128 }); console.log(b.ok, b.error.code, b.error.limit, b.error.limit_kind, b.error.field); // false "budget_exceeded" 2000 "object" "segments" console.log(b.error.hint); // "lower segments/rings; or raise the limit (2000) with meshforge.session({ maxFaces: N }), or s.apply({\"op\":\"set_limits\",\"max_faces\":N}) before this command" console.log(small.limits()); // {maxFaces: 2000, maxTotalFaces: 1000000, totalFaces: 0} small.free(); try { meshforge.session({ max_faces: 10 }); } catch (err) { console.log(err.code, err.error.hint.startsWith("did you mean 'maxFaces'?")); // "invalid_argument" true } ``` ## Errors Failed replies carry `error.code` (`ErrorCode` in meshforge.d.ts), `message`, and when they apply `field`, `valid_range`, `reason`, `expected` and `hint` (what to do instead, often with an example). **Read `error.hint` first**; nothing changed. In a batch, `failed_index` names the failed command; the ones before it stayed applied. ```js // This block fails on purpose: it shows the error replies. const e = s.apply({ op: "create_primitive", kind: "cube", name: "box2", sise: 1 }); console.log(e.ok, e.error.code, e.error.hint.split("?")[0]); // false "parse" "did you mean 'size'" const batch = s.apply([ { op: "create_primitive", kind: "cube", name: "a" }, { op: "extrude", object: "nope", distance: 1 }, ]); console.log(batch.failed_index, batch.error.code, batch.error.message.split(":")[0]); // 1 "unknown_object" "command 1 (extrude) failed" check(s.undo()); // the batch's first command stayed applied; one undo removes it ``` Calls that return data throw `MeshforgeError` (`code`, `error`): `unknown_object`, `invalid_argument`, `freed`, `not_initialized`, `init_failed`. ```js // This block fails on purpose: exportGlb throws for a name that does not exist. try { s.exportGlb("nope"); } catch (err) { console.log(err instanceof meshforge.MeshforgeError, err.code); // true "unknown_object" } ``` ## Performance Timings for 0.3.0 in headless Chromium: docs/releases/0.3.0.md, "Runtime performance" (`node web/runtime/test/jam-headless.mjs` prints them). Tips: batch commands in one `apply([...])` call; call `meshData` once per frame at most, only for objects in `changed_objects`; reuse the mesh with `toThree(THREE, data, { mesh })`; keep budgets low; `s.free()` sessions you are done with. ## Characters: the weights-only build For skinning only, import `meshforge-weights.js` (a third of the download; `session()` throws `not_in_build`). Weights calls take glb bytes and return `{ok, ..., glb}`; the full build has them too. **Only skin clothed characters or props.** A character you pass to `autoWeights` must keep at least its base clothing layer; never skin, show or export a bare body. ```js import weights from "meshforge-weights"; await weights.init(); // Your game's own files (any URL): fetch them as bytes. const load = async (url) => new Uint8Array(await (await fetch(url)).arrayBuffer()); const characterGlb = await load("assets/character.glb"); // the mesh to skin: a clothed character or a prop const rigGlb = await load("assets/rig.glb"); // any glb with a skin: its skeleton is used const scarfGlb = await load("assets/scarf.glb"); // something worn with the character const skinned = check(weights.autoWeights(characterGlb, rigGlb)); console.log(skinned.ok, skinned.joints, skinned.glb.length > 0); // true 3 true // Copy the character's weights onto a garment or prop worn with it: const worn = check(weights.transferWeights(skinned.glb, scarfGlb, {})); console.log(worn.ok); // true // LODs need the full build: meshforge.decimate(glb, { ratio: 0.5 }). const lod = check(meshforge.decimate(skinned.glb, { ratio: 0.5 })); console.log(lod.ok, lod.glb.length < skinned.glb.length); // true true ``` Load the result with GLTFLoader from your game's own dependencies. These calls are heavy: run them in `meshforge.worker()` (`await mf.autoWeights(...)`).