Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Cull swaying foliage, add foliage shadow levels and a far tree level (part of #186)

Nguyen Xuan And96ae811ee79
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index de5c25f3..bf4651e8 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -75,7 +75,7 @@
"eevee": 41.9
},
"mountain-valley": {
- "cycles": 13.0,
+ "cycles": 13,
"eevee": 28.3
},
"outdoor-hdri": {
@@ -257,12 +257,12 @@
"gpu-vs-cpu": 0.0061
},
"mountain-valley": {
- "gpu-vs-cycles": 0.2623,
- "gpu-vs-eevee": 0.2971,
- "cpu-vs-cycles": 0.26,
- "cpu-vs-eevee": 0.2947,
+ "gpu-vs-cycles": 0.2629,
+ "gpu-vs-eevee": 0.2981,
+ "cpu-vs-cycles": 0.2607,
+ "cpu-vs-eevee": 0.2959,
"eevee-vs-cycles": 0.1879,
- "gpu-vs-cpu": 0.0192
+ "gpu-vs-cpu": 0.0188
},
"outdoor-hdri": {
"gpu-vs-cycles": 0.0462,
diff --git a/bench/reference/images/mountain-valley.jpg b/bench/reference/images/mountain-valley.jpg
index 0c1438f7..8acedfd9 100644
Binary files a/bench/reference/images/mountain-valley.jpg and b/bench/reference/images/mountain-valley.jpg differ
diff --git a/bench/reference/profile-scene.mjs b/bench/reference/profile-scene.mjs
index 1a237d1c..5a1e159d 100644
--- a/bench/reference/profile-scene.mjs
+++ b/bench/reference/profile-scene.mjs
@@ -30,11 +30,12 @@ async function profileOnce(page) {
started = performance.now();
};
// Counts what each frame hands to the GPU: draw calls and triangles.
- const drawn = { calls: 0, triangles: 0 };
+ const drawn = { calls: 0, triangles: 0, instancesByTriangleCount: {} };
const originalDraw = WebGL2RenderingContext.prototype.drawElementsInstanced;
WebGL2RenderingContext.prototype.drawElementsInstanced = function (mode, count, type, offset, instances) {
drawn.calls++;
drawn.triangles += (count / 3) * instances;
+ drawn.instancesByTriangleCount[count / 3] = (drawn.instancesByTriangleCount[count / 3] ?? 0) + instances;
return originalDraw.call(this, mode, count, type, offset, instances);
};
const scene = await REFERENCE_SCENES[id]();
@@ -58,10 +59,17 @@ async function profileOnce(page) {
const firstFrameDrawn = { ...drawn };
drawn.calls = 0;
drawn.triangles = 0;
+ drawn.instancesByTriangleCount = {};
renderer.render(frame);
wait();
lap('secondFrame');
const secondFrameDrawn = { ...drawn };
+ // The shadow pass is the first frame minus the main pass: instances drawn per triangle count of the geometry.
+ const shadowInstancesByTriangleCount = {};
+ for (const [triangles, instances] of Object.entries(firstFrameDrawn.instancesByTriangleCount)) {
+ const shadowInstances = instances - (secondFrameDrawn.instancesByTriangleCount[triangles] ?? 0);
+ if (shadowInstances > 0) shadowInstancesByTriangleCount[triangles] = shadowInstances;
+ }
WebGL2RenderingContext.prototype.drawElementsInstanced = originalDraw;
renderer.render(frame);
wait();
@@ -69,7 +77,7 @@ async function profileOnce(page) {
const image = canvas.toDataURL('image/png');
lap('canvasToPng');
renderer.dispose();
- return { parts: scene.parts.length, batches: renderer.batches.length, sceneTriangles: renderer.triangles, firstFrameDrawn, secondFrameDrawn, pngBytes: image.length, milliseconds };
+ return { parts: scene.parts.length, batches: renderer.batches.length, sceneTriangles: renderer.triangles, firstFrameDrawn: { calls: firstFrameDrawn.calls, triangles: firstFrameDrawn.triangles }, secondFrameDrawn: { calls: secondFrameDrawn.calls, triangles: secondFrameDrawn.triangles }, shadowInstancesByTriangleCount, mainInstancesByTriangleCount: secondFrameDrawn.instancesByTriangleCount, pngBytes: image.length, milliseconds };
}, sceneId);
}
diff --git a/bench/runtime/PROFILE.md b/bench/runtime/PROFILE.md
index 82edfe97..5a424f95 100644
--- a/bench/runtime/PROFILE.md
+++ b/bench/runtime/PROFILE.md
@@ -220,3 +220,19 @@ Next ideas, by expected size: a far level that keeps the picture (try the clump
- Triangles fell 76 percent; the SwiftShader shadow share (first frame minus later frame) fell from 2.1 to 2.6 s to 1.5 to 1.9 s, less than the triangle count because the foliage, the terrain and the per-instance selection remain. The steady frame does not draw the shadow map (it is static unless a caster moves or wind advances), so the plain frame is unchanged: 3060 median 17.6 to 18.4 ms before and after, SwiftShader 7.0 to 7.3 s. The saving lands on the first frame and on every frame that redraws the map.
- Picture: `mountain-valley` GPU render against the render before the change differs in 27,167 of 518,400 pixels, 80 of them by more than 8 levels (largest 24 of 255); SwiftShader 33,356 pixels, 78 above 8 levels (largest 35). In the darkest quarter of the image, where shadows are, the mean difference is 0.075 and 0.085 levels. Score against Cycles 0.3473 to 0.3478 (SwiftShader 0.3460 to 0.3466), against EEVEE 0.2420 to 0.2426. The other 20 scenes keep their scores to four digits.
- Not done: a shadow level for foliage, which needs a bound that includes the wind sway.
+
+### Foliage shadow levels, culled foliage and a far tree level (issue #186, 2026-11-03)
+
+`node bench/reference/profile-scene.mjs mountain-valley gpu` now also prints the instances drawn per triangle count of the geometry, for the shadow pass and for the main pass. Triangles handed to the GPU, measured on the RTX 3060:
+
+| Step | Main pass | Shadow pass |
+| --- | --- | --- |
+| Before (main at 52244d3) | 6,456,732 | 2,341,826 |
+| Swaying foliage culled, foliage shadow layers | 5,368,328 | 1,759,378 |
+| Plus the fourth tree level, as kept | 2,891,430 | 1,394,478 |
+
+- Swaying batches (`foliage`, `grass`) are cullable now. The vertex shader moves a vertex by at most 0.555 (foliage) or 0.51 (grass) times the wind strength, so each bound grows by 0.56 times the strength (`SWAY_REACH_PER_STRENGTH` in `renderer.js`). That is exact, so the picture does not change; it removed 1.09 million main pass triangles of off-screen foliage.
+- Foliage shadow layers: a third of the leaves 1.7 times larger (error 1 m) and an eighth 2.8 times larger (error 2 m), with the tree's own leaf material. Trunks gain a second shadow level with a third of the rings. A tree at the last camera level had 2,050 trunk triangles in the main pass and now has 750 (conifer), with its crown clumps 1.5 times wider.
+- Score against Cycles for `mountain-valley`: GPU 0.2623 to 0.2629, SwiftShader 0.2600 to 0.2607 (limit 0.002). The other 22 scenes keep their scores to four digits.
+- The frame time on the 3060 is a range, not a result: three runs of the main pass were 18.3 to 18.8 ms before and 11.8 to 14.7 ms after, with other sessions loading the machine.
+- Not done: the shadow pass still draws 3,649 shadow trunks of 130 triangles and about 3,200 crown clumps of 96 to 108 triangles for trees that are smaller than a texel; the terrain tile of 8,192 triangles is drawn 14 times.
diff --git a/changes/issue-186.md b/changes/issue-186.md
new file mode 100644
index 00000000..05ea0e34
--- /dev/null
+++ b/changes/issue-186.md
@@ -0,0 +1 @@
+- Draw fewer triangles for forests (issue #186). Swaying `foliage` and `grass` batches are now frustum culled with a bound that grows with the wind strength, and tree foliage has thinner `shadowLods` (a third of the leaves, then an eighth) next to the trunk levels from #171. A tree has a fourth level of detail beyond 150 m, with a third of the rings on each limb and crown clumps 1.5 times wider, so `createTree` returns four levels and `TREE_LEVEL_DISTANCES` has three entries. `mountain-valley` draws 2.89 instead of 6.46 million triangles in the main pass and 1.39 instead of 2.34 million in the shadow pass; its score against Cycles stays within 0.001 of before.
diff --git a/docs/culling-lod.md b/docs/culling-lod.md
index 9b4edaca..5f74db38 100644
--- a/docs/culling-lod.md
+++ b/docs/culling-lod.md
@@ -9,7 +9,9 @@ On by default, with no schema and no option to set. Each frame the renderer test
What is not culled, because its bounding sphere would not hold or because it draws in another pass:
- Skinned and morphed parts.
-- `foliage`, `grass`, `water`, `fire` and `smoke` materials, whose vertex shader moves vertices.
+- `water`, `fire` and `smoke` materials, whose vertex shader moves vertices.
+
+`foliage` and `grass` sway in the wind but by a known amount, so they are culled and take levels like rigid parts: the bound of each instance grows by 0.56 times the wind strength (the farthest `windOffset` in the vertex shader moves a vertex per unit of strength).
- Parts with an `assembly`.
- Alpha-blended, `liquid` and `foam` batches.
- The shadow passes. A caster outside the view can still shadow the view, so shadow maps draw every caster.
diff --git a/docs/vegetation.md b/docs/vegetation.md
index eb93aba9..772fbe38 100644
--- a/docs/vegetation.md
+++ b/docs/vegetation.md
@@ -32,23 +32,26 @@ Branches are swept tubes with parallel-transported rings, a taper, a root flare
Leaves sit on terminal twigs, face outward and up with jitter, and carry vertex colors that darken toward the crown center, so the canopy has depth.
Shading normals blend toward the crown, so a flat card lights like part of a rounded crown.
-The tree has three levels of detail, each listing parts with a `role`, `geometry`, `material` and `tintable` flag:
+The tree has four levels of detail, each listing parts with a `role`, `geometry`, `material` and `tintable` flag:
| Level | Content | Default switch distance |
| --- | --- | --- |
| 0 | Full skeleton, every leaf site | up to 38 m |
| 1 | Twigs dropped, fewer sides, one third of the leaves 1.7 times larger | 38 to 95 m |
-| 2 | Trunk and main limbs, crown as merged clumps (low-poly blobs or crossed cards) | beyond 95 m |
+| 2 | Trunk and main limbs, crown as merged clumps (low-poly blobs or crossed cards) | 95 to 150 m |
+| 3 | The same with a third of the rings on each limb, three or four sides and crown clumps 1.5 times wider | beyond 150 m |
-Measured triangle counts for seed 4 (level 0 / 1 / 2):
+Measured triangle counts for seed 4 (level 0 / 1 / 2 / 3):
| Species | `cards` | `mesh` |
| --- | --- | --- |
-| broadleaf | 5.8k / 1.8k / 0.5k | 16.0k / 5.3k / 3.0k |
-| birch | 7.9k / 2.3k / 0.6k | 21.9k / 7.0k / 2.8k |
-| conifer | 18.5k / 4.7k / 2.2k | 63.9k / 19.8k / 3.4k |
-| palm | 3.8k / 1.0k / 0.9k | 11.8k / 3.7k / 2.9k |
-| bush | 3.1k / 1.1k / 0.4k | 10.9k / 3.7k / 1.9k |
+| broadleaf | 5.8k / 1.8k / 0.5k / 0.3k | 24.0k / 7.9k / 3.2k / 3.0k |
+| birch | 7.9k / 2.3k / 0.6k / 0.4k | 21.9k / 7.0k / 2.8k / 2.6k |
+| conifer | 18.5k / 4.7k / 2.2k / 0.9k | 63.9k / 19.8k / 3.4k / 2.2k |
+| palm | 3.8k / 1.0k / 0.9k / 0.4k | 11.8k / 3.7k / 2.9k / 2.4k |
+| bush | 3.1k / 1.1k / 0.4k / 0.2k | 10.9k / 3.7k / 1.8k / 1.8k |
+
+In the shadow map, foliage has its own thinner layers (`shadowLods` on the foliage part: a third of the leaves 1.7 times larger, then an eighth 2.8 times larger), and the bark has a trunk with half the sides and one with a third of the rings. The renderer picks one by the size of a shadow texel.
Cards are single-sided now that the renderer honors `doubleSided`; the old duplicated back faces cost 22 to 41 percent of level 0 (broadleaf 7.4k to 5.8k, birch 10.7k to 7.9k, conifer 26.1k to 18.5k, palm 6.4k to 3.8k, bush 4.7k to 3.1k).
diff --git a/src/render-culling.js b/src/render-culling.js
index 08ba2c65..e238f125 100644
--- a/src/render-culling.js
+++ b/src/render-culling.js
@@ -97,9 +97,10 @@ export class InstanceSelection {
/**
* Splits a batch's instances into the ones that touch the frustum, by level. `bounds` is the geometry's bounding
* sphere, `levelErrors` the error of each level in geometry units (level 0 is 0), and `pixelsPerUnit` the pixels
- * that one world unit covers at depth 1 (half the canvas height times projection[5]).
+ * that one world unit covers at depth 1 (half the canvas height times projection[5]). `margin` widens every sphere by that many
+ * world units, for vertices that move away from their geometry (wind sway).
*/
-export function selectInstances(selection, { instanceData, instanceCount, stride, bounds, levelErrors, planes, viewProjection, pixelsPerUnit, pixelError = DEFAULT_LOD_PIXEL_ERROR }) {
+export function selectInstances(selection, { instanceData, instanceCount, stride, bounds, margin = 0, levelErrors, planes, viewProjection, pixelsPerUnit, pixelError = DEFAULT_LOD_PIXEL_ERROR }) {
selection.counts.fill(0);
selection.visibleCount = 0;
const hasLevels = levelErrors.length > 1;
@@ -110,7 +111,7 @@ export function selectInstances(selection, { instanceData, instanceCount, stride
const y = instanceData[offset + 1] * centerX + instanceData[offset + 5] * centerY + instanceData[offset + 9] * centerZ + instanceData[offset + 13];
const z = instanceData[offset + 2] * centerX + instanceData[offset + 6] * centerY + instanceData[offset + 10] * centerZ + instanceData[offset + 14];
const worldScale = largestColumnLength(instanceData, offset);
- if (isOutsideFrustum(planes, x, y, z, bounds.radius * worldScale)) continue;
+ if (isOutsideFrustum(planes, x, y, z, bounds.radius * worldScale + margin)) continue;
let level = 0;
if (hasLevels) {
const depth = viewProjection[3] * x + viewProjection[7] * y + viewProjection[11] * z + viewProjection[15];
diff --git a/src/renderer.js b/src/renderer.js
index e5b04985..f58811c5 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -36,6 +36,10 @@ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain'
const SWAYING_TAGS = new Set(['foliage', 'grass']);
// Tags whose vertex shader moves vertices away from the instance matrix, so a bounding sphere would not hold.
const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);
+// The farthest a vertex of a swaying tag moves in the world, per unit of wind strength (windOffset in shaders.js): foliage
+// reaches 0.1 * 2.5 * 1.9 + 0.08 = 0.555 and grass 0.42 + 0.05 + 0.04 = 0.51. Their bounds grow by this much times the
+// strength, so they can be culled and given levels like rigid parts.
+const SWAY_REACH_PER_STRENGTH = 0.56;
const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];
@@ -242,7 +246,8 @@ const OBJECT_ID_PASS_MODE = 5;
function isCullable(parts) {
const first = parts[0];
- if (first.skin || first.morph || DEFORMING_TAGS.has(first.material.tag)) return false;
+ if (first.skin || first.morph) return false;
+ if (DEFORMING_TAGS.has(first.material.tag) && !SWAYING_TAGS.has(first.material.tag)) return false;
if (renderPass(first.material) !== 'opaque' || materialAlphaState(first.material)[0] === 'blend') return false;
return parts.every(part => !part.assembly);
}
@@ -846,17 +851,18 @@ export class Renderer67 {
const cullable = isCullable(parts);
if (first.lods) {
validateLods(first, first.lods);
- if (!cullable) throw new RangeError(`lods need rigid, opaque parts without assembly motion: ${first.name}`);
+ if (!cullable) throw new RangeError(`lods need rigid or swaying, opaque parts without assembly motion: ${first.name}`);
}
if (first.shadowLods) {
validateLods(first, first.shadowLods);
- if (!cullable) throw new RangeError(`shadowLods need rigid, opaque parts without assembly motion: ${first.name}`);
+ if (!cullable) throw new RangeError(`shadowLods need rigid or swaying, opaque parts without assembly motion: ${first.name}`);
}
const levels = first.lods ?? [{ geometry: first.geometry, error: 0 }];
const sphere = geometryBoundingSphere(first.geometry);
const bounds = { center: sphere.center, radius: sphere.radius + Math.max(...levels.map(level => level.error)) };
const shadowLevels = first.shadowLods ? createLevelSet(first.shadowLods, parts.length) : null;
- return { cullable, bounds, ...createLevelSet(levels, parts.length), shadowLevels };
+ const swayReach = SWAYING_TAGS.has(first.material.tag) ? SWAY_REACH_PER_STRENGTH : 0;
+ return { cullable, bounds, swayReach, ...createLevelSet(levels, parts.length), shadowLevels };
}
/** The vertex array and instance buffer that draw one level of a batch (or of its `shadowLevels`) from the instances selected for it. */
@@ -893,7 +899,7 @@ export class Renderer67 {
selectBatchInstances(batch) {
if (!this.culling || !batch.cullable) return null;
return selectInstances(batch.selection, {
- instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds,
+ instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds, margin: batch.swayReach * Math.abs(this.windState.strength),
levelErrors: batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,
pixelsPerUnit: this.canvas.height / 2 * this.projection[5], pixelError: this.lodPixelError,
});
@@ -1244,7 +1250,7 @@ export class Renderer67 {
// Texels per world unit along the map's x axis; an orthographic matrix has depth 1 everywhere.
const texelsPerUnit = selectsLevels ? Math.hypot(lightMatrix[0], lightMatrix[4], lightMatrix[8]) * resolution / 2 : 0;
return selectInstances(levelSet.selection, {
- instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds,
+ instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds, margin: batch.swayReach * Math.abs(this.windState.strength),
levelErrors: selectsLevels ? levelSet.levelErrors : [0], planes, viewProjection: lightMatrix,
pixelsPerUnit: texelsPerUnit, pixelError: this.lodPixelError,
});
diff --git a/src/vegetation-species.js b/src/vegetation-species.js
index ca3667e0..1fce9f80 100644
--- a/src/vegetation-species.js
+++ b/src/vegetation-species.js
@@ -128,5 +128,8 @@ export const LEVEL_SETTINGS = [
{ sideScale: 1, leafKeep: 1, leafScale: 1, maximumBranchLevel: Infinity },
{ sideScale: 0.6, leafKeep: 0.34, leafScale: 1.7, maximumBranchLevel: -1 },
{ sideScale: 0.4, leafKeep: 0, leafScale: 1, maximumBranchLevel: 1 },
+ // Far level: `pointStride` keeps every n-th ring of a branch above the trunk and `crownScale` widens the crown clumps,
+ // so it keeps the trunk, its first branches and the width of the crown in far fewer triangles.
+ { sideScale: 0.25, leafKeep: 0, leafScale: 1, maximumBranchLevel: 1, pointStride: 3, crownScale: 1.5 },
];
-export const TREE_LEVEL_DISTANCES = [38, 95];
+export const TREE_LEVEL_DISTANCES = [38, 95, 150];
diff --git a/src/vegetation.js b/src/vegetation.js
index a4802d88..49668bdf 100644
--- a/src/vegetation.js
+++ b/src/vegetation.js
@@ -151,6 +151,12 @@ function describeCrown(leafSites) {
return { center, radius };
}
+/** Every `stride`-th ring of a branch, and always its tip. */
+function thinnedRings(points, radii, stride) {
+ const kept = points.map((point, index) => index).filter(index => index % stride === 0 || index === points.length - 1);
+ return { points: kept.map(index => points[index]), radii: kept.map(index => radii[index]) };
+}
+
function buildBark(skeleton, preset, setting, bark) {
const lastLevel = preset.levels.length - 1;
const maximumLevel = setting.maximumBranchLevel < 0 ? lastLevel + setting.maximumBranchLevel : setting.maximumBranchLevel;
@@ -160,6 +166,7 @@ function buildBark(skeleton, preset, setting, bark) {
const baseSides = preset.sides[Math.min(branch.level, preset.sides.length - 1)];
const sides = Math.max(3, Math.round(baseSides * setting.sideScale));
let { points, radii } = branch;
+ if (setting.pointStride > 1) ({ points, radii } = thinnedRings(points, radii, setting.pointStride));
if (branch.level === 0) {
const direction = normalized(subtractVectors(points[1], points[0]));
points = [addScaled(points[0], direction, -0.3), ...points];
@@ -182,6 +189,14 @@ function buildShadowTrunk(skeleton, preset, bark) {
return { geometry: buildBark(skeleton, preset, trunkOnly, bark), error: 2 * thickestBranchRadius + 0.15 * trunkRadius };
}
+// The trunk of the shadow level again with a third of its rings, which cuts a bend of the trunk by at most this many meters.
+const THINNED_TRUNK_ERROR = 0.3;
+
+function buildThinnedShadowTrunk(skeleton, preset, bark, trunk) {
+ const thinned = { sideScale: 0.25, maximumBranchLevel: 0, pointStride: 3 };
+ return { geometry: buildBark(skeleton, preset, thinned, bark), error: trunk.error + THINNED_TRUNK_ERROR };
+}
+
function isTextureDescriptor(value) {
return Boolean(value) && typeof value === 'object' && Boolean(value.image);
}
@@ -296,7 +311,7 @@ function addBlob(builder, center, radius, shading) {
}
}
-function addCrownClumps(builder, skeleton, spec, mode, random) {
+function addCrownClumps(builder, skeleton, spec, mode, random, widthScale = 1) {
const cellSize = skeleton.crown.radius / 2.1;
const cells = new Map();
for (const site of skeleton.leafSites) {
@@ -307,7 +322,7 @@ function addCrownClumps(builder, skeleton, spec, mode, random) {
for (const sites of cells.values()) {
const center = scaleVector(sites.reduce((sum, site) => addVectors(sum, site.position), [0, 0, 0]), 1 / sites.length);
const shading = crownShading(skeleton, center);
- const radius = cellSize * (0.55 + 0.1 * Math.min(sites.length, 5));
+ const radius = cellSize * (0.55 + 0.1 * Math.min(sites.length, 5)) * widthScale;
if (mode === 'mesh') {
addBlob(builder, center, radius, shading);
continue;
@@ -331,11 +346,10 @@ function addCrownClumps(builder, skeleton, spec, mode, random) {
}
}
-function buildFoliage(skeleton, preset, mode, levelIndex, random) {
- const setting = LEVEL_SETTINGS[levelIndex];
+function buildFoliage(skeleton, preset, mode, setting, random) {
const builder = createMeshBuilder({ withColors: true });
if (setting.leafKeep === 0) {
- addCrownClumps(builder, skeleton, preset.leaf, mode, random);
+ addCrownClumps(builder, skeleton, preset.leaf, mode, random, setting.crownScale);
return builder.build();
}
const stride = Math.round(1 / setting.leafKeep);
@@ -357,6 +371,21 @@ function createBarkMaterial(preset, scannedTextures) {
return material;
}
+// Thinner leaf layers for a shadow map whose texels are wider than a leaf. Each keeps the covered area of the layer above it
+// (fewer leaves, each larger), draws with the same material as the tree, and `error` is how far a leaf may sit from where
+// the full layer has one: about the spacing of the leaves it replaces.
+const SHADOW_FOLIAGE_SETTINGS = [
+ { leafKeep: 0.34, leafScale: 1.7, error: 1 },
+ { leafKeep: 0.125, leafScale: 2.8, error: 2 },
+];
+
+function buildShadowFoliage(skeleton, preset, mode, seed, firstSetting) {
+ return SHADOW_FOLIAGE_SETTINGS.slice(firstSetting).map((setting, index) => ({
+ geometry: buildFoliage(skeleton, preset, mode, setting, createRandom(seed * 104729 + 50 + firstSetting + index)),
+ error: setting.error,
+ }));
+}
+
function createMaterials(preset, mode, scannedBark, scannedLeaves) {
const bark = createBarkMaterial(preset, scannedBark);
if (mode === 'mesh') {
@@ -439,13 +468,20 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {
const scannedLeaves = leaves === 'cards' ? resolveLeafTextures(options.leafTextures, options.species) : null;
const materials = createMaterials(preset, leaves, scannedBark, scannedLeaves);
const shadowTrunk = buildShadowTrunk(skeleton, preset, bark);
+ const thinnedShadowTrunk = buildThinnedShadowTrunk(skeleton, preset, bark, shadowTrunk);
const levels = LEVEL_SETTINGS.map((setting, levelIndex) => {
const levelRandom = createRandom(seed * 104729 + levelIndex);
const foliageMaterial = setting.leafKeep === 0 ? materials.crown : materials.foliage;
const barkGeometry = buildBark(skeleton, preset, setting, bark);
+ const foliageGeometry = buildFoliage(skeleton, preset, leaves, setting, levelRandom);
+ // Level 0 can drop to either thinner layer and level 1 to the second; the crown clumps of level 2 are thin enough.
+ const shadowFoliage = setting.leafKeep === 0 ? [] : buildShadowFoliage(skeleton, preset, leaves, seed, levelIndex);
return describeLevel([
- { role: 'bark', geometry: barkGeometry, material: materials.bark, tintable: false, shadowLods: [{ geometry: barkGeometry, error: 0 }, shadowTrunk] },
- { role: 'foliage', geometry: buildFoliage(skeleton, preset, leaves, levelIndex, levelRandom), material: foliageMaterial, tintable: true },
+ { role: 'bark', geometry: barkGeometry, material: materials.bark, tintable: false, shadowLods: [{ geometry: barkGeometry, error: 0 }, shadowTrunk, thinnedShadowTrunk] },
+ {
+ role: 'foliage', geometry: foliageGeometry, material: foliageMaterial, tintable: true,
+ ...(shadowFoliage.length ? { shadowLods: [{ geometry: foliageGeometry, error: 0 }, ...shadowFoliage] } : {}),
+ },
]);
});
bakeCrownSkyVisibility(levels);
diff --git a/tests/render-culling.test.js b/tests/render-culling.test.js
index 76b24e9a..f76e4a00 100644
--- a/tests/render-culling.test.js
+++ b/tests/render-culling.test.js
@@ -91,6 +91,7 @@ function drawingRenderer(parts) {
renderer.geometryBuffers = new Map();
renderer.culling = true;
renderer.lodPixelError = 1;
+ renderer.windState = { time: 0, strength: 0.3 };
renderer.canvas = { height: CANVAS_HEIGHT };
const noop = () => {};
renderer.context = {
@@ -141,10 +142,10 @@ test('culling is off for deforming, skinned and alpha-blended batches, and lods
const lods = [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.1 }];
const { renderer, batch } = drawingRenderer([rigidPart('tree', geometry, [0, 0, 0])]);
assert.equal(batch.cullable, true);
- const swaying = rigidPart('grass', geometry, [0, 0, 0]);
- swaying.material.tag = 'grass';
- assert.equal(renderer.createCullingState([swaying]).cullable, false);
- assert.throws(() => renderer.createCullingState([{ ...swaying, lods }]), /lods need rigid, opaque parts/);
+ const deforming = rigidPart('water', geometry, [0, 0, 0]);
+ deforming.material.tag = 'water';
+ assert.equal(renderer.createCullingState([deforming]).cullable, false);
+ assert.throws(() => renderer.createCullingState([{ ...deforming, lods }]), /lods need rigid or swaying, opaque parts/);
const glass = rigidPart('glass', geometry, [0, 0, 0]);
glass.material.alphaMode = 'blend';
glass.material.opacity = 0.5;
@@ -178,9 +179,36 @@ test('the shadow pass skips instances outside the light and picks the shadow lev
test('a batch without shadow levels uses its camera levels in the shadow pass, and shadow levels are refused on deforming parts', () => {
const geometry = box(0, 1);
const { renderer } = drawingRenderer([rigidPart('tree', geometry, [0, 0, 0])]);
- const swaying = rigidPart('grass', geometry, [0, 0, 0], { shadowLods: [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.1 }] });
- swaying.material.tag = 'grass';
- assert.throws(() => renderer.createCullingState([swaying]), /shadowLods need rigid, opaque parts/);
+ const deforming = rigidPart('water', geometry, [0, 0, 0], { shadowLods: [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.1 }] });
+ deforming.material.tag = 'water';
+ assert.throws(() => renderer.createCullingState([deforming]), /shadowLods need rigid or swaying, opaque parts/);
const plain = renderer.createCullingState([rigidPart('plain', geometry, [0, 0, 0])]);
assert.equal(plain.shadowLevels, null);
});
+
+test('swaying foliage is culled and given shadow levels, with a bound that grows with the wind', () => {
+ const geometry = sphere(24, 12);
+ const shadowLods = [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.5 }];
+ const foliage = rigidPart('leaves', geometry, [0, 0, 0], { shadowLods });
+ foliage.material.tag = 'foliage';
+ const { renderer, batch } = drawingRenderer([foliage]);
+ assert.equal(batch.cullable, true);
+ assert.equal(batch.shadowLevels.levelGeometries[1], shadowLods[1].geometry);
+ assert.ok(batch.swayReach > 0.5, 'the reach covers the farthest leaf the wind shader moves (0.555 per unit of strength)');
+ const rigid = renderer.createCullingState([rigidPart('rock', geometry, [0, 0, 0])]);
+ assert.equal(rigid.swayReach, 0);
+ // An instance just outside the frustum edge swings into view when the wind is strong enough.
+ const { projection, viewProjection, planes } = cameraMatrices([0, 0, 10]);
+ renderer.viewProjection = viewProjection;
+ renderer.projection = projection;
+ renderer.frustumPlanes = planes;
+ const edge = rigidPart('edge', geometry, [9.8, 0, 0]);
+ edge.material.tag = 'foliage';
+ const edgeBatch = renderer.createCullingState([edge]);
+ const select = strength => {
+ renderer.windState = { time: 0, strength };
+ return renderer.selectBatchInstances({ ...edgeBatch, instanceData: instanceData([[9.8, 0, 0]]), instanceCount: 1 }).visibleCount;
+ };
+ assert.equal(select(0), 0);
+ assert.equal(select(4), 1);
+});
diff --git a/tests/vegetation.test.js b/tests/vegetation.test.js
index 6937fde9..eb8165da 100644
--- a/tests/vegetation.test.js
+++ b/tests/vegetation.test.js
@@ -32,7 +32,7 @@ test('every species and leaf mode yields valid geometry on all levels', () => {
for (const species of SPECIES_NAMES) {
for (const leaves of ['cards', 'mesh']) {
const tree = createTree({ species, leaves }, 3);
- assert.equal(tree.levels.length, 3);
+ assert.equal(tree.levels.length, 4);
for (const level of tree.levels) {
for (const part of level.parts) assertValidGeometry(part.geometry);
}
@@ -70,17 +70,28 @@ test('invalid inputs are rejected', () => {
});
test('triangle budgets fall with each level of detail', () => {
- const budgets = { broadleaf: [60000, 12000, 2500], birch: [60000, 12000, 2500], conifer: [60000, 12000, 2500], palm: [30000, 8000, 3000], bush: [20000, 5000, 2500] };
+ const budgets = { broadleaf: [60000, 12000, 2500, 2500], birch: [60000, 12000, 2500, 2500], conifer: [60000, 12000, 2500, 1200], palm: [30000, 8000, 3000, 3000], bush: [20000, 5000, 2500, 2500] };
for (const species of SPECIES_NAMES) {
for (const leaves of ['cards', 'mesh']) {
const triangles = createTree({ species, leaves }, 4).levels.map(level => level.triangles);
- assert.ok(triangles[0] > triangles[1] && triangles[1] > triangles[2], `${species} ${leaves} ${triangles}`);
+ assert.ok(triangles[0] > triangles[1] && triangles[1] > triangles[2] && triangles[2] >= triangles[3], `${species} ${leaves} ${triangles}`);
const scale = leaves === 'mesh' ? 2 : 1;
triangles.forEach((count, level) => assert.ok(count <= budgets[species][level] * scale, `${species} ${leaves} level ${level}: ${count}`));
}
}
});
+test('foliage carries thinner shadow layers, and the far conifer level costs under half the level before it', () => {
+ const tree = createTree('conifer', 4);
+ const [full, sparse, sparsest] = tree.levels[0].parts[1].shadowLods;
+ assert.equal(full.error, 0);
+ assert.ok(full.geometry.indices.length > sparse.geometry.indices.length && sparse.geometry.indices.length > sparsest.geometry.indices.length);
+ assert.ok(sparse.error > 0 && sparsest.error > sparse.error, 'errors grow as the layers thin out');
+ assert.equal(tree.levels[1].parts[1].shadowLods.length, 2, 'level 1 already is the first thinner layer');
+ assert.equal(tree.levels[2].parts[1].shadowLods, undefined, 'the crown clumps are thin enough');
+ assert.ok(tree.levels[3].triangles < tree.levels[2].triangles / 2);
+});
+
test('wind sway comes from leaves on the foliage tag while bark stays static', () => {
const tree = createTree({ species: 'conifer', leaves: 'mesh' }, 1);
assert.equal(tree.levels[0].parts[0].material.tag, undefined);