Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a ground clutter addon and share tiles with grass

Nguyen Xuan An2b00b866468b
diff --git a/.gitignore b/.gitignore
index 1854972f..160c6b3b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,6 +23,7 @@ public/vehicle.md
public/vegetation.md
public/terrain.md
public/grass.md
+public/clutter.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 517642bb..dccce65d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@
- Add `67js/addons/grass`: terrain-following grass fields of clumped, curved blades with rounded normals, root-to-tip colour, dry patches, masks for paths, four presets and tile level of detail
- Bend `grass` tag vertices by blade height and roll wind gusts across the field as a travelling wave
- Break up grass fields with `patchiness` (short, thin and dense patches), seed `stalks` and folded blades, and let sunlight glow through backlit blades
+- Add `67js/addons/clutter`: pebbles, chipped rocks with moss, twigs and fallen leaves scattered over terrain in streamed tiles, with four presets
+- Share one tile and level-of-detail system between grass and clutter
- Add splat `variation` (brightness and hue drift at three scales that grows with distance) and `edgeNoise` (ragged layer borders), both on by default
## 0.10.0
diff --git a/README.md b/README.md
index fbd88eac..dce7971f 100644
--- a/README.md
+++ b/README.md
@@ -119,6 +119,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Environment | `67js/addons/hdri` | Image-based lighting from Radiance `.hdr` files, with blurred reflections. |
| Terrain | `67js/addons/terrain`, `67js/addons/texture-set` | [Chunked terrain](docs/terrain.md) with level of detail and a four-layer splat material from scanned textures. |
| Grass | `67js/addons/grass` | [Grass fields](docs/grass.md) of clumped, curved blades with rolling wind gusts, paths and level of detail. |
+| Clutter | `67js/addons/clutter` | [Pebbles, rocks, twigs and fallen leaves](docs/clutter.md) scattered over terrain in streamed tiles. |
| Vegetation | `67js/addons/vegetation` | [Seeded trees, bushes and grass](docs/vegetation.md) with scanned leaves and bark, wind and level of detail. |
| Liquid | `67js/addons/spume` | [Baked liquid playback](docs/spume.md) with refraction and spray from the Spume solver. |
| Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](docs/vehicle.md): wheel spin, steering, roll, pitch and ground following. |
diff --git a/docs/clutter.md b/docs/clutter.md
new file mode 100644
index 00000000..d2aced2d
--- /dev/null
+++ b/docs/clutter.md
@@ -0,0 +1,81 @@
+# Ground clutter
+
+`67js/addons/clutter` scatters pebbles, rocks, twigs and fallen leaves over terrain.
+It is in the current source and not yet published.
+
+```js
+import { createClutter } from '67js/addons/clutter';
+
+const clutter = createClutter({
+ preset: 'forest',
+ area: { minX: -40, maxX: 40, minZ: -70, maxZ: 30 },
+ terrainHeight: terrain.heightAt,
+ eye,
+ seed: 5,
+});
+
+const renderer = new Renderer67(canvas, [...terrain.parts, ...grass.parts, ...clutter.parts], { world: true, ground: false });
+
+// When the camera moves:
+if (clutter.update(eye)) renderer.replaceParts([...terrain.parts, ...grass.parts, ...clutter.parts]);
+```
+
+## How it is made
+
+- A stone is a sphere displaced by smooth noise. Rocks are also cut by four random planes, which gives them flat, chipped faces. Pebbles stay round.
+- A stone sinks a third to a half of its height into the ground and tilts with the terrain.
+- Vertex colours give each stone its own tone and hue, from blue-grey to rust. Blotches follow the stone's own space. The underside is darker, soil clings near the ground line, and rocks gather moss on top.
+- Twigs are tapered tubes that lie on the ground and follow it. Leaves are small cupped strips in a palette of dry browns.
+- Items gather into patches of about 7 m (`clumping`), so the ground does not read as an even sprinkle.
+- Everything is vertex-coloured and untextured. Each tile has at most two parts, stones and litter, and both stream through `renderer.replaceParts`.
+
+Clutter shows best on paths, clearings, riverbanks and forest floor. Under a dense meadow most of it hides in the grass. To fill a path, pass the inverse of the grass mask as the clutter `mask`.
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `area` | required | `{ minX, maxX, minZ, maxZ }` in metres. |
+| `preset` | `'meadow'` | `meadow`, `forest`, `riverbed` or `scree`. Every other option overrides the preset. |
+| `terrainHeight` | `() => 0` | Ground height at `(x, z)`. Pass `terrain.heightAt`. |
+| `mask` | none | Coverage at `(x, z)` from 0 to 1. |
+| `pebbles`, `rocks`, `twigs`, `leaves` | from preset | Items per square metre. |
+| `pebbleSize`, `rockSize` | `[0.012, 0.05]`, `[0.08, 0.38]` | Radius range in metres. Most stones fall near the small end. |
+| `moss` | from preset | Moss on rock tops, 0 to 1. |
+| `clumping` | `0.6` | How strongly items gather into patches, 0 to 1. |
+| `stoneColor`, `mossColor`, `soilColor`, `twigColor` | earth tones | Linear RGB. |
+| `leafColors` | four dry browns | A list of linear RGB colours. Each leaf picks one. |
+| `castShadow` | `true` | Stones cast shadows. Twigs and leaves never do. |
+| `tileSize`, `levels`, `cullDistance` | `4`, `CLUTTER_LEVELS`, last level | Tiling and level of detail. |
+| `eye`, `seed` | area centre, `1` | Initial camera position and random seed. |
+
+`createClutter` returns `{ parts, update(eye), stats(), materials, settings }`.
+
+## Level of detail
+
+| Level | Distance | Kept | Stone mesh |
+| --- | --- | --- | --- |
+| 0 | up to 12 m | everything | rocks 12 × 7, pebbles 6 × 4 |
+| 1 | 12 to 30 m | 20 % | rocks 6 × 4, pebbles an octahedron |
+| 2 | 30 to 70 m | rocks only | rocks 6 × 4 |
+
+Grass and clutter share the tile system in `src/tile-field.js`, with the same 10 % hysteresis.
+
+## Measured
+
+On an 80 × 100 m area, eye 1.3 m above the ground, built in Node:
+
+| Preset | Triangles | Geometry | Build |
+| --- | --- | --- | --- |
+| `meadow` | 28 k | about 1 MB | about 0.1 s |
+| `forest` | 84 k | about 4.5 MB | about 0.3 s |
+| `riverbed` | 445 k | about 16.5 MB | about 1 s |
+| `scree` | 604 k | about 22 MB | about 1 s |
+
+`riverbed` and `scree` are dense by design. Lower `pebbles` or `cullDistance` for phones.
+
+## Limits
+
+- Stones are untextured. Up close they read as smooth, mottled stones, not as scanned rock.
+- Clutter does not collide with grass blades or with each other, so two stones can overlap.
+- Leaves lie flat and do not move in the wind.
diff --git a/docs/guide.md b/docs/guide.md
index cd78d61c..7cf3e41a 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -221,6 +221,8 @@ Cards (`leaves: 'cards'`, the default) are single-sided, alpha-masked, double-si
Tint the ground under the grass with `grass.groundColor`. The [Grass contract](/grass.md) lists options, levels, measured budgets and limits.
+`67js/addons/clutter` is in the current source and not yet published. It scatters pebbles, rocks, twigs and fallen leaves over terrain in the same streamed tiles. Pick a `preset` (`meadow`, `forest`, `riverbed`, `scree`), pass `terrainHeight`, and add `clutter.parts` next to the grass. The [Clutter contract](/clutter.md) lists options and budgets.
+
## Terrain and ground textures
`67js/addons/terrain` and `67js/addons/texture-set` are available from version `0.10.0`. They build a chunked, seeded heightfield with distance level of detail and a four-layer ground material (slope, height and mask rules, height-based edge blending, triplanar cliffs, anti-tiling) from CC0 scans.
diff --git a/package.json b/package.json
index 1269e8c5..571cfeb9 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,8 @@
"docs/agent-review.md",
"docs/vegetation.md",
"docs/terrain.md",
- "docs/grass.md"
+ "docs/grass.md",
+ "docs/clutter.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -87,6 +88,7 @@
"./addons/vegetation": "./build/vegetation.js",
"./addons/terrain": "./build/terrain.js",
"./addons/grass": "./build/grass.js",
+ "./addons/clutter": "./build/clutter.js",
"./addons/texture-set": "./build/texture-set.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index d5c4935d..07597403 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -42,7 +42,7 @@ const sourceDocuments = [
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md',
'retarget.md',
'vehicle.md',
- 'vegetation.md', 'terrain.md', 'grass.md',
+ 'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index e78e6e14..56bb7d28 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -14,7 +14,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- An object studio uses `src/model.js` and `src/main.js`.
- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`. Real trees, bushes, grass and forest scattering use optional `src/vegetation.js` and `docs/vegetation.md` (`leaves: 'mesh'` needs no alpha support).
-- A grass field, meadow, lawn or savanna over terrain uses optional `src/grass.js` and the checkout's `docs/grass.md`: clumped curved blades, tile level of detail, `mask` for paths. Darken every ground layer under the grass toward `grass.groundColor` (a bright floor between blades looks fake); prefer it over scattered `grass` clumps for anything wider than a few metres.
+- A grass field, meadow, lawn or savanna over terrain uses optional `src/grass.js` and the checkout's `docs/grass.md`: clumped curved blades, tile level of detail, `mask` for paths. Darken every ground layer under the grass toward `grass.groundColor` (a bright floor between blades looks fake); prefer it over scattered `grass` clumps for anything wider than a few metres. Pebbles, rocks, twigs and fallen leaves on paths, riverbanks or forest floor use optional `src/clutter.js` and the checkout's `docs/clutter.md` (`riverbed`, `forest`, `scree`, `meadow` presets).
- A deterministic film uses `src/film.js` and `src/film-player.js`.
- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.
- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.
diff --git a/src/clutter.js b/src/clutter.js
new file mode 100644
index 00000000..e9888ec9
--- /dev/null
+++ b/src/clutter.js
@@ -0,0 +1,346 @@
+// Ground clutter: pebbles, rocks, twigs and fallen leaves scattered over terrain in streamable tiles.
+// Stones are noise-displaced spheres cut by a few random planes, so rocks get flat chipped faces while pebbles stay
+// round. They sink into the ground, darken underneath and near the soil line, and rocks gather moss on top.
+// Everything is vertex-coloured and untextured, so tiles stream with `renderer.replaceParts`.
+
+import {
+ FULL_TURN, addTube, clamp, createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, valueNoise,
+} from './vegetation-geometry.js';
+import { createTileField, hashTile, tileMatrix } from './tile-field.js';
+
+// Rocks draw their keep key below this value and everything else above it, so the farthest level keeps only rocks.
+const ROCK_KEY_LIMIT = 0.04;
+
+export const CLUTTER_LEVELS = Object.freeze([
+ Object.freeze({ distance: 12, keep: 1, detail: 1 }),
+ Object.freeze({ distance: 30, keep: 0.2, detail: 0 }),
+ Object.freeze({ distance: 70, keep: ROCK_KEY_LIMIT, detail: 0 }),
+]);
+
+/** Items per square metre near the camera. */
+export const CLUTTER_PRESETS = Object.freeze({
+ meadow: Object.freeze({ pebbles: 0.8, rocks: 0.03, twigs: 0.08, leaves: 0.3, moss: 0.4 }),
+ forest: Object.freeze({ pebbles: 0.5, rocks: 0.06, twigs: 1.2, leaves: 16, moss: 0.8 }),
+ riverbed: Object.freeze({ pebbles: 14, rocks: 0.6, twigs: 0.15, leaves: 0.1, moss: 0.15 }),
+ scree: Object.freeze({ pebbles: 12, rocks: 1.4, twigs: 0, leaves: 0, moss: 0.05 }),
+});
+
+const DEFAULTS = Object.freeze({
+ pebbleSize: [0.012, 0.05],
+ rockSize: [0.08, 0.38],
+ stoneColor: [0.13, 0.125, 0.11],
+ mossColor: [0.06, 0.09, 0.025],
+ soilColor: [0.07, 0.055, 0.04],
+ twigColor: [0.11, 0.075, 0.045],
+ leafColors: [[0.2, 0.1, 0.035], [0.32, 0.19, 0.05], [0.1, 0.065, 0.03], [0.14, 0.12, 0.04]],
+ clumping: 0.6,
+});
+
+const KINDS = Object.freeze(['pebbles', 'rocks', 'twigs', 'leaves']);
+const MAXIMUM_ITEMS_PER_KIND = 20000;
+// Sphere resolution per detail level (index 0 far, 1 near). Pebbles are small and many, so they get coarser spheres,
+// down to an octahedron far away, where one covers a pixel or two.
+const ROCK_DETAIL = Object.freeze([Object.freeze({ segments: 6, rings: 4 }), Object.freeze({ segments: 12, rings: 7 })]);
+const PEBBLE_DETAIL = Object.freeze([Object.freeze({ segments: 4, rings: 2 }), Object.freeze({ segments: 6, rings: 4 })]);
+
+function smoothstep(edgeLow, edgeHigh, value) {
+ const amount = clamp((value - edgeLow) / (edgeHigh - edgeLow), 0, 1);
+ return amount * amount * (3 - 2 * amount);
+}
+
+function groundNormal(terrainHeight, x, z) {
+ const step = 0.25;
+ const slopeX = terrainHeight(x + step, z) - terrainHeight(x - step, z);
+ const slopeZ = terrainHeight(x, z + step) - terrainHeight(x, z - step);
+ return normalized([-slopeX, 2 * step, -slopeZ]);
+}
+
+/**
+ * Right-handed frame on the ground: `up` is the terrain normal and `forward` follows `yaw` across it. Local x, y
+ * and z map to forward, up and side; a mirrored frame would turn every stone inside out.
+ */
+function groundFrame(up, yaw) {
+ const heading = [Math.cos(yaw), 0, Math.sin(yaw)];
+ const side = normalized(crossProduct(heading, up));
+ const forward = normalized(crossProduct(up, side));
+ return { up, forward, side };
+}
+
+function placeInFrame(frame, origin, local) {
+ return [0, 1, 2].map(axis => origin[axis] + frame.forward[axis] * local[0] + frame.up[axis] * local[1] + frame.side[axis] * local[2]);
+}
+
+/** Field-scale clumping: items gather into patches of about 7 m instead of spreading evenly. */
+function clumpWeight(x, z, settings, salt) {
+ const patch = smoothstep(0.3, 0.75, valueNoise(x * 0.15, z * 0.15, settings.seed + salt));
+ return lerp(1, patch * 2, settings.clumping);
+}
+
+function planTileItems(tile, settings) {
+ const items = [];
+ KINDS.forEach((kind, kindIndex) => {
+ const density = settings[kind];
+ if (!(density > 0)) return;
+ const random = createRandom(hashTile(settings.seed + kindIndex * 7907, tile.column, tile.row));
+ // Twice the candidates, each accepted with half its clump weight, so the mean density matches `density`.
+ const candidates = Math.min(MAXIMUM_ITEMS_PER_KIND, Math.round(density * settings.tileSize * settings.tileSize * 2));
+ for (let index = 0; index < candidates; index++) {
+ const x = tile.tileX + random() * settings.tileSize;
+ const z = tile.tileZ + random() * settings.tileSize;
+ const acceptRoll = random();
+ const keepRoll = random();
+ const shapeRolls = [random(), random(), random(), random(), random(), random()];
+ const coverage = settings.mask ? clamp(settings.mask(x, z), 0, 1) : 1;
+ if (acceptRoll * 2 >= clumpWeight(x, z, settings, 131 + kindIndex * 17) * coverage) continue;
+ const keepKey = kind === 'rocks' ? keepRoll * ROCK_KEY_LIMIT : lerp(ROCK_KEY_LIMIT, 1, keepRoll);
+ items.push({ kind, x, z, keepKey, shapeRolls });
+ }
+ });
+ return items;
+}
+
+/** Radius multiplier of a stone along `direction`: smooth noise, then flat chipped faces from cutting planes. */
+function stoneRadius(direction, stone) {
+ const [x, y, z] = direction;
+ const phases = stone.phases;
+ let radius = 1 + stone.roughness * (
+ Math.sin(x * 2.6 + phases[0]) * Math.sin(y * 2.6 + phases[1])
+ + 0.5 * Math.sin(z * 4.4 + phases[2]) * Math.cos(x * 3.4 + phases[3])
+ );
+ for (const plane of stone.planes) {
+ const facing = x * plane.normal[0] + y * plane.normal[1] + z * plane.normal[2];
+ if (facing > 0.05) radius = Math.min(radius, plane.distance / facing);
+ }
+ return radius;
+}
+
+function stoneColor(normal, localPoint, heightAboveGround, stone, vertexIndex, settings) {
+ const underside = lerp(0.45, 1, smoothstep(-0.6, 0.7, normal[1]));
+ const speckle = lerp(0.82, 1.12, (hashTile(stone.colorSeed, vertexIndex, 3) & 1023) / 1023);
+ // Blotches and veins across the surface, in the stone's own space so they stay put as it turns.
+ const blotch = valueNoise(localPoint[0] * stone.grain + localPoint[1] * 0.7 * stone.grain, localPoint[2] * stone.grain, stone.colorSeed);
+ const stain = lerp(0.6, 1.25, blotch);
+ let color = stone.base.map(channel => channel * underside * speckle * stain);
+ const moss = stone.moss * smoothstep(0.35, 0.85, normal[1]) * smoothstep(0.3, 0.6, valueNoise(normal[0] * 3 + stone.phases[0], normal[2] * 3, stone.colorSeed));
+ color = lerpVectors(color, settings.mossColor, moss);
+ // Soil clings to the stone where it meets the ground.
+ const soil = 1 - smoothstep(0, stone.height * 0.35, heightAboveGround);
+ return lerpVectors(color, settings.soilColor, soil * 0.7);
+}
+
+function addStone(builder, item, tileOrigin, settings, detail) {
+ const isRock = item.kind === 'rocks';
+ const { segments, rings } = (isRock ? ROCK_DETAIL : PEBBLE_DETAIL)[detail];
+ const rolls = item.shapeRolls;
+ const sizeRange = isRock ? settings.rockSize : settings.pebbleSize;
+ // Most stones are small: a power curve leaves a few large ones.
+ const radius = lerp(sizeRange[0], sizeRange[1], rolls[0] ** 2.5);
+ const random = createRandom(hashTile(settings.seed, Math.floor(item.x * 977), Math.floor(item.z * 977)));
+ const stone = {
+ roughness: isRock ? 0.16 : 0.08,
+ phases: [random() * FULL_TURN, random() * FULL_TURN, random() * FULL_TURN, random() * FULL_TURN],
+ planes: [],
+ moss: isRock ? settings.moss : settings.moss * 0.2,
+ colorSeed: hashTile(settings.seed + 17, Math.floor(item.x * 977), Math.floor(item.z * 977)),
+ height: radius * lerp(0.45, 0.75, rolls[1]),
+ };
+ if (isRock) {
+ for (let plane = 0; plane < 4; plane++) {
+ const theta = random() * FULL_TURN;
+ const lift = random() * 1.6 - 0.4;
+ stone.planes.push({ normal: normalized([Math.cos(theta), lift, Math.sin(theta)]), distance: lerp(0.68, 0.9, random()) });
+ }
+ }
+ // Each stone gets its own tone and hue, from blue-grey to rust, as a mixed riverbed has.
+ const tone = lerp(0.55, 1.45, rolls[2]);
+ const warmth = rolls[3] * 2 - 1;
+ stone.base = settings.stoneColor.map((channel, index) => channel * tone * [1 + warmth * 0.25, 1 + warmth * 0.04, 1 - warmth * 0.3][index]);
+ stone.grain = lerp(2.5, 5, random());
+ const scale = [radius * lerp(0.75, 1.1, rolls[4]), stone.height, radius * lerp(0.7, 1, rolls[5])];
+ const ground = settings.terrainHeight(item.x, item.z);
+ const frame = groundFrame(groundNormal(settings.terrainHeight, item.x, item.z), rolls[5] * FULL_TURN);
+ // Sink a third to a half of the stone so it sits in the ground instead of resting on it.
+ const sink = lerp(0.3, 0.5, rolls[1]);
+ const center = [item.x - tileOrigin[0], ground + stone.height * (1 - 2 * sink), item.z - tileOrigin[1]];
+
+ const directions = [[0, 1, 0]];
+ for (let ring = 1; ring < rings; ring++) {
+ const polar = Math.PI * ring / rings;
+ for (let segment = 0; segment < segments; segment++) {
+ const azimuth = FULL_TURN * segment / segments;
+ directions.push([Math.sin(polar) * Math.cos(azimuth), Math.cos(polar), Math.sin(polar) * Math.sin(azimuth)]);
+ }
+ }
+ directions.push([0, -1, 0]);
+ const localPoints = directions.map(direction => {
+ const distance = stoneRadius(direction, stone);
+ return direction.map((component, axis) => component * distance * scale[axis]);
+ });
+ const triangles = [];
+ const ringStart = ring => 1 + (ring - 1) * segments;
+ const bottom = directions.length - 1;
+ for (let segment = 0; segment < segments; segment++) {
+ const next = (segment + 1) % segments;
+ triangles.push([0, ringStart(1) + next, ringStart(1) + segment]);
+ for (let ring = 1; ring < rings - 1; ring++) {
+ const upper = ringStart(ring);
+ const lower = ringStart(ring + 1);
+ triangles.push([upper + segment, upper + next, lower + segment]);
+ triangles.push([upper + next, lower + next, lower + segment]);
+ }
+ const last = ringStart(rings - 1);
+ triangles.push([last + segment, last + next, bottom]);
+ }
+ // Smooth normals from the faces around each vertex; the sphere has no seam, so none show.
+ const localNormals = localPoints.map(() => [0, 0, 0]);
+ for (const [first, second, third] of triangles) {
+ const edgeOne = [0, 1, 2].map(axis => localPoints[second][axis] - localPoints[first][axis]);
+ const edgeTwo = [0, 1, 2].map(axis => localPoints[third][axis] - localPoints[first][axis]);
+ const face = crossProduct(edgeOne, edgeTwo);
+ for (const vertex of [first, second, third]) for (let axis = 0; axis < 3; axis++) localNormals[vertex][axis] += face[axis];
+ }
+ const firstVertex = builder.vertexCount;
+ localPoints.forEach((point, index) => {
+ const position = placeInFrame(frame, center, point);
+ const normal = normalized(placeInFrame(frame, [0, 0, 0], normalized(localNormals[index])));
+ const color = stoneColor(normal, point.map((component, axis) => component / scale[axis]), position[1] - ground, stone, index, settings);
+ builder.addVertex(position, normal, 0, 0, color);
+ });
+ for (const [first, second, third] of triangles) builder.addTriangle(firstVertex + first, firstVertex + second, firstVertex + third);
+}
+
+function addTwig(builder, item, tileOrigin, settings, detail) {
+ const rolls = item.shapeRolls;
+ const length = lerp(0.1, 0.45, rolls[0] ** 1.5);
+ const thickness = lerp(0.003, 0.011, rolls[1]) * (0.6 + length);
+ const yaw = rolls[2] * FULL_TURN;
+ const bend = (rolls[3] - 0.5) * 0.6;
+ const pointCount = detail ? 4 : 2;
+ const points = [];
+ const radii = [];
+ for (let index = 0; index < pointCount; index++) {
+ const progress = index / (pointCount - 1);
+ const angle = yaw + bend * progress;
+ const along = (progress - 0.5) * length;
+ const x = item.x + Math.cos(angle) * along;
+ const z = item.z + Math.sin(angle) * along;
+ const radius = thickness * lerp(1, 0.45, progress);
+ points.push([x - tileOrigin[0], settings.terrainHeight(x, z) + radius * 0.7, z - tileOrigin[1]]);
+ radii.push(radius);
+ }
+ const color = settings.twigColor.map(channel => channel * lerp(0.7, 1.3, rolls[4]));
+ addTube(builder, points, radii, detail ? 5 : 3, 1, color);
+}
+
+function addLeaf(builder, item, tileOrigin, settings, detail) {
+ const rolls = item.shapeRolls;
+ const length = lerp(0.04, 0.1, rolls[0]);
+ const width = length * lerp(0.4, 0.65, rolls[1]);
+ const curl = width * lerp(0.05, 0.45, rolls[2]);
+ const palette = settings.leafColors;
+ const base = palette[Math.floor(rolls[3] * palette.length) % palette.length];
+ const color = base.map(channel => channel * lerp(0.75, 1.25, rolls[4]));
+ const ground = settings.terrainHeight(item.x, item.z);
+ const frame = groundFrame(groundNormal(settings.terrainHeight, item.x, item.z), rolls[5] * FULL_TURN);
+ const origin = [item.x - tileOrigin[0], ground + 0.004, item.z - tileOrigin[1]];
+ const rows = detail ? 3 : 2;
+ const grid = [];
+ for (let row = 0; row < rows; row++) {
+ const progress = row / (rows - 1);
+ const halfWidth = width * 0.5 * Math.sin(Math.PI * lerp(0.08, 1, progress)) ** 0.8;
+ const rowVertices = [];
+ for (let across = -1; across <= 1; across++) {
+ // Edges curl up and the leaf lies cupped; the midrib is a little darker.
+ const lift = curl * across * across;
+ const local = [(progress - 0.5) * length, lift, across * halfWidth];
+ const normal = normalized(placeInFrame(frame, [0, 0, 0], [0, 1, -across * curl / Math.max(halfWidth, 1e-4)]));
+ const shade = across === 0 ? 0.82 : 1;
+ rowVertices.push(builder.addVertex(placeInFrame(frame, origin, local), normal, (across + 1) / 2, progress, color.map(channel => channel * shade)));
+ }
+ grid.push(rowVertices);
+ }
+ for (let row = 0; row < rows - 1; row++) {
+ for (let column = 0; column < 2; column++) {
+ // Counter-clockwise from above, so the upper face is the front and keeps its sky-facing normal.
+ builder.addTriangle(grid[row][column], grid[row][column + 1], grid[row + 1][column]);
+ builder.addTriangle(grid[row][column + 1], grid[row + 1][column + 1], grid[row + 1][column]);
+ }
+ }
+}
+
+function requireRange(value, name) {
+ if (!Array.isArray(value) || value.length !== 2 || !(value[0] > 0) || !(value[1] >= value[0])) throw new RangeError(`Clutter ${name} must be [minimum, maximum] in metres.`);
+}
+
+function requireColor(value, name) {
+ if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) throw new TypeError(`Clutter ${name} must be three linear RGB numbers.`);
+}
+
+function resolveSettings(options) {
+ const preset = CLUTTER_PRESETS[options.preset ?? 'meadow'];
+ if (!preset) throw new RangeError(`Unknown clutter preset: ${options.preset}. Use ${Object.keys(CLUTTER_PRESETS).join(', ')}.`);
+ const defined = Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
+ const settings = { tileSize: 4, seed: 1, terrainHeight: () => 0, castShadow: true, ...DEFAULTS, ...preset, ...defined };
+ const { area } = settings;
+ if (!area || ![area.minX, area.maxX, area.minZ, area.maxZ].every(Number.isFinite) || area.maxX <= area.minX || area.maxZ <= area.minZ) {
+ throw new TypeError('Clutter area needs finite minX < maxX and minZ < maxZ.');
+ }
+ for (const kind of KINDS) {
+ if (!(settings[kind] >= 0)) throw new RangeError(`Clutter ${kind} must be a non-negative count per square metre.`);
+ }
+ for (const name of ['moss', 'clumping']) {
+ if (!(settings[name] >= 0 && settings[name] <= 1)) throw new RangeError(`Clutter ${name} must be between 0 and 1.`);
+ }
+ if (!(settings.tileSize > 0)) throw new RangeError('Clutter tileSize must be positive.');
+ requireRange(settings.pebbleSize, 'pebbleSize');
+ requireRange(settings.rockSize, 'rockSize');
+ for (const name of ['stoneColor', 'mossColor', 'soilColor', 'twigColor']) requireColor(settings[name], name);
+ if (!Array.isArray(settings.leafColors) || settings.leafColors.length === 0) throw new TypeError('Clutter leafColors must be a non-empty list of colours.');
+ settings.leafColors.forEach((color, index) => requireColor(color, `leafColors[${index}]`));
+ if (typeof settings.terrainHeight !== 'function') throw new TypeError('Clutter terrainHeight must be a function (x, z) => y.');
+ if (settings.mask !== undefined && typeof settings.mask !== 'function') throw new TypeError('Clutter mask must be a function (x, z) => 0..1.');
+ settings.levels = settings.levels ?? CLUTTER_LEVELS;
+ settings.cullDistance = settings.cullDistance ?? settings.levels.at(-1).distance;
+ return settings;
+}
+
+/**
+ * Scatters pebbles, rocks, twigs and fallen leaves over `area` ({ minX, maxX, minZ, maxZ }).
+ * Options: `preset` ('meadow', 'forest', 'riverbed', 'scree'), `terrainHeight(x, z)`, `mask(x, z)` (0..1),
+ * counts per square metre `pebbles`, `rocks`, `twigs`, `leaves`, `pebbleSize` and `rockSize` radius ranges,
+ * `moss` (0..1), `clumping` (0..1), linear `stoneColor`, `mossColor`, `soilColor`, `twigColor` and `leafColors`,
+ * `castShadow` (stones only), `tileSize`, `levels`, `cullDistance`, `seed`, `eye`.
+ * Returns `{ parts, update(eye), stats(), materials, settings }`. When `update` returns true, call
+ * `renderer.replaceParts([...otherParts, ...clutter.parts])`.
+ */
+export function createClutter(options = {}) {
+ const settings = resolveSettings(options);
+ const materials = {
+ stone: { color: [1, 1, 1], roughness: 0.88, metallic: 0, emission: 0 },
+ litter: { color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0, doubleSided: true },
+ };
+
+ function buildParts(tile, levelIndex) {
+ const level = settings.levels[levelIndex];
+ tile.cache.items ??= planTileItems(tile, settings);
+ const tileOrigin = [tile.tileX, tile.tileZ];
+ const stones = createMeshBuilder({ withColors: true });
+ const litter = createMeshBuilder({ withColors: true });
+ for (const item of tile.cache.items) {
+ if (item.keepKey >= level.keep) continue;
+ if (item.kind === 'pebbles' || item.kind === 'rocks') addStone(stones, item, tileOrigin, settings, level.detail);
+ else if (item.kind === 'twigs') addTwig(litter, item, tileOrigin, settings, level.detail);
+ else addLeaf(litter, item, tileOrigin, settings, level.detail);
+ }
+ const parts = [];
+ const matrix = tileMatrix(tile);
+ if (stones.vertexCount > 0) parts.push({ name: `Clutter stones ${tile.column},${tile.row}`, geometry: stones.build(), matrix, material: materials.stone, castShadow: settings.castShadow });
+ if (litter.vertexCount > 0) parts.push({ name: `Clutter litter ${tile.column},${tile.row}`, geometry: litter.build(), matrix, material: materials.litter, castShadow: false });
+ return parts;
+ }
+
+ const field = createTileField({ ...settings, buildParts });
+ field.update(settings.eye ?? [(settings.area.minX + settings.area.maxX) / 2, 2, (settings.area.minZ + settings.area.maxZ) / 2]);
+ return { get parts() { return field.parts; }, update: field.update, stats: field.stats, materials, settings };
+}
+
diff --git a/src/grass.js b/src/grass.js
index ae6fb4cb..63885294 100644
--- a/src/grass.js
+++ b/src/grass.js
@@ -6,6 +6,7 @@
import {
FULL_TURN, WORLD_UP, clamp, createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, valueNoise,
} from './vegetation-geometry.js';
+import { createTileField, hashTile, tileMatrix } from './tile-field.js';
export const GRASS_LEVELS = Object.freeze([
Object.freeze({ distance: 10, keep: 1, segments: 4, widthScale: 1 }),
@@ -46,15 +47,9 @@ function fieldPatch(x, z, settings) {
};
}
-function tileSeed(seed, column, row) {
- let mixed = Math.imul(column + 7919, 374761393) ^ Math.imul(row - 104729, 668265263) ^ Math.imul(seed, 2246822519);
- mixed = Math.imul(mixed ^ mixed >>> 13, 1274126177);
- return (mixed ^ mixed >>> 16) >>> 0;
-}
-
// Independent value in [0, 1) per clump cell; `salt` picks which property it is.
function cellHash(column, row, seed, salt) {
- return tileSeed(seed + salt * 1013, column, row) / 4294967296;
+ return hashTile(seed + salt * 1013, column, row) / 4294967296;
}
/** Nearest jittered clump centre around (x, z): cellular noise, as the clumping in the Ghost of Tsushima talk. */
@@ -89,7 +84,7 @@ function smoothstep(edgeLow, edgeHigh, value) {
/** Every blade of one tile at full density, in a stable order; each level keeps the blades whose `keepKey` is below its share. */
function planTileBlades(column, row, settings, keepLimit) {
const { tileSize, origin, seed, terrainHeight, mask, density } = settings;
- const random = createRandom(tileSeed(seed, column, row));
+ const random = createRandom(hashTile(seed, column, row));
const count = Math.min(MAXIMUM_BLADES_PER_TILE, Math.round(density * tileSize * tileSize));
const blades = [];
for (let index = 0; index < count; index++) {
@@ -247,83 +242,24 @@ function resolveSettings(options) {
export function createGrass(options = {}) {
const settings = resolveSettings({ tileSize: 4, seed: 1, terrainHeight: () => 0, castShadow: false, ...options });
const material = { tag: 'grass', color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0, doubleSided: true };
- const columns = Math.ceil((settings.area.maxX - settings.area.minX) / settings.tileSize);
- const rows = Math.ceil((settings.area.maxZ - settings.area.minZ) / settings.tileSize);
- const tiles = [];
- for (let row = 0; row < rows; row++) {
- for (let column = 0; column < columns; column++) {
- const tileX = settings.origin[0] + column * settings.tileSize;
- const tileZ = settings.origin[1] + row * settings.tileSize;
- const centerX = tileX + settings.tileSize / 2;
- const centerZ = tileZ + settings.tileSize / 2;
- tiles.push({ column, row, tileX, tileZ, centerX, centerZ, centerY: settings.terrainHeight(centerX, centerZ), level: -1, blades: null, part: null });
- }
- }
- function buildTileGeometry(tile, levelIndex) {
+ function buildParts(tile, levelIndex) {
const level = settings.levels[levelIndex];
- if (!tile.blades || tile.plannedKeep < level.keep) {
- tile.blades = planTileBlades(tile.column, tile.row, settings, level.keep);
- tile.plannedKeep = level.keep;
+ if (!tile.cache.blades || tile.cache.plannedKeep < level.keep) {
+ tile.cache.blades = planTileBlades(tile.column, tile.row, settings, level.keep);
+ tile.cache.plannedKeep = level.keep;
}
const builder = createMeshBuilder({ withColors: true });
- for (const blade of tile.blades) {
+ for (const blade of tile.cache.blades) {
if (blade.keepKey < level.keep) addBlade(builder, blade, tile.tileX, tile.tileZ, level, settings);
}
- return builder.vertexCount > 0 ? builder.build() : null;
- }
-
- function levelFor(tile, eye) {
- const distance = Math.max(0, Math.hypot(eye[0] - tile.centerX, eye[1] - tile.centerY, eye[2] - tile.centerZ) - settings.tileSize * 0.5);
- if (distance > settings.cullDistance) return -1;
- let target = settings.levels.findIndex(level => distance <= level.distance);
- if (target === -1) target = settings.levels.length - 1;
- // Hysteresis: a tile only moves to a coarser level once it is clearly past the boundary, so tiles on an edge do not flicker.
- if (tile.level >= 0 && target > tile.level && distance <= settings.levels[tile.level].distance * 1.1) return tile.level;
- return target;
- }
-
- let visibleParts = [];
- function update(eye) {
- if (!eye || eye.length < 3 || ![eye[0], eye[1], eye[2]].every(Number.isFinite)) throw new TypeError('update needs an eye position [x, y, z].');
- let changed = false;
- for (const tile of tiles) {
- const target = levelFor(tile, eye);
- if (target === tile.level) continue;
- changed = true;
- tile.level = target;
- if (target === -1) {
- tile.part = null;
- continue;
- }
- const geometry = buildTileGeometry(tile, target);
- tile.part = geometry ? {
- name: `Grass tile ${tile.column},${tile.row}`,
- geometry,
- matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tile.tileX, 0, tile.tileZ, 1]),
- material,
- castShadow: settings.castShadow,
- } : null;
- }
- if (changed) visibleParts = tiles.filter(tile => tile.part).map(tile => tile.part);
- return changed;
- }
-
- function stats() {
- const levelCounts = settings.levels.map(() => 0);
- let triangles = 0;
- let vertices = 0;
- for (const tile of tiles) {
- if (!tile.part) continue;
- levelCounts[tile.level] += 1;
- triangles += tile.part.geometry.indices.length / 3;
- vertices += tile.part.geometry.positions.length / 3;
- }
- return { tiles: tiles.length, visibleTiles: visibleParts.length, levelCounts, triangles, vertices, geometryBytes: vertices * 11 * 4 + triangles * 12 };
+ if (builder.vertexCount === 0) return [];
+ return [{ name: `Grass tile ${tile.column},${tile.row}`, geometry: builder.build(), matrix: tileMatrix(tile), material, castShadow: settings.castShadow }];
}
- update(settings.eye ?? [(settings.area.minX + settings.area.maxX) / 2, 2, (settings.area.minZ + settings.area.maxZ) / 2]);
+ const field = createTileField({ ...settings, buildParts });
+ field.update(settings.eye ?? [(settings.area.minX + settings.area.maxX) / 2, 2, (settings.area.minZ + settings.area.maxZ) / 2]);
// Colour for the ground under the blades: gaps then read as shaded grass instead of bare soil.
const groundColor = lerpVectors(settings.base, settings.tip, 0.3);
- return { get parts() { return visibleParts; }, update, material, stats, settings, groundColor };
+ return { get parts() { return field.parts; }, update: field.update, material, stats: field.stats, settings, groundColor };
}
diff --git a/src/tile-field.js b/src/tile-field.js
new file mode 100644
index 00000000..806c2aee
--- /dev/null
+++ b/src/tile-field.js
@@ -0,0 +1,81 @@
+// Square tiles over an area that pick a level of detail from the camera distance and rebuild only when it changes.
+// Grass and ground clutter share it: each supplies `buildParts(tile, levelIndex)` and gets streamable parts back.
+
+const HYSTERESIS = 1.1;
+
+/** Stable 32-bit hash of a tile (or any integer cell) and a seed. */
+export function hashTile(seed, column, row) {
+ let mixed = Math.imul(column + 7919, 374761393) ^ Math.imul(row - 104729, 668265263) ^ Math.imul(seed, 2246822519);
+ mixed = Math.imul(mixed ^ mixed >>> 13, 1274126177);
+ return (mixed ^ mixed >>> 16) >>> 0;
+}
+
+/** Translation matrix that places tile-local geometry at the tile's corner. */
+export function tileMatrix(tile) {
+ return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tile.tileX, 0, tile.tileZ, 1]);
+}
+
+/**
+ * `levels` is a list of `{ distance }` from near to far; tiles past `cullDistance` are dropped.
+ * `buildParts(tile, levelIndex)` returns the tile's parts at that level (an empty array is fine).
+ * A tile keeps `tile.cache` between rebuilds for whatever the caller wants to plan once.
+ */
+export function createTileField({ area, tileSize, levels, cullDistance, terrainHeight, buildParts }) {
+ const columns = Math.ceil((area.maxX - area.minX) / tileSize);
+ const rows = Math.ceil((area.maxZ - area.minZ) / tileSize);
+ const tiles = [];
+ for (let row = 0; row < rows; row++) {
+ for (let column = 0; column < columns; column++) {
+ const tileX = area.minX + column * tileSize;
+ const tileZ = area.minZ + row * tileSize;
+ const centerX = tileX + tileSize / 2;
+ const centerZ = tileZ + tileSize / 2;
+ tiles.push({ column, row, tileX, tileZ, centerX, centerZ, centerY: terrainHeight(centerX, centerZ), level: -1, cache: {}, parts: [] });
+ }
+ }
+
+ function levelFor(tile, eye) {
+ const distance = Math.max(0, Math.hypot(eye[0] - tile.centerX, eye[1] - tile.centerY, eye[2] - tile.centerZ) - tileSize * 0.5);
+ if (distance > cullDistance) return -1;
+ let target = levels.findIndex(level => distance <= level.distance);
+ if (target === -1) target = levels.length - 1;
+ // Hysteresis: a tile only moves to a coarser level once it is clearly past the boundary, so tiles on an edge do not flicker.
+ if (tile.level >= 0 && target > tile.level && distance <= levels[tile.level].distance * HYSTERESIS) return tile.level;
+ return target;
+ }
+
+ let visibleParts = [];
+ function update(eye) {
+ if (!eye || eye.length < 3 || ![eye[0], eye[1], eye[2]].every(Number.isFinite)) throw new TypeError('update needs an eye position [x, y, z].');
+ let changed = false;
+ for (const tile of tiles) {
+ const target = levelFor(tile, eye);
+ if (target === tile.level) continue;
+ changed = true;
+ tile.level = target;
+ tile.parts = target === -1 ? [] : buildParts(tile, target);
+ }
+ if (changed) visibleParts = tiles.flatMap(tile => tile.parts);
+ return changed;
+ }
+
+ function stats() {
+ const levelCounts = levels.map(() => 0);
+ let visibleTiles = 0;
+ let triangles = 0;
+ let vertices = 0;
+ for (const tile of tiles) {
+ if (tile.parts.length === 0) continue;
+ visibleTiles += 1;
+ levelCounts[tile.level] += 1;
+ for (const part of tile.parts) {
+ triangles += part.geometry.indices.length / 3;
+ vertices += part.geometry.positions.length / 3;
+ }
+ }
+ // Position, normal, uv and colour floats per vertex, three 32-bit indices per triangle.
+ return { tiles: tiles.length, visibleTiles, levelCounts, triangles, vertices, geometryBytes: vertices * 11 * 4 + triangles * 12 };
+ }
+
+ return { get parts() { return visibleParts; }, update, stats };
+}
diff --git a/tests/clutter.test.js b/tests/clutter.test.js
new file mode 100644
index 00000000..ee49c979
--- /dev/null
+++ b/tests/clutter.test.js
@@ -0,0 +1,92 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { CLUTTER_LEVELS, CLUTTER_PRESETS, createClutter } from '../src/clutter.js';
+
+const smallArea = { minX: 0, maxX: 8, minZ: 0, maxZ: 8 };
+const near = { area: smallArea, eye: [4, 1, 4] };
+
+function triangleFacesAgreeWithNormals(geometry) {
+ const { positions, normals, indices } = geometry;
+ for (let index = 0; index < indices.length; index += 3) {
+ const corners = [indices[index], indices[index + 1], indices[index + 2]].map(vertex => [0, 1, 2].map(axis => positions[vertex * 3 + axis]));
+ const first = [0, 1, 2].map(axis => corners[1][axis] - corners[0][axis]);
+ const second = [0, 1, 2].map(axis => corners[2][axis] - corners[0][axis]);
+ const face = [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];
+ const normal = [0, 1, 2].map(axis => normals[indices[index] * 3 + axis]);
+ if (face[0] * normal[0] + face[1] * normal[1] + face[2] * normal[2] < 0) return false;
+ }
+ return true;
+}
+
+test('the same options and seed build identical clutter', () => {
+ const first = createClutter({ ...near, preset: 'riverbed', seed: 2 });
+ const second = createClutter({ ...near, preset: 'riverbed', seed: 2 });
+ assert.equal(first.parts.length, second.parts.length);
+ first.parts.forEach((part, index) => assert.deepEqual(part.geometry.positions, second.parts[index].geometry.positions));
+ const other = createClutter({ ...near, preset: 'riverbed', seed: 3 });
+ assert.notDeepEqual(first.parts[0].geometry.positions, other.parts[0].geometry.positions);
+});
+
+test('stones face outward and stand on the ground they sink into', () => {
+ const terrainHeight = (x, z) => 1 + x * 0.05 + Math.sin(z);
+ const clutter = createClutter({ ...near, preset: 'scree', twigs: 0, leaves: 0, terrainHeight });
+ const stones = clutter.parts.filter(part => part.name.startsWith('Clutter stones'));
+ assert.ok(stones.length > 0);
+ for (const part of stones) {
+ assert.ok(triangleFacesAgreeWithNormals(part.geometry), 'winding and normals agree, so stones are not inside out');
+ assert.equal(part.castShadow, true);
+ }
+ // Every stone reaches below the ground and above it.
+ const { positions } = stones[0].geometry;
+ let below = 0;
+ let above = 0;
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ const x = positions[vertex * 3] + stones[0].matrix[12];
+ const z = positions[vertex * 3 + 2] + stones[0].matrix[14];
+ if (positions[vertex * 3 + 1] < terrainHeight(x, z)) below += 1;
+ else above += 1;
+ }
+ assert.ok(below > 0 && above > below * 0.5);
+});
+
+test('fallen leaves face the sky and litter never casts shadows', () => {
+ const clutter = createClutter({ ...near, preset: 'forest', pebbles: 0, rocks: 0, twigs: 0 });
+ const litter = clutter.parts.filter(part => part.name.startsWith('Clutter litter'));
+ assert.ok(litter.length > 0);
+ for (const part of litter) {
+ assert.equal(part.castShadow, false);
+ assert.equal(part.material.doubleSided, true);
+ assert.ok(triangleFacesAgreeWithNormals(part.geometry));
+ }
+});
+
+test('the farthest level keeps only rocks, and far tiles are culled', () => {
+ const area = { minX: -80, maxX: 80, minZ: -80, maxZ: 80 };
+ const clutter = createClutter({ area, preset: 'meadow', pebbles: 2, rocks: 0, twigs: 1, leaves: 1, eye: [0, 1, 0] });
+ const stats = clutter.stats();
+ assert.equal(stats.levelCounts[2], 0, 'without rocks the last level is empty');
+ assert.ok(stats.levelCounts[0] > 0 && stats.levelCounts[1] > 0);
+ assert.ok(stats.visibleTiles < stats.tiles);
+ const rocky = createClutter({ area, preset: 'meadow', rocks: 0.5, eye: [0, 1, 0] }).stats();
+ assert.ok(rocky.levelCounts[2] > 0);
+ assert.equal(CLUTTER_LEVELS.at(-1).distance, 70);
+});
+
+test('a zero mask clears clutter, and update stays quiet when nothing moves', () => {
+ assert.equal(createClutter({ ...near, mask: () => 0 }).parts.length, 0);
+ const clutter = createClutter({ ...near, preset: 'forest' });
+ assert.equal(clutter.update([4, 1, 4]), false);
+ assert.equal(clutter.update([400, 1, 400]), true);
+ assert.equal(clutter.parts.length, 0);
+});
+
+test('every preset builds, and bad options fail with clear errors', () => {
+ for (const preset of Object.keys(CLUTTER_PRESETS)) assert.ok(createClutter({ ...near, preset }).parts.length > 0, preset);
+ assert.throws(() => createClutter({ ...near, preset: 'beach' }), /Unknown clutter preset/);
+ assert.throws(() => createClutter({}), /area/);
+ assert.throws(() => createClutter({ ...near, pebbles: -1 }), /pebbles/);
+ assert.throws(() => createClutter({ ...near, moss: 2 }), /moss/);
+ assert.throws(() => createClutter({ ...near, rockSize: [0.5, 0.1] }), /rockSize/);
+ assert.throws(() => createClutter({ ...near, leafColors: [] }), /leafColors/);
+ assert.throws(() => createClutter({ ...near, mask: 1 }), /mask/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index fb9d72d0..492ec89d 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -31,6 +31,7 @@ export default defineConfig({
vegetation: 'src/vegetation.js',
terrain: 'src/terrain.js',
grass: 'src/grass.js',
+ clutter: 'src/clutter.js',
'texture-set': 'src/texture-set.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',