3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Tint the closed-room fill by the room's albedo and fade it toward corners (#1334)
Nguyen Xuan An30705676cc0b
diff --git a/bench/reference/interior-regions.mjs b/bench/reference/interior-regions.mjsnew file mode 100644index 00000000..5f908ac5--- /dev/null+++ b/bench/reference/interior-regions.mjs@@ -0,0 +1,54 @@+// Prints the mean red, green and blue (display 0 to 255) of named regions of the window room probe's 960x540 frame, for each PNG+// given, with the whole-frame RMSE against the first one (issue #1334, #2160). The first file is the reference (the path tracer).+// node bench/reference/interior-regions.mjs <reference.png> [other.png ...]+import sharp from 'sharp';++const FRAME_WIDTH = 960;+const FRAME_HEIGHT = 540;++// Boxes `[left, top, right, bottom]` in pixels of interior-exposure.mjs's default camera. The floor boxes leave out the sunlit patch.+export const REGIONS = {+ 'left wall': [20, 130, 150, 270],+ 'back wall': [300, 190, 660, 320],+ 'right wall': [800, 150, 940, 280],+ 'ceiling': [250, 5, 700, 110],+ 'floor': [20, 440, 380, 535],+ 'sunlit floor': [540, 475, 840, 530],+ 'wall-floor corner': [260, 326, 700, 344],+ 'wall-ceiling corner': [260, 156, 700, 174],+};++async function readPixels(path) {+ const { data, info } = await sharp(path).removeAlpha().raw().toBuffer({ resolveWithObject: true });+ if (info.width !== FRAME_WIDTH || info.height !== FRAME_HEIGHT) throw new Error(`${path} is ${info.width}x${info.height}; render the probe at ${FRAME_WIDTH}x${FRAME_HEIGHT} (the default).`);+ return data;+}++export function regionMeans(data, [left, top, right, bottom]) {+ const totals = [0, 0, 0];+ let count = 0;+ for (let row = top; row < bottom; row++) {+ for (let column = left; column < right; column++) {+ for (let channel = 0; channel < 3; channel++) totals[channel] += data[(row * FRAME_WIDTH + column) * 3 + channel];+ count++;+ }+ }+ return totals.map(total => total / count);+}++function rmse(first, second) {+ let total = 0;+ for (let index = 0; index < first.length; index++) total += (first[index] - second[index]) ** 2;+ return Math.sqrt(total / first.length);+}++const paths = process.argv.slice(2);+if (paths.length === 0) throw new Error('Pass at least one PNG path: node bench/reference/interior-regions.mjs <reference.png> [other.png ...]');+const images = await Promise.all(paths.map(readPixels));+for (const [index, path] of paths.entries()) {+ console.log(`${path} rmse-vs-first ${rmse(images[0], images[index]).toFixed(2)}`);+ for (const [name, box] of Object.entries(REGIONS)) {+ const [red, green, blue] = regionMeans(images[index], box);+ console.log(` ${name.padEnd(20)} R ${red.toFixed(1).padStart(6)} G ${green.toFixed(1).padStart(6)} B ${blue.toFixed(1).padStart(6)}`);+ }+}diff --git a/changes/1334.md b/changes/1334.mdindex be3dca2d..d58aefae 100644--- a/changes/1334.md+++ b/changes/1334.md@@ -1 +1 @@-- A path traced job's exposure advice says a daylit interior traces about 1 to 2 stops brighter than the raster frame at the same exposure, with the measured table in the path tracer guide (#1334).+- A closed room with a window now gets the sky light its surfaces bounce on to each other, tinted by the room's albedo and fading toward corners, so its walls no longer render near black or blue-grey, and a path traced job's exposure advice says a daylit interior traces about 1 to 2 stops brighter than the raster frame at the same exposure, with the measured table in the path tracer guide (#1334).diff --git a/changes/1334.size.md b/changes/1334.size.mdindex c1b4e370..38bee8f1 100644--- a/changes/1334.size.md+++ b/changes/1334.size.md@@ -1 +1,2 @@-- scene:agent-scene+lazy: the closed-room sky fill (interiorSkyFill and its helper, 322 bytes gzip) brings a windowed room to 1.34 times under the path tracer instead of 2.6 times, a visible fix of the largest raster-versus-tracer gap measured on interiors+- scene:agent-scene+lazy: the closed-room sky fill (interiorSkyFill and its helpers, 857 bytes gzip in total: 322 for the fill, 535 for its tint, its corner falloff and its sun test) brings a windowed room to 1.40 times under the path tracer instead of 2.6 times, with walls of the tracer's warm hue (back wall red over blue 1.36 against 1.40, was 0.90) and the whole-frame RMSE 26.62 instead of 29.43. The lead accepted the growth because it closes the largest raster-versus-tracer gap measured on interiors+- entry:floor-sky-visibility: the same fill is this entry's own code (847 bytes gzip against main, 322 of them the fill the lead accepted before and about 525 its tint, corner falloff and sun test), the bytes that give the window room walls of the tracer's warm hue and corners that stay darkerdiff --git a/docs/lighting.md b/docs/lighting.mdindex 90139b92..f627e574 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -273,4 +273,4 @@ Two shapes were considered: mutable light nodes with independent scene ownershipRun `node --test tests/lighting.test.js` for retained-state checks and `node scripts/smoke-lighting.mjs` with the development server running for linear HDR pixel checks, native GPU timing and before/after laboratory images.-The recipe path's trace covers every surface of a closed room, not only the floor: the ceiling, walls and props get the sky they can see, so a sealed room renders near black like the path tracer and a room with a window keeps the light that comes through it (#1334, `bench/reference/interior-exposure.mjs`). A closed room also gets the sky light its surfaces bounce on to each other (`interiorSkyFill` in `src/floor-sky-visibility.js`, `report.interiorFill`): the traced visibility of every point that sees the room from inside (at most a quarter of its rays escape) is raised by `4 * albedo * open / (1 - albedo * (1 - open))`, at most 0.5, where `open` is one minus the closed-room ray share and `albedo` the mean diffuse albedo of the traced points. A sealed room has `open` 0 and gets nothing; open scenes are not traced this way. On the window probe at exposure 3.6 the raster mean goes from 0.0388 to 0.0758 linear against 0.1014 from the path tracer (2.6 times darker before, 1.34 times after); the gain 4 is fitted on that one room, so it is a calibration, not a measurement of every room (the halls `temple-hall` and `dark-shaft` get fills of 0.13 and 0.09 and their mean moves by 2 percent). A recipe that leaves `shadow` out gets a sun shadow view fitted to its bounds when they are wider than the default 7 m view and narrower than 130 m (three automatic cascades past 40 m), so the sun no longer reaches past thin walls: the sealed probe room reads 0.0007 linear against 0.0006 from the path tracer (#1359). A recipe that sets `shadow` to anything but the defaults keeps exactly what it set; one that writes the default values out is read as having left it out. A flat horizontal slab wider than 10 m and under 15 percent as thick as it is wide, counted with the bounds padding (a ground plane) is left out of the fit when other parts exist, so a 1 m object on a 50 m plane keeps the default view and its sharp shadow instead of getting a 40 m one.+The recipe path's trace covers every surface of a closed room, not only the floor: the ceiling, walls and props get the sky they can see, so a sealed room renders near black like the path tracer and a room with a window keeps the light that comes through it (#1334, `bench/reference/interior-exposure.mjs`). A closed room also gets the sky light its surfaces bounce on to each other (`interiorSkyFill` in `src/floor-sky-visibility.js`, `report.interiorFill`): the traced visibility of every point that sees the room from inside (at most a quarter of its rays escape) is raised by `4 * albedo * open / (1 - albedo * (1 - open))`, at most 0.5, where `open` is one minus the closed-room ray share and `albedo` the mean diffuse albedo of the traced points. The fill is scaled down for a point whose rays meet a surface within 15 percent of the room's smallest span (up to 40 percent less, `interiorCornerWeight`), so corners and wall/floor junctions stay darker than the middle of a wall. It is tinted through the vertex colour by `interiorFillTint`: the mean albedo over the daylight hue, at the same luminance, so a room of plaster and wood bounces warm light where the sky term alone is blue-grey; a point the sun reaches directly keeps its colour. A sealed room has `open` 0 and gets nothing; open scenes are not traced this way. On the window probe at exposure 3.6 the raster mean goes from 0.0388 to 0.0722 linear against 0.1014 from the path tracer (2.6 times darker before, 1.40 times after), the whole-frame RMSE against the tracer is 26.62, and the back wall's red over blue is 1.36 against 1.40 from the tracer; the gain 4, the daylight hue and the falloff are fitted on that one room, so they are a calibration, not a measurement of every room (the halls `temple-hall` and `dark-shaft` get fills of 0.13 and 0.09 and their mean moves by 2 percent). A recipe that leaves `shadow` out gets a sun shadow view fitted to its bounds when they are wider than the default 7 m view and narrower than 130 m (three automatic cascades past 40 m), so the sun no longer reaches past thin walls: the sealed probe room reads 0.0007 linear against 0.0006 from the path tracer (#1359). A recipe that sets `shadow` to anything but the defaults keeps exactly what it set; one that writes the default values out is read as having left it out. A flat horizontal slab wider than 10 m and under 15 percent as thick as it is wide, counted with the bounds padding (a ground plane) is left out of the fit when other parts exist, so a 1 m object on a 50 m plane keeps the default view and its sharp shadow instead of getting a 40 m one.diff --git a/src/floor-sky-visibility.js b/src/floor-sky-visibility.jsindex c5db6eea..881bb7e4 100644--- a/src/floor-sky-visibility.js+++ b/src/floor-sky-visibility.js@@ -44,6 +44,32 @@ export function interiorSkyFill(openShare, meanAlbedo) {return Math.min(INTERIOR_FILL_MAXIMUM, (INTERIOR_FILL_GAIN * albedo * open) / (1 - albedo * (1 - open)));}+// The hue of the daylit ambient light that the shader's sky term gives a surface (blue-white). The fill is bounced light, so it has+// the room's albedo hue, and dividing that by this hue makes the shader's blue ambient come out as the bounce colour. Fitted on the window room.+export const INTERIOR_SKY_HUE = Object.freeze([0.82, 1, 1.75]);+// How much of the fill a point loses where its rays meet a surface close by (a corner or a wall/floor junction): the fill is spread over the points so its room-wide mean stays the same.+export const INTERIOR_CORNER_FALLOFF = 0.4;+// "Close by" is this share of the room's smallest span.+export const INTERIOR_NEAR_SPAN_SHARE = 0.15;++const LUMINANCE_WEIGHTS = [0.2126, 0.7152, 0.0722];++/**+ * The colour factor that gives the fill the hue of the light a room bounces: the area-weighted mean albedo of its surfaces over the+ * daylight hue, scaled to the same luminance so the tint moves hue only, never the level. Neutral albedo gives a factor that undoes+ * the blue of the sky term.+ */+export function interiorFillTint(meanAlbedo) {+ const raw = meanAlbedo.map((value, channel) => Math.max(value, 0.01) / INTERIOR_SKY_HUE[channel]);+ const luminance = raw.reduce((total, value, channel) => total + value * LUMINANCE_WEIGHTS[channel], 0);+ return raw.map(value => value / luminance);+}++/** How strongly a point is lit by the fill relative to the room mean: 1 in the open, lower the more of its rays meet a surface close by. */+export function interiorCornerWeight(nearShare) {+ return Math.max(0, 1 - INTERIOR_CORNER_FALLOFF * nearShare);+}+// A traced point sees the room from inside when at most this share of its rays escape; the outer face of a wall (about half, the ground hides the rest) and the lawn see the sky and are not part of the room.const INTERIOR_MAXIMUM_ESCAPE = 0.25;@@ -54,22 +80,32 @@ function isInteriorVertex(escapedShare) {/*** The fill for the traced parts of a closed room: `openShare` is what the room opens to the sky (1 minus the closed-room ray share); the mean albedo is taken over the points that see* the room from inside (the cut gives every part about the same area per point), and only those points get the fill.- * Each traced part is `{ skyVisibility, escapedShares, tracedVertices, albedo }`; their `skyVisibility` is raised in place.+ * The fill is scaled by `interiorCornerWeight` (less in corners and at junctions) and tinted by `interiorFillTint` through the vertex+ * colour, in proportion to the share of the point's light that is fill and not at all where the sun reaches the point.+ * Each traced part is `{ skyVisibility, escapedShares, nearShares, sunlit, colors, tracedVertices, albedo }`; their `skyVisibility` and `colors` are changed in place.*/function applyInteriorFill(tracedParts, openShare) {let count = 0;- let albedoTotal = 0;- for (const { escapedShares, tracedVertices, albedo } of tracedParts) {+ const albedoTotal = [0, 0, 0];+ for (const { escapedShares, nearShares, tracedVertices, albedo } of tracedParts) {for (const vertex of tracedVertices) {if (!isInteriorVertex(escapedShares[vertex])) continue;count++;- albedoTotal += albedo;+ for (let channel = 0; channel < 3; channel++) albedoTotal[channel] += albedo[channel];}}- const fill = count > 0 ? interiorSkyFill(openShare, albedoTotal / count) : 0;- for (const { skyVisibility, escapedShares, tracedVertices } of tracedParts) {+ if (count === 0) return 0;+ const meanAlbedo = albedoTotal.map(total => total / count);+ const fill = interiorSkyFill(openShare, (meanAlbedo[0] + meanAlbedo[1] + meanAlbedo[2]) / 3);+ const tint = interiorFillTint(meanAlbedo);+ for (const { skyVisibility, escapedShares, nearShares, sunlit, colors, tracedVertices } of tracedParts) {for (const vertex of tracedVertices) {- if (isInteriorVertex(escapedShares[vertex])) skyVisibility[vertex] = Math.min(1, skyVisibility[vertex] + fill);+ if (!isInteriorVertex(escapedShares[vertex])) continue;+ const pointFill = fill * interiorCornerWeight(nearShares[vertex]);+ const lifted = Math.min(1, skyVisibility[vertex] + pointFill);+ const fillShare = sunlit[vertex] || lifted === 0 ? 0 : (lifted - skyVisibility[vertex]) / lifted;+ skyVisibility[vertex] = lifted;+ for (let channel = 0; channel < 3; channel++) colors[vertex * 3 + channel] *= 1 + fillShare * (tint[channel] - 1);}}return fill;@@ -262,6 +298,18 @@ function cutGeometry(geometry, matrix, maximumEdge, onlyUpward = true) {return { builder, indices, tracedVertices };}+// A trace of the surfaces near a point stops at this distance: `INTERIOR_NEAR_SPAN_SHARE` of the smallest span of the parts.+function nearDistanceOf(parts, partIndices) {+ const { minimum, maximum } = sceneBoundsOf(partIndices.map(index => worldBounds(parts[index])));+ return INTERIOR_NEAR_SPAN_SHARE * Math.min(maximum[0] - minimum[0], maximum[1] - minimum[1], maximum[2] - minimum[2]);+}++// True when the sun reaches the point: its light keeps the colour it has, so the fill's tint leaves the point alone.+function seesSun(tracer, point, normal, offset, sunDirection) {+ if (normal[0] * sunDirection[0] + normal[1] * sunDirection[1] + normal[2] * sunDirection[2] <= 0) return false;+ return tracer.trace(point[0] + normal[0] * offset, point[1] + normal[1] * offset, point[2] + normal[2] * offset, sunDirection[0], sunDirection[1], sunDirection[2], Infinity, true).nearestTriangle < 0;+}+function fixedSamples(sampleCount) {return Array.from({ length: sampleCount }, (unused, sample) => [(sample + 0.5) / sampleCount, (radicalInverse(sample) + FIXED_ROTATION) % 1]);}@@ -273,7 +321,7 @@ function fixedSamples(sampleCount) {* larger than the bake's triangle limit, or the trace passes `maxSeconds`. It reads no clock to decide anything else, and* the rays are a fixed set, so the same scene gives the same bytes.*/-export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS, maximumTexels = FLOOR_SKY_MAXIMUM_TEXELS, maxSeconds = FLOOR_SKY_MAXIMUM_SECONDS, maximumRays = FLOOR_SKY_MAXIMUM_RAYS, strength: requestedStrength, includeClosedRooms = false, onlyClosedRooms = false, surfaces = 'floors' } = {}) {+export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS, maximumTexels = FLOOR_SKY_MAXIMUM_TEXELS, maxSeconds = FLOOR_SKY_MAXIMUM_SECONDS, maximumRays = FLOOR_SKY_MAXIMUM_RAYS, strength: requestedStrength, includeClosedRooms = false, onlyClosedRooms = false, surfaces = 'floors', sunDirection = null } = {}) {const started = performance.now();const unchanged = reason => ({ parts, report: { floors: [], texels: 0, rays: 0, seconds: (performance.now() - started) / 1000, reason } });const floorIndices = findFloorParts(parts);@@ -311,6 +359,7 @@ export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS,const samples = fixedSamples(raysPerTexel);const direction = [0, 0, 0];const worldNormal = [0, 0, 0];+ const nearDistance = everySurface ? nearDistanceOf(parts, cutPartIndices) : 0;const floors = [];let totalRays = 0;const tracedParts = [];@@ -323,6 +372,8 @@ export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS,const vertexCount = builder.positions.length / 3;const skyVisibility = new Float32Array(vertexCount).fill(1);const escapedShares = new Float32Array(vertexCount);+ const nearShares = new Float32Array(vertexCount);+ const sunlit = new Uint8Array(vertexCount);for (const vertex of tracedVertices) {if (performance.now() - started > maxSeconds * 1000) return unchanged('passed maxSeconds');const local = builder.positions.slice(vertex * 3, vertex * 3 + 3);@@ -334,11 +385,15 @@ export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS,worldNormal[1] /= length;worldNormal[2] /= length;let escaped = 0;+ let near = 0;for (const [firstUnit, secondUnit] of samples) {cosineDirection(worldNormal, firstUnit, secondUnit, direction);const hit = tracer.trace(point[0] + worldNormal[0] * offset, point[1] + worldNormal[1] * offset, point[2] + worldNormal[2] * offset, direction[0], direction[1], direction[2], Infinity, true);if (hit.nearestTriangle < 0) escaped++;+ else if (everySurface && tracer.trace(point[0] + worldNormal[0] * offset, point[1] + worldNormal[1] * offset, point[2] + worldNormal[2] * offset, direction[0], direction[1], direction[2], nearDistance, true).nearestTriangle >= 0) near++;}+ nearShares[vertex] = near / raysPerTexel;+ if (everySurface && sunDirection && isInteriorVertex(escaped / raysPerTexel)) sunlit[vertex] = seesSun(tracer, point, worldNormal, offset, sunDirection) ? 1 : 0;skyVisibility[vertex] = 1 - strength * (1 - escaped / raysPerTexel);escapedShares[vertex] = escaped / raysPerTexel;totalRays += raysPerTexel;@@ -352,11 +407,13 @@ export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS,};if (builder.hasUvs) cutGeometryResult.uvs = new Float32Array(builder.uvs);if (builder.hasColors) cutGeometryResult.colors = new Float32Array(builder.colors);+ // The fill tints the colour of a closed room's points, so every part of one carries a colour (white where it had none).+ if (everySurface && !builder.hasColors) cutGeometryResult.colors = new Float32Array(vertexCount * 3).fill(1);nextParts[index] = Object.freeze({ ...part, geometry: Object.freeze(cutGeometryResult) });const floor = { name: part.name, texels: tracedVertices.size, triangles: indices.length / 3, meanVisibility: 1 };floors.push(floor);const albedo = partDiffuseAlbedo(part.material ?? {});- tracedParts.push({ floor, skyVisibility, escapedShares, tracedVertices, albedo: (albedo[0] + albedo[1] + albedo[2]) / 3 });+ tracedParts.push({ floor, skyVisibility, escapedShares, nearShares, sunlit, colors: cutGeometryResult.colors, tracedVertices, albedo });}// A closed room also gets the sky light its surfaces bounce on to each other (#1334): without it every point the window cannot see is as dark as a sealed room.const interiorFill = everySurface ? applyInteriorFill(tracedParts, 1 - roomShare) : 0;@@ -376,6 +433,13 @@ export function environmentHasSun(environment) {return (environment?.keyIntensity ?? 1) * (keyColor[0] + keyColor[1] + keyColor[2]) > 0;}+function unitSunDirection(environment) {+ const direction = environment?.lightDirection;+ if (!direction) return null;+ const length = Math.hypot(...direction);+ return length > 0 ? direction.map(component => component / length) : null;+}+/*** The default for a scene: a closed room a sun lights gets the sky trace at `FLOOR_SKY_ROOM_STRENGTH`, and every other scene (open ground,* a room lit by lamps alone) comes back unchanged, because the trace made those worse against Cycles. `environment.floorSkyTrace: false`@@ -383,7 +447,7 @@ export function environmentHasSun(environment) {*/export function applyDefaultFloorSky(parts, environment, options = {}) {if (environment?.floorSkyTrace === false || !environmentHasSun(environment)) return { parts, report: null };- return applyFloorSkyVisibility(parts, { onlyClosedRooms: true, surfaces: 'all', ...options });+ return applyFloorSkyVisibility(parts, { onlyClosedRooms: true, surfaces: 'all', sunDirection: unitSunDirection(environment), ...options });}const defaultResults = new WeakMap();diff --git a/tests/interior-fill.test.js b/tests/interior-fill.test.jsindex 806451f3..8c34ec25 100644--- a/tests/interior-fill.test.js+++ b/tests/interior-fill.test.js@@ -3,31 +3,33 @@import test from 'node:test';import assert from 'node:assert/strict';import { box } from '../src/geometry.js';-import { applyDefaultFloorSky, interiorSkyFill, INTERIOR_FILL_MAXIMUM } from '../src/floor-sky-visibility.js';+import { applyDefaultFloorSky, interiorSkyFill, interiorFillTint, interiorCornerWeight, INTERIOR_FILL_MAXIMUM } from '../src/floor-sky-visibility.js';const HALF_WIDTH = 4;const FRONT = -3;const BACK = 3.5;const HEIGHT = 3;const WALL = 0.2;-const SUN = { keyIntensity: 1 };+const SUN = { keyIntensity: 1, lightDirection: [0.3, 0.55, -0.8] };+const PLASTER = [0.75, 0.72, 0.66];+const WOOD = [0.45, 0.32, 0.2];-function slab(name, center, size) {+function slab(name, center, size, color = [0.7, 0.7, 0.7]) {const matrix = new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);- return { name, geometry: box(0, 1), matrix, material: { color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.9 } };+ return { name, geometry: box(0, 1), matrix, material: { color, metallic: 0, roughness: 0.9 } };}// The probe room of bench/reference/interior-exposure.mjs: a window in the front wall, or none when sealed.-function room({ window }) {+function room({ window, warm = false }) {const depth = BACK - FRONT;const middleZ = (FRONT + BACK) / 2;const frontZ = FRONT - WALL / 2;const parts = [- slab('floor', [0, -WALL / 2, middleZ], [HALF_WIDTH * 2 + WALL * 2, WALL, depth + WALL * 2]),- slab('ceiling', [0, HEIGHT + WALL / 2, middleZ], [HALF_WIDTH * 2 + WALL * 2, WALL, depth + WALL * 2]),- slab('wall-left', [-HALF_WIDTH - WALL / 2, HEIGHT / 2, middleZ], [WALL, HEIGHT, depth + WALL * 2]),- slab('wall-right', [HALF_WIDTH + WALL / 2, HEIGHT / 2, middleZ], [WALL, HEIGHT, depth + WALL * 2]),- slab('wall-back', [0, HEIGHT / 2, BACK + WALL / 2], [HALF_WIDTH * 2, HEIGHT, WALL]),+ slab('floor', [0, -WALL / 2, middleZ], [HALF_WIDTH * 2 + WALL * 2, WALL, depth + WALL * 2], warm ? WOOD : undefined),+ slab('ceiling', [0, HEIGHT + WALL / 2, middleZ], [HALF_WIDTH * 2 + WALL * 2, WALL, depth + WALL * 2], warm ? PLASTER : undefined),+ slab('wall-left', [-HALF_WIDTH - WALL / 2, HEIGHT / 2, middleZ], [WALL, HEIGHT, depth + WALL * 2], warm ? PLASTER : undefined),+ slab('wall-right', [HALF_WIDTH + WALL / 2, HEIGHT / 2, middleZ], [WALL, HEIGHT, depth + WALL * 2], warm ? PLASTER : undefined),+ slab('wall-back', [0, HEIGHT / 2, BACK + WALL / 2], [HALF_WIDTH * 2, HEIGHT, WALL], warm ? PLASTER : undefined),];if (!window) {parts.push(slab('wall-front', [0, HEIGHT / 2, frontZ], [HALF_WIDTH * 2, HEIGHT, WALL]));@@ -90,3 +92,73 @@ test('an open scene gets no fill', () => {const { report } = applyDefaultFloorSky(open, SUN, { maximumTexels: 4000 });assert.equal(report.interiorFill ?? 0, 0);});++// The vertices of the inside face of the back wall, as `{ visibility, color, height }` (the world height of the vertex).+function backWallInsideVertices(part) {+ const { skyVisibility, normals, colors, positions } = part.geometry;+ const vertices = [];+ for (let vertex = 0; vertex < skyVisibility.length; vertex++) {+ if (Math.round(normals[vertex * 3 + 2]) !== -1) continue;+ const height = part.matrix[5] * positions[vertex * 3 + 1] + part.matrix[13];+ vertices.push({ visibility: skyVisibility[vertex], color: [colors[vertex * 3], colors[vertex * 3 + 1], colors[vertex * 3 + 2]], height });+ }+ return vertices;+}++// The mean red over blue of the colour of the floor's top-face vertices within 0.3 m of the world point (x, z).+function floorColorAround(part, x, z) {+ const { colors, normals, positions } = part.geometry;+ const ratios = [];+ for (let vertex = 0; vertex < normals.length / 3; vertex++) {+ if (Math.round(normals[vertex * 3 + 1]) !== 1) continue;+ const worldX = part.matrix[0] * positions[vertex * 3] + part.matrix[12];+ const worldZ = part.matrix[10] * positions[vertex * 3 + 2] + part.matrix[14];+ if (Math.hypot(worldX - x, worldZ - z) < 0.3) ratios.push(colors[vertex * 3] / colors[vertex * 3 + 2]);+ }+ assert.ok(ratios.length > 0, `no floor vertex near ${x}, ${z}`);+ return mean(ratios);+}++function mean(values) {+ return values.reduce((total, value) => total + value, 0) / values.length;+}++test('the tint turns the shader blue ambient into the colour the room bounces, without changing its level', () => {+ const luminance = tint => 0.2126 * tint[0] + 0.7152 * tint[1] + 0.0722 * tint[2];+ const neutral = interiorFillTint([0.6, 0.6, 0.6]);+ const warm = interiorFillTint([0.66, 0.6, 0.52]);+ assert.ok(neutral[0] > 1 && neutral[2] < 1, `a grey room undoes the blue of the sky term: ${neutral}`);+ assert.ok(warm[0] / warm[2] > neutral[0] / neutral[2] + 0.1, `a warm room tints warmer than a grey one: ${warm} against ${neutral}`);+ assert.ok(Math.abs(luminance(neutral) - 1) < 1e-9 && Math.abs(luminance(warm) - 1) < 1e-9);+});++test('the corner weight is 1 in the open and falls as more rays meet a surface close by', () => {+ assert.equal(interiorCornerWeight(0), 1);+ assert.ok(interiorCornerWeight(0.5) < interiorCornerWeight(0.2));+ assert.ok(interiorCornerWeight(1) > 0.4 && interiorCornerWeight(1) < 0.8, `the most a corner loses is ${1 - interiorCornerWeight(1)}`);+});++test('the fill is warm on the walls of a warm room, and the sealed room and the sunlit floor keep their colour', () => {+ const windowed = applyDefaultFloorSky(room({ window: true, warm: true }), SUN, { maximumTexels: 4000 }).parts;+ const sealed = applyDefaultFloorSky(room({ window: false, warm: true }), SUN, { maximumTexels: 4000 }).parts;+ const wallColors = backWallInsideVertices(windowed.find(part => part.name === 'wall-back')).map(vertex => vertex.color);+ const redOverBlue = mean(wallColors.map(color => color[0] / color[2]));+ assert.ok(redOverBlue > 1.2, `the back wall's fill is warm: red over blue ${redOverBlue.toFixed(2)}`);+ for (const part of sealed) {+ assert.ok(part.geometry.colors.every(channel => channel === 1), `a sealed room keeps white vertex colours (${part.name})`);+ }+ const floor = windowed.find(part => part.name === 'floor');+ // Sun toward [0.3, 0.55, -0.8] through the window lands on the floor around x -1.4, z -0.6 (the patch's middle); the far corner stays in shade.+ const sunlitRedOverBlue = floorColorAround(floor, -1.4, -0.6);+ const shadedRedOverBlue = floorColorAround(floor, 2.5, 2.5);+ assert.ok(Math.abs(sunlitRedOverBlue - 1) < 1e-6, `the floor where the sun lands keeps its colour: red over blue ${sunlitRedOverBlue}`);+ assert.ok(shadedRedOverBlue > 1.1, `the shaded floor takes the tint: red over blue ${shadedRedOverBlue}`);+});++test('the fill fades toward the wall/floor junction instead of staying flat', () => {+ const windowed = applyDefaultFloorSky(room({ window: true }), SUN, { maximumTexels: 4000 }).parts;+ const vertices = backWallInsideVertices(windowed.find(part => part.name === 'wall-back'));+ const nearFloor = mean(vertices.filter(vertex => vertex.height < 0.2).map(vertex => vertex.visibility));+ const middle = mean(vertices.filter(vertex => vertex.height > 1.2 && vertex.height < 1.8).map(vertex => vertex.visibility));+ assert.ok(nearFloor < middle - 0.03, `the junction is darker: ${nearFloor.toFixed(3)} against the wall's middle ${middle.toFixed(3)}`);+});