Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(geometry): repeat leaflets along a curve and surface foliage helpers (#211) (#224)
Matthew Kissinger9949c84062c8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 86f498ee..671290c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,13 @@ does not publish a package.`--check`, `--upgrade` and `--repair`, so a host with folder-scoped edit permissionsno longer approves every root `KILN_PROGRESS.md` update. Absolute, traversal and managedpaths are refused. The default guide is unchanged.+- Add `repeatAlongCurve` for leaflets, cards and studs along a sampled curve+ ([#211](https://github.com/instruktlabs/kiln/issues/211)). By default it merges the copies+ into one geometry (one primitive per frond) with each copy's UVs kept, an optional `_along`+ attribute and an `opposite` row; `merge: false` returns shared-geometry nodes. Merges are+ bounded at 262,144 vertices. Discovery now answers foliage wording ("palm frond+ leaflets", "fern", "grass clump") with the repetition and card helpers, and the authoring+ skill describes the foliage workflow and when per-element naming applies.## 1.3.1 (2026-10-17)diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex ae910c2d..0d901d67 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -8398,6 +8398,18 @@ arrayLinear('Post', post, 10, [0.5, 0, 0], root);`example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });arrayRadial('Bolt', bolt, 8, 'y', root);`},+ {+ name: "repeatAlongCurve",+ signature: "repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })",+ returns: "THREE.BufferGeometry (merge: true) or THREE.Object3D[] (merge: false)",+ category: "arrays",+ description: "Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns shared-geometry nodes like arrayLinear.",+ example: `const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);+const leaflet = foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 });+const frond = repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true });+createPart('Frond_0', frond, foliageMaterial(albedo), { parent: root });`,+ promptNotes: "One merged geometry is one part; name the frond, not each leaflet. opposite: true adds the second row in the same primitive. Merges are capped at 262,144 vertices."+ },{name: "mirror",signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",@@ -8960,6 +8972,7 @@ var init_geometry_budget = __esm(() => {subdivisionAttributeBytes: 128 * 1024 * 1024,subdivisionIterations: 10,repeatedMeshes: 1e4,+ curveRepeatVertices: 262144,primitiveSegments: 4096,primitiveGridVertices: 262144,unwrapVertices: 65536,@@ -27263,6 +27276,165 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, opti}return out;}+function repeatAlongCurve(source, points, options) {+ const name = "repeatAlongCurve";+ if (!options || typeof options !== "object")+ throw new TypeError(`${name} needs an options object with count.`);+ const { count, align = "tangent", merge = true, opposite = false } = options;+ assertRepetitionCount(name, opposite ? count * 2 : count);+ if (opposite && align !== "tangent")+ throw new RangeError(`${name} opposite needs align: tangent.`);+ if (align !== "tangent" && align !== "none")+ throw new RangeError(`${name} align must be tangent or none.`);+ if (!Array.isArray(points) || points.length < 2)+ throw new RangeError(`${name} needs at least two points; sample the curve first.`);+ if (points.length > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`${name} accepts at most ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples} points.`);+ for (const [i, point] of points.entries())+ assertFiniteTriple(`${name} points[${i}]`, point);+ const up = options.up ?? [0, 1, 0];+ assertFiniteTriple(`${name} up`, up);+ const upVector = new THREE36.Vector3(...up);+ if (upVector.lengthSq() === 0)+ throw new RangeError(`${name} up must not be zero.`);+ upVector.normalize();+ const span = (label, value, fallback) => {+ const [a, b] = value === undefined ? [fallback, fallback] : Array.isArray(value) ? value : [value, value];+ if (!Number.isFinite(a) || !Number.isFinite(b))+ throw new RangeError(`${name} ${label} must be finite.`);+ return [a, b];+ };+ const scale = span("scale", options.scale, 1);+ if (scale[0] <= 0 || scale[1] <= 0)+ throw new RangeError(`${name} scale must be positive.`);+ const twist = span("twist", options.twist, 0);+ if (align === "none" && (twist[0] !== 0 || twist[1] !== 0))+ throw new RangeError(`${name} twist needs align: tangent.`);+ const start = options.start ?? 0;+ const end = options.end ?? 1;+ if (!(start >= 0 && end <= 1 && start <= end))+ throw new RangeError(`${name} start and end must satisfy 0 <= start <= end <= 1.`);+ const cumulative = [0];+ for (let i = 1;i < points.length; i++) {+ const [ax, ay, az] = points[i - 1];+ const [bx, by, bz] = points[i];+ cumulative.push(cumulative[i - 1] + Math.hypot(bx - ax, by - ay, bz - az));+ }+ const length = cumulative.at(-1);+ if (!(length > 0) || !Number.isFinite(length))+ throw new RangeError(`${name} curve length must be positive and finite.`);+ const frames = [];+ let previousUp = upVector.clone();+ for (let copy = 0;copy < count; copy++) {+ const t = count === 1 ? 0 : copy / (count - 1);+ const s = (start + (end - start) * t) * length;+ let segment = 0;+ while (segment < points.length - 2 && !(s < cumulative[segment + 1]))+ segment++;+ while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])+ segment++;+ const a = new THREE36.Vector3(...points[segment]);+ const b = new THREE36.Vector3(...points[segment + 1]);+ const segmentLength = cumulative[segment + 1] - cumulative[segment];+ const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;+ const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));+ const k = THREE36.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE36.Matrix4;+ let angle = 0;+ if (align === "tangent") {+ const tangent = b.clone().sub(a).normalize();+ let side = upVector.clone().sub(tangent.clone().multiplyScalar(upVector.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = new THREE36.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side.normalize();+ previousUp = side;+ rotation.makeBasis(tangent, side, new THREE36.Vector3().crossVectors(tangent, side));+ angle = THREE36.MathUtils.degToRad(THREE36.MathUtils.lerp(twist[0], twist[1], t));+ }+ for (const extra of opposite ? [0, Math.PI] : [0]) {+ const turned = rotation.clone();+ if (angle + extra)+ turned.multiply(new THREE36.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE36.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE36.Matrix4().makeScale(k, k, k));+ if (!matrix.elements.every(Number.isFinite))+ throw new RangeError(`${name} produced a non-finite copy transform.`);+ frames.push({ matrix, t });+ }+ }+ if (!merge) {+ const mesh = source.isMesh ? source : source.children?.find((child) => child.isMesh);+ if (!mesh)+ throw new TypeError(`${name} with merge: false needs a Mesh source.`);+ const prefix = options.name ?? source.name ?? "Copy";+ return frames.map((frame, i) => {+ const copy = createInstance(`${prefix}${i}`, source, {+ parent: options.parent+ });+ frame.matrix.decompose(copy.position, copy.quaternion, copy.scale);+ return copy;+ });+ }+ const copies = frames.length;+ const geometry = source.isBufferGeometry ? source : source.isMesh ? source.geometry : undefined;+ if (!geometry)+ throw new TypeError(`${name} needs a BufferGeometry or Mesh source.`);+ if (Object.keys(geometry.morphAttributes).length)+ throw new RangeError(`${name} does not copy morph targets.`);+ const positionAttribute = geometry.getAttribute("position");+ if (!positionAttribute)+ throw new RangeError(`${name} source has no position attribute.`);+ const perCopy = positionAttribute.count;+ const total = perCopy * copies;+ if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)+ throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);+ const merged = new THREE36.BufferGeometry;+ const vector = new THREE36.Vector3;+ const normalMatrix = new THREE36.Matrix3;+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const size = attribute.itemSize;+ const transformed = key === "position" || key === "normal" || key === "tangent";+ const ArrayType = transformed ? Float32Array : attribute.array?.constructor ?? Float32Array;+ const out = new ArrayType(total * size);+ for (let copy = 0;copy < copies; copy++) {+ const frame = frames[copy].matrix;+ normalMatrix.getNormalMatrix(frame);+ for (let i = 0;i < perCopy; i++) {+ const target = (copy * perCopy + i) * size;+ if (key === "position") {+ vector.fromBufferAttribute(attribute, i).applyMatrix4(frame);+ out.set([vector.x, vector.y, vector.z], target);+ } else if (key === "normal" || key === "tangent") {+ vector.set(attribute.getX(i), attribute.getY(i), attribute.getZ(i));+ vector.applyMatrix3(normalMatrix).normalize();+ out.set(size === 4 ? [vector.x, vector.y, vector.z, attribute.getW(i)] : [vector.x, vector.y, vector.z], target);+ } else {+ for (let c = 0;c < size; c++)+ out[target + c] = attribute.getComponent(i, c);+ }+ }+ }+ merged.setAttribute(key, new THREE36.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ }+ if (options.along) {+ const along = new Float32Array(total);+ for (let copy = 0;copy < copies; copy++)+ along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);+ merged.setAttribute("_along", new THREE36.BufferAttribute(along, 1));+ }+ const index = geometry.getIndex();+ if (index) {+ const indices = total > 65535 ? new Uint32Array(index.count * copies) : new Uint16Array(index.count * copies);+ for (let copy = 0;copy < copies; copy++)+ for (let i = 0;i < index.count; i++)+ indices[copy * index.count + i] = index.getX(i) + copy * perCopy;+ merged.setIndex(new THREE36.BufferAttribute(indices, 1));+ }+ merged.computeBoundingBox();+ merged.computeBoundingSphere();+ return merged;+}function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();@@ -30799,6 +30971,7 @@ function buildSandboxGlobals(usage, options = {}) {circleProfile: wrap("circleProfile", circleProfile),arrayLinear: wrap("arrayLinear", arrayLinear),arrayRadial: wrap("arrayRadial", arrayRadial),+ repeatAlongCurve: wrap("repeatAlongCurve", repeatAlongCurve),mirror: wrap("mirror", mirror),subdivide: wrap("subdivide", subdivide),mergeVertices: wrap("mergeVertices", mergeVertices),@@ -41821,6 +41994,47 @@ define2("arrayRadial", {aliases: ["circular repeat", "radial pattern"],intents: ["repeat a mesh around a center"]});+define2("repeatAlongCurve", {+ axes: "Each copy's local +X follows the curve tangent (the outgoing segment at a sample point); local +Y points toward up, default [0,1,0], made perpendicular to the tangent. twist rotates about the tangent in degrees.",+ origin: "Each copy is translated to its arc-length position on the curve.",+ coordinates: "Points, up and the merged geometry share one local space; no parent transform is applied.",+ ownership: "merge true returns a new BufferGeometry; merge false creates mesh nodes sharing the source geometry/material.",+ parameters: [+ "points: at least two finite [x,y,z] samples (bezierCurve, catmullRomPath) with positive total length.",+ "count is a safe integer from 1 to 10,000 copies, evenly spaced by arc length from start to end (fractions, default 0 and 1). The source itself is not placed or moved.",+ "scale and twist are a number or an [attachment, tip] pair interpolated across the copies; scale is positive. twist needs align: tangent.",+ "opposite true adds a second copy twisted a further 180 degrees at each position (2 × count copies, same _along).",+ "merge false needs a Mesh source and returns copies named Mesh_<name><i> under parent."+ ],+ topology: [+ "merge true: one primitive whose vertices and indices are the source repeated count times; copies are not welded."+ ],+ preservation: [+ "merge true copies every attribute per copy; UVs and other attributes are unchanged, position/normal/tangent are transformed. along: true adds float _along, 0 on the first copy and 1 on the last.",+ "Material groups and morph targets are not copied; the merged geometry takes one material."+ ],+ cost: "merge true allocates count × source vertices, at most 262,144 vertices; larger merges fail before allocation."+}, {+ references: ["src/ops.ts", "src/geometry-budget.ts"],+ tags: ["repeat", "curve", "foliage", "merge"],+ aliases: ["leaflets along a stem", "copies along a path", "frond leaflets"],+ intents: [+ "repeat cards or leaflets along a curve",+ "merge repeated copies into one primitive with UVs kept"+ ],+ limitations: [+ "Tangents come from the polyline segments; sample curves densely for smooth turns.",+ "The default legacy GLB converter does not export the _along attribute.",+ "Merged copies are one part: they are not separately named or addressable."+ ],+ related: [+ { name: "bezierCurve", relation: "prerequisite" },+ { name: "catmullRomPath", relation: "prerequisite" },+ { name: "foliageCardGeo", relation: "companion" },+ { name: "repeatInstances", relation: "alternative" },+ { name: "arrayLinear", relation: "alternative" }+ ]+});define2("mirror", {...reuseFacts,axes: "Reflects across the origin plane normal to X/Y/Z.",@@ -42585,6 +42799,16 @@ var discoveryIntents = {"regular spacing","bench or fence slats"],+ repeatAlongCurve: [+ "leaflets along a stem",+ "palm frond leaflets",+ "fern frond",+ "repeat cards along a curve",+ "leaves along a branch",+ "one merged primitive per frond"+ ],+ repeatInstances: ["many identical leaves instanced", "instanced repeated parts", "batch copies"],+ crossedQuadsGeo: ["grass clump", "bush or shrub cards", "cross billboard plant"],wallWithOpening: ["wall aperture", "cut a window", "doorway opening", "door or window in a wall"],room: ["hollow enclosure", "walls and floor", "room with doors and windows"],createGableShell: ["enclosed building shell", "gable house with openings"],@@ -42628,7 +42852,7 @@ var discoveryIntents = {boolIntersect: ["intersection of solids", "overlapping volume"],beamBetween: ["beam between points", "bar connecting endpoints"],autoUnwrap: ["unwrap texture coordinates", "UV atlas", "unfold mesh"],- foliageCardGeo: ["thin leaf cutout", "foliage card"],+ foliageCardGeo: ["thin leaf cutout", "foliage card", "single leaflet card", "fern leaf"],foliageMaterial: ["leaf transparency", "foliage cutout", "alpha mask"]};var stopwords = new Set([diff --git a/dist/build.json b/dist/build.jsonindex bca0efd2..e39ef5f4 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:fde0385cddab538fe68c221db77dbc6b8944679a2e86a42ba213e6524ed33cce"+ "bundleHash": "sha256:4cbcdd1fd68e59e1fa4c1117db544fb3feae766778af50a12a2fd9a10d1b24fb"},"agent-run": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:f62ce5ffe1bb811eec81f982cdfa832e35f70d0a14cb6e7b9ba6ce7a2275c607"+ "bundleHash": "sha256:91bc1d3195738d8a2f73be78a4244a31e5683959a31b412826f492721c8353c5"},"agent-providers": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"},"cli": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:fb0adc73d25acba5923a3d1234c637dca133cd326c42a47b60b2751e58e462a1"+ "bundleHash": "sha256:6cacc84f73dbb600481d7549bc77c348013da1ffea0492dae1d00f26e25ec322"},"engine": {- "identity": "sha256:ca2c37a68cba501909fa67cae3f6ee88127a35df8d3508102cf333fd5afc0bdf",+ "identity": "sha256:d71f5b28bc9572e3e74b37e93e6ad9917638d7f1421531506ed48a8e998ea1e9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "dee8f1780b1e49feca7939dae14d72902d9781faad9784b5b4f3b2f2fdd3e76b",+ "sourceHash": "9e6070306969a354eb0817fba2931ec0504db414ecea16f3d06c7c5e85f670a6","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:cadfac179357407c9bd8d719c49125f56129050fa7eb7f9aeac50673fe743014"+ "bundleHash": "sha256:ea01dc20d07ae19bb315d1c8954f403b191156afffa0218e82ea02e15af24724"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex f7dcd59a..ae7f3474 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -5921,6 +5921,7 @@ var init_geometry_budget = __esm(() => {subdivisionAttributeBytes: 128 * 1024 * 1024,subdivisionIterations: 10,repeatedMeshes: 1e4,+ curveRepeatVertices: 262144,primitiveSegments: 4096,primitiveGridVertices: 262144,unwrapVertices: 65536,@@ -24945,6 +24946,165 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, opti}return out;}+function repeatAlongCurve(source, points, options) {+ const name = "repeatAlongCurve";+ if (!options || typeof options !== "object")+ throw new TypeError(`${name} needs an options object with count.`);+ const { count, align = "tangent", merge = true, opposite = false } = options;+ assertRepetitionCount(name, opposite ? count * 2 : count);+ if (opposite && align !== "tangent")+ throw new RangeError(`${name} opposite needs align: tangent.`);+ if (align !== "tangent" && align !== "none")+ throw new RangeError(`${name} align must be tangent or none.`);+ if (!Array.isArray(points) || points.length < 2)+ throw new RangeError(`${name} needs at least two points; sample the curve first.`);+ if (points.length > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`${name} accepts at most ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples} points.`);+ for (const [i, point] of points.entries())+ assertFiniteTriple(`${name} points[${i}]`, point);+ const up = options.up ?? [0, 1, 0];+ assertFiniteTriple(`${name} up`, up);+ const upVector = new THREE36.Vector3(...up);+ if (upVector.lengthSq() === 0)+ throw new RangeError(`${name} up must not be zero.`);+ upVector.normalize();+ const span = (label, value, fallback) => {+ const [a, b] = value === undefined ? [fallback, fallback] : Array.isArray(value) ? value : [value, value];+ if (!Number.isFinite(a) || !Number.isFinite(b))+ throw new RangeError(`${name} ${label} must be finite.`);+ return [a, b];+ };+ const scale = span("scale", options.scale, 1);+ if (scale[0] <= 0 || scale[1] <= 0)+ throw new RangeError(`${name} scale must be positive.`);+ const twist = span("twist", options.twist, 0);+ if (align === "none" && (twist[0] !== 0 || twist[1] !== 0))+ throw new RangeError(`${name} twist needs align: tangent.`);+ const start = options.start ?? 0;+ const end = options.end ?? 1;+ if (!(start >= 0 && end <= 1 && start <= end))+ throw new RangeError(`${name} start and end must satisfy 0 <= start <= end <= 1.`);+ const cumulative = [0];+ for (let i = 1;i < points.length; i++) {+ const [ax, ay, az] = points[i - 1];+ const [bx, by, bz] = points[i];+ cumulative.push(cumulative[i - 1] + Math.hypot(bx - ax, by - ay, bz - az));+ }+ const length = cumulative.at(-1);+ if (!(length > 0) || !Number.isFinite(length))+ throw new RangeError(`${name} curve length must be positive and finite.`);+ const frames = [];+ let previousUp = upVector.clone();+ for (let copy = 0;copy < count; copy++) {+ const t = count === 1 ? 0 : copy / (count - 1);+ const s = (start + (end - start) * t) * length;+ let segment = 0;+ while (segment < points.length - 2 && !(s < cumulative[segment + 1]))+ segment++;+ while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])+ segment++;+ const a = new THREE36.Vector3(...points[segment]);+ const b = new THREE36.Vector3(...points[segment + 1]);+ const segmentLength = cumulative[segment + 1] - cumulative[segment];+ const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;+ const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));+ const k = THREE36.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE36.Matrix4;+ let angle = 0;+ if (align === "tangent") {+ const tangent = b.clone().sub(a).normalize();+ let side = upVector.clone().sub(tangent.clone().multiplyScalar(upVector.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = new THREE36.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side.normalize();+ previousUp = side;+ rotation.makeBasis(tangent, side, new THREE36.Vector3().crossVectors(tangent, side));+ angle = THREE36.MathUtils.degToRad(THREE36.MathUtils.lerp(twist[0], twist[1], t));+ }+ for (const extra of opposite ? [0, Math.PI] : [0]) {+ const turned = rotation.clone();+ if (angle + extra)+ turned.multiply(new THREE36.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE36.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE36.Matrix4().makeScale(k, k, k));+ if (!matrix.elements.every(Number.isFinite))+ throw new RangeError(`${name} produced a non-finite copy transform.`);+ frames.push({ matrix, t });+ }+ }+ if (!merge) {+ const mesh = source.isMesh ? source : source.children?.find((child) => child.isMesh);+ if (!mesh)+ throw new TypeError(`${name} with merge: false needs a Mesh source.`);+ const prefix = options.name ?? source.name ?? "Copy";+ return frames.map((frame, i) => {+ const copy = createInstance(`${prefix}${i}`, source, {+ parent: options.parent+ });+ frame.matrix.decompose(copy.position, copy.quaternion, copy.scale);+ return copy;+ });+ }+ const copies = frames.length;+ const geometry = source.isBufferGeometry ? source : source.isMesh ? source.geometry : undefined;+ if (!geometry)+ throw new TypeError(`${name} needs a BufferGeometry or Mesh source.`);+ if (Object.keys(geometry.morphAttributes).length)+ throw new RangeError(`${name} does not copy morph targets.`);+ const positionAttribute = geometry.getAttribute("position");+ if (!positionAttribute)+ throw new RangeError(`${name} source has no position attribute.`);+ const perCopy = positionAttribute.count;+ const total = perCopy * copies;+ if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)+ throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);+ const merged = new THREE36.BufferGeometry;+ const vector = new THREE36.Vector3;+ const normalMatrix = new THREE36.Matrix3;+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const size = attribute.itemSize;+ const transformed = key === "position" || key === "normal" || key === "tangent";+ const ArrayType = transformed ? Float32Array : attribute.array?.constructor ?? Float32Array;+ const out = new ArrayType(total * size);+ for (let copy = 0;copy < copies; copy++) {+ const frame = frames[copy].matrix;+ normalMatrix.getNormalMatrix(frame);+ for (let i = 0;i < perCopy; i++) {+ const target = (copy * perCopy + i) * size;+ if (key === "position") {+ vector.fromBufferAttribute(attribute, i).applyMatrix4(frame);+ out.set([vector.x, vector.y, vector.z], target);+ } else if (key === "normal" || key === "tangent") {+ vector.set(attribute.getX(i), attribute.getY(i), attribute.getZ(i));+ vector.applyMatrix3(normalMatrix).normalize();+ out.set(size === 4 ? [vector.x, vector.y, vector.z, attribute.getW(i)] : [vector.x, vector.y, vector.z], target);+ } else {+ for (let c = 0;c < size; c++)+ out[target + c] = attribute.getComponent(i, c);+ }+ }+ }+ merged.setAttribute(key, new THREE36.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ }+ if (options.along) {+ const along = new Float32Array(total);+ for (let copy = 0;copy < copies; copy++)+ along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);+ merged.setAttribute("_along", new THREE36.BufferAttribute(along, 1));+ }+ const index = geometry.getIndex();+ if (index) {+ const indices = total > 65535 ? new Uint32Array(index.count * copies) : new Uint16Array(index.count * copies);+ for (let copy = 0;copy < copies; copy++)+ for (let i = 0;i < index.count; i++)+ indices[copy * index.count + i] = index.getX(i) + copy * perCopy;+ merged.setIndex(new THREE36.BufferAttribute(indices, 1));+ }+ merged.computeBoundingBox();+ merged.computeBoundingSphere();+ return merged;+}function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();@@ -28481,6 +28641,7 @@ function buildSandboxGlobals(usage, options = {}) {circleProfile: wrap("circleProfile", circleProfile),arrayLinear: wrap("arrayLinear", arrayLinear),arrayRadial: wrap("arrayRadial", arrayRadial),+ repeatAlongCurve: wrap("repeatAlongCurve", repeatAlongCurve),mirror: wrap("mirror", mirror),subdivide: wrap("subdivide", subdivide),mergeVertices: wrap("mergeVertices", mergeVertices),@@ -30355,6 +30516,18 @@ arrayLinear('Post', post, 10, [0.5, 0, 0], root);`example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });arrayRadial('Bolt', bolt, 8, 'y', root);`},+ {+ name: "repeatAlongCurve",+ signature: "repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })",+ returns: "THREE.BufferGeometry (merge: true) or THREE.Object3D[] (merge: false)",+ category: "arrays",+ description: "Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns shared-geometry nodes like arrayLinear.",+ example: `const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);+const leaflet = foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 });+const frond = repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true });+createPart('Frond_0', frond, foliageMaterial(albedo), { parent: root });`,+ promptNotes: "One merged geometry is one part; name the frond, not each leaflet. opposite: true adds the second row in the same primitive. Merges are capped at 262,144 vertices."+ },{name: "mirror",signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",@@ -45150,6 +45323,47 @@ var init_helper_contracts = __esm(() => {aliases: ["circular repeat", "radial pattern"],intents: ["repeat a mesh around a center"]});+ define2("repeatAlongCurve", {+ axes: "Each copy's local +X follows the curve tangent (the outgoing segment at a sample point); local +Y points toward up, default [0,1,0], made perpendicular to the tangent. twist rotates about the tangent in degrees.",+ origin: "Each copy is translated to its arc-length position on the curve.",+ coordinates: "Points, up and the merged geometry share one local space; no parent transform is applied.",+ ownership: "merge true returns a new BufferGeometry; merge false creates mesh nodes sharing the source geometry/material.",+ parameters: [+ "points: at least two finite [x,y,z] samples (bezierCurve, catmullRomPath) with positive total length.",+ "count is a safe integer from 1 to 10,000 copies, evenly spaced by arc length from start to end (fractions, default 0 and 1). The source itself is not placed or moved.",+ "scale and twist are a number or an [attachment, tip] pair interpolated across the copies; scale is positive. twist needs align: tangent.",+ "opposite true adds a second copy twisted a further 180 degrees at each position (2 × count copies, same _along).",+ "merge false needs a Mesh source and returns copies named Mesh_<name><i> under parent."+ ],+ topology: [+ "merge true: one primitive whose vertices and indices are the source repeated count times; copies are not welded."+ ],+ preservation: [+ "merge true copies every attribute per copy; UVs and other attributes are unchanged, position/normal/tangent are transformed. along: true adds float _along, 0 on the first copy and 1 on the last.",+ "Material groups and morph targets are not copied; the merged geometry takes one material."+ ],+ cost: "merge true allocates count × source vertices, at most 262,144 vertices; larger merges fail before allocation."+ }, {+ references: ["src/ops.ts", "src/geometry-budget.ts"],+ tags: ["repeat", "curve", "foliage", "merge"],+ aliases: ["leaflets along a stem", "copies along a path", "frond leaflets"],+ intents: [+ "repeat cards or leaflets along a curve",+ "merge repeated copies into one primitive with UVs kept"+ ],+ limitations: [+ "Tangents come from the polyline segments; sample curves densely for smooth turns.",+ "The default legacy GLB converter does not export the _along attribute.",+ "Merged copies are one part: they are not separately named or addressable."+ ],+ related: [+ { name: "bezierCurve", relation: "prerequisite" },+ { name: "catmullRomPath", relation: "prerequisite" },+ { name: "foliageCardGeo", relation: "companion" },+ { name: "repeatInstances", relation: "alternative" },+ { name: "arrayLinear", relation: "alternative" }+ ]+ });define2("mirror", {...reuseFacts,axes: "Reflects across the origin plane normal to X/Y/Z.",@@ -45920,6 +46134,16 @@ var init_intents = __esm(() => {"regular spacing","bench or fence slats"],+ repeatAlongCurve: [+ "leaflets along a stem",+ "palm frond leaflets",+ "fern frond",+ "repeat cards along a curve",+ "leaves along a branch",+ "one merged primitive per frond"+ ],+ repeatInstances: ["many identical leaves instanced", "instanced repeated parts", "batch copies"],+ crossedQuadsGeo: ["grass clump", "bush or shrub cards", "cross billboard plant"],wallWithOpening: ["wall aperture", "cut a window", "doorway opening", "door or window in a wall"],room: ["hollow enclosure", "walls and floor", "room with doors and windows"],createGableShell: ["enclosed building shell", "gable house with openings"],@@ -45963,7 +46187,7 @@ var init_intents = __esm(() => {boolIntersect: ["intersection of solids", "overlapping volume"],beamBetween: ["beam between points", "bar connecting endpoints"],autoUnwrap: ["unwrap texture coordinates", "UV atlas", "unfold mesh"],- foliageCardGeo: ["thin leaf cutout", "foliage card"],+ foliageCardGeo: ["thin leaf cutout", "foliage card", "single leaflet card", "fern leaf"],foliageMaterial: ["leaf transparency", "foliage cutout", "alpha mask"]};stopwords = new Set([diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 977fefee..95c8fa86 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -6548,6 +6548,7 @@ var init_geometry_budget = __esm(() => {subdivisionAttributeBytes: 128 * 1024 * 1024,subdivisionIterations: 10,repeatedMeshes: 1e4,+ curveRepeatVertices: 262144,primitiveSegments: 4096,primitiveGridVertices: 262144,unwrapVertices: 65536,@@ -18443,6 +18444,165 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, opti}return out;}+function repeatAlongCurve(source, points, options) {+ const name = "repeatAlongCurve";+ if (!options || typeof options !== "object")+ throw new TypeError(`${name} needs an options object with count.`);+ const { count, align = "tangent", merge = true, opposite = false } = options;+ assertRepetitionCount(name, opposite ? count * 2 : count);+ if (opposite && align !== "tangent")+ throw new RangeError(`${name} opposite needs align: tangent.`);+ if (align !== "tangent" && align !== "none")+ throw new RangeError(`${name} align must be tangent or none.`);+ if (!Array.isArray(points) || points.length < 2)+ throw new RangeError(`${name} needs at least two points; sample the curve first.`);+ if (points.length > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`${name} accepts at most ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples} points.`);+ for (const [i, point] of points.entries())+ assertFiniteTriple(`${name} points[${i}]`, point);+ const up = options.up ?? [0, 1, 0];+ assertFiniteTriple(`${name} up`, up);+ const upVector = new THREE33.Vector3(...up);+ if (upVector.lengthSq() === 0)+ throw new RangeError(`${name} up must not be zero.`);+ upVector.normalize();+ const span = (label, value, fallback) => {+ const [a, b] = value === undefined ? [fallback, fallback] : Array.isArray(value) ? value : [value, value];+ if (!Number.isFinite(a) || !Number.isFinite(b))+ throw new RangeError(`${name} ${label} must be finite.`);+ return [a, b];+ };+ const scale = span("scale", options.scale, 1);+ if (scale[0] <= 0 || scale[1] <= 0)+ throw new RangeError(`${name} scale must be positive.`);+ const twist = span("twist", options.twist, 0);+ if (align === "none" && (twist[0] !== 0 || twist[1] !== 0))+ throw new RangeError(`${name} twist needs align: tangent.`);+ const start = options.start ?? 0;+ const end = options.end ?? 1;+ if (!(start >= 0 && end <= 1 && start <= end))+ throw new RangeError(`${name} start and end must satisfy 0 <= start <= end <= 1.`);+ const cumulative = [0];+ for (let i = 1;i < points.length; i++) {+ const [ax, ay, az] = points[i - 1];+ const [bx, by, bz] = points[i];+ cumulative.push(cumulative[i - 1] + Math.hypot(bx - ax, by - ay, bz - az));+ }+ const length = cumulative.at(-1);+ if (!(length > 0) || !Number.isFinite(length))+ throw new RangeError(`${name} curve length must be positive and finite.`);+ const frames = [];+ let previousUp = upVector.clone();+ for (let copy = 0;copy < count; copy++) {+ const t = count === 1 ? 0 : copy / (count - 1);+ const s = (start + (end - start) * t) * length;+ let segment = 0;+ while (segment < points.length - 2 && !(s < cumulative[segment + 1]))+ segment++;+ while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])+ segment++;+ const a = new THREE33.Vector3(...points[segment]);+ const b = new THREE33.Vector3(...points[segment + 1]);+ const segmentLength = cumulative[segment + 1] - cumulative[segment];+ const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;+ const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));+ const k = THREE33.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE33.Matrix4;+ let angle = 0;+ if (align === "tangent") {+ const tangent = b.clone().sub(a).normalize();+ let side = upVector.clone().sub(tangent.clone().multiplyScalar(upVector.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = new THREE33.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side.normalize();+ previousUp = side;+ rotation.makeBasis(tangent, side, new THREE33.Vector3().crossVectors(tangent, side));+ angle = THREE33.MathUtils.degToRad(THREE33.MathUtils.lerp(twist[0], twist[1], t));+ }+ for (const extra of opposite ? [0, Math.PI] : [0]) {+ const turned = rotation.clone();+ if (angle + extra)+ turned.multiply(new THREE33.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE33.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE33.Matrix4().makeScale(k, k, k));+ if (!matrix.elements.every(Number.isFinite))+ throw new RangeError(`${name} produced a non-finite copy transform.`);+ frames.push({ matrix, t });+ }+ }+ if (!merge) {+ const mesh = source.isMesh ? source : source.children?.find((child) => child.isMesh);+ if (!mesh)+ throw new TypeError(`${name} with merge: false needs a Mesh source.`);+ const prefix = options.name ?? source.name ?? "Copy";+ return frames.map((frame, i) => {+ const copy = createInstance(`${prefix}${i}`, source, {+ parent: options.parent+ });+ frame.matrix.decompose(copy.position, copy.quaternion, copy.scale);+ return copy;+ });+ }+ const copies = frames.length;+ const geometry = source.isBufferGeometry ? source : source.isMesh ? source.geometry : undefined;+ if (!geometry)+ throw new TypeError(`${name} needs a BufferGeometry or Mesh source.`);+ if (Object.keys(geometry.morphAttributes).length)+ throw new RangeError(`${name} does not copy morph targets.`);+ const positionAttribute = geometry.getAttribute("position");+ if (!positionAttribute)+ throw new RangeError(`${name} source has no position attribute.`);+ const perCopy = positionAttribute.count;+ const total = perCopy * copies;+ if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)+ throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);+ const merged = new THREE33.BufferGeometry;+ const vector = new THREE33.Vector3;+ const normalMatrix = new THREE33.Matrix3;+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const size = attribute.itemSize;+ const transformed = key === "position" || key === "normal" || key === "tangent";+ const ArrayType = transformed ? Float32Array : attribute.array?.constructor ?? Float32Array;+ const out = new ArrayType(total * size);+ for (let copy = 0;copy < copies; copy++) {+ const frame = frames[copy].matrix;+ normalMatrix.getNormalMatrix(frame);+ for (let i = 0;i < perCopy; i++) {+ const target = (copy * perCopy + i) * size;+ if (key === "position") {+ vector.fromBufferAttribute(attribute, i).applyMatrix4(frame);+ out.set([vector.x, vector.y, vector.z], target);+ } else if (key === "normal" || key === "tangent") {+ vector.set(attribute.getX(i), attribute.getY(i), attribute.getZ(i));+ vector.applyMatrix3(normalMatrix).normalize();+ out.set(size === 4 ? [vector.x, vector.y, vector.z, attribute.getW(i)] : [vector.x, vector.y, vector.z], target);+ } else {+ for (let c = 0;c < size; c++)+ out[target + c] = attribute.getComponent(i, c);+ }+ }+ }+ merged.setAttribute(key, new THREE33.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ }+ if (options.along) {+ const along = new Float32Array(total);+ for (let copy = 0;copy < copies; copy++)+ along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);+ merged.setAttribute("_along", new THREE33.BufferAttribute(along, 1));+ }+ const index = geometry.getIndex();+ if (index) {+ const indices = total > 65535 ? new Uint32Array(index.count * copies) : new Uint16Array(index.count * copies);+ for (let copy = 0;copy < copies; copy++)+ for (let i = 0;i < index.count; i++)+ indices[copy * index.count + i] = index.getX(i) + copy * perCopy;+ merged.setIndex(new THREE33.BufferAttribute(indices, 1));+ }+ merged.computeBoundingBox();+ merged.computeBoundingSphere();+ return merged;+}function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();@@ -25246,6 +25406,7 @@ function buildSandboxGlobals(usage, options = {}) {circleProfile: wrap("circleProfile", circleProfile),arrayLinear: wrap("arrayLinear", arrayLinear),arrayRadial: wrap("arrayRadial", arrayRadial),+ repeatAlongCurve: wrap("repeatAlongCurve", repeatAlongCurve),mirror: wrap("mirror", mirror),subdivide: wrap("subdivide", subdivide),mergeVertices: wrap("mergeVertices", mergeVertices),@@ -27134,6 +27295,18 @@ arrayLinear('Post', post, 10, [0.5, 0, 0], root);`example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });arrayRadial('Bolt', bolt, 8, 'y', root);`},+ {+ name: "repeatAlongCurve",+ signature: "repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })",+ returns: "THREE.BufferGeometry (merge: true) or THREE.Object3D[] (merge: false)",+ category: "arrays",+ description: "Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns shared-geometry nodes like arrayLinear.",+ example: `const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);+const leaflet = foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 });+const frond = repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true });+createPart('Frond_0', frond, foliageMaterial(albedo), { parent: root });`,+ promptNotes: "One merged geometry is one part; name the frond, not each leaflet. opposite: true adds the second row in the same primitive. Merges are capped at 262,144 vertices."+ },{name: "mirror",signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex dd95bab9..76989f2c 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -7733,6 +7733,7 @@ var init_geometry_budget = __esm(() => {subdivisionAttributeBytes: 128 * 1024 * 1024,subdivisionIterations: 10,repeatedMeshes: 1e4,+ curveRepeatVertices: 262144,primitiveSegments: 4096,primitiveGridVertices: 262144,unwrapVertices: 65536,@@ -24509,6 +24510,165 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, opti}return out;}+function repeatAlongCurve(source, points, options) {+ const name = "repeatAlongCurve";+ if (!options || typeof options !== "object")+ throw new TypeError(`${name} needs an options object with count.`);+ const { count, align = "tangent", merge = true, opposite = false } = options;+ assertRepetitionCount(name, opposite ? count * 2 : count);+ if (opposite && align !== "tangent")+ throw new RangeError(`${name} opposite needs align: tangent.`);+ if (align !== "tangent" && align !== "none")+ throw new RangeError(`${name} align must be tangent or none.`);+ if (!Array.isArray(points) || points.length < 2)+ throw new RangeError(`${name} needs at least two points; sample the curve first.`);+ if (points.length > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`${name} accepts at most ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples} points.`);+ for (const [i, point] of points.entries())+ assertFiniteTriple(`${name} points[${i}]`, point);+ const up = options.up ?? [0, 1, 0];+ assertFiniteTriple(`${name} up`, up);+ const upVector = new THREE37.Vector3(...up);+ if (upVector.lengthSq() === 0)+ throw new RangeError(`${name} up must not be zero.`);+ upVector.normalize();+ const span = (label, value, fallback) => {+ const [a, b] = value === undefined ? [fallback, fallback] : Array.isArray(value) ? value : [value, value];+ if (!Number.isFinite(a) || !Number.isFinite(b))+ throw new RangeError(`${name} ${label} must be finite.`);+ return [a, b];+ };+ const scale = span("scale", options.scale, 1);+ if (scale[0] <= 0 || scale[1] <= 0)+ throw new RangeError(`${name} scale must be positive.`);+ const twist = span("twist", options.twist, 0);+ if (align === "none" && (twist[0] !== 0 || twist[1] !== 0))+ throw new RangeError(`${name} twist needs align: tangent.`);+ const start = options.start ?? 0;+ const end = options.end ?? 1;+ if (!(start >= 0 && end <= 1 && start <= end))+ throw new RangeError(`${name} start and end must satisfy 0 <= start <= end <= 1.`);+ const cumulative = [0];+ for (let i = 1;i < points.length; i++) {+ const [ax, ay, az] = points[i - 1];+ const [bx, by, bz] = points[i];+ cumulative.push(cumulative[i - 1] + Math.hypot(bx - ax, by - ay, bz - az));+ }+ const length = cumulative.at(-1);+ if (!(length > 0) || !Number.isFinite(length))+ throw new RangeError(`${name} curve length must be positive and finite.`);+ const frames = [];+ let previousUp = upVector.clone();+ for (let copy = 0;copy < count; copy++) {+ const t = count === 1 ? 0 : copy / (count - 1);+ const s = (start + (end - start) * t) * length;+ let segment = 0;+ while (segment < points.length - 2 && !(s < cumulative[segment + 1]))+ segment++;+ while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])+ segment++;+ const a = new THREE37.Vector3(...points[segment]);+ const b = new THREE37.Vector3(...points[segment + 1]);+ const segmentLength = cumulative[segment + 1] - cumulative[segment];+ const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;+ const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));+ const k = THREE37.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE37.Matrix4;+ let angle = 0;+ if (align === "tangent") {+ const tangent = b.clone().sub(a).normalize();+ let side = upVector.clone().sub(tangent.clone().multiplyScalar(upVector.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));+ if (side.lengthSq() < 0.000000000001)+ side = new THREE37.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side.normalize();+ previousUp = side;+ rotation.makeBasis(tangent, side, new THREE37.Vector3().crossVectors(tangent, side));+ angle = THREE37.MathUtils.degToRad(THREE37.MathUtils.lerp(twist[0], twist[1], t));+ }+ for (const extra of opposite ? [0, Math.PI] : [0]) {+ const turned = rotation.clone();+ if (angle + extra)+ turned.multiply(new THREE37.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE37.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE37.Matrix4().makeScale(k, k, k));+ if (!matrix.elements.every(Number.isFinite))+ throw new RangeError(`${name} produced a non-finite copy transform.`);+ frames.push({ matrix, t });+ }+ }+ if (!merge) {+ const mesh = source.isMesh ? source : source.children?.find((child) => child.isMesh);+ if (!mesh)+ throw new TypeError(`${name} with merge: false needs a Mesh source.`);+ const prefix = options.name ?? source.name ?? "Copy";+ return frames.map((frame, i) => {+ const copy = createInstance(`${prefix}${i}`, source, {+ parent: options.parent+ });+ frame.matrix.decompose(copy.position, copy.quaternion, copy.scale);+ return copy;+ });+ }+ const copies = frames.length;+ const geometry = source.isBufferGeometry ? source : source.isMesh ? source.geometry : undefined;+ if (!geometry)+ throw new TypeError(`${name} needs a BufferGeometry or Mesh source.`);+ if (Object.keys(geometry.morphAttributes).length)+ throw new RangeError(`${name} does not copy morph targets.`);+ const positionAttribute = geometry.getAttribute("position");+ if (!positionAttribute)+ throw new RangeError(`${name} source has no position attribute.`);+ const perCopy = positionAttribute.count;+ const total = perCopy * copies;+ if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)+ throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);+ const merged = new THREE37.BufferGeometry;+ const vector = new THREE37.Vector3;+ const normalMatrix = new THREE37.Matrix3;+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const size = attribute.itemSize;+ const transformed = key === "position" || key === "normal" || key === "tangent";+ const ArrayType = transformed ? Float32Array : attribute.array?.constructor ?? Float32Array;+ const out = new ArrayType(total * size);+ for (let copy = 0;copy < copies; copy++) {+ const frame = frames[copy].matrix;+ normalMatrix.getNormalMatrix(frame);+ for (let i = 0;i < perCopy; i++) {+ const target = (copy * perCopy + i) * size;+ if (key === "position") {+ vector.fromBufferAttribute(attribute, i).applyMatrix4(frame);+ out.set([vector.x, vector.y, vector.z], target);+ } else if (key === "normal" || key === "tangent") {+ vector.set(attribute.getX(i), attribute.getY(i), attribute.getZ(i));+ vector.applyMatrix3(normalMatrix).normalize();+ out.set(size === 4 ? [vector.x, vector.y, vector.z, attribute.getW(i)] : [vector.x, vector.y, vector.z], target);+ } else {+ for (let c = 0;c < size; c++)+ out[target + c] = attribute.getComponent(i, c);+ }+ }+ }+ merged.setAttribute(key, new THREE37.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ }+ if (options.along) {+ const along = new Float32Array(total);+ for (let copy = 0;copy < copies; copy++)+ along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);+ merged.setAttribute("_along", new THREE37.BufferAttribute(along, 1));+ }+ const index = geometry.getIndex();+ if (index) {+ const indices = total > 65535 ? new Uint32Array(index.count * copies) : new Uint16Array(index.count * copies);+ for (let copy = 0;copy < copies; copy++)+ for (let i = 0;i < index.count; i++)+ indices[copy * index.count + i] = index.getX(i) + copy * perCopy;+ merged.setIndex(new THREE37.BufferAttribute(indices, 1));+ }+ merged.computeBoundingBox();+ merged.computeBoundingSphere();+ return merged;+}function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();@@ -28045,6 +28205,7 @@ function buildSandboxGlobals(usage, options = {}) {circleProfile: wrap("circleProfile", circleProfile),arrayLinear: wrap("arrayLinear", arrayLinear),arrayRadial: wrap("arrayRadial", arrayRadial),+ repeatAlongCurve: wrap("repeatAlongCurve", repeatAlongCurve),mirror: wrap("mirror", mirror),subdivide: wrap("subdivide", subdivide),mergeVertices: wrap("mergeVertices", mergeVertices),@@ -29919,6 +30080,18 @@ arrayLinear('Post', post, 10, [0.5, 0, 0], root);`example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });arrayRadial('Bolt', bolt, 8, 'y', root);`},+ {+ name: "repeatAlongCurve",+ signature: "repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })",+ returns: "THREE.BufferGeometry (merge: true) or THREE.Object3D[] (merge: false)",+ category: "arrays",+ description: "Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns shared-geometry nodes like arrayLinear.",+ example: `const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);+const leaflet = foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 });+const frond = repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true });+createPart('Frond_0', frond, foliageMaterial(albedo), { parent: root });`,+ promptNotes: "One merged geometry is one part; name the frond, not each leaflet. opposite: true adds the second row in the same primitive. Merges are capped at 262,144 vertices."+ },{name: "mirror",signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",@@ -45936,6 +46109,47 @@ define2("arrayRadial", {aliases: ["circular repeat", "radial pattern"],intents: ["repeat a mesh around a center"]});+define2("repeatAlongCurve", {+ axes: "Each copy's local +X follows the curve tangent (the outgoing segment at a sample point); local +Y points toward up, default [0,1,0], made perpendicular to the tangent. twist rotates about the tangent in degrees.",+ origin: "Each copy is translated to its arc-length position on the curve.",+ coordinates: "Points, up and the merged geometry share one local space; no parent transform is applied.",+ ownership: "merge true returns a new BufferGeometry; merge false creates mesh nodes sharing the source geometry/material.",+ parameters: [+ "points: at least two finite [x,y,z] samples (bezierCurve, catmullRomPath) with positive total length.",+ "count is a safe integer from 1 to 10,000 copies, evenly spaced by arc length from start to end (fractions, default 0 and 1). The source itself is not placed or moved.",+ "scale and twist are a number or an [attachment, tip] pair interpolated across the copies; scale is positive. twist needs align: tangent.",+ "opposite true adds a second copy twisted a further 180 degrees at each position (2 × count copies, same _along).",+ "merge false needs a Mesh source and returns copies named Mesh_<name><i> under parent."+ ],+ topology: [+ "merge true: one primitive whose vertices and indices are the source repeated count times; copies are not welded."+ ],+ preservation: [+ "merge true copies every attribute per copy; UVs and other attributes are unchanged, position/normal/tangent are transformed. along: true adds float _along, 0 on the first copy and 1 on the last.",+ "Material groups and morph targets are not copied; the merged geometry takes one material."+ ],+ cost: "merge true allocates count × source vertices, at most 262,144 vertices; larger merges fail before allocation."+}, {+ references: ["src/ops.ts", "src/geometry-budget.ts"],+ tags: ["repeat", "curve", "foliage", "merge"],+ aliases: ["leaflets along a stem", "copies along a path", "frond leaflets"],+ intents: [+ "repeat cards or leaflets along a curve",+ "merge repeated copies into one primitive with UVs kept"+ ],+ limitations: [+ "Tangents come from the polyline segments; sample curves densely for smooth turns.",+ "The default legacy GLB converter does not export the _along attribute.",+ "Merged copies are one part: they are not separately named or addressable."+ ],+ related: [+ { name: "bezierCurve", relation: "prerequisite" },+ { name: "catmullRomPath", relation: "prerequisite" },+ { name: "foliageCardGeo", relation: "companion" },+ { name: "repeatInstances", relation: "alternative" },+ { name: "arrayLinear", relation: "alternative" }+ ]+});define2("mirror", {...reuseFacts,axes: "Reflects across the origin plane normal to X/Y/Z.",@@ -46700,6 +46914,16 @@ var discoveryIntents = {"regular spacing","bench or fence slats"],+ repeatAlongCurve: [+ "leaflets along a stem",+ "palm frond leaflets",+ "fern frond",+ "repeat cards along a curve",+ "leaves along a branch",+ "one merged primitive per frond"+ ],+ repeatInstances: ["many identical leaves instanced", "instanced repeated parts", "batch copies"],+ crossedQuadsGeo: ["grass clump", "bush or shrub cards", "cross billboard plant"],wallWithOpening: ["wall aperture", "cut a window", "doorway opening", "door or window in a wall"],room: ["hollow enclosure", "walls and floor", "room with doors and windows"],createGableShell: ["enclosed building shell", "gable house with openings"],@@ -46743,7 +46967,7 @@ var discoveryIntents = {boolIntersect: ["intersection of solids", "overlapping volume"],beamBetween: ["beam between points", "bar connecting endpoints"],autoUnwrap: ["unwrap texture coordinates", "UV atlas", "unfold mesh"],- foliageCardGeo: ["thin leaf cutout", "foliage card"],+ foliageCardGeo: ["thin leaf cutout", "foliage card", "single leaflet card", "fern leaf"],foliageMaterial: ["leaf transparency", "foliage cutout", "alpha mask"]};var stopwords = new Set([diff --git a/docs/geometry.md b/docs/geometry.mdindex 412853c5..4818c7e6 100644--- a/docs/geometry.md+++ b/docs/geometry.md@@ -398,6 +398,8 @@ Output is experimental, has no UVs, and records resolution and evaluation counts`arrayLinear` and `arrayRadial` require integer counts from 1 to 10,000, including the existing source; their return value contains `count - 1` new meshes. Count 1 returns no copies. Frames, offsets/centers, and all resulting positions must be finite, with rejection before attaching any copies. Resources remain shared and these helpers do not batch draw calls.+`repeatAlongCurve(source, points, { count, ... })` places `count` copies along a sampled curve, evenly spaced by arc length between `start` and `end` (fractions of its length). Each copy's local +X follows the tangent of the segment it sits on (the outgoing segment at a sample point) and local +Y points toward `up`, default `[0,1,0]`, made perpendicular to the tangent. `scale` and `twist` are constant or interpolated from attachment to tip; `opposite: true` adds a copy twisted a further 180 degrees at each position. With the default `merge: true` it returns one BufferGeometry: every source attribute is copied per copy, UVs unchanged, positions, normals and tangents transformed, material groups and morph targets not copied, and `along: true` adds a float `_along` attribute from 0 on the first copy to 1 on the last (the default `legacy` GLB converter does not yet export author underscore attributes, so `_along` is available in source but not in the saved GLB; see [#195](https://github.com/instruktlabs/kiln/issues/195)). A merge larger than 262,144 vertices fails before allocating. With `merge: false` it returns shared-geometry mesh nodes, like `arrayLinear`, and does not move the source.+These are per-operation compute limits for every asset. Choose a coarser sampling/subdivision or deliberately split large work; no asset category selects a different budget.Basic shape factories now reject invalid dimensions and segment counts beforediff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.mdindex 169dcf97..f75b4dfe 100644--- a/skills/kiln-author-asset/references/geometry-recipes.md+++ b/skills/kiln-author-asset/references/geometry-recipes.md@@ -258,6 +258,16 @@ material capabilities before choosing a delivery resource, then inspect GPU viewand destination filtering/backfaces. Raw `THREE.DataTexture` is not an availableauthoring route. Solid leaves and custom surfaces remain valid alternatives.+For fronds, ferns and leaves along a stem, build one leaflet (`foliageCardGeo` or a+small custom card), sample the stem with `bezierCurve` or `catmullRomPath`, and+place copies with `repeatAlongCurve`. Each copy's +X follows the stem and +Y points+toward `up`; `scale` and `twist` taper from attachment to tip, and `opposite: true`+adds the second row. Choose the representation the destination needs: the default+merge returns one geometry, so one primitive per frond with each copy's UVs kept;+`merge: false` returns shared-geometry nodes, which `repeatInstances` can batch in a+three.js runtime export. Do not hand-build hundreds of leaflets with `meshGeo`.+Grass clumps and shrubs can use `crossedQuadsGeo` cards.+For original cutouts, `proceduralTexture` V3 authors rectangular RGBA pixels;`textureAtlas` combines named fixed regions from V3 recipes or exact saved maprevisions. Discover their full contracts before authoring. Atlas regions do not@@ -377,7 +387,9 @@ choice belongs to export settings, not asset source.Put repeated assemblies in ordinary functions with JSDoc parameters and named return values. Pass parent/material explicitly; return the assembly root and attachment markers. Change one parameter at the call site for a variant. Give such a function a name prefix or suffix and use it for every part it creates (`Leg_L`, `Leg_R`); calling it twice with the same names makes duplicate node names, which QA reports as `UNIVERSAL_DUPLICATE_NODE_NAME`. The runnable [reusable-frame recipe](reusable-frame.kiln.js) demonstrates this without imports or hidden dependencies.Include the assembly and element index in repeated child names as well, so each-leaflet, slat or fastener remains addressable during revision comparison. When a+separately addressable slat, fastener or leaflet node remains addressable during+revision comparison. This applies to parts, not to copies merged into one geometry:+a frond built by `repeatAlongCurve` is one named part (`Frond_3`). When aresize must retain those children, keep their count explicit and redistributetheir attachment positions; deriving the count from the new length can silentlydelete parts. Check the exported child inventory as well as the changed outline.diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex d842f2ea..99547ac8 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -475,6 +475,17 @@ arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?, center?: [x,// hierarchy-preserving assembly replication.// e.g. const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position:// [1,0,0], parent: root }); arrayRadial('Bolt', bolt, 8, 'y', root);+repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })+ // Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each+ // copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns+ // ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns+ // shared-geometry nodes like arrayLinear.+ // NOTE: One merged geometry is one part; name the frond, not each leaflet. opposite: true+ // adds the second row in the same primitive. Merges are capped at 262,144 vertices.+ // e.g. const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32); const leaflet =+ // foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 }); const frond =+ // repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1,+ // opposite: true }); createPart('Frond_0', frond, foliageMaterial(albedo), { parent: root });mirror(name, source, axis: 'x'|'y'|'z', parent?)// Reflects source across the plane whose normal is \`axis\`. Uses negative scale (winding flip// handled by viewers).diff --git a/src/__tests__/ops.test.ts b/src/__tests__/ops.test.tsindex 1984864a..c795eebe 100644--- a/src/__tests__/ops.test.ts+++ b/src/__tests__/ops.test.ts@@ -7,10 +7,18 @@import { describe, it, expect } from 'bun:test';import * as THREE from 'three';-import { boxGeo, sphereGeo, cylinderGeo, createPart, gameMaterial } from '../primitives';+import {+ boxGeo,+ sphereGeo,+ cylinderGeo,+ createPart,+ foliageCardGeo,+ gameMaterial,+} from '../primitives';import {arrayLinear,arrayRadial,+ repeatAlongCurve,mergeVertices,subdivide,revolveGeo,@@ -368,3 +376,160 @@ describe('arrayRadial', () => {expect(copies[1]!.position.z).toBeCloseTo(0, 10);});});++describe('repeatAlongCurve', () => {+ // #211: a palm's ~600 leaflets were built by hand with meshGeo, because no helper+ // copied one leaflet along a rachis and merged the copies with their UVs kept.+ const leaflet = () => foliageCardGeo({ width: 0.04, height: 0.3, yPivot: 0 });+ const rachis: [number, number, number][] = [+ [0, 0, 0],+ [1, 0, 0],+ [2, 0, -1],+ ];++ it('merges copies into one primitive whose UVs equal the source per copy', () => {+ const source = leaflet();+ const merged = repeatAlongCurve(source, rachis, { count: 12 }) as THREE.BufferGeometry;+ const sourceCount = source.getAttribute('position').count;+ expect(merged.getAttribute('position').count).toBe(12 * sourceCount);+ expect(merged.index!.count).toBe(12 * source.index!.count);+ expect(merged.groups).toEqual([]);+ const sourceUv = Array.from(source.getAttribute('uv').array);+ const uv = merged.getAttribute('uv').array;+ for (let copy = 0; copy < 12; copy++)+ expect(Array.from(uv.slice(copy * sourceUv.length, (copy + 1) * sourceUv.length))).toEqual(+ sourceUv,+ );+ });++ it('turns each copy so its local +X follows the curve tangent and +Y points up', () => {+ // Equal segments put the copies at the start, the corner and the end. A thin bar+ // along local +X and a stub along local +Y show each copy's frame.+ const path: [number, number, number][] = [+ [0, 0, 0],+ [1, 0, 0],+ [1, 0, -1],+ ];+ const bar = boxGeo(0.1, 0.002, 0.002).translate(0.05, 0, 0);+ const stub = boxGeo(0.002, 0.05, 0.002).translate(0, 0.025, 0);+ const centroidTip = (geometry: THREE.BufferGeometry, copy: number) => {+ const merged = repeatAlongCurve(geometry, path, { count: 3 }) as THREE.BufferGeometry;+ const position = merged.getAttribute('position');+ const perCopy = geometry.getAttribute('position').count;+ const sum = new THREE.Vector3();+ for (let i = copy * perCopy; i < (copy + 1) * perCopy; i++)+ sum.add(new THREE.Vector3().fromBufferAttribute(position, i));+ return sum.divideScalar(perCopy);+ };+ const bases = [+ [0, 0, 0],+ [1, 0, 0],+ [1, 0, -1],+ ];+ // At the corner the outgoing segment's direction is the tangent.+ const tangents = [+ [1, 0, 0],+ [0, 0, -1],+ [0, 0, -1],+ ];+ for (const copy of [0, 1, 2]) {+ const base = new THREE.Vector3(...(bases[copy] as [number, number, number]));+ const along = centroidTip(bar, copy).sub(base);+ const tangent = new THREE.Vector3(...(tangents[copy] as [number, number, number]));+ expect(along.distanceTo(tangent.clone().multiplyScalar(0.05))).toBeLessThan(1e-6);+ const up = centroidTip(stub, copy).sub(base);+ expect(up.distanceTo(new THREE.Vector3(0, 0.025, 0))).toBeLessThan(1e-6);+ }+ });++ it('places an opposite row in the same primitive with opposite: true', () => {+ const stub = boxGeo(0.002, 0.05, 0.002).translate(0, 0.025, 0);+ const perCopy = stub.getAttribute('position').count;+ const merged = repeatAlongCurve(stub, [rachis[0]!, rachis[1]!], {+ count: 2,+ opposite: true,+ }) as THREE.BufferGeometry;+ expect(merged.getAttribute('position').count).toBe(4 * perCopy);+ const centroidY = (copy: number) => {+ let y = 0;+ for (let i = copy * perCopy; i < (copy + 1) * perCopy; i++)+ y += merged.getAttribute('position').getY(i);+ return y / perCopy;+ };+ // Each position gets its copy, then the opposite copy twisted 180 degrees.+ expect([0, 1, 2, 3].map((copy) => Math.round(centroidY(copy) * 1000) / 1000)).toEqual([+ 0.025, -0.025, 0.025, -0.025,+ ]);+ });++ it('adds an optional _along attribute from attachment (0) to tip (1)', () => {+ const merged = repeatAlongCurve(leaflet(), rachis, {+ count: 5,+ along: true,+ }) as THREE.BufferGeometry;+ const along = merged.getAttribute('_along');+ const perCopy = leaflet().getAttribute('position').count;+ expect([0, 1, 2, 3, 4].map((copy) => along.getX(copy * perCopy))).toEqual([+ 0, 0.25, 0.5, 0.75, 1,+ ]);+ });++ it('tapers scale and twist from attachment to tip', () => {+ const bar = boxGeo(0.1, 0.01, 0.01).translate(0.05, 0, 0);+ const merged = repeatAlongCurve(bar, [rachis[0]!, rachis[1]!], {+ count: 2,+ scale: [1, 0.5],+ twist: [0, 180],+ }) as THREE.BufferGeometry;+ merged.computeBoundingBox();+ // The tip copy is half length: the whole span is 1 (spacing) + 0.05 (half bar).+ expect(merged.boundingBox!.max.x).toBeCloseTo(1.05, 5);+ });++ it('creates shared-geometry nodes when merge is false', () => {+ const root = new THREE.Object3D();+ const source = new THREE.Mesh(leaflet(), gameMaterial(0x3f7a2c));+ source.name = 'Leaflet';+ const copies = repeatAlongCurve(source, rachis, {+ count: 4,+ merge: false,+ name: 'Leaflet',+ parent: root,+ }) as THREE.Object3D[];+ expect(copies).toHaveLength(4);+ expect(copies.map((copy) => copy.name)).toEqual([+ 'Mesh_Leaflet0',+ 'Mesh_Leaflet1',+ 'Mesh_Leaflet2',+ 'Mesh_Leaflet3',+ ]);+ for (const copy of copies) {+ expect((copy as THREE.Mesh).geometry).toBe(source.geometry);+ expect(copy.parent).toBe(root);+ }+ });++ it('refuses an over-budget merge with a bounded diagnostic', () => {+ const dense = sphereGeo(0.1, 64, 64);+ expect(() => repeatAlongCurve(dense, rachis, { count: 200 })).toThrow(+ /repeatAlongCurve would produce \d+ vertices; the limit is 262144/,+ );+ });++ it('rejects invalid curves and options', () => {+ expect(() => repeatAlongCurve(leaflet(), [[0, 0, 0]], { count: 2 })).toThrow(/two points/);+ expect(() =>+ repeatAlongCurve(+ leaflet(),+ [+ [0, 0, 0],+ [0, 0, 0],+ ],+ { count: 2 },+ ),+ ).toThrow(/length/);+ expect(() => repeatAlongCurve(leaflet(), rachis, { count: 0 })).toThrow(/count/);+ expect(() => repeatAlongCurve(leaflet(), rachis, { count: 2, scale: -1 })).toThrow(/scale/);+ expect(() => repeatAlongCurve(leaflet(), rachis, { count: 2, merge: false })).toThrow(/Mesh/);+ });+});diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex d2d72b93..687c7a4c 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -2103,6 +2103,53 @@ define(intents: ['repeat a mesh around a center'],},);+define(+ 'repeatAlongCurve',+ {+ axes: "Each copy's local +X follows the curve tangent (the outgoing segment at a sample point); local +Y points toward up, default [0,1,0], made perpendicular to the tangent. twist rotates about the tangent in degrees.",+ origin: 'Each copy is translated to its arc-length position on the curve.',+ coordinates:+ 'Points, up and the merged geometry share one local space; no parent transform is applied.',+ ownership:+ 'merge true returns a new BufferGeometry; merge false creates mesh nodes sharing the source geometry/material.',+ parameters: [+ 'points: at least two finite [x,y,z] samples (bezierCurve, catmullRomPath) with positive total length.',+ 'count is a safe integer from 1 to 10,000 copies, evenly spaced by arc length from start to end (fractions, default 0 and 1). The source itself is not placed or moved.',+ 'scale and twist are a number or an [attachment, tip] pair interpolated across the copies; scale is positive. twist needs align: tangent.',+ 'opposite true adds a second copy twisted a further 180 degrees at each position (2 × count copies, same _along).',+ 'merge false needs a Mesh source and returns copies named Mesh_<name><i> under parent.',+ ],+ topology: [+ 'merge true: one primitive whose vertices and indices are the source repeated count times; copies are not welded.',+ ],+ preservation: [+ 'merge true copies every attribute per copy; UVs and other attributes are unchanged, position/normal/tangent are transformed. along: true adds float _along, 0 on the first copy and 1 on the last.',+ 'Material groups and morph targets are not copied; the merged geometry takes one material.',+ ],+ cost: 'merge true allocates count × source vertices, at most 262,144 vertices; larger merges fail before allocation.',+ },+ {+ references: ['src/ops.ts', 'src/geometry-budget.ts'],+ tags: ['repeat', 'curve', 'foliage', 'merge'],+ aliases: ['leaflets along a stem', 'copies along a path', 'frond leaflets'],+ intents: [+ 'repeat cards or leaflets along a curve',+ 'merge repeated copies into one primitive with UVs kept',+ ],+ limitations: [+ 'Tangents come from the polyline segments; sample curves densely for smooth turns.',+ 'The default legacy GLB converter does not export the _along attribute.',+ 'Merged copies are one part: they are not separately named or addressable.',+ ],+ related: [+ { name: 'bezierCurve', relation: 'prerequisite' },+ { name: 'catmullRomPath', relation: 'prerequisite' },+ { name: 'foliageCardGeo', relation: 'companion' },+ { name: 'repeatInstances', relation: 'alternative' },+ { name: 'arrayLinear', relation: 'alternative' },+ ],+ },+);define('mirror',{diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex ac974421..e95f1d7c 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -1001,6 +1001,19 @@ const PRIMITIVES: HelperSpec[] = [example:"const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });\narrayRadial('Bolt', bolt, 8, 'y', root);",},+ {+ name: 'repeatAlongCurve',+ signature:+ "repeatAlongCurve(source: BufferGeometry | Mesh, points: [x,y,z][], opts: { count, align?: 'tangent'|'none', up?: [x,y,z], scale?: n | [attach, tip], twist?: deg | [attach, tip], opposite?: false, start?: 0..1, end?: 0..1, merge?: true, along?: false, name?, parent? })",+ returns: 'THREE.BufferGeometry (merge: true) or THREE.Object3D[] (merge: false)',+ category: 'arrays',+ description:+ "Copies one leaflet, card or stud along a sampled curve, evenly spaced by arc length. Each copy's local +X follows the tangent and +Y points toward up. merge: true (default) returns ONE geometry for one primitive per frond, with UVs kept per copy; merge: false returns shared-geometry nodes like arrayLinear.",+ example:+ "const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);\nconst leaflet = foliageCardGeo({ width: 0.05, height: 0.35, yPivot: 0 });\nconst frond = repeatAlongCurve(leaflet, rachis, { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true });\ncreatePart('Frond_0', frond, foliageMaterial(albedo), { parent: root });",+ promptNotes:+ 'One merged geometry is one part; name the frond, not each leaflet. opposite: true adds the second row in the same primitive. Merges are capped at 262,144 vertices.',+ },{name: 'mirror',signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",diff --git a/src/discovery/intents.ts b/src/discovery/intents.tsindex 2b689c67..fb5f04b7 100644--- a/src/discovery/intents.ts+++ b/src/discovery/intents.ts@@ -14,6 +14,16 @@ export const discoveryIntents: Readonly<Record<string, readonly string[]>> = {'regular spacing','bench or fence slats',],+ repeatAlongCurve: [+ 'leaflets along a stem',+ 'palm frond leaflets',+ 'fern frond',+ 'repeat cards along a curve',+ 'leaves along a branch',+ 'one merged primitive per frond',+ ],+ repeatInstances: ['many identical leaves instanced', 'instanced repeated parts', 'batch copies'],+ crossedQuadsGeo: ['grass clump', 'bush or shrub cards', 'cross billboard plant'],wallWithOpening: ['wall aperture', 'cut a window', 'doorway opening', 'door or window in a wall'],room: ['hollow enclosure', 'walls and floor', 'room with doors and windows'],createGableShell: ['enclosed building shell', 'gable house with openings'],@@ -57,7 +67,7 @@ export const discoveryIntents: Readonly<Record<string, readonly string[]>> = {boolIntersect: ['intersection of solids', 'overlapping volume'],beamBetween: ['beam between points', 'bar connecting endpoints'],autoUnwrap: ['unwrap texture coordinates', 'UV atlas', 'unfold mesh'],- foliageCardGeo: ['thin leaf cutout', 'foliage card'],+ foliageCardGeo: ['thin leaf cutout', 'foliage card', 'single leaflet card', 'fern leaf'],foliageMaterial: ['leaf transparency', 'foliage cutout', 'alpha mask'],};diff --git a/src/discovery/lexical-index.test.ts b/src/discovery/lexical-index.test.tsindex f142acd3..86875749 100644--- a/src/discovery/lexical-index.test.ts+++ b/src/discovery/lexical-index.test.ts@@ -78,6 +78,28 @@ test('new catalog entries and aliases enter the next index without hand-maintainexpect((await after.search('quasar frobnicator'))[0]?.id).toBe('operation:novelFixture');});+test('foliage wording reaches the repetition and card helpers', async () => {+ // #211: "palm frond leaflets" returned room and wall assemblies, "fern" returned+ // nothing and "grass clump" returned glass materials.+ const run = createDiscoveryService(+ entries,+ createLexicalDiscoveryIndex(entries),+ async () => ({}),+ );+ const top = async (query: string) =>+ (await run({ query })).entries.slice(0, 3).map((entry) => entry.id);+ for (const query of [+ 'palm frond leaflets',+ 'leaflets along a stem',+ 'fern',+ 'repeat cards along a curve',+ ])+ expect(await top(query)).toContain('operation:repeatAlongCurve');+ expect(await top('palm frond leaflets')).not.toContain('assembly:room');+ expect(await top('grass clump')).toContain('operation:crossedQuadsGeo');+ expect(await top('many identical leaves instanced')).toContain('operation:repeatInstances');+});+test('everyday object words reach the reviewed structure and material entries', async () => {// Dogfood run C (C-A2): "bench" found nothing and "cast iron" expanded to cost/caster.const run = createDiscoveryService(diff --git a/src/geometry-budget.ts b/src/geometry-budget.tsindex ba96004e..b928d8dc 100644--- a/src/geometry-budget.ts+++ b/src/geometry-budget.ts@@ -5,6 +5,8 @@ export const GEOMETRY_ALLOCATION_LIMITS = Object.freeze({subdivisionAttributeBytes: 128 * 1024 * 1024,subdivisionIterations: 10,repeatedMeshes: 10_000,+ // repeatAlongCurve merge: vertices in the one merged geometry it returns.+ curveRepeatVertices: 262_144,primitiveSegments: 4096,primitiveGridVertices: 262_144,// xatlasjs 0.2 returns Uint16 indices and source-vertex correspondence.diff --git a/src/ops.ts b/src/ops.tsindex f56ae17e..0722e1d8 100644--- a/src/ops.ts+++ b/src/ops.ts@@ -172,6 +172,247 @@ export function arrayRadial(return out;}+export interface RepeatAlongCurveOptions {+ /** Copies placed along the curve, evenly spaced by arc length from `start` to `end`. */+ count: number;+ /** `tangent` (default) turns local +X along the curve; `none` keeps the source orientation. */+ align?: 'tangent' | 'none';+ /** Local +Y points toward this direction, made perpendicular to the tangent. Default [0,1,0]. */+ up?: [number, number, number];+ /** Uniform scale, or [attachment, tip] interpolated across the copies. Default 1. */+ scale?: number | [number, number];+ /** Degrees about the tangent, or [attachment, tip]. Default 0. */+ twist?: number | [number, number];+ /** Also place a copy twisted a further 180 degrees at each position: a frond's second row. */+ opposite?: boolean;+ /** Fractions of the curve's length where the first and last copy sit. Default 0 and 1. */+ start?: number;+ end?: number;+ /** true (default) returns one merged geometry; false returns shared-geometry mesh nodes. */+ merge?: boolean;+ /** Merged only: add a float `_along` attribute, 0 on the first copy and 1 on the last. */+ along?: boolean;+ /** Unmerged only: copies are named `${name}${i}` (createInstance adds `Mesh_`). */+ name?: string;+ /** Unmerged only: the parent that receives the copies. */+ parent?: THREE.Object3D;+}++/**+ * Copy one source along a sampled curve (`bezierCurve`, `catmullRomPath`), for leaflets on+ * a rachis, cards along a stem or studs along a rail. Each copy's local +X follows the curve+ * tangent (the outgoing segment at a sample point) and local +Y points toward `up`.+ *+ * With `merge` (the default) the copies become one BufferGeometry: one primitive per call,+ * UVs and other attributes copied unchanged per copy, positions/normals/tangents transformed.+ * Material groups are dropped, so the merged geometry takes one material.+ * Without it the copies are shared-geometry nodes like `arrayLinear`; the source is not moved.+ *+ * @example+ * const rachis = bezierCurve([[0,0,0],[0.6,0.5,0],[1.4,0.3,0]], 32);+ * const frond = repeatAlongCurve(leafletGeo, rachis,+ * { count: 40, up: [0,0,1], scale: [1, 0.4], start: 0.1, opposite: true, along: true });+ */+export function repeatAlongCurve(+ source: THREE.BufferGeometry | THREE.Object3D,+ points: readonly (readonly [number, number, number])[],+ options: RepeatAlongCurveOptions,+): THREE.BufferGeometry | THREE.Object3D[] {+ const name = 'repeatAlongCurve';+ if (!options || typeof options !== 'object')+ throw new TypeError(`${name} needs an options object with count.`);+ const { count, align = 'tangent', merge = true, opposite = false } = options;+ assertRepetitionCount(name, opposite ? count * 2 : count);+ if (opposite && align !== 'tangent')+ throw new RangeError(`${name} opposite needs align: tangent.`);+ if (align !== 'tangent' && align !== 'none')+ throw new RangeError(`${name} align must be tangent or none.`);+ if (!Array.isArray(points) || points.length < 2)+ throw new RangeError(`${name} needs at least two points; sample the curve first.`);+ if (points.length > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(+ `${name} accepts at most ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples} points.`,+ );+ for (const [i, point] of points.entries()) assertFiniteTriple(`${name} points[${i}]`, point);+ const up = options.up ?? [0, 1, 0];+ assertFiniteTriple(`${name} up`, up);+ const upVector = new THREE.Vector3(...up);+ if (upVector.lengthSq() === 0) throw new RangeError(`${name} up must not be zero.`);+ upVector.normalize();+ const span = (label: string, value: number | [number, number] | undefined, fallback: number) => {+ const [a, b] =+ value === undefined ? [fallback, fallback] : Array.isArray(value) ? value : [value, value];+ if (!Number.isFinite(a) || !Number.isFinite(b))+ throw new RangeError(`${name} ${label} must be finite.`);+ return [a, b] as const;+ };+ const scale = span('scale', options.scale, 1);+ if (scale[0] <= 0 || scale[1] <= 0) throw new RangeError(`${name} scale must be positive.`);+ const twist = span('twist', options.twist, 0);+ if (align === 'none' && (twist[0] !== 0 || twist[1] !== 0))+ throw new RangeError(`${name} twist needs align: tangent.`);+ const start = options.start ?? 0;+ const end = options.end ?? 1;+ if (!(start >= 0 && end <= 1 && start <= end))+ throw new RangeError(`${name} start and end must satisfy 0 <= start <= end <= 1.`);++ // Arc length per sample; a copy at length s uses the segment s falls in.+ const cumulative = [0];+ for (let i = 1; i < points.length; i++) {+ const [ax, ay, az] = points[i - 1]!;+ const [bx, by, bz] = points[i]!;+ cumulative.push(cumulative[i - 1]! + Math.hypot(bx - ax, by - ay, bz - az));+ }+ const length = cumulative.at(-1)!;+ if (!(length > 0) || !Number.isFinite(length))+ throw new RangeError(`${name} curve length must be positive and finite.`);++ // Each frame carries its position's t, so an opposite copy shares its partner's _along.+ const frames: { matrix: THREE.Matrix4; t: number }[] = [];+ let previousUp = upVector.clone();+ for (let copy = 0; copy < count; copy++) {+ const t = count === 1 ? 0 : copy / (count - 1);+ const s = (start + (end - start) * t) * length;+ let segment = 0;+ while (segment < points.length - 2 && !(s < cumulative[segment + 1]!)) segment++;+ // Skip zero-length segments so a repeated sample cannot erase the tangent.+ while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])+ segment++;+ const a = new THREE.Vector3(...points[segment]!);+ const b = new THREE.Vector3(...points[segment + 1]!);+ const segmentLength = cumulative[segment + 1]! - cumulative[segment]!;+ const local = segmentLength > 0 ? (s - cumulative[segment]!) / segmentLength : 0;+ const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));+ const k = THREE.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE.Matrix4();+ let angle = 0;+ if (align === 'tangent') {+ const tangent = b.clone().sub(a).normalize();+ // `up` parallel to the tangent leaves the previous copy's up, then any perpendicular.+ let side = upVector.clone().sub(tangent.clone().multiplyScalar(upVector.dot(tangent)));+ if (side.lengthSq() < 1e-12)+ side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));+ if (side.lengthSq() < 1e-12)+ side = new THREE.Vector3(+ Math.abs(tangent.x) < 0.9 ? 1 : 0,+ Math.abs(tangent.x) < 0.9 ? 0 : 1,+ 0,+ ).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side.normalize();+ previousUp = side;+ rotation.makeBasis(tangent, side, new THREE.Vector3().crossVectors(tangent, side));+ angle = THREE.MathUtils.degToRad(THREE.MathUtils.lerp(twist[0], twist[1], t));+ }+ for (const extra of opposite ? [0, Math.PI] : [0]) {+ const turned = rotation.clone();+ if (angle + extra) turned.multiply(new THREE.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE.Matrix4()+ .makeTranslation(position.x, position.y, position.z)+ .multiply(turned)+ .multiply(new THREE.Matrix4().makeScale(k, k, k));+ if (!matrix.elements.every(Number.isFinite))+ throw new RangeError(`${name} produced a non-finite copy transform.`);+ frames.push({ matrix, t });+ }+ }++ if (!merge) {+ // Duck-typed: sandbox objects come from another module realm (see createInstance).+ const mesh = (source as { isMesh?: boolean }).isMesh+ ? source+ : (source as THREE.Object3D).children?.find((child) => (child as THREE.Mesh).isMesh);+ if (!mesh) throw new TypeError(`${name} with merge: false needs a Mesh source.`);+ const prefix = options.name ?? (source as THREE.Object3D).name ?? 'Copy';+ return frames.map((frame, i) => {+ const copy = createInstance(`${prefix}${i}`, source as THREE.Object3D, {+ parent: options.parent,+ });+ frame.matrix.decompose(copy.position, copy.quaternion, copy.scale);+ return copy;+ });+ }+ const copies = frames.length;++ const geometry = (source as { isBufferGeometry?: boolean }).isBufferGeometry+ ? (source as THREE.BufferGeometry)+ : (source as { isMesh?: boolean }).isMesh+ ? (source as THREE.Mesh).geometry+ : undefined;+ if (!geometry) throw new TypeError(`${name} needs a BufferGeometry or Mesh source.`);+ if (Object.keys(geometry.morphAttributes).length)+ throw new RangeError(`${name} does not copy morph targets.`);+ // Groups are not copied: the merged geometry renders with one material, as a single-material+ // mesh already ignores them (BoxGeometry carries one group per face).+ const positionAttribute = geometry.getAttribute('position');+ if (!positionAttribute) throw new RangeError(`${name} source has no position attribute.`);+ const perCopy = positionAttribute.count;+ const total = perCopy * copies;+ if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)+ throw new RangeError(+ `${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`,+ );++ const merged = new THREE.BufferGeometry();+ const vector = new THREE.Vector3();+ const normalMatrix = new THREE.Matrix3();+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const size = attribute.itemSize;+ const transformed = key === 'position' || key === 'normal' || key === 'tangent';+ const ArrayType = transformed+ ? Float32Array+ : (((attribute as THREE.BufferAttribute).array?.constructor as new (+ n: number,+ ) => THREE.TypedArray) ?? Float32Array);+ const out = new ArrayType(total * size);+ for (let copy = 0; copy < copies; copy++) {+ const frame = frames[copy]!.matrix;+ normalMatrix.getNormalMatrix(frame);+ for (let i = 0; i < perCopy; i++) {+ const target = (copy * perCopy + i) * size;+ if (key === 'position') {+ vector.fromBufferAttribute(attribute, i).applyMatrix4(frame);+ out.set([vector.x, vector.y, vector.z], target);+ } else if (key === 'normal' || key === 'tangent') {+ vector.set(attribute.getX(i), attribute.getY(i), attribute.getZ(i));+ vector.applyMatrix3(normalMatrix).normalize();+ out.set(+ size === 4+ ? [vector.x, vector.y, vector.z, attribute.getW(i)]+ : [vector.x, vector.y, vector.z],+ target,+ );+ } else {+ for (let c = 0; c < size; c++) out[target + c] = attribute.getComponent(i, c);+ }+ }+ }+ merged.setAttribute(+ key,+ new THREE.BufferAttribute(out, size, transformed ? false : attribute.normalized),+ );+ }+ if (options.along) {+ const along = new Float32Array(total);+ for (let copy = 0; copy < copies; copy++)+ along.fill(frames[copy]!.t, copy * perCopy, (copy + 1) * perCopy);+ merged.setAttribute('_along', new THREE.BufferAttribute(along, 1));+ }+ const index = geometry.getIndex();+ if (index) {+ const indices =+ total > 65_535+ ? new Uint32Array(index.count * copies)+ : new Uint16Array(index.count * copies);+ for (let copy = 0; copy < copies; copy++)+ for (let i = 0; i < index.count; i++)+ indices[copy * index.count + i] = index.getX(i) + copy * perCopy;+ merged.setIndex(new THREE.BufferAttribute(indices, 1));+ }+ merged.computeBoundingBox();+ merged.computeBoundingSphere();+ return merged;+}+/*** Mirror: create one mirrored instance of `source` across the given plane.* Plane is identified by its normal axis ('x' = mirror across YZ plane).diff --git a/src/primitives.ts b/src/primitives.tsindex 3e11de09..d7cd3a99 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -2418,6 +2418,7 @@ export function buildSandboxGlobals(// Array/mirror/subdivide/curve opsarrayLinear: wrap('arrayLinear', ops.arrayLinear),arrayRadial: wrap('arrayRadial', ops.arrayRadial),+ repeatAlongCurve: wrap('repeatAlongCurve', ops.repeatAlongCurve),mirror: wrap('mirror', ops.mirror),subdivide: wrap('subdivide', ops.subdivide),mergeVertices: wrap('mergeVertices', ops.mergeVertices),