Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Hide sky light inside tree crowns and on valley floors (issue #191)

Nguyen Xuan Anf66ddb2c14fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3532348..b24f2a96 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Hide sky light where the scene blocks it: inside tree crowns and on a valley floor (issue #191, part of it). `createTree` bakes a sky visibility into each foliage vertex from the leaf density above it, and `createTerrain` bakes one into each terrain vertex from the horizon in 16 directions. The shader multiplies it into the environment light only, and meshes without it read 1. On `bench/reference`, the `foliage` crown went from 0.298 to 0.200 (Cycles 0.175) and the score from 0.1173 to 0.1023 (EEVEE 0.0888); `mountain-valley` went from 0.3483 to 0.2623 (EEVEE 0.1879), and its floor from 0.417 to 0.360 (Cycles 0.272). No other scene changed to four digits. The agent scene geometry bound allows 4 more bytes for each terrain vertex.
- Compare trees like with like (issue #166, part of it). The Blender side of `bench/reference` now rebuilds the 67js leaf model for `foliage` materials (back-face normal, colour and normal variation, sky reflection 0.3, and light from behind as a Translucent BSDF with weight `0.3 * pi / (3.7, 3.4, 2.9)`), and the 67js back light is now shadowed by the sun shadow. `foliage` goes from 0.1290 to 0.1173 against Cycles (EEVEE 0.0864 to 0.0888) and `mountain-valley` from 0.3473 to 0.3483 (EEVEE 0.1828 to 0.1879); no other scene moved. The remaining gap is canopy and valley sky occlusion, recorded in `bench/reference/README.md`.
- Make every test file pass on its own, and check it in CI (issue #172). `node --test tests/agent-bake.test.js` failed 16 of 19 because `npm test` preloaded every on-demand module into each test process, so 28 files only passed through that preload. The loading path agents use was fine (`tests/agent-scene-on-demand.test.js` runs it in clean processes). Each of those files now imports `tests/support/load-agent-scene-modules.mjs` itself, `npm test` no longer preloads, and `npm run test:isolated` (`scripts/test-each-file.mjs`) runs each file in its own process, 4 at a time at below-normal priority, rerunning a failure alone once so a busy machine does not count. It runs in the `Test` workflow.
- Fix links in the npm package that pointed at docs it does not ship (issue #178). `docs/guide.md`, `docs/material-maps.md`, `README.md` and `ROADMAP.md` now link the 20 unshipped docs, `CONTRIBUTING.md`, the texture credits and the changelog by absolute GitHub URL; shipping those docs would add 64 KB gzip. `npm run check:links:package` packs the archive, unpacks it and checks every link inside (26 files, 0 broken), and the `Test` workflow runs it.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index d539703e..2f66ce59 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -45,7 +45,7 @@ Three scenes test what people want to make, not one feature. Each one is built w
| Scene | Parts | Triangles drawn | 67js against Cycles | EEVEE against Cycles | Largest visible gap |
| --- | --- | --- | --- | --- | --- |
| `megacity-dusk` | 4,300 | 51.6 thousand | 0.1627 | 0.1524 | Window bands are sharper, and facades get no light from the windows |
-| `mountain-valley` | 7,698 | 9.72 million | 0.3483 | 0.1879 | The valley floor and the trees are 2 to 3 times as bright as in Cycles, and shadowed rock is brighter (see "Leaf model and tree regions") |
+| `mountain-valley` | 7,698 | 9.72 million | 0.2623 | 0.1879 | The valley floor and the trees are 1.3 to 1.7 times as bright as in Cycles, and shadowed rock is brighter (see "Sky visibility in crowns and valleys") |
| `temple-hall` | 155 | 11 thousand | 0.2126 | 0.2341 | The fog shafts are stronger in 67js, and the floor gets no bounce light |
With the shadow floor `temple-hall` scored 0.5841, `mountain-valley` 0.3658 and `megacity-dusk` 0.1583.
@@ -309,6 +309,37 @@ What the experiments show, each with the flags of this runner:
Blender render time of the two rerun scenes, now in `baseline.json`: `foliage` 26.4 s in Cycles and 13.5 s in EEVEE, `mountain-valley` 35.9 s and 39.2 s (other jobs loaded the machine).
+### Sky visibility in crowns and valleys (issue #191)
+
+The two experiments above point at the same missing term: sky light that reaches a surface which the scene itself shades. Cycles blocks that light and 67js did not. Two bakes now give the sky term a visibility, and no recipe field changes.
+
+Causes, each measured on its own:
+
+- Crown. With `--ambient 0` the 67js crown is 0.176, the same as the whole Cycles crown (0.175). The 0.12 the world adds in 67js (0.298 in total) is therefore sky light that Cycles stops inside the crown.
+- Valley floor, from the heightfield. A script walked 32 horizon directions from 6 floor points of the `mountain-valley` height function and computed the cosine weighted share of the sky above the horizon. The ring leaves 0.69 to 0.72 of the sky open. Without the ring the share is 0.995 to 0.999. Cycles was not rerun without the ring.
+- The valley sky term is 0.416 minus 0.180 = 0.236 in 67js, and 0.272 minus 0.180 = 0.092 in Cycles, which needs a share of 0.39. The ring explains the larger part of the gap. The estimate 0.18 + 0.7 * 0.236 = 0.345 is close to the measured result below (0.360). The rest is not explained: the sky of the HDRI is brightest near the horizon, which the ring hides, and a cosine share cannot see that.
+
+What changed:
+
+- `createTree` gives each foliage vertex a `skyVisibility` (`src/tree-sky.js`). The leaf vertices are binned in a grid of 14 cells along the longest side. For each occupied cell, 9 rays go up (1 zenith, 4 at 40 degrees, 4 at 65 degrees) and add the leaf density they cross. The cell keeps the mean of `exp(-depth)`, with a floor of 0.04. The opacity of one leaf vertex, 0.3, is the one fitted number: it was set on the `foliage` crown and not on `mountain-valley`. A level with fewer leaves counts each vertex for more, so the three levels agree.
+- `createTerrain` gives each terrain vertex a `skyVisibility` (`src/terrain-sky.js`). For 16 azimuths it marches the heightfield outward in growing steps, keeps the highest horizon, and integrates the cosine weighted sky above it for the tilted surface normal. It samples a lattice of at most 160 nodes per side and interpolates, so the cost does not grow with the grid.
+- The value travels in the fourth component of the vertex colour attribute, so the attribute layout is the same. The shader multiplies it into `occlusion` (which scales the environment light) and into the two fill lights in world mode. Direct lights are not touched. A mesh without the value reads 1.
+- The tree value is computed on first read, which is when the renderer uploads the geometry. The terrain value is computed per chunk when the chunk is built.
+
+Results (FLIP against Cycles, RTX 3060, 2026-11-02), with EEVEE against Cycles beside them. Region luminance is the mean display luminance of the region, taken on the Cycles image:
+
+| Scene and region | Cycles | EEVEE | 67js before | 67js after |
+| --- | --- | --- | --- | --- |
+| `foliage` score | - | 0.0888 | 0.1173 | 0.1023 |
+| `foliage` crown | 0.175 | 0.227 | 0.298 | 0.200 |
+| `mountain-valley` score | - | 0.1879 | 0.3483 | 0.2623 |
+| `mountain-valley` floor, rows 440 to 530 | 0.272 | 0.306 | 0.417 | 0.360 |
+| `mountain-valley` trees (green) | 0.151 | 0.193 | 0.312 | 0.254 |
+
+The `foliage` crown is now within 0.03 of Cycles, but the scene still scores worse than EEVEE: with the opacity at 0.12 the score was 0.1033 and the crown 0.226, so the rest of the crown error is leaf shape and placement, not sky. The valley trees stop at 0.254 because a conifer crown is already at the visibility floor, and a tree in the valley does not see the ring. The score against EEVEE of `mountain-valley` rose from 0.2382 to 0.2971, since EEVEE does not hide the sky either. No other scene changed to four digits in the full rescore, and the plain frame time of `material-spheres` did not change beyond the noise of a loaded machine (median 1.18 ms before, 1.0 ms after over 4 alternating runs).
+
+Build time, on this machine with other jobs running: a 5 km valley terrain adds about 0.2 to 0.35 s (1.7 to 2.2 s before). A conifer crown costs about 4 ms and a broadleaf crown 6 ms for three levels, so the 3 variants of the valley forest add about 15 ms, and a forest of 3,600 distinct trees would add about 15 to 20 s only if every tree is drawn, since the value is lazy.
+
## Limits
- Scores come from one camera for each scene and one machine. They do not measure motion or speed.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index e65c9311..6f40fa24 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -161,12 +161,12 @@
"gpu-vs-cpu": 0.0089
},
"foliage": {
- "gpu-vs-cycles": 0.1173,
- "gpu-vs-eevee": 0.0836,
- "cpu-vs-cycles": 0.117,
- "cpu-vs-eevee": 0.0833,
+ "gpu-vs-cycles": 0.1023,
+ "gpu-vs-eevee": 0.0853,
+ "cpu-vs-cycles": 0.102,
+ "cpu-vs-eevee": 0.0849,
"eevee-vs-cycles": 0.0888,
- "gpu-vs-cpu": 0.01
+ "gpu-vs-cpu": 0.0098
},
"glass": {
"gpu-vs-cycles": 0.1034,
@@ -233,12 +233,12 @@
"gpu-vs-cpu": 0.0061
},
"mountain-valley": {
- "gpu-vs-cycles": 0.3483,
- "gpu-vs-eevee": 0.2382,
- "cpu-vs-cycles": 0.3469,
- "cpu-vs-eevee": 0.2368,
+ "gpu-vs-cycles": 0.2623,
+ "gpu-vs-eevee": 0.2971,
+ "cpu-vs-cycles": 0.26,
+ "cpu-vs-eevee": 0.2947,
"eevee-vs-cycles": 0.1879,
- "gpu-vs-cpu": 0.02
+ "gpu-vs-cpu": 0.0192
},
"outdoor-hdri": {
"gpu-vs-cycles": 0.0462,
diff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpg
index 7aa38e8c..5a1b9ecc 100644
Binary files a/bench/reference/images/foliage.jpg and b/bench/reference/images/foliage.jpg differ
diff --git a/bench/reference/images/mountain-valley.jpg b/bench/reference/images/mountain-valley.jpg
index 187b8bdf..0c1438f7 100644
Binary files a/bench/reference/images/mountain-valley.jpg and b/bench/reference/images/mountain-valley.jpg differ
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index f2cf62fb..5e980f6c 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 292734,
- "gzip": 84060,
- "brotli": 71533
+ "min": 294907,
+ "gzip": 84612,
+ "brotli": 72087
},
"entry:model": {
"min": 40093,
@@ -39,14 +39,14 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 171999,
- "gzip": 52846,
- "brotli": 45706
+ "min": 172310,
+ "gzip": 52936,
+ "brotli": 45770
},
"entry:gltf+lazy": {
- "min": 183290,
- "gzip": 56173,
- "brotli": 48745
+ "min": 183601,
+ "gzip": 56264,
+ "brotli": 48809
},
"entry:modeling": {
"min": 21149,
@@ -109,14 +109,14 @@
"brotli": 12172
},
"entry:vegetation": {
- "min": 49217,
- "gzip": 17468,
- "brotli": 14786
+ "min": 51082,
+ "gzip": 18204,
+ "brotli": 15365
},
"entry:terrain": {
- "min": 7387,
- "gzip": 3322,
- "brotli": 3012
+ "min": 8837,
+ "gzip": 3992,
+ "brotli": 3594
},
"entry:navmesh": {
"min": 7206,
@@ -134,9 +134,9 @@
"brotli": 4675
},
"entry:light-bake": {
- "min": 76459,
- "gzip": 27896,
- "brotli": 24559
+ "min": 76987,
+ "gzip": 28081,
+ "brotli": 24730
},
"entry:path-tracer": {
"min": 35311,
@@ -149,24 +149,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 239032,
- "gzip": 74924,
- "brotli": 65544
+ "min": 241280,
+ "gzip": 75905,
+ "brotli": 66520
},
"entry:agent-scene+lazy": {
- "min": 734453,
- "gzip": 254034,
- "brotli": 224197
+ "min": 738589,
+ "gzip": 255849,
+ "brotli": 225881
},
"entry:agent-asset": {
- "min": 334071,
- "gzip": 106324,
- "brotli": 93424
+ "min": 336327,
+ "gzip": 107300,
+ "brotli": 94281
},
"entry:agent-asset+lazy": {
- "min": 771254,
- "gzip": 265468,
- "brotli": 234049
+ "min": 775398,
+ "gzip": 267282,
+ "brotli": 235771
},
"entry:hdri": {
"min": 8075,
@@ -184,44 +184,44 @@
"brotli": 1425
},
"entry:material-layer-shaders": {
- "min": 77871,
- "gzip": 20210,
- "brotli": 17757
+ "min": 78182,
+ "gzip": 20300,
+ "brotli": 17846
},
"entry:light-linking": {
- "min": 68966,
- "gzip": 18535,
- "brotli": 16283
+ "min": 69277,
+ "gzip": 18622,
+ "brotli": 16363
},
"entry:cascaded-shadows": {
- "min": 96709,
- "gzip": 27065,
- "brotli": 23102
+ "min": 97036,
+ "gzip": 27150,
+ "brotli": 23145
},
"scene:lit-box": {
- "min": 222245,
- "gzip": 61522,
- "brotli": 52440
+ "min": 224221,
+ "gzip": 62045,
+ "brotli": 52910
},
"scene:gltf-box": {
- "min": 284766,
- "gzip": 82521,
- "brotli": 71752
+ "min": 286743,
+ "gzip": 83064,
+ "brotli": 72232
},
"scene:gltf-box+lazy": {
- "min": 296057,
- "gzip": 85849,
- "brotli": 74800
+ "min": 298034,
+ "gzip": 86392,
+ "brotli": 75292
},
"scene:agent-scene": {
- "min": 335191,
- "gzip": 101255,
- "brotli": 88193
+ "min": 339101,
+ "gzip": 102720,
+ "brotli": 89464
},
"scene:agent-scene+lazy": {
- "min": 830612,
- "gzip": 280360,
- "brotli": 246904
+ "min": 836410,
+ "gzip": 282648,
+ "brotli": 248866
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 563dfd99..1b301e94 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -25,8 +25,8 @@
"entry:retarget": 15700,
"entry:skeleton-pose": 19200,
"entry:vehicle": 14700,
- "entry:vegetation": 17900,
- "entry:terrain": 3400,
+ "entry:vegetation": 18600,
+ "entry:terrain": 4100,
"entry:navmesh": 3400,
"entry:grass": 4400,
"entry:clutter": 5300,
diff --git a/src/agent-scene.js b/src/agent-scene.js
index bce8a8de..c3b8b56f 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -19,6 +19,8 @@ export {
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
+// Terrain meshes carry one more float for each vertex (sky visibility) than the 56 bytes the budget estimates.
+const TERRAIN_SKY_VISIBILITY_BYTES = 4;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations'];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
@@ -1007,7 +1009,7 @@ export function createAgentScene(input, inputLimits = {}) {
if (residentStats.vertices + pendingVertices - plan.estimatedVertices + vertices > limits.maxVertices) {
throw new RangeError(`Mesh ${plan.definition.id} has ${vertices} render vertices after its edits, which exceeds maxVertices across the scene. Reduce detail or edits.`);
}
- } else if (vertices > plan.estimatedVertices || geometryBytes > plan.estimatedVertices * 56) {
+ } else if (vertices > plan.estimatedVertices || geometryBytes > plan.estimatedVertices * (56 + TERRAIN_SKY_VISIBILITY_BYTES)) {
throw new RangeError('Generated geometry exceeds its conservative preflight bound.');
}
record = Object.freeze({
diff --git a/src/light-bake.js b/src/light-bake.js
index 2bb81b22..fd65496b 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -578,18 +578,21 @@ function unwrapIntoSecondUvSet(geometry, scale) {
const result = { positions: extracted.positions, normals: extracted.normals, indices: extracted.indices, lightUvs: extracted.uvs };
const uvs = geometry.uvs ? new Float32Array(newCount * 2) : null;
const colors = geometry.colors ? new Float32Array(newCount * 3) : null;
+ const skyVisibility = geometry.skyVisibility ? new Float32Array(newCount) : null;
for (let vertex = 0; vertex < newCount; vertex++) {
const source = Math.round(extracted.colors[vertex * 3]);
if (uvs) {
uvs[vertex * 2] = geometry.uvs[source * 2];
uvs[vertex * 2 + 1] = geometry.uvs[source * 2 + 1];
}
+ if (skyVisibility) skyVisibility[vertex] = geometry.skyVisibility[source];
if (colors) {
for (let channel = 0; channel < 3; channel++) colors[vertex * 3 + channel] = geometry.colors[source * 3 + channel];
}
}
if (uvs) result.uvs = uvs;
if (colors) result.colors = colors;
+ if (skyVisibility) result.skyVisibility = skyVisibility;
return { geometry: result, utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };
}
diff --git a/src/renderer.js b/src/renderer.js
index aafba1b8..3b13c88d 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -353,8 +353,23 @@ function interleaveUvSets(geometry) {
return combined;
}
+// Sky visibility rides in the fourth component of the vertex colour attribute, so the attribute layout stays the same.
+function interleaveColorsWithSkyVisibility(geometry) {
+ const vertexCount = geometry.skyVisibility.length;
+ const combined = new Float32Array(vertexCount * 4);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ for (let channel = 0; channel < 3; channel++) {
+ combined[vertex * 4 + channel] = geometry.colors ? geometry.colors[vertex * 3 + channel] : 1;
+ }
+ combined[vertex * 4 + 3] = geometry.skyVisibility[vertex];
+ }
+ return combined;
+}
+
function geometryBufferBytes(geometry) {
- return ['positions', 'normals', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), uvBufferBytes(geometry));
+ const plainBytes = ['positions', 'normals', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), uvBufferBytes(geometry));
+ if (!geometry.skyVisibility) return plainBytes;
+ return plainBytes - (geometry.colors?.byteLength ?? 0) + geometry.skyVisibility.length * 16;
}
function validateReplacementGeometry(geometry) {
@@ -776,9 +791,10 @@ export class Renderer67 {
if (geometry[field]) {
const target = field === 'indices' ? context.ELEMENT_ARRAY_BUFFER : context.ARRAY_BUFFER;
const values = field === 'uvs' && geometry.lightUvs ? interleaveUvSets(geometry) : geometry[field];
- geometryBuffers.set(field, this.uploadBuffer(target, values));
+ geometryBuffers.set(field, this.uploadBuffer(target, field === 'colors' && geometry.skyVisibility ? interleaveColorsWithSkyVisibility(geometry) : values));
}
}
+ if (geometry.skyVisibility && !geometry.colors) geometryBuffers.set('colors', this.uploadBuffer(context.ARRAY_BUFFER, interleaveColorsWithSkyVisibility(geometry)));
if (geometry.lightUvs && !geometry.uvs) geometryBuffers.set('uvs', this.uploadBuffer(context.ARRAY_BUFFER, interleaveUvSets(geometry)));
this.geometryBuffers.set(geometry, geometryBuffers);
}
@@ -799,11 +815,12 @@ export class Renderer67 {
// (-1, -1) marks "no UVs": grass wind then bends by local height instead of by blade position.
context.vertexAttrib2f(13, -1, -1);
}
- if (geometry.colors) {
- if (geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
+ if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
+ if (geometry.skyVisibility && geometry.skyVisibility.length !== geometry.positions.length / 3) throw new Error('Geometry skyVisibility must hold one value for every vertex.');
+ if (geometry.colors || geometry.skyVisibility) {
context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get('colors'));
context.enableVertexAttribArray(14);
- context.vertexAttribPointer(14, 3, context.FLOAT, false, 0, 0);
+ context.vertexAttribPointer(14, geometry.skyVisibility ? 4 : 3, context.FLOAT, false, 0, 0);
} else {
context.disableVertexAttribArray(14);
context.vertexAttrib3f(14, 1, 1, 1);
diff --git a/src/shaders.js b/src/shaders.js
index 1d9baea5..2ba1ad7d 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -102,7 +102,7 @@ layout(location=10) in vec4 instanceSurface;
layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
layout(location=13) in vec4 uvSets;
-layout(location=14) in vec3 vertexColor;
+layout(location=14) in vec4 vertexColor;
layout(location=15) in vec3 instanceEmissive;
uniform mat4 viewProjection;
uniform mat4 lightProjection;
@@ -119,6 +119,7 @@ out vec4 shadowPosition;
out vec2 textureUV;
out vec2 lightmapUV;
out vec3 vertexTint;
+out float vertexSkyVisibility;
flat out vec3 emissionColor;
flat out float instanceOrdinal;
out vec3 boxPosition;
@@ -150,7 +151,8 @@ void main() {
baseColor = instanceColor;
textureUV = uv;
lightmapUV = uvSets.zw;
- vertexTint = vertexColor;
+ vertexTint = vertexColor.rgb;
+ vertexSkyVisibility = vertexColor.a;
emissionColor = instanceEmissive;
instanceOrdinal = float(gl_InstanceID);
surface = instanceSurface;
@@ -363,6 +365,7 @@ in vec4 shadowPosition;
in vec2 textureUV;
in vec2 lightmapUV;
in vec3 vertexTint;
+in float vertexSkyVisibility;
flat in vec3 emissionColor;
flat in float instanceOrdinal;
uniform sampler2D lightMap;
@@ -806,8 +809,8 @@ void main() {
vec3 baseReflectance = mix(materialDielectric, color, metallic);
${featureCode("mainSetup")} float visibility = shadowVisibility(normal);
vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility${featureCode("linkSun")}, color, metallic, roughness);
- radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity, color, metallic, roughness);
- radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity, color, metallic, roughness);
+ radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);
+ radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);
for (int index = 0; index < 8; index++) {
if (index >= pointLightCount) break;
vec3 offset = pointLightPositions[index].xyz - worldPosition;
@@ -867,7 +870,8 @@ ${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;
vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), baseReflectance);
float occlusion = 1.0;
if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, mapUV(hasOcclusionMap)).r, occlusionStrength);
- occlusion *= splatCavity;
+ // Trees and terrain bake how much sky each vertex sees; everything else carries 1.
+ occlusion *= splatCavity * vertexSkyVisibility;
// Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.
float skyReflection = canopyShaded ? 0.3 : 1.0;
if (ENVIRONMENT_ENABLED) {
diff --git a/src/terrain-sky.js b/src/terrain-sky.js
new file mode 100644
index 00000000..3278dabd
--- /dev/null
+++ b/src/terrain-sky.js
@@ -0,0 +1,92 @@
+// Sky visibility of a heightfield: the share of the cosine-weighted sky above a ground point that the terrain around
+// it leaves open. A valley floor inside a ring of peaks sees only part of the sky; a plateau sees all of it.
+// It is computed from the horizon in a few directions, lazily for each grid point the first time a mesh needs it.
+
+const AZIMUTH_COUNT = 16;
+const FIRST_STEP_CELLS = 2;
+const STEP_GROWTH = 1.3;
+const HALF_PI = Math.PI / 2;
+// At most about 160 lattice nodes along a side, so the cost does not grow with the grid.
+const NODES_PER_SIDE = 160;
+
+// Integral of max(dot(normal, direction), 0) over elevation, up to `elevation`, for one azimuth. `up` is the normal's
+// y component and `across` its horizontal component along that azimuth.
+function irradianceUpTo(elevation, up, across) {
+ return up * Math.sin(elevation) ** 2 / 2 + across * (elevation / 2 + Math.sin(2 * elevation) / 4);
+}
+
+/**
+ * `heights` is a (gridCells + 1) squared row-major grid with `spacing` meters between points; `highest` is its maximum.
+ * `normalAt(column, row, target)` writes the unit surface normal into target. Returns `(column, row) => visibility`
+ * in 0 to 1, where a point whose whole sky is open reads 1.
+ */
+export function createSkyVisibilitySampler({ heights, gridCells, spacing, highest, normalAt }) {
+ const gridSide = gridCells + 1;
+ const cache = new Float32Array(gridSide * gridSide).fill(Number.NaN);
+ const maximumDistance = gridCells * spacing;
+ const nodeStride = Math.max(1, Math.round(gridCells / NODES_PER_SIDE));
+ const normal = new Float32Array(3);
+ const cosines = Array.from({ length: AZIMUTH_COUNT }, (_, index) => Math.cos(index / AZIMUTH_COUNT * 2 * Math.PI));
+ const sines = Array.from({ length: AZIMUTH_COUNT }, (_, index) => Math.sin(index / AZIMUTH_COUNT * 2 * Math.PI));
+
+ function heightAtGrid(gridX, gridZ) {
+ const column = Math.min(Math.floor(gridX), gridCells - 1);
+ const row = Math.min(Math.floor(gridZ), gridCells - 1);
+ const fractionX = gridX - column;
+ const fractionZ = gridZ - row;
+ const index = row * gridSide + column;
+ const lower = heights[index] * (1 - fractionX) + heights[index + 1] * fractionX;
+ const upper = heights[index + gridSide] * (1 - fractionX) + heights[index + gridSide + 1] * fractionX;
+ return lower * (1 - fractionZ) + upper * fractionZ;
+ }
+
+ function horizonTangent(column, row, base, cosine, sine) {
+ let tangent = -Infinity;
+ for (let distance = spacing * FIRST_STEP_CELLS; distance <= maximumDistance; distance *= STEP_GROWTH) {
+ // Nothing further out can rise above the horizon found so far.
+ if ((highest - base) / distance <= tangent) break;
+ const gridX = column + cosine * distance / spacing;
+ const gridZ = row + sine * distance / spacing;
+ if (gridX < 0 || gridZ < 0 || gridX > gridCells || gridZ > gridCells) break;
+ tangent = Math.max(tangent, (heightAtGrid(gridX, gridZ) - base) / distance);
+ }
+ return tangent;
+ }
+
+ function compute(column, row) {
+ const base = heights[row * gridSide + column];
+ if (highest - base <= 0) return 1;
+ normalAt(column, row, normal);
+ const up = Math.max(normal[1], 1e-6);
+ let visible = 0;
+ let total = 0;
+ for (let azimuth = 0; azimuth < AZIMUTH_COUNT; azimuth++) {
+ const across = normal[0] * cosines[azimuth] + normal[2] * sines[azimuth];
+ const horizon = Math.atan(horizonTangent(column, row, base, cosines[azimuth], sines[azimuth]));
+ const surfaceHorizon = Math.atan(-across / up);
+ const open = irradianceUpTo(HALF_PI, up, across);
+ total += open - irradianceUpTo(surfaceHorizon, up, across);
+ visible += open - irradianceUpTo(Math.max(horizon, surfaceHorizon), up, across);
+ }
+ return total > 0 ? Math.min(1, Math.max(0, visible / total)) : 1;
+ }
+
+ // Sky visibility changes slowly, so it is computed on a lattice every `nodeStride` grid points and interpolated.
+ function nodeValue(column, row) {
+ const index = row * gridSide + column;
+ if (Number.isNaN(cache[index])) cache[index] = compute(column, row);
+ return cache[index];
+ }
+
+ return function skyVisibilityAt(column, row) {
+ const lowColumn = Math.floor(column / nodeStride) * nodeStride;
+ const lowRow = Math.floor(row / nodeStride) * nodeStride;
+ const highColumn = Math.min(lowColumn + nodeStride, gridCells);
+ const highRow = Math.min(lowRow + nodeStride, gridCells);
+ const fractionColumn = highColumn === lowColumn ? 0 : (column - lowColumn) / (highColumn - lowColumn);
+ const fractionRow = highRow === lowRow ? 0 : (row - lowRow) / (highRow - lowRow);
+ const near = nodeValue(lowColumn, lowRow) * (1 - fractionColumn) + nodeValue(highColumn, lowRow) * fractionColumn;
+ const far = nodeValue(lowColumn, highRow) * (1 - fractionColumn) + nodeValue(highColumn, highRow) * fractionColumn;
+ return near * (1 - fractionRow) + far * fractionRow;
+ };
+}
diff --git a/src/terrain.js b/src/terrain.js
index 283a832a..e7798cc2 100644
--- a/src/terrain.js
+++ b/src/terrain.js
@@ -2,6 +2,8 @@
// The finest grid is sampled once. Every mesh vertex reads that grid, and heightAt() interpolates it over the same
// triangles as the finest mesh, so vegetation and vehicles sit on the rendered surface.
+import { createSkyVisibilitySampler } from './terrain-sky.js';
+
const DEFAULT_NOISE = Object.freeze({
amplitude: 14,
mountainAmplitude: 46,
@@ -223,6 +225,8 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels
target[offset + 2] = -slopeZ * inverseLength;
}
+ const skyVisibilityAt = createSkyVisibilitySampler({ heights, gridCells, spacing, highest, normalAt: (column, row, target) => gridNormal(column, row, 1, target, 0) });
+
function locate(worldX, worldZ) {
const gridX = clamp((worldX - origin) / spacing, 0, gridCells);
const gridZ = clamp((worldZ - origin) / spacing, 0, gridCells);
@@ -267,6 +271,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels
const positions = new Float32Array(side * side * 3);
const normals = new Float32Array(side * side * 3);
const uvs = new Float32Array(side * side * 2);
+ const skyVisibility = new Float32Array(side * side);
const firstColumn = chunkColumn * resolution;
const firstRow = chunkRow * resolution;
for (let row = 0; row < side; row++) {
@@ -279,6 +284,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels
positions.set([worldX, snappedHeight(column, row, side, step, gridColumn, gridRow, edgeLevels, level), worldZ], vertex * 3);
gridNormal(gridColumn, gridRow, step, normals, vertex * 3);
uvs.set([worldX, worldZ], vertex * 2);
+ skyVisibility[vertex] = skyVisibilityAt(clamp(gridColumn, 0, gridCells), clamp(gridRow, 0, gridCells));
}
}
const indices = new Uint32Array(cells * cells * 6);
@@ -297,7 +303,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels
cursor += 6;
}
}
- return { positions, normals, uvs, indices: cursor === indices.length ? indices : indices.slice(0, cursor) };
+ return { positions, normals, uvs, skyVisibility, indices: cursor === indices.length ? indices : indices.slice(0, cursor) };
}
function snappedHeight(column, row, side, step, gridColumn, gridRow, edgeLevels, level) {
diff --git a/src/tree-sky.js b/src/tree-sky.js
new file mode 100644
index 00000000..65232735
--- /dev/null
+++ b/src/tree-sky.js
@@ -0,0 +1,85 @@
+// Sky visibility inside a tree crown: how much of the sky a leaf card sees through the other leaves around it.
+// Leaf vertices are binned into a coarse grid, and each vertex looks up through the grid along a few directions; the
+// more leaf it passes, the less sky it keeps. The result is stored once, when the tree is built, as one value per vertex.
+
+const GRID_CELLS_ALONG_LONGEST_SIDE = 14;
+// Leaf vertices per cell that cut the sky to 1/e over one cell of path. Fitted once against Cycles on the `foliage` scene.
+const OPACITY_PER_VERTEX = 0.3;
+const MINIMUM_VISIBILITY = 0.04;
+const STEPS_PER_CELL = 2;
+const UP_DIRECTIONS = buildUpDirections();
+
+// One zenith ray and two rings of four rays, 40 and 65 degrees from the zenith.
+function buildUpDirections() {
+ const directions = [[0, 1, 0]];
+ for (const [zenithAngle, phase] of [[40, 0], [65, 45]]) {
+ const sine = Math.sin(zenithAngle * Math.PI / 180);
+ const cosine = Math.cos(zenithAngle * Math.PI / 180);
+ for (let ray = 0; ray < 4; ray++) {
+ const azimuth = (phase + ray * 90) * Math.PI / 180;
+ directions.push([sine * Math.cos(azimuth), cosine, sine * Math.sin(azimuth)]);
+ }
+ }
+ return directions;
+}
+
+function boundsOfPositions(positions) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], positions[offset + axis]);
+ maximum[axis] = Math.max(maximum[axis], positions[offset + axis]);
+ }
+ }
+ return { minimum, maximum };
+}
+
+/**
+ * Returns one sky visibility in 0 to 1 for every vertex of a foliage geometry. `vertexWeight` scales how much leaf each
+ * vertex stands for: a level that keeps fewer leaves passes a larger value for each one.
+ */
+export function computeCrownSkyVisibility(positions, vertexWeight = 1) {
+ const vertexCount = positions.length / 3;
+ const { minimum, maximum } = boundsOfPositions(positions);
+ const longest = Math.max(maximum[0] - minimum[0], maximum[1] - minimum[1], maximum[2] - minimum[2], 1e-6);
+ const cell = longest / GRID_CELLS_ALONG_LONGEST_SIDE;
+ const size = [0, 1, 2].map(axis => Math.floor((maximum[axis] - minimum[axis]) / cell) + 1);
+ const density = new Float32Array(size[0] * size[1] * size[2]);
+ const cellOf = (value, axis) => Math.floor((value - minimum[axis]) / cell);
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ const index = (cellOf(positions[offset + 2], 2) * size[1] + cellOf(positions[offset + 1], 1)) * size[0] + cellOf(positions[offset], 0);
+ density[index] += OPACITY_PER_VERTEX * vertexWeight;
+ }
+ const step = cell / STEPS_PER_CELL;
+ // Visibility is worked out once for each occupied cell, from its centre, and shared by the vertices inside it.
+ const cellVisibility = new Float32Array(density.length).fill(Number.NaN);
+
+ function visibilityOfCell(column, row, layer) {
+ const centre = [minimum[0] + (column + 0.5) * cell, minimum[1] + (row + 0.5) * cell, minimum[2] + (layer + 0.5) * cell];
+ let open = 0;
+ for (const direction of UP_DIRECTIONS) {
+ let opticalDepth = 0;
+ for (let travelled = 0; ; travelled += step) {
+ const probeColumn = cellOf(centre[0] + direction[0] * travelled, 0);
+ const probeRow = cellOf(centre[1] + direction[1] * travelled, 1);
+ const probeLayer = cellOf(centre[2] + direction[2] * travelled, 2);
+ if (probeColumn < 0 || probeLayer < 0 || probeColumn >= size[0] || probeRow >= size[1] || probeLayer >= size[2]) break;
+ opticalDepth += density[(probeLayer * size[1] + probeRow) * size[0] + probeColumn] / STEPS_PER_CELL;
+ }
+ open += Math.exp(-opticalDepth);
+ }
+ return Math.max(MINIMUM_VISIBILITY, open / UP_DIRECTIONS.length);
+ }
+
+ const visibility = new Float32Array(vertexCount);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ const column = cellOf(positions[vertex * 3], 0);
+ const row = cellOf(positions[vertex * 3 + 1], 1);
+ const layer = cellOf(positions[vertex * 3 + 2], 2);
+ const index = (layer * size[1] + row) * size[0] + column;
+ if (Number.isNaN(cellVisibility[index])) cellVisibility[index] = visibilityOfCell(column, row, layer);
+ visibility[vertex] = cellVisibility[index];
+ }
+ return visibility;
+}
diff --git a/src/vegetation.js b/src/vegetation.js
index c51d2222..a4802d88 100644
--- a/src/vegetation.js
+++ b/src/vegetation.js
@@ -13,6 +13,7 @@ import {
createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, randomInRange, scaleVector,
subtractVectors, valueNoise, vectorLength,
} from './vegetation-geometry.js';
+import { computeCrownSkyVisibility } from './tree-sky.js';
import { LEVEL_SETTINGS, SPECIES, TREE_LEVEL_DISTANCES } from './vegetation-species.js';
import { barkTextureDescriptor, leafTextureDescriptor } from './vegetation-textures.js';
@@ -379,6 +380,28 @@ function createMaterials(preset, mode, scannedBark, scannedLeaves) {
};
}
+// Every level describes the same crown, so each vertex of a thinner level stands for more leaf than one of level 0.
+// `skyVisibility` is worked out the first time something reads it (the renderer, when it uploads the geometry), so a
+// tree that is only measured or exported costs nothing extra, and a forest of distinct trees pays for the ones drawn.
+function bakeCrownSkyVisibility(levels) {
+ const foliageOf = level => level.parts.find(part => part.role === 'foliage').geometry;
+ const fullVertexCount = foliageOf(levels[0]).positions.length / 3;
+ for (const level of levels) {
+ const geometry = foliageOf(level);
+ const vertexCount = geometry.positions.length / 3;
+ if (vertexCount === 0) continue;
+ let skyVisibility = null;
+ Object.defineProperty(geometry, 'skyVisibility', {
+ enumerable: true,
+ configurable: true,
+ get() {
+ skyVisibility ??= computeCrownSkyVisibility(geometry.positions, fullVertexCount / vertexCount);
+ return skyVisibility;
+ },
+ });
+ }
+}
+
function boundsOf(geometries) {
const minimum = [Infinity, Infinity, Infinity];
const maximum = [-Infinity, -Infinity, -Infinity];
@@ -425,6 +448,7 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {
{ role: 'foliage', geometry: buildFoliage(skeleton, preset, leaves, levelIndex, levelRandom), material: foliageMaterial, tintable: true },
]);
});
+ bakeCrownSkyVisibility(levels);
return {
kind: 'tree', species: options.species, seed, height, leaves, levels, materials,
distances: TREE_LEVEL_DISTANCES,
diff --git a/tests/sky-visibility.test.js b/tests/sky-visibility.test.js
new file mode 100644
index 00000000..eaade650
--- /dev/null
+++ b/tests/sky-visibility.test.js
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createTerrain } from '../src/terrain.js';
+import { createTree } from '../src/vegetation.js';
+
+function lowestAndMeanOf(values) {
+ let lowest = Infinity;
+ let sum = 0;
+ for (const value of values) {
+ lowest = Math.min(lowest, value);
+ sum += value;
+ }
+ return { lowest, mean: sum / values.length };
+}
+
+test('flat terrain sees the whole sky', () => {
+ const terrain = createTerrain({ size: 256, resolution: 8, chunks: 4, height: () => 3 });
+ for (const part of terrain.parts) {
+ assert.equal(part.geometry.skyVisibility.length, part.geometry.positions.length / 3);
+ for (const value of part.geometry.skyVisibility) assert.equal(value, 1);
+ }
+});
+
+test('a bowl hides part of the sky on its floor and none on its rim', () => {
+ const bowl = (x, z) => 300 * Math.min(1, Math.hypot(x, z) / 400) ** 2;
+ const terrain = createTerrain({ size: 1024, resolution: 16, chunks: 8, height: bowl, eye: [0, 100, 0] });
+ const floorChunk = terrain.parts.find(part => part.name === 'Terrain chunk 4,4').geometry;
+ const floor = lowestAndMeanOf(floorChunk.skyVisibility);
+ assert.ok(floor.mean < 0.8, `bowl floor mean ${floor.mean}`);
+ assert.ok(floor.lowest > 0, 'the floor still sees some sky');
+ const summit = lowestAndMeanOf(terrain.parts.find(part => part.name === 'Terrain chunk 0,0').geometry.skyVisibility);
+ assert.ok(summit.mean > floor.mean);
+ for (const part of terrain.parts) {
+ for (const value of part.geometry.skyVisibility) assert.ok(value >= 0 && value <= 1);
+ }
+});
+
+test('terrain sky visibility is the same on every build', () => {
+ const options = { size: 512, resolution: 8, chunks: 4, seed: 4, eye: [0, 80, 0] };
+ const first = createTerrain(options).parts.map(part => [...part.geometry.skyVisibility]);
+ const second = createTerrain(options).parts.map(part => [...part.geometry.skyVisibility]);
+ assert.deepEqual(first, second);
+});
+
+test('crown vertices inside the leaves see less sky than the outermost ones, at every level', () => {
+ const tree = createTree('broadleaf', 3);
+ for (const level of tree.levels) {
+ const foliage = level.parts.find(part => part.role === 'foliage').geometry;
+ assert.equal(foliage.skyVisibility.length, foliage.positions.length / 3);
+ let highestVertex = 0;
+ for (let vertex = 1; vertex < foliage.skyVisibility.length; vertex++) {
+ if (foliage.positions[vertex * 3 + 1] > foliage.positions[highestVertex * 3 + 1]) highestVertex = vertex;
+ }
+ const { lowest, mean } = lowestAndMeanOf(foliage.skyVisibility);
+ assert.ok(lowest >= 0.04 - 1e-6 && lowest < mean, `level range ${lowest} to ${mean}`);
+ assert.ok(foliage.skyVisibility[highestVertex] > mean, 'the top of the crown sees more sky than the average vertex');
+ }
+});
+
+test('bark and other parts carry no sky visibility', () => {
+ const tree = createTree('broadleaf', 3);
+ assert.equal(tree.levels[0].parts.find(part => part.role === 'bark').geometry.skyVisibility, undefined);
+});