3D engine that AI agents drive
Install the impostor and dither GLSL by a source transform, so shaders.js carries none of it
Nguyen Xuan An06f83510f655
diff --git a/src/gl-program.js b/src/gl-program.jsindex bf925111..e935f4ad 100644--- a/src/gl-program.js+++ b/src/gl-program.js@@ -1,5 +1,7 @@// Shader program helpers shared by the renderer and its optional addons, kept apart so an addon does not pull in the renderer.+import { shaderTransforms } from './shader-registry.js';+export const fullscreenVertex = `#version 300 esprecision highp float;out vec2 textureCoordinate;@@ -16,7 +18,7 @@ export function startProgram(context, vertexSource, fragmentSource) {const shaders = [];for (const [kind, source] of [[context.VERTEX_SHADER, vertexSource], [context.FRAGMENT_SHADER, fragmentSource]]) {const shader = context.createShader(kind);- context.shaderSource(shader, source);+ context.shaderSource(shader, shaderTransforms.reduce((text, transform) => transform(text), source));context.compileShader(shader);context.attachShader(program, shader);shaders.push(shader);diff --git a/src/impostor-shader.js b/src/impostor-shader.jsindex 9e6a8248..0524d0eb 100644--- a/src/impostor-shader.js+++ b/src/impostor-shader.js@@ -4,7 +4,7 @@// 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 { materialTags, addonGlsl } from './shader-registry.js';+import { materialTags, shaderTransforms } from './shader-registry.js';/** Frames per side of the hemi-octahedral atlas (the atlas holds this many squared views). */export const IMPOSTOR_FRAMES = 8;@@ -43,7 +43,8 @@ vec3 impostorCard(vec3 localPosition, vec2 corner, mat4 modelMatrix, mat4 clipMa}`;-// The hooks sit in main() of the colour and shadow vertex shaders (shaders.js); importing this module installs them.+// Importing this module installs a transform that startProgram applies to every shader source: it inserts the card code+// before known lines of the colour vertex, shadow vertex and fragment shaders, so shaders.js carries none of it.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.@@ -57,10 +58,7 @@ const ALPHA_COVERAGE = ` if (materialOpacity > 1.0) {}`;-Object.assign(addonGlsl, {- alpha: ALPHA_COVERAGE,- defs: impostorShader,- color: ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {+const COLOR_HOOK = ` if (instanceSurface.w == ${IMPOSTOR_TAG}.0) {vec2 atlasUv;vec3 cardNormal;world.xyz = impostorCard(position, uv, instanceMatrix, viewProjection, time, wind, atlasUv, cardNormal);@@ -68,12 +66,28 @@ Object.assign(addonGlsl, {worldPosition = world.xyz;worldNormal = cardNormal;}-`,- depth: ` 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;}-`,-});+`;++function insertBefore(source, anchor, code) {+ return source.includes(anchor) ? source.replace(anchor, () => code + anchor) : source;+}++/** 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('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);+ return insertBefore(withDefinitions, ' textureUV = uv;+ gl_Position = lightProjection * world;', DEPTH_HOOK);+}++shaderTransforms.push(addImpostorCode);diff --git a/src/shader-registry.js b/src/shader-registry.jsindex d5f6209a..1a8ed738 100644--- a/src/shader-registry.js+++ b/src/shader-registry.js@@ -54,8 +54,8 @@ export function requireFeatureCode(feature) {/** 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: `defs` and `color` in the colour vertex shader, `defs` and `depth` in the shadow vertex shader and `alpha` in the fragment shader's surfaceAlpha.-export const addonGlsl = { defs: '', color: '', depth: '', alpha: '' };+// Functions from source to source that startProgram applies to every shader before compiling it; the vegetation addon adds its card code here.+export const shaderTransforms = [];/** The most morph targets one geometry carries; the morph shader's weight array has this length. */export const MAX_MORPH_TARGETS = 64;diff --git a/src/shaders.js b/src/shaders.jsindex 3b5a0d08..9d384535 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -1,5 +1,4 @@import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.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 };@@ -88,7 +87,6 @@ flat out mat3 boxNormalMatrix;${skinningShader(features)}${morphingShader(features)}${windShader(features)}-${addonGlsl.defs}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;@@ -106,7 +104,7 @@ void main() {vec3 localNormal = USES_MORPH ? morphedNormal(normal) : normal;vec3 deformedNormal = (USES_SKIN || USES_CROWD) ? transpose(inverse(mat3(deformation))) * localNormal : localNormal;worldNormal = normalize(instanceNormal * deformedNormal);-${addonGlsl.color} // 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.boxPosition = (USES_MORPH ? morphedPosition(position) : position) * vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));boxNormal = deformedNormal;boxNormalMatrix = instanceNormal;@@ -143,14 +141,13 @@ out vec2 textureUV;${skinningShader(features)}${morphingShader(features)}${windShader(features)}-${addonGlsl.defs}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);-${addonGlsl.depth} textureUV = uv;+ textureUV = uv;gl_Position = lightProjection * world;}`;}@@ -467,7 +464,7 @@ ${featureCode("worldMossFunction")}// Opaque draws 1, mask resolves to a cutoutfloat surfaceAlpha(float textureAlpha) {if (!USES_ALPHA_MODE) return 1.0;float alpha = materialOpacity * textureAlpha;-${addonGlsl.alpha} if (alphaMode > 1.5) return alpha;+ 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 --git a/tests/vegetation-impostors.test.js b/tests/vegetation-impostors.test.jsindex c84f8a61..02719042 100644--- a/tests/vegetation-impostors.test.js+++ b/tests/vegetation-impostors.test.js@@ -5,8 +5,8 @@ import { createTree, scatterVegetation, selectLevels } from '../src/vegetation.jimport {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';+import { addImpostorCode, IMPOSTOR_FRAMES, impostorShader } from '../src/impostor-shader.js';+import { createDepthVertexShader, createFragmentShader, createVertexShader, depthFragmentShader } from '../src/shaders.js';const FAST_BAKE = { frameSize: 32 };const THRESHOLDS = [38, 95, 150];@@ -144,9 +144,13 @@ test('a 5,000 tree forest draws far fewer triangles with impostors', () => {assert.ok(earlyCards.triangles < 1.5e6);});-test('the shaders carry the card code only where a pass needs it', () => {- 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']), /incoming \? coverage < 1\.0 - threshold : coverage <= threshold/);+test('the impostor code is added to the three shaders it hooks into and to nothing else', () => {+ const colour = addImpostorCode(createVertexShader([]));+ assert.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(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');});