3D engine that AI agents drive
Merge origin/main into feat/vegetation-impostors; move impostor and dither code out of the core
Nguyen Xuan An5f14040d7c04
diff --cc bench/tool-cost-budgets.jsonindex 6661fb40,6661fb40..164195f5--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@@ -1,5 -1,5 +1,4 @@@{-- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681); depth bias line depthBias (issue #310): the scene_capabilities result raised to 17000 (measured 16979); view transforms and looks (issue #282): one viewTransform line in scene_capabilities, so the result is raised to 17020 (measured 16996); both depthBias and viewTransform lines together: raised to 17320 (measured 17292); outlines and toon light (issue #285), after merging depthBias and view transforms: environment.lines is one free record and material toon one short line, total 192150 (measured 192127), scene_create 63800 (measured 63778), scene_apply 45480 (measured 45463), scene_create_asset 19500 (measured 19480), and the scene_capabilities result 17670 (measured 17647) for the lineArt entry; moving cloth colliders and pins (issue #326): result 17880 (measured 17855); retarget from catalog assets, foot lock and morph tracks (issue #325): schemas 192690 (measured 192661), scene_apply 45750 (measured 45729), scene_create_asset 19770 (measured 19746)","schemaTotalBytes": 192690,"schemaToolBytes": {"scene_create": 63800,diff --cc src/impostor-shader.jsindex 908e3a2e,00000000..c79d69e0mode 100644,000000..100644--- a/src/impostor-shader.js+++ b/src/impostor-shader.js@@@ -1,64 -1,0 +1,78 @@@+// GLSL for the `impostor` material tag: one camera-facing card per tree that shows the nearest baked view.+// The card is a quad with corners (+-radius, centerHeight +- radius, 0) and uv (0..1, 0 at the top), built by+// vegetation-impostors.js; the shader recovers radius and center height from any one corner, so the card needs no+// extra attribute. The same function runs in the colour and shadow vertex shaders: in the shadow pass the "eye" is+// the light, so the card shows the tree as the sun sees it.+- import { registerImpostorShaderCode } from './impostor-slots.js';++import { registerAddonGlsl } from './impostor-slots.js';++/** Frames per side of the hemi-octahedral atlas (the atlas holds this many squared views). */+export const IMPOSTOR_FRAMES = 8;+/** The value of `material.tag === 'impostor'` in the instance data. */+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) {+ 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);+}++// 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) {+ 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;+ vec3 center = (modelMatrix * vec4(0.0, centerHeight, 0.0, 1.0)).xyz;+ vec4 apex = inverse(clipMatrix) * vec4(0.0, 0.0, 1.0, 0.0);+ vec3 toEye = normalize(abs(apex.w) > 0.000001 ? apex.xyz / apex.w - center : -apex.xyz);+ vec3 right = cross(vec3(0.0, 1.0, 0.0), toEye);+ float rightLength = length(right);+ right = rightLength > 0.001 ? right / rightLength : vec3(1.0, 0.0, 0.0);+ vec3 cardUp = cross(toEye, right);+ cardNormal = toEye;+ float scale = length(modelMatrix[0].xyz);+ vec3 localDirection = normalize(transpose(mat3(modelMatrix)) * toEye);+ atlasUv = (impostorCell(localDirection) + corner) / ${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;+}+`;++// The hooks sit in main() of the colour and shadow vertex shaders (shaders.js); importing this module installs them.- registerImpostorShaderCode({++materialTags.impostor = IMPOSTOR_TAG;++++// A fade carries its coverage in the opacity: 1 plus the coverage for the outgoing side, 2 plus it for the incoming side.++const ALPHA_COVERAGE = ` if (materialOpacity > 1.0) {++ float biased = materialOpacity - 1.0;++ bool incoming = biased > 1.0;++ float coverage = incoming ? biased - 1.0 : biased;++ float threshold = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));++ if (textureAlpha < alphaCutoff || (incoming ? coverage < 1.0 - threshold : coverage <= threshold)) discard;++ return 1.0;++ }++`;++++registerAddonGlsl({++ alphaCoverage: ALPHA_COVERAGE,+ declarations: impostorShader,+ colorHook: ` vec3 impostorNormal = vec3(0.0, 1.0, 0.0);- bool isImpostor = USES_IMPOSTOR && instanceSurface.w == ${IMPOSTOR_TAG}.0;++ bool isImpostor = instanceSurface.w == ${IMPOSTOR_TAG}.0;+ if (isImpostor) {+ vec2 atlasUv;+ world.xyz = impostorCard(position, uv, instanceMatrix, viewProjection, time, wind, atlasUv, impostorNormal);+ uv = atlasUv;+ }+`,+ normalHook: ` if (isImpostor) worldNormal = impostorNormal;+`,+ depthHook: ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {+ vec3 lightFacing;+ world.xyz = impostorCard(position, uv, instanceMatrix, lightProjection, time, wind, shadowUv, lightFacing);+ }+`,+});diff --cc src/renderer.jsindex 3d11135b,52b07e23..9acac618--- a/src/renderer.js+++ b/src/renderer.js@@@ -1,5 -1,5 +1,6 @@@++import { materialTags } from './shader-registry.js';import { mat4, mat3 } from 'gl-matrix';- import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, createFragmentShader, liquidPassDrawer, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';+ import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';import { postFragment, createPostFragment, POST_STEPS, skyFragment, bloomFragment } from './post.js';import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';import { ambientOcclusionFragment } from './ambient-occlusion.js';@@@ -22,7 -22,7 +23,6 @@@ import { resolveShadowLight, shadowBiasimport { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';const SHADOW_MAP_SIZE = 2048;- const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12, impostor: 13 };-const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });@@@ -198,9 -198,8 +198,8 @@@ function validateAlphaMaterial(materialfunction materialAlphaState(material) {validateAlphaMaterial(material);const alphaMode = material.alphaMode ?? 'opaque';- const alphaCutoff = alphaMode === 'mask' || alphaMode === 'dither' ? material.alphaCutoff ?? 0.5 : 0;- // A dither fade keeps its pixels in the incoming side's half of the pattern: opacity plus one tells the shader.- const opacity = alphaMode === 'opaque' ? 1 : (material.opacity ?? 1) + (alphaMode === 'dither' && material.ditherIncoming === true ? 1 : 0);+ const alphaCutoff = alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0;- const opacity = alphaMode === 'opaque' ? 1 : material.opacity ?? 1;++ const opacity = alphaMode === 'opaque' ? 1 : (material.opacity ?? 1) + (material.opacityBias ?? 0);return [alphaMode, alphaCutoff, opacity, material.doubleSided === true];}@@@ -265,7 -264,7 +264,7 @@@ function packInstance(data, index, partdata[offset + 28] = material.metallic;data[offset + 29] = material.roughness;data[offset + 30] = material.emission ?? 0;-- data[offset + 31] = MATERIAL_TAGS[material.tag] ?? 0;++ data[offset + 31] = materialTags[material.tag] ?? 0;copyVector3(data, offset + 32, part.assembly?.offset ?? ZERO_VECTOR);copyVector3(data, offset + 35, part.assembly?.detailOffset ?? ZERO_VECTOR);copyVector3(data, offset + 38, material.emissiveColor ?? material.color);diff --cc src/shader-registry.jsindex eb909b8b,0e642c15..a2deaae3--- a/src/shader-registry.js+++ b/src/shader-registry.js@@@ -1,15 -1,52 +1,63 @@@- // Tables that addons fill on import, kept apart from shaders.js and renderer.js so an addon can register without- // pulling either into its bundle, and a scene without the addon pays only for the empty slots.+ // Where the optional GLSL and JavaScript of the renderer's features is registered. Addon modules import this small+ // module, not shaders.js, so an addon that only registers its code does not carry the renderer's whole shader text.++ // A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry+ // it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:+ // declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, normalUv+ // (a suffix on the normal map's UV, as in `textureUV * scale + offset`), and the+ // one-line linkSun (a factor on the sun) with linkPoint, linkSpot and linkArea (statements that skip a light for a part).+ // A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.+ export const registeredFeatureCode = new Map();++ // material-layer-shaders.js sets bind(renderer, layerMaps): it binds the textures of material.layerMaps for one batch.+ export const layerTextureSupport = {};++ // view-transform-shader.js sets apply(source, kind, viewTransform, hasLook), bindLook(renderer, program) and dispose(renderer).+ export const viewTransformShader = {};++ // splat-shader.js sets the JavaScript half of the splat ground material: validate, textureBytes, resolveSize,+ // packParameters and buildPixels. The renderer calls them only for a material with layers.+ const splatSupport = {};++ /** The texture units of the splat samplers. */+ export const SPLAT_UNITS = Object.freeze({ splatColor: 11, splatNormal: 12, splatPacked: 13, splatMask: 14 });++ export function registerSplatSupport(functions) {+ Object.assign(splatSupport, functions);+ }++ export function requireSplatSupport() {+ if (!splatSupport.validate) {+ throw new Error("Splat layers need their code: add import '@codepawlhq/67js/addons/splat-shader'.");+ }+ return splatSupport;+ }++ /** Register the GLSL of an optional feature. Called by the module that holds it, on import. */+ export function registerShaderFeatureCode(feature, slots) {+ registeredFeatureCode.set(feature, slots);+ }++ // The addon that registers each feature's code; a feature not listed here is registered by material-layer-shaders.+ const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader' };++ export function requireFeatureCode(feature) {+ const slots = registeredFeatureCode.get(feature);+ if (!slots) {+ const addon = FEATURE_ADDONS[feature] ?? 'material-layer-shaders';+ throw new Error(`The ${feature} feature needs its shader code: add import '@codepawlhq/67js/addons/${addon}' (a recipe: await loadAgentSceneModules(recipe)).`);+ }+ return slots;+ }+++/** Value of `material.tag` in the instance data; the vegetation addon adds `impostor`. */+export const materialTags = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };+- /**- * GLSL the vegetation addon splices into the shaders: `declarations`, `colorHook` and `normalHook` in the colour vertex- * shader, `depthHook` in the shadow vertex shader and `alphaCoverage` in the fragment shader's surfaceAlpha.- */++// GLSL the vegetation addon splices into the shaders: `declarations`, `colorHook` and `normalHook` in the colour vertex++// shader, `depthHook` in the shadow vertex shader and `alphaCoverage` in the fragment shader's surfaceAlpha.+export const addonGlsl = { declarations: '', colorHook: '', normalHook: '', depthHook: '', alphaCoverage: '' };++export function registerAddonGlsl(slots) {+ Object.assign(addonGlsl, slots);+}diff --cc src/shaders.jsindex cd6d6378,675f1df1..f4b67e5b--- a/src/shaders.js+++ b/src/shaders.js@@@ -1,7 -1,8 +1,9 @@@import { MAX_MORPH_TARGETS } from './morph.js';import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';- import { environmentLookupGlsl, environmentShadingGlsl } from './environment-shading.js';- import { impostorGlsl } from './impostor-slots.js';++import { addonGlsl } from './shader-registry.js';+ import { registeredFeatureCode, requireFeatureCode, registerShaderFeatureCode, registerSplatSupport, requireSplatSupport, layerTextureSupport, viewTransformShader, SPLAT_UNITS } from './shader-registry.js';++ export { registerShaderFeatureCode, registerSplatSupport, requireSplatSupport, layerTextureSupport, viewTransformShader, SPLAT_UNITS };const morphingShader = `uniform float morphEnabled;@@@ -138,15 -117,14 +118,15 @@@ out vec3 boxNormalflat out mat3 boxNormalMatrix;${skinningShader()}${morphingShader}- ${windShader}- ${impostorGlsl.declarations}+ ${windShader(features)}++${addonGlsl.declarations}void main() {// A crowd batch reads its joints and weights from the UV and colour attributes, which then carry no texture or tint.vec2 uv = USES_CROWD ? vec2(-1.0) : uvSets.xy;mat4 deformation = USES_CROWD ? crowdTransform() : (USES_SKIN ? skinTransform() : mat4(1.0));vec4 world = instanceMatrix * deformation * vec4(USES_MORPH ? morphedPosition(position) : position, 1.0);world.xyz += USES_CROWD ? vec3(0.0) : assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);- ${impostorGlsl.colorHook} if (USES_WIND) world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);- if (USES_WIND) world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);++${addonGlsl.colorHook} if (USES_WIND) world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);if (USES_WAVES && instanceSurface.w == 3.0) {world.y += sin(world.x * 1.4 + time * 0.8) * 0.025 + sin(world.z * 1.8 - time) * 0.02;}@@@ -157,7 -135,7 +137,7 @@@vec3 localNormal = USES_MORPH ? morphedNormal(normal) : normal;vec3 deformedNormal = (USES_SKIN || USES_CROWD) ? transpose(inverse(mat3(deformation))) * localNormal : localNormal;worldNormal = normalize(instanceNormal * deformedNormal);- ${impostorGlsl.normalHook} // Metres along the object's own axes, so a pattern follows a moving node and is not stretched by its scale.- // Metres along the object's own axes, so a pattern follows a moving node and is not stretched by its scale.++${addonGlsl.normalHook} // Metres along the object's own axes, so a pattern follows a moving node and is not stretched by its scale.boxPosition = (USES_MORPH ? morphedPosition(position) : position) * vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));boxNormal = deformedNormal;boxNormalMatrix = instanceNormal;@@@ -193,16 -171,14 +173,16 @@@ uniform float windout vec2 textureUV;${skinningShader()}${morphingShader}- ${windShader}- ${impostorGlsl.declarations}+ ${windShader(features)}++${addonGlsl.declarations}void main() {vec2 uv = USES_CROWD ? vec2(-1.0) : uvSets.xy;vec4 world = instanceMatrix * (USES_CROWD ? crowdTransform() : skinTransform()) * vec4(morphedPosition(position), 1.0);world.xyz += USES_CROWD ? vec3(0.0) : assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);// Same displacement as the colour pass, so shadows follow the swaying leaves.world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);- textureUV = uv;+ vec2 shadowUv = uv;- ${impostorGlsl.depthHook} textureUV = shadowUv;++${addonGlsl.depthHook} textureUV = shadowUv;gl_Position = lightProjection * world;}`;}@@@ -555,15 -495,7 +499,7 @@@ ${featureCode("worldMossFunction")}// Ofloat surfaceAlpha(float textureAlpha) {if (!USES_ALPHA_MODE) return 1.0;float alpha = materialOpacity * textureAlpha;- if (alphaMode > 2.5) {- // Screen-door fade: opacity above 1 marks the incoming side, which keeps the pixels the outgoing side drops.- bool incoming = materialOpacity > 1.0;- float coverage = incoming ? materialOpacity - 1.0 : materialOpacity;- float threshold = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));- if (textureAlpha < alphaCutoff || (incoming ? coverage < 1.0 - threshold : coverage <= threshold)) discard;- return 1.0;- }-- if (alphaMode > 1.5) return alpha;++${addonGlsl.alphaCoverage} if (alphaMode > 1.5) return alpha;if (alphaToCoverage > 0.5) {float softness = max(fwidth(alpha), 0.0001);alpha = clamp((alpha - alphaCutoff) / softness + 0.5, 0.0, 1.0);diff --cc src/vegetation-impostors.jsindex f209385f,00000000..0cda46cemode 100644,000000..100644--- a/src/vegetation-impostors.js+++ b/src/vegetation-impostors.js@@@ -1,398 -1,0 +1,399 @@@+// Impostors and cross-fades for vegetation levels.+//+// An impostor is a tree drawn as one camera-facing card. `bakeImpostorAtlas` renders the tree from every direction of a+// hemi-octahedral grid into a colour atlas (RGBA) and a normal atlas (tangent space of the view, OpenGL green up), on the+// CPU, so it runs in Node and the browser alike and its pixels repeat exactly. The `impostor` material tag in the vertex+// shader (impostor-shader.js) turns the card to the eye and picks the nearest view. Level changes fade with a screen-door+// dither (`alphaMode: 'dither'`), chosen from the distance alone, so a seek to any camera repeats the same picture.++import { IMPOSTOR_FRAMES } from './impostor-shader.js';++export const FADE_STEPS = 8;+export const IMPOSTOR_CARD_TRIANGLES = 2;+const DEFAULT_FRAME_SIZE = 96;+const DEFAULT_BAKE_LEVEL = 1;+const FRAME_MARGIN_PIXELS = 2;+const EMPTY_BAND = 1e-6;++const impostorCache = new WeakMap();++function srgbToLinear(byte) {+ const value = byte / 255;+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;+}++function linearToSrgbByte(value) {+ const clamped = Math.min(1, Math.max(0, value));+ const encoded = clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;+ return Math.round(encoded * 255);+}++const SRGB_DECODE = Float32Array.from({ length: 256 }, (_, byte) => srgbToLinear(byte));++/** The direction (unit vector from the tree to the eye, in the tree's frame) that atlas cell `column`, `row` was baked from. */+export function impostorFrameDirection(column, row) {+ const squareX = (column + 0.5) / IMPOSTOR_FRAMES * 2 - 1;+ const squareY = (row + 0.5) / IMPOSTOR_FRAMES * 2 - 1;+ const x = (squareX + squareY) / 2;+ const z = (squareX - squareY) / 2;+ const y = 1 - Math.abs(x) - Math.abs(z);+ const length = Math.hypot(x, y, z);+ return [x / length, y / length, z / length];+}++/** The atlas cell the shader picks for a direction to the eye (the same fold as `impostorCell` in impostor-shader.js). */+export function impostorCellOf(direction) {+ const y = Math.max(direction[1], 0);+ const sum = Math.max(Math.abs(direction[0]) + y + Math.abs(direction[2]), 1e-5);+ const squareX = ((direction[0] + direction[2]) / sum) * 0.5 + 0.5;+ const squareY = ((direction[0] - direction[2]) / sum) * 0.5 + 0.5;+ const clampCell = value => Math.min(IMPOSTOR_FRAMES - 1, Math.max(0, Math.floor(value * IMPOSTOR_FRAMES)));+ return { column: clampCell(squareX), row: clampCell(squareY) };+}++/** Right and up of a card that faces `toEye`, as the shader builds them. */+export function impostorCardBasis(toEye) {+ let right = [toEye[2], 0, -toEye[0]];+ const rightLength = Math.hypot(right[0], right[2]);+ right = rightLength > 0.001 ? [right[0] / rightLength, 0, right[2] / rightLength] : [1, 0, 0];+ const up = [+ toEye[1] * right[2] - toEye[2] * right[1],+ toEye[2] * right[0] - toEye[0] * right[2],+ toEye[0] * right[1] - toEye[1] * right[0],+ ];+ return { right, up };+}++function prepareParts(variant, level) {+ return variant.levels[level].parts.map((part) => {+ const { geometry, material } = part;+ const map = material.map?.image?.data ? material.map : null;+ return {+ geometry, map,+ wrap: map ? map.wrapS === 10497 : false,+ baseColor: material.color,+ cutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0,+ };+ });+}++function drawFrame(parts, view, extent, size, buffers) {+ const { colorPixels, normalPixels, depthBuffer, offset, rowStride } = buffers;+ const { right, up, toEye, center } = view;+ const pixelsPerMeter = size / (2 * extent);+ for (const part of parts) {+ const { positions, normals, uvs, colors, indices } = part.geometry;+ const vertexCount = positions.length / 3;+ const screenX = new Float32Array(vertexCount);+ const screenY = new Float32Array(vertexCount);+ const depth = new Float32Array(vertexCount);+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ const x = positions[vertex * 3] - center[0];+ const y = positions[vertex * 3 + 1] - center[1];+ const z = positions[vertex * 3 + 2] - center[2];+ screenX[vertex] = (x * right[0] + y * right[1] + z * right[2]) * pixelsPerMeter + size / 2;+ screenY[vertex] = size / 2 - (x * up[0] + y * up[1] + z * up[2]) * pixelsPerMeter;+ depth[vertex] = x * toEye[0] + y * toEye[1] + z * toEye[2];+ }+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const a = indices[triangle];+ const b = indices[triangle + 1];+ const c = indices[triangle + 2];+ const area = (screenX[b] - screenX[a]) * (screenY[c] - screenY[a]) - (screenX[c] - screenX[a]) * (screenY[b] - screenY[a]);+ if (Math.abs(area) < 1e-9) continue;+ const minimumX = Math.max(0, Math.floor(Math.min(screenX[a], screenX[b], screenX[c])));+ const maximumX = Math.min(size - 1, Math.ceil(Math.max(screenX[a], screenX[b], screenX[c])));+ const minimumY = Math.max(0, Math.floor(Math.min(screenY[a], screenY[b], screenY[c])));+ const maximumY = Math.min(size - 1, Math.ceil(Math.max(screenY[a], screenY[b], screenY[c])));+ for (let pixelY = minimumY; pixelY <= maximumY; pixelY++) {+ for (let pixelX = minimumX; pixelX <= maximumX; pixelX++) {+ const sampleX = pixelX + 0.5;+ const sampleY = pixelY + 0.5;+ const weightA = ((screenX[b] - sampleX) * (screenY[c] - sampleY) - (screenX[c] - sampleX) * (screenY[b] - sampleY)) / area;+ const weightB = ((screenX[c] - sampleX) * (screenY[a] - sampleY) - (screenX[a] - sampleX) * (screenY[c] - sampleY)) / area;+ const weightC = 1 - weightA - weightB;+ if (weightA < 0 || weightB < 0 || weightC < 0) continue;+ const pixelDepth = weightA * depth[a] + weightB * depth[b] + weightC * depth[c];+ const bufferIndex = pixelY * size + pixelX;+ if (pixelDepth <= depthBuffer[bufferIndex]) continue;+ let red = part.baseColor[0];+ let green = part.baseColor[1];+ let blue = part.baseColor[2];+ if (colors) {+ red *= weightA * colors[a * 3] + weightB * colors[b * 3] + weightC * colors[c * 3];+ green *= weightA * colors[a * 3 + 1] + weightB * colors[b * 3 + 1] + weightC * colors[c * 3 + 1];+ blue *= weightA * colors[a * 3 + 2] + weightB * colors[b * 3 + 2] + weightC * colors[c * 3 + 2];+ }+ if (part.map) {+ const u = weightA * uvs[a * 2] + weightB * uvs[b * 2] + weightC * uvs[c * 2];+ const v = weightA * uvs[a * 2 + 1] + weightB * uvs[b * 2 + 1] + weightC * uvs[c * 2 + 1];+ const texel = sampleTexel(part.map, u, v, part.wrap);+ if (texel.alpha / 255 < part.cutoff) continue;+ red *= texel.red;+ green *= texel.green;+ blue *= texel.blue;+ }+ let normalX = weightA * normals[a * 3] + weightB * normals[b * 3] + weightC * normals[c * 3];+ let normalY = weightA * normals[a * 3 + 1] + weightB * normals[b * 3 + 1] + weightC * normals[c * 3 + 1];+ let normalZ = weightA * normals[a * 3 + 2] + weightB * normals[b * 3 + 2] + weightC * normals[c * 3 + 2];+ const normalLength = Math.hypot(normalX, normalY, normalZ) || 1;+ normalX /= normalLength;+ normalY /= normalLength;+ normalZ /= normalLength;+ const facing = normalX * toEye[0] + normalY * toEye[1] + normalZ * toEye[2];+ const flip = facing < 0 ? -1 : 1;+ const tangentX = (normalX * right[0] + normalY * right[1] + normalZ * right[2]) * flip;+ const tangentY = (normalX * up[0] + normalY * up[1] + normalZ * up[2]) * flip;+ const tangentZ = Math.abs(facing);+ depthBuffer[bufferIndex] = pixelDepth;+ const colorIndex = offset + pixelY * rowStride + pixelX * 4;+ colorPixels[colorIndex] = linearToSrgbByte(red);+ colorPixels[colorIndex + 1] = linearToSrgbByte(green);+ colorPixels[colorIndex + 2] = linearToSrgbByte(blue);+ colorPixels[colorIndex + 3] = 255;+ normalPixels[colorIndex] = Math.round((tangentX * 0.5 + 0.5) * 255);+ normalPixels[colorIndex + 1] = Math.round((tangentY * 0.5 + 0.5) * 255);+ normalPixels[colorIndex + 2] = Math.round((tangentZ * 0.5 + 0.5) * 255);+ normalPixels[colorIndex + 3] = 255;+ }+ }+ }+ }+}++const sampledTexel = { red: 0, green: 0, blue: 0, alpha: 0 };++function sampleTexel(map, u, v, wrap) {+ const { width, height, data } = map.image;+ const fractionU = wrap ? u - Math.floor(u) : Math.min(1, Math.max(0, u));+ const fractionV = wrap ? v - Math.floor(v) : Math.min(1, Math.max(0, v));+ const x = Math.min(width - 1, Math.floor(fractionU * width));+ const y = Math.min(height - 1, Math.floor(fractionV * height));+ const index = (y * width + x) * 4;+ sampledTexel.red = SRGB_DECODE[data[index]];+ sampledTexel.green = SRGB_DECODE[data[index + 1]];+ sampledTexel.blue = SRGB_DECODE[data[index + 2]];+ sampledTexel.alpha = data[index + 3];+ return sampledTexel;+}++// Empty pixels take the colour of a covered neighbour (alpha stays 0), so mip levels and filtering never pull in black.+function bleedColors(colorPixels, size, frameColumn, frameRow, atlasWidth) {+ const rowStride = atlasWidth * 4;+ const origin = frameRow * size * rowStride + frameColumn * size * 4;+ for (let pass = 0; pass < 3; pass++) {+ const filled = [];+ for (let pixelY = 0; pixelY < size; pixelY++) {+ for (let pixelX = 0; pixelX < size; pixelX++) {+ const index = origin + pixelY * rowStride + pixelX * 4;+ if (colorPixels[index + 3] !== 0) continue;+ for (const [stepX, stepY] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {+ const neighborX = pixelX + stepX;+ const neighborY = pixelY + stepY;+ if (neighborX < 0 || neighborY < 0 || neighborX >= size || neighborY >= size) continue;+ const neighbor = origin + neighborY * rowStride + neighborX * 4;+ if (colorPixels[neighbor + 3] === 0) continue;+ filled.push([index, neighbor]);+ break;+ }+ }+ }+ for (const [index, neighbor] of filled) {+ colorPixels[index] = colorPixels[neighbor];+ colorPixels[index + 1] = colorPixels[neighbor + 1];+ colorPixels[index + 2] = colorPixels[neighbor + 2];+ colorPixels[index + 3] = 1;+ }+ }+ for (let pixelY = 0; pixelY < size; pixelY++) {+ for (let pixelX = 0; pixelX < size; pixelX++) {+ const index = origin + pixelY * rowStride + pixelX * 4;+ if (colorPixels[index + 3] === 1) colorPixels[index + 3] = 0;+ }+ }+}++/**+ * Bakes `variant` (a tree from `createTree`) into atlases of IMPOSTOR_FRAMES squared views, `frameSize` pixels each.+ * Returns the pixels of the colour and normal atlas and the card: `radius` and `centerHeight` in the tree's meters.+ */+export function bakeImpostorAtlas(variant, { frameSize = DEFAULT_FRAME_SIZE, level = DEFAULT_BAKE_LEVEL } = {}) {+ const minimum = variant.bounds.minimum;+ const maximum = variant.bounds.maximum;+ const center = [(minimum[0] + maximum[0]) / 2, (minimum[1] + maximum[1]) / 2, (minimum[2] + maximum[2]) / 2];+ const radius = Math.hypot(maximum[0] - minimum[0], maximum[1] - minimum[1], maximum[2] - minimum[2]) / 2;+ const cardRadius = radius * frameSize / (frameSize - 2 * FRAME_MARGIN_PIXELS);+ const atlasWidth = frameSize * IMPOSTOR_FRAMES;+ const colorPixels = new Uint8ClampedArray(atlasWidth * atlasWidth * 4);+ const normalPixels = new Uint8ClampedArray(atlasWidth * atlasWidth * 4);+ for (let index = 0; index < normalPixels.length; index += 4) {+ normalPixels[index] = 128;+ normalPixels[index + 1] = 128;+ normalPixels[index + 2] = 255;+ normalPixels[index + 3] = 255;+ }+ const parts = prepareParts(variant, level);+ const depthBuffer = new Float32Array(frameSize * frameSize);+ for (let row = 0; row < IMPOSTOR_FRAMES; row++) {+ for (let column = 0; column < IMPOSTOR_FRAMES; column++) {+ const toEye = impostorFrameDirection(column, row);+ const { right, up } = impostorCardBasis(toEye);+ depthBuffer.fill(-Infinity);+ const offset = row * frameSize * atlasWidth * 4 + column * frameSize * 4;+ drawFrame(parts, { right, up, toEye, center }, cardRadius, frameSize, { colorPixels, normalPixels, depthBuffer, offset, rowStride: atlasWidth * 4 });+ bleedColors(colorPixels, frameSize, column, row, atlasWidth);+ }+ }+ return { width: atlasWidth, height: atlasWidth, colorPixels, normalPixels, radius: cardRadius, centerHeight: center[1], center, frameSize };+}++function textureDescriptor(pixels, size, colorSpace) {+ const data = pixels;+ const image = typeof ImageData === 'undefined' ? { width: size, height: size, data } : new ImageData(data, size, size);+ return { image, colorSpace, wrapS: 33071, wrapT: 33071, minFilter: 9987, magFilter: 9729 };+}++function cardGeometry(radius, centerHeight) {+ return {+ positions: new Float32Array([-radius, centerHeight + radius, 0, radius, centerHeight + radius, 0, radius, centerHeight - radius, 0, -radius, centerHeight - radius, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+}++/** The impostor of a tree variant: `{ geometry, material, bakeMilliseconds }`, baked once and cached on the variant. */+export function getImpostor(variant, options = {}) {+ const cached = impostorCache.get(variant);+ if (cached) return cached;+ const started = performance.now();+ const atlas = bakeImpostorAtlas(variant, options);+ const impostor = {+ geometry: cardGeometry(atlas.radius, atlas.centerHeight),+ material: {+ tag: 'impostor', color: [1, 1, 1], roughness: 0.9, metallic: 0, emission: 0,+ map: textureDescriptor(atlas.colorPixels, atlas.width, 'srgb'),+ normalMap: textureDescriptor(atlas.normalPixels, atlas.width, 'linear'),+ alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true,+ },+ atlasSize: atlas.width,+ bakeMilliseconds: 0,+ };+ impostor.bakeMilliseconds = performance.now() - started;+ impostorCache.set(variant, impostor);+ return impostor;+}++/**+ * Bakes the impostor of every tree variant now, so no frame pays for it. `variants` is `forest.variants` (species to+ * variant arrays) or a list of variants. Returns `{ count, milliseconds }`.+ */+export function prepareImpostors(variants, options = {}) {+ const list = Array.isArray(variants) ? variants : Object.values(variants).flat();+ const started = performance.now();+ let count = 0;+ for (const variant of list) {+ if (variant.kind !== 'tree') continue;+ getImpostor(variant, options);+ count++;+ }+ return { count, milliseconds: performance.now() - started };+}++/**+ * Where a distance falls among level `thresholds`, with a cross-fade of `band` (a fraction) around each one.+ * Returns `{ level, next, step }`: `step` of FADE_STEPS eighths of the way from `level` to `next`; 0 means only `level`.+ * It depends on the distance alone, so a given camera always gives the same answer.+ */+export function blendLevels(distance, thresholds, band) {+ for (let index = 0; index < thresholds.length; index++) {+ const low = thresholds[index] * (1 - band);+ const high = thresholds[index] * (1 + band);+ if (distance < low || (high - low < EMPTY_BAND && distance < thresholds[index])) return { level: index, next: index, step: 0 };+ if (distance <= high && high - low >= EMPTY_BAND) {+ const step = Math.round((distance - low) / (high - low) * FADE_STEPS);+ if (step <= 0) return { level: index, next: index, step: 0 };+ if (step >= FADE_STEPS) return { level: index + 1, next: index + 1, step: 0 };+ return { level: index, next: index + 1, step };+ }+ }+ return { level: thresholds.length, next: thresholds.length, step: 0 };+}++function tintedMaterial(material, tintable, tint) {+ return tintable ? { ...material, color: material.color.map((channel, axis) => channel * tint[axis]) } : material;+}+- function fadedMaterial(material, opacity, incoming) {- return { ...material, alphaMode: 'dither', alphaCutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0.5, opacity, ditherIncoming: incoming };++// A fade is a mask material whose opacity bias carries the dither coverage (see ALPHA_COVERAGE in impostor-shader.js).++function fadedMaterial(material, coverage, incoming) {++ return { ...material, alphaMode: 'mask', alphaCutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0.5, opacityBias: incoming ? 1 + coverage : coverage };+}++function blendParts(instance, level, useImpostor, fade, options) {+ const key = `${useImpostor ? 'i' : level}|${fade ? `${fade.opacity}|${fade.incoming}` : ''}`;+ instance.blendParts ??= new Map();+ if (instance.blendParts.has(key)) return instance.blendParts.get(key);+ const label = `${instance.species} ${instance.index}`;+ const fadeMaterial = material => (fade ? fadedMaterial(material, fade.opacity, fade.incoming) : material);+ let parts;+ if (useImpostor) {+ const impostor = getImpostor(instance.variant, options);+ parts = [{ name: `${label} impostor`, geometry: impostor.geometry, matrix: instance.matrix, material: fadeMaterial(tintedMaterial(impostor.material, true, instance.tint)) }];+ } else {+ parts = instance.variant.levels[level].parts.map(part => ({+ name: `${label} ${part.role}`, geometry: part.geometry, shadowLods: part.shadowLods, matrix: instance.matrix,+ material: fadeMaterial(tintedMaterial(part.material, part.tintable, instance.tint)),+ }));+ }+ instance.blendParts.set(key, parts);+ return parts;+}++/**+ * `selectLevels` with cross-fades and impostors: the level comes from the distance alone (no hysteresis), and within+ * `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 } = {}) {+ const impostorOptions = impostors && typeof impostors === 'object' ? impostors : {};+ const firstImpostorLevel = impostors ? impostorOptions.from ?? 3 : Infinity;+ const parts = [];+ const levelCounts = [];+ let changed = false;+ let culled = 0;+ let triangles = 0;+ let cards = 0;+ let fading = 0;+ 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 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);+ const step = bothCards ? 0 : blend.step;+ const signature = `${blend.level}:${step > 0 ? blend.next : blend.level}:${step}`;+ if (signature !== instance.blendSignature) changed = true;+ instance.blendSignature = signature;+ instance.level = blend.level;+ if (blend.level < 0) {+ culled++;+ continue;+ }+ levelCounts[blend.level] = (levelCounts[blend.level] ?? 0) + 1;+ const drawLevel = (level, opacity, incoming) => {+ const useImpostor = usesCard(level);+ parts.push(...blendParts(instance, level, useImpostor, opacity === 1 ? null : { opacity, incoming }, impostorOptions));+ triangles += useImpostor ? IMPOSTOR_CARD_TRIANGLES : instance.variant.levels[level].triangles;+ if (useImpostor) cards++;+ };+ if (step === 0) {+ drawLevel(blend.level, 1, false);+ } else {+ fading++;+ drawLevel(blend.level, 1 - step / FADE_STEPS, false);+ drawLevel(blend.next, step / FADE_STEPS, true);+ }+ }+ return { parts, changed, levelCounts: Array.from(levelCounts, count => count ?? 0), culled, triangles, impostors: cards, fading };+}diff --cc tests/vegetation-impostors.test.jsindex 30741a32,00000000..c84f8a61mode 100644,000000..100644--- a/tests/vegetation-impostors.test.js+++ b/tests/vegetation-impostors.test.js@@@ -1,153 -1,0 +1,152 @@@+import test from 'node:test';+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,+} from '../src/vegetation-impostors.js';+import { IMPOSTOR_FRAMES, impostorShader } from '../src/impostor-shader.js';+import { createDepthVertexShader, createFragmentShader, createVertexShader } from '../src/shaders.js';++const FAST_BAKE = { frameSize: 32 };+const THRESHOLDS = [38, 95, 150];++function digestOf(pixels) {+ return createHash('sha256').update(pixels).digest('hex');+}++function createForest(treeCount, seed = 5) {+ const side = Math.sqrt(treeCount / 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 });+ return forest;+}++test('every atlas cell is picked from the direction it was baked from', () => {+ for (let row = 0; row < IMPOSTOR_FRAMES; row++) {+ for (let column = 0; column < IMPOSTOR_FRAMES; column++) {+ const direction = impostorFrameDirection(column, row);+ assert.ok(Math.abs(Math.hypot(...direction) - 1) < 1e-9);+ assert.ok(direction[1] > 0);+ assert.deepEqual(impostorCellOf(direction), { column, row });+ }+ }+});++test('the card basis is orthonormal and falls back straight above the tree', () => {+ for (const toEye of [[0.6, 0.5, -0.62], [0, 1, 0], [1, 0.01, 0]]) {+ const length = Math.hypot(...toEye);+ const direction = toEye.map(value => value / length);+ const { right, up } = impostorCardBasis(direction);+ const dot = (first, second) => first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+ assert.ok(Math.abs(dot(right, up)) < 1e-9);+ assert.ok(Math.abs(dot(right, direction)) < 1e-9);+ assert.ok(Math.abs(dot(up, direction)) < 1e-9);+ assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9);+ }+});++test('an atlas bake covers the tree, repeats exactly and keeps unit normals', () => {+ const tree = createTree('broadleaf', 4);+ const first = bakeImpostorAtlas(tree, { ...FAST_BAKE, level: 2 });+ const second = bakeImpostorAtlas(tree, { ...FAST_BAKE, level: 2 });+ assert.equal(digestOf(first.colorPixels), digestOf(second.colorPixels));+ assert.equal(digestOf(first.normalPixels), digestOf(second.normalPixels));+ let covered = 0;+ for (let index = 3; index < first.colorPixels.length; index += 4) if (first.colorPixels[index] === 255) covered++;+ const share = covered / (first.colorPixels.length / 4);+ assert.ok(share > 0.05 && share < 0.6, `covered share ${share}`);+ for (let index = 0; index < first.normalPixels.length; index += 4) {+ if (first.colorPixels[index + 3] !== 255) continue;+ const x = first.normalPixels[index] / 255 * 2 - 1;+ const y = first.normalPixels[index + 1] / 255 * 2 - 1;+ const z = first.normalPixels[index + 2] / 255 * 2 - 1;+ assert.ok(z > -0.02, 'a baked normal never faces away from the view');+ assert.ok(Math.abs(Math.hypot(x, y, z) - 1) < 0.05);+ }+});++test('the impostor card holds the tree and carries the impostor tag', () => {+ const tree = createTree('conifer', 2);+ const impostor = getImpostor(tree, { ...FAST_BAKE, level: 2 });+ assert.equal(getImpostor(tree), impostor, 'the bake is cached on the variant');+ assert.equal(impostor.material.tag, 'impostor');+ assert.equal(impostor.geometry.indices.length, 6);+ assert.ok(impostor.geometry.positions[0] < 0 && impostor.geometry.positions[3] > 0);+ assert.ok(impostor.bakeMilliseconds > 0);+});++test('a distance gives the same blend whatever came before, with eighths between two levels', () => {+ const band = 0.06;+ assert.deepEqual(blendLevels(10, THRESHOLDS, band), { level: 0, next: 0, step: 0 });+ assert.deepEqual(blendLevels(500, THRESHOLDS, band), { level: 3, next: 3, step: 0 });+ assert.deepEqual(blendLevels(38, THRESHOLDS, band), { level: 0, next: 1, step: FADE_STEPS / 2 });+ let previousStep = 0;+ for (let distance = 35; distance < 41.5; distance += 0.05) {+ const blend = blendLevels(distance, THRESHOLDS, band);+ assert.deepEqual(blend, blendLevels(distance, THRESHOLDS, band));+ const fraction = blend.level === 1 ? FADE_STEPS : blend.step;+ assert.ok(fraction >= previousStep, 'the fade only moves one way as the distance grows');+ previousStep = fraction;+ }+ assert.equal(previousStep, FADE_STEPS);+});++test('a fade draws both levels with complementary coverage and repeats for a camera', () => {+ const forest = createForest(300);+ const instance = forest.instances.find(candidate => candidate.variant.kind === 'tree');+ const eye = [instance.position[0] + 38, instance.position[1], instance.position[2]];+ const direct = selectBlendedLevels([instance], eye, { fade: 0.06 });+ assert.equal(direct.fading, 1);- const outgoing = direct.parts.filter(part => part.material.alphaMode === 'dither' && !part.material.ditherIncoming);- const incoming = direct.parts.filter(part => part.material.ditherIncoming);++ const outgoing = direct.parts.filter(part => part.material.opacityBias > 0 && part.material.opacityBias < 1);++ const incoming = direct.parts.filter(part => part.material.opacityBias > 1);+ assert.ok(outgoing.length > 0 && incoming.length > 0);- assert.ok(Math.abs(outgoing[0].material.opacity + incoming[0].material.opacity - 1) < 1e-9);++ assert.ok(Math.abs(outgoing[0].material.opacityBias + incoming[0].material.opacityBias - 1 - 1) < 1e-9);+ selectBlendedLevels([instance], [instance.position[0] + 300, 0, instance.position[2]], { fade: 0.06 });+ const after = selectBlendedLevels([instance], eye, { fade: 0.06 });- assert.deepEqual(after.parts.map(part => [part.name, part.material.opacity, part.material.ditherIncoming]), direct.parts.map(part => [part.name, part.material.opacity, part.material.ditherIncoming]));++ assert.deepEqual(after.parts.map(part => [part.name, part.material.opacityBias]), direct.parts.map(part => [part.name, part.material.opacityBias]));+ assert.equal(selectBlendedLevels([instance], eye, { fade: 0.06 }).changed, false);+ assert.equal(selectBlendedLevels([instance], eye, { fade: 0.06 }).parts[0], direct.parts[0], 'unchanged parts keep their identity');+});++test('selectLevels keeps its hysteresis path unless fade or impostors are asked for', () => {+ const forest = createForest(200);+ const eye = [0, 2, 0];+ const plain = selectLevels(forest.instances, eye, {});+ assert.equal(plain.impostors, undefined);- assert.ok(plain.parts.every(part => part.material.tag !== 'impostor' && part.material.alphaMode !== 'dither'));++ assert.ok(plain.parts.every(part => part.material.tag !== 'impostor' && part.material.opacityBias === undefined));+});++test('impostors replace the last level only beyond its fade band', () => {+ const forest = createForest(600);+ const eye = [0, 2, 0];+ const view = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE } });+ const cards = view.parts.filter(part => part.material.tag === 'impostor');+ assert.equal(cards.length, view.impostors);+ assert.ok(cards.length > 0);+ for (const instance of forest.instances) {+ const distance = Math.hypot(instance.position[0], instance.position[1] - 2, instance.position[2]);+ const hasCard = view.parts.some(part => part.name.startsWith(`${instance.species} ${instance.index} `) && part.material.tag === 'impostor');+ if (instance.variant.kind !== 'tree') continue;+ if (distance < 150 * 0.94) assert.equal(hasCard, false, `${distance} m draws a mesh level`);+ if (distance > 150 * 1.06) assert.equal(hasCard, true, `${distance} m draws a card`);+ }+});++test('a 5,000 tree forest draws far fewer triangles with impostors', () => {+ const forest = createForest(5000);+ const eye = [0, 2, 0];+ const plain = selectLevels(forest.instances, eye, {});+ const withCards = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE } });+ const earlyCards = selectLevels(forest.instances, eye, { impostors: { ...FAST_BAKE, from: 2 } });+ console.log(`trees ${forest.instances.length}, triangles plain ${plain.triangles}, cards from level 3 ${withCards.triangles}, from level 2 ${earlyCards.triangles}`);+ assert.ok(forest.instances.length > 4000);+ assert.ok(withCards.triangles < plain.triangles * 0.25);+ assert.ok(earlyCards.triangles < 1.5e6);+});++test('the shaders carry the card code only where a pass needs it', () => {- assert.match(createVertexShader(['impostor']), /#define USES_IMPOSTOR \(true\)/);- assert.match(createVertexShader([]), /#define USES_IMPOSTOR false/);++ assert.match(createVertexShader([]), /impostorCard\(position, uv, instanceMatrix, viewProjection/);+ assert.match(createDepthVertexShader(), /impostorCard\(position, uv, instanceMatrix, lightProjection/);+ assert.match(impostorShader, new RegExp(`floor\\(square \\* ${IMPOSTOR_FRAMES}\\.0\\)`));- assert.match(createFragmentShader(['alphaMode', 'impostor']), /incoming \? coverage < 1\.0 - threshold : coverage <= threshold/);++ assert.match(createFragmentShader(['alphaMode']), /incoming \? coverage < 1\.0 - threshold : coverage <= threshold/);+});