Skip to content

3D engine that AI agents drive

Grow cloud towers from levels with gradient normals (#2039)

Nguyen Xuan An09da01f398ac
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 071524c3..bcbe0e8d 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -105,6 +105,7 @@ on:
- 'src/cloth-self-collision.js'
- 'src/cloth.js'
- 'src/cloud-geometry.js'
+ - 'src/cloud-levels.js'
- 'src/cooperative.js'
- 'src/coplanar-overlap.js'
- 'src/crowd-skinning.js'
diff --git a/changes/2039-cloud-levels.md b/changes/2039-cloud-levels.md
new file mode 100644
index 00000000..a89386f9
--- /dev/null
+++ b/changes/2039-cloud-levels.md
@@ -0,0 +1 @@
+- The `cloud` geometry grows towers from `levels` (lobes on the surface of the level before), with `upBias`, `unionSoftness` and normals taken from the field gradient (#2039).
diff --git a/changes/2039-cloud-levels.size.md b/changes/2039-cloud-levels.size.md
new file mode 100644
index 00000000..784d256d
--- /dev/null
+++ b/changes/2039-cloud-levels.size.md
@@ -0,0 +1,4 @@
+- entry:modeling: the level growth and grid union are the whole feature, loaded only for recipes that contain a cloud geometry.
+- scene:agent-scene: three more cloud fields in the schema and capability text, in the core so agents can find them without loading the builder.
+- scene:agent-scene+lazy: the lazy modeling chunk carries the level builder, loaded only by recipes that use a cloud.
+- goal:agent-scene: an agent-facing capability (anime cumulus tower from one geometry record).
diff --git a/docs/modeling.md b/docs/modeling.md
index 7319b567..57d86018 100644
--- a/docs/modeling.md
+++ b/docs/modeling.md
@@ -146,10 +146,15 @@ through its depth. `"\n"` starts a new line 1.2 em lower. `size` is the em heigh
| `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. |
+| `resolution` | 48 (128 with `levels`) | whole, 16 to 96 (16 to 160 with `levels`) | Cells along the longest side; it sets the triangle count. |
+| `levels` | none | 1 to 4 of `{count, sizeRatio}`, 1000 lobes in all | Grows a tower: the first level is the dome layout (`count` 1 to 48 lobes), and each later level puts its lobes on the surface of the level before. `sizeRatio` (0.02 to 2) is the lobe size as a share of the first level's. `puffs` is not used with levels. |
+| `upBias` | 0.5 | 0 to 1, with `levels` | 0 grows lobes in every direction; 1 never grows them downward. |
+| `unionSoftness` | 0.14 (0.3 with `levels`) | 0.02 to 1 | The blend between lobes as a share of lobe radius; with levels each level blends by its own radius. Lower is tighter. |
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.
+With `levels` such as `[{"count": 7, "sizeRatio": 1}, {"count": 60, "sizeRatio": 0.35}, {"count": 680, "sizeRatio": 0.12}]` the cloud becomes a tower covered in rounded lobes. Normals come from the gradient of the blended field at each vertex, not from the mesh faces, so toon steps follow the lobes without fine rings. Later levels find their neighbours in a grid, so 680 bumps cost little per sample; three such towers at `resolution` 128 take about 2.3 s together. A mesh over 150000 faces is refused with the resolution to pass instead.
+
For a sky with many clouds, keep `resolution` at 48 or lower and repeat a few cloud shapes with a node's `instances` (see [agent-scene.md](agent-scene.md)) instead of building one mesh per cloud. Triangles grow with the square of `resolution`.
## Resource and precision limits
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index d98793c0..566a2c04 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -364,7 +364,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('cloud'), seed: looseField, puffs: looseField, width: looseField, height: looseField, flatBase: looseField, resolution: looseField, levels: z.array(z.unknown()).max(4).optional(), upBias: looseField, unionSoftness: 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 2fb6eeb9..b715b834 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -233,7 +233,7 @@ 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', '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.',
+ 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). levels:[{count, sizeRatio}] (1-4 levels, 1000 lobes in all, first count 1-48) grows each level of lobes on the surface of the level before, such as [{count:7,sizeRatio:1},{count:60,sizeRatio:0.35},{count:680,sizeRatio:0.12}] for a tower covered in rounded bumps; with levels, puffs is not used, resolution is 16-160 (default 128, at most 150000 faces), upBias 0-1 (0.5; 1 never grows down) and unionSoftness 0.02-1 (0.3 of the lobe radius of each level; also blends a cloud without levels, default 0.14) apply. Normals come from the field gradient, so toon steps stay clean. 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.js b/src/agent-scene.js
index 54a2773e..7ad4ee42 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -535,7 +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'],
+ cloud: ['seed', 'puffs', 'width', 'height', 'flatBase', 'resolution', 'levels', 'upBias', 'unionSoftness'],
fragment: ['source', 'seed', 'cells', 'index', 'impact', 'impactRadius'],
dented: ['source', 'impacts', 'stiffness', 'maxDepth', 'radius'],
};
diff --git a/src/cloud-geometry.js b/src/cloud-geometry.js
index 12a53e52..88f4622a 100644
--- a/src/cloud-geometry.js
+++ b/src/cloud-geometry.js
@@ -1,5 +1,6 @@
import { invalidField } from './field-error.js';
import { meshDistanceField, planDistanceField } from './modeling-sdf.js';
+import { CLOUD_LEVEL_LIMITS, growLevels, levelSettings, levelUnion, smoothMinimum } from './cloud-levels.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
@@ -14,7 +15,7 @@ export const CLOUD_LIMITS = Object.freeze({
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'];
+const CLOUD_FIELDS = ['id', 'type', 'seed', 'puffs', 'width', 'height', 'flatBase', 'resolution', 'levels', 'upBias', 'unionSoftness'];
// 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
@@ -31,10 +32,14 @@ const OVERLAP_SHARE = 0.4;
const BLEND_PER_RADIUS = 0.14;
const BASE_ROUNDING_PER_RADIUS = 0.12;
const FULL_TURN = Math.PI * 2;
+// Vertices reserved per resolution squared for a cloud with levels; towers measured 2 to 3.1 at resolution 128 to 160 (the check after meshing is the real limit).
+const LEVEL_VERTICES_PER_SQUARED_RESOLUTION = 4;
+// With levels the normal is the field gradient over this share of a cell, small enough to follow the small bumps.
+const LEVEL_NORMAL_STEP_SHARE = 0.15;
-function limited(value, name, whole) {
- const [minimum, maximum] = CLOUD_LIMITS[name];
- const fallback = CLOUD_LIMITS.defaults[name];
+function limited(value, name, whole, limits = CLOUD_LIMITS) {
+ const [minimum, maximum] = limits[name];
+ const fallback = limits.defaults[name];
const resolved = value ?? fallback;
const valid = Number.isFinite(resolved) && resolved >= minimum && resolved <= maximum && (!whole || Number.isInteger(resolved));
if (!valid) {
@@ -43,25 +48,49 @@ function limited(value, name, whole) {
return resolved;
}
+// The levels, upBias and unionSoftness fields live in CLOUD_LEVEL_LIMITS; resolution has its own range once levels are given.
+function leveledSettings(value, levels) {
+ const limits = CLOUD_LEVEL_LIMITS;
+ return {
+ levels: levelSettings(levels),
+ upBias: limited(value.upBias, 'upBias', false, limits),
+ unionSoftness: limited(value.unionSoftness, 'unionSoftness', false, limits),
+ resolution: limited(value.resolution, 'resolution', true, limits),
+ };
+}
+
/** 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 {
+ if (value.levels !== undefined && value.puffs !== undefined) {
+ throw invalidField('cloud.puffs', value.puffs, 'left out when levels is given; the first level count sets the big lobes, so remove puffs');
+ }
+ if (value.levels === undefined && value.upBias !== undefined) {
+ throw invalidField('cloud.upBias', value.upBias, 'used together with levels; add levels such as [{count: 7, sizeRatio: 1}, {count: 60, sizeRatio: 0.35}] or remove upBias');
+ }
+ const shared = {
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),
+ };
+ if (value.levels !== undefined) return { ...shared, puffs: null, ...leveledSettings(value, value.levels) };
+ return {
+ ...shared,
+ puffs: limited(value.puffs, 'puffs', true),
resolution: limited(value.resolution, 'resolution', true),
+ levels: null,
+ upBias: null,
+ unionSoftness: value.unionSoftness === undefined ? null : limited(value.unionSoftness, 'unionSoftness', false, CLOUD_LEVEL_LIMITS),
};
}
/** The vertex count to reserve for a cloud record: validated, not meshed. */
export function cloudVertexEstimate(value) {
- const { resolution } = cloudSettings(value);
- return 8 * resolution * resolution;
+ const { resolution, levels } = cloudSettings(value);
+ return (levels ? LEVEL_VERTICES_PER_SQUARED_RESOLUTION : 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
@@ -86,6 +115,13 @@ function scatterPuffs({ seed, puffs }) {
return lobes;
}
+// The lobes of every level, each an array of { center, radius }: the dome layout alone, or the dome grown into levels.
+function scatterLevels(settings) {
+ if (!settings.levels) return [scatterPuffs(settings)];
+ const baseLobes = scatterPuffs({ seed: settings.seed, puffs: settings.levels[0].count });
+ return growLevels(baseLobes, settings.levels, settings);
+}
+
function domeReach(climb) {
return DOME_HALF_WIDTH * (1 - climb) ** DOME_NARROWING;
}
@@ -116,46 +152,43 @@ function extentOf(lobes, axis) {
// 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 }) {
+function fitLayout(levelLobes, { width, height }) {
+ const lobes = levelLobes.flat();
const x = extentOf(lobes, 0);
const y = extentOf(lobes, 1);
const z = extentOf(lobes, 2);
- const centred = lobes.map(({ center, radius }) => ({
+ const centred = ({ 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;
+ return { levelLobes: levelLobes.map(level => level.map(centred)), stretch: [side, height / (y.high - y.low), side] };
}
// 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) {
+// keeps the round underside of the lowest lobes; 1 cuts as far as the widest lobe reaches. A union of one level blends by a share
+// of the widest lobe; with levels, each level blends by a share of its own widest lobe, so small bumps stay crisp.
+function layoutField(levelLobes, { flatBase, unionSoftness, levels }) {
+ const lobes = levelLobes.flat();
const widest = Math.max(...lobes.map(lobe => lobe.radius));
- const blend = widest * BLEND_PER_RADIUS;
+ const softness = unionSoftness ?? BLEND_PER_RADIUS;
+ const blends = levelLobes.map(level => softness * (levels ? Math.max(...level.map(lobe => lobe.radius)) : widest));
+ const union = levelUnion(levelLobes.map((level, index) => ({ lobes: level, blend: blends[index] })));
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);
+ const joined = union(x, y, z);
+ if (flatBase === 0) return joined;
+ return -smoothMinimum(-joined, y - cutHeight, rounding);
};
- return { distance, cutHeight, slack: blend / 4 };
+ return { distance, cutHeight, slack: Math.max(...blends) / 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);
+function stretchedField({ levelLobes, stretch }, settings) {
+ const lobes = levelLobes.flat();
+ const { distance, cutHeight, slack } = layoutField(levelLobes, settings);
const [stretchX, stretchY, stretchZ] = stretch;
const shortest = Math.min(...stretch);
const extents = [0, 1, 2].map(axis => extentOf(lobes, axis));
@@ -172,6 +205,18 @@ function stretchedField({ lobes, stretch }, flatBase) {
/** 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));
+ const field = stretchedField(fitLayout(scatterLevels(settings), settings), settings);
+ const plan = planDistanceField(field, settings.resolution);
+ if (!settings.levels) return meshDistanceField(plan);
+ const mesh = meshDistanceField({ ...plan, normalStep: plan.edge * LEVEL_NORMAL_STEP_SHARE });
+ checkFaceCount(mesh, settings.resolution);
+ return mesh;
+}
+
+export function checkFaceCount({ indices }, resolution) {
+ const faces = indices.length / 3;
+ if (faces > CLOUD_LEVEL_LIMITS.faces) {
+ const lowered = Math.max(CLOUD_LEVEL_LIMITS.resolution[0], Math.floor(resolution * Math.sqrt(CLOUD_LEVEL_LIMITS.faces / faces)));
+ throw new RangeError(`cloud.resolution ${resolution} makes ${faces} faces, over the limit of ${CLOUD_LEVEL_LIMITS.faces}. Pass resolution ${lowered} or lower, or use fewer lobes.`);
+ }
}
diff --git a/src/cloud-levels.js b/src/cloud-levels.js
new file mode 100644
index 00000000..ddccccfc
--- /dev/null
+++ b/src/cloud-levels.js
@@ -0,0 +1,210 @@
+import { invalidField } from './field-error.js';
+import { seededRandom } from './seeded-random.js';
+
+// Cloud levels: lobes grown on the surface of the lobes before them (a few big ones, many medium ones on those, many small bumps on
+// those), and the smooth union that joins them. Level 0 is checked against every lobe; deeper levels find their neighbours in a
+// uniform grid, so hundreds of bumps do not make every sample cost one distance per bump. Plain arithmetic in a fixed order.
+
+export const CLOUD_LEVEL_LIMITS = Object.freeze({
+ levels: [1, 4],
+ firstLevelCount: [1, 48],
+ count: [1, 1000],
+ sizeRatio: [0.02, 2],
+ totalLobes: 1000,
+ upBias: [0, 1],
+ unionSoftness: [0.02, 1],
+ resolution: [16, 160],
+ faces: 150_000,
+ defaults: Object.freeze({ upBias: 0.5, unionSoftness: 0.3, resolution: 128 }),
+});
+const LEVEL_FIELDS = ['count', 'sizeRatio'];
+// A grown lobe sits this share of its radius inside its parent's surface, so it protrudes by the rest.
+const SINK_SHARE = 0.3;
+const SIZE_JITTER = 0.4;
+// A deeper level only matters near the surface it grows on: past this many (radius + blend) from the union so far, its lobes
+// are skipped. The surface being meshed is always closer than that.
+const REACH_PER_RADIUS = 2;
+const FULL_TURN = Math.PI * 2;
+// Channels of the seeded random draws, kept apart from the base layout's channels 0 to 3.
+const LEVEL_CHANNEL_START = 16;
+
+function levelError(path, value, expected) {
+ return invalidField(`cloud.levels${path}`, value, expected);
+}
+
+/** Validates the `levels` array and returns it as [{ count, sizeRatio }]. */
+export function levelSettings(levels) {
+ const [minimumLevels, maximumLevels] = CLOUD_LEVEL_LIMITS.levels;
+ if (!Array.isArray(levels) || levels.length < minimumLevels || levels.length > maximumLevels) {
+ throw levelError('', levels, `an array of ${minimumLevels} to ${maximumLevels} levels such as [{count: 7, sizeRatio: 1}, {count: 60, sizeRatio: 0.35}, {count: 680, sizeRatio: 0.12}]`);
+ }
+ const settings = levels.map((level, index) => levelSetting(level, index));
+ const total = settings.reduce((sum, level) => sum + level.count, 0);
+ if (total > CLOUD_LEVEL_LIMITS.totalLobes) {
+ throw levelError('', total, `at most ${CLOUD_LEVEL_LIMITS.totalLobes} lobes in all; lower a count`);
+ }
+ return settings;
+}
+
+function levelSetting(level, index) {
+ const path = `[${index}]`;
+ if (level === null || typeof level !== 'object' || Array.isArray(level)) throw levelError(path, level, 'an object {count, sizeRatio}');
+ for (const key of Object.keys(level)) {
+ if (!LEVEL_FIELDS.includes(key)) throw levelError(`${path}.${key}`, level[key], `one of ${LEVEL_FIELDS.join(', ')}; remove "${key}"`);
+ }
+ const [minimumCount, maximumCount] = index === 0 ? CLOUD_LEVEL_LIMITS.firstLevelCount : CLOUD_LEVEL_LIMITS.count;
+ if (!Number.isInteger(level.count) || level.count < minimumCount || level.count > maximumCount) {
+ throw levelError(`${path}.count`, level.count, `a whole number from ${minimumCount} to ${maximumCount}`);
+ }
+ const [minimumRatio, maximumRatio] = CLOUD_LEVEL_LIMITS.sizeRatio;
+ if (!Number.isFinite(level.sizeRatio) || level.sizeRatio < minimumRatio || level.sizeRatio > maximumRatio) {
+ throw levelError(`${path}.sizeRatio`, level.sizeRatio, `a number from ${minimumRatio} to ${maximumRatio}, the lobe size as a share of the first level's, such as ${index === 0 ? 1 : 0.35}`);
+ }
+ return { count: level.count, sizeRatio: level.sizeRatio };
+}
+
+// A direction on the unit sphere. upBias 0 is uniform; 1 flattens the lower half onto the equator, so lobes grow up and out.
+function growthDirection(index, channel, seed, upBias) {
+ const height = random(index, channel, seed) * 2 - 1;
+ const azimuth = random(index, channel + 1, seed) * FULL_TURN;
+ const ring = Math.sqrt(1 - height * height);
+ const lifted = height < 0 ? height * (1 - upBias) : height;
+ const direction = [ring * Math.cos(azimuth), lifted, ring * Math.sin(azimuth)];
+ const length = Math.hypot(direction[0], direction[1], direction[2]);
+ return direction.map(value => value / length);
+}
+
+function random(index, channel, seed) {
+ return seededRandom(index, channel, seed);
+}
+
+// The parent whose share of the total surface area (radius squared) covers `position`, 0 to 1: big lobes carry more children, so
+// small and large ones end up equally covered, and each lobe's children are an even run of the sequence.
+function parentBySurface(parents, position) {
+ const total = parents.reduce((sum, parent) => sum + parent.radius ** 2, 0);
+ let covered = 0;
+ for (const parent of parents) {
+ covered += parent.radius ** 2;
+ if (position * total <= covered) return parent;
+ }
+ return parents[parents.length - 1];
+}
+
+/** Level 0 is the base layout scaled by its sizeRatio; each later level puts its lobes on the lobes of the level before, each a share of its parent's radius (the ratio of the two sizeRatios). Returns an array of lobe arrays. */
+export function growLevels(baseLobes, levels, { seed, upBias }) {
+ const grown = [baseLobes.map(({ center, radius }) => ({ center, radius: radius * levels[0].sizeRatio }))];
+ for (let level = 1; level < levels.length; level++) {
+ const parents = grown[level - 1];
+ const channel = LEVEL_CHANNEL_START * level;
+ const shrink = levels[level].sizeRatio / levels[level - 1].sizeRatio;
+ const lobes = [];
+ for (let index = 0; index < levels[level].count; index++) {
+ const parent = parentBySurface(parents, (index + 0.5) / levels[level].count);
+ const radius = parent.radius * shrink * (1 - SIZE_JITTER / 2 + SIZE_JITTER * random(index, channel + 2, seed));
+ const direction = growthDirection(index, channel, seed, upBias);
+ const reach = parent.radius - SINK_SHARE * radius;
+ lobes.push({ center: parent.center.map((value, axis) => value + direction[axis] * reach), radius });
+ }
+ grown.push(lobes);
+ }
+ return grown;
+}
+
+export 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;
+}
+
+function widestRadius(lobes) {
+ return lobes.reduce((widest, lobe) => Math.max(widest, lobe.radius), 0);
+}
+
+// A uniform grid of lobe centres: cells are counted, then lobe numbers are written in order, so each cell lists its lobes by number.
+function gridOf(lobes, cellSize) {
+ const low = [0, 1, 2].map(axis => Math.min(...lobes.map(lobe => lobe.center[axis])));
+ const high = [0, 1, 2].map(axis => Math.max(...lobes.map(lobe => lobe.center[axis])));
+ const cells = low.map((start, axis) => Math.floor((high[axis] - start) / cellSize) + 1);
+ const cellOf = lobe => lobe.center.map((value, axis) => Math.floor((value - low[axis]) / cellSize));
+ const flat = ([x, y, z]) => (z * cells[1] + y) * cells[0] + x;
+ const starts = new Int32Array(cells[0] * cells[1] * cells[2] + 1);
+ for (const lobe of lobes) starts[flat(cellOf(lobe)) + 1]++;
+ for (let cell = 0; cell < starts.length - 1; cell++) starts[cell + 1] += starts[cell];
+ const filled = starts.slice();
+ const members = new Int32Array(lobes.length);
+ lobes.forEach((lobe, number) => {
+ members[filled[flat(cellOf(lobe))]++] = number;
+ });
+ return { low, cells, starts, members, cellSize };
+}
+
+function packLobes(lobes) {
+ const packed = new Float64Array(lobes.length * 4);
+ lobes.forEach(({ center, radius }, number) => packed.set([center[0], center[1], center[2], radius], number * 4));
+ return packed;
+}
+
+// Folds the lobes of one deeper level into `best`, in lobe order. A lobe changes the result only where its distance is within
+// `blend` of the union so far, which is inside a ball of radius (radius + blend + best) around its centre, so only the lobes
+// whose cells meet the box of that ball are folded; the rest would return `best` unchanged.
+function levelFolder(lobes, blend) {
+ const widest = widestRadius(lobes);
+ const reach = REACH_PER_RADIUS * (widest + blend);
+ const grid = gridOf(lobes, widest + blend + reach);
+ const packed = packLobes(lobes);
+ const candidates = new Int32Array(lobes.length);
+ const range = (position, radius, axis) => [
+ Math.max(0, Math.floor((position - radius - grid.low[axis]) / grid.cellSize)),
+ Math.min(grid.cells[axis] - 1, Math.floor((position + radius - grid.low[axis]) / grid.cellSize)),
+ ];
+ return (best, x, y, z) => {
+ if (best > reach) return best;
+ const radius = widest + blend + best;
+ const [fromX, toX] = range(x, radius, 0);
+ const [fromY, toY] = range(y, radius, 1);
+ const [fromZ, toZ] = range(z, radius, 2);
+ let count = 0;
+ for (let cellZ = fromZ; cellZ <= toZ; cellZ++) {
+ for (let cellY = fromY; cellY <= toY; cellY++) {
+ const row = (cellZ * grid.cells[1] + cellY) * grid.cells[0];
+ for (let position = grid.starts[row + fromX]; position < grid.starts[row + toX + 1]; position++) candidates[count++] = grid.members[position];
+ }
+ }
+ const ordered = candidates.subarray(0, count).sort();
+ let union = best;
+ for (const number of ordered) {
+ const offset = number * 4;
+ const distance = Math.sqrt((x - packed[offset]) ** 2 + (y - packed[offset + 1]) ** 2 + (z - packed[offset + 2]) ** 2) - packed[offset + 3];
+ union = smoothMinimum(union, distance, blend);
+ }
+ return union;
+ };
+}
+
+/** The smooth union of levels [{ lobes, blend }] as a distance function; level 0 checks every lobe, deeper levels use a grid. */
+export function levelUnion(levels) {
+ const [first, ...deeper] = levels;
+ const folders = deeper.map(({ lobes, blend }) => levelFolder(lobes, blend));
+ return (x, y, z) => {
+ let union = Infinity;
+ for (const { center, radius } of first.lobes) {
+ const lobeDistance = Math.hypot(x - center[0], y - center[1], z - center[2]) - radius;
+ union = Number.isFinite(union) ? smoothMinimum(union, lobeDistance, first.blend) : lobeDistance;
+ }
+ for (const fold of folders) union = fold(union, x, y, z);
+ return union;
+ };
+}
+
+/** Every lobe of every level checked one by one, with no grid and no skipping: the reference the grid is tested against. */
+export function levelUnionByBruteForce(levels) {
+ return (x, y, z) => {
+ let union = Infinity;
+ for (const { lobes, blend } of levels) {
+ 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;
+ }
+ }
+ return union;
+ };
+}
diff --git a/src/modeling-sdf.js b/src/modeling-sdf.js
index cfe840e3..f3d08628 100644
--- a/src/modeling-sdf.js
+++ b/src/modeling-sdf.js
@@ -303,7 +303,7 @@ export function meshDistanceField(plan) {
const normals = new Float32Array(positions.length);
const uvs = new Float32Array(positions.length / 3 * 2);
for (let vertex = 0; vertex < positions.length / 3; vertex++) {
- const gradient = gradientAt(plan.root.distance, separatedPositions[vertex * 3], separatedPositions[vertex * 3 + 1], separatedPositions[vertex * 3 + 2], plan.edge * 0.5);
+ const gradient = gradientAt(plan.root.distance, separatedPositions[vertex * 3], separatedPositions[vertex * 3 + 1], separatedPositions[vertex * 3 + 2], plan.normalStep ?? plan.edge * 0.5);
normals.set(gradient, vertex * 3);
const strongest = Math.abs(gradient[0]) >= Math.abs(gradient[1]) && Math.abs(gradient[0]) >= Math.abs(gradient[2]) ? 0 : Math.abs(gradient[1]) >= Math.abs(gradient[2]) ? 1 : 2;
const [u, v] = [[1, 2], [0, 2], [0, 1]][strongest];
diff --git a/tests/cloud-geometry.test.js b/tests/cloud-geometry.test.js
index 13963dc0..b18c905d 100644
--- a/tests/cloud-geometry.test.js
+++ b/tests/cloud-geometry.test.js
@@ -3,7 +3,9 @@ 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 { CLOUD_LIMITS, checkFaceCount } from '../src/cloud-geometry.js';
+import { growLevels, levelSettings, levelUnion, levelUnionByBruteForce } from '../src/cloud-levels.js';
+import { seededRandom } from '../src/seeded-random.js';
import { cloudGeometry, cloudVertexEstimate } from '../src/modeling.js';
function hashOf(mesh) {
@@ -114,3 +116,111 @@ test('a recipe cloud geometry becomes a part and respects the vertex budget', ()
assert.throws(() => recipe({ puffs: null }), /puffs/);
assert.throws(() => recipe({ radius: 3 }), /radius/);
});
+
+const TOWER_LEVELS = [{ count: 7, sizeRatio: 1 }, { count: 60, sizeRatio: 0.35 }, { count: 680, sizeRatio: 0.12 }];
+
+test('a cloud without levels keeps the bytes it had before levels existed', () => {
+ assert.equal(hashOf(cloudGeometry({ seed: 7, puffs: 12 })), 'c5df2864c435732ada8ae8f7d6e9ccd77dc8aca16a4a1eaa452edb80de81cad1');
+});
+
+test('a tower of levels is deterministic, closed, one piece and sized as asked', () => {
+ const tower = cloudGeometry({ seed: 3, levels: TOWER_LEVELS, resolution: 64, width: 8, height: 6 });
+ assert.equal(hashOf(cloudGeometry({ seed: 3, levels: TOWER_LEVELS, resolution: 64, width: 8, height: 6 })), hashOf(tower));
+ assert.notEqual(hashOf(cloudGeometry({ seed: 4, levels: TOWER_LEVELS, resolution: 64, width: 8, height: 6 })), hashOf(tower));
+ assert.notEqual(hashOf(cloudGeometry({ seed: 3, levels: TOWER_LEVELS.slice(0, 2), resolution: 64, width: 8, height: 6 })), hashOf(tower));
+ assert.equal(openEdgeCount(tower), 0);
+ assert.equal(pieceCount(tower), 1);
+ const { low, high } = boundsOf(tower);
+ assert.ok(Math.max(high[0] - low[0], high[2] - low[2]) > 8 * 0.95 && Math.max(high[0] - low[0], high[2] - low[2]) < 8 * 1.05);
+ assert.ok(Math.abs(low[1]) < 0.1);
+});
+
+test('the grid gives the same union as checking every lobe, wherever the surface can be', () => {
+ const baseLobes = [{ center: [0, 0, 0], radius: 1 }, { center: [1.2, 0.3, 0], radius: 0.8 }, { center: [-0.8, 0.9, 0.4], radius: 0.7 }];
+ const grown = growLevels(baseLobes, levelSettings(TOWER_LEVELS), { seed: 5, upBias: 0.5 });
+ const levels = grown.map(lobes => ({ lobes, blend: 0.3 * Math.max(...lobes.map(lobe => lobe.radius)) }));
+ const fast = levelUnion(levels);
+ const slow = levelUnionByBruteForce(levels);
+ let compared = 0;
+ for (let sample = 0; sample < 4000; sample++) {
+ const point = [0, 1, 2].map(axis => (seededRandom(sample, axis, 9) - 0.5) * 5);
+ const reference = slow(...point);
+ if (Math.abs(reference) > 0.1) continue;
+ compared++;
+ assert.ok(Math.abs(fast(...point) - reference) < 1e-9, `sample ${sample} differs`);
+ }
+ assert.ok(compared > 100, `only ${compared} samples near the surface`);
+});
+
+test('grown lobes sit on their parents and upBias 1 never grows them downward', () => {
+ const baseLobes = [{ center: [0, 0, 0], radius: 1 }];
+ const levels = levelSettings([{ count: 1, sizeRatio: 1 }, { count: 50, sizeRatio: 0.3 }]);
+ const lifted = growLevels(baseLobes, levels, { seed: 2, upBias: 1 })[1];
+ const uniform = growLevels(baseLobes, levels, { seed: 2, upBias: 0 })[1];
+ assert.ok(lifted.every(lobe => lobe.center[1] >= -1e-12));
+ assert.ok(uniform.some(lobe => lobe.center[1] < -0.2));
+ for (const lobe of uniform) assert.ok(Math.hypot(...lobe.center) < 1 && Math.hypot(...lobe.center) > 1 - 0.3 * lobe.radius - 1e-9);
+});
+
+test('normals come from the field gradient: unit length and facing along the face they belong to', () => {
+ const mesh = cloudGeometry({ seed: 2, levels: TOWER_LEVELS, resolution: 48 });
+ let alignment = 0;
+ let pairs = 0;
+ let facingAway = 0;
+ for (let corner = 0; corner < mesh.indices.length; corner += 3) {
+ const [first, second, third] = [0, 1, 2].map(side => mesh.indices[corner + side]);
+ const point = vertex => [0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis]);
+ const [firstPoint, secondPoint, thirdPoint] = [first, second, third].map(point);
+ const edgeOne = secondPoint.map((value, axis) => value - firstPoint[axis]);
+ const edgeTwo = thirdPoint.map((value, axis) => value - firstPoint[axis]);
+ const face = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];
+ const faceLength = Math.hypot(...face);
+ if (faceLength < 1e-9) continue;
+ for (const vertex of [first, second, third]) {
+ const normal = [0, 1, 2].map(axis => mesh.normals[vertex * 3 + axis]);
+ assert.ok(Math.abs(Math.hypot(...normal) - 1) < 1e-4);
+ alignment += (normal[0] * face[0] + normal[1] * face[1] + normal[2] * face[2]) / faceLength;
+ pairs++;
+ if ((normal[0] * face[0] + normal[1] * face[1] + normal[2] * face[2]) < 0) facingAway++;
+ }
+ }
+ assert.ok(alignment / pairs > 0.8, `normals follow their faces on average: ${alignment / pairs}`);
+ assert.ok(facingAway / pairs < 0.01, `${facingAway} of ${pairs} corners face away from their triangle`);
+});
+
+test('levels, upBias, unionSoftness and size limits name the field and what to pass', () => {
+ assert.throws(() => cloudGeometry({ levels: [] }), /cloud\.levels.*1 to 4 levels/);
+ assert.throws(() => cloudGeometry({ levels: 'many' }), /cloud\.levels.*array/);
+ assert.throws(() => cloudGeometry({ levels: Array(5).fill({ count: 2, sizeRatio: 0.5 }) }), /cloud\.levels.*1 to 4 levels/);
+ assert.throws(() => cloudGeometry({ levels: [{ count: 49, sizeRatio: 1 }] }), /cloud\.levels\[0\]\.count.*1 to 48/);
+ assert.throws(() => cloudGeometry({ levels: [{ count: 7, sizeRatio: 1 }, { count: 1001, sizeRatio: 0.3 }] }), /cloud\.levels\[1\]\.count.*1 to 1000/);
+ assert.throws(() => cloudGeometry({ levels: [{ count: 40, sizeRatio: 1 }, { count: 600, sizeRatio: 0.3 }, { count: 600, sizeRatio: 0.1 }] }), /at most 1000 lobes in all/);
+ assert.throws(() => cloudGeometry({ levels: [{ count: 7, sizeRatio: 5 }] }), /cloud\.levels\[0\]\.sizeRatio/);
+ assert.throws(() => cloudGeometry({ levels: [{ count: 7, sizeRatio: 1, size: 2 }] }), /cloud\.levels\[0\]\.size.*remove "size"/);
+ assert.throws(() => cloudGeometry({ levels: TOWER_LEVELS, puffs: 10 }), /cloud\.puffs.*remove puffs/);
+ assert.throws(() => cloudGeometry({ upBias: 0.5 }), /cloud\.upBias.*add levels/);
+ assert.throws(() => cloudGeometry({ levels: TOWER_LEVELS, upBias: 2 }), /cloud\.upBias.*0 to 1/);
+ assert.throws(() => cloudGeometry({ unionSoftness: 0 }), /cloud\.unionSoftness.*0\.02 to 1/);
+ assert.throws(() => cloudGeometry({ levels: TOWER_LEVELS, resolution: 161 }), /cloud\.resolution.*16 to 160/);
+ assert.throws(() => cloudGeometry({ levels: TOWER_LEVELS, resolution: 160 }, 1000), /exceeding maxVertices 1000/);
+});
+
+test('a mesh over the face limit says which resolution to pass', () => {
+ assert.throws(() => checkFaceCount({ indices: new Uint32Array(3 * 200_000) }, 160), /makes 200000 faces, over the limit of 150000\. Pass resolution 138 or lower/);
+ checkFaceCount({ indices: new Uint32Array(3 * 150_000) }, 160);
+});
+
+test('unionSoftness widens the blend between lobes of a cloud without levels', () => {
+ assert.notEqual(hashOf(cloudGeometry({ seed: 7, puffs: 12, unionSoftness: 0.5 })), hashOf(cloudGeometry({ seed: 7, puffs: 12 })));
+});
+
+test('a recipe cloud with levels becomes a part', () => {
+ const scene = createAgentScene({
+ format: 'crucible.scene',
+ schemaVersion: 1,
+ materials: [{ id: 'white', color: [0.95, 0.95, 0.97], roughness: 1 }],
+ geometries: [{ id: 'cloud', type: 'cloud', seed: 4, levels: TOWER_LEVELS, resolution: 40 }],
+ nodes: [{ id: 'cloud-node', geometry: 'cloud', material: 'white' }],
+ });
+ assert.equal(hashOf(scene.parts[0].geometry), hashOf(cloudGeometry({ seed: 4, levels: TOWER_LEVELS, resolution: 40 })));
+});