3D engine that AI agents drive
Merge origin/main into feat/615-field-math; register rotation operators and hull modifiers lazily (issue #615)
Nguyen Xuan An87e0ba099cb9
diff --cc changes/615-field-math.size.mdindex b67e749b,00000000..d4007f1amode 100644,000000..100644--- a/changes/615-field-math.size.md+++ b/changes/615-field-math.size.md@@@ -1,8 -1,0 +1,3 @@@+- entry:mesh: rotation operators for fields, curve resample and fillet for instances, and the bounding box and convex hull modifiers are about 1.8 KB gzip of mesh code that agents cannot get any other way.- - entry:light-bake: it bundles the mesh code, so it carries the same 1.8 KB of new mesh operators.- - entry:light-bake-gpu: it bundles the mesh code, so it carries the same new mesh operators.- - entry:ground-bounce: it bundles the mesh code, so it carries the same new mesh operators.- - entry:floor-sky-visibility: it bundles the mesh code, so it carries the same new mesh operators.- - entry:water-reflection: it bundles the mesh code, so it carries the same new mesh operators.+- scene:agent-scene+lazy: the new mesh operators live in the lazy part, which holds the whole mesh engine.- - goal:agent-scene: the core grows 32 bytes for the operator names; the notes were shortened elsewhere to pay for the rest.++- goal:agent-scene: the core grows under 64 bytes for the operator names; the notes were shortened elsewhere to pay for the rest.diff --cc src/agent-scene-capabilities.jsindex 7b009472,27580b1a..07f35055--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@@ -181,8 -179,8 +181,8 @@@ export const AGENT_SCENE_CAPABILITIESgeometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, default 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its width and height. fStop (0.7 to 64) turns on depth of field focused on target; 1.4 or lower is full blur, and effects.depthOfField.blur must stay 0. Orthographic and shifted cameras render with the rasterizer, not the path tracer.',terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',- placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start on a decoded copy of its own; set-motion tracks move the node and scene time seeks the clip. Copies share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',- navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a translation track with interpolation LINEAR. radius 0.3 m keeps the walker off holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y (half the walker height). Ground and avoided nodes are read at their authored pose. Errors name an unwalkable or unreachable end.',+ placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy of its own (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds its wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',- navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose.',++ navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height.',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),meshModifiers: MESH_MODIFIER_NOTES,@@@ -192,7 -190,7 +192,8 @@@fieldExpressions: Object.freeze({operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,+ rotation: 'rotate [v, axis, rad]; align [dir]: Euler of +Y to dir; transform [p, move, euler, size].',+ surfaces: 'nearest {surface, at, read distance|point|normal}; raycast {surface, at, direction, read hit|distance|point|normal, miss}. at defaults to position; rays go forward. surface: geometry id (instances where) or record (mesh edits). attr group + name reads a vertex group.',}),instancing: Object.freeze({ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES }),operations: Object.freeze([diff --cc src/field-rotation.jsindex 9589133e,00000000..960af553mode 100644,000000..100644--- a/src/field-rotation.js+++ b/src/field-rotation.js@@@ -1,116 -1,0 +1,119 @@@+import { partsOf, requireScalar, vectorValue } from './expression.js';++import { registerFieldOperator } from './mesh-fields.js';++// Rotation and matrix operators of the field language, kept apart from the vector basics in mesh-fields.js.+// Angles are radians and an Euler triple is X then Y then Z (the rotation of a node), like sin and cos.+//+// { "rotate": [vector, axis, angle] } turn a vector about an axis+// { "align": [direction] } Euler angles that turn +Y onto the direction+// { "transform": [point, move, euler, size] } scale, rotate, then move a point (move, euler and size are optional)++const UP = Object.freeze([0, 1, 0]);+const PARALLEL_LIMIT = 1 - 1e-12;+const GIMBAL_LIMIT = 1 - 1e-9;++function normalizedOrZero(vector) {+ const length = Math.hypot(vector[0], vector[1], vector[2]);+ return length === 0 ? [0, 0, 0] : [vector[0] / length, vector[1] / length, vector[2] / length];+}++/** Rodrigues rotation of a vector about an axis; a zero axis leaves the vector as it is. */+export function rotateAboutAxis(vector, axis, angle) {+ const unit = normalizedOrZero(axis);+ if (unit[0] === 0 && unit[1] === 0 && unit[2] === 0) return [...vector];+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const along = unit[0] * vector[0] + unit[1] * vector[1] + unit[2] * vector[2];+ const crossed = [+ unit[1] * vector[2] - unit[2] * vector[1],+ unit[2] * vector[0] - unit[0] * vector[2],+ unit[0] * vector[1] - unit[1] * vector[0],+ ];+ return vector.map((component, axisIndex) => component * cosine + crossed[axisIndex] * sine + unit[axisIndex] * along * (1 - cosine));+}++/** Rotation matrix (row major, 9 numbers) for XYZ Euler angles: Rz * Ry * Rx. */+export function eulerMatrix([angleX, angleY, angleZ]) {+ const [sinX, cosX, sinY, cosY, sinZ, cosZ] = [Math.sin(angleX), Math.cos(angleX), Math.sin(angleY), Math.cos(angleY), Math.sin(angleZ), Math.cos(angleZ)];+ return [+ cosZ * cosY, cosZ * sinY * sinX - sinZ * cosX, cosZ * sinY * cosX + sinZ * sinX,+ sinZ * cosY, sinZ * sinY * sinX + cosZ * cosX, sinZ * sinY * cosX - cosZ * sinX,+ -sinY, cosY * sinX, cosY * cosX,+ ];+}++/** XYZ Euler angles of the shortest turn that takes +Y onto the direction; a zero direction gives no turn. */+export function alignEuler(direction) {+ const target = normalizedOrZero(direction);+ const cosine = target[1];+ if (target[0] === 0 && target[1] === 0 && target[2] === 0) return [0, 0, 0];+ let axis = [UP[1] * target[2] - UP[2] * target[1], UP[2] * target[0] - UP[0] * target[2], UP[0] * target[1] - UP[1] * target[0]];+ if (cosine <= -PARALLEL_LIMIT) axis = [1, 0, 0];+ const angle = Math.acos(Math.min(1, Math.max(-1, cosine)));+ const columns = [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(basis => rotateAboutAxis(basis, axis, angle));+ const entry = (row, column) => columns[column][row];+ if (Math.abs(entry(2, 0)) >= GIMBAL_LIMIT) {+ return [Math.atan2(-entry(1, 2), entry(1, 1)), Math.asin(Math.max(-1, Math.min(1, -entry(2, 0)))), 0];+ }+ return [Math.atan2(entry(2, 1), entry(2, 2)), Math.asin(-entry(2, 0)), Math.atan2(entry(1, 0), entry(0, 0))];+}++function vectorOperand(value, label) {+ if (value.kind !== 'vector') throw new TypeError(`${label} needs a vector.`);+ return value.parts;+}++// One result per element is shared by the three parts, so a vector result is computed once per element.+function sharedVector(compute) {+ let cachedIndex = -1;+ let cachedResult = null;+ return axis => index => {+ if (index !== cachedIndex) {+ cachedResult = compute(index);+ cachedIndex = index;+ }+ return cachedResult[axis];+ };+}++function readVector(parts, index) {+ return [parts[0](index), parts[1](index), parts[2](index)];+}++function buildRotate([vector, axis, angle]) {+ const vectorParts = vectorOperand(vector, 'rotate');+ const axisParts = vectorOperand(axis, 'rotate');+ const angleAt = requireScalar(angle, 'rotate');+ const part = sharedVector(index => rotateAboutAxis(readVector(vectorParts, index), readVector(axisParts, index), angleAt(index)));+ return vectorValue(part(0), part(1), part(2));+}++function buildAlign([direction]) {+ const directionParts = vectorOperand(direction, 'align');+ const part = sharedVector(index => alignEuler(readVector(directionParts, index)));+ return vectorValue(part(0), part(1), part(2));+}++function buildTransform([point, move, euler, size]) {+ const pointParts = vectorOperand(point, 'transform');+ const moveParts = move === undefined ? null : partsOf(move);+ const eulerParts = euler === undefined ? null : vectorOperand(euler, 'transform');+ const sizeParts = size === undefined ? null : partsOf(size);+ const part = sharedVector(index => {+ const scaled = readVector(pointParts, index).map((component, axis) => (sizeParts ? component * sizeParts[axis](index) : component));+ const matrix = eulerParts ? eulerMatrix(readVector(eulerParts, index)) : null;+ const turned = matrix+ ? [0, 1, 2].map(row => matrix[row * 3] * scaled[0] + matrix[row * 3 + 1] * scaled[1] + matrix[row * 3 + 2] * scaled[2])+ : scaled;+ return turned.map((component, axis) => (moveParts ? component + moveParts[axis](index) : component));+ });+ return vectorValue(part(0), part(1), part(2));+}++export const ROTATION_OPERATORS = Object.freeze({+ rotate: { min: 3, max: 3, build: buildRotate },+ align: { min: 1, max: 1, build: buildAlign },+ transform: { min: 1, max: 4, build: buildTransform },+});++++for (const [name, operator] of Object.entries(ROTATION_OPERATORS)) registerFieldOperator(name, operator);diff --cc src/mesh-fields.jsindex 7426a987,687a3942..0173d6f0--- a/src/mesh-fields.js+++ b/src/mesh-fields.js@@@ -158,11 -157,17 +157,23 @@@ OPERATORS.set('normalize', vectorOperatOPERATORS.set('x', vectorOperator(1, 1, selectComponent(0)));OPERATORS.set('y', vectorOperator(1, 1, selectComponent(1)));OPERATORS.set('z', vectorOperator(1, 1, selectComponent(2)));- for (const [name, operator] of Object.entries(ROTATION_OPERATORS)) OPERATORS.set(name, operator);++// Operators that other modules add (field-rotation.js registers itself), so a bundle that never uses one does not carry its code.++export function registerFieldOperator(name, operator) {++ OPERATORS.set(name, operator);++ FIELD_OPERATORS.push(name);++}export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };- const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random']);- export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);+ const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random', 'nearest', 'raycast']);++ // Inputs that other modules supply (the surface inputs register themselves), so a bundle that never reads one does not carry its code.+ const FIELD_SOURCES = new Map();++ export function registerFieldSource(name, compile) {+ FIELD_SOURCES.set(name, compile);+ }-export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);++// Every operator and input name; registerFieldOperator adds the late ones.++export const FIELD_OPERATORS = [...OPERATORS.keys(), ...SOURCE_KEYS];// ---------------------------------------------------------------------------------------------------------------// Compiling an expression against an element context: { count, positions(), normals(), tag(name) }.diff --cc src/mesh-hull-modifiers.jsindex c702f4cb,00000000..b7553084mode 100644,000000..100644--- a/src/mesh-hull-modifiers.js+++ b/src/mesh-hull-modifiers.js@@@ -1,158 -1,0 +1,161 @@@+import { createMeshData } from './mesh-data.js';++import { registerModifierRunner } from './mesh-modifiers.js';++// Two whole-mesh modifiers that replace the mesh with a simple solid around it: bounding_box is the axis-aligned box+// (6 quads) and convex_hull is the smallest convex solid (triangles). Tags and attributes are dropped.++export const MAX_HULL_VERTICES = 8192;+const HULL_EPSILON_SCALE = 1e-9;++// Corner k of the box is (k & 1, k >> 1 & 1, k >> 2 & 1), 0 for the minimum and 1 for the maximum of that axis.+// Every face lists its corners counter-clockwise seen from outside.+const BOX_FACES = Object.freeze([[0, 4, 6, 2], [1, 3, 7, 5], [0, 1, 5, 4], [2, 6, 7, 3], [0, 2, 3, 1], [4, 5, 7, 6]]);++/** The axis-aligned box around all vertices: 8 vertices, 6 quads. */+export function boundingBoxMesh(mesh) {+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ for (let axis = 0; axis < 3; axis++) {+ const value = mesh.positions[vertex * 3 + axis];+ if (value < low[axis]) low[axis] = value;+ if (value > high[axis]) high[axis] = value;+ }+ }+ const positions = new Float32Array(24);+ for (let corner = 0; corner < 8; corner++) {+ for (let axis = 0; axis < 3; axis++) positions[corner * 3 + axis] = (corner >> axis) & 1 ? high[axis] : low[axis];+ }+ const faceOffsets = Uint32Array.from({ length: 7 }, (unused, face) => face * 4);+ return createMeshData({ positions, faceOffsets, cornerVertices: Uint32Array.from(BOX_FACES.flat()) });+}++function pointAt(positions, vertex) {+ return [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];+}++function subtract(first, second) {+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+}++function cross(first, second) {+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];+}++function dot(first, second) {+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+}++// A hull face keeps its outward plane, so "which side of it is this point" is one dot product.+function createFace(positions, first, second, third) {+ const origin = pointAt(positions, first);+ const raw = cross(subtract(pointAt(positions, second), origin), subtract(pointAt(positions, third), origin));+ const length = Math.hypot(raw[0], raw[1], raw[2]) || 1;+ const normal = [raw[0] / length, raw[1] / length, raw[2] / length];+ return { corners: [first, second, third], normal, offset: dot(normal, origin), alive: true };+}++function distanceAbove(face, point) {+ return dot(face.normal, point) - face.offset;+}++function findStartingTetrahedron(positions, count, epsilon) {+ const extreme = [0, 0];+ for (let vertex = 1; vertex < count; vertex++) {+ if (positions[vertex * 3] < positions[extreme[0] * 3]) extreme[0] = vertex;+ if (positions[vertex * 3] > positions[extreme[1] * 3]) extreme[1] = vertex;+ }+ const first = extreme[0];+ let second = extreme[1];+ if (first === second || Math.hypot(...subtract(pointAt(positions, first), pointAt(positions, second))) <= epsilon) {+ second = Array.from({ length: count }, (unused, vertex) => vertex)+ .reduce((best, vertex) => (Math.hypot(...subtract(pointAt(positions, vertex), pointAt(positions, first))) > Math.hypot(...subtract(pointAt(positions, best), pointAt(positions, first))) ? vertex : best), first);+ }+ const line = subtract(pointAt(positions, second), pointAt(positions, first));+ let third = -1;+ let bestArea = epsilon;+ for (let vertex = 0; vertex < count; vertex++) {+ const area = Math.hypot(...cross(line, subtract(pointAt(positions, vertex), pointAt(positions, first))));+ if (area > bestArea) {+ bestArea = area;+ third = vertex;+ }+ }+ if (third < 0) throw new RangeError('convex_hull needs vertices that do not all lie on one line.');+ const normal = cross(line, subtract(pointAt(positions, third), pointAt(positions, first)));+ let fourth = -1;+ let bestHeight = epsilon * Math.hypot(...normal);+ for (let vertex = 0; vertex < count; vertex++) {+ const height = Math.abs(dot(normal, subtract(pointAt(positions, vertex), pointAt(positions, first))));+ if (height > bestHeight) {+ bestHeight = height;+ fourth = vertex;+ }+ }+ if (fourth < 0) throw new RangeError('convex_hull needs vertices that do not all lie in one plane.');+ return [first, second, third, fourth];+}++/** Incremental convex hull of all vertices as a triangle mesh with outward faces; unused vertices are dropped. */+export function convexHullMesh(mesh) {+ if (mesh.vertexCount > MAX_HULL_VERTICES) {+ throw new RangeError(`convex_hull takes at most ${MAX_HULL_VERTICES} vertices and the mesh has ${mesh.vertexCount}. Decimate or weld first.`);+ }+ const { positions } = mesh;+ const count = mesh.vertexCount;+ const bounds = boundingBoxMesh(mesh).positions;+ const epsilon = Math.hypot(bounds[21] - bounds[0], bounds[22] - bounds[1], bounds[23] - bounds[2]) * HULL_EPSILON_SCALE;+ const [first, second, third, fourth] = findStartingTetrahedron(positions, count, epsilon);+ const inside = [0, 1, 2].map(axis => (positions[first * 3 + axis] + positions[second * 3 + axis] + positions[third * 3 + axis] + positions[fourth * 3 + axis]) / 4);+ const faces = [];+ for (const [a, b, c] of [[first, second, third], [first, second, fourth], [first, third, fourth], [second, third, fourth]]) {+ const face = createFace(positions, a, b, c);+ if (distanceAbove(face, inside) > 0) {+ face.corners = [a, c, b];+ face.normal = face.normal.map(component => -component);+ face.offset = -face.offset;+ }+ faces.push(face);+ }+ const used = new Set([first, second, third, fourth]);+ for (let vertex = 0; vertex < count; vertex++) {+ if (used.has(vertex)) continue;+ const point = pointAt(positions, vertex);+ const visible = faces.filter(face => face.alive && distanceAbove(face, point) > epsilon);+ if (visible.length === 0) continue;+ const horizon = new Map();+ for (const face of visible) {+ face.alive = false;+ for (let side = 0; side < 3; side++) horizon.set(`${face.corners[side]}:${face.corners[(side + 1) % 3]}`, [face.corners[side], face.corners[(side + 1) % 3]]);+ }+ for (const [start, end] of horizon.values()) {+ if (horizon.has(`${end}:${start}`)) continue;+ faces.push(createFace(positions, start, end, vertex));+ }+ }+ const alive = faces.filter(face => face.alive);+ const remap = new Map();+ const hullPositions = [];+ const cornerVertices = [];+ for (const face of alive) {+ for (const vertex of face.corners) {+ if (!remap.has(vertex)) {+ remap.set(vertex, remap.size);+ hullPositions.push(...pointAt(positions, vertex));+ }+ cornerVertices.push(remap.get(vertex));+ }+ }+ const faceOffsets = Uint32Array.from({ length: alive.length + 1 }, (unused, face) => face * 3);+ return createMeshData({ positions: Float32Array.from(hullPositions), faceOffsets, cornerVertices: Uint32Array.from(cornerVertices) });+}++export const HULL_RUNNERS = Object.freeze({+ bounding_box: mesh => ({ mesh: boundingBoxMesh(mesh), result: {} }),+ convex_hull: mesh => {+ const hull = convexHullMesh(mesh);+ return { mesh: hull, result: { hullVertices: hull.vertexCount } };+ },+});++++for (const [operation, runner] of Object.entries(HULL_RUNNERS)) registerModifierRunner(operation, runner);diff --cc src/mesh-instances.jsindex 6e922182,f490dc20..4947ef2d--- a/src/mesh-instances.js+++ b/src/mesh-instances.js@@@ -1,7 -1,8 +1,10 @@@import { quat } from 'gl-matrix';import { INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES } from './mesh-operations.js';import { evaluateField, pointSetContext, seededRandom } from './mesh-fields.js';+import { MAX_CURVE_POINTS, filletCurve, resampleCurve } from './curve-operations.js';+ import { createTriangleSurfaceIndex } from './mesh-query.js';+ import './mesh-field-surfaces.js';++import './field-rotation.js';// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from adiff --cc src/mesh-modifiers.jsindex c1dfabe1,78e348d8..334ac628--- a/src/mesh-modifiers.js+++ b/src/mesh-modifiers.js@@@ -185,10 -184,9 +184,17 @@@ function simpleDeformPositions(mesh, {}/** Run a modifier edit. Returns { mesh, result } where result holds the counts to report. */++// Modifiers that other modules supply (mesh-hull-modifiers.js registers itself), so a bundle that never runs one does not carry its code.++const REGISTERED_RUNNERS = Object.create(null);++++export function registerModifierRunner(operation, runner) {++ REGISTERED_RUNNERS[operation] = runner;++}++export function runModifierEdit(mesh, edit, { maxVertices, maxFaces }) {if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) return GENERATOR_RUNNERS[edit.op](mesh, edit, { maxVertices, maxFaces });if (Object.hasOwn(NORMAL_RUNNERS, edit.op)) return { mesh: NORMAL_RUNNERS[edit.op](mesh, edit), result: {} };- if (Object.hasOwn(HULL_RUNNERS, edit.op)) return HULL_RUNNERS[edit.op](mesh);++ if (Object.hasOwn(REGISTERED_RUNNERS, edit.op)) return REGISTERED_RUNNERS[edit.op](mesh, edit);if (isDeformModifier(edit.op)) return runDeformEdit(mesh, edit);switch (edit.op) {case 'weld': {diff --cc src/mesh-operations.jsindex 0652f422,5025d84b..b7624d1c--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@@ -5,7 -5,7 +5,7 @@@ export const MAX_MESH_EDITS = 64// Modifiers that work on the whole mesh and take no selection or name. Their fields are checked in mesh-modifiers.js and// each one is described for agents by MESH_MODIFIER_NOTES in agent-scene-capabilities.js.--export const MODIFIER_OPERATIONS = Object.freeze({++export const MODIFIER_OPERATIONS = /* @__PURE__ */ Object.freeze({weld: { fields: ['distance'], tags: [] },triangulate: { fields: ['minVertices'], tags: [] },edge_split: { fields: ['angle'], tags: [] },@@@ -21,11 -21,9 +21,11 @@@wave: { fields: ['height', 'width', 'narrowness', 'speed', 'time', 'timeOffset', 'start', 'cyclic', 'axes', 'normal'], tags: [] },weighted_normal: { fields: ['angle', 'weight'], tags: [] },smooth_by_angle: { fields: ['angle', 'ignoreSharp'], tags: [] },+ bounding_box: { fields: [], tags: [] },+ convex_hull: { fields: [], tags: [] },});--export const MESH_EDIT_OPERATIONS = Object.freeze({++export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({extrude_face_region: { fields: ['select', 'name', 'offset', 'direction', 'alongNormals'], tags: ['cap', 'side'] },extrude_individual: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },inset_region: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },@@@ -65,13 -63,13 +65,13 @@@});// Limits of the sculpt and shrinkwrap edits, and their vocabulary, as plain data.--export const SCULPT_STROKE_TYPES = Object.freeze(['inflate', 'displace', 'smooth']);++export const SCULPT_STROKE_TYPES = /* @__PURE__ */ Object.freeze(['inflate', 'displace', 'smooth']);export const MAX_SCULPT_STROKES = 32;export const MAX_SCULPT_VISITS = 5_000_000;--export const SHRINKWRAP_MODES = Object.freeze(['nearest', 'project']);++export const SHRINKWRAP_MODES = /* @__PURE__ */ Object.freeze(['nearest', 'project']);export const MAX_SHRINKWRAP_TRIANGLE_TESTS = 20_000_000;--export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide', 'set_position', 'displace', 'decimate', 'remesh', ...Object.keys(MODIFIER_OPERATIONS)]);++export const STACK_OPERATIONS = /* @__PURE__ */ Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide', 'set_position', 'displace', 'decimate', 'remesh', ...Object.keys(MODIFIER_OPERATIONS)]);export const MAX_STACK_NODES = 16;// Field expressions (mesh-fields.js) and instancing (mesh-instances.js): limits and names as plain data. A test@@@ -80,19 -78,18 +80,19 @@@ export const MAX_FIELD_NODES = 64export const MAX_FIELD_DEPTH = 12;export const MAX_FIELD_ELEMENTS = 250_000;export const MAX_FIELD_WORK = 8_000_000;- export const FIELD_ATTRIBUTES = Object.freeze(['position', 'normal', 'index', 'tag']);-export const FIELD_ATTRIBUTES = Object.freeze(['position', 'normal', 'index', 'tag', 'group']);--export const FIELD_OPERATOR_NAMES = Object.freeze([++export const FIELD_ATTRIBUTES = /* @__PURE__ */ Object.freeze(['position', 'normal', 'index', 'tag', 'group']);++export const FIELD_OPERATOR_NAMES = /* @__PURE__ */ Object.freeze(['add', 'mul', 'min', 'max', 'sub', 'div', 'mod', 'pow', 'atan2', 'clamp', 'mix', 'smoothstep','neg', 'abs', 'sqrt', 'sin', 'cos', 'floor', 'ceil', 'round', 'fract', 'sign', 'saturate','lt', 'lte', 'gt', 'gte', 'eq', 'and', 'or', 'not', 'if','vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z',+ 'rotate', 'align', 'transform',- 'attr', 'noise', 'random',+ 'attr', 'noise', 'random', 'nearest', 'raycast',]);- export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface', 'curve']);-export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface']);++export const INSTANCE_SOURCES = /* @__PURE__ */ Object.freeze(['grid', 'scatter', 'surface', 'curve']);export const MAX_INSTANCE_CANDIDATES = 2048;// Imported GLB parts take the same edits. Skin weights, morph deltas and vertex colours of new geometry come from the// nearest point of the original surface; an edit that reaches farther than this fraction of the part's bounds// diagonal from that surface is rejected on a skinned or morphed part, because the transfer would be a guess.--export const IMPORTED_MESH_EDIT_LIMITS = Object.freeze({ maxTransferFraction: 0.25, maxEditedParts: 64 });++export const IMPORTED_MESH_EDIT_LIMITS = /* @__PURE__ */ Object.freeze({ maxTransferFraction: 0.25, maxEditedParts: 64 });diff --cc src/mesh-recipe.jsindex ae260c3c,e8451959..9b9e6060--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@@ -20,6 -20,9 +20,11 @@@ import { decimateMesh } from './mesh-deimport { isModifierOperation, normalizeModifierEdit, runModifierEdit } from './mesh-modifiers.js';import { sculptMesh, checkSculptBudget } from './mesh-sculpt.js';import { shrinkwrapMesh } from './mesh-shrinkwrap.js';+ import { triangulatedSurface } from './mesh-surface-distance.js';+ import { createTriangleSurfaceIndex } from './mesh-query.js';+ import './mesh-field-surfaces.js';++import './field-rotation.js';++import './mesh-hull-modifiers.js';import { remeshMesh, remeshGridSize, MAX_REMESH_RESOLUTION } from './mesh-remesh.js';import {MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES, SCULPT_STROKE_TYPES, MAX_SCULPT_STROKES, SHRINKWRAP_MODES,