3D engine that AI agents drive
feat: add curve length spacing and realize for instances (#698) (#735)
Nguyen Xuan Ane6a48013a7da
diff --git a/changes/698.md b/changes/698.mdnew file mode 100644index 00000000..2befa2d8--- /dev/null+++ b/changes/698.md@@ -0,0 +1 @@+- Add `curve.length` spacing and `realize` (into one mesh per material) for recipe `instances`.diff --git a/changes/698.size.md b/changes/698.size.mdnew file mode 100644index 00000000..3cae559f--- /dev/null+++ b/changes/698.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: curve.length spacing and realize instances (merging transformed geometries per material) in src/mesh-instances.js and src/mesh-instance-placement.js.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 665c67ec..80c0002a 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -258,7 +258,7 @@ Give exactly one point source. `grid` is `{ counts: [nx, ny, nz], spacing: [dx,on the triangles of a recipe geometry in proportion to their area; they are in that geometry's own space, so parentthe group to the node that carries it. `seed` (default 0) fixes the placement. `where` is a number[field expression](mesh.md#field-expressions) over the points (position, normal, index): points where it is 0 are-dropped. `curve` is `{ points, count, closed, fillet }`: `count` points at equal arc length along the polyline through `points` (2 to 256, the first and last on its ends unless `closed`), with `fillet` rounding every corner by that radius (reduced where it does not fit). `yaw` turns each instance randomly about up, `alignToNormal` (surface or curve) turns up to the surface normal or the direction of the curve, and `scale`+dropped. `curve` is `{ points, count, length, closed, fillet }`: `count` points at equal arc length along the polyline through `points` (2 to 256, the first and last on its ends unless `closed`), or `length` spacing in metres between samples (not both `count` and `length`), with `fillet` rounding every corner by that radius (reduced where it does not fit). `yaw` turns each instance randomly about up, `alignToNormal` (surface or curve) turns up to the surface normal or the direction of the curve, and `scale`is a random uniform `[min, max]`. At most 2048 candidate points per node, and the scene's node limit still applies.The group's own scale applies to the spacing and the points, because they are in its space.@@ -276,8 +276,7 @@ The group's own scale applies to the spacing and the points, because they are in- `variants`: 1 to 16 geometry ids or `{ geometry, material }`. Each point takes one at random, or the one `variant` (a number field, rounded down and wrapped) names. The node needs only a material when it lists variants.- `rotation`: vector field of extra Euler angles in radians, turned after `yaw` and `alignToNormal`. `size`: number or vector field, a scale per point, multiplied by the `scale` range and kept from 0.001 to 1000.- `at`: with a `surface` source, `"vertices"` (welded by position) or `"faces"` (centres, normal of the face) place on the mesh itself; `count` is then the most points allowed, and more is an error.--Not yet: realizing the instances into one mesh.+- `realize` (on `instances` or `place`): when `true`, merges the placed instances into one realized mesh per material under the group node, bounded by `maxVertices`.### Placed catalog assetsdiff --git a/docs/parity.md b/docs/parity.mdindex dabe03eb..5e75fe62 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -82,7 +82,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Generate > Mirror Modifier | done | Stack node with axis and merge. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | || Modeling > Modifiers > Generate > Multiresolution Modifier | missing | No multiresolution. | | || Modeling > Modifiers > Generate > Remesh Modifier | partial | Voxel mode as `remesh` (voxel size or resolution), as an edit or a stack node, compared with Blender on 2 shared fixtures. Blocks, smooth and sharp modes are missing. | [blender golden](../tests/blender-golden.test.js), [decimate](../tests/mesh-decimate.test.js) | #40 |-| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. Its `where` can read a path mesh with `nearest` and a terrain with `raycast`. `place` adds Poisson spacing, a density field, variants, per-point rotation and size fields, and vertex or face-centre points. Instances are not realized into one mesh, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/mesh-instance-placement.test.js](../tests/mesh-instance-placement.test.js) | #42, #698 |+| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. Its `where` can read a path mesh with `nearest` and a terrain with `raycast`. `place` adds Poisson spacing, a density field, variants, per-point rotation and size fields, vertex or face-centre points, and `realize` into one mesh per material. `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/mesh-instance-placement.test.js](../tests/mesh-instance-placement.test.js) | #42, #698 || Modeling > Modifiers > Generate > Screw Modifier | partial | `screw` edit and stack node revolves every edge of the mesh about x, y or z with `angle`, `steps`, `iterations` and a `lift` along the axis; a whole number of turns closes the ring. Counts, area and positions match Blender on 2 cases (the volume of the open strips differs by winding). No merge option, no object axis, no normal calculation and no separate render steps. `lathe` stays the way to revolve a profile. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 || Modeling > Modifiers > Generate > Skin Modifier | partial | `skin` edit and stack node: a square tube on every edge of the mesh, radius a number or a scalar field per vertex, closed by end caps. Simple version: tubes that meet overlap, there is no branch solver, no loose ends marking and no Blender comparison. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js) | #42 || Modeling > Modifiers > Generate > Solidify Modifier | done | Stack node with thickness, offset and even thickness. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |@@ -120,7 +120,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Particle Instance Modifier | partial | An emitter system repeats its node's mesh once per particle. There is no choice of instanced object with rotation, no collection and no moving source. | [particles](../tests/particles.test.js) | #63 || Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), collision with chosen static meshes and the floor with bounce and friction, spin, color and alpha over life (a fade to black; no per-vertex alpha), no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 || Modeling > Modifiers > Physics > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 |-| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |+| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances` (including curve points by count or length, fillet and `realize`); they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43, #698 || Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface, curve, with Poisson spacing, density, variants, rotation and scale fields) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 || Modeling > Transform | partial | Node transforms, and `translate` on a selection with falloff. There is no rotate or scale on a selection. | | || Sculpting & Painting > Brushes | out of scope | Brush settings for a hand. Strokes have explicit parameters. | | |diff --git a/src/agent-mesh.js b/src/agent-mesh.jsindex b1f46a47..f5fe3f4d 100644--- a/src/agent-mesh.js+++ b/src/agent-mesh.js@@ -5,6 +5,7 @@ import { lintMesh } from './mesh-lint.js';import { applyMeshEdits, evaluateMeshStack } from './mesh-recipe.js';import { extractRender } from './mesh-render.js';import { normalizeShapeKeys, shapeKeyTargets } from './mesh-shape-keys.js';+import { realizedGeometry } from './mesh-instances.js';import { MESH_SMOOTH_ANGLE_DEFAULT } from './agent-scene-capabilities.js';export { MESH_SMOOTH_ANGLE_DEFAULT };@@ -87,6 +88,13 @@ export function meshCacheStats() {export function generateMeshGeometry(baseGeometry, edits, {maxVertices, smoothAngle = MESH_SMOOTH_ANGLE_DEFAULT, resolveCutter, stack = [], cacheKey, shapeKeys = [],}) {+ const realized = cacheKey && realizedGeometry(cacheKey);+ if (realized) {+ if (realized.positions.length / 3 > maxVertices) {+ throw invalidField('edits', realized.positions.length / 3, `an edited mesh of at most ${maxVertices} render vertices (maxVertices); use fewer subdivisions or segments`);+ }+ return realized;+ }const editsKey = cacheKey === undefined ? undefined : `${cacheKey}|edits|${JSON.stringify(edits)}`;let edited = editsKey === undefined ? undefined : evaluationCache.get(editsKey);if (!edited) {diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 3552eb86..c4962d3e 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -803,7 +803,7 @@ function normalizeRecipe(input, limits) {if (!definition) throw invalidField('instances.surface', id, `the ID of a geometry in geometries, such as ${recipe.geometries[0]?.id ?? 'ground'}`);return generateGeometry(definition, Math.min(limits.maxVertices, 1_000_000));},- });+ }, recipe.geometries);recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);addArmatures(recipe, limits);if (recipe.nodes.some(node => node.relations !== undefined)) {diff --git a/src/mesh-instance-placement.js b/src/mesh-instance-placement.jsindex 9486332c..adb04617 100644--- a/src/mesh-instance-placement.js+++ b/src/mesh-instance-placement.js@@ -1,4 +1,4 @@-import { quat } from 'gl-matrix';+import { quat, vec3 } from 'gl-matrix';import { seededRandom } from './mesh-fields.js';// The `place` record of an `instances` spec: what keeps, shapes and varies the points once a source made them.@@ -13,8 +13,9 @@ import { seededRandom } from './mesh-fields.js';//// Every choice is a pure function of the point index and the seed, so a scene builds the same way each time.-export const PLACE_FIELDS = Object.freeze(['at', 'spacing', 'density', 'variants', 'variant', 'rotation', 'size']);+export const PLACE_FIELDS = Object.freeze(['at', 'spacing', 'density', 'variants', 'variant', 'rotation', 'size', 'realize']);export const MAX_VARIANTS = 16;+export const MAX_REALIZED_VERTICES = 250_000;const MAX_SPACING = 1e6;const MIN_SIZE = 0.001;const MAX_SIZE = 1000;@@ -38,6 +39,7 @@ export function checkedPlace(place) {if (place.spacing !== undefined && !(typeof place.spacing === 'number' && place.spacing > 0 && place.spacing <= MAX_SPACING)) {throw placeError('spacing is a distance above 0.');}+ if (place.realize !== undefined && typeof place.realize !== 'boolean') throw placeError('realize must be boolean.');if (place.variant !== undefined && place.variants === undefined) throw placeError('variant needs a variants list.');const variants = place.variants === undefined ? null : variantList(place.variants);return { ...place, variants };@@ -154,3 +156,61 @@ export function clampedSize(values, index, perAxis) {const pick = axis => Math.min(MAX_SIZE, Math.max(MIN_SIZE, values[perAxis ? index * 3 + axis : index]));return [pick(0), pick(1), pick(2)];}++/**+ * Merge transformed copies of render geometries into one combined render geometry ({ positions, normals, indices,+ * ...(uvs), ...(colors) }), checked against `maxVertices` before allocating buffers.+ */+export function mergeRealizedInstances(entries, maxVertices = MAX_REALIZED_VERTICES) {+ const totalVertices = entries.reduce((sum, entry) => sum + entry.geometry.positions.length / 3, 0);+ if (totalVertices > maxVertices) {+ throw new RangeError(`Realized instances have ${totalVertices} vertices, over the limit of ${maxVertices}.`);+ }+ const totalIndices = entries.reduce((sum, entry) => sum + entry.geometry.indices.length, 0);+ const hasUvs = entries.some(entry => entry.geometry.uvs?.length);+ const hasColors = entries.some(entry => entry.geometry.colors?.length);+ const positions = new Float32Array(totalVertices * 3);+ const normals = new Float32Array(totalVertices * 3);+ const indices = new Uint32Array(totalIndices);+ const uvs = hasUvs ? new Float32Array(totalVertices * 2) : null;+ const colors = hasColors ? new Float32Array(totalVertices * 3) : null;+ if (colors) colors.fill(1);+ const point = [0, 0, 0];+ const normal = [0, 0, 0];+ let vertexBase = 0;+ let indexBase = 0;+ for (const { geometry, translation, rotation, scale } of entries) {+ const vertexCount = geometry.positions.length / 3;+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ const sourceOffset = vertex * 3;+ const targetOffset = (vertexBase + vertex) * 3;+ point[0] = geometry.positions[sourceOffset] * scale[0];+ point[1] = geometry.positions[sourceOffset + 1] * scale[1];+ point[2] = geometry.positions[sourceOffset + 2] * scale[2];+ vec3.transformQuat(point, point, rotation);+ positions[targetOffset] = point[0] + translation[0];+ positions[targetOffset + 1] = point[1] + translation[1];+ positions[targetOffset + 2] = point[2] + translation[2];+ normal[0] = geometry.normals[sourceOffset] / scale[0];+ normal[1] = geometry.normals[sourceOffset + 1] / scale[1];+ normal[2] = geometry.normals[sourceOffset + 2] / scale[2];+ vec3.transformQuat(normal, normal, rotation);+ const normalLength = Math.hypot(normal[0], normal[1], normal[2]) || 1;+ normals[targetOffset] = normal[0] / normalLength;+ normals[targetOffset + 1] = normal[1] / normalLength;+ normals[targetOffset + 2] = normal[2] / normalLength;+ }+ if (uvs && geometry.uvs?.length === vertexCount * 2) uvs.set(geometry.uvs, vertexBase * 2);+ if (colors && geometry.colors?.length === vertexCount * 3) colors.set(geometry.colors, vertexBase * 3);+ for (let cursor = 0; cursor < geometry.indices.length; cursor++) {+ indices[indexBase + cursor] = vertexBase + geometry.indices[cursor];+ }+ vertexBase += vertexCount;+ indexBase += geometry.indices.length;+ }+ return {+ positions, normals, indices,+ ...(uvs ? { uvs } : {}),+ ...(colors ? { colors } : {}),+ };+}diff --git a/src/mesh-instances.js b/src/mesh-instances.jsindex 0809b10c..899bce50 100644--- a/src/mesh-instances.js+++ b/src/mesh-instances.js@@ -1,12 +1,12 @@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 { MAX_CURVE_POINTS, curveLength, filletCurve, resampleCurve } from './curve-operations.js';import { createTriangleSurfaceIndex } from './mesh-query.js';import './mesh-field-surfaces.js';import './field-rotation.js';import {- checkedPlace, clampedSize, eulerQuaternion, meshPoints, pickVariant, thinByDensity, thinBySpacing,+ checkedPlace, clampedSize, eulerQuaternion, mergeRealizedInstances, meshPoints, pickVariant, thinByDensity, thinBySpacing,} from './mesh-instance-placement.js';// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all@@ -28,10 +28,29 @@ import {export { MAX_INSTANCE_CANDIDATES };const MAX_COORDINATE = 1e6;const SOURCES = INSTANCE_SOURCES;-const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale', 'place']);+const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale', 'place', 'realize']);const MAX_SEED = 0x7fffffff;const CURVE_FILLET_SEGMENTS = 8;const UP = Object.freeze([0, 1, 0]);+const REALIZED_MAX_ENTRIES = 128;+const realizedGeometries = new Map();++export function realizedGeometry(key) {+ return realizedGeometries.get(key);+}++export function realizedVertexCount(key) {+ const geometry = realizedGeometries.get(key);+ return geometry ? geometry.positions.length / 3 : 0;+}++function storeRealizedGeometry(key, geometry) {+ if (realizedGeometries.has(key)) realizedGeometries.delete(key);+ realizedGeometries.set(key, geometry);+ while (realizedGeometries.size > REALIZED_MAX_ENTRIES) {+ realizedGeometries.delete(realizedGeometries.keys().next().value);+ }+}const CHANNEL_SCATTER = 20;const CHANNEL_YAW = 10;@@ -155,18 +174,30 @@ export function surfacePoints(geometry, count, seed) {// Points at equal arc length along a polyline, optionally with rounded corners; the "normal" of each point is the// direction of travel, so alignToNormal turns up along the curve.function curvePoints(source) {- plainRecord(source, 'curve', ['points', 'count', 'closed', 'fillet']);+ plainRecord(source, 'curve', ['points', 'count', 'length', 'closed', 'fillet']);if (!Array.isArray(source.points) || source.points.length < 2 || source.points.length > MAX_CURVE_POINTS) {throw instanceError(`curve points are 2 to ${MAX_CURVE_POINTS} positions.`);}const corners = source.points.map(point => coordinates(point, 'curve point'));const closed = source.closed === true;if (source.closed !== undefined && typeof source.closed !== 'boolean') throw instanceError('curve closed must be boolean.');- const count = wholeNumber(source.count, closed ? 3 : 2, MAX_INSTANCE_CANDIDATES, 'curve count');+ if ((source.count === undefined) === (source.length === undefined)) {+ throw instanceError('curve needs count or length, not both.');+ }+ if (source.length !== undefined && !(typeof source.length === 'number' && Number.isFinite(source.length) && source.length > 0 && source.length <= MAX_COORDINATE)) {+ throw instanceError('curve length is a spacing above 0.');+ }if (source.fillet !== undefined && !(typeof source.fillet === 'number' && source.fillet > 0 && source.fillet <= MAX_COORDINATE)) {throw instanceError('curve fillet is a radius above 0.');}const path = source.fillet === undefined ? corners : filletCurve(corners, source.fillet, CURVE_FILLET_SEGMENTS, closed);+ const minimumCount = closed ? 3 : 2;+ const rawCount = source.count !== undefined+ ? source.count+ : closed+ ? Math.max(minimumCount, Math.round(curveLength(path, true) / source.length))+ : Math.max(minimumCount, Math.floor(curveLength(path, false) / source.length) + 1);+ const count = wholeNumber(rawCount, minimumCount, MAX_INSTANCE_CANDIDATES, 'curve count');const samples = resampleCurve(path, count, closed);const positions = new Float64Array(count * 3);const normals = new Float64Array(count * 3);@@ -234,7 +265,7 @@ function instanceScale(spec, seed, candidate, sizes) {function checkedSpec(spec) {plainRecord(spec, 'instances', INSTANCE_FIELDS);const seed = spec.seed === undefined ? 0 : wholeNumber(spec.seed, 0, MAX_SEED, 'seed');- for (const flag of ['yaw', 'alignToNormal']) {+ for (const flag of ['yaw', 'alignToNormal', 'realize']) {if (spec[flag] !== undefined && typeof spec[flag] !== 'boolean') throw instanceError(`${flag} must be boolean.`);}if (spec.alignToNormal && !Object.hasOwn(spec, 'surface') && !Object.hasOwn(spec, 'curve')) throw instanceError('alignToNormal needs a surface or curve source, because only those have normals.');@@ -263,7 +294,7 @@ function placementFields(spec, place, points, resolveSurface) {* returns the render geometry ({ positions, normals, indices }) for a surface source. Nodes without `instances` pass* through untouched.*/-export function expandInstancedNodes(nodes, { resolveSurface, maxNodes }) {+export function expandInstancedNodes(nodes, { resolveSurface, maxNodes, maxVertices }, geometries) {if (!Array.isArray(nodes)) return nodes;const expanded = [];for (const node of nodes) {@@ -279,13 +310,48 @@ export function expandInstancedNodes(nodes, { resolveSurface, maxNodes }) {const points = candidatePoints(spec, seed, resolveSurface, place);const fields = placementFields(spec, place, points, resolveSurface);expanded.push(group);- for (const [slot, candidate] of keptIndices(spec, place, points, fields, seed).entries()) {+ const placements = keptIndices(spec, place, points, fields, seed).map((candidate, slot) => {const variant = place.variants ? pickVariant(place.variants, fields.variant?.values, candidate, seed) : { geometry, material };- expanded.push({- id: `${node.id}.${slot}`, parent: node.id, geometry: variant.geometry, material: variant.material ?? material,+ return {+ slot, geometry: variant.geometry, material: variant.material ?? material,translation: [points.positions[candidate * 3], points.positions[candidate * 3 + 1], points.positions[candidate * 3 + 2]],rotation: instanceRotation(spec, seed, candidate, points.normals, fields.rotation?.values),scale: instanceScale(spec, seed, candidate, fields.size),+ };+ });+ if (spec.realize || place.realize) {+ const byMaterial = new Map();+ for (const item of placements) {+ if (!byMaterial.has(item.material)) byMaterial.set(item.material, []);+ byMaterial.get(item.material).push({+ geometry: resolveSurface(item.geometry),+ translation: item.translation, rotation: item.rotation, scale: item.scale,+ });+ }+ let groupIndex = 0;+ for (const [materialId, entries] of byMaterial) {+ const merged = mergeRealizedInstances(entries, maxVertices);+ const childId = `${node.id}.${groupIndex}`;+ const geometryId = `${node.id}.realized.${groupIndex}`;+ let subdivisions = 1;+ while (subdivisions <= 128 && realizedGeometries.has(JSON.stringify({ type: 'box', bevel: 0, subdivisions }))) subdivisions++;+ const base = { type: 'box', bevel: 0, subdivisions };+ storeRealizedGeometry(JSON.stringify(base), merged);+ const registered = geometries?.push({ id: geometryId, type: 'mesh', base });+ expanded.push({+ id: childId, parent: node.id, geometry: geometryId, material: materialId,+ translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1],+ ...(typeof registered === 'number' ? {} : { realizedGeometry: merged }),+ });+ groupIndex++;+ if (expanded.length > maxNodes) throw new RangeError(`Instances expand past the limit of ${maxNodes} nodes.`);+ }+ continue;+ }+ for (const item of placements) {+ expanded.push({+ id: `${node.id}.${item.slot}`, parent: node.id, geometry: item.geometry, material: item.material,+ translation: item.translation, rotation: item.rotation, scale: item.scale,});if (expanded.length > maxNodes) throw new RangeError(`Instances expand past the limit of ${maxNodes} nodes.`);}diff --git a/tests/mesh-instance-placement.test.js b/tests/mesh-instance-placement.test.jsindex d29200fe..069805e3 100644--- a/tests/mesh-instance-placement.test.js+++ b/tests/mesh-instance-placement.test.js@@ -2,6 +2,7 @@ import './support/load-agent-scene-modules.mjs';import assert from 'node:assert/strict';import test from 'node:test';import { box, sphere } from '../src/geometry.js';+import { createAgentScene } from '../src/agent-scene.js';import { expandInstancedNodes } from '../src/mesh-instances.js';const base = { id: 'rock', geometry: 'rockA', material: 'stone' };@@ -120,3 +121,64 @@ test('bad place records name the field', () => {}assert.throws(() => expandInstancedNodes([{ id: 'bare', material: 'stone', instances: { grid } }], options), /geometry and material/);});++test('curve source accepts length spacing or count, with fillet and closed loops', () => {+ const open = children(expand({+ curve: { points: [[0, 0, 0], [6, 0, 0], [6, 0, 4]], length: 2 },+ alignToNormal: true,+ }));+ assert.equal(open.length, 6);+ assert.deepEqual(open[0].translation, [0, 0, 0]);+ assert.ok(Math.abs(open[5].translation[0] - 6) < 1e-9 && Math.abs(open[5].translation[2] - 4) < 1e-9);++ const closed = children(expand({+ curve: { points: [[0, 0, 0], [4, 0, 0], [4, 0, 4], [0, 0, 4]], length: 4, closed: true, fillet: 0.5 },+ }));+ assert.equal(closed.length, 4);++ assert.throws(() => expand({ curve: { points: [[0, 0, 0], [2, 0, 0]], count: 3, length: 1 } }), /count or length/);+ assert.throws(() => expand({ curve: { points: [[0, 0, 0], [2, 0, 0]] } }), /count or length/);+ assert.throws(() => expand({ curve: { points: [[0, 0, 0], [2, 0, 0]], length: 0 } }), /curve length/);+});++test('realize merges instances into one mesh per material in expandInstancedNodes and createAgentScene', () => {+ const cube = box(0, 1);+ const cubeVerts = cube.positions.length / 3;+ const cubeIndices = cube.indices.length;+ const realized = children(expand({+ grid: { counts: [4, 1, 1], spacing: [2, 0, 0] },+ place: {+ variants: ['rockA', { geometry: 'rockB', material: 'moss' }],+ variant: { mod: [{ attr: 'index' }, 2] },+ realize: true,+ },+ }, base, { ...options, resolveSurface: () => cube }));+ assert.equal(realized.length, 2);+ assert.equal(realized[0].material, 'stone');+ assert.equal(realized[1].material, 'moss');+ assert.equal(realized[0].realizedGeometry.positions.length / 3, cubeVerts * 2);+ assert.equal(realized[0].realizedGeometry.indices.length, cubeIndices * 2);++ assert.throws(() => expand({+ grid: { counts: [10, 1, 1], spacing: [1, 1, 1] },+ realize: true,+ }, base, { ...options, maxVertices: cubeVerts * 2, resolveSurface: () => cube }), /Realized instances have/);+ assert.throws(() => expand({ grid: { counts: [2, 1, 1], spacing: [1, 1, 1] }, realize: 'yes' }), /realize must be boolean/);+ assert.throws(() => expand({ grid: { counts: [2, 1, 1], spacing: [1, 1, 1] }, place: { realize: 'yes' } }), /realize must be boolean/);++ const scene = createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'post', type: 'box', bevel: 0, subdivisions: 1 }],+ materials: [{ id: 'wood', color: [0.5, 0.3, 0.1] }],+ nodes: [{+ id: 'fence', geometry: 'post', material: 'wood',+ instances: { curve: { points: [[0, 0, 0], [6, 0, 0]], length: 2 }, alignToNormal: true, realize: true },+ }],+ });+ assert.equal(scene.parts.length, 1);+ assert.equal(scene.parts[0].name, 'fence.0');+ assert.equal(scene.parts[0].geometry.positions.length / 3, 24 * 4);+ const afterEdit = scene.apply([{ type: 'set-node', id: 'fence', translation: [0, 1, 0] }], { expectedRevision: scene.revision });+ assert.equal(afterEdit, 1);+ assert.equal(scene.parts.length, 1);+});