3D engine that AI agents drive
Blend the four baked views of an impostor card and pick levels by pixel error (part of #324)
Nguyen Xuan An5baf59386566
diff --git a/changes/324.md b/changes/324.mdindex 48fbd109..14afe9a9 100644--- a/changes/324.md+++ b/changes/324.md@@ -1 +1,2 @@- Add baked impostor levels and dithered cross-fades to the vegetation addon (issue #324). `selectLevels(instances, eye, { impostors: { from: 3 }, fade: 0.06 })` draws far trees as one camera-facing card from a 64-view hemi-octahedral colour and normal atlas baked on the CPU (0.6 to 0.7 s for five species in Node), lit by the scene and casting a shadow from the light's side, and cross-fades neighbouring levels with a dither coverage, chosen from the distance alone. A 5,223-tree forest drops from 2.68M to 0.52M triangles with cards from level 3 and 0.36M from level 2 (measured in Node). Both are opt-in, so existing scenes draw as before.+- Impostor cards blend the four baked views around the viewing direction (a stochastic per-pixel pick, so a circling camera no longer steps between 64 views), and `selectLevels` takes `pixelError: { pixels, height, fov }` to set the switch distances from a screen error (part of #324). A frame-difference test checks that a dolly across the card boundary shows no pop.diff --git a/changes/324.size.md b/changes/324.size.mdindex 85e2be52..df67b7c9 100644--- a/changes/324.size.md+++ b/changes/324.size.md@@ -2,3 +2,4 @@- entry:vegetation: the new CPU atlas baker, the card shader code and the cross-fade selection are about 4.2 KB gzip of new addon code.- scene:gltf-box: the same core hooks as entry:core (71 bytes gzip).- scene:gltf-box+lazy: the same core hooks as entry:core (73 bytes).+- entry:vegetation: the view blend in the card shaders and `pixelErrorScale` add a few hundred bytes gzip to the lazy vegetation addon. entry:core, scene:lit-box and scene:agent-scene do not change.diff --git a/docs/culling-lod.md b/docs/culling-lod.mdindex b4a40400..8aef6023 100644--- a/docs/culling-lod.md+++ b/docs/culling-lod.md@@ -34,7 +34,7 @@ An instance uses the coarsest level whose `error` (the farthest its vertices lie## Cross-fades and impostor levels-`lods` switch a mesh by its pixel error and do not fade. The vegetation addon chooses its own levels by distance (`selectLevels`) and can fade between them: `selectLevels(instances, eye, { fade: 0.06 })` draws both levels near a threshold with complementary screen-door coverage (a mask material whose `opacityBias` carries the coverage; the code registers when the vegetation addon is imported), and `impostors` adds a last level that draws one baked card per tree (material tag `impostor`). Culling treats the card as a rigid part: its bounding sphere holds the quad, and the sway is a few centimetres. Both choices depend on the distance only, so they keep the determinism below; see [Vegetation](/vegetation.md#impostors-and-cross-fade).+`lods` switch a mesh by its pixel error and do not fade. The vegetation addon chooses its own levels by distance (`selectLevels`) and can fade between them: `selectLevels(instances, eye, { fade: 0.06 })` draws both levels near a threshold with complementary screen-door coverage (a mask material whose `opacityBias` carries the coverage; the code registers when the vegetation addon is imported), `pixelError: { pixels, height, fov }` sets the switch distances from an error in screen pixels (4 pixels on a 1080 pixel high view with a 60 degree field of view gives the default distances), and `impostors` adds a last level that draws one baked card per tree (material tag `impostor`), which shows a stochastic blend of the four baked views around the viewing direction. Culling treats the card as a rigid part: its bounding sphere holds the quad, and the sway is a few centimetres. These choices depend on the distance and the view only, so they keep the determinism below; see [Vegetation](https://67js.codepawl.com/vegetation.md#impostors-and-cross-fade).## Determinismdiff --git a/docs/vegetation.md b/docs/vegetation.mdindex 68a23c0f..0e49f3a5 100644--- a/docs/vegetation.md+++ b/docs/vegetation.md@@ -132,11 +132,13 @@ prepareImpostors(forest.variants); // bake now, so no frame paysconst view = selectLevels(forest.instances, camera.eye, { impostors: { from: 3 }, fade: 0.06, cullDistance: 900 });```+`pixelError: { pixels, height, fov }` sets the switch distances from an error in screen pixels instead of metres. The default distances (38, 95 and 150 m) hold for 4 pixels on a 1080 pixel high view with a 60 degree vertical field of view; `pixelErrorScale` returns the factor for any other view, and the factor grows with the instance's scale. It works with `fade`, with `impostors` and with the plain selection.+`impostors` (`true` or `{ from, frameSize, level }`) draws every tree from level `from` on (default 3, beyond 150 m) as one card instead of its mesh. `from: 2` starts at 95 m. Bushes and palms take it too; grass and flowers do not. The result gains `impostors` (cards drawn) and `fading` (instances in a cross-fade).An impostor is baked per tree variant on first use, or by `prepareImpostors(variants)`. `bakeImpostorAtlas` draws the tree from 8 by 8 directions of a hemi-octahedral grid (the upper hemisphere, so a view from below the horizon shows the horizon view) into a colour atlas (sRGB, alpha is the leaf mask) and a normal atlas (linear, the tangent space of that view, green up), each 96 px a frame, on the CPU in plain JavaScript: it runs in Node and the browser alike and the pixels repeat exactly. It bakes level 1 of the tree. Instance tint multiplies the colour like it does on the meshes.-The card is a quad with the `impostor` material tag. The vertex shader (`src/impostor-shader.js`) turns it to the eye, picks the atlas cell nearest the view direction in the tree's own frame (so yaw is respected) and sways its top by `frame.wind`; the standard fragment shader then lights it with the sun, the sky and the shadow map like any other surface, using the baked normals. In the shadow pass the "eye" is the light, so the card casts the tree's shadow as the sun sees it, cutout by the baked leaf mask. The card counts 2 triangles.+The card is a quad with the `impostor` material tag. The vertex shader (`src/impostor-shader.js`) turns it to the eye, finds the four atlas views around the view direction in the tree's own frame (so yaw is respected) and sways its top by `frame.wind`; the standard fragment shader then lights it with the sun, the sky and the shadow map like any other surface, using the baked normals. The fragment shader draws each pixel from one of those four views, chosen by their bilinear weights against a screen pattern (a stochastic blend: one sample a pixel, with the mip level and normal basis taken from the card's own uv so they stay smooth), so a camera circling a tree moves through the views without steps. In the shadow pass the "eye" is the light, so the card casts the tree's shadow as the sun sees it, cutout by the baked leaf mask. The card counts 2 triangles.`fade` (a fraction of the switch distance, default 0.06 when `impostors` is on) cross-fades two neighbouring levels over a band of that fraction either side of each threshold: both draw, with a mask material whose `opacityBias` carries the dither coverage (the dither code and the card shader register on import of the addon, so scenes without it do not carry them), and whose coverage in eighths of the way is complementary (a pixel the outgoing level drops is drawn by the incoming one, from the same interleaved-gradient pattern of the screen position). The level and the step come from the distance alone, so a camera position always draws the same picture and a seek repeats. Selection with `fade` or `impostors` keeps no hysteresis, since the band does its job; `changed` is true when any instance moved to another level or step. Shadows draw every level of a fade at full coverage.@@ -150,7 +152,11 @@ Measured (Node, 2026-11-03), 5,223 trees (broadleaf, birch, conifer, bush, 3 varBaking one variant each of the five species takes 0.6 to 0.7 s in Node on the CPU (about 0.14 s a variant; 0.1 s a variant with mesh leaves), and 1.4 to 2.6 s for nine variants in headless Chrome on SwiftShader. `npm run smoke:vegetation-impostors` draws a forest with every level, with cards and with fades, and writes the pictures to `artifacts/`.-The depth of each view is used to resolve hidden surfaces while baking but is not stored, and the card shows the nearest single view with no blending between neighbouring views and no parallax, so a tree seen while the camera circles it steps between 64 views. Both are open work on issue #324.+Measured (2026-11-04, headless Chrome on SwiftShader, `scripts/measure-vegetation-forest.mjs`), the same 5,223 trees seen from the forest edge at 960 by 540: 2,552,514 triangles with every tree at its level and 366,062 with cards from level 3 (5,083 cards). The mean FLIP error of the card picture against the full-level picture is 0.0073 (`scripts/flip-pair.py`). That bounds, loosely, the change in a reference score against Cycles; it is not that score, since no Blender forest scene exists yet, so the 0.005 limit of issue #324 is still open. The forest is open ground, not `large-outdoor` terrain.++`tests/vegetation-pop.test.js` dollies a camera past the card boundary of one tree and measures the mean RGB change between frames: the largest step with the fade is 0.083 and a hard switch at the same place is 0.299, so the test fails above 0.1 or above 0.4 of the hard switch (plain camera motion changes a frame by 0.006 on average). Baking the 12 variants of the forest took 1.3 s in headless Chrome on SwiftShader; the baker runs on the CPU, so the GPU does not change it.++The depth of each view is used to resolve hidden surfaces while baking but is not stored, so the card has no parallax: a tree seen from a changing angle blends views but does not shift its branches.## Measureddiff --git a/scripts/flip-pair.py b/scripts/flip-pair.pynew file mode 100644index 00000000..4393420b--- /dev/null+++ b/scripts/flip-pair.py@@ -0,0 +1,9 @@+# Mean FLIP error between artifacts/forest-pair/plain.png and cards.png (0 means identical).+import flip_evaluator+import numpy as np+from PIL import Image++reference = np.asarray(Image.open("artifacts/forest-pair/plain.png").convert("RGB"), dtype=np.float32) / 255+test = np.asarray(Image.open("artifacts/forest-pair/cards.png").convert("RGB"), dtype=np.float32) / 255+_, mean_error, _ = flip_evaluator.evaluate(reference, test, "LDR", inputsRGB=True)+print(f"mean FLIP {mean_error:.4f}")diff --git a/scripts/measure-vegetation-forest.mjs b/scripts/measure-vegetation-forest.mjsnew file mode 100644index 00000000..90e4d9c6--- /dev/null+++ b/scripts/measure-vegetation-forest.mjs@@ -0,0 +1,69 @@+// Draws a 5,000-tree forest at a fixed camera with every tree at its full level and with impostor cards from level 3, in+// headless Chrome (SwiftShader unless `--gpu`), writes both pictures to artifacts/forest-pair and prints the triangle counts.+// Score the pair with: uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I scripts/flip-pair.py+import { chromium } from 'playwright';+import { spawn } from 'node:child_process';+import { mkdir, writeFile } from 'node:fs/promises';++const port = 5188;+const useGpu = process.argv.includes('--gpu');+const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+let browser;+try {+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('The server did not start.')), 30000);+ server.stdout.on('data', (data) => {+ if (/ready in/.test(data.toString())) {+ clearTimeout(timeout);+ resolve();+ }+ });+ server.on('exit', (code) => reject(new Error(`The server exited ${code}.`)));+ });+ const args = useGpu ? ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] : ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'];+ browser = await chromium.launch({ headless: true, args });+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ page.on('pageerror', error => console.error(error.message));+ await page.goto(`http://127.0.0.1:${port}/`);+ let result;+ for (let attempt = 0; attempt < 4 && !result; attempt++) {+ try {+ result = await page.evaluate(async () => {+ const { scatterVegetation, selectLevels, prepareImpostors } = await import('/src/vegetation.js');+ const { Renderer67 } = await import('/src/renderer.js');+ const side = Math.sqrt(5000 / 0.0035);+ const forest = scatterVegetation({ area: { minX: -side / 2, maxX: side / 2, minZ: -side / 2, maxZ: side / 2 }, density: 0.0035, mix: { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2 }, seed: 5 });+ const bake = prepareImpostors(forest.variants);+ const frame = { eye: [0, 4, -side / 2 + 20], target: [0, 12, 200], up: [0, 1, 0], fov: 45, near: 0.5, far: 1500, time: 1, wind: 0 };+ const canvas = document.createElement('canvas');+ canvas.width = 960;+ canvas.height = 540;+ document.body.append(canvas);+ const draw = (view) => {+ const renderer = new Renderer67(canvas, view.parts, { ground: true, world: true, samples: 1, pixelRatio: 1 });+ renderer.render(frame);+ const picture = canvas.toDataURL('image/png');+ renderer.dispose?.();+ return picture;+ };+ const plainView = selectLevels(forest.instances, frame.eye, {});+ const cardView = selectLevels(forest.instances, frame.eye, { impostors: { from: 3 } });+ return {+ trees: forest.instances.length, bake,+ plainTriangles: plainView.triangles, cardTriangles: cardView.triangles, cards: cardView.impostors,+ pictures: { plain: draw(plainView), cards: draw(cardView) },+ };+ });+ } catch (error) {+ if (!/context was destroyed/.test(error.message)) throw error;+ await page.waitForLoadState('load');+ }+ }+ await mkdir('artifacts/forest-pair', { recursive: true });+ for (const [name, picture] of Object.entries(result.pictures)) await writeFile(`artifacts/forest-pair/${name}.png`, Buffer.from(picture.split(',')[1], 'base64'));+ delete result.pictures;+ console.log(JSON.stringify(result));+} finally {+ await browser?.close();+ server.kill();+}diff --git a/src/impostor-shader.js b/src/impostor-shader.jsindex 015675da..d93012f5 100644--- a/src/impostor-shader.js+++ b/src/impostor-shader.js@@ -12,17 +12,20 @@ export const IMPOSTOR_FRAMES = 8;export const IMPOSTOR_TAG = 13;export const impostorShader = `-// Hemi-octahedral cell of a direction in the tree's own frame; the upper hemisphere fills the square.-vec2 impostorCell(vec3 localDirection) {+// Hemi-octahedral position of a direction in the tree's own frame, in cells: the upper hemisphere fills the square and a+// cell's own view sits at its middle, so the four views around the position can be blended in the fragment shader.+vec2 impostorCellPosition(vec3 localDirection) {vec3 folded = vec3(localDirection.x, max(localDirection.y, 0.0), localDirection.z);folded /= max(abs(folded.x) + folded.y + abs(folded.z), 0.00001);vec2 square = vec2(folded.x + folded.z, folded.x - folded.z) * 0.5 + 0.5;- return clamp(floor(square * ${IMPOSTOR_FRAMES}.0), 0.0, ${IMPOSTOR_FRAMES - 1}.0);+ return square * ${IMPOSTOR_FRAMES}.0 - 0.5;}-// Returns the world position of this corner and the atlas uv of the nearest view. clipMatrix is the matrix of the pass-// (camera or light); the eye is where it projects to w = 0, or for an orthographic pass a direction.-vec3 impostorCard(vec3 localPosition, vec2 corner, mat4 modelMatrix, mat4 clipMatrix, float seconds, float strength, out vec2 atlasUv, out vec3 cardNormal) {+// Returns the world position of this corner, the atlas uv of the first of the four views around the viewing direction+// and viewBlend: the fractions toward the second view along each axis, then the uv step to it (0 at the atlas edge).+// clipMatrix is the matrix of the pass (camera or light); the eye is where it projects to w = 0, or for an orthographic+// pass a direction.+vec3 impostorCard(vec3 localPosition, vec2 corner, mat4 modelMatrix, mat4 clipMatrix, float seconds, float strength, out vec2 atlasUv, out vec4 viewBlend, out vec3 cardNormal) {vec2 side = vec2(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0);float radius = abs(localPosition.x);float centerHeight = localPosition.y - side.y * radius;@@ -36,7 +39,11 @@ vec3 impostorCard(vec3 localPosition, vec2 corner, mat4 modelMatrix, mat4 clipMacardNormal = toEye;float scale = length(modelMatrix[0].xyz);vec3 localDirection = normalize(transpose(mat3(modelMatrix)) * toEye);- atlasUv = (impostorCell(localDirection) + corner) / ${IMPOSTOR_FRAMES}.0;+ vec2 cellPosition = impostorCellPosition(localDirection);+ vec2 firstCell = clamp(floor(cellPosition), 0.0, ${IMPOSTOR_FRAMES - 1}.0);+ vec2 secondCell = clamp(floor(cellPosition) + 1.0, 0.0, ${IMPOSTOR_FRAMES - 1}.0);+ atlasUv = (firstCell + corner) / ${IMPOSTOR_FRAMES}.0;+ viewBlend = vec4(cellPosition - floor(cellPosition), (secondCell - firstCell) / ${IMPOSTOR_FRAMES}.0);float heightFraction = side.y * 0.5 + 0.5;float sway = sin(seconds * 1.2 + center.z * 0.31 + center.x * 0.17) * strength * 0.05 * radius * heightFraction * heightFraction;return center + (right * (side.x * radius + sway) + cardUp * side.y * radius) * scale;@@ -58,10 +65,12 @@ const ALPHA_COVERAGE = ` if (materialOpacity > 1.0) {}`;-const COLOR_HOOK = ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {+const VIEW_BLEND_OUTPUT = 'out vec4 cardViewBlend;\n';+const COLOR_HOOK = ` cardViewBlend = vec4(0.0);+ if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {vec2 atlasUv;vec3 cardNormal;- world.xyz = impostorCard(position, uv, instanceMatrix, viewProjection, time, wind, atlasUv, cardNormal);+ world.xyz = impostorCard(position, uv, instanceMatrix, viewProjection, time, wind, atlasUv, cardViewBlend, cardNormal);uv = atlasUv;worldPosition = world.xyz;worldNormal = cardNormal;@@ -71,8 +80,9 @@ const COLOR_HOOK = ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {const DEPTH_HOOK = ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {vec3 lightFacing;vec2 atlasUv;- world.xyz = impostorCard(position, uv, instanceMatrix, lightProjection, time, wind, atlasUv, lightFacing);- uv = atlasUv;+ vec4 viewBlend;+ world.xyz = impostorCard(position, uv, instanceMatrix, lightProjection, time, wind, atlasUv, viewBlend, lightFacing);+ uv = atlasUv + step(0.5, viewBlend.xy) * viewBlend.zw;}`;@@ -80,12 +90,39 @@ function insertBefore(source, anchor, code) {return source.includes(anchor) ? source.replace(anchor, () => code + anchor) : source;}+// The colour fragment shader samples the atlas through cardUV: the view picked for this pixel among the four around the+// viewing direction, by their bilinear weights against a screen pattern like the fade's (a stochastic blend, so one sample+// a pixel). Gradients still come from textureUV, so mip levels and the normal basis stay smooth across the picks.+const VIEW_BLEND_FRAGMENT = `in vec4 cardViewBlend;+vec2 cardUV;+vec2 pickCardUV() {+ vec2 fraction = cardViewBlend.xy;+ float threshold = fract(52.9829189 * fract(dot(gl_FragCoord.xy + 17.0, vec2(0.06711056, 0.00583715))));+ float afterFirst = (1.0 - fraction.x) * (1.0 - fraction.y);+ float afterSecond = afterFirst + fraction.x * (1.0 - fraction.y);+ float afterThird = afterSecond + (1.0 - fraction.x) * fraction.y;+ vec2 pick = threshold < afterFirst ? vec2(0.0) : threshold < afterSecond ? vec2(1.0, 0.0) : threshold < afterThird ? vec2(0.0, 1.0) : vec2(1.0);+ return textureUV + pick * cardViewBlend.zw;+}+`;++function addViewBlend(source) {+ if (!source.includes('in vec2 textureUV;') || !source.includes('void main() {')) return source;+ const gradients = 'dFdx(textureUV), dFdy(textureUV)';+ return source+ .replace('texture(baseMap, textureUV)', () => `textureGrad(baseMap, cardUV, ${gradients})`)+ .replace(/texture\(normalMap, textureUV([^)]*)\)/, (match, transform) => `textureGrad(normalMap, cardUV${transform}, ${gradients})`)+ .replace('in vec2 textureUV;', () => `in vec2 textureUV;\n${VIEW_BLEND_FRAGMENT}`)+ .replace('void main() {', () => 'void main() {\n cardUV = pickCardUV();');+}+/** Adds the card and dither code to a shader source that has the lines it hooks into; other sources pass through. */export function addImpostorCode(source) {- if (source.includes('float surfaceAlpha(float textureAlpha) {')) return insertBefore(source, ' if (alphaMode > 1.5) return alpha;', ALPHA_COVERAGE);+ if (source.includes('float surfaceAlpha(float textureAlpha) {')) return addViewBlend(insertBefore(source, ' if (alphaMode > 1.5) return alpha;', ALPHA_COVERAGE));if (!source.includes('uniform float wind;') || !source.includes('void main() {')) return source;- const withDefinitions = insertBefore(source, 'void main() {', impostorShader);- if (withDefinitions.includes('worldNormal = normalize(')) return insertBefore(withDefinitions, " // Metres along the object's own axes", COLOR_HOOK);+ const isColor = source.includes('worldNormal = normalize(');+ const withDefinitions = insertBefore(source, 'void main() {', (isColor ? VIEW_BLEND_OUTPUT : '') + impostorShader);+ if (isColor) return insertBefore(withDefinitions, " // Metres along the object's own axes", COLOR_HOOK);return insertBefore(withDefinitions, ' textureUV = uv;\n gl_Position = lightProjection * world;', DEPTH_HOOK);}diff --git a/src/vegetation-impostors.js b/src/vegetation-impostors.jsindex 0cda46ce..d2d16a78 100644--- a/src/vegetation-impostors.js+++ b/src/vegetation-impostors.js@@ -320,6 +320,20 @@ export function blendLevels(distance, thresholds, band) {return { level: thresholds.length, next: thresholds.length, step: 0 };}+// The default switch distances hold for a 4 pixel error on a 1080 pixel high view with a 60 degree vertical field of view.+const REFERENCE_PIXELS_PER_RADIAN = 1080 / (2 * Math.tan(Math.PI / 6));+const REFERENCE_PIXEL_ERROR = 4;++/**+ * The factor on the default switch distances for a level to show an error of at most `pixels` on screen+ * (`{ pixels = 4, height, fov }`: the view's height in pixels and its vertical field of view in degrees).+ * A finer error or a taller view switches later; an instance's own scale multiplies the distance too, since its errors grow with it.+ */+export function pixelErrorScale({ pixels = REFERENCE_PIXEL_ERROR, height = 1080, fov = 60 } = {}) {+ const pixelsPerRadian = height / (2 * Math.tan(fov * Math.PI / 360));+ return pixelsPerRadian / REFERENCE_PIXELS_PER_RADIAN * REFERENCE_PIXEL_ERROR / pixels;+}+function tintedMaterial(material, tintable, tint) {return tintable ? { ...material, color: material.color.map((channel, axis) => channel * tint[axis]) } : material;}@@ -354,7 +368,8 @@ function blendParts(instance, level, useImpostor, fade, options) {* `fade` (a fraction of a threshold, either side) two levels draw with complementary dither coverage.* `impostors` is `true` or `{ from, frameSize, level }`: levels from `from` (default 3, the last) draw the baked card.*/-export function selectBlendedLevels(instances, eye, { distanceScale = 1, fade = 0.06, cullDistance = Infinity, impostors = false } = {}) {+export function selectBlendedLevels(instances, eye, { distanceScale = 1, fade = 0.06, cullDistance = Infinity, impostors = false, pixelError = null } = {}) {+ const pixelScale = pixelError ? pixelErrorScale(pixelError) : 1;const impostorOptions = impostors && typeof impostors === 'object' ? impostors : {};const firstImpostorLevel = impostors ? impostorOptions.from ?? 3 : Infinity;const parts = [];@@ -367,7 +382,7 @@ export function selectBlendedLevels(instances, eye, { distanceScale = 1, fade =for (const instance of instances) {const distance = Math.hypot(eye[0] - instance.position[0], eye[1] - instance.position[1], eye[2] - instance.position[2]);const culledNow = distance > cullDistance;- const thresholds = instance.variant.distances.map(threshold => threshold * distanceScale);+ const thresholds = instance.variant.distances.map(threshold => threshold * distanceScale * pixelScale * (pixelError ? instance.scale : 1));const blend = culledNow ? { level: -1, next: -1, step: 0 } : blendLevels(distance, thresholds, fade);const usesCard = level => instance.variant.kind === 'tree' && level >= firstImpostorLevel;const bothCards = blend.step > 0 && usesCard(blend.level) && usesCard(blend.next);diff --git a/src/vegetation.js b/src/vegetation.jsindex 1bb64074..93124bdd 100644--- a/src/vegetation.js+++ b/src/vegetation.js@@ -17,9 +17,9 @@ import {import { computeCrownSkyVisibility } from './tree-sky.js';import { LEVEL_SETTINGS, SPECIES, TREE_LEVEL_DISTANCES } from './vegetation-species.js';import { barkTextureDescriptor, leafTextureDescriptor } from './vegetation-textures.js';-import { selectBlendedLevels } from './vegetation-impostors.js';+import { pixelErrorScale, selectBlendedLevels } from './vegetation-impostors.js';-export { prepareImpostors, getImpostor, bakeImpostorAtlas, blendLevels } from './vegetation-impostors.js';+export { prepareImpostors, getImpostor, bakeImpostorAtlas, blendLevels, pixelErrorScale } from './vegetation-impostors.js';const DEFAULT_FADE_BAND = 0.06;export { SPECIES };@@ -749,16 +749,17 @@ function nextLevel(currentLevel, distance, thresholds, hysteresis, cullDistance)* `fade` (a fraction, such as 0.06) cross-fades neighbouring levels with a dither; `impostors` (`true` or `{ from }`) draws the baked card from level `from` (default 3) on. Either one picks the level from the distance alone, with no hysteresis.* Returns `{ parts, changed, levelCounts, culled, triangles }` (`culled` counts instances past `cullDistance`); rebuild or update the renderer when `changed` is true.*/-export function selectLevels(instances, eye, { distanceScale = 1, hysteresis = 0.12, cullDistance = Infinity, fade = 0, impostors = false } = {}) {- if (fade > 0 || impostors) return selectBlendedLevels(instances, eye, { distanceScale, fade: fade || DEFAULT_FADE_BAND, cullDistance, impostors });+export function selectLevels(instances, eye, { distanceScale = 1, hysteresis = 0.12, cullDistance = Infinity, fade = 0, impostors = false, pixelError = null } = {}) {+ if (fade > 0 || impostors) return selectBlendedLevels(instances, eye, { distanceScale, fade: fade || DEFAULT_FADE_BAND, cullDistance, impostors, pixelError });const parts = [];const levelCounts = [];let changed = false;let culled = 0;let triangles = 0;+ const pixelScale = pixelError ? pixelErrorScale(pixelError) : 1;for (const instance of instances) {const distance = Math.hypot(eye[0] - instance.position[0], eye[1] - instance.position[1], eye[2] - instance.position[2]);- const thresholds = instance.variant.distances.map(threshold => threshold * distanceScale);+ const thresholds = instance.variant.distances.map(threshold => threshold * distanceScale * pixelScale * (pixelError ? instance.scale : 1));const level = nextLevel(instance.level, distance, thresholds, hysteresis, cullDistance);if (level !== instance.level) changed = true;instance.level = level;diff --git a/tests/vegetation-impostors.test.js b/tests/vegetation-impostors.test.jsindex 02719042..2f5145fd 100644--- a/tests/vegetation-impostors.test.js+++ b/tests/vegetation-impostors.test.js@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { createHash } from 'node:crypto';import { createTree, scatterVegetation, selectLevels } from '../src/vegetation.js';import {- bakeImpostorAtlas, blendLevels, FADE_STEPS, getImpostor, impostorCardBasis, impostorCellOf, impostorFrameDirection, selectBlendedLevels,+ bakeImpostorAtlas, blendLevels, FADE_STEPS, getImpostor, impostorCardBasis, impostorCellOf, impostorFrameDirection, pixelErrorScale, selectBlendedLevels,} from '../src/vegetation-impostors.js';import { addImpostorCode, IMPOSTOR_FRAMES, impostorShader } from '../src/impostor-shader.js';import { createDepthVertexShader, createFragmentShader, createVertexShader, depthFragmentShader } from '../src/shaders.js';@@ -149,8 +149,23 @@ test('the impostor code is added to the three shaders it hooks into and to nothiassert.ok(colour.includes("impostorCard(position, uv, instanceMatrix, viewProjection"));assert.ok(colour.includes("worldNormal = cardNormal"));assert.ok(addImpostorCode(createDepthVertexShader()).includes("impostorCard(position, uv, instanceMatrix, lightProjection"));- assert.ok(impostorShader.includes(`floor(square * ${IMPOSTOR_FRAMES}.0)`));+ assert.ok(impostorShader.includes(`square * ${IMPOSTOR_FRAMES}.0 - 0.5`));+ assert.ok(addImpostorCode(createFragmentShader(["alphaMode"])).includes("textureGrad(baseMap, cardUV"));assert.ok(addImpostorCode(createFragmentShader(["alphaMode"])).includes("incoming ? coverage < 1.0 - threshold : coverage <= threshold"));assert.equal(addImpostorCode(depthFragmentShader), depthFragmentShader);assert.equal(createVertexShader([]).includes('impostorCard'), false, 'the core shaders carry none of it');});++test('a pixel error moves the switch distances with the view and the tree size', () => {+ assert.ok(Math.abs(pixelErrorScale({}) - 1) < 1e-9, 'the defaults are the reference view');+ assert.ok(Math.abs(pixelErrorScale({ pixels: 2 }) - 2) < 1e-9, 'half the error switches twice as far');+ assert.ok(pixelErrorScale({ height: 2160 }) > 1.99 && pixelErrorScale({ height: 2160 }) < 2.01);+ assert.ok(pixelErrorScale({ fov: 30 }) > pixelErrorScale({ fov: 60 }), 'a narrower view magnifies, so levels switch later');+ const forest = createForest(300);+ const eye = [0, 2, 0];+ const reference = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE } });+ const sameView = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE }, pixelError: { pixels: 4, height: 1080, fov: 60 } });+ const finer = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE }, pixelError: { pixels: 1, height: 1080, fov: 60 } });+ assert.ok(sameView.triangles >= reference.triangles * 0.5 && sameView.triangles <= reference.triangles * 2);+ assert.ok(finer.triangles > sameView.triangles, 'a finer error keeps more triangles');+});diff --git a/tests/vegetation-pop.test.js b/tests/vegetation-pop.test.jsnew file mode 100644index 00000000..9c864510--- /dev/null+++ b/tests/vegetation-pop.test.js@@ -0,0 +1,117 @@+// Frame-difference pop test: dollies a camera slowly across the level boundary where trees become impostor cards and+// compares the largest single-frame change with a hard switch at the same place.+// It draws in headless Chrome (SwiftShader, no GPU) from the Vite dev server, and skips when Chrome cannot start.+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';++// A pop is a single-frame change of the mean RGB value (0 to 1) above this, or above this share of the change a hard switch+// makes in one frame. Measured 2026-11-04 on SwiftShader: the fade's largest step is 0.083, a hard switch is 0.30, and plain+// camera motion over the same dolly changes a frame by 0.006 on average and 0.010 at most.+const POP_THRESHOLD = 0.1;+const HARD_SWITCH_RATIO = 0.4;+const PORT = 5187;++async function startServer() {+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(PORT), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('The dev server did not start.')), 30000);+ server.stdout.on('data', (data) => {+ if (/ready in/.test(data.toString())) {+ clearTimeout(timeout);+ resolve();+ }+ });+ server.on('exit', (code) => {+ clearTimeout(timeout);+ reject(new Error(`The dev server exited ${code}.`));+ });+ });+ return server;+}++async function evaluateWithRetry(page, task, argument) {+ for (let attempt = 0; ; attempt++) {+ try {+ return await page.evaluate(task, argument);+ } catch (error) {+ if (attempt >= 3 || !/context was destroyed/.test(error.message)) throw error;+ await page.waitForLoadState('load');+ }+ }+}++// Draws one frame per camera distance and returns the mean absolute RGB change (0 to 1) between neighbouring frames.+async function frameChanges(page, settings) {+ return evaluateWithRetry(page, async (options) => {+ const { scatterVegetation, selectLevels, prepareImpostors } = await import('/src/vegetation.js');+ const { Renderer67 } = await import('/src/renderer.js');+ const forest = scatterVegetation({ area: { minX: -2, maxX: 2, minZ: -2, maxZ: 2 }, density: 0.05, mix: { broadleaf: 1 }, seed: 5 });+ const tree = forest.instances.slice(0, 1);+ prepareImpostors(forest.variants, { frameSize: 96 });+ const width = 320;+ const height = 180;+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ document.body.append(canvas);+ const copy = document.createElement('canvas');+ copy.width = width;+ copy.height = height;+ const copyContext = copy.getContext('2d', { willReadFrequently: true });+ const changes = [];+ let previous = null;+ for (let step = 0; step <= options.steps; step++) {+ const distance = options.start + (options.end - options.start) * step / options.steps;+ const eye = [tree[0].position[0], 4, tree[0].position[2] + distance];+ const view = selectLevels(tree, eye, { impostors: { from: 3 }, fade: options.fade, distanceScale: options.distanceScale });+ const renderer = new Renderer67(canvas, view.parts, { ground: true, world: true, samples: 1, pixelRatio: 1 });+ renderer.render({ eye, target: [tree[0].position[0], 6, tree[0].position[2]], up: [0, 1, 0], fov: 50, near: 0.5, far: 1500, time: 1, wind: 0 });+ copyContext.drawImage(canvas, 0, 0);+ const pixels = copyContext.getImageData(0, 0, width, height).data;+ renderer.dispose?.();+ if (previous) {+ let total = 0;+ for (let index = 0; index < pixels.length; index += 4) {+ total += Math.abs(pixels[index] - previous[index]) + Math.abs(pixels[index + 1] - previous[index + 1]) + Math.abs(pixels[index + 2] - previous[index + 2]);+ }+ changes.push(total / (pixels.length / 4 * 3 * 255));+ }+ previous = pixels;+ }+ return changes;+ }, settings);+}++test('a slow dolly across the impostor boundary shows no pop in a frame difference', async (context) => {+ let chromium;+ try {+ ({ chromium } = await import('playwright'));+ } catch {+ context.skip('playwright is not installed');+ return;+ }+ const server = await startServer();+ let browser;+ try {+ try {+ browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+ } catch (error) {+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);+ return;+ }+ const page = await browser.newPage({ viewport: { width: 320, height: 180 } });+ await page.goto(`http://127.0.0.1:${PORT}/`);+ // One tree fills the view. With the switch distances scaled by 0.05 its card begins at 7.5 m, so the dolly from 6 to 9.5 m crosses the whole fade band.+ const crossing = { start: 6, end: 9.5, steps: 40, fade: 0.06, distanceScale: 0.05 };+ const withFade = await frameChanges(page, crossing);+ const hardSwitch = await frameChanges(page, { ...crossing, fade: 0.0001 });+ const largest = values => Math.max(...values);+ console.log(JSON.stringify({ withFade: largest(withFade), hardSwitch: largest(hardSwitch) }));+ assert.ok(largest(withFade) < POP_THRESHOLD, `the fade jumps ${largest(withFade)} in one frame`);+ assert.ok(largest(withFade) < largest(hardSwitch) * HARD_SWITCH_RATIO, `the fade jumps ${largest(withFade)} against ${largest(hardSwitch)} for a hard switch`);+ } finally {+ await browser?.close();+ server.kill();+ }+});