3D engine that AI agents drive
Give the water mirror coarser terrain levels with terrain mirrorLevels (part of #316)
Nguyen Xuan An7bb27ac851d1
diff --git a/scripts/benchmark-water-reflection.mjs b/scripts/benchmark-water-reflection.mjsindex b253bd66..7997d767 100644--- a/scripts/benchmark-water-reflection.mjs+++ b/scripts/benchmark-water-reflection.mjs@@ -18,6 +18,7 @@ const width = argument('width', 1920);const height = argument('height', 1080);const smallPartCount = argument('parts', 20000);const SAMPLES = argument('samples', 20);+const mirrorLevels = argument('mirror-levels', 0);const countsOnly = process.argv.includes('--counts-only');const stillsFolder =process.argv.includes('--stills') ? process.argv[process.argv.indexOf('--stills') + 1] : null;@@ -29,14 +30,14 @@ try {const page = await browser.newPage({ viewport: { width, height } });await page.route('**/water-benchmark.html', route => route.fulfill({ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>` }));await page.goto(`${serverUrl}/water-benchmark.html`);- const results = await page.evaluate(async ({ smallPartCount, samples, wantStills, countsOnly }) => {+ const results = await page.evaluate(async ({ smallPartCount, samples, wantStills, countsOnly, mirrorLevels }) => {const { Renderer67 } = await import('/src/renderer.js');const { box } = await import('/src/geometry.js');const { createTerrain } = await import('/src/terrain.js');const { applyWaterReflection, attachWaterReflection } = await import('/src/water-reflection.js');const canvas = document.querySelector('canvas');- const terrain = createTerrain({ size: 900, resolution: 128, chunks: 8, levels: 1, height: (x, z) => 22 * Math.sin(x * 0.009) * Math.cos(z * 0.011) + 9 * Math.sin(x * 0.03 + z * 0.02) - 4 });+ const terrain = createTerrain({ size: 900, resolution: 128, chunks: 8, levels: 1, mirrorLevels, height: (x, z) => 22 * Math.sin(x * 0.009) * Math.cos(z * 0.011) + 9 * Math.sin(x * 0.03 + z * 0.02) - 4 });const pebble = box(0.05, 2);let seed = 12345;const random = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };@@ -129,7 +130,7 @@ try {if (wantStills) report.halfScale = await measure('scale 0.5', true, { scale: 0.5 });report.stillCamera = await measure('still camera', true, {}, true);return report;- }, { smallPartCount, samples: SAMPLES, wantStills: stillsFolder !== null, countsOnly });+ }, { smallPartCount, samples: SAMPLES, wantStills: stillsFolder !== null, countsOnly, mirrorLevels });if (stillsFolder) {await mkdir(stillsFolder, { recursive: true });for (const [name, entry] of Object.entries(results)) {diff --git a/src/renderer.js b/src/renderer.jsindex a8b9f3c8..91f6e5cb 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -293,7 +293,7 @@ function partGeometries(part) {/** The state of one list of levels: errors, geometries, the draw of each level once it is first needed, and a selection. */function createLevelSet(levels, instanceCount) {- return { levelErrors: levels.map(level => level.error), levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(instanceCount, levels.length) };+ return { levelErrors: levels.map(level => level.mirrorOnly ? Infinity : level.error), mirrorErrors: levels.map(level => level.error), levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(instanceCount, levels.length) };}function groundPart() {@@ -949,7 +949,7 @@ export class Renderer67 {if (!this.culling || !batch.cullable) return null;return selectInstances(batch.selection, {instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds, margin: batch.swayReach * Math.abs(this.windState.strength),- levelErrors: batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,+ levelErrors: this.mirrorCulling ? batch.mirrorErrors : batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,pixelsPerUnit: this.canvas.height / 2 * this.projection[5], pixelError: this.lodPixelError * (this.mirrorCulling?.lodScale ?? 1),belowHeight: this.mirrorCulling?.belowHeight, minimumPixelRadius: this.mirrorCulling?.minimumPixelRadius,});diff --git a/src/terrain.js b/src/terrain.jsindex 18030d04..2bcb4156 100644--- a/src/terrain.js+++ b/src/terrain.js@@ -150,13 +150,16 @@ function resolveHeightFunction(height, size, seed) {return createNoiseHeight(height ?? {}, seed);}-function validateOptions({ size, resolution, chunks, levels }) {+function validateOptions({ size, resolution, chunks, levels, mirrorLevels }) {if (!(size > 0) || !Number.isFinite(size)) throw new RangeError('size must be a positive number of metres.');if (!Number.isInteger(chunks) || chunks < 1) throw new RangeError('chunks must be a positive integer.');if (!Number.isInteger(levels) || levels < 1) throw new RangeError('levels must be a positive integer.');if (!Number.isInteger(resolution) || resolution < 1 || resolution % (2 ** (levels - 1)) !== 0) {throw new RangeError(`resolution must be a positive integer divisible by 2^(levels - 1) = ${2 ** (levels - 1)}.`);}+ if (!Number.isInteger(mirrorLevels) || mirrorLevels < 0 || resolution % (2 ** (levels - 1 + mirrorLevels)) !== 0) {+ throw new RangeError('mirrorLevels must be a whole number of extra halvings that the resolution divides by (2^(levels - 1 + mirrorLevels)).');+ }}const SIDES = Object.freeze(['west', 'east', 'north', 'south']);@@ -190,8 +193,8 @@ function pointInsideHoles(holes, pointX, pointZ) {* Ground spans x and z from -size / 2 to size / 2. Call update(eye) each frame (or when the camera moves) and, when it* returns a non-empty list, pass the scene parts to renderer.replaceParts.*/-export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material = DEFAULT_MATERIAL, lodDistance, eye, holes } = {}) {- validateOptions({ size, resolution, chunks, levels });+export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material = DEFAULT_MATERIAL, lodDistance, eye, holes, mirrorLevels = 0 } = {}) {+ validateOptions({ size, resolution, chunks, levels, mirrorLevels });const holeCircles = normalizeTerrainHoles(holes);const isHole = (worldX, worldZ) => holeCircles !== null && pointInsideHoles(holeCircles, worldX, worldZ);const heightFunction = resolveHeightFunction(height, size, seed);@@ -346,6 +349,33 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levelsreturn Math.min(levels - 1, Math.floor(Math.log2(distance / nearDistance)) + 1);}+ // How far a coarser mesh can sit from the finest one on this chunk: the largest second difference of the heights at that step.+ function coarseError(state, level) {+ const step = 2 ** level;+ let largest = 0;+ for (let row = 0; row <= resolution; row += step) {+ for (let column = 0; column <= resolution; column += step) {+ const gridColumn = state.chunkColumn * resolution + column;+ const gridRow = state.chunkRow * resolution + row;+ const middle = gridHeight(gridColumn, gridRow);+ largest = Math.max(largest, Math.abs(gridHeight(gridColumn - step, gridRow) + gridHeight(gridColumn + step, gridRow) - 2 * middle) / 2, Math.abs(gridHeight(gridColumn, gridRow - step) + gridHeight(gridColumn, gridRow + step) - 2 * middle) / 2);+ }+ }+ return largest;+ }++ // Coarser meshes for the water mirror only (the renderer never picks them for the main camera): each has its own edges, so a+ // seam can open between two chunks that the mirror draws at different levels, which the blurred reflection hides.+ function buildMirrorLods(state) {+ const lods = [{ geometry: state.part.geometry, error: 0 }];+ for (let extra = 1; extra <= mirrorLevels; extra++) {+ const level = state.targetLevel + extra;+ const edgeLevels = { west: level, east: level, north: level, south: level };+ lods.push({ geometry: buildChunkGeometry(state.chunkColumn, state.chunkRow, level, edgeLevels), error: Math.max(lods[extra - 1].error, coarseError(state, level)), mirrorOnly: true });+ }+ return lods;+ }+let triangleTotal = 0;function update(eyePosition) {if (!Array.isArray(eyePosition) && !(eyePosition instanceof Float32Array)) throw new TypeError('update needs an eye position [x, y, z].');@@ -358,6 +388,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levelsif (unchanged) continue;if (state.part.geometry) triangleTotal -= state.part.geometry.indices.length / 3;state.part.geometry = buildChunkGeometry(state.chunkColumn, state.chunkRow, state.targetLevel, edgeLevels);+ if (mirrorLevels > 0) state.part.lods = buildMirrorLods(state);triangleTotal += state.part.geometry.indices.length / 3;state.level = state.targetLevel;state.edgeLevels = edgeLevels;diff --git a/tests/render-culling.test.js b/tests/render-culling.test.jsindex 0da56d25..dc29f970 100644--- a/tests/render-culling.test.js+++ b/tests/render-culling.test.js@@ -232,7 +232,7 @@ test('the renderer lets the water mirror widen the level error, and a normal fraconst { projection, viewProjection, planes } = cameraMatrices();const renderer = Object.create(Renderer67.prototype);Object.assign(renderer, { culling: true, canvas: { height: CANVAS_HEIGHT }, projection, viewProjection, frustumPlanes: planes, lodPixelError: 1, windState: { strength: 0 } });- const batch = { cullable: true, selection: new InstanceSelection(2, 2), instanceData: instanceData([[0, -5, 0], [0, 1, 0]]), instanceCount: 2, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: [0, 0.02] };+ const batch = { cullable: true, selection: new InstanceSelection(2, 2), instanceData: instanceData([[0, -5, 0], [0, 1, 0]]), instanceCount: 2, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: [0, 0.02], mirrorErrors: [0, 0.02] };const levelOfSecond = () => {const selection = renderer.selectBatchInstances(batch);return selection.indices[1][0] === 1 ? 1 : 0;@@ -244,3 +244,22 @@ test('the renderer lets the water mirror widen the level error, and a normal fraassert.equal(mirrored.visibleCount, 1);assert.equal(levelOfSecond(), 1);});++test('a mirrorOnly level is never chosen by a normal frame and is chosen by the water mirror', () => {+ const { projection, viewProjection, planes } = cameraMatrices();+ const renderer = Object.create(Renderer67.prototype);+ Object.assign(renderer, { culling: true, canvas: { height: CANVAS_HEIGHT }, projection, viewProjection, frustumPlanes: planes, lodPixelError: 1, windState: { strength: 0 } });+ const geometry = box(0, 1);+ const lods = [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.0001, mirrorOnly: true }];+ const state = createLevelSetFor(lods);+ const batch = { cullable: true, selection: state.selection, instanceData: instanceData([[0, 1, 0]]), instanceCount: 1, bounds: { center: [0, 0, 0], radius: 1 }, swayReach: 0, levelErrors: state.levelErrors, mirrorErrors: state.mirrorErrors };+ assert.equal(renderer.selectBatchInstances(batch).counts[1], 0, 'the main camera keeps level 0 even when the error is tiny');+ renderer.mirrorCulling = { belowHeight: -10, lodScale: 3, minimumPixelRadius: 0 };+ assert.equal(renderer.selectBatchInstances(batch).counts[1], 1);+});++function createLevelSetFor(lods) {+ const renderer = Object.create(Renderer67.prototype);+ const part = { name: 'p', geometry: lods[0].geometry, lods, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5, emission: 0 } };+ return renderer.createCullingState([part]);+}diff --git a/tests/terrain.test.js b/tests/terrain.test.jsindex 10de9b88..66324d4a 100644--- a/tests/terrain.test.js+++ b/tests/terrain.test.js@@ -44,6 +44,23 @@ test('the same seed gives the same terrain and another seed differs', () => {assert.deepEqual(first.parts[3].geometry.positions, second.parts[3].geometry.positions);});+test('mirrorLevels gives every chunk coarser mirrorOnly meshes with growing errors, and none without the option', () => {+ const plain = createTerrain(SMALL);+ assert.ok(plain.parts.every(part => part.lods === undefined));+ const terrain = createTerrain({ ...SMALL, levels: 1, resolution: 16, mirrorLevels: 3 });+ for (const part of terrain.parts) {+ assert.equal(part.lods.length, 4);+ assert.equal(part.lods[0].geometry, part.geometry);+ assert.equal(part.lods[0].mirrorOnly, undefined);+ assert.ok(part.lods.slice(1).every(level => level.mirrorOnly === true));+ for (let index = 1; index < part.lods.length; index++) {+ assert.ok(part.lods[index].error >= part.lods[index - 1].error);+ assert.ok(part.lods[index].geometry.indices.length < part.lods[index - 1].geometry.indices.length);+ }+ }+ assert.throws(() => createTerrain({ ...SMALL, levels: 3, mirrorLevels: 3 }), RangeError);+});+test('heightAt returns the vertex height at mesh vertices of the finest level', () => {const terrain = createTerrain(SMALL);terrain.update([0, 1, 0]);