ugly-game 0.15.62 → 0.15.64

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.
@@ -22,6 +22,66 @@ export interface PropWorld {
22
22
  saturation: number;
23
23
  valueLift: number;
24
24
  }
25
+ /**
26
+ * Opt-in photoreal shading controls, renderer-wide (every model drawn by this renderer).
27
+ *
28
+ * Every default selects exactly the shading that existed before these options, so a caller that
29
+ * never calls `setLook` (or passes none of these to the constructor) renders as it always did.
30
+ * Only PBR materials (those with `roughness` set) and thin glass are affected; legacy matte props
31
+ * keep their flat ambient and display-space lighting regardless.
32
+ */
33
+ export interface PropLook {
34
+ /**
35
+ * 'legacy' (default) is the historical `hdr / (1 + 0.35·hdr)` highlight compression.
36
+ * 'aces' is Stephen Hill's fitted ACES (RRT+ODT) curve, applied after `exposure`.
37
+ */
38
+ toneMapping: 'legacy' | 'aces';
39
+ /** Linear multiplier on HDR radiance before tone mapping. Default 1. */
40
+ exposure: number;
41
+ /**
42
+ * Renderer-wide linear HDR equirectangular environment (filterable float/unorm format, ideally a
43
+ * roughness-prefiltered mip chain like `PropMesh.environment`). Caller-owned; never destroyed
44
+ * here. Required by `environmentDiffuse` and `environmentSpecular`; without it both are inert.
45
+ */
46
+ environment: GPUTexture | null;
47
+ /**
48
+ * Image-based diffuse ambient intensity. 0 (default) keeps the flat `amb` colour passed to
49
+ * `frame()`. Above 0, the diffuse ambient of EVERY PBR material becomes
50
+ * `environment(N, irradiance mip) × environmentDiffuse` and the flat `amb` is ignored for them.
51
+ */
52
+ environmentDiffuse: number;
53
+ /**
54
+ * Mip level sampled for the irradiance approximation. Undefined (default) picks three levels
55
+ * above the 1×1 tail (8×4 on a 2:1 chain): the true last mip is one flat colour with no
56
+ * direction left in it. Set `mipLevelCount - 1` for the literal blurriest mip.
57
+ */
58
+ environmentDiffuseLod?: number;
59
+ /**
60
+ * When true, PBR materials WITHOUT their own `PropMesh.environment` reflect this environment
61
+ * (lod = roughness × (mipLevelCount − 1)) instead of the analytic studio environment. Materials
62
+ * with their own environment keep it. Default false.
63
+ */
64
+ environmentSpecular: boolean;
65
+ /**
66
+ * Sun-shadow receive filter. 'pcf3' (default) is the historical 3×3 PCF at 1-texel spacing.
67
+ * 'pcf5' / 'pcf7' are 25 / 49-tap grids and 'poisson' a 16-tap per-pixel-rotated Poisson disc,
68
+ * all spanning `shadowRadius` texels, with receiver-plane depth bias so wide kernels do not
69
+ * acne on sloped receivers.
70
+ */
71
+ shadowFilter: 'pcf3' | 'pcf5' | 'pcf7' | 'poisson';
72
+ /** Filter radius in shadow-map texels for the soft filters. Ignored by 'pcf3'. Default 2. */
73
+ shadowRadius: number;
74
+ }
75
+ /** Constructor options. All optional; omitting them is the historical renderer. */
76
+ export interface PropRendererOptions extends Partial<PropLook> {
77
+ /**
78
+ * MSAA sample count for every pipeline that draws into the caller's colour/depth views
79
+ * (opaque, blended, and every cull/depth-write variant). Default 1. With 4, `frame()` must be
80
+ * given 4× multisampled colour and depth views and the caller resolves them. The sun-shadow
81
+ * occluder pass is unaffected (always single-sample).
82
+ */
83
+ sampleCount?: 1 | 4;
84
+ }
25
85
  export interface PropMesh {
26
86
  /** Offline-cooked deformation bounds. Omit for procedural meshes. */
27
87
  extent?: {
@@ -252,6 +312,12 @@ export declare class GpuPropsRenderer {
252
312
  private shadowBG;
253
313
  private lastSV;
254
314
  private lastSS;
315
+ private lastEnv;
316
+ /** Bound at group 1 binding 2 when no PropLook.environment is set; never sampled then. */
317
+ private dummyEnv;
318
+ private look;
319
+ /** MSAA sample count the draw pipelines were built with. */
320
+ readonly sampleCount: 1 | 4;
255
321
  /** Per-world look + motion. Defaults are inert: no sway, no grain, no grade. */
256
322
  private world;
257
323
  private phase;
@@ -261,9 +327,16 @@ export declare class GpuPropsRenderer {
261
327
  * no per-model textures to author, download, or keep coherent.
262
328
  */
263
329
  setWorld(w: Partial<PropWorld>): void;
330
+ /**
331
+ * Set the opt-in photoreal controls (see PropLook). Merges like `setWorld`; pass a field as its
332
+ * default to turn it back off. Takes effect on the next `frame()`.
333
+ */
334
+ setLook(look: Partial<PropLook>): void;
335
+ /** The current photoreal controls. */
336
+ getLook(): Readonly<PropLook>;
264
337
  /** Advance the wind phase. Pass the frame delta; sway is skipped entirely when windAmp is 0. */
265
338
  tick(dt: number): void;
266
- constructor(device: GPUDevice, format: GPUTextureFormat);
339
+ constructor(device: GPUDevice, format: GPUTextureFormat, options?: PropRendererOptions);
267
340
  /**
268
341
  * Upload a decoded base-colour map with a full mip chain.
269
342
  *
@@ -277,8 +350,14 @@ export declare class GpuPropsRenderer {
277
350
  * getting this wrong is the classic washed-out-albedo bug.
278
351
  */
279
352
  private uploadAlbedo;
280
- /** Change scalar PBR properties without rebuilding geometry or texture bindings. */
281
- setMaterial(model: number, surface: Pick<PropMesh, 'roughness' | 'metalness' | 'clearcoat' | 'clearcoatRoughness' | 'reflectionStrength' | 'specularIntensity' | 'metalFlakes' | 'flakeScale' | 'pearlStrength'>): void;
353
+ /**
354
+ * Change scalar PBR properties without rebuilding geometry or texture bindings.
355
+ *
356
+ * `alpha` fades a model in place (a body fading away to show what is inside it). Below 1 the
357
+ * model moves to the blended pipeline and out of shadowPass from the next frame, exactly as if
358
+ * `setModels` had been given that alpha; back at 1 it is opaque and casts again.
359
+ */
360
+ setMaterial(model: number, surface: Pick<PropMesh, 'alpha' | 'roughness' | 'metalness' | 'clearcoat' | 'clearcoatRoughness' | 'reflectionStrength' | 'specularIntensity' | 'metalFlakes' | 'flakeScale' | 'pearlStrength'>): void;
282
361
  setModels(meshes: PropMesh[]): void;
283
362
  /**
284
363
  * Group instances by model and upload the per-model instance buffers.
@@ -15,7 +15,13 @@ const SHADER = /* wgsl */ `
15
15
  // csm + cascades are APPENDED, not woven in: every field above keeps the byte offset it had, so the
16
16
  // existing writes in frame() are untouched and a caller that knows nothing about cascades stays
17
17
  // byte-identical. lightVP remains the legacy cascade-0 slot; shading reads cascades instead.
18
- struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<f32>, amb: vec4<f32>, cam: vec4<f32>, fog: vec4<f32>, up: vec4<f32>, wind: vec4<f32>, surf: vec4<f32>, grade: vec4<f32>, csm: vec4<f32>, cascades: array<mat4x4<f32>, ${MAX_CASCADES}> };
18
+ // look + look2 (the opt-in photoreal controls, see PropLook) are appended after the cascades for the
19
+ // same reason, and every one of their defaults selects the exact expressions that ran before them:
20
+ // look = (toneMapping 0 legacy / 1 aces, exposure, environment-diffuse intensity (0 ⇒ flat amb),
21
+ // environment specular for every PBR material (0/1))
22
+ // look2 = (shadow filter 0 pcf3 / 1 pcf5 / 2 pcf7 / 3 poisson, radius in texels,
23
+ // scene-environment max lod, scene-environment irradiance lod)
24
+ struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<f32>, amb: vec4<f32>, cam: vec4<f32>, fog: vec4<f32>, up: vec4<f32>, wind: vec4<f32>, surf: vec4<f32>, grade: vec4<f32>, csm: vec4<f32>, cascades: array<mat4x4<f32>, ${MAX_CASCADES}>, look: vec4<f32>, look2: vec4<f32> };
19
25
  @group(0) @binding(0) var<uniform> u: U;
20
26
  // One instance. 'm' is the placement; d0/d1/d2 are the per-instance DEFORM, which is what lets
21
27
  // thousands of visibly different plants share a single mesh and a single draw call. Baking each
@@ -41,6 +47,9 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
41
47
  @group(2) @binding(5) var ormTex: texture_2d<f32>;
42
48
  @group(1) @binding(0) var shadowMap: texture_depth_2d_array; // the SAME cascaded sun shadow map the terrain cubes sample
43
49
  @group(1) @binding(1) var shadowSamp: sampler_comparison;
50
+ // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
51
+ // sampled: look.z and look.w are forced to 0 on the CPU without it.
52
+ @group(1) @binding(2) var sceneEnvTex: texture_2d<f32>;
44
53
  struct VO { @builtin(position) pos: vec4<f32>, @location(0) world: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: vec3<f32>, @location(3) l: vec3<f32>, @location(4) uv: vec2<f32> };
45
54
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
46
55
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
@@ -124,8 +133,62 @@ fn fixedFill(N: vec3<f32>, up: vec3<f32>) -> f32 {
124
133
  let L = normalize(up * 0.82 + t * 0.57);
125
134
  return max(dot(N, L), 0.0);
126
135
  }
136
+ // Wider, opt-in sun-shadow filters. Grid PCF is noise-free; the Poisson disc is cheaper per unit of
137
+ // penumbra but rotates per pixel (interleaved gradient noise), so it trades banding for fine grain.
138
+ //
139
+ // RECEIVER-PLANE DEPTH BIAS. A constant bias that is enough for a 1-texel kernel is nowhere near
140
+ // enough for a 4-texel one: on a sloped receiver the far taps compare against depths the surface
141
+ // itself occupies, and the ground fills with acne stripes. So each tap's reference depth follows the
142
+ // receiver's own plane (dz/duv, from the world-space derivatives the caller took in uniform control
143
+ // flow), plus one texel of that slope for the quantisation of the map itself.
144
+ fn softShadow(uv: vec2<f32>, z: f32, layer: i32, texel: vec2<f32>, frag: vec2<f32>, wdx: vec3<f32>, wdy: vec3<f32>) -> f32 {
145
+ let mode = u.look2.x;
146
+ let radius = max(u.look2.y, 0.0);
147
+ let lx = (u.cascades[layer] * vec4(wdx, 0.0)).xyz;
148
+ let ly = (u.cascades[layer] * vec4(wdy, 0.0)).xyz;
149
+ let ux = lx.xy * vec2(0.5, -0.5);
150
+ let uy = ly.xy * vec2(0.5, -0.5);
151
+ let det = ux.x * uy.y - uy.x * ux.y;
152
+ var dz = vec2(0.0);
153
+ if (abs(det) > 1e-14) {
154
+ dz = vec2(uy.y * lx.z - ux.y * ly.z, ux.x * ly.z - uy.x * lx.z) / det;
155
+ }
156
+ // Grazing receivers produce unbounded slopes; cap at ~one depth unit per map width.
157
+ dz = clamp(dz, vec2(-1.0), vec2(1.0));
158
+ let zr = z - (abs(dz.x) * texel.x + abs(dz.y) * texel.y);
159
+ if (mode > 2.5) {
160
+ let ign = fract(52.9829189 * fract(dot(frag, vec2(0.06711056, 0.00583715))));
161
+ let a = ign * 6.2831853;
162
+ let cs = cos(a); let sn = sin(a);
163
+ // 16-tap Poisson disc on the unit disc.
164
+ var poisson = array<vec2<f32>, 16>(
165
+ vec2(-0.94201624, -0.39906216), vec2(0.94558609, -0.76890725), vec2(-0.09418410, -0.92938870), vec2(0.34495938, 0.29387760),
166
+ vec2(-0.91588581, 0.45771432), vec2(-0.81544232, -0.87912464), vec2(-0.38277543, 0.27676845), vec2(0.97484398, 0.75648379),
167
+ vec2(0.44323325, -0.97511554), vec2(0.53742981, -0.47373420), vec2(-0.26496911, -0.41893023), vec2(0.79197514, 0.19090188),
168
+ vec2(-0.24188840, 0.99706507), vec2(-0.81409955, 0.91437590), vec2(0.19984126, 0.78641367), vec2(0.14383161, -0.14100790));
169
+ var s = 0.0;
170
+ for (var k = 0; k < 16; k = k + 1) {
171
+ let p = poisson[k];
172
+ let o = vec2(p.x * cs - p.y * sn, p.x * sn + p.y * cs) * radius * texel;
173
+ s = s + textureSampleCompareLevel(shadowMap, shadowSamp, uv + o, layer, zr + dot(dz, o));
174
+ }
175
+ return s / 16.0;
176
+ }
177
+ let reach = select(2, 3, mode > 1.5);
178
+ let spacing = radius / f32(reach);
179
+ var s = 0.0;
180
+ var n = 0.0;
181
+ for (var dy = -reach; dy <= reach; dy = dy + 1) {
182
+ for (var dx = -reach; dx <= reach; dx = dx + 1) {
183
+ let o = vec2(f32(dx), f32(dy)) * spacing * texel;
184
+ s = s + textureSampleCompareLevel(shadowMap, shadowSamp, uv + o, layer, zr + dot(dz, o));
185
+ n = n + 1.0;
186
+ }
187
+ }
188
+ return s / n;
189
+ }
127
190
  // PCF 3×3 sun shadow — mirrors gpuShadow.shadowFactor so props sit in the SAME shadow as the terrain. 1 = lit, 0 = shadowed.
128
- fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>) -> f32 {
191
+ fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>, frag: vec2<f32>, wdx: vec3<f32>, wdy: vec3<f32>) -> f32 {
129
192
  let lp = u.cascades[layer] * vec4(world, 1.0);
130
193
  let proj = lp.xyz / lp.w;
131
194
  let uv = proj.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);
@@ -135,6 +198,9 @@ fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>)
135
198
  *inside = true;
136
199
  let bias = max(0.0006 * (1.0 - ndl), 0.0004) * (1.0 + f32(layer) * 1.5);
137
200
  let texel = 1.0 / vec2<f32>(textureDimensions(shadowMap));
201
+ if (u.look2.x > 0.5) {
202
+ return softShadow(uv, proj.z - bias, layer, texel, frag, wdx, wdy);
203
+ }
138
204
  var s = 0.0;
139
205
  for (var dy = -1; dy <= 1; dy = dy + 1) {
140
206
  for (var dx = -1; dx <= 1; dx = dx + 1) {
@@ -145,11 +211,11 @@ fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>)
145
211
  }
146
212
  // Tightest cascade that CONTAINS the point wins — the same rule gpuShadow uses, so a prop and the
147
213
  // terrain under it always resolve against the same map and cannot disagree about being in shadow.
148
- fn shadowFactor(world: vec3<f32>, ndl: f32) -> f32 {
214
+ fn shadowFactor(world: vec3<f32>, ndl: f32, frag: vec2<f32>, wdx: vec3<f32>, wdy: vec3<f32>) -> f32 {
149
215
  let n = i32(u.csm.x);
150
216
  var inside = false;
151
217
  for (var c = 0; c < n; c = c + 1) {
152
- let f = pcfLayer(world, ndl, c, &inside);
218
+ let f = pcfLayer(world, ndl, c, &inside, frag, wdx, wdy);
153
219
  if (inside) { return f; }
154
220
  }
155
221
  return 1.0;
@@ -208,20 +274,43 @@ fn studioEnv(r: vec3<f32>, rough: f32) -> vec3<f32> {
208
274
  c += vec3(2.5, 2.35, 2.1) * (stripA + stripB) * (1.0 - rough * 0.7);
209
275
  return c;
210
276
  }
277
+ fn equirectUV(r: vec3<f32>) -> vec2<f32> {
278
+ return vec2(atan2(r.z,r.x)/6.2831853+0.5,acos(clamp(r.y,-1.0,1.0))/3.14159265);
279
+ }
211
280
  fn environment(r: vec3<f32>, rough: f32) -> vec3<f32> {
212
- if (mtl.coat.z < 0.5) { return studioEnv(r,rough); }
213
- let uv=vec2(atan2(r.z,r.x)/6.2831853+0.5,acos(clamp(r.y,-1.0,1.0))/3.14159265);
281
+ if (mtl.coat.z >= 0.5) { return sampleEquirect(environmentTex,r,rough*mtl.coat.w); }
282
+ // Opt-in: every other PBR material reflects the renderer-wide environment instead of studioEnv.
283
+ if (u.look.w > 0.5) { return sampleEquirect(sceneEnvTex,r,rough*u.look2.z); }
284
+ return studioEnv(r,rough);
285
+ }
286
+ fn sampleEquirect(envTex: texture_2d<f32>, r: vec3<f32>, roughLod: f32) -> vec3<f32> {
287
+ let uv=equirectUV(r);
214
288
  // Roughness alone under-filters glossy curved surfaces: one screen pixel can
215
289
  // span many environment texels, making chrome/clearcoat flash while orbiting.
216
290
  // Respect that footprint as well as the material's prefiltered reflection.
217
291
  // Longitude wraps at the panorama seam; unwrap its derivatives so crossing
218
292
  // that seam does not introduce a spurious blurry stripe.
219
293
  let dx=dpdx(uv); let dy=dpdy(uv);
220
- let dimensions=vec2<f32>(textureDimensions(environmentTex));
294
+ let dimensions=vec2<f32>(textureDimensions(envTex));
221
295
  let sx=vec2(dx.x-round(dx.x),dx.y)*dimensions;
222
296
  let sy=vec2(dy.x-round(dy.x),dy.y)*dimensions;
223
297
  let pixelLod=log2(max(1.0,max(length(sx),length(sy))));
224
- return textureSampleLevel(environmentTex,albedoSamp,uv,max(rough*mtl.coat.w,pixelLod)).rgb;
298
+ return textureSampleLevel(envTex,albedoSamp,uv,max(roughLod,pixelLod)).rgb;
299
+ }
300
+ // Fitted ACES (Stephen Hill's RRT+ODT fit, sRGB primaries in and out).
301
+ fn acesFitted(c: vec3<f32>) -> vec3<f32> {
302
+ let i = mat3x3<f32>(vec3(0.59719, 0.07600, 0.02840), vec3(0.35458, 0.90834, 0.13383), vec3(0.04823, 0.01566, 0.83777));
303
+ let o = mat3x3<f32>(vec3(1.60475, -0.10208, -0.00327), vec3(-0.53108, 1.10813, -0.07276), vec3(-0.07367, -0.00605, 1.07602));
304
+ let v = i * c;
305
+ let a = v * (v + 0.0245786) - 0.000090537;
306
+ let b = v * (0.983729 * v + 0.4329510) + 0.238081;
307
+ return clamp(o * (a / b), vec3(0.0), vec3(1.0));
308
+ }
309
+ // Linear HDR → display sRGB. look.x = 0 is the historical highlight compression, untouched.
310
+ fn toneMap(hdr: vec3<f32>) -> vec3<f32> {
311
+ let x = hdr * u.look.y;
312
+ if (u.look.x > 0.5) { return linearToSrgb(acesFitted(max(x, vec3(0.0)))); }
313
+ return linearToSrgb(x / (vec3(1.0) + x * 0.35));
225
314
  }
226
315
  fn fresnel(f0: vec3<f32>, cosTheta: f32) -> vec3<f32> {
227
316
  return f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(cosTheta, 0.0, 1.0), 5.0);
@@ -255,7 +344,7 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
255
344
  }
256
345
  let ff = select(1.0, 0.5 + 0.85 * fixedFill(N, u.up.xyz), u.up.w > 0.5); // fixed fill (fall back to flat amb if no up)
257
346
  let d = clamp(dot(N, -normalize(u.sun.xyz)), 0.0, 1.0);
258
- let sh = mix(1.0, shadowFactor(i.world, d), u.sun.w); // u.sun.w = shadow-receive enable (0 ⇒ off, byte-identical for demo)
347
+ let sh = mix(1.0, shadowFactor(i.world, d, i.pos.xy, px, py), u.sun.w); // u.sun.w = shadow-receive enable (0 ⇒ off, byte-identical for demo)
259
348
  // procedural grain modulates the role colour; the per-world grade then re-tints the whole planet
260
349
  // Albedo modulates the vertex colour rather than replacing it, so the StyleGuide role tint and the
261
350
  // per-instance hue jitter still act on a textured prop — and an untextured one samples the 1x1
@@ -297,9 +386,16 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
297
386
  let R = reflect(-V,N);
298
387
  let env = environment(R,rough) * mtl.coat.y;
299
388
  let reflected = env * fresnel(f0,nv) * (1.0-rough*0.6);
300
- let ambient=mix(u.amb.xyz,environment(N,1.0)*0.45,select(0.0,0.6,mtl.coat.z>0.5));
389
+ var ambient=mix(u.amb.xyz,environment(N,1.0)*0.45,select(0.0,0.6,mtl.coat.z>0.5));
390
+ var skyOcclusion=0.6 + 0.4*max(N.y,0.0);
391
+ if (u.look.z > 0.0) {
392
+ // Image-based ambient: the renderer environment's blurry mip in direction N stands in for
393
+ // irradiance. It already darkens downward normals, so the fake sky term above is dropped.
394
+ ambient=textureSampleLevel(sceneEnvTex,albedoSamp,equirectUV(N),u.look2.w).rgb*u.look.z;
395
+ skyOcclusion=1.0;
396
+ }
301
397
  let ao=select(1.0,orm.r,mtl.maps.y>0.5);
302
- let diffuse = albedo * ambient * (0.6 + 0.4*max(N.y,0.0)) * (1.0-metal)*ao;
398
+ let diffuse = albedo * ambient * skyOcclusion * (1.0-metal)*ao;
303
399
  let coatF = fresnel(vec3(0.04),nv) * mtl.coat.x;
304
400
  let coating = environment(R,mtl.surface.z) * coatF * mtl.coat.y;
305
401
  // A soft fiber lobe distinguishes woven upholstery from a glossy dielectric.
@@ -324,7 +420,7 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
324
420
  let hdr = (flakes + direct + diffuse * (1.0-mtl.surface.y*0.12) + reflected + sheen) * (vec3(1.0)-coatF) + coating;
325
421
  // Smooth highlight compression preserves saturated paint rather than
326
422
  // clipping reflected softboxes to a flat white patch.
327
- lit = linearToSrgb(hdr / (vec3(1.0) + hdr * 0.35));
423
+ lit = toneMap(hdr);
328
424
  }
329
425
  let dist = length(i.world - u.cam.xyz);
330
426
  let f = clamp(1.0 - exp(-dist * u.fog.w), 0.0, 1.0);
@@ -339,7 +435,7 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
339
435
  let F = 0.04 + 0.96*pow(1.0-nv,5.0);
340
436
  opacity = clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
341
437
  let radiance = environment(reflect(-V,N),max(mtl.mat.z,0.045));
342
- lit = linearToSrgb(radiance/(vec3(1.0)+radiance*0.35));
438
+ lit = toneMap(radiance);
343
439
  }
344
440
  // A display-referred render texture (rear-view camera) is already lit.
345
441
  if (mtl.optics.y > 0.5) { return vec4(tex.rgb, mtl.mat.x); }
@@ -403,6 +499,17 @@ fn deformLocal(p: vec3<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>) -> vec
403
499
  }
404
500
  return o.lightVP * vec4(world, 1.0);
405
501
  }`;
502
+ const DEFAULT_LOOK = {
503
+ toneMapping: 'legacy',
504
+ exposure: 1,
505
+ environment: null,
506
+ environmentDiffuse: 0,
507
+ environmentDiffuseLod: undefined,
508
+ environmentSpecular: false,
509
+ shadowFilter: 'pcf3',
510
+ shadowRadius: 2,
511
+ };
512
+ const SHADOW_FILTER = { pcf3: 0, pcf5: 1, pcf7: 2, poisson: 3 };
406
513
  /**
407
514
  * Floats per instance in the storage buffer: mat4 + d0 + d1 + d2 + d3.
408
515
  *
@@ -554,6 +661,12 @@ export class GpuPropsRenderer {
554
661
  shadowBG = null;
555
662
  lastSV = null;
556
663
  lastSS = null;
664
+ lastEnv = null;
665
+ /** Bound at group 1 binding 2 when no PropLook.environment is set; never sampled then. */
666
+ dummyEnv;
667
+ look = { ...DEFAULT_LOOK };
668
+ /** MSAA sample count the draw pipelines were built with. */
669
+ sampleCount;
557
670
  /** Per-world look + motion. Defaults are inert: no sway, no grain, no grade. */
558
671
  world = {
559
672
  windDir: [1, 0],
@@ -575,13 +688,34 @@ export class GpuPropsRenderer {
575
688
  setWorld(w) {
576
689
  this.world = { ...this.world, ...w };
577
690
  }
691
+ /**
692
+ * Set the opt-in photoreal controls (see PropLook). Merges like `setWorld`; pass a field as its
693
+ * default to turn it back off. Takes effect on the next `frame()`.
694
+ */
695
+ setLook(look) {
696
+ const next = { ...this.look };
697
+ for (const [key, value] of Object.entries(look))
698
+ if (value !== undefined || key === 'environmentDiffuseLod')
699
+ next[key] = value;
700
+ this.look = next;
701
+ }
702
+ /** The current photoreal controls. */
703
+ getLook() {
704
+ return { ...this.look };
705
+ }
578
706
  /** Advance the wind phase. Pass the frame delta; sway is skipped entirely when windAmp is 0. */
579
707
  tick(dt) {
580
708
  if (this.world.windAmp > 0)
581
709
  this.phase += dt * (0.8 + this.world.windAmp * 2.4);
582
710
  }
583
- constructor(device, format) {
711
+ constructor(device, format, options = {}) {
584
712
  this.device = device;
713
+ const { sampleCount = 1, ...look } = options;
714
+ // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
715
+ if (![1, 4].includes(sampleCount))
716
+ throw new RangeError(`Unsupported prop sampleCount ${String(sampleCount)}`);
717
+ this.sampleCount = sampleCount;
718
+ this.setLook(look);
585
719
  const sm = device.createShaderModule({ code: SHADER });
586
720
  // The three groups the SHADER declares, written out so BOTH render pipelines share them. Under
587
721
  // `layout: 'auto'` each pipeline would mint its own and the bind groups built elsewhere in this
@@ -612,6 +746,11 @@ export class GpuPropsRenderer {
612
746
  visibility: GPUShaderStage.FRAGMENT,
613
747
  sampler: { type: 'comparison' },
614
748
  },
749
+ {
750
+ binding: 2,
751
+ visibility: GPUShaderStage.FRAGMENT,
752
+ texture: { sampleType: 'float' },
753
+ },
615
754
  ],
616
755
  });
617
756
  const bgl2 = device.createBindGroupLayout({
@@ -669,6 +808,8 @@ export class GpuPropsRenderer {
669
808
  ],
670
809
  },
671
810
  primitive: { topology: 'triangle-list', cullMode: 'none' },
811
+ // Only the passes that target the caller's views. The occluder below stays single-sample.
812
+ ...(sampleCount > 1 ? { multisample: { count: sampleCount } } : {}),
672
813
  };
673
814
  const opaqueDescriptor = {
674
815
  ...commonDraw,
@@ -758,7 +899,7 @@ export class GpuPropsRenderer {
758
899
  },
759
900
  });
760
901
  this.uBuf = device.createBuffer({
761
- size: 128 + 16 * 9 + 16 + 64 * MAX_CASCADES, // + csm vec4 + the cascade matrices
902
+ size: 128 + 16 * 9 + 16 + 64 * MAX_CASCADES + 32, // + csm vec4 + the cascade matrices + look, look2
762
903
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
763
904
  });
764
905
  for (let c = 0; c < MAX_CASCADES; c++)
@@ -780,6 +921,11 @@ export class GpuPropsRenderer {
780
921
  });
781
922
  this.dummyShadowView = dummy.createView({ dimension: '2d-array' }); // the binding is an array now
782
923
  this.dummyShadowSamp = device.createSampler({ compare: 'less' });
924
+ this.dummyEnv = device.createTexture({
925
+ size: [1, 1],
926
+ format: 'rgba8unorm',
927
+ usage: GPUTextureUsage.TEXTURE_BINDING,
928
+ });
783
929
  }
784
930
  /**
785
931
  * Upload a decoded base-colour map with a full mip chain.
@@ -835,7 +981,13 @@ export class GpuPropsRenderer {
835
981
  }
836
982
  return tex;
837
983
  }
838
- /** Change scalar PBR properties without rebuilding geometry or texture bindings. */
984
+ /**
985
+ * Change scalar PBR properties without rebuilding geometry or texture bindings.
986
+ *
987
+ * `alpha` fades a model in place (a body fading away to show what is inside it). Below 1 the
988
+ * model moves to the blended pipeline and out of shadowPass from the next frame, exactly as if
989
+ * `setModels` had been given that alpha; back at 1 it is opaque and casts again.
990
+ */
839
991
  setMaterial(model, surface) {
840
992
  const packed = this.models.at(model);
841
993
  if (model < 0 || !packed)
@@ -864,6 +1016,14 @@ export class GpuPropsRenderer {
864
1016
  packed.materialValues[index] = bounded;
865
1017
  changed = true;
866
1018
  }
1019
+ if (surface.alpha !== undefined && Number.isFinite(surface.alpha)) {
1020
+ const alpha = Math.max(0, Math.min(1, surface.alpha));
1021
+ if (Math.abs(packed.alpha - alpha) >= 1e-7) {
1022
+ packed.alpha = alpha;
1023
+ packed.materialValues[0] = alpha;
1024
+ changed = true;
1025
+ }
1026
+ }
867
1027
  if (changed)
868
1028
  this.device.queue.writeBuffer(packed.matBuf, 0, packed.materialValues);
869
1029
  }
@@ -1323,7 +1483,7 @@ export class GpuPropsRenderer {
1323
1483
  lightVP, shadowView, shadowSamp) {
1324
1484
  const receive = !!(lightVP && shadowView && shadowSamp);
1325
1485
  const mats = lightVP ? (Array.isArray(lightVP) ? lightVP : [lightVP]) : [];
1326
- const u = new Float32Array(68 + 4 + 16 * MAX_CASCADES);
1486
+ const u = new Float32Array(68 + 4 + 16 * MAX_CASCADES + 8);
1327
1487
  u.set(camVP, 0);
1328
1488
  u.set(mats[0] ?? IDENTITY4, 16); // legacy cascade-0 slot, kept so the offsets above never move
1329
1489
  u.set([sunDir[0], sunDir[1], sunDir[2], receive ? 1 : 0], 32); // sun.w = shadow-receive enable
@@ -1344,19 +1504,40 @@ export class GpuPropsRenderer {
1344
1504
  u[68] = receive ? Math.min(MAX_CASCADES, mats.length) : 0;
1345
1505
  for (let i = 0; i < Math.min(MAX_CASCADES, mats.length); i++)
1346
1506
  u.set(mats[i], 72 + i * 16);
1507
+ // look / look2 — the opt-in photoreal controls. Defaults write (0, 1, 0, 0) and (0, ·, ·, ·),
1508
+ // which select the historical expressions in every branch they guard.
1509
+ const look = this.look;
1510
+ const env = look.environment;
1511
+ const envMaxLod = env ? env.mipLevelCount - 1 : 0;
1512
+ const lookAt = 72 + 16 * MAX_CASCADES;
1513
+ u.set([
1514
+ look.toneMapping === 'aces' ? 1 : 0,
1515
+ Number.isFinite(look.exposure) ? Math.max(0, look.exposure) : 1,
1516
+ env && look.environmentDiffuse > 0 ? look.environmentDiffuse : 0,
1517
+ env && look.environmentSpecular ? 1 : 0,
1518
+ SHADOW_FILTER[look.shadowFilter],
1519
+ Math.max(0, look.shadowRadius),
1520
+ envMaxLod,
1521
+ Math.max(0, Math.min(envMaxLod, look.environmentDiffuseLod ?? envMaxLod - 3)),
1522
+ ], lookAt);
1347
1523
  this.device.queue.writeBuffer(this.uBuf, 0, u);
1348
1524
  // group 1: the shadow map + comparison sampler (dummy when not receiving). Rebuild only when the view changes.
1349
1525
  const sv = shadowView ?? this.dummyShadowView, ss = shadowSamp ?? this.dummyShadowSamp;
1350
- if (!this.shadowBG || sv !== this.lastSV || ss !== this.lastSS) {
1526
+ if (!this.shadowBG ||
1527
+ sv !== this.lastSV ||
1528
+ ss !== this.lastSS ||
1529
+ env !== this.lastEnv) {
1351
1530
  this.shadowBG = this.device.createBindGroup({
1352
1531
  layout: this.drawBGL[1],
1353
1532
  entries: [
1354
1533
  { binding: 0, resource: sv },
1355
1534
  { binding: 1, resource: ss },
1535
+ { binding: 2, resource: (env ?? this.dummyEnv).createView() },
1356
1536
  ],
1357
1537
  });
1358
1538
  this.lastSV = sv;
1359
1539
  this.lastSS = ss;
1540
+ this.lastEnv = env;
1360
1541
  }
1361
1542
  const rp = enc.beginRenderPass({
1362
1543
  colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.62",
3
+ "version": "0.15.64",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {