ugly-game 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,75 @@
1
+ export interface ProbeGrid {
2
+ ox: number;
3
+ oy: number;
4
+ oz: number;
5
+ /** World units between adjacent probes. */
6
+ cell: number;
7
+ nx: number;
8
+ ny: number;
9
+ nz: number;
10
+ }
11
+ /** What a ray found. `albedo` is the surface colour used for the single bounce. */
12
+ export interface TraceHit {
13
+ t: number;
14
+ n: [number, number, number];
15
+ albedo: [number, number, number];
16
+ }
17
+ /** Trace a ray and return the nearest hit within `maxT`, or null for "escaped to sky". */
18
+ export type TraceFn = (ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, maxT: number) => TraceHit | null;
19
+ export interface BakeOptions {
20
+ /** Rays per probe. More is smoother and slower; 32 is a reasonable floor. */
21
+ rays?: number;
22
+ /** Direction the sunlight TRAVELS (not the direction to the sun). */
23
+ sun?: [number, number, number];
24
+ sunColor?: [number, number, number];
25
+ /** Radiance of the sky along a ray that escaped. Defaults to a dim blue-grey gradient. */
26
+ sky?: (dy: number) => [number, number, number];
27
+ /** How far a bounce ray looks before it counts as sky. */
28
+ maxDistance?: number;
29
+ }
30
+ export declare const PROBE_AXES: readonly [number, number, number][];
31
+ /** Floats per probe in the packed buffer: 6 axes × vec4 (rgb + pad, for std140-friendly strides). */
32
+ export declare const PROBE_STRIDE: number;
33
+ /** Deterministic near-uniform sphere directions (Fibonacci) — no RNG, so a re-bake is repeatable. */
34
+ export declare function sphereDirs(n: number): [number, number, number][];
35
+ /**
36
+ * Bake `grid` into a packed ambient-cube buffer of `nx*ny*nz*6` vec4s, axis-major within a probe.
37
+ *
38
+ * Each ray either hits a surface — contributing that surface's sun-lit albedo, one bounce — or
39
+ * escapes and contributes sky. The result is projected onto the six axes weighted by `max(0, d·axis)`,
40
+ * so each axis ends up with the irradiance arriving from that hemisphere.
41
+ */
42
+ export declare function bakeProbeGrid(grid: ProbeGrid, trace: TraceFn, opts?: BakeOptions): Float32Array<ArrayBuffer>;
43
+ /**
44
+ * CPU mirror of the WGSL `giAt` below — trilinear across the eight surrounding probes, then the
45
+ * ambient cube resolved against `n`. Mirrored 1:1 on purpose: it is what lets a headless oracle
46
+ * test the thing the GPU will actually do.
47
+ */
48
+ export declare function sampleProbeGrid(probes: Float32Array, grid: ProbeGrid, x: number, y: number, z: number, n: [number, number, number]): [number, number, number];
49
+ /**
50
+ * Drop-in WGSL, mirroring `sampleProbeGrid` exactly. Paste into a receiver fragment shader that has
51
+ * a `probes: array<vec4<f32>>` storage binding and a `giGrid` uniform in scope:
52
+ *
53
+ * struct GiGrid { org: vec4<f32>, dim: vec4<f32> }; // org.xyz = grid origin, org.w = cell size
54
+ * // dim.xyz = nx,ny,nz, dim.w = enable (0 = off)
55
+ *
56
+ * Gate on `giGrid.dim.w`: a caller that supplies no probes gets 0 and the flat ambient it had.
57
+ *
58
+ * UNVERIFIED. `sampleProbeGrid` above is covered by shared/giProbes.test.mts and this is written to
59
+ * mirror it line for line, but no renderer binds it yet, so nothing has executed it on a GPU. The
60
+ * mirror is a claim, not a measurement — treat the first splice into a fragment shader as the point
61
+ * where it gets tested, and compare against the CPU function on the same inputs.
62
+ */
63
+ export declare const GI_WGSL = "\nfn giProbeAt(ix: i32, iy: i32, iz: i32, w: array<f32, 6>, wsum: f32) -> vec3<f32> {\n let nx = i32(giGrid.dim.x); let ny = i32(giGrid.dim.y);\n let base = (iz * ny * nx + iy * nx + ix) * 6;\n var c = vec3<f32>(0.0);\n for (var a = 0; a < 6; a = a + 1) {\n c = c + probes[base + a].rgb * w[a];\n }\n return c / wsum;\n}\n\nfn giAt(p: vec3<f32>, n: vec3<f32>) -> vec3<f32> {\n if (giGrid.dim.w < 0.5) { return vec3<f32>(0.0); }\n let dim = vec3<i32>(i32(giGrid.dim.x), i32(giGrid.dim.y), i32(giGrid.dim.z));\n let f = (p - giGrid.org.xyz) / giGrid.org.w;\n let fc = clamp(f, vec3<f32>(0.0), vec3<f32>(dim - vec3<i32>(1)));\n let i0 = vec3<i32>(floor(fc));\n let i1 = min(i0 + vec3<i32>(1), dim - vec3<i32>(1));\n let t = clamp(fc - vec3<f32>(i0), vec3<f32>(0.0), vec3<f32>(1.0));\n\n // Ambient cube: only the three axes the normal faces contribute, weighted by (n\u00B7axis)\u00B2.\n var w = array<f32, 6>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);\n var wsum = 0.0;\n let d = array<f32, 6>(n.x, -n.x, n.y, -n.y, n.z, -n.z);\n for (var a = 0; a < 6; a = a + 1) {\n if (d[a] > 0.0) { w[a] = d[a] * d[a]; wsum = wsum + w[a]; }\n }\n if (wsum <= 0.0) { return vec3<f32>(0.0); }\n\n let c00 = mix(giProbeAt(i0.x, i0.y, i0.z, w, wsum), giProbeAt(i1.x, i0.y, i0.z, w, wsum), t.x);\n let c10 = mix(giProbeAt(i0.x, i1.y, i0.z, w, wsum), giProbeAt(i1.x, i1.y, i0.z, w, wsum), t.x);\n let c01 = mix(giProbeAt(i0.x, i0.y, i1.z, w, wsum), giProbeAt(i1.x, i0.y, i1.z, w, wsum), t.x);\n let c11 = mix(giProbeAt(i0.x, i1.y, i1.z, w, wsum), giProbeAt(i1.x, i1.y, i1.z, w, wsum), t.x);\n return mix(mix(c00, c10, t.y), mix(c01, c11, t.y), t.z);\n}\n";
64
+ /** Convenience: a TraceFn over an axis-aligned box list, so the box case still has a one-liner. */
65
+ export declare function boxTrace(boxes: readonly {
66
+ x: number;
67
+ y: number;
68
+ z: number;
69
+ sx: number;
70
+ sy: number;
71
+ sz: number;
72
+ r: number;
73
+ g: number;
74
+ b: number;
75
+ }[]): TraceFn;
@@ -0,0 +1,261 @@
1
+ // PLATFORM. An irradiance probe grid that any world can bake, plus the WGSL to sample it.
2
+ //
3
+ // gpuGI.ts already bakes probes, but only for a LIST OF BOXES: `bakeProbes(boxes, grid)` ray-casts
4
+ // against `GIBox[]`. A voxel or SDF world has no box list — it has a density function — so that
5
+ // signature cannot express it, and its renderer half clears the colour target and hardcodes its sun,
6
+ // which makes it a demo rather than a component.
7
+ //
8
+ // This module keeps the part that generalises. The scene arrives as a TRACE CALLBACK:
9
+ //
10
+ // bakeProbeGrid(grid, (ox,oy,oz, dx,dy,dz, maxT) => hit | null)
11
+ //
12
+ // so a caller backs it with whatever it has — an SDF march, a voxel DDA, a BVH, a box list. Each
13
+ // probe stores a 6-axis AMBIENT CUBE (irradiance along ±X/±Y/±Z, the Half-Life 2 trick): cheap to
14
+ // store, keeps direction, so a red floor bleeds red upward and a nook that sees little sky goes
15
+ // dark on its own.
16
+ //
17
+ // The bake is PRESENTATIONAL — it must never feed a deterministic sim. It uses plain Math and a
18
+ // caller-supplied trace, neither of which is hash-stable across machines.
19
+ export const PROBE_AXES = [
20
+ [1, 0, 0],
21
+ [-1, 0, 0],
22
+ [0, 1, 0],
23
+ [0, -1, 0],
24
+ [0, 0, 1],
25
+ [0, 0, -1],
26
+ ];
27
+ /** Floats per probe in the packed buffer: 6 axes × vec4 (rgb + pad, for std140-friendly strides). */
28
+ export const PROBE_STRIDE = 6 * 4;
29
+ function defaultSky(dy) {
30
+ if (dy < 0)
31
+ return [0.03, 0.03, 0.04]; // below the horizon there is almost nothing to gather
32
+ const t = dy;
33
+ // Deliberately dim: a bright sky washes out the colour bleed that makes GI legible at all.
34
+ return [0.16 + 0.08 * t, 0.19 + 0.11 * t, 0.24 + 0.16 * t];
35
+ }
36
+ /** Deterministic near-uniform sphere directions (Fibonacci) — no RNG, so a re-bake is repeatable. */
37
+ export function sphereDirs(n) {
38
+ const out = [];
39
+ const ga = Math.PI * (3 - Math.sqrt(5));
40
+ for (let i = 0; i < n; i++) {
41
+ const y = 1 - ((i + 0.5) / n) * 2, r = Math.sqrt(Math.max(0, 1 - y * y)), th = ga * i;
42
+ out.push([Math.cos(th) * r, y, Math.sin(th) * r]);
43
+ }
44
+ return out;
45
+ }
46
+ /**
47
+ * Bake `grid` into a packed ambient-cube buffer of `nx*ny*nz*6` vec4s, axis-major within a probe.
48
+ *
49
+ * Each ray either hits a surface — contributing that surface's sun-lit albedo, one bounce — or
50
+ * escapes and contributes sky. The result is projected onto the six axes weighted by `max(0, d·axis)`,
51
+ * so each axis ends up with the irradiance arriving from that hemisphere.
52
+ */
53
+ export function bakeProbeGrid(grid, trace, opts = {}) {
54
+ const rays = opts.rays ?? 32;
55
+ const sunRaw = opts.sun ?? [-0.4, -0.85, -0.32];
56
+ const sl = Math.hypot(sunRaw[0], sunRaw[1], sunRaw[2]) || 1;
57
+ const sun = [
58
+ sunRaw[0] / sl,
59
+ sunRaw[1] / sl,
60
+ sunRaw[2] / sl,
61
+ ];
62
+ const sunCol = opts.sunColor ?? [1.15, 1.05, 0.9];
63
+ const sky = opts.sky ?? defaultSky;
64
+ const maxT = opts.maxDistance ?? grid.cell * Math.max(grid.nx, grid.ny, grid.nz) * 2;
65
+ const dirs = sphereDirs(rays);
66
+ const n = grid.nx * grid.ny * grid.nz;
67
+ const out = new Float32Array(n * PROBE_STRIDE);
68
+ for (let iz = 0; iz < grid.nz; iz++)
69
+ for (let iy = 0; iy < grid.ny; iy++)
70
+ for (let ix = 0; ix < grid.nx; ix++) {
71
+ const px = grid.ox + ix * grid.cell, py = grid.oy + iy * grid.cell, pz = grid.oz + iz * grid.cell;
72
+ const acc = new Float64Array(18); // 6 axes × rgb
73
+ const wsum = new Float64Array(6);
74
+ for (const [dx, dy, dz] of dirs) {
75
+ const hit = trace(px, py, pz, dx, dy, dz, maxT);
76
+ let r, g, b;
77
+ if (hit) {
78
+ // One bounce: how lit is the surface we struck? A face turned away from the sun
79
+ // contributes only its own ambient, which is what makes cave interiors settle dark
80
+ // instead of merely dimmer.
81
+ const ndl = Math.max(0, -(hit.n[0] * sun[0] + hit.n[1] * sun[1] + hit.n[2] * sun[2]));
82
+ r = hit.albedo[0] * sunCol[0] * ndl;
83
+ g = hit.albedo[1] * sunCol[1] * ndl;
84
+ b = hit.albedo[2] * sunCol[2] * ndl;
85
+ }
86
+ else {
87
+ const s = sky(dy);
88
+ r = s[0];
89
+ g = s[1];
90
+ b = s[2];
91
+ }
92
+ for (let a = 0; a < 6; a++) {
93
+ const ax = PROBE_AXES[a];
94
+ const w = dx * ax[0] + dy * ax[1] + dz * ax[2];
95
+ if (w <= 0)
96
+ continue;
97
+ acc[a * 3] += r * w;
98
+ acc[a * 3 + 1] += g * w;
99
+ acc[a * 3 + 2] += b * w;
100
+ wsum[a] += w;
101
+ }
102
+ }
103
+ const base = (iz * grid.ny * grid.nx + iy * grid.nx + ix) * PROBE_STRIDE;
104
+ for (let a = 0; a < 6; a++) {
105
+ const w = wsum[a] || 1;
106
+ out[base + a * 4] = acc[a * 3] / w;
107
+ out[base + a * 4 + 1] = acc[a * 3 + 1] / w;
108
+ out[base + a * 4 + 2] = acc[a * 3 + 2] / w;
109
+ out[base + a * 4 + 3] = 0;
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ /**
115
+ * CPU mirror of the WGSL `giAt` below — trilinear across the eight surrounding probes, then the
116
+ * ambient cube resolved against `n`. Mirrored 1:1 on purpose: it is what lets a headless oracle
117
+ * test the thing the GPU will actually do.
118
+ */
119
+ export function sampleProbeGrid(probes, grid, x, y, z, n) {
120
+ const fx = (x - grid.ox) / grid.cell, fy = (y - grid.oy) / grid.cell, fz = (z - grid.oz) / grid.cell;
121
+ const cl = (v, hi) => Math.max(0, Math.min(hi, v));
122
+ const x0 = Math.floor(cl(fx, grid.nx - 1)), y0 = Math.floor(cl(fy, grid.ny - 1)), z0 = Math.floor(cl(fz, grid.nz - 1));
123
+ const x1 = Math.min(x0 + 1, grid.nx - 1), y1 = Math.min(y0 + 1, grid.ny - 1), z1 = Math.min(z0 + 1, grid.nz - 1);
124
+ const tx = cl(fx - x0, 1), ty = cl(fy - y0, 1), tz = cl(fz - z0, 1);
125
+ // Ambient-cube weights: only the three axes the normal faces contribute, weighted by n·axis².
126
+ const w = new Float64Array(6);
127
+ let wsum = 0;
128
+ for (let a = 0; a < 6; a++) {
129
+ const ax = PROBE_AXES[a];
130
+ const d = n[0] * ax[0] + n[1] * ax[1] + n[2] * ax[2];
131
+ if (d <= 0)
132
+ continue;
133
+ w[a] = d * d;
134
+ wsum += w[a];
135
+ }
136
+ if (wsum === 0)
137
+ return [0, 0, 0];
138
+ const at = (ix, iy, iz) => {
139
+ const base = (iz * grid.ny * grid.nx + iy * grid.nx + ix) * PROBE_STRIDE;
140
+ let r = 0, g = 0, b = 0;
141
+ for (let a = 0; a < 6; a++) {
142
+ if (w[a] === 0)
143
+ continue;
144
+ r += probes[base + a * 4] * w[a];
145
+ g += probes[base + a * 4 + 1] * w[a];
146
+ b += probes[base + a * 4 + 2] * w[a];
147
+ }
148
+ return [r / wsum, g / wsum, b / wsum];
149
+ };
150
+ const lerp3 = (p, q, t) => [
151
+ p[0] + (q[0] - p[0]) * t,
152
+ p[1] + (q[1] - p[1]) * t,
153
+ p[2] + (q[2] - p[2]) * t,
154
+ ];
155
+ const c00 = lerp3(at(x0, y0, z0), at(x1, y0, z0), tx);
156
+ const c10 = lerp3(at(x0, y1, z0), at(x1, y1, z0), tx);
157
+ const c01 = lerp3(at(x0, y0, z1), at(x1, y0, z1), tx);
158
+ const c11 = lerp3(at(x0, y1, z1), at(x1, y1, z1), tx);
159
+ return lerp3(lerp3(c00, c10, ty), lerp3(c01, c11, ty), tz);
160
+ }
161
+ /**
162
+ * Drop-in WGSL, mirroring `sampleProbeGrid` exactly. Paste into a receiver fragment shader that has
163
+ * a `probes: array<vec4<f32>>` storage binding and a `giGrid` uniform in scope:
164
+ *
165
+ * struct GiGrid { org: vec4<f32>, dim: vec4<f32> }; // org.xyz = grid origin, org.w = cell size
166
+ * // dim.xyz = nx,ny,nz, dim.w = enable (0 = off)
167
+ *
168
+ * Gate on `giGrid.dim.w`: a caller that supplies no probes gets 0 and the flat ambient it had.
169
+ *
170
+ * UNVERIFIED. `sampleProbeGrid` above is covered by shared/giProbes.test.mts and this is written to
171
+ * mirror it line for line, but no renderer binds it yet, so nothing has executed it on a GPU. The
172
+ * mirror is a claim, not a measurement — treat the first splice into a fragment shader as the point
173
+ * where it gets tested, and compare against the CPU function on the same inputs.
174
+ */
175
+ export const GI_WGSL = /* wgsl */ `
176
+ fn giProbeAt(ix: i32, iy: i32, iz: i32, w: array<f32, 6>, wsum: f32) -> vec3<f32> {
177
+ let nx = i32(giGrid.dim.x); let ny = i32(giGrid.dim.y);
178
+ let base = (iz * ny * nx + iy * nx + ix) * 6;
179
+ var c = vec3<f32>(0.0);
180
+ for (var a = 0; a < 6; a = a + 1) {
181
+ c = c + probes[base + a].rgb * w[a];
182
+ }
183
+ return c / wsum;
184
+ }
185
+
186
+ fn giAt(p: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
187
+ if (giGrid.dim.w < 0.5) { return vec3<f32>(0.0); }
188
+ let dim = vec3<i32>(i32(giGrid.dim.x), i32(giGrid.dim.y), i32(giGrid.dim.z));
189
+ let f = (p - giGrid.org.xyz) / giGrid.org.w;
190
+ let fc = clamp(f, vec3<f32>(0.0), vec3<f32>(dim - vec3<i32>(1)));
191
+ let i0 = vec3<i32>(floor(fc));
192
+ let i1 = min(i0 + vec3<i32>(1), dim - vec3<i32>(1));
193
+ let t = clamp(fc - vec3<f32>(i0), vec3<f32>(0.0), vec3<f32>(1.0));
194
+
195
+ // Ambient cube: only the three axes the normal faces contribute, weighted by (n·axis)².
196
+ var w = array<f32, 6>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
197
+ var wsum = 0.0;
198
+ let d = array<f32, 6>(n.x, -n.x, n.y, -n.y, n.z, -n.z);
199
+ for (var a = 0; a < 6; a = a + 1) {
200
+ if (d[a] > 0.0) { w[a] = d[a] * d[a]; wsum = wsum + w[a]; }
201
+ }
202
+ if (wsum <= 0.0) { return vec3<f32>(0.0); }
203
+
204
+ let c00 = mix(giProbeAt(i0.x, i0.y, i0.z, w, wsum), giProbeAt(i1.x, i0.y, i0.z, w, wsum), t.x);
205
+ let c10 = mix(giProbeAt(i0.x, i1.y, i0.z, w, wsum), giProbeAt(i1.x, i1.y, i0.z, w, wsum), t.x);
206
+ let c01 = mix(giProbeAt(i0.x, i0.y, i1.z, w, wsum), giProbeAt(i1.x, i0.y, i1.z, w, wsum), t.x);
207
+ let c11 = mix(giProbeAt(i0.x, i1.y, i1.z, w, wsum), giProbeAt(i1.x, i1.y, i1.z, w, wsum), t.x);
208
+ return mix(mix(c00, c10, t.y), mix(c01, c11, t.y), t.z);
209
+ }
210
+ `;
211
+ /** Convenience: a TraceFn over an axis-aligned box list, so the box case still has a one-liner. */
212
+ export function boxTrace(boxes) {
213
+ return (ox, oy, oz, dx, dy, dz, maxT) => {
214
+ let best = null;
215
+ for (const b of boxes) {
216
+ const o = [ox, oy, oz], d = [dx, dy, dz];
217
+ const mn = [b.x - b.sx / 2, b.y - b.sy / 2, b.z - b.sz / 2];
218
+ const mx = [b.x + b.sx / 2, b.y + b.sy / 2, b.z + b.sz / 2];
219
+ let tmin = -Infinity, tmax = Infinity, axis = 0, sign = 1, miss = false;
220
+ for (let a = 0; a < 3; a++) {
221
+ if (Math.abs(d[a]) < 1e-9) {
222
+ if (o[a] < mn[a] || o[a] > mx[a]) {
223
+ miss = true;
224
+ break;
225
+ }
226
+ continue;
227
+ }
228
+ const inv = 1 / d[a];
229
+ let t1 = (mn[a] - o[a]) * inv, t2 = (mx[a] - o[a]) * inv, s = -1;
230
+ if (t1 > t2) {
231
+ const tmp = t1;
232
+ t1 = t2;
233
+ t2 = tmp;
234
+ s = 1;
235
+ }
236
+ if (t1 > tmin) {
237
+ tmin = t1;
238
+ axis = a;
239
+ sign = s;
240
+ }
241
+ if (t2 < tmax)
242
+ tmax = t2;
243
+ if (tmin > tmax) {
244
+ miss = true;
245
+ break;
246
+ }
247
+ }
248
+ if (miss || tmax < 0)
249
+ continue;
250
+ const t = tmin > 0 ? tmin : tmax;
251
+ if (t < 0 || t > maxT)
252
+ continue;
253
+ if (best && t >= best.t)
254
+ continue;
255
+ const nrm = [0, 0, 0];
256
+ nrm[axis] = sign;
257
+ best = { t, n: nrm, albedo: [b.r, b.g, b.b] };
258
+ }
259
+ return best;
260
+ };
261
+ }
@@ -1,3 +1,4 @@
1
+ import { type ProbeGrid } from './giProbes';
1
2
  export interface CubeInstance {
2
3
  x: number;
3
4
  y: number;
@@ -44,6 +45,8 @@ export declare class GpuShadowRenderer {
44
45
  private shadowBGL;
45
46
  private mainBGL;
46
47
  private shadowSampler;
48
+ private giGridBuf;
49
+ private giProbeBuf;
47
50
  private count;
48
51
  private cam;
49
52
  private shadowCam;
@@ -127,6 +130,12 @@ export declare class GpuShadowRenderer {
127
130
  overlayPass(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView): void;
128
131
  /** Write a frustum's cull uniform: 6 planes + count + this frustum's VP + occlusion params (occ on the camera pass). */
129
132
  private writeCull;
133
+ /**
134
+ * Supply a baked irradiance grid (see giProbes.bakeProbeGrid), or `null` to turn indirect light
135
+ * off. The probe buffer is reallocated only when the grid's size changes, so re-baking a moving
136
+ * cage each frame is a plain writeBuffer.
137
+ */
138
+ setGI(probes: Float32Array<ArrayBuffer> | null, grid: ProbeGrid | null): void;
130
139
  /** The sun shadow-map depth view + its comparison sampler + texel size. Feed these into GpuPropsRenderer/
131
140
  * GpuSkinRenderer.frame(lightVP, …) so mesh props & creatures RECEIVE the same sun shadow the cubes sample.
132
141
  *
package/dist/gpuShadow.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * emissive flag (> 0 ⇒ the cube self-glows at full brightness, bypassing sun/shadow/AO — used for the
13
13
  * place ghost, destroy marker, projectiles, and sparkles so effect cubes read as distinct from terrain). */
14
14
  import { frustumPlanes } from './mat4';
15
+ import { GI_WGSL, PROBE_STRIDE } from './giProbes';
15
16
  const SHADOW_SIZE = 2048;
16
17
  // CASCADED SHADOW MAPS. One ortho map has to choose between resolution and reach: AMS ran a single
17
18
  // 90-block box against a 280-block draw distance, so everything past it was simply unshadowed and
@@ -220,6 +221,13 @@ const MAIN_WGSL = COMMON_WGSL +
220
221
  @group(0) @binding(5) var atlasTex: texture_2d<f32>;
221
222
  @group(0) @binding(6) var atlasSamp: sampler;
222
223
  @group(0) @binding(7) var<storage, read> tileRects: array<vec4<f32>>; // [u0,v0,du,dv] per (material*3 + face-variant)
224
+ // GLOBAL ILLUMINATION (giProbes.ts). org.xyz = grid origin, org.w = cell size; dim.xyz = nx,ny,nz,
225
+ // dim.w = enable. A caller that never calls setGI leaves dim.w at 0, giAt returns zero, and this is
226
+ // byte-identical to the flat-ambient version it replaced.
227
+ struct GiGrid { org: vec4<f32>, dim: vec4<f32> };
228
+ @group(0) @binding(8) var<uniform> giGrid: GiGrid;
229
+ @group(0) @binding(9) var<storage, read> probes: array<vec4<f32>>;
230
+ ${GI_WGSL}
223
231
 
224
232
  struct VOut { @builtin(position) clip: vec4<f32>, @location(0) world: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) hue: f32, @location(3) emis: f32, @location(4) blk: vec3<f32>, @location(5) objN: vec3<f32>, @location(6) tile: f32, @location(7) upc: f32 };
225
233
 
@@ -352,7 +360,10 @@ fn fixedFill(N: vec3<f32>, up: vec3<f32>) -> f32 {
352
360
  // orientation legible day or night, while the sun adds bright, shadow-casting key light on top during the day.
353
361
  let fill = cam.sun.w * (0.5 + 0.85 * fixedFill(N, cam.up.xyz));
354
362
  let key = cam.sunCol.xyz * ndl * sh; // direct sun (shadowed) — primary light
355
- let lit = base * (fill + key) * ao;
363
+ // INDIRECT: baked one-bounce irradiance, zero unless setGI supplied probes — additive over the
364
+ // existing look rather than a replacement for the ambient knob.
365
+ let gi = giAt(i.world, N);
366
+ let lit = base * (fill + key + gi) * ao;
356
367
  // cam.up.w > 0.5 selects LINEAR-HDR output (unclamped, no gamma) for an HDR pipeline that tonemaps downstream;
357
368
  // otherwise the classic gamma-encoded LDR path (all existing consumers). Keeps both looks from one shader.
358
369
  if (cam.up.w > 0.5) { return vec4(max(lit, vec3(0.0)), 1.0); }
@@ -394,6 +405,8 @@ export class GpuShadowRenderer {
394
405
  shadowBGL;
395
406
  mainBGL;
396
407
  shadowSampler;
408
+ giGridBuf;
409
+ giProbeBuf;
397
410
  count = 0;
398
411
  // camVP(16) + lightVP[MAX_CASCADES](16 each) + sun + sunCol + tint + atlas + up + csm
399
412
  cam = new Float32Array(16 + MAX_CASCADES * 16 + 6 * 4);
@@ -513,6 +526,16 @@ export class GpuShadowRenderer {
513
526
  visibility: GPUShaderStage.FRAGMENT,
514
527
  buffer: { type: 'read-only-storage' },
515
528
  }, // per-tile UV rects
529
+ {
530
+ binding: 8,
531
+ visibility: GPUShaderStage.FRAGMENT,
532
+ buffer: { type: 'uniform' },
533
+ }, // GI grid descriptor
534
+ {
535
+ binding: 9,
536
+ visibility: GPUShaderStage.FRAGMENT,
537
+ buffer: { type: 'read-only-storage' },
538
+ }, // GI probe irradiance
516
539
  ],
517
540
  });
518
541
  this.mainPipe = device.createRenderPipeline({
@@ -528,6 +551,18 @@ export class GpuShadowRenderer {
528
551
  });
529
552
  this.shadowBGL = shadowBGL;
530
553
  this.mainBGL = mainBGL;
554
+ // GI defaults: a zeroed descriptor (dim.w = 0 ⇒ disabled) and a one-probe placeholder, so the
555
+ // bindings always exist and a caller that never touches GI pays nothing but two tiny buffers.
556
+ this.giGridBuf = device.createBuffer({
557
+ size: 32,
558
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
559
+ });
560
+ device.queue.writeBuffer(this.giGridBuf, 0, new Float32Array(8));
561
+ this.giProbeBuf = device.createBuffer({
562
+ size: PROBE_STRIDE * 4,
563
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
564
+ });
565
+ device.queue.writeBuffer(this.giProbeBuf, 0, new Float32Array(PROBE_STRIDE));
531
566
  this.shadowSampler = device.createSampler({
532
567
  compare: 'less',
533
568
  magFilter: 'linear',
@@ -841,6 +876,8 @@ export class GpuShadowRenderer {
841
876
  { binding: 5, resource: this.atlasView },
842
877
  { binding: 6, resource: this.atlasSampler },
843
878
  { binding: 7, resource: { buffer: this.tileRectBuf } },
879
+ { binding: 8, resource: { buffer: this.giGridBuf } },
880
+ { binding: 9, resource: { buffer: this.giProbeBuf } },
844
881
  ],
845
882
  });
846
883
  }
@@ -986,6 +1023,39 @@ export class GpuShadowRenderer {
986
1023
  u[47] = HIZ_DOWN;
987
1024
  this.device.queue.writeBuffer(buf, 0, u);
988
1025
  }
1026
+ /**
1027
+ * Supply a baked irradiance grid (see giProbes.bakeProbeGrid), or `null` to turn indirect light
1028
+ * off. The probe buffer is reallocated only when the grid's size changes, so re-baking a moving
1029
+ * cage each frame is a plain writeBuffer.
1030
+ */
1031
+ setGI(probes, grid) {
1032
+ const d = this.device;
1033
+ if (!probes || !grid) {
1034
+ d.queue.writeBuffer(this.giGridBuf, 0, new Float32Array(8)); // dim.w = 0 ⇒ off
1035
+ return;
1036
+ }
1037
+ const need = probes.byteLength;
1038
+ if (this.giProbeBuf.size < need) {
1039
+ this.giProbeBuf.destroy();
1040
+ this.giProbeBuf = d.createBuffer({
1041
+ size: need,
1042
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
1043
+ });
1044
+ if (this.sceneReady)
1045
+ this.makeBindGroups(); // the old buffer is baked into the bind group
1046
+ }
1047
+ d.queue.writeBuffer(this.giProbeBuf, 0, probes);
1048
+ d.queue.writeBuffer(this.giGridBuf, 0, new Float32Array([
1049
+ grid.ox,
1050
+ grid.oy,
1051
+ grid.oz,
1052
+ grid.cell,
1053
+ grid.nx,
1054
+ grid.ny,
1055
+ grid.nz,
1056
+ 1,
1057
+ ]));
1058
+ }
989
1059
  /** The sun shadow-map depth view + its comparison sampler + texel size. Feed these into GpuPropsRenderer/
990
1060
  * GpuSkinRenderer.frame(lightVP, …) so mesh props & creatures RECEIVE the same sun shadow the cubes sample.
991
1061
  *
@@ -28,6 +28,8 @@ export declare class GpuTaaResolve {
28
28
  * previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
29
29
  * only — reprojection done with a jittered matrix would chase its own offset.
30
30
  */
31
- frame(enc: GPUCommandEncoder, out: GPUTextureView, invCurrVP: Float32Array, prevVP: Float32Array, blend?: number, enabled?: boolean): void;
31
+ frame(enc: GPUCommandEncoder, out: GPUTextureView, invCurrVP: Float32Array, prevVP: Float32Array, blend?: number, enabled?: boolean,
32
+ /** Clip width in standard deviations. Lower = harsher rejection, less ghosting, more shimmer. */
33
+ clipSigma?: number): void;
32
34
  destroy(): void;
33
35
  }
@@ -46,7 +46,7 @@ struct RU {
46
46
  invCurrVP: mat4x4<f32>,
47
47
  prevVP: mat4x4<f32>,
48
48
  texel: vec4<f32>, // xy = 1/size, zw = size
49
- ctrl: vec4<f32>, // x = history blend, y = enabled, z = reset
49
+ ctrl: vec4<f32>, // x = history blend, y = enabled, z = reset, w = clip sigma
50
50
  };
51
51
  @group(0) @binding(0) var<uniform> ru: RU;
52
52
  @group(0) @binding(1) var histSamp: sampler;
@@ -69,17 +69,27 @@ struct ROut { @location(0) screen: vec4<f32>, @location(1) hist: vec4<f32> };
69
69
  // Disabled, or the first frame after a cut: the current frame IS the answer and the history.
70
70
  if (ru.ctrl.y < 0.5 || ru.ctrl.z > 0.5) { o.screen = vec4(cur, 1.0); o.hist = vec4(cur, 1.0); return o; }
71
71
 
72
- // 3x3 neighbourhood colour box of the current frame -- the anti-ghosting clamp. Coordinates are
73
- // clamped to the texture: an out-of-range textureLoad returns zero in WGSL, which would drag the
74
- // box's minimum to black along every screen edge and put a dark rim on the frame.
75
- var mn = cur; var mx = cur;
72
+ // ANTI-GHOSTING CLAMP, by VARIANCE rather than by min/max. A raw 3x3 min/max box is enormous over
73
+ // high-frequency detail -- a voxel world's textured terrain spans most of the range inside any
74
+ // nine pixels -- so stale history passes through it essentially unmodified and smears behind
75
+ // motion. Clipping to mean +/- gamma*sigma tracks what the neighbourhood actually IS rather than
76
+ // its extremes, which is what makes the rejection bite.
77
+ // Coordinates are clamped to the texture: an out-of-range textureLoad returns zero in WGSL, which
78
+ // would drag the mean to black along every screen edge and rim the frame.
79
+ var m1 = vec3<f32>(0.0); var m2 = vec3<f32>(0.0);
76
80
  for (var dy = -1; dy <= 1; dy = dy + 1) {
77
81
  for (var dx = -1; dx <= 1; dx = dx + 1) {
78
82
  let q = clamp(px + vec2<i32>(dx, dy), vec2<i32>(0, 0), dim - vec2<i32>(1, 1));
79
83
  let c = textureLoad(colorTex, q, 0).rgb;
80
- mn = min(mn, c); mx = max(mx, c);
84
+ m1 = m1 + c; m2 = m2 + c * c;
81
85
  }
82
86
  }
87
+ let mu = m1 / 9.0;
88
+ let sigma = sqrt(max(vec3<f32>(0.0), m2 / 9.0 - mu * mu));
89
+ let gamma = ru.ctrl.w; // clip width in standard deviations
90
+ // Always admit the current pixel, so a legitimately extreme sample is never clipped against itself.
91
+ var mn = min(mu - gamma * sigma, cur);
92
+ var mx = max(mu + gamma * sigma, cur);
83
93
 
84
94
  // Depth -> world -> previous clip. WebGPU depth is [0,1] and clip-space Y is up while the
85
95
  // framebuffer's Y is down, hence the flip in both directions.
@@ -96,7 +106,13 @@ struct ROut { @location(0) screen: vec4<f32>, @location(1) hist: vec4<f32> };
96
106
  let prevUV = vec2<f32>(pndc.x * 0.5 + 0.5, 0.5 - pndc.y * 0.5);
97
107
  if (prevUV.x >= 0.0 && prevUV.x <= 1.0 && prevUV.y >= 0.0 && prevUV.y <= 1.0) {
98
108
  let hist = clamp(textureSampleLevel(histTex, histSamp, prevUV, 0.0).rgb, mn, mx);
99
- outc = mix(cur, hist, ru.ctrl.x); // ctrl.x ~ 0.9 => 10% current, 90% reprojected history
109
+ // TRUST LESS WHEN MOVING. The further a pixel travelled since last frame, the likelier its
110
+ // history is disoccluded or belongs to different geometry -- and the more a wrong sample reads
111
+ // as a trailing smear. Fade the history weight out with screen-space velocity instead of
112
+ // holding 90% regardless of how fast the camera swings.
113
+ let velPx = length((uv - prevUV) * vec2<f32>(ru.texel.z, ru.texel.w));
114
+ let trust = clamp(1.0 - velPx * 0.045, 0.25, 1.0);
115
+ outc = mix(cur, hist, ru.ctrl.x * trust);
100
116
  }
101
117
  }
102
118
  o.screen = vec4(outc, 1.0); o.hist = vec4(outc, 1.0);
@@ -185,7 +201,9 @@ export class GpuTaaResolve {
185
201
  * previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
186
202
  * only — reprojection done with a jittered matrix would chase its own offset.
187
203
  */
188
- frame(enc, out, invCurrVP, prevVP, blend = 0.9, enabled = true) {
204
+ frame(enc, out, invCurrVP, prevVP, blend = 0.9, enabled = true,
205
+ /** Clip width in standard deviations. Lower = harsher rejection, less ghosting, more shimmer. */
206
+ clipSigma = 1.25) {
189
207
  if (this.histView.length !== 2)
190
208
  return;
191
209
  this.u.set(invCurrVP, 0);
@@ -197,6 +215,7 @@ export class GpuTaaResolve {
197
215
  this.u[36] = blend;
198
216
  this.u[37] = enabled ? 1 : 0;
199
217
  this.u[38] = this.primed ? 0 : 1; // first frame after a cut has no history to blend
218
+ this.u[39] = clipSigma;
200
219
  this.device.queue.writeBuffer(this.uBuf, 0, this.u);
201
220
  const pass = enc.beginRenderPass({
202
221
  colorAttachments: [
@@ -18,7 +18,8 @@ export interface FrameInfo {
18
18
  }
19
19
  export interface GameLoopOpts {
20
20
  render: (info: FrameInfo) => void;
21
- /** Render FPS per tier. Default { active: 60, blurred: 20, hidden: 0 }. */
21
+ /** Render FPS per tier. Default { active: Infinity, blurred: Infinity, hidden: 0 } — uncapped
22
+ * while visible. Pass finite numbers to cap; 0 disables rendering for that tier. */
22
23
  gameFps?: {
23
24
  active: number;
24
25
  blurred: number;
@@ -1,7 +1,7 @@
1
1
  // ─────────────────────────────────────────────────────────────────────────────
2
2
  // GAME LOOP — the one rAF loop a game hands its render (and optionally its sim) to.
3
3
  // It owns three things a hand-rolled loop keeps getting wrong:
4
- // 1. RENDER PACING by page tier — active 60 / blurred 20 / hidden 0 (overridable).
4
+ // 1. RENDER PACING by page tier — uncapped while visible / hidden 0 (overridable).
5
5
  // 2. A FIXED-STEP SIM accumulator (opt-in via `tick`) that advances on wall time
6
6
  // while visible and FREEZES while hidden, with a catch-up clamp.
7
7
  // 3. SIM RESTORE on resume — the part games forget. Hand it a NetAdapter and it
@@ -11,7 +11,14 @@
11
11
  // catch-up clamping for free. Clock/rAF/pageState are injectable for tests.
12
12
  // ─────────────────────────────────────────────────────────────────────────────
13
13
  import { createPageState } from './pageState';
14
- const DEFAULT_GAME_FPS = { active: 60, blurred: 20, hidden: 0 };
14
+ // UNCAPPED by default. Pinning render to 60 threw away every frame a 120/144Hz display could have
15
+ // shown, and throttling a merely-BLURRED window to 20 made the game stutter whenever focus sat on a
16
+ // devtools panel or a second monitor — neither is something a player asked for. `Infinity` means
17
+ // "render every animation frame"; 0 still means "never render", which is why uncapped cannot just
18
+ // be 0. A caller that genuinely wants to throttle can still pass `gameFps`.
19
+ //
20
+ // `hidden: 0` stays: a hidden tab is not a focus question, and browsers stop firing rAF there anyway.
21
+ const DEFAULT_GAME_FPS = { active: Infinity, blurred: Infinity, hidden: 0 };
15
22
  const DEFAULT_SIM = { fps: 60, maxCatchUpFrames: 6 };
16
23
  export function runGameLoop(opts) {
17
24
  const gameFps = opts.gameFps ?? DEFAULT_GAME_FPS;
@@ -65,8 +72,8 @@ export function runGameLoop(opts) {
65
72
  acc -= fixedDt;
66
73
  }
67
74
  }
68
- // RENDER: gate to the tier's FPS. 0 ⇒ never render (also covers a hidden tab
69
- // whose browser still fires the occasional rAF).
75
+ // RENDER: gate to the tier's FPS. 0 ⇒ never render (also covers a hidden tab whose browser still
76
+ // fires the occasional rAF); Infinity ⇒ uncapped, one render per animation frame.
70
77
  const fps = gameFps[tier];
71
78
  if (fps > 0) {
72
79
  renderAcc += wallDt;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {