This 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. Generated from docs/command-api.md. The same text, as plain text for agents: llms-full.txt.
Contents
- How it works
- Conventions
- What every result contains
- Brief replies
- Commands
- create_primitive
- rename_object
- delete_object
- select
- Tags
- transform
- extrude
- loop_cut
- subdivide
- mirror
- merge_by_distance
- decimate
- delete_faces
- bevel
- array
- solidify
- Modifiers
- add_modifier
- set_modifier
- move_modifier
- set_modifiers
- remove_modifier
- apply_modifier
- uv_unwrap
- query
- import_gltf
- import_obj
- export_glb
- helix
- thread
- import_stl
- export_stl
- set_limits
- inset
- displace
- set_material
- duplicate
- join
- undo / redo
- boolean
- checkpoint / restore / list_checkpoints / drop_checkpoint
- tag
- untag
- sweep
- pipe
- revolve
- loft
- create_text
- load_font
- create_skeleton / auto_weights / transfer_weights
- shrinkwrap / snap_to_surface / check_poke_through
- place / align / check_contacts
- pose
- Batches
- Error codes
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,resultsholds the results that succeeded andfailed_indexnames the command that failed.
- success:
- A failed command changes nothing. Read
error.message: it says what is wrong and what to do (for exampleface 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-1and0..vertices-1. (If a result ever says"renumbered":true, old ids are void; query again.) - You do not need ids. Use
selectto 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 withoutfaces/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
transformmoves them. - Undo covers every command that changes geometry or objects.
selectandqueryare not recorded. Undo restores the selection that went with the geometry. - Stored normals are dropped when geometry changes.
export_glbwrites normals per itsnormalsoption (defaultauto: 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, seeset_limits) it fails withbudget_exceededand 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 withbudget_exceeded(fielddata) 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 samebudget_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),joinwithoutkeep_sourcesreplaces 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 thatf32positions lose all precision and products of two of them overflow. Most larger arguments are aninvalid_argumentnaming them (e.g.size_y,center,distance,noise.frequency); the rest come back as fieldresult(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 withinvalid_argument, fieldresult, 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_glbonly),reverted,reapplied.glb_base64andstl_base64read"elided: reply full": ask with"reply":"full"for the bytesface_groups(sweep, pipe, revolve, loft) is left out: select parts by tag; apointspath over 64 points reads"elided (N): reply full"(path_lengthstays); - 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 aselect,closed: falseorassigned_faces: 0. A line carrying onlynew,deleted,material,assigned_faces,closed: true,new_tagsor (for ops other thanselect)selectedis dropped;renumbered(old ids are void) keeps it, and so donew/deletednames theobjectssummary leaves out. Then"applied":ncounts the commands that ran and each kept line carries itsindexin the batch. A batch where every line has news keeps them all, withoutappliedor 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 (aquery, aselect, atag) 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 noobjects. Thenredowhen there are steps to redo. The undo depth is not in brief replies (full results carryhistory); - floats are rounded: 5 significant digits on a line (
0.96282), 7 in aquerypayload; a box (bbox, ormin/max) is rounded outwards (min down, max up) to the digits of its own extent, so a 1.2 m part at x = 12345 reads12345.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 reads0. 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 itsindexin the batch; objectskeeps the last 32 summaries, after the same marker;- each list in a
querypayload (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
queryis lean:countshasvertices,faces,triangles,shellsandboundary_loops(noedges;vertex_slots/face_slotsonly when deleted ids leave holes, that is when they differ from the live counts;evaluatedwithoutedges), andbboxis left out when the reply'sobjectssummary carries the same box for that object (a box that changed after the query stays).
error and warnings are never cut.
{"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):
[
{"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).
{"op":"create_primitive","kind":"cube","name":"box","size":2}
{"op":"create_primitive","kind":"cube","name":"plank","size":[1.2,0.05,0.3],"center":[0,0.5,0]}
{"op":"create_primitive","kind":"cylinder","name":"pillar","radius":0.25,"height":3,"segments":24,"center":[2,1.5,0]}
{"op":"create_primitive","kind":"cone","name":"leaves","radius":0.6,"height":1.4,"segments":8,"center":[0,1.4,0]}
{"op":"create_primitive","kind":"torus","name":"tyre","radius":0.4,"minor_radius":0.12,"segments":24,"rings":12,"center":[3,0,0]}
{"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.
{"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
{"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).
{"op":"select","object":"box","select":{"faces_facing":[0,1,0],"within_deg":10}}
{"op":"select","object":"box","select":{"faces":[0,1]},"mode":"add"}
{"op":"select","object":"box","select":{"grow":1}}
{"op":"select","object":"box","select":{"in_box":{"min":[-2,0.9,-2],"max":[2,2,2]},"domain":"vertices"}}
{"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).
[
{"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":<face selector>} | 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":<face selector>,"b":<face selector>} | 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).
{"op":"transform","object":"box","translate":[0,0.5,0]}
{"op":"transform","object":"box","target":"object","rotate_deg":[0,45,0],"scale":[1,2,1],"pivot":"origin"}
{"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.
{"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.
{"op":"loop_cut","object":"box","edge":[0,2],"cuts":2}
{"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.
{"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).
{"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.
{"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).
{"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.
{"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 forloop_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.
[
{"op":"create_primitive","kind":"cube","name":"chest"},
{"op":"bevel","object":"chest","select":{"sharper_than_deg":30},"width":0.05,"segments":3}
]
{"op":"bevel","object":"chest","faces":[3],"width":0.02,"segments":2,"profile":0.25}
{"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.
{"op":"array","object":"chest","count":3,"offset":[1.5,0,0]}
[
{"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]}
]
[
{"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.
[
{"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).
[
{"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",...}.
{"op":"set_modifier","object":"rounded","index":0,"set":{"segments":4}}
{"op":"set_modifier","object":"rounded","index":0,"modifier":{"type":"bevel","width":0.1,"segments":4,"angle_deg":30}}
{"op":"set_modifier","object":"rounded","index":1,"enabled":false}
move_modifier
Moves the modifier at from to position to.
{"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.
{"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
{"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.
{"op":"apply_modifier","object":"rounded","index":0}
{"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 givenseams;seamscuts only alongseams(plus mesh boundaries; charts that are not disks are still cut);projectgroups faces by normal direction and projects each group flat (no solve: several times faster thanauto, 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 inlayer(default false).margin: gap between charts and to the border, UV units (default 0.005, max 0.2). The packer cannot keep a margin of1 / (1 + sqrt(n))or more betweenncharts (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) orconformal(least angle distortion).rotate:arbitrary(default),ninetyornone.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 about1 / 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 everyuv_qualityinput except one (cylinder_256x96packs 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.highgives 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, ...).
{"op":"uv_unwrap","object":"box","method":"auto","margin":0.01}
{"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).
{"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).
{"op":"query"}
{"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}]}.
{"op":"query","object":"chest","include":["modifiers"]}
{"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.
{"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).
{"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).
{"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.
{"op":"export_glb","objects":["box"],"normals":"flat","path":"out/box.glb"}
{"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.
{"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.)
{"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:
[
{"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.
{"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.
{"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.
{"op":"set_limits","max_faces":500000}
{"op":"set_limits"}
{"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.
[
{"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}
]
{"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.
{"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.
{"op":"set_material","object":"crate","name":"wood","color":[0.55,0.38,0.2],"metallic":0,"roughness":0.8}
{"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.
{"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.
{"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).
{"op":"undo"}
{"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.
{"op":"create_primitive","kind":"cube","name":"plate","size":1}
{"op":"create_primitive","kind":"cylinder","name":"drill","radius":0.2,"height":2,"segments":24}
{"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.
restorecosts nothing for objects that did not change since the checkpoint. (100k-triangle numbers: see the cost note below.) restoreis undoable: it is one undo step, andundoreturns to the scene before the restore. The checkpoint is kept, so you can restore it again. If the scene already matches,restorechanges nothing and warns.checkpointwith 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 withcheckpoint_limitand nothing changes; drop one withdrop_checkpointand 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. restorewarns when the restored scene is overmax_total_faces.- Checkpoints live in the session (and replay from a CLI
.mfssession file); they are not written to exported files.
{"op":"checkpoint","name":"before_bevel"}
{"op":"restore","name":"before_bevel"}
{"op":"list_checkpoints"}
{"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).
[
{"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.
{"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 alongup. 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": Nrounds 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, leavesmoothoff 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.
upsets where the profile's +y points at the start (default +Y, or +Z if the path starts along Y).twist_degadds 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;warnkeeps 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.
queryvalidatereports 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.
{"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}
{"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.
{"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}
{"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 = 0become 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), andtop+cap/bottom+capon 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
uaround,valong the profile's length; caps a disk.
{"op":"revolve","name":"vase","profile":[[0,0],[0.3,0],[0.4,0.3],[0.15,0.8],[0.2,1]],"segments":24}
{"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]}
{"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 ascaleper 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.
{"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}
{"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":"<name>").
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):\nstarts 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 xsizeapart.depth(0.2): extrusion along Z, centred on z = 0.align(center): each lineleft(starts at x = 0),centerorright(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) orbottom(last baseline at 0).letter_spacing(0, -1..=10): extra space between letters as a fraction ofsize; 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, namedname/0,name/1, ... in the order of the drawn characters (the text without whitespace, ortext.drawnwhen some are missing), so each letter can be moved, coloured or animated alone. The names are listed once, increated_objects. Default: one object.center([0,0,0]) moves the laid-out text;namedefaults totext, made unique.font(builtin): or thenameof aload_font.sizeis the font's cap height (from its OS/2 table, else the height ofH); its own advances andkernpairs space the letters.bevel(0): rounds or chamfers the front and back edges by this width (and depth); at most 0.45 xdepth(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_reducedlists 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 (fieldcurve_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).
{"op":"create_text","text":"OPEN","name":"sign","size":0.5,"depth":0.1}
{"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]}
{"op":"create_text","text":"WIN!","name":"title","per_glyph":true,"letter_spacing":0.1}
{"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.
{"op":"load_font","name":"sign","data":"AAEAAAAIAIAAAwAA..."}
{"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 <name>_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.
{"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.
[
{"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):
[
{"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.
[
{"op":"duplicate","object":"arm","name":"sleeve","scale":[1.1,1,1.1],"pivot":[0,1,0]},
{"op":"transfer_weights","object":"sleeve","from":"arm"}
]
{"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.
[
{"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}.
[
{"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 thanclearance(default 0; pass theoffsetyou 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).sampleslists the deepestlimit(default 5, at most 64) as{vertex, position, depth}, deepest first;depthis how far past the allowed surface the vertex is, andmax_depththe 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_pointslists up tolimitplaces 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":falseand a warning saycrossingsis 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.
{"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_maxsays 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 (withfulla 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.
[
{"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:
[
{"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 withintolerance(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, butdistanceapart.
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 transforms
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.
{"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:
{"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.
{"op":"pose","object":"arm","rotations":{"upper":[0,0,15]},"merge":true}
{"op":"export_glb","objects":["arm"],"pose_clip":true,"path":"out/arm_posed.glb"}
{"op":"pose","skeleton":"arm_rig","rotations":{"lower":[30,0,0]}}
{"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
[
{"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 |