Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Hold far sun cascade maps while the camera moves inside them, and redraw only slices that changed (closes part of #504)

Nguyen Xuan An1c4711e774d1
diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.js
index fa047193..c9e79281 100644
--- a/src/cascaded-shadows.js
+++ b/src/cascaded-shadows.js
@@ -157,9 +157,24 @@ export function writeCascadeMatrix(target, { center, radius }, towardLight, reso
const far = -(snappedZ - radius);
const projection = mat4.ortho(mat4.create(), snappedX - radius, snappedX + radius, snappedY - radius, snappedY + radius, near, far);
mat4.multiply(target, projection, rotation);
- return { texel, range: far - near };
+ return { texel, range: far - near, snappedX, snappedY, near, far, radius };
}
+// A slice that moved but still sits inside the map drawn for it can keep that map: same light direction, the sphere inside
+// the drawn square, and its casters inside the drawn depth range.
+function fitCovers(fit, sphere, towardLight, casterReach) {
+ if (vec3.squaredDistance(fit.towardLight, towardLight) > 1e-12) return false;
+ const rotation = mat4.lookAt(mat4.create(), [0, 0, 0], [-towardLight[0], -towardLight[1], -towardLight[2]], Math.abs(towardLight[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0]);
+ const center = vec3.transformMat4(vec3.create(), sphere.center, rotation);
+ return Math.abs(center[0] - fit.snappedX) + sphere.radius <= fit.radius
+ && Math.abs(center[1] - fit.snappedY) + sphere.radius <= fit.radius
+ && -(center[2] + casterReach) >= fit.near
+ && -(center[2] - sphere.radius) <= fit.far;
+}
+
+// While the camera moves, a slice past the first is drawn this much wider than it needs, so it stays valid for many frames.
+const HOLD_MARGIN = 0.25;
+
export class CascadedShadows {
constructor({ count = 3, resolution = DEFAULT_RESOLUTION, maximumDistance = DEFAULT_MAXIMUM_DISTANCE, splitLambda = DEFAULT_SPLIT_LAMBDA, casterReach = DEFAULT_CASTER_REACH } = {}) {
this.count = integerInRange(count, 1, MAXIMUM_CASCADES, 'cascade count');
@@ -169,7 +184,8 @@ export class CascadedShadows {
this.casterReach = numberInRange(casterReach, 1, 1e5, 'cascade casterReach');
this.shaderFeature = 'cascadedShadows';
this.matrices = new Float32Array(MAXIMUM_CASCADES * 16);
- this.previousMatrices = new Float32Array(MAXIMUM_CASCADES * 16);
+ this.drawnMatrices = new Float32Array(MAXIMUM_CASCADES * 16);
+ this.holds = [];
this.splits = new Float32Array(MAXIMUM_CASCADES).fill(1e9);
this.texels = new Float32Array(MAXIMUM_CASCADES).fill(1);
this.ranges = new Float32Array(MAXIMUM_CASCADES).fill(1);
@@ -191,6 +207,9 @@ export class CascadedShadows {
context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
this.framebuffer = context.createFramebuffer();
+ // A new array holds no depth yet, so every slice draws on its first update.
+ this.drawCount = 0;
+ this.drawnMatrices.fill(0);
}
// Fits every slice to the current camera. Returns the number of slices whose matrix moved.
@@ -207,14 +226,33 @@ export class CascadedShadows {
splits.forEach((split, layer) => {
const endFraction = Math.min((split - nearDistance) / planeSpan, 1);
const sphere = boundingSphere(frustumSlice(corners, previousFraction, endFraction));
- const fitted = writeCascadeMatrix(this.matrices.subarray(layer * 16, layer * 16 + 16), sphere, towardLight, this.resolution, this.casterReach);
+ const fitted = this.chooseFit(layer, sphere, towardLight);
+ this.matrices.set(fitted.matrix, layer * 16);
this.splits[layer] = split;
this.texels[layer] = fitted.texel;
this.ranges[layer] = fitted.range;
previousFraction = endFraction;
});
this.forward.set([...renderer.viewForward, this.count]);
- return this.matrices.some((value, index) => value !== this.previousMatrices[index]);
+ return this.matrices.some((value, index) => value !== this.drawnMatrices[index]);
+ }
+
+ // The nearest slice always fits exactly. A farther slice that moved keeps its last map while the new slice still sits inside
+ // it, and is redrawn wider than needed when it does not; a camera that stops settles back on the exact fit.
+ chooseFit(layer, sphere, towardLight) {
+ const hold = this.holds[layer] ??= { fit: null, tight: null };
+ const tight = { matrix: new Float32Array(16), towardLight: vec3.clone(towardLight) };
+ Object.assign(tight, writeCascadeMatrix(tight.matrix, sphere, towardLight, this.resolution, this.casterReach));
+ const moved = hold.tight && tight.matrix.some((value, index) => value !== hold.tight.matrix[index]);
+ hold.tight = tight;
+ if (layer === 0 || !hold.fit || !moved) {
+ hold.fit = tight;
+ } else if (!fitCovers(hold.fit, sphere, towardLight, this.casterReach)) {
+ const wide = { matrix: new Float32Array(16), towardLight: vec3.clone(towardLight) };
+ Object.assign(wide, writeCascadeMatrix(wide.matrix, { center: sphere.center, radius: sphere.radius * (1 + HOLD_MARGIN) }, towardLight, this.resolution, this.casterReach));
+ hold.fit = wide;
+ }
+ return hold.fit;
}
/** Whether the main shader reads the cascades alone: volume fog and subsurface thickness still read the single map. */
@@ -231,7 +269,6 @@ export class CascadedShadows {
}
const moved = this.fitToCamera(renderer);
if (!moved && !casterChanged && this.drawCount > 0) return;
- this.previousMatrices.set(this.matrices);
this.drawCount++;
context.bindFramebuffer(context.FRAMEBUFFER, this.framebuffer);
context.drawBuffers([context.NONE]);
@@ -240,9 +277,15 @@ export class CascadedShadows {
context.enable(context.DEPTH_TEST);
context.enable(context.CULL_FACE);
for (let layer = 0; layer < this.count; layer++) {
+ const layerMatrix = this.matrices.subarray(layer * 16, layer * 16 + 16);
+ const drawnMatrix = this.drawnMatrices.subarray(layer * 16, layer * 16 + 16);
+ // A slice whose matrix did not change keeps the depth it holds, because the casters it draws depend on that matrix alone.
+ // Far slices have large texels and snap to them, so most of them hold still while the camera orbits.
+ if (!casterChanged && this.drawCount > 1 && drawnMatrix.every((value, index) => value === layerMatrix[index])) continue;
+ drawnMatrix.set(layerMatrix);
context.framebufferTextureLayer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, this.texture, 0, layer);
context.clear(context.DEPTH_BUFFER_BIT);
- renderer.drawShadowCasters(this.matrices.subarray(layer * 16, layer * 16 + 16), this.resolution);
+ renderer.drawShadowCasters(layerMatrix, this.resolution);
}
context.bindFramebuffer(context.FRAMEBUFFER, null);
}
diff --git a/tests/cascaded-shadows.test.js b/tests/cascaded-shadows.test.js
index 986e100b..aa2c6897 100644
--- a/tests/cascaded-shadows.test.js
+++ b/tests/cascaded-shadows.test.js
@@ -75,3 +75,41 @@ test('the cascade shader replaces the classic sun map and a plain shader has no
assert.doesNotMatch(plain, /cascadeVisibility|cascadeShadowMap/);
assert.doesNotMatch(plain, /#define shadowVisibility/);
});
+
+test('an update redraws only the slices whose matrix changed, and every slice when a caster changed', () => {
+ const context = new Proxy({}, { get: (target, name) => (name in target ? target[name] : () => ({})) });
+ const drawnLayers = [];
+ const renderer = { context, renderTargets: { record() {} }, drawShadowCasters: matrix => drawnLayers.push(matrix[0]) };
+ const cascades = createCascadedShadows({ count: 3, resolution: 256 });
+ const setMatrices = firstValues => {
+ firstValues.forEach((value, layer) => cascades.matrices.fill(value, layer * 16, layer * 16 + 16));
+ cascades.fitToCamera = () => cascades.matrices.some((value, index) => value !== cascades.drawnMatrices[index]);
+ };
+ setMatrices([1, 2, 3]);
+ cascades.update(renderer, false);
+ assert.deepEqual(drawnLayers.splice(0), [1, 2, 3]);
+ cascades.update(renderer, false);
+ assert.deepEqual(drawnLayers.splice(0), [], 'nothing moved');
+ setMatrices([1, 2, 4]);
+ cascades.update(renderer, false);
+ assert.deepEqual(drawnLayers.splice(0), [4], 'only the moved slice');
+ cascades.update(renderer, true);
+ assert.deepEqual(drawnLayers.splice(0), [1, 2, 4], 'a changed caster redraws every slice');
+});
+
+test('a moving camera keeps a far slice\'s map until the slice leaves it, and a stopped camera settles on the exact fit', () => {
+ const cascades = createCascadedShadows({ count: 2, resolution: 2048 });
+ const sphereAt = x => ({ center: [x, 0, -100], radius: 80 });
+ const exact = cascades.chooseFit(1, sphereAt(0), TOWARD_LIGHT);
+ assert.equal(exact.radius, 80, 'the first fit is exact');
+ const wide = cascades.chooseFit(1, sphereAt(2), TOWARD_LIGHT);
+ assert.ok(wide.radius > 80, 'the first move draws wider than needed');
+ const kept = cascades.chooseFit(1, sphereAt(6), TOWARD_LIGHT);
+ assert.equal(kept, wide, 'a small move stays inside the wide map');
+ const redrawn = cascades.chooseFit(1, sphereAt(60), TOWARD_LIGHT);
+ assert.notEqual(redrawn, wide, 'a large move leaves it');
+ const settled = cascades.chooseFit(1, sphereAt(60), TOWARD_LIGHT);
+ assert.equal(settled.radius, 80, 'a camera that stopped gets the exact fit');
+ assert.equal(cascades.chooseFit(0, sphereAt(0), TOWARD_LIGHT).radius, 80);
+ assert.equal(cascades.chooseFit(0, sphereAt(3), TOWARD_LIGHT).radius, 80, 'the nearest slice always fits exactly');
+});