3D engine that AI agents drive
Draw the post pass with only the steps a frame uses (Part of #74)
Nguyen Xuan Ane9c01af71770
diff --git a/src/post.js b/src/post.jsindex 27ba77de..dfb994dd 100644--- a/src/post.js+++ b/src/post.js@@ -1,6 +1,8 @@export { fullscreenVertex } from './gl-program.js';-export const postFragment = `#version 300 es+function postFragmentSource(definitions) {+ return `#version 300 es+${definitions}precision highp float;in vec2 textureCoordinate;uniform sampler2D frameTexture;@@ -163,9 +165,9 @@ void main() {float secondLuma = luminance(second);vec3 color = secondLuma < minimumLuma || secondLuma > maximumLuma ? first : second;if (maximumLuma - minimumLuma < max(0.03, maximumLuma * 0.125)) color = center;- float coverage = texture(frameTexture, textureCoordinate).a;- if (transparent > 0.5) color = center / max(coverage, 0.00001);- if (occlusionStrength > 0.0) {+ float coverage = POST_TRANSPARENT ? texture(frameTexture, textureCoordinate).a : 1.0;+ if (POST_TRANSPARENT) color = center / max(coverage, 0.00001);+ if (POST_OCCLUSION) {float visibility = 0.0;for (int row = -1; row <= 1; row++) {for (int column = -1; column <= 1; column++) {@@ -176,13 +178,14 @@ void main() {float directShare = 1.0 / (1.0 + 0.4 * luminance(color));color *= mix(1.0, visibility / 9.0, occlusionStrength * directShare);}- if (bloomStrength > 0.0) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;- if (volumeDensity > 0.0) color = volumeFog(color);+ if (POST_BLOOM) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;+ if (POST_VOLUME) color = volumeFog(color);if (hdrEnabled > 0.5) {color = clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);color = pow(color, vec3(1.0 / 2.2));}- if (volumeExplosion > 0.5) color = explosion(color);+ if (POST_EXPLOSION) color = explosion(color);+ if (POST_FINISH) {color = mix(color, vec3(luminance(color)), monochrome);if (grade.x != 1.0) color = mix(vec3(luminance(color)), color, grade.x);if (grade.y != 1.0) color = (color - 0.5) * grade.y + 0.5;@@ -191,9 +194,11 @@ void main() {color *= max(0.0, 1.0 - (cinematic * 0.20 + vignette) * dot(centered, centered));float grain = fract(sin(dot(gl_FragCoord.xy + floor(time * 24.0), vec2(12.9898, 78.233))) * 43758.5453) - 0.5;color += grain * (0.018 * cinematic + grainAmount);- float alpha = transparent > 0.5 ? coverage : 1.0;+ }+ float alpha = POST_TRANSPARENT ? coverage : 1.0;outputColor = vec4(color * (1.0 - fade) * alpha, alpha);}`;+}export const skyFragment = `#version 300 esprecision highp float;@@ -249,3 +254,27 @@ void main() {color += sampleBloom(textureCoordinate - texelDirection * 3.230769) * 0.070270;outputColor = vec4(color, 1.0);}`;++// Every optional step of the post pass, with the GLSL condition that turns it on. SwiftShader pays for a step that a+// uniform switches off, so a frame that uses few steps draws with a program that has the others compiled out.+const POST_STEP_CONDITIONS = {+ transparent: ['POST_TRANSPARENT', 'transparent > 0.5'],+ occlusion: ['POST_OCCLUSION', 'occlusionStrength > 0.0'],+ bloom: ['POST_BLOOM', 'bloomStrength > 0.0'],+ volume: ['POST_VOLUME', 'volumeDensity > 0.0'],+ explosion: ['POST_EXPLOSION', 'volumeExplosion > 0.5'],+ finish: ['POST_FINISH', 'true'],+};++export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS));++/** The post pass with only the listed steps compiled in; every step is switched by its uniform, as before. */+export function createPostFragment(steps = POST_STEPS) {+ const enabled = new Set(steps);+ const definitions = Object.entries(POST_STEP_CONDITIONS)+ .map(([step, [macro, condition]]) => `#define ${macro} ${enabled.has(step) ? `(${condition})` : 'false'}`)+ .join('\n');+ return postFragmentSource(definitions);+}++export const postFragment = createPostFragment();diff --git a/src/renderer.js b/src/renderer.jsindex eb3652c2..ddce0e89 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1,6 +1,6 @@import { mat4, mat3 } from 'gl-matrix';import { layerTextureSupport, vertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';-import { postFragment, skyFragment, bloomFragment } from './post.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';import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';@@ -36,6 +36,12 @@ const SWAYING_TAGS = new Set(['foliage', 'grass']);// Tags whose vertex shader moves vertices away from the instance matrix, so a bounding sphere would not hold.const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);+const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];++function postUniformLocations(context, program) {+ return Object.fromEntries(POST_UNIFORMS.map(name => [name, context.getUniformLocation(program, name)]));+}+const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];// Tags whose look the main fragment shader draws with code that other tags never reach.const TAG_SHADER_FEATURES = new Set(['floor', 'water', 'foliage', 'terrain', 'grass', 'fire', 'smoke', 'unlit']);@@ -509,7 +515,8 @@ export class Renderer67 {if (!benchmark) {this.postProgram = finishProgram(this.context, pending.post);this.skyProgram = finishProgram(this.context, pending.sky);- this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));+ this.postUniforms = postUniformLocations(this.context, this.postProgram);+ this.postVariants = new Map();this.bloomProgram = finishProgram(this.context, pending.bloom);this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));@@ -1519,6 +1526,41 @@ export class Renderer67 {context.drawArrays(context.TRIANGLES, 0, 3);}+ // The post steps this frame uses. A step that is off costs nothing in a program that has it compiled out.+ postStepsOf(frame, effects, volume, occluded) {+ const steps = [];+ if (this.transparent) steps.push('transparent');+ if (occluded) steps.push('occlusion');+ if (effects.bloom.strength > 0) steps.push('bloom');+ if (volume.density > 0) steps.push('volume');+ if (frame.volumeExplosion) steps.push('explosion');+ const gradesColor = effects.saturation !== 1 || effects.contrast !== 1 || effects.temperature !== 0;+ const finishes = gradesColor || (frame.monochrome ?? 0) !== 0 || Boolean(frame.cinematic) || effects.vignette !== 0 || effects.grain !== 0;+ if (finishes) steps.push('finish');+ return steps;+ }++ // Compiles a program for the steps of this frame the first time they occur. The program with every step stays in use+ // until the driver has finished building the new one, so a step that appears later does not stall a frame.+ selectPostProgram(steps) {+ if (steps.length === POST_STEPS.length) return { program: this.postProgram, uniforms: this.postUniforms };+ const key = steps.join(',');+ let variant = this.postVariants.get(key);+ if (!variant) {+ variant = { pending: startProgram(this.context, fullscreenVertex, createPostFragment(steps)) };+ this.postVariants.set(key, variant);+ }+ if (variant.pending) {+ const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');+ const building = parallelCompile && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);+ if (building) return { program: this.postProgram, uniforms: this.postUniforms };+ variant.program = finishProgram(this.context, variant.pending);+ variant.uniforms = postUniformLocations(this.context, variant.program);+ variant.pending = null;+ }+ return variant;+ }+resolveFrame(frame, effects, environment, volume) {const context = this.context;context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);@@ -1534,54 +1576,55 @@ export class Renderer67 {context.disable(context.DEPTH_TEST);context.disable(context.CULL_FACE);context.bindVertexArray(null);- context.useProgram(this.postProgram);+ const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded));+ context.useProgram(post.program);context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, sourceTexture);- context.uniform1i(this.postUniforms.frameTexture, 0);+ context.uniform1i(post.uniforms.frameTexture, 0);context.activeTexture(context.TEXTURE1);context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);- context.uniform1i(this.postUniforms.sceneDepth, 1);+ context.uniform1i(post.uniforms.sceneDepth, 1);context.activeTexture(context.TEXTURE3);context.bindTexture(context.TEXTURE_2D, this.shadowTexture);- context.uniform1i(this.postUniforms.volumeShadowMap, 3);- context.uniformMatrix4fv(this.postUniforms.volumeLightProjection, false, this.lightProjection);- context.uniform3fv(this.postUniforms.volumeLightDirection, environment.lightDirection);- context.uniform3fv(this.postUniforms.volumeLightColor, this.lighting.keyColor);- context.uniform1f(this.postUniforms.volumeDensity, volume.density);- context.uniform3fv(this.postUniforms.volumeMinimum, volume.minimum);- context.uniform3fv(this.postUniforms.volumeMaximum, volume.maximum);- context.uniform3fv(this.postUniforms.volumeColor, volume.color);- context.uniform3fv(this.postUniforms.volumeAmbient, volume.ambient);- context.uniform3fv(this.postUniforms.volumeDrift, volume.drift);- context.uniform1i(this.postUniforms.volumeSteps, volume.steps);- context.uniform1f(this.postUniforms.volumeAnisotropy, volume.anisotropy);- context.uniform1f(this.postUniforms.volumeNoiseAmount, volume.noiseAmount);- context.uniform1f(this.postUniforms.volumeNoiseScale, volume.noiseScale);- context.uniform1f(this.postUniforms.volumeMaxDistance, volume.maxDistance);- context.uniform1f(this.postUniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);+ context.uniform1i(post.uniforms.volumeShadowMap, 3);+ context.uniformMatrix4fv(post.uniforms.volumeLightProjection, false, this.lightProjection);+ context.uniform3fv(post.uniforms.volumeLightDirection, environment.lightDirection);+ context.uniform3fv(post.uniforms.volumeLightColor, this.lighting.keyColor);+ context.uniform1f(post.uniforms.volumeDensity, volume.density);+ context.uniform3fv(post.uniforms.volumeMinimum, volume.minimum);+ context.uniform3fv(post.uniforms.volumeMaximum, volume.maximum);+ context.uniform3fv(post.uniforms.volumeColor, volume.color);+ context.uniform3fv(post.uniforms.volumeAmbient, volume.ambient);+ context.uniform3fv(post.uniforms.volumeDrift, volume.drift);+ context.uniform1i(post.uniforms.volumeSteps, volume.steps);+ context.uniform1f(post.uniforms.volumeAnisotropy, volume.anisotropy);+ context.uniform1f(post.uniforms.volumeNoiseAmount, volume.noiseAmount);+ context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);+ context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);+ context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);context.activeTexture(context.TEXTURE2);context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);- context.uniform1i(this.postUniforms.bloomTexture, 2);- context.uniform1f(this.postUniforms.bloomStrength, effects.bloom.strength);+ context.uniform1i(post.uniforms.bloomTexture, 2);+ context.uniform1f(post.uniforms.bloomStrength, effects.bloom.strength);context.activeTexture(context.TEXTURE4);context.bindTexture(context.TEXTURE_2D, occluded ? this.occlusionTarget.texture : this.whiteTexture);- context.uniform1i(this.postUniforms.occlusionTexture, 4);- context.uniform1f(this.postUniforms.occlusionStrength, occluded ? effects.ambientOcclusion : 0);- context.uniform2f(this.postUniforms.occlusionTexel, 1 / Math.ceil(this.canvas.width / 2), 1 / Math.ceil(this.canvas.height / 2));- context.uniform1f(this.postUniforms.transparent, this.transparent ? 1 : 0);- context.uniform1f(this.postUniforms.hdrEnabled, this.hdr ? 1 : 0);- context.uniform3f(this.postUniforms.grade, effects.saturation, effects.contrast, effects.temperature);- context.uniform1f(this.postUniforms.vignette, effects.vignette);- context.uniform1f(this.postUniforms.grainAmount, effects.grain);- context.uniform2f(this.postUniforms.resolution, this.canvas.width, this.canvas.height);- context.uniform1f(this.postUniforms.monochrome, frame.monochrome ?? 0);- context.uniform1f(this.postUniforms.fade, frame.fade ?? 0);- context.uniform1f(this.postUniforms.cinematic, frame.cinematic ? 1 : 0);- context.uniform1f(this.postUniforms.time, frame.time ?? 0);- context.uniform1f(this.postUniforms.volumeExplosion, frame.volumeExplosion ? 1 : 0);- context.uniform1f(this.postUniforms.explosionProgress, frame.explosionProgress ?? 1);- context.uniformMatrix4fv(this.postUniforms.inverseViewProjection, false, this.inverseViewProjection);- context.uniform3fv(this.postUniforms.eye, frame.eye);+ context.uniform1i(post.uniforms.occlusionTexture, 4);+ context.uniform1f(post.uniforms.occlusionStrength, occluded ? effects.ambientOcclusion : 0);+ context.uniform2f(post.uniforms.occlusionTexel, 1 / Math.ceil(this.canvas.width / 2), 1 / Math.ceil(this.canvas.height / 2));+ context.uniform1f(post.uniforms.transparent, this.transparent ? 1 : 0);+ context.uniform1f(post.uniforms.hdrEnabled, this.hdr ? 1 : 0);+ context.uniform3f(post.uniforms.grade, effects.saturation, effects.contrast, effects.temperature);+ context.uniform1f(post.uniforms.vignette, effects.vignette);+ context.uniform1f(post.uniforms.grainAmount, effects.grain);+ context.uniform2f(post.uniforms.resolution, this.canvas.width, this.canvas.height);+ context.uniform1f(post.uniforms.monochrome, frame.monochrome ?? 0);+ context.uniform1f(post.uniforms.fade, frame.fade ?? 0);+ context.uniform1f(post.uniforms.cinematic, frame.cinematic ? 1 : 0);+ context.uniform1f(post.uniforms.time, frame.time ?? 0);+ context.uniform1f(post.uniforms.volumeExplosion, frame.volumeExplosion ? 1 : 0);+ context.uniform1f(post.uniforms.explosionProgress, frame.explosionProgress ?? 1);+ context.uniformMatrix4fv(post.uniforms.inverseViewProjection, false, this.inverseViewProjection);+ context.uniform3fv(post.uniforms.eye, frame.eye);context.drawArrays(context.TRIANGLES, 0, 3);}@@ -1997,6 +2040,7 @@ export class Renderer67 {this.context.deleteProgram(this.program);this.context.deleteProgram(this.depthProgram);if (this.postProgram) this.context.deleteProgram(this.postProgram);+ for (const variant of this.postVariants?.values() ?? []) this.context.deleteProgram(variant.program ?? variant.pending.program);if (this.skyProgram) this.context.deleteProgram(this.skyProgram);if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);if (this.occlusionProgram) this.context.deleteProgram(this.occlusionProgram);