3D engine that AI agents drive
Remove bake streaks and fog glow speckle in dark scenes
Nguyen Xuan An08085ecf215d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7791205..1e75f2a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Remove the streaks in baked dark scenes and the speckle in the fog's glow (part of issue #159, which stays open). A bake unwrapped each shared geometry once at unit size, so a 2 x 32 x 180 m wall got texels 90 times longer than wide (carpet 2,867 times), which drew as streaks fanning from the vanishing point; it now unwraps each part at its world size and smooths the gathered light and sky visibility over neighbouring texels of the same surface. The glow reads the frame's mip chain instead of 24 jittered single pixels. `bench/reference/noise.py` measures what FLIP misses (high frequency energy in dark regions and around the door): `temple-hall` baked 0.448 to 0.182 and its glow ring 1.826 to 0.990 (Cycles 0.158 and 1.053), `dark-shaft` baked 0.318 to 0.150; whole frame scores against Cycles stay within 0.006 and `temple-hall` baked goes from 0.0716 to 0.0578. A baked part's report `skyVisibility` now weighs texels by area, and baked thin parts get more texels (`brick-room` 28,576 to 98,848). Core grows 92 bytes gzip and a frame with fog costs about 0.5 ms more on a shared machine. **Baked scenes with long or thin parts look smoother and lightmaps are larger.**- Light the fog around bright sources and keep it dark in closed rooms (part of issue #159, which stays open). `volumeFog` added a constant ambient everywhere, so the air of a closed room glowed; it now keeps 15 percent of it where the sun's shadow map says the fog is in shadow. It also scatters the light of bright pixels sideways: 24 jittered taps of the frame, weighted by the fog opacity. Against Cycles, `dark-shaft` goes from 0.2321 to 0.1425 (shaft region 0.2157 to 0.1219), `temple-hall` from 0.2126 to 0.1438 (region 0.2512 to 0.2341), and the older `fog` from 0.2643 to 0.2238; all other scenes are unchanged to four digits. Core grows 115 bytes gzip and a frame with fog costs about 0.1 to 0.3 ms more. **Fog scenes get brighter around bright sources and darker in shadow.**- Stop world light from reaching closed spaces in a baked scene, and score bright regions on their own (part of issue #159, which stays open). A bake now records how much sky each texel sees from the rays it already shoots, and a part that sees under 98 percent of it gets that as an `occlusionMap` read through the lightmap UVs, so the shader's world diffuse light and reflections shrink inside a closed room. A part that sees the sky gets no map, a scene without a bake runs the same shaders, and there is no new recipe field. Against Cycles, `dark-shaft` (new: a closed room, one roof opening, a sun shaft in fog) goes from 0.2612 with the old bake to 0.1301 and `temple-hall` from 0.2239 to 0.1129 (EEVEE 0.2653 and 0.2341), and a `brightRegion` that `score.py` picks from the Cycles image scores the shaft pixels on their own. The no-bake scores of `outdoor-hdri`, `character`, `metal`, `car-paint` and `foliage` are unchanged to four digits. **A baked part that sees little sky now draws darker.**- Let a key shadow block the sun fully. It kept 18 percent of the sun, so a sealed hall was evenly lit and every shadow was too light. **This darkens shadows in existing scenes that have no fill light.** Against Cycles, `temple-hall` goes from 0.5841 to 0.2126 (EEVEE 0.2341), `mountain-valley` from 0.3658 to 0.3473 and `long-street` from 0.1555 to 0.1407; `fog` (+0.0031) and `megacity-dusk` (+0.0044) get worse.diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 490f7a8d..a7a51716 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -100,6 +100,37 @@ The region of `dark-shaft` improved clearly without a bake (0.2157 to 0.1219). TCost: `frame-time.mjs dark-shaft gpu`, plain frame, two runs each on a loaded machine: 1.9 and 2.1 ms before, 2.1 and 2.3 ms after, so about 0.1 to 0.3 ms for the 24 extra taps. The core entry grows by 115 bytes gzip (83,853 to 83,968), and six size budgets rose by 50 to 100 bytes because their bundles contain the post shader. `images/dark-shaft-baked.jpg` and `images/temple-hall-baked.jpg` come from `npm run reference -- --bake dark-shaft,temple-hall`.+## Streaks and speckle in dark scenes (2026-11-02, part of issue #159)++FLIP does not punish two defects that show at a glance in the baked frames and around the door of `temple-hall`, so `bench/reference/noise.py` measures them. It takes the display-space luminance of a frame, subtracts a gaussian blur of it (sigma 6 px) and reports the standard deviation of what is left, as a percentage, over two regions chosen from the Cycles image: `dark` (Cycles under 0.1 and more than 12 px from any brighter pixel, where walls, ceiling and floor sit) and `glow` (30 to 60 px from the pixels where Cycles is over 0.5, the ring around the door). Cycles has its own path tracing noise, so its value is the floor a clean render reaches, not zero.++**Bake streaks.** Cause, measured: `planLightmaps` unwrapped each geometry once, at unit size, and gave every part that shares it the same layout. The hall's walls, floor and carpet all share the unit box, so a 2 x 32 x 180 m wall got one square of the lightmap per face, the same as a 2 m cube. The texels were 90 times longer than wide on the wall, 180 times on the floor and 2,867 times on the carpet (up to 5 m long, 0.002 m wide), which draws as streaks that fan out from the vanishing point along every long edge, and as the red lines on the carpet. The unwrap now sees the part at its world size (the length of each matrix column, normals by the inverse transpose), is cached per geometry and scale, and gives texels of equal size both ways (stretch 1.00 on all three parts). A second effect stayed once the streaks were gone: each texel has only 48 rays, so the lightmap was grain. `smoothTexels` now blurs the gathered light and the sky visibility over neighbouring texels (two passes of a gaussian, sigma 1.5 texels, a 7 x 7 window) and counts a neighbour only when it lies on the same plane (normal dot above 0.9, within one texel of this texel's plane), so a corner, a seam and the gap between two parts do not leak. Only fixing the stretch made the metric worse (`temple-hall` baked 0.448 to 0.443, `dark-shaft` baked 0.318 to 0.375) because streaks became fine grain; the smoothing is what lowers it.++**Glow speckle.** Cause, measured: the 24 taps of the fog's glow each read one pixel of the frame, rotated by the per-pixel step jitter, so the sum is a different 24 samples per pixel. Without the jitter the same taps draw ghost copies of the door. Each tap now reads the frame's mip chain at the level that covers the gap between neighbouring taps (`log2(0.7 * radius in pixels)`), with no jitter, so the 24 taps add up to a smooth blur. The renderer builds the mips only for a frame with `volumeFog`, and puts the texture back to a plain linear filter when the fog goes away. The ring profile is kept: the mean display luminance 30 to 45 px from the door is 0.0889 before and 0.0903 after, against 0.1000 in Cycles.++High frequency energy against Cycles (`dark` / `glow`; lower is smoother), 67js render on 2026-11-02:++| Scene | Cycles | Before | After |+| --- | --- | --- | --- |+| `temple-hall` baked | 0.158 / 1.053 | 0.448 / 1.826 | 0.182 / 0.990 |+| `temple-hall` no bake | 0.158 / 1.053 | 0.182 / 1.539 | 0.161 / 0.826 |+| `dark-shaft` baked | 0.140 / 0.140 | 0.318 / 0.643 | 0.150 / 0.310 |+| `dark-shaft` no bake | 0.140 / 0.140 | 0.105 / 0.505 | 0.085 / 0.256 |++Scores against Cycles, whole frame (shaft region), before this change and after:++| Scene | No bake before | No bake now | Baked before | Baked now |+| --- | --- | --- | --- | --- |+| `dark-shaft` | 0.1425 (0.1219) | 0.1430 (0.1273) | 0.0669 (0.1814) | 0.0653 (0.1847) |+| `temple-hall` | 0.1438 (0.2341) | 0.1436 (0.2305) | 0.0716 (0.2575) | 0.0578 (0.2550) |+| `fog` | 0.2238 | 0.2242 | | |++The region of baked `dark-shaft` and of plain `dark-shaft` got a little worse (0.0033 and 0.0054), the cost of a smoother glow. Every scene without `volumeFog` and every unbaked scene keeps its scores to four digits. Baked rooms on the same machine and the same scoring: `lit-interior` 0.1974 before and 0.1915 now, `brick-room` 0.2070 and 0.2048 (the 0.1444 and 0.1515 in the CHANGELOG were measured before the one sun and key shadow changes, and the code before this change scores 0.1974 and 0.2070 today). `temple-hall` keeps `bakeOptions` `{ texelsPerUnit: 2, samples: 48, maxSeconds: 300 }`: the bake now has 456,000 texels (440,192 before), under the 1 million limit. Bake time did not change measurably (`temple-hall` 37 to 49 s in the runs of both versions, `dark-shaft` 9 to 13 s, on a loaded machine). `brick-room` has 98,848 texels where it had 28,576, because thin parts no longer share one small square; its bake still takes 3.5 s.++A part's `skyVisibility` in the bake report is now a mean over texels spread by area, so a floor slab reads 0.5 (its top face sees the closed room, its underside sees outside) where every face counted the same before (a slab's four sides then outweighed its top).++Cost: the core entry grows 92 bytes gzip over the fog change (83,968 to 84,060; 207 bytes over the 83,853 before it). `frame-time.mjs dark-shaft gpu`, plain frame on a shared machine: 2.75 and 2.81 ms, where the fog change measured 2.1 and 2.3, so the mip chain costs about 0.5 ms for a frame at 960 x 540 (noisy). Size baseline and budgets were rewritten.+## BaselineMeasured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 058440b8..8b3ee0e5 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -141,24 +141,24 @@"gpu-vs-cpu": 0.0066},"dark-shaft": {- "gpu-vs-cycles": 0.1425,- "gpu-vs-eevee": 0.1826,- "cpu-vs-cycles": 0.1431,- "cpu-vs-eevee": 0.182,+ "gpu-vs-cycles": 0.143,+ "gpu-vs-eevee": 0.1831,+ "cpu-vs-cycles": 0.1437,+ "cpu-vs-eevee": 0.1825,"eevee-vs-cycles": 0.2653,- "gpu-vs-cpu": 0.0057,+ "gpu-vs-cpu": 0.0047,"region-pixels": 0.099,- "region-gpu-vs-cycles": 0.1219,- "region-gpu-vs-eevee": 0.2248,+ "region-gpu-vs-cycles": 0.1273,+ "region-gpu-vs-eevee": 0.2312,"region-eevee-vs-cycles": 0.2643},"fog": {- "gpu-vs-cycles": 0.2238,- "gpu-vs-eevee": 0.1077,- "cpu-vs-cycles": 0.2235,- "cpu-vs-eevee": 0.1082,+ "gpu-vs-cycles": 0.2242,+ "gpu-vs-eevee": 0.1079,+ "cpu-vs-cycles": 0.2239,+ "cpu-vs-eevee": 0.1084,"eevee-vs-cycles": 0.2662,- "gpu-vs-cpu": 0.0111+ "gpu-vs-cpu": 0.0089},"foliage": {"gpu-vs-cycles": 0.129,@@ -257,15 +257,15 @@"gpu-vs-cpu": 0.0032},"temple-hall": {- "gpu-vs-cycles": 0.1438,- "gpu-vs-eevee": 0.1553,- "cpu-vs-cycles": 0.1443,- "cpu-vs-eevee": 0.1548,+ "gpu-vs-cycles": 0.1436,+ "gpu-vs-eevee": 0.1542,+ "cpu-vs-cycles": 0.1441,+ "cpu-vs-eevee": 0.1537,"eevee-vs-cycles": 0.2341,- "gpu-vs-cpu": 0.007,+ "gpu-vs-cpu": 0.0039,"region-pixels": 0.0958,- "region-gpu-vs-cycles": 0.2341,- "region-gpu-vs-eevee": 0.2759,+ "region-gpu-vs-cycles": 0.2305,+ "region-gpu-vs-eevee": 0.2681,"region-eevee-vs-cycles": 0.2455}}diff --git a/bench/reference/images/dark-shaft-baked.jpg b/bench/reference/images/dark-shaft-baked.jpgindex c65a20a0..17b7731d 100644Binary files a/bench/reference/images/dark-shaft-baked.jpg and b/bench/reference/images/dark-shaft-baked.jpg differdiff --git a/bench/reference/images/dark-shaft.jpg b/bench/reference/images/dark-shaft.jpgindex 5ec8379d..a986a57b 100644Binary files a/bench/reference/images/dark-shaft.jpg and b/bench/reference/images/dark-shaft.jpg differdiff --git a/bench/reference/images/fog.jpg b/bench/reference/images/fog.jpgindex ed4709a5..582f894e 100644Binary files a/bench/reference/images/fog.jpg and b/bench/reference/images/fog.jpg differdiff --git a/bench/reference/images/temple-hall-baked.jpg b/bench/reference/images/temple-hall-baked.jpgindex 10156610..b566c2e0 100644Binary files a/bench/reference/images/temple-hall-baked.jpg and b/bench/reference/images/temple-hall-baked.jpg differdiff --git a/bench/reference/images/temple-hall.jpg b/bench/reference/images/temple-hall.jpgindex a211300d..67e88491 100644Binary files a/bench/reference/images/temple-hall.jpg and b/bench/reference/images/temple-hall.jpg differdiff --git a/bench/reference/noise.py b/bench/reference/noise.pynew file mode 100644index 00000000..3b8c317b--- /dev/null+++ b/bench/reference/noise.py@@ -0,0 +1,74 @@+# Measures the speckle and streaks that FLIP does not punish: the high-frequency energy of a 67js frame, against Cycles.+# uv run --no-project --python 3.12 --with pillow --with numpy --with scipy python -I bench/reference/noise.py <67js png> <cycles npy> [<label>]+# Both images go to display space with the tone curve of src/post.js. The energy of a region is the standard deviation of+# (image - gaussian blur of the image) over that region, as a percentage of display luminance.+# dark : pixels where Cycles is darker than DARK_LUMINANCE and farther than DARK_MARGIN pixels from a brighter pixel.+# Streaks and blotches on walls, floors and ceilings land here.+# glow : the ring from GLOW_INNER to GLOW_OUTER pixels around the pixels where Cycles is brighter than GLOW_SOURCE.+# Lower is smoother, and the Cycles value is the floor a clean render reaches (Cycles has its own path tracing noise).+import json+import sys++import numpy as np+from PIL import Image+from scipy import ndimage++GAMMA = 2.2+BLUR_SIGMA = 6+DARK_LUMINANCE = 0.1+DARK_MARGIN = 12+GLOW_SOURCE = 0.5+GLOW_INNER = 30+GLOW_OUTER = 60+LUMA = np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)+++def display_luminance(linear):+ color = np.maximum(linear, 0)+ mapped = np.clip((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0, 1)+ return (mapped ** (1 / GAMMA)) @ LUMA+++def load_png_luminance(path):+ image = np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255+ return image @ LUMA+++def high_frequency(luminance):+ return luminance - ndimage.gaussian_filter(luminance, BLUR_SIGMA)+++def region_masks(cycles_luminance):+ bright = cycles_luminance >= DARK_LUMINANCE+ distance_to_bright = ndimage.distance_transform_edt(~bright)+ dark = distance_to_bright > DARK_MARGIN+ source = cycles_luminance >= GLOW_SOURCE+ distance_to_source = ndimage.distance_transform_edt(~source) if source.any() else np.zeros_like(distance_to_bright)+ glow = source.any() & (distance_to_source >= GLOW_INNER) & (distance_to_source <= GLOW_OUTER)+ return dark, glow+++def energy(luminance, mask):+ if not mask.any():+ return None+ return round(float(high_frequency(luminance)[mask].std()) * 100, 3)+++def measure(png_path, cycles_path):+ cycles = display_luminance(np.load(cycles_path).astype(np.float32))+ image = load_png_luminance(png_path)+ dark, glow = region_masks(cycles)+ source = cycles >= GLOW_SOURCE+ ring = (ndimage.distance_transform_edt(~source) >= 30) & (ndimage.distance_transform_edt(~source) <= 45) if source.any() else glow+ return {+ "ring-30-45": round(float(image[ring].mean()), 4), "ring-30-45-cycles": round(float(cycles[ring].mean()), 4),+ "dark": energy(image, dark), "dark-cycles": energy(cycles, dark),+ "glow": energy(image, glow), "glow-cycles": energy(cycles, glow),+ "dark-pixels": int(dark.sum()), "glow-pixels": int(glow.sum()),+ }+++if __name__ == "__main__":+ result = measure(sys.argv[1], sys.argv[2])+ label = sys.argv[3] if len(sys.argv) > 3 else sys.argv[1]+ print(label, json.dumps(result))diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex b661358e..f2cf62fb 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 291778,- "gzip": 83778,- "brotli": 71349+ "min": 292734,+ "gzip": 84060,+ "brotli": 71533},"entry:model": {"min": 40093,@@ -39,14 +39,14 @@"brotli": 7331},"entry:gltf": {- "min": 170614,- "gzip": 52375,- "brotli": 45267+ "min": 171999,+ "gzip": 52846,+ "brotli": 45706},"entry:gltf+lazy": {- "min": 181587,- "gzip": 55582,- "brotli": 48213+ "min": 183290,+ "gzip": 56173,+ "brotli": 48745},"entry:modeling": {"min": 21149,@@ -69,9 +69,9 @@"brotli": 12998},"entry:mesh": {- "min": 226597,- "gzip": 76567,- "brotli": 64891+ "min": 241629,+ "gzip": 81376,+ "brotli": 68692},"entry:shrinkwrap": {"min": 56188,@@ -118,6 +118,11 @@"gzip": 3322,"brotli": 3012},+ "entry:navmesh": {+ "min": 7206,+ "gzip": 3257,+ "brotli": 2924+ },"entry:grass": {"min": 9441,"gzip": 4236,@@ -129,9 +134,9 @@"brotli": 4675},"entry:light-bake": {- "min": 73438,- "gzip": 26713,- "brotli": 23608+ "min": 76459,+ "gzip": 27896,+ "brotli": 24559},"entry:path-tracer": {"min": 35311,@@ -144,24 +149,24 @@"brotli": 762},"entry:agent-scene": {- "min": 226825,- "gzip": 70681,- "brotli": 61823+ "min": 239032,+ "gzip": 74924,+ "brotli": 65544},"entry:agent-scene+lazy": {- "min": 689337,- "gzip": 237502,- "brotli": 209805+ "min": 734453,+ "gzip": 254034,+ "brotli": 224197},"entry:agent-asset": {- "min": 321931,- "gzip": 102275,- "brotli": 89778+ "min": 334071,+ "gzip": 106324,+ "brotli": 93424},"entry:agent-asset+lazy": {- "min": 726210,- "gzip": 249137,- "brotli": 219752+ "min": 771254,+ "gzip": 265468,+ "brotli": 234049},"entry:hdri": {"min": 8075,@@ -179,44 +184,44 @@"brotli": 1425},"entry:material-layer-shaders": {- "min": 77526,- "gzip": 20073,- "brotli": 17610+ "min": 77871,+ "gzip": 20210,+ "brotli": 17757},"entry:light-linking": {- "min": 68941,- "gzip": 18518,- "brotli": 16273+ "min": 68966,+ "gzip": 18535,+ "brotli": 16283},"entry:cascaded-shadows": {- "min": 96700,- "gzip": 27048,- "brotli": 23073+ "min": 96709,+ "gzip": 27065,+ "brotli": 23102},"scene:lit-box": {- "min": 221329,- "gzip": 61256,- "brotli": 52261+ "min": 222245,+ "gzip": 61522,+ "brotli": 52440},"scene:gltf-box": {- "min": 282929,- "gzip": 81913,- "brotli": 71197+ "min": 284766,+ "gzip": 82521,+ "brotli": 71752},"scene:gltf-box+lazy": {- "min": 293902,- "gzip": 85119,- "brotli": 74130+ "min": 296057,+ "gzip": 85849,+ "brotli": 74800},"scene:agent-scene": {- "min": 329077,- "gzip": 98988,- "brotli": 86269+ "min": 335191,+ "gzip": 101255,+ "brotli": 88193},"scene:agent-scene+lazy": {- "min": 791589,- "gzip": 265817,- "brotli": 234213+ "min": 830612,+ "gzip": 280360,+ "brotli": 246904}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex d9f2012f..5ce5636b 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -6,18 +6,18 @@"agent-scene": 100000},"budgets": {- "entry:core": 84400,+ "entry:core": 85800,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,"entry:canvas2d": 9400,- "entry:gltf": 52850,- "entry:gltf+lazy": 56200,+ "entry:gltf": 54000,+ "entry:gltf+lazy": 57300,"entry:modeling": 8700,"entry:sculpt": 2500,"entry:surface": 10100,"entry:mesh-query": 15900,- "entry:mesh": 81500,+ "entry:mesh": 83100,"entry:shrinkwrap": 18300,"entry:surface-attachment": 11800,"entry:physics": 18000,@@ -27,26 +27,26 @@"entry:vehicle": 14700,"entry:vegetation": 17900,"entry:terrain": 3400,- "entry:navmesh": 3300,+ "entry:navmesh": 3400,"entry:grass": 4400,"entry:clutter": 5300,- "entry:light-bake": 27300,- "entry:path-tracer": 14400,+ "entry:light-bake": 28500,+ "entry:path-tracer": 14600,"entry:texture-set": 900,- "entry:agent-scene": 74900,- "entry:agent-scene+lazy": 253450,- "entry:agent-asset": 106300,- "entry:agent-asset+lazy": 264850,+ "entry:agent-scene": 76500,+ "entry:agent-scene+lazy": 259200,+ "entry:agent-asset": 108500,+ "entry:agent-asset+lazy": 270800,"entry:hdri": 3300,"entry:camera-effects": 8600,"entry:render-passes": 1700,- "entry:material-layer-shaders": 20300,- "entry:light-linking": 18650,- "entry:cascaded-shadows": 27300,- "scene:lit-box": 61450,- "scene:gltf-box": 82500,- "scene:gltf-box+lazy": 85800,- "scene:agent-scene": 101200,- "scene:agent-scene+lazy": 279700+ "entry:material-layer-shaders": 20700,+ "entry:light-linking": 19000,+ "entry:cascaded-shadows": 27700,+ "scene:lit-box": 62800,+ "scene:gltf-box": 84200,+ "scene:gltf-box+lazy": 87600,+ "scene:agent-scene": 103300,+ "scene:agent-scene+lazy": 286000}}diff --git a/src/light-bake.js b/src/light-bake.jsindex 02421223..1e4a08a2 100644--- a/src/light-bake.js+++ b/src/light-bake.js@@ -33,6 +33,13 @@ const DEFAULT_SPOT_PENUMBRA = 0.15;const MAP_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];const SURFACE_UTILIZATION_FLOOR = 0.05;+const MINIMUM_AXIS_SCALE = 1e-6;+// Smoothing of the gathered light over texels of one surface: two passes of a gaussian of sigma 1.5 texels over a 7 x 7 window.+const SMOOTH_PASSES = 2;+const SMOOTH_RADIUS_TEXELS = 3;+const SMOOTH_SIGMA_TEXELS = 1.5;+const SMOOTH_MINIMUM_FACING = 0.9;+const SMOOTH_PLANE_TEXELS = 1;const DILATION_PASSES = 2;const AVERAGE_GRID = 16;const LIGHT_MAP_CLAMP_TO_EDGE = 33071;@@ -514,27 +521,59 @@ function worldTriangleArea(part) {return area;}+/** The length of each matrix column: how far the part stretches a unit step along its own x, y and z. */+export function partAxisScale(matrix) {+ const lengths = [0, 1, 2].map(column => Math.hypot(matrix[column * 4], matrix[column * 4 + 1], matrix[column * 4 + 2]));+ return lengths.map(length => Math.max(length, MINIMUM_AXIS_SCALE));+}++function scaleKey(scale) {+ return scale.map(length => length.toPrecision(6)).join(',');+}++/**+ * The geometry as it is sized in the world, so the unwrap gives every metre the same share of the lightmap. A shared unit+ * box scaled to 2 x 32 x 180 m would otherwise get one square per face and texels 90 times longer than wide, which draws+ * as streaks along the long axis. Normals follow the inverse transpose of the scale.+ */+function scaledForUnwrap(geometry, scale) {+ const positions = Float32Array.from(geometry.positions, (value, index) => value * scale[index % 3]);+ const normals = Float32Array.from(geometry.normals, (value, index) => value / scale[index % 3]);+ return { ...geometry, positions, normals };+}++/** Returns an unwrapped geometry to the part's own units: positions divided, normals multiplied by the scale and made unit length. */+function unscaledAfterUnwrap(extracted, scale) {+ const positions = Float32Array.from(extracted.positions, (value, index) => value / scale[index % 3]);+ const normals = Float32Array.from(extracted.normals, (value, index) => value * scale[index % 3]);+ for (let vertex = 0; vertex < normals.length / 3; vertex++) {+ const length = Math.hypot(normals[vertex * 3], normals[vertex * 3 + 1], normals[vertex * 3 + 2]) || 1;+ for (let axis = 0; axis < 3; axis++) normals[vertex * 3 + axis] /= length;+ }+ return { ...extracted, positions, normals };+}+/** Gives a geometry its lightmap UVs in channel 0, from the unwrap that `uv_unwrap` uses. */-function unwrapForLightmap(geometry) {- const { positions, normals, indices } = geometry;+function unwrapForLightmap(geometry, scale) {+ const { positions, normals, indices } = scaledForUnwrap(geometry, scale);const mesh = meshFromGeometry({ positions, normals, indices }, { quads: false, tags: 'none' });const unwrapped = unwrapUv(mesh);const { geometry: unwrappedGeometry } = extractRender(unwrapped.mesh);- return { geometry: unwrappedGeometry, utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };+ return { geometry: unscaledAfterUnwrap(unwrappedGeometry, scale), utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };}/*** Gives a geometry lightmap UVs in `lightUvs` and keeps its own `uvs` and `colors`. The unwrap splits vertices along its* seams, so each source vertex index rides through it as a corner colour and the attributes are gathered back from it.*/-function unwrapIntoSecondUvSet(geometry) {- const { positions, normals, indices } = geometry;+function unwrapIntoSecondUvSet(geometry, scale) {+ const { positions, normals, indices } = scaledForUnwrap(geometry, scale);const vertexCount = positions.length / 3;const sourceIndices = new Float32Array(vertexCount * 3);for (let vertex = 0; vertex < vertexCount; vertex++) sourceIndices[vertex * 3] = vertex;const mesh = meshFromGeometry({ positions, normals, indices, colors: sourceIndices }, { quads: false, tags: 'none' });const unwrapped = unwrapUv(mesh);- const { geometry: extracted } = extractRender(unwrapped.mesh);+ const extracted = unscaledAfterUnwrap(extractRender(unwrapped.mesh).geometry, scale);const newCount = extracted.positions.length / 3;const result = { positions: extracted.positions, normals: extracted.normals, indices: extracted.indices, lightUvs: extracted.uvs };const uvs = geometry.uvs ? new Float32Array(newCount * 2) : null;@@ -658,6 +697,54 @@ function dilate(radiance, covered, resolution) {}}+/**+ * Smooths the gathered values (each an array of three floats per texel) over neighbouring texels of the same surface.+ * A texel has only `samples` rays, so its value is noisy, and the noise reads as grain on every wall. A neighbour counts only+ * when it lies on the same plane (its normal agrees and its position is within a texel of this texel's plane), so a corner,+ * a seam between charts and the gap between two parts never leak light into each other. Same input, same bytes.+ */+export function smoothTexels(arrays, covered, positions, normals, resolution, spacing) {+ const radius = SMOOTH_RADIUS_TEXELS;+ const sigmaSquared = SMOOTH_SIGMA_TEXELS * SMOOTH_SIGMA_TEXELS;+ const planeTolerance = spacing * SMOOTH_PLANE_TEXELS;+ let sources = arrays;+ for (let pass = 0; pass < SMOOTH_PASSES; pass++) {+ const results = sources.map(source => new Float32Array(source.length));+ for (let row = 0; row < resolution; row++) {+ for (let column = 0; column < resolution; column++) {+ const center = row * resolution + column;+ if (!covered[center]) continue;+ const totals = sources.map(() => [0, 0, 0]);+ let weightSum = 0;+ for (let rowShift = -radius; rowShift <= radius; rowShift++) {+ const neighbourRow = row + rowShift;+ if (neighbourRow < 0 || neighbourRow >= resolution) continue;+ for (let columnShift = -radius; columnShift <= radius; columnShift++) {+ const neighbourColumn = column + columnShift;+ if (neighbourColumn < 0 || neighbourColumn >= resolution) continue;+ const neighbour = neighbourRow * resolution + neighbourColumn;+ if (!covered[neighbour]) continue;+ const facing = normals[center * 3] * normals[neighbour * 3] + normals[center * 3 + 1] * normals[neighbour * 3 + 1] + normals[center * 3 + 2] * normals[neighbour * 3 + 2];+ if (facing < SMOOTH_MINIMUM_FACING) continue;+ const offset = (positions[neighbour * 3] - positions[center * 3]) * normals[center * 3] + (positions[neighbour * 3 + 1] - positions[center * 3 + 1]) * normals[center * 3 + 1] + (positions[neighbour * 3 + 2] - positions[center * 3 + 2]) * normals[center * 3 + 2];+ if (Math.abs(offset) > planeTolerance) continue;+ const weight = Math.exp(-(rowShift * rowShift + columnShift * columnShift) / (2 * sigmaSquared));+ weightSum += weight;+ sources.forEach((source, which) => {+ for (let channel = 0; channel < 3; channel++) totals[which][channel] += weight * source[neighbour * 3 + channel];+ });+ }+ }+ results.forEach((result, which) => {+ for (let channel = 0; channel < 3; channel++) result[center * 3 + channel] = totals[which][channel] / weightSum;+ });+ }+ }+ sources = results;+ }+ return sources;+}+function lightmapDescriptor(bytes, resolution, colorSpace) {return { image: createImage(bytes, resolution, resolution), colorSpace, wrapS: LIGHT_MAP_CLAMP_TO_EDGE, wrapT: LIGHT_MAP_CLAMP_TO_EDGE, minFilter: LIGHT_MAP_LINEAR, magFilter: LIGHT_MAP_LINEAR };}@@ -731,9 +818,13 @@ export function planLightmaps(parts, lighting, options = {}) {return;}const slot = usesLightMapSlot(part.material);+ const scale = partAxisScale(part.matrix);const cache = slot ? secondSetCache : unwrapCache;- if (!cache.has(part.geometry)) cache.set(part.geometry, slot ? unwrapIntoSecondUvSet(part.geometry) : unwrapForLightmap(part.geometry));- entries.push({ part, index, unwrapped: cache.get(part.geometry), area: worldTriangleArea(part), slot });+ if (!cache.has(part.geometry)) cache.set(part.geometry, new Map());+ const unwraps = cache.get(part.geometry);+ const key = scaleKey(scale);+ if (!unwraps.has(key)) unwraps.set(key, slot ? unwrapIntoSecondUvSet(part.geometry, scale) : unwrapForLightmap(part.geometry, scale));+ entries.push({ part, index, unwrapped: unwraps.get(key), area: worldTriangleArea(part), slot });});return { parts, lights, settings, started, entries, skipped };}@@ -801,10 +892,13 @@ export function traceLightmaps(plan, tracedSettings) {const sealed = meanSkyVisibility < SKY_VISIBLE_ENOUGH && !part.material.occlusionMap;if (peak <= 0 && !sealed) continue;let bakedResult = part;- if (sealed) dilate(skyVisibility, covered.slice(), resolution);- dilate(radiance, covered, resolution);- if (peak > 0) bakedResult = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, lightmapTexture(radiance, resolution, peak), peak);- if (sealed) bakedResult = skyVisibilityPart(bakedResult, unwrapped.geometry, skyVisibilityTexture(skyVisibility, resolution), slot);+ const spacing = Math.sqrt(area / Math.max(skyTexels, 1));+ const [smoothRadiance, smoothSkyVisibility] = smoothTexels([radiance, skyVisibility], covered, positions, normals, resolution, spacing);+ if (sealed) dilate(smoothSkyVisibility, covered.slice(), resolution);+ dilate(smoothRadiance, covered, resolution);+ const smoothPeak = smoothRadiance.reduce((largest, value) => Math.max(largest, value), 0);+ if (smoothPeak > 0) bakedResult = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, lightmapTexture(smoothRadiance, resolution, smoothPeak), smoothPeak);+ if (sealed) bakedResult = skyVisibilityPart(bakedResult, unwrapped.geometry, skyVisibilityTexture(smoothSkyVisibility, resolution), slot);baked[index] = bakedResult;}const report = { parts: partReports, skipped, texels: texelTotal, rayWork, seconds: (performance.now() - started) / 1000 };diff --git a/src/post.js b/src/post.jsindex 9ef02846..d8012c74 100644--- a/src/post.js+++ b/src/post.js@@ -142,9 +142,10 @@ vec3 volumeFog(vec3 background) {if (transmittance < 0.001) break;}for (int tap = 0; tap < 24; tap++) {- float index = float(tap) + jitter;- vec2 offset = vec2(cos(index * 2.4) * resolution.y / resolution.x, sin(index * 2.4)) * (0.03 + 0.0002 * index * index);- accumulated += texture(frameTexture, textureCoordinate + offset).rgb * volumeColor * (0.009 * (1.0 - transmittance) / (1.0 + 0.04 * index));+ float index = float(tap) + 0.5;+ float radius = 0.03 + 0.0002 * index * index;+ vec2 offset = vec2(cos(index * 2.4) * resolution.y / resolution.x, sin(index * 2.4)) * radius;+ accumulated += textureLod(frameTexture, textureCoordinate + offset, log2(0.7 * radius * resolution.y)).rgb * volumeColor * (0.009 * (1.0 - transmittance) / (1.0 + 0.04 * index));}return accumulated + background * transmittance;}diff --git a/src/renderer.js b/src/renderer.jsindex ad3ed8d5..e760e7d2 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1585,6 +1585,15 @@ export class Renderer67 {context.useProgram(post.program);context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, sourceTexture);+ // The fog's glow reads blurred copies of the frame from its mip chain, so a tap is smooth instead of one speckled pixel.+ if (volume.density > 0) {+ context.generateMipmap(context.TEXTURE_2D);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_LINEAR);+ this.mipmappedTexture = sourceTexture;+ } else if (this.mipmappedTexture === sourceTexture) {+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);+ this.mipmappedTexture = null;+ }context.uniform1i(post.uniforms.frameTexture, 0);context.activeTexture(context.TEXTURE1);context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);diff --git a/tests/agent-bake.test.js b/tests/agent-bake.test.jsindex dd64e5e8..2d2abfec 100644--- a/tests/agent-bake.test.js+++ b/tests/agent-bake.test.js@@ -239,7 +239,7 @@ test('explicit settings far above the preset budget run when they fit the hard l});test('an explicit bake that passes maxSeconds fails cleanly with a lower setting to try', () => {- const slow = { samples: 256, bounces: 3, texelsPerUnit: 7 };+ const slow = { samples: 256, bounces: 3, texelsPerUnit: 4 };// A fast machine finishes this bake inside the real limit, so each clock read is made to cost a second.const realNow = performance.now;let clockReads = 0;diff --git a/tests/light-bake-texel-density.test.js b/tests/light-bake-texel-density.test.jsnew file mode 100644index 00000000..0ba77885--- /dev/null+++ b/tests/light-bake-texel-density.test.js@@ -0,0 +1,56 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { box } from '../src/geometry.js';+import { bakeLightmaps, partAxisScale } from '../src/light-bake.js';++const cube = box(0, 1);++function placed(name, translation, scale) {+ const matrix = new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]);+ return { name, geometry: cube, matrix, material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0 } };+}++// How many times longer a texel is along u than along v on each triangle of a baked part, in metres.+function texelStretchPerTriangle(part) {+ const { positions, indices, uvs } = part.geometry;+ const scale = partAxisScale(part.matrix);+ const stretches = [];+ for (let triangle = 0; triangle < indices.length / 3; triangle++) {+ const [first, second, third] = [0, 1, 2].map(corner => indices[triangle * 3 + corner]);+ const edgeOne = [0, 1, 2].map(axis => (positions[second * 3 + axis] - positions[first * 3 + axis]) * scale[axis]);+ const edgeTwo = [0, 1, 2].map(axis => (positions[third * 3 + axis] - positions[first * 3 + axis]) * scale[axis]);+ const uOne = uvs[second * 2] - uvs[first * 2];+ const vOne = uvs[second * 2 + 1] - uvs[first * 2 + 1];+ const uTwo = uvs[third * 2] - uvs[first * 2];+ const vTwo = uvs[third * 2 + 1] - uvs[first * 2 + 1];+ const determinant = uOne * vTwo - vOne * uTwo;+ if (Math.abs(determinant) < 1e-12) continue;+ const alongU = edgeOne.map((value, axis) => (value * vTwo - edgeTwo[axis] * vOne) / determinant);+ const alongV = edgeOne.map((value, axis) => (-value * uTwo + edgeTwo[axis] * uOne) / determinant);+ stretches.push(Math.hypot(...alongU) / Math.hypot(...alongV));+ }+ return stretches;+}++test('a long thin part that shares the unit box keeps square texels in the world', () => {+ // The parts share one geometry. Unwrapped once at unit size, every face of a 2 x 32 x 180 m wall got one square of the+ // lightmap, so its texels were 90 times longer than wide and the bake drew as streaks along the long axis.+ const parts = [+ placed('wall', [-4, 16, 0], [2, 32, 180]),+ placed('carpet', [0, 0.03, 0], [5, 0.06, 172]),+ placed('cube', [4, 1, 0], [2, 2, 2]),+ ];+ const lighting = { pointLights: [{ position: [0, 10, 0], color: [1, 1, 1], intensity: 400, radius: 0.1 }], keyColor: [0, 0, 0] };+ const { parts: baked } = bakeLightmaps(parts, lighting, { samples: 2, bounces: 1, texelsPerUnit: 1, maxResolution: 64 });+ assert.equal(parts[0].geometry, parts[1].geometry);+ for (const part of baked) {+ const stretches = texelStretchPerTriangle(part);+ assert.ok(stretches.length > 0, `${part.name} has triangles with area in the lightmap`);+ const worst = Math.max(...stretches.map(stretch => Math.max(stretch, 1 / stretch)));+ assert.ok(worst < 1.25, `${part.name} texels are ${worst.toFixed(2)} times longer one way than the other`);+ const { normals } = part.geometry;+ for (let vertex = 0; vertex < normals.length / 3; vertex++) {+ assert.ok(Math.abs(Math.hypot(normals[vertex * 3], normals[vertex * 3 + 1], normals[vertex * 3 + 2]) - 1) < 1e-4);+ }+ }+});diff --git a/tests/light-bake.test.js b/tests/light-bake.test.jsindex ae91ae99..eb85b9fc 100644--- a/tests/light-bake.test.js+++ b/tests/light-bake.test.js@@ -74,7 +74,9 @@ test('a part that sees little of the sky gets a linear occlusion map, and a partassert.equal(closedFloor.material.occlusionMap.colorSpace, 'linear');assert.equal(closedFloor.material.occlusionStrength, 1);assert.ok(Math.min(...closedFloor.material.occlusionMap.image.data.filter((value, index) => index % 4 === 0)) < 8);- assert.ok(closed.report.parts[0].skyVisibility < 0.5);+ // The mean is over texels, and a floor slab is half top face (sees the closed room) and half underside (sees outside), now that texels are spread by area.+ assert.ok(Math.abs(closed.report.parts[0].skyVisibility - 0.5) < 0.05);+ assert.ok(closed.report.parts[6].skyVisibility < 0.05);const open = bakeLightmaps([placed('floor', [0, -0.05, 0], [6, 0.1, 6])], lamp, fastOptions);assert.equal(open.parts[0].material.occlusionMap, undefined);assert.equal(open.report.parts[0].skyVisibility, 1);