3D engine that AI agents drive
Add budgeted MSAA, FXAA, specular filtering and atmospheric rendering
Nguyen Xuan An62e8f53698b5
diff --git a/scripts/smoke.mjs b/scripts/smoke.mjsindex acb05f30..49d324aa 100644--- a/scripts/smoke.mjs+++ b/scripts/smoke.mjs@@ -33,8 +33,8 @@ try {const extension = context.getExtension('WEBGL_debug_renderer_info');return { parts: renderer.partCount, triangles: renderer.triangles, calls: renderer.batches.length, glError: context.getError(), gpu: extension ? context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unavailable' };});- assert.equal(graphics.parts, 252);- assert.equal(graphics.calls, 9);+ assert.equal(graphics.parts, 325);+ assert.equal(graphics.calls, 10);assert.equal(graphics.glError, 0);await page.getByRole('button', { name: 'Ceramic finish' }).click();assert.equal(await page.locator('#finish-name').textContent(), 'Ceramic');@@ -57,7 +57,7 @@ try {await page.waitForFunction(() => window.__benchmarkReport, null, { timeout: 90000 });const report = await page.evaluate(() => window.__benchmarkReport);assert.equal(report.results.length, 4);- assert.deepEqual(report.results.map((result) => result.calls), [9, 253, 9, 253]);+ assert.deepEqual(report.results.map((result) => result.calls), [10, 326, 10, 326]);assert.ok(report.results.every((result) => result.pixelAgreement > 0.999), JSON.stringify(report.results));await page.getByRole('button', { name: 'Back to model' }).click();await page.setViewportSize({ width: 390, height: 844 });diff --git a/src/budget.js b/src/budget.jsnew file mode 100644index 00000000..609a7ad3--- /dev/null+++ b/src/budget.js@@ -0,0 +1,28 @@+const MEBIBYTE = 1024 * 1024;++export const RENDER_PRESETS = Object.freeze({+ preview: { width: 960, height: 540, samples: 2, fps: 24, memoryBudgetMiB: 256 },+ balanced: { width: 1280, height: 720, samples: 4, fps: 24, memoryBudgetMiB: 384 },+ high: { width: 1920, height: 1080, samples: 4, fps: 24, memoryBudgetMiB: 512 },+ cpu: { width: 640, height: 360, samples: 1, fps: 12, memoryBudgetMiB: 192 },+});++export function estimateFrameBytes(width, height, samples, shadowResolution = 2048) {+ // Color/depth MSAA, resolve texture, browser buffers and one screenshot/encoder staging frame.+ return width * height * (8 * Math.max(1, samples) + 20) + shadowResolution ** 2 * 4;+}++export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memoryBudgetMiB = 256, geometryBytes = 0, shadowResolution = 2048, maximumSize = 8192 }) {+ for (const value of [width, height, pixelRatio, samples, memoryBudgetMiB, maximumSize]) {+ if (!Number.isFinite(value) || value <= 0) throw new Error('Render dimensions, sample count and budget must be positive finite numbers.');+ }+ if (geometryBytes < 0 || !Number.isFinite(geometryBytes)) throw new Error('Geometry memory must be a nonnegative finite number.');+ const available = memoryBudgetMiB * MEBIBYTE - geometryBytes - shadowResolution ** 2 * 4;+ if (available < 64 * 64 * (8 * samples + 20)) throw new Error('Memory budget cannot hold the scene and a minimum render target. Lower scene detail or increase the budget.');+ const requestedWidth = Math.max(1, Math.round(width * pixelRatio));+ const requestedHeight = Math.max(1, Math.round(height * pixelRatio));+ const scale = Math.min(1, maximumSize / requestedWidth, maximumSize / requestedHeight, Math.sqrt(available / (requestedWidth * requestedHeight * (8 * samples + 20))));+ const renderWidth = Math.max(1, Math.floor(requestedWidth * scale));+ const renderHeight = Math.max(1, Math.floor(requestedHeight * scale));+ return { width: renderWidth, height: renderHeight, samples, estimatedBytes: estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution) + geometryBytes, reduced: scale < 1 };+}diff --git a/src/post.js b/src/post.jsnew file mode 100644index 00000000..e075f811--- /dev/null+++ b/src/post.js@@ -0,0 +1,78 @@+export const fullscreenVertex = `#version 300 es+precision highp float;+out vec2 textureCoordinate;+void main() {+ vec2 position = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));+ textureCoordinate = position;+ gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0);+}`;++export const postFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+uniform sampler2D frameTexture;+uniform vec2 resolution;+uniform float monochrome;+uniform float fade;+uniform float cinematic;+uniform float time;+out vec4 outputColor;+float luminance(vec3 color) { return dot(color, vec3(0.299, 0.587, 0.114)); }+void main() {+ vec2 texel = 1.0 / resolution;+ vec3 center = texture(frameTexture, textureCoordinate).rgb;+ vec3 northwest = texture(frameTexture, textureCoordinate + vec2(-1.0, -1.0) * texel).rgb;+ vec3 northeast = texture(frameTexture, textureCoordinate + vec2(1.0, -1.0) * texel).rgb;+ vec3 southwest = texture(frameTexture, textureCoordinate + vec2(-1.0, 1.0) * texel).rgb;+ vec3 southeast = texture(frameTexture, textureCoordinate + vec2(1.0, 1.0) * texel).rgb;+ float centerLuma = luminance(center);+ float northwestLuma = luminance(northwest);+ float northeastLuma = luminance(northeast);+ float southwestLuma = luminance(southwest);+ float southeastLuma = luminance(southeast);+ float minimumLuma = min(centerLuma, min(min(northwestLuma, northeastLuma), min(southwestLuma, southeastLuma)));+ float maximumLuma = max(centerLuma, max(max(northwestLuma, northeastLuma), max(southwestLuma, southeastLuma)));+ vec2 direction = vec2(-((northwestLuma + northeastLuma) - (southwestLuma + southeastLuma)), (northwestLuma + southwestLuma) - (northeastLuma + southeastLuma));+ float reduction = max((northwestLuma + northeastLuma + southwestLuma + southeastLuma) * 0.03125, 0.0078125);+ direction = clamp(direction / (min(abs(direction.x), abs(direction.y)) + reduction), vec2(-6.0), vec2(6.0)) * texel;+ vec3 first = 0.5 * (texture(frameTexture, textureCoordinate + direction * (-1.0 / 6.0)).rgb + texture(frameTexture, textureCoordinate + direction * (1.0 / 6.0)).rgb);+ vec3 second = first * 0.5 + 0.25 * (texture(frameTexture, textureCoordinate - direction * 0.5).rgb + texture(frameTexture, textureCoordinate + direction * 0.5).rgb);+ float secondLuma = luminance(second);+ vec3 color = secondLuma < minimumLuma || secondLuma > maximumLuma ? first : second;+ if (maximumLuma - minimumLuma < max(0.03, maximumLuma * 0.125)) color = center;+ color = mix(color, vec3(luminance(color)), monochrome);+ vec2 centered = textureCoordinate * 2.0 - 1.0;+ color *= 1.0 - cinematic * 0.20 * 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;+ outputColor = vec4(color * (1.0 - fade), 1.0);+}`;++export const skyFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+uniform vec3 skyTop;+uniform vec3 skyBottom;+uniform vec3 sunDirection;+uniform mat4 inverseViewProjection;+uniform vec3 eye;+uniform float time;+uniform float daylight;+out vec4 outputColor;+float noise(vec2 position) {+ return sin(position.x * 2.1 + sin(position.y * 1.3)) * 0.5 + sin(position.y * 2.8 - position.x * 0.8) * 0.3;+}+void main() {+ vec4 world = inverseViewProjection * vec4(textureCoordinate * 2.0 - 1.0, 1.0, 1.0);+ vec3 direction = normalize(world.xyz / world.w - eye);+ float height = clamp(direction.y * 1.3 + 0.12, 0.0, 1.0);+ vec3 color = mix(skyBottom, skyTop, pow(height, 0.6));+ float sun = max(dot(direction, normalize(sunDirection)), 0.0);+ color += vec3(1.0, 0.72, 0.35) * pow(sun, 300.0) * 0.7 * daylight;+ color += vec3(0.30, 0.22, 0.12) * pow(sun, 8.0) * daylight;+ vec2 cloudPosition = direction.xz / max(0.08, direction.y) * 0.5 + vec2(time * 0.006, 0.0);+ float cloud = smoothstep(0.1, 0.55, noise(cloudPosition) + noise(cloudPosition * 2.4) * 0.25);+ cloud *= smoothstep(0.02, 0.22, direction.y) * (1.0 - smoothstep(0.5, 0.95, direction.y));+ color = mix(color, mix(skyBottom, vec3(0.94, 0.93, 0.85), 0.7), cloud * 0.28 * daylight);+ outputColor = vec4(color, 1.0);+}`;diff --git a/src/renderer.js b/src/renderer.jsindex 599667ba..6d9c1225 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1,5 +1,9 @@import { mat4, mat3 } from 'gl-matrix';import { vertexShader, fragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';+import { fullscreenVertex, postFragment, skyFragment } from './post.js';+import { planRenderSize } from './budget.js';++const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9 };function compileProgram(context, vertexSource, fragmentSource) {const program = context.createProgram();@@ -55,27 +59,41 @@ export function groupParts(parts, batching = true) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, samples = 4, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {this.canvas = canvas;this.context = canvas.getContext('webgl2', { antialias: true, alpha: false, powerPreference: 'high-performance' });if (!this.context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');this.pixelRatio = pixelRatio;this.benchmark = benchmark;+ this.world = world;+ this.environment = environment;+ this.shadowBounds = shadowBounds;+ this.memoryBudgetMiB = memoryBudgetMiB;+ this.samples = benchmark ? 1 : Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES));+ this.geometryBytes = 0;this.buffers = [];this.batches = [];this.view = mat4.create();this.projection = mat4.create();this.viewProjection = mat4.create();this.lightProjection = mat4.create();+ this.inverseViewProjection = mat4.create();this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ if (!benchmark) {+ this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);+ this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);+ this.postUniforms = Object.fromEntries(['frameTexture', 'resolution', 'monochrome', 'fade', 'cinematic', 'time'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));+ this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));+ }this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');this.partCount = parts.length;this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);- groupParts([...parts, groundPart()], batching).forEach((group) => this.batches.push(this.uploadBatch(group)));+ groupParts(ground ? [...parts, groundPart()] : parts, batching).forEach((group) => this.batches.push(this.uploadBatch(group)));this.createShadowMap();this.resize();+ if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);}uploadBuffer(target, data) {@@ -83,6 +101,7 @@ export class Renderer67 {this.buffers.push(buffer);this.context.bindBuffer(target, buffer);this.context.bufferData(target, data, this.context.STATIC_DRAW);+ this.geometryBytes += data.byteLength;return buffer;}@@ -106,7 +125,7 @@ export class Renderer67 {instanceData.set(part.matrix, offset);instanceData.set(normalMatrix, offset + 16);instanceData.set(part.material.color, offset + 25);- instanceData.set([part.material.metallic, part.material.roughness, part.material.emission ?? 0, part.material.tag === 'floor' ? 2 : part.material.tag === 'armor' ? 1 : 0], offset + 28);+ instanceData.set([part.material.metallic, part.material.roughness, part.material.emission ?? 0, MATERIAL_TAGS[part.material.tag] ?? 0], offset + 28);});this.uploadBuffer(context.ARRAY_BUFFER, instanceData);for (let column = 0; column < 4; column++) this.attribute(2 + column, 4, stride * 4, column * 16);@@ -138,8 +157,10 @@ export class Renderer67 {context.drawBuffers([context.NONE]);context.readBuffer(context.NONE);if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Shadow framebuffer is incomplete.');- const lightView = mat4.lookAt(mat4.create(), [-3, 6, 4], [0, 1, 0], [0, 1, 0]);- mat4.ortho(this.lightProjection, -3.5, 3.5, -3.5, 3.5, 0.1, 15);+ const defaults = this.world ? { eye: [-25, 60, 30], target: [0, 2, -10], extent: 65, near: 1, far: 220 } : { eye: [-3, 6, 4], target: [0, 1, 0], extent: 3.5, near: 0.1, far: 15 };+ const light = { ...defaults, ...this.shadowBounds };+ const lightView = mat4.lookAt(mat4.create(), light.eye, light.target, [0, 1, 0]);+ mat4.ortho(this.lightProjection, -light.extent, light.extent, -light.extent, light.extent, light.near, light.far);mat4.multiply(this.lightProjection, this.lightProjection, lightView);context.viewport(0, 0, 2048, 2048);context.enable(context.DEPTH_TEST);@@ -155,15 +176,91 @@ export class Renderer67 {}resize() {- const ratio = Math.min(window.devicePixelRatio || 1, this.pixelRatio);- const width = Math.max(1, Math.round(this.canvas.clientWidth * ratio));- const height = Math.max(1, Math.round(this.canvas.clientHeight * ratio));+ const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, maximumSize: this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE) });+ const { width, height } = plan;+ this.memoryPlan = plan;if (this.canvas.width !== width || this.canvas.height !== height) {this.canvas.width = width;this.canvas.height = height;+ if (!this.benchmark) this.allocateFrameTargets(width, height);}- mat4.perspective(this.projection, Math.PI / 5.5, width / height, 0.1, 100);- this.projection[8] = !this.benchmark && this.canvas.clientWidth > 700 ? -0.25 : 0;+ mat4.perspective(this.projection, this.world ? Math.PI / 4 : Math.PI / 5.5, width / height, 0.1, this.world ? 600 : 100);+ this.projection[8] = !this.benchmark && !this.world && this.canvas.clientWidth > 700 ? -0.25 : 0;+ }++ releaseFrameTargets() {+ const context = this.context;+ if (this.multisampleFramebuffer) context.deleteFramebuffer(this.multisampleFramebuffer);+ if (this.resolveFramebuffer) context.deleteFramebuffer(this.resolveFramebuffer);+ if (this.multisampleColor) context.deleteRenderbuffer(this.multisampleColor);+ if (this.multisampleDepth) context.deleteRenderbuffer(this.multisampleDepth);+ if (this.frameTexture) context.deleteTexture(this.frameTexture);+ }++ allocateFrameTargets(width, height) {+ const context = this.context;+ this.releaseFrameTargets();+ this.multisampleFramebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);+ this.multisampleColor = context.createRenderbuffer();+ context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleColor);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.samples, context.RGBA8, width, height);+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, this.multisampleColor);+ this.multisampleDepth = context.createRenderbuffer();+ context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleDepth);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.samples, context.DEPTH_COMPONENT24, width, height);+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, this.multisampleDepth);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Multisample framebuffer allocation failed. Choose a lower quality preset.');+ this.frameTexture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, this.frameTexture);+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA8, width, height, 0, context.RGBA, context.UNSIGNED_BYTE, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ this.resolveFramebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, this.resolveFramebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.frameTexture, 0);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ }++ drawSky(frame) {+ const context = this.context;+ const environment = { skyTop: [0.20, 0.38, 0.52], skyBottom: [0.62, 0.70, 0.67], lightDirection: [-3, 6, 4], daylight: 1, ...this.environment, ...frame.environment };+ context.disable(context.DEPTH_TEST);+ context.disable(context.CULL_FACE);+ context.bindVertexArray(null);+ context.useProgram(this.skyProgram);+ context.uniform3fv(this.skyUniforms.skyTop, environment.skyTop);+ context.uniform3fv(this.skyUniforms.skyBottom, environment.skyBottom);+ context.uniform3fv(this.skyUniforms.sunDirection, environment.lightDirection);+ context.uniformMatrix4fv(this.skyUniforms.inverseViewProjection, false, this.inverseViewProjection);+ context.uniform3fv(this.skyUniforms.eye, frame.eye);+ context.uniform1f(this.skyUniforms.time, frame.time ?? 0);+ context.uniform1f(this.skyUniforms.daylight, environment.daylight);+ context.drawArrays(context.TRIANGLES, 0, 3);+ }++ resolveFrame(frame) {+ const context = this.context;+ context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);+ context.blitFramebuffer(0, 0, this.canvas.width, this.canvas.height, 0, 0, this.canvas.width, this.canvas.height, context.COLOR_BUFFER_BIT, context.NEAREST);+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ context.disable(context.DEPTH_TEST);+ context.disable(context.CULL_FACE);+ context.bindVertexArray(null);+ context.useProgram(this.postProgram);+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D, this.frameTexture);+ context.uniform1i(this.postUniforms.frameTexture, 0);+ 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.drawArrays(context.TRIANGLES, 0, 3);}drawBatch(batch) {@@ -171,14 +268,21 @@ export class Renderer67 {this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);}- render({ eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false }) {+ render(frame) {+ const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;const start = performance.now();const context = this.context;+ if (frame.fov) mat4.perspective(this.projection, frame.fov * Math.PI / 180, this.canvas.width / this.canvas.height, 0.1, this.world ? 600 : 100);mat4.lookAt(this.view, eye, target, [0, 1, 0]);mat4.multiply(this.viewProjection, this.projection, this.view);+ mat4.invert(this.inverseViewProjection, this.viewProjection);+ context.bindFramebuffer(context.FRAMEBUFFER, this.benchmark ? null : this.multisampleFramebuffer);context.viewport(0, 0, this.canvas.width, this.canvas.height);context.clearColor(0.145, 0.162, 0.177, 1);context.clear(context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT);+ if (this.world && !this.benchmark) this.drawSky(frame);+ context.enable(context.DEPTH_TEST);+ context.enable(context.CULL_FACE);context.useProgram(this.program);context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.viewProjection);context.uniformMatrix4fv(this.uniforms.lightProjection, false, this.lightProjection);@@ -187,20 +291,36 @@ export class Renderer67 {context.uniform2fv(this.uniforms.armorSurface, armorSurface);context.uniform1f(this.uniforms.exposure, exposure);context.uniform1f(this.uniforms.inspection, inspection ? 1 : 0);+ const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };+ context.uniform1f(this.uniforms.time, frame.time ?? 0);+ context.uniform1f(this.uniforms.wind, frame.wind ?? 0.3);+ context.uniform1f(this.uniforms.worldMode, this.world ? 1 : 0);+ context.uniform1f(this.uniforms.daylight, environment.daylight);+ context.uniform3fv(this.uniforms.lightDirection, environment.lightDirection);+ context.uniform3fv(this.uniforms.fogColor, environment.fogColor);+ context.uniform1f(this.uniforms.fogDensity, environment.fogDensity);+ context.uniform3fv(this.uniforms.waterRipple, frame.waterRipple ?? [10000, 0, 10000]);+ context.uniform1f(this.uniforms.rippleTime, frame.rippleTime ?? -1000);+ context.uniform1f(this.uniforms.explosionProgress, frame.explosionProgress ?? 1);+ context.uniform3fv(this.uniforms.explosionCenter, environment.explosionCenter);context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, this.shadowTexture);context.uniform1i(this.uniforms.shadowMap, 0);for (const batch of this.batches) this.drawBatch(batch);context.bindVertexArray(null);+ if (!this.benchmark) this.resolveFrame(frame);this.cpuMilliseconds = performance.now() - start;}dispose() {+ this.releaseFrameTargets();this.batches.forEach((batch) => this.context.deleteVertexArray(batch.vertexArray));this.buffers.forEach((buffer) => this.context.deleteBuffer(buffer));this.context.deleteTexture(this.shadowTexture);this.context.deleteFramebuffer(this.shadowFramebuffer);this.context.deleteProgram(this.program);this.context.deleteProgram(this.depthProgram);+ if (this.postProgram) this.context.deleteProgram(this.postProgram);+ if (this.skyProgram) this.context.deleteProgram(this.skyProgram);}}diff --git a/src/shaders.js b/src/shaders.jsindex 58781a5c..1f4c9e95 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -8,6 +8,10 @@ layout(location=9) in vec3 instanceColor;layout(location=10) in vec4 instanceSurface;uniform mat4 viewProjection;uniform mat4 lightProjection;+uniform float time;+uniform float wind;+uniform float explosionProgress;+uniform vec3 explosionCenter;out vec3 worldPosition;out vec3 worldNormal;out vec3 baseColor;@@ -15,6 +19,15 @@ out vec4 surface;out vec4 shadowPosition;void main() {vec4 world = instanceMatrix * vec4(position, 1.0);+ if (instanceSurface.w == 4.0 || instanceSurface.w == 7.0) {+ world.x += sin(time * 1.2 + world.z * 0.31 + world.x * 0.17) * wind * 0.10 * max(position.y + 0.5, 0.0);+ }+ if (instanceSurface.w == 3.0) {+ world.y += sin(world.x * 1.4 + time * 0.8) * 0.025 + sin(world.z * 1.8 - time) * 0.02;+ }+ if (instanceSurface.w == 8.0 || instanceSurface.w == 9.0) {+ world.xyz = mix(explosionCenter, world.xyz, 0.03 + explosionProgress * 0.97);+ }worldPosition = world.xyz;worldNormal = normalize(instanceNormal * normal);baseColor = instanceColor;@@ -68,6 +81,15 @@ uniform vec3 armorColor;uniform vec2 armorSurface;uniform float exposure;uniform float inspection;+uniform float worldMode;+uniform float time;+uniform float daylight;+uniform vec3 lightDirection;+uniform vec3 fogColor;+uniform float fogDensity;+uniform vec3 waterRipple;+uniform float rippleTime;+uniform float explosionProgress;uniform sampler2D shadowMap;out vec4 outputColor;const float PI = 3.14159265359;@@ -79,7 +101,7 @@ vec3 fresnel(float cosine, vec3 reflectance) {float shadowVisibility(vec3 normal) {vec3 projected = shadowPosition.xyz / shadowPosition.w * 0.5 + 0.5;if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 1.0;- float bias = max(0.0006, 0.002 * (1.0 - dot(normal, normalize(vec3(-3.0, 6.0, 4.0)))));+ float bias = max(0.0006, 0.002 * (1.0 - dot(normal, normalize(lightDirection))));float visibility = 0.0;vec2 texel = 1.0 / vec2(textureSize(shadowMap, 0));for (int row = -1; row <= 1; row++) {@@ -131,23 +153,52 @@ void main() {metallic = armorSurface.x;roughness = armorSurface.y;}+ vec3 normalChange = max(abs(dFdx(normal)), abs(dFdy(normal)));+ roughness = clamp(sqrt(roughness * roughness + dot(normalChange, normalChange) * 0.3), 0.075, 1.0);+ if (surface.w == 3.0) {+ normal = normalize(vec3(-cos(worldPosition.x * 1.4 + time * 0.8) * 0.035, 1.0, -cos(worldPosition.z * 1.8 - time) * 0.036));+ float radius = length(worldPosition.xz - waterRipple.xz);+ float age = time - rippleTime;+ float wave = sin(radius * 11.0 - age * 8.0) * exp(-abs(radius - age * 1.4) * 1.5) * exp(-age * 0.7) * step(0.0, age);+ normal.xz += normalize(worldPosition.xz - waterRipple.xz + 0.001) * wave * 0.07;+ normal = normalize(normal);+ color = mix(color, vec3(0.10, 0.23, 0.25), pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0));+ roughness = 0.16;+ }+ if (surface.w == 5.0) {+ float mottling = sin(worldPosition.x * 3.3) * sin(worldPosition.z * 4.1) * 0.5 + sin(worldPosition.x * 0.9 + worldPosition.z * 1.7) * 0.5;+ color *= 0.94 + mottling * 0.06;+ }float visibility = shadowVisibility(normal);- vec3 radiance = illuminate(normal, viewDirection, normalize(vec3(-3.0, 6.0, 4.0)), vec3(6.5, 5.7, 4.7) * visibility, color, metallic, roughness);- radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), vec3(1.4, 3.4, 3.2), color, metallic, roughness);- radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.8, 0.9, 1.1), color, metallic, roughness);+ vec3 keyColor = mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9) * daylight, worldMode);+ vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, color, metallic, roughness);+ radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode), color, metallic, roughness);+ radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode), color, metallic, roughness);vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));- radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55);- radiance += color * (1.0 - metallic) * vec3(0.16, 0.20, 0.22) * (0.45 + 0.55 * max(normal.y, 0.0));+ radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode);+ radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0));+ if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * daylight;radiance += color * surface.z;- if (surface.w > 1.5) {+ if (surface.w == 2.0) {float contact = 1.0 - 0.45 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);radiance = vec3(0.034, 0.041, 0.046) * (0.4 + visibility * 0.6) * contact;float fog = 1.0 - exp(-length(worldPosition.xz) * 0.05);radiance = mix(radiance, vec3(0.018, 0.022, 0.026), fog);}+ if (surface.w == 8.0) {+ float turbulence = sin(worldPosition.x * 3.0 + time * 4.0) * sin(worldPosition.y * 4.2 - time * 3.0) * sin(worldPosition.z * 3.7);+ float heat = clamp(0.65 + turbulence * 0.3 - explosionProgress * 0.25, 0.0, 1.0);+ radiance = mix(vec3(3.0, 0.12, 0.01), vec3(18.0, 9.0, 1.0), heat) * max(0.15, surface.z);+ }+ if (surface.w == 9.0) {+ float turbulence = sin(worldPosition.x * 2.0 + time) * sin(worldPosition.y * 3.3 - time * 0.6);+ radiance = color * (0.5 + turbulence * 0.15) + vec3(0.8, 0.10, 0.015) * max(0.0, 1.0 - explosionProgress) * max(0.0, -normal.y);+ }+ float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);+ radiance = mix(radiance, fogColor, fog * worldMode);if (inspection > 0.5) radiance = normal * 0.5 + 0.5;outputColor = vec4(pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);- if (surface.w > 1.5 && inspection < 0.5) {+ if (surface.w == 2.0 && inspection < 0.5) {float distanceFade = exp(-length(worldPosition.xz) * 0.08);float contact = 1.0 - 0.1 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);vec3 floorColor = mix(vec3(0.145, 0.162, 0.177), vec3(0.17, 0.19, 0.205), distanceFade);diff --git a/tests/budget.test.js b/tests/budget.test.jsnew file mode 100644index 00000000..887b122c--- /dev/null+++ b/tests/budget.test.js@@ -0,0 +1,24 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { planRenderSize, RENDER_PRESETS } from '../src/budget.js';++test('high resolution render targets shrink before exceeding their memory budget', () => {+ const plan = planRenderSize({ width: 7680, height: 4320, samples: 4, memoryBudgetMiB: 128, geometryBytes: 20 * 1024 ** 2 });+ assert.ok(plan.reduced);+ assert.ok(plan.estimatedBytes <= 128 * 1024 ** 2);+ assert.ok(Math.abs(plan.width / plan.height - 16 / 9) < 0.003);+});++test('presets fit their budget and device texture limits', () => {+ for (const preset of Object.values(RENDER_PRESETS)) {+ const plan = planRenderSize({ ...preset, maximumSize: 1024 });+ assert.ok(plan.width <= 1024 && plan.height <= 1024);+ assert.ok(plan.estimatedBytes <= preset.memoryBudgetMiB * 1024 ** 2);+ }+});++test('invalid or impossible memory requests fail before allocation', () => {+ assert.throws(() => planRenderSize({ width: 0, height: 720 }));+ assert.throws(() => planRenderSize({ width: 1280, height: 720, geometryBytes: 300 * 1024 ** 2, memoryBudgetMiB: 128 }), /cannot hold/);+ assert.throws(() => planRenderSize({ width: Infinity, height: 720 }));+});diff --git a/tests/export.test.js b/tests/export.test.jsindex a10a57ad..7e2c61fe 100644--- a/tests/export.test.js+++ b/tests/export.test.js@@ -14,5 +14,5 @@ test('exported GLB loads with an independent glTF loader and preserves every parlet meshCount = 0;gltf.scene.traverse((node) => { if (node.isMesh) meshCount++; });assert.equal(meshCount, parts.length);- assert.ok(binary.byteLength < 500000);+ assert.ok(binary.byteLength < 1024 * 1024);});