Skip to content

3D engine that AI agents drive

Add a cloud geometry: a seeded puff-cluster cumulus as one closed mesh (#2039)

Nguyen Xuan An46f31a6dc51e
diff --git a/changes/2039-cloud-builder.md b/changes/2039-cloud-builder.md
new file mode 100644
index 00000000..68eae984
--- /dev/null
+++ b/changes/2039-cloud-builder.md
@@ -0,0 +1 @@
+- Scenes can build anime cumulus: a `cloud` geometry (`seed`, `puffs`, `width`, `height`, `flatBase`) makes one closed mesh of round puffs that toon-shades into clean lobes (#2039)
diff --git a/changes/2039-cloud-builder.size.md b/changes/2039-cloud-builder.size.md
new file mode 100644
index 00000000..ed0e3422
--- /dev/null
+++ b/changes/2039-cloud-builder.size.md
@@ -0,0 +1,4 @@
+- entry:modeling: the cloud builder (puff layout, smooth union, base cut) is about 1.5 KB gzip and is the whole feature; it loads only for recipes that contain a cloud geometry.
+- scene:agent-scene: 244 bytes gzip in the core for the cloud geometry's schema, field list and capability text, so agents can find and validate it without loading the builder.
+- scene:agent-scene+lazy: the lazy modeling chunk carries the cloud builder, 1.5 KB gzip, loaded only by recipes that use it.
+- goal:agent-scene: an agent-facing capability (anime cumulus from one geometry record); the builder itself is outside the core bundle.
diff --git a/docs/modeling.md b/docs/modeling.md
index f83bf8e5..b23c0b25 100644
--- a/docs/modeling.md
+++ b/docs/modeling.md
@@ -135,6 +135,21 @@ through its depth. `"\n"` starts a new line 1.2 em lower. `size` is the em heigh
- One glyph and a word match Blender 5.2 with the same font in volume, area and bounds to 2e-5. Blender's text size unit is not the em,
so the golden script calibrates it on the capital I. There is no kerning, bevel or text on a curve.
+## Cloud
+
+`cloudGeometry({ seed, puffs, width, height, flatBase, resolution })` builds a cumulus as one closed mesh: a wide base of big lobes with smaller puffs on a dome above it, joined by a smooth union and meshed by surface nets. The same record gives the same bytes. Shade it with `toon` (for example `"toon": 3`) and the lobes read as clean bands.
+
+| Field | Default | Range | Meaning |
+| --- | --- | --- | --- |
+| `seed` | 1 | whole, 0 to 2147483647 | Another seed makes another cloud. |
+| `puffs` | 14 | whole, 2 to 48 | Lobes in the cluster. |
+| `width` | 10 | 0.5 to 2000 | Widest side in metres, centred on x and z. |
+| `height` | 5 | 0.25 to 2000 | Top to base in metres, measured before the base is cut. |
+| `flatBase` | 0.6 | 0 to 1 | 0 keeps a round underside; 1 cuts it flat the furthest. The base always sits on y = 0. |
+| `resolution` | 48 | whole, 16 to 96 | Cells along the longest side; it sets the triangle count. |
+
+A scene geometry takes the same fields with `"type": "cloud"` (see `scene_capabilities` `cloud`). A bad value throws an error that names the field and the accepted range. Lobes are stretched with the box, so a tall or flat cloud has taller or flatter puffs.
+
## Resource and precision limits
Each generator accepts at most 4096 input points. Extrusion applies that limit across its contour and holes.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 3901be31..28980143 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -363,6 +363,7 @@ function curveAndTextGeometries(id) {
.describe('Sweep along points, a shape or splines; see scene_capabilities curveText.'),
z.strictObject({ ...id, type: z.literal('sdf'), root: z.record(z.string(), z.unknown()), resolution: looseField }).describe('Signed-distance shapes with smooth union; see scene_capabilities curveText.'),
z.strictObject({ ...id, type: z.literal('text'), text: z.string().max(256), size: looseField, depth: looseField, font: looseField, align: looseField, curveSegments: looseField }).describe('3D text; see scene_capabilities curveText.'),
+ z.strictObject({ ...id, type: z.literal('cloud'), seed: looseField, puffs: looseField, width: looseField, height: looseField, flatBase: looseField, resolution: looseField }).describe('Seeded cumulus of round puffs; see scene_capabilities cloud.'),
z.strictObject({ ...id, type: z.literal('terrain'), size: looseField, resolution: looseField, seed: looseField, amplitude: looseField, holes: z.array(z.unknown()).max(16).optional() }).describe('Hills with round holes; see scene_capabilities terrain.'),
];
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3835587d..0c8b8e6b 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -231,8 +231,9 @@ export const MESH_BOOLEAN_NOTES = Object.freeze({
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
format: 'crucible.scene', schemaVersion: 1,
- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh', 'fragment', 'dented']),
+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'cloud', 'mesh', 'fragment', 'dented']),
camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its size. fStop (0.7-64) turns on depth of field focused on target; 1.4 or lower is full blur; focusDistance (m along the view axis, with fStop; default the distance to target) moves the focus plane without moving target (not the effects.focusDistance of the blur effect). effects.depthOfField.blur must stay 0. Orthographic/shifted cameras use the rasterizer.',
+ cloud: 'Geometry cloud: one closed, smooth mesh of round puffs for cumulus, a wide base with a tower of smaller lobes above, the flat base at y = 0. seed 1 (whole, 0-2147483647), puffs 14 (2-48), width 10 m (0.5-2000), height 5 m (0.25-2000, measured before the base is cut), flatBase 0.6 (0 keeps a round underside, 1 cuts flattest), resolution 48 cells (16-96). The same seed gives the same bytes; toon-shade it (material toon: 3) for clean lobes.',
terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius}, no surface inside; radius a few cells or more.',
vehicleDamage: 'Geometry dented {source, impacts:[{point, direction, impulse N s}] 1-8, stiffness 2000, maxDepth 0.25 m, radius 0.4}: the source (not a fragment or dent) pushed in around each point by min(maxDepth, impulse/stiffness); a part that comes off is a body on a fixed joint with breakImpulse. docs/vehicle.md.',
placedAssets: 'Node field asset:{id or name,materials?,flatten?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog, or name: its exact file name, stored as the id; give one). Its transform places it. scene_apply add-node with an asset field places the first or any later instance, so a scene need not start with its assets. materials:[{name,id?,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name; an id (such as "stool-heat") gives that material a handle that a set-motion material track can drive: emission and emissiveColor fade a heat glow, one id per placement. emissionMask:{axis:x|y|z,from,to} (metres in the own space of the part, smooth ramp, from above to flips it) multiplies emission so the glow sits only at one end while texture and shading stay; rasterizer only, path tracers ignore it. flatten:{color?,unlit?} flattens every material of the placement in one call: unlit true draws them without lighting, color [r,g,b] paints them one colour (textures dropped), both give a flat silhouette; a named override still wins. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start; set-motion tracks move the node and scene time seeks the clip. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame (docs/vehicle.md). Max 512 placements, 16 assets, 16 animated.',
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index b09e8e65..a22e5d08 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -59,7 +59,7 @@ let physicsLoader = null;
// Each test errs on the side of loading: a false positive costs a chunk, a false negative a clear error.
const MODULE_MARKERS = {
mesh: ['"type":"mesh"', '"instances"'],
- modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"', '"type":"curve"', '"type":"sdf"'],
+ modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"', '"type":"curve"', '"type":"sdf"', '"type":"cloud"'],
text: ['"type":"text"'],
motion: ['"motion":{', '"bake-motion"', '"add-explosion"'],
motionBake: ['"bake-motion"'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 70258db9..54a2773e 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -535,6 +535,7 @@ const GEOMETRY_FIELDS = {
text: ['text', 'size', 'depth', 'font', 'align', 'curveSegments'],
mesh: ['base', 'edits', 'stack', 'smoothAngle', 'shapeKeys'],
terrain: ['size', 'resolution', 'seed', 'amplitude', 'holes'],
+ cloud: ['seed', 'puffs', 'width', 'height', 'flatBase', 'resolution'],
fragment: ['source', 'seed', 'cells', 'index', 'impact', 'impactRadius'],
dented: ['source', 'impacts', 'stiffness', 'maxDepth', 'radius'],
};
@@ -569,6 +570,7 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {
for (const field of GEOMETRY_FIELDS[value.type]) {
// Terrain checks its own numbers (a whole resolution from 2 to 256), so its message names the real range; null is not absent there, so it still fails below.
if (value.type === 'terrain' && ['size', 'resolution', 'amplitude'].includes(field) && value[field] !== null) continue;
+ if (value.type === 'cloud' && value[field] !== null) continue;
if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack', 'shapeKeys', 'points', 'taper', 'text', 'font', 'align', 'from', 'to', 'shape', 'splines', 'kind', 'weights', 'order', 'knots', 'knotMode', 'trim', 'grow', 'root', 'source', 'impact', 'impacts'].includes(field)) {
finite(value[field], field);
}
@@ -627,6 +629,8 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {
}
case 'terrain':
return agentSceneModule('terrain').terrainVertexEstimate(value);
+ case 'cloud':
+ return agentSceneModule('modeling').cloudVertexEstimate(value);
case 'extrude': {
const holes = value.holes ?? [];
if (!Array.isArray(holes) || holes.length > 128) {
@@ -822,6 +826,8 @@ function generateGeometry(value, maxVertices, scope) {
return agentSceneModule('text').text(value.text, { ...value, maxVertices });
case 'terrain':
return agentSceneModule('terrain').generateTerrainGeometry(value, maxVertices);
+ case 'cloud':
+ return agentSceneModule('modeling').cloudGeometry(value, maxVertices);
case 'fragment': {
if (!scope) throw invalidField('type', 'fragment', 'a geometry inside a recipe, where its source geometry is found by ID');
const source = scope.definitions.get(value.source);
diff --git a/src/cloud-geometry.js b/src/cloud-geometry.js
new file mode 100644
index 00000000..12a53e52
--- /dev/null
+++ b/src/cloud-geometry.js
@@ -0,0 +1,177 @@
+import { invalidField } from './field-error.js';
+import { meshDistanceField, planDistanceField } from './modeling-sdf.js';
+import { seededRandom } from './seeded-random.js';
+
+// The cloud geometry: a seeded cluster of round puffs (a wide base of lobes with a tower of smaller ones above it), joined by a
+// smooth union and meshed by surface nets as one closed surface. Plain arithmetic in a fixed order, so a seed gives the same bytes.
+
+export const CLOUD_LIMITS = Object.freeze({
+ puffs: [2, 48],
+ width: [0.5, 2000],
+ height: [0.25, 2000],
+ flatBase: [0, 1],
+ resolution: [16, 96],
+ seed: [0, 0x7fffffff],
+ defaults: Object.freeze({ seed: 1, puffs: 14, width: 10, height: 5, flatBase: 0.6, resolution: 48 }),
+});
+const CLOUD_FIELDS = ['id', 'type', 'seed', 'puffs', 'width', 'height', 'flatBase', 'resolution'];
+// The dome the puffs are drawn in, in arbitrary units: half width at the base, height, how fast it narrows toward the top, how
+// strongly puffs favour the lower half, and how deep below the dome surface a shell puff may sit (share of the reach). The core
+// lobes cover CORE_HEIGHT_SHARE of the height with CORE_RADIUS_SHARE of the dome reach. OVERLAP_SHARE is how deep two neighbours
+// sink into each other.
+const DOME_HALF_WIDTH = 1.6;
+const DOME_HEIGHT = 2.6;
+const DOME_NARROWING = 0.55;
+const DOME_HEIGHT_BIAS = 1.3;
+const SHELL_DEPTH = 0.8;
+const CORE_LOBES = 4;
+const CORE_HEIGHT_SHARE = 0.9;
+const CORE_RADIUS_SHARE = 0.8;
+const OVERLAP_SHARE = 0.4;
+const BLEND_PER_RADIUS = 0.14;
+const BASE_ROUNDING_PER_RADIUS = 0.12;
+const FULL_TURN = Math.PI * 2;
+
+function limited(value, name, whole) {
+ const [minimum, maximum] = CLOUD_LIMITS[name];
+ const fallback = CLOUD_LIMITS.defaults[name];
+ const resolved = value ?? fallback;
+ const valid = Number.isFinite(resolved) && resolved >= minimum && resolved <= maximum && (!whole || Number.isInteger(resolved));
+ if (!valid) {
+ throw invalidField(`cloud.${name}`, resolved, `${whole ? 'a whole number' : 'a number'} from ${minimum} to ${maximum}, such as ${fallback}`);
+ }
+ return resolved;
+}
+
+/** Validates a cloud record and returns its settings with the defaults filled in. */
+export function cloudSettings(value) {
+ for (const key of Object.keys(value)) {
+ if (!CLOUD_FIELDS.includes(key)) throw invalidField(`cloud.${key}`, value[key], `one of ${CLOUD_FIELDS.slice(2).join(', ')}; remove "${key}"`);
+ }
+ return {
+ seed: limited(value.seed, 'seed', true),
+ puffs: limited(value.puffs, 'puffs', true),
+ width: limited(value.width, 'width', false),
+ height: limited(value.height, 'height', false),
+ flatBase: limited(value.flatBase, 'flatBase', false),
+ resolution: limited(value.resolution, 'resolution', true),
+ };
+}
+
+/** The vertex count to reserve for a cloud record: validated, not meshed. */
+export function cloudVertexEstimate(value) {
+ const { resolution } = cloudSettings(value);
+ return 8 * resolution * resolution;
+}
+
+// A dome of lobes. A few big core lobes stacked on the axis fill the inside, so the surface has no cavities; the other puffs sit
+// on the shell of the dome, which narrows toward the top, smaller higher up. Each shell puff is pulled toward its nearest
+// neighbour until the two overlap, so the cluster is one piece. Sizes are in an arbitrary unit and are fitted to the box after.
+function scatterPuffs({ seed, puffs }) {
+ const random = (index, channel) => seededRandom(index, channel, seed);
+ const coreCount = Math.max(1, Math.min(CORE_LOBES, Math.floor(puffs / 4)));
+ const lobes = [];
+ for (let core = 0; core < coreCount; core++) {
+ const climb = core / coreCount * CORE_HEIGHT_SHARE;
+ lobes.push({ center: [0, climb * DOME_HEIGHT, 0], radius: CORE_RADIUS_SHARE * domeReach(climb) });
+ }
+ for (let index = lobes.length; index < puffs; index++) {
+ const climb = random(index, 0) ** DOME_HEIGHT_BIAS;
+ const reach = domeReach(climb) * (SHELL_DEPTH + (1 - SHELL_DEPTH) * Math.sqrt(random(index, 1)));
+ const azimuth = random(index, 2) * FULL_TURN;
+ const radius = (0.66 - 0.3 * climb) * (0.8 + 0.4 * random(index, 3));
+ const center = [Math.cos(azimuth) * reach, climb * DOME_HEIGHT, Math.sin(azimuth) * reach];
+ lobes.push({ center: pulledToNeighbour(center, radius, lobes), radius });
+ }
+ return lobes;
+}
+
+function domeReach(climb) {
+ return DOME_HALF_WIDTH * (1 - climb) ** DOME_NARROWING;
+}
+
+// Moves a new lobe along the line to its nearest earlier lobe until they overlap by a fifth of the smaller radius or more.
+function pulledToNeighbour(center, radius, lobes) {
+ let nearest = lobes[0];
+ let nearestGap = Infinity;
+ for (const lobe of lobes) {
+ const gap = Math.hypot(center[0] - lobe.center[0], center[1] - lobe.center[1], center[2] - lobe.center[2]);
+ if (gap < nearestGap) {
+ nearest = lobe;
+ nearestGap = gap;
+ }
+ }
+ const wanted = nearest.radius + radius - OVERLAP_SHARE * Math.min(nearest.radius, radius);
+ if (nearestGap <= wanted) return center;
+ const pull = wanted / nearestGap;
+ return center.map((value, axis) => nearest.center[axis] + (value - nearest.center[axis]) * pull);
+}
+
+
+function extentOf(lobes, axis) {
+ const low = Math.min(...lobes.map(lobe => lobe.center[axis] - lobe.radius));
+ const high = Math.max(...lobes.map(lobe => lobe.center[axis] + lobe.radius));
+ return { low, high };
+}
+
+// Centres the layout on x and z and rests it on y = 0, then picks the stretch that takes it to the requested box. Stretching
+// the whole layout keeps every overlap, so the puffs stay joined; tall or flat clouds get squashed or stretched lobes.
+function fitLayout(lobes, { width, height }) {
+ const x = extentOf(lobes, 0);
+ const y = extentOf(lobes, 1);
+ const z = extentOf(lobes, 2);
+ const centred = lobes.map(({ center, radius }) => ({
+ center: [center[0] - (x.low + x.high) / 2, center[1] - y.low, center[2] - (z.low + z.high) / 2],
+ radius,
+ }));
+ const side = width / Math.max(x.high - x.low, z.high - z.low);
+ return { lobes: centred, stretch: [side, height / (y.high - y.low), side] };
+}
+
+function smoothMinimum(first, second, blend) {
+ const weight = Math.max(blend - Math.abs(first - second), 0) / blend;
+ return Math.min(first, second) - weight * weight * blend / 4;
+}
+
+// The union of the lobes with the underside cut flat by a plane that rounds off where it meets them, in layout units. flatBase 0
+// keeps the round underside of the lowest lobes; 1 cuts as far as the widest lobe reaches.
+function layoutField(lobes, flatBase) {
+ const widest = Math.max(...lobes.map(lobe => lobe.radius));
+ const blend = widest * BLEND_PER_RADIUS;
+ const rounding = widest * BASE_ROUNDING_PER_RADIUS;
+ const cutHeight = extentOf(lobes, 1).low + flatBase * widest * 0.9;
+ const distance = (x, y, z) => {
+ let union = Infinity;
+ for (const { center, radius } of lobes) {
+ const lobeDistance = Math.hypot(x - center[0], y - center[1], z - center[2]) - radius;
+ union = Number.isFinite(union) ? smoothMinimum(union, lobeDistance, blend) : lobeDistance;
+ }
+ if (flatBase === 0) return union;
+ return -smoothMinimum(-union, y - cutHeight, rounding);
+ };
+ return { distance, cutHeight, slack: blend / 4 };
+}
+
+// The field in metres: points go back into layout units, and distances come out scaled by the smallest stretch so they never
+// overstate how far a point is from the surface. y = 0 is the cut base.
+function stretchedField({ lobes, stretch }, flatBase) {
+ const { distance, cutHeight, slack } = layoutField(lobes, flatBase);
+ const [stretchX, stretchY, stretchZ] = stretch;
+ const shortest = Math.min(...stretch);
+ const extents = [0, 1, 2].map(axis => extentOf(lobes, axis));
+ const lowestLayoutY = Math.max(extents[1].low, cutHeight);
+ return {
+ distance: (x, y, z) => distance(x / stretchX, y / stretchY + cutHeight, z / stretchZ) * shortest,
+ bounds: {
+ min: [(extents[0].low - slack) * stretchX, (lowestLayoutY - cutHeight - slack) * stretchY, (extents[2].low - slack) * stretchZ],
+ max: [(extents[0].high + slack) * stretchX, (extents[1].high - cutHeight + slack) * stretchY, (extents[2].high + slack) * stretchZ],
+ },
+ };
+}
+
+/** Mesh a cloud record: positions, gradient normals (not yet unit length), UVs and indices, one closed surface with its flat base at y = 0 and the width and height as asked, before the base is cut. */
+export function cloudMesh(value) {
+ const settings = cloudSettings(value);
+ const field = stretchedField(fitLayout(scatterPuffs(settings), settings), settings.flatBase);
+ return meshDistanceField(planDistanceField(field, settings.resolution));
+}
diff --git a/src/modeling-sdf.js b/src/modeling-sdf.js
index 03d77abc..cfe840e3 100644
--- a/src/modeling-sdf.js
+++ b/src/modeling-sdf.js
@@ -229,7 +229,11 @@ export function planSdf(value) {
if (!Number.isInteger(resolution) || resolution < SDF_LIMITS.minResolution || resolution > SDF_LIMITS.maxResolution) {
throw fail('sdf.resolution', resolution, `a whole number of cells along the longest side, ${SDF_LIMITS.minResolution} to ${SDF_LIMITS.maxResolution}; the grid is capped at ${SDF_LIMITS.maxResolution ** 3} cells`);
}
- const root = compileNode(value.root, 'sdf.root', 0, { count: 0 });
+ return planDistanceField(compileNode(value.root, 'sdf.root', 0, { count: 0 }), resolution);
+}
+
+/** The sampling grid of a compiled field { distance, bounds }: resolution cells along its longest side, plus padding. */
+export function planDistanceField(root, resolution) {
const extent = root.bounds.max.map((high, axis) => high - root.bounds.min[axis]);
const edge = Math.max(...extent) / resolution;
const points = extent.map(length => Math.ceil(length / edge - 1e-9) + 1 + PADDING_VOXELS * 2);
@@ -282,7 +286,11 @@ function triangulate(quads, positions) {
/** Mesh an sdf geometry: positions, normals from the field gradient, box-projected UVs and triangle indices. */
export function sdfGeometry(value) {
- const plan = planSdf(value);
+ return meshDistanceField(planSdf(value));
+}
+
+/** Mesh a planned field (planSdf or planDistanceField) with surface nets. */
+export function meshDistanceField(plan) {
const grid = { points: plan.points, edge: plan.edge };
const distances = sampleGrid(plan);
const { cellVertex, positions: cellPositions } = placeCellVertices(distances, grid, plan.origin);
diff --git a/src/modeling.js b/src/modeling.js
index 4a6f5157..52900687 100644
--- a/src/modeling.js
+++ b/src/modeling.js
@@ -1,6 +1,7 @@
import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';
import { sweepSamples } from './modeling-bezier.js';
import { KNOT_MODES, NURBS_DEFAULT_ORDER, NURBS_MAX_ORDER, resampleSamples, sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';
+import { cloudMesh } from './cloud-geometry.js';
import { planSdf, sdfGeometry as buildSdf } from './modeling-sdf.js';
const MAX_INPUT_POINTS = 4096;
@@ -562,5 +563,13 @@ export function sdfGeometry(value, maxVertices = DEFAULT_VERTEX_LIMIT) {
return meshFrom(buildSdf(value), maxVertices);
}
+/** The cloud scene geometry: a seeded cluster of puffs as one closed, smooth surface. See docs/modeling.md. */
+export function cloudGeometry(value, maxVertices = DEFAULT_VERTEX_LIMIT) {
+ return meshFrom(cloudMesh(value), maxVertices);
+}
+
+/** The vertex count reserved for a cloud geometry, validated like cloudGeometry. */
+export { cloudVertexEstimate } from './cloud-geometry.js';
+
/** The vertex count reserved for an sdf geometry, validated like sdfGeometry. */
export { sdfVertexEstimate } from './modeling-sdf.js';
diff --git a/tests/actionable-errors-scene-core.test.js b/tests/actionable-errors-scene-core.test.js
index 5db4f1f1..1a0f1519 100644
--- a/tests/actionable-errors-scene-core.test.js
+++ b/tests/actionable-errors-scene-core.test.js
@@ -36,7 +36,7 @@ const RECIPE_CASES = [
['a camera takes fov or focalLength, never both', recipe => { recipe.camera = { fov: 40, focalLength: 50 }; }, RangeError, /^camera\.focalLength: got 50; expected only one of fov \(degrees\) or focalLength \(millimetres with sensorWidth\), such as fov 45; remove the other\.$/],
['a missing material names the choices', recipe => { recipe.nodes[0].material = 'ghost'; }, RangeError, /^nodes\.body\.material: got "ghost"; expected one of plain\.$/],
['a duplicate ID names the collection', recipe => { recipe.nodes[1].id = 'body'; }, RangeError, /^nodes\[1\]\.id: got "body"; expected an ID no other nodes entry uses; rename one, or remove the other\.$/],
- ['a geometry type outside the list names the list', recipe => { recipe.geometries[0].type = 'blob'; }, TypeError, /^geometries\[0\]\.type: got "blob"; expected one of box, cylinder.*terrain, fragment, dented.$/],
+ ['a geometry type outside the list names the list', recipe => { recipe.geometries[0].type = 'blob'; }, TypeError, /^geometries\[0\]\.type: got "blob"; expected one of box, cylinder.*terrain, cloud, fragment, dented.$/],
['a point list gives the range and an example', recipe => { recipe.geometries.push({ id: 'ring', type: 'lathe', profile: [[1, 0]] }); }, RangeError, /^geometries\[2\]\.profile: got "1 points"; expected a list of 2 to 4096 points of 2 numbers, such as \[\[0,0\],\[1,1\]\]\.$/],
['a wrong schema version gives the expected value', recipe => { recipe.schemaVersion = 2; }, RangeError, /^schemaVersion: got 2; expected 1\.$/],
// src/agent-terrain.js
diff --git a/tests/cloud-geometry.test.js b/tests/cloud-geometry.test.js
new file mode 100644
index 00000000..13963dc0
--- /dev/null
+++ b/tests/cloud-geometry.test.js
@@ -0,0 +1,116 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { CLOUD_LIMITS } from '../src/cloud-geometry.js';
+import { cloudGeometry, cloudVertexEstimate } from '../src/modeling.js';
+
+function hashOf(mesh) {
+ const hash = createHash('sha256');
+ for (const array of [mesh.positions, mesh.normals, mesh.uvs, mesh.indices]) hash.update(Buffer.from(array.buffer, array.byteOffset, array.byteLength));
+ return hash.digest('hex');
+}
+
+function boundsOf({ positions }) {
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ low[axis] = Math.min(low[axis], positions[offset + axis]);
+ high[axis] = Math.max(high[axis], positions[offset + axis]);
+ }
+ }
+ return { low, high };
+}
+
+// Edges that do not belong to exactly two triangles; zero means the surface is closed.
+function openEdgeCount({ indices }) {
+ const uses = new Map();
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ for (let side = 0; side < 3; side++) {
+ const from = indices[offset + side];
+ const to = indices[offset + (side + 1) % 3];
+ const key = from < to ? `${from}|${to}` : `${to}|${from}`;
+ uses.set(key, (uses.get(key) ?? 0) + 1);
+ }
+ }
+ return [...uses.values()].filter(count => count !== 2).length;
+}
+
+function pieceCount({ positions, indices }) {
+ const parent = Array.from({ length: positions.length / 3 }, (_, index) => index);
+ const root = vertex => {
+ while (parent[vertex] !== vertex) vertex = parent[vertex] = parent[parent[vertex]];
+ return vertex;
+ };
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ parent[root(indices[offset + 1])] = root(indices[offset]);
+ parent[root(indices[offset + 2])] = root(indices[offset]);
+ }
+ return new Set(Array.from(new Set(indices), vertex => root(vertex))).size;
+}
+
+test('the same seed gives the same bytes and another seed gives another cloud', () => {
+ const first = cloudGeometry({ seed: 7, puffs: 12 });
+ assert.equal(hashOf(cloudGeometry({ seed: 7, puffs: 12 })), hashOf(first));
+ assert.notEqual(hashOf(cloudGeometry({ seed: 8, puffs: 12 })), hashOf(first));
+});
+
+test('a cloud is one closed surface with outward normals and a flat base on y = 0', () => {
+ for (const seed of [1, 2, 3, 4]) {
+ const mesh = cloudGeometry({ seed, puffs: 16, flatBase: 0.7 });
+ assert.equal(openEdgeCount(mesh), 0, `seed ${seed} has open edges`);
+ assert.equal(pieceCount(mesh), 1, `seed ${seed} splits into several pieces`);
+ assert.ok(Math.abs(boundsOf(mesh).low[1]) < 0.05, `seed ${seed} base is off y = 0`);
+ const normalLength = Math.hypot(mesh.normals[0], mesh.normals[1], mesh.normals[2]);
+ assert.ok(Math.abs(normalLength - 1) < 1e-4);
+ }
+});
+
+test('width and height size the cloud and flatBase flattens its underside', () => {
+ const round = cloudGeometry({ seed: 5, width: 20, height: 8, flatBase: 0 });
+ const flat = cloudGeometry({ seed: 5, width: 20, height: 8, flatBase: 1 });
+ const { low, high } = boundsOf(round);
+ assert.ok(Math.max(high[0] - low[0], high[2] - low[2]) > 20 * 0.97 && Math.max(high[0] - low[0], high[2] - low[2]) < 20 * 1.03);
+ assert.ok(high[1] - low[1] > 8 * 0.97 && high[1] - low[1] < 8 * 1.03);
+ const flatBase = boundsOf(flat);
+ assert.ok(flatBase.high[1] < high[1], 'a flatter base cuts height off the underside');
+ const underside = mesh => Array.from({ length: mesh.positions.length / 3 }, (_, vertex) => mesh.positions[vertex * 3 + 1]).filter(y => y < 0.3).length;
+ assert.ok(underside(flat) > underside(round) * 2, 'flatBase puts many more vertices on the base plane');
+});
+
+test('more puffs make a lumpier, larger-surface cloud within the vertex estimate', () => {
+ const few = cloudGeometry({ seed: 9, puffs: 3 });
+ const many = cloudGeometry({ seed: 9, puffs: 30 });
+ assert.notEqual(hashOf(few), hashOf(many));
+ assert.ok(many.positions.length / 3 <= cloudVertexEstimate({ resolution: CLOUD_LIMITS.defaults.resolution }));
+});
+
+test('bad values name the field and what to pass', () => {
+ assert.throws(() => cloudGeometry({ puffs: 1 }), /cloud\.puffs: got 1; expected a whole number from 2 to 48, such as 14/);
+ assert.throws(() => cloudGeometry({ puffs: 2.5 }), /cloud\.puffs.*whole number/);
+ assert.throws(() => cloudGeometry({ width: 0 }), /cloud\.width.*0\.5 to 2000/);
+ assert.throws(() => cloudGeometry({ height: Number.NaN }), /cloud\.height/);
+ assert.throws(() => cloudGeometry({ flatBase: 1.5 }), /cloud\.flatBase.*0 to 1/);
+ assert.throws(() => cloudGeometry({ resolution: 200 }), /cloud\.resolution.*16 to 96/);
+ assert.throws(() => cloudGeometry({ seed: -1 }), /cloud\.seed/);
+ assert.throws(() => cloudGeometry({ colour: 'white' }), /cloud\.colour.*remove "colour"/);
+ assert.throws(() => cloudGeometry({ resolution: 96 }, 1000), /exceeding maxVertices 1000/);
+});
+
+test('a recipe cloud geometry becomes a part and respects the vertex budget', () => {
+ const recipe = (geometry, limits) => createAgentScene({
+ format: 'crucible.scene',
+ schemaVersion: 1,
+ materials: [{ id: 'white', color: [0.95, 0.95, 0.97], roughness: 1 }],
+ geometries: [{ id: 'cloud', type: 'cloud', ...geometry }],
+ nodes: [{ id: 'cloud-node', geometry: 'cloud', material: 'white' }],
+ }, limits);
+ const scene = recipe({ seed: 11, puffs: 10, resolution: 32 });
+ assert.equal(hashOf(scene.parts[0].geometry), hashOf(cloudGeometry({ seed: 11, puffs: 10, resolution: 32 })));
+ assert.throws(() => recipe({ resolution: 96 }, { maxVertices: 1000 }), /vertices|maxVertices/);
+ assert.throws(() => recipe({ puffs: 100 }), /cloud\.puffs/);
+ assert.throws(() => recipe({ puffs: null }), /puffs/);
+ assert.throws(() => recipe({ radius: 3 }), /radius/);
+});
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index aaceaedf..2d755170 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -163,7 +163,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
assert.equal(recipeSchema.properties.materials.maxItems, 256);
assert.equal(recipeSchema.properties.geometries.maxItems, 256);
// The tool lists the common fields; the strict schema still validates and scene_capabilities serves the full outline.
- assert.deepEqual(recipeSchema.properties.geometries.items.properties.type.enum, ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'terrain', 'grid', 'plane', 'cone', 'icoSphere', 'circle', 'line', 'fragment', 'dented', 'mesh']);
+ assert.deepEqual(recipeSchema.properties.geometries.items.properties.type.enum, ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'cloud', 'terrain', 'grid', 'plane', 'cone', 'icoSphere', 'circle', 'line', 'fragment', 'dented', 'mesh']);
assert.ok(recipeSchema.properties.environment.properties.setup);
assert.equal(recipeSchema.properties.shadow.additionalProperties, false);
for (const topic of ['geometries', 'environment', 'effects', 'motion', 'physics', 'cloth', 'armatures', 'materialFields', 'meshEdit', 'meshStack']) {