ugly-game 0.15.73 → 0.15.75

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.
@@ -1,5 +1,10 @@
1
1
  /// <reference types="@webgpu/types" preserve="true" />
2
+ export { WET_RIND_WGSL } from './wetRind.js';
3
+ export { INTERIOR_LIGHT_WGSL } from './interiorLight.js';
2
4
  import { type DepthConvention } from '../depthConvention.js';
5
+ import { type PropInspectionChannel } from './propInspection.js';
6
+ export type { PropInspectionChannel } from './propInspection.js';
7
+ export { THIN_TISSUE_WGSL } from './thinTissue.js';
3
8
  export declare const MAX_CASCADES = 4;
4
9
  export declare const MAX_PROP_POINT_LIGHTS = 8;
5
10
  /** Caller-selected local lights, in the same rebased coordinates as frame().
@@ -91,6 +96,9 @@ export interface PropLook {
91
96
  }
92
97
  /** Constructor options. All optional; omitting them is the historical renderer. */
93
98
  export interface PropRendererOptions extends Partial<PropLook> {
99
+ /** Compile material/topology inspection channels. Off by default. On the
100
+ * first topology view, an expanded corner stream is built for wire/density. */
101
+ inspection?: boolean;
94
102
  /**
95
103
  * MSAA sample count for every pipeline that draws into the caller's colour/depth views
96
104
  * (opaque, blended, and every cull/depth-write variant). Default 1. With 4, `frame()` must be
@@ -134,6 +142,12 @@ export interface PropMesh {
134
142
  * with distance. Unlike `unlit`, vertex colours count.
135
143
  */
136
144
  glow?: boolean;
145
+ /** Normal-incidence optical depth of the clear or tissue rind over a luminous
146
+ * source. On glow materials a positive value attenuates its linear radiance
147
+ * by the viewing path length. Zero keeps the display-referred glow path. */
148
+ interiorOpticalDepth?: number;
149
+ /** Local height of the wet contact zone above model y=0. Omitted for dry material. */
150
+ wetRindHeight?: number;
137
151
  /** Caller-owned linear occlusion/roughness/metalness map (RGB). */
138
152
  ormMap?: GPUTexture;
139
153
  normalScale?: number;
@@ -284,6 +298,9 @@ export interface PropInstance {
284
298
  }
285
299
  export declare class GpuPropsRenderer {
286
300
  private device;
301
+ private inspection;
302
+ private srgbTarget;
303
+ private inspectionGeometry?;
287
304
  private pipe;
288
305
  /**
289
306
  * The same pipeline with source-alpha blending and depth writes off, for models with `alpha < 1`.
@@ -455,5 +472,5 @@ export declare class GpuPropsRenderer {
455
472
  * a single shared uniform written once per cascade during encoding does not work — see `lightBufs`.
456
473
  */
457
474
  shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
458
- frame(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, camVP: Float32Array, sunDir: [number, number, number], sunCol: [number, number, number], amb: [number, number, number], camPos: [number, number, number], fog: [number, number, number], fogDensity: number, up?: [number, number, number], lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler): void;
475
+ frame(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, camVP: Float32Array, sunDir: [number, number, number], sunCol: [number, number, number], amb: [number, number, number], camPos: [number, number, number], fog: [number, number, number], fogDensity: number, up?: [number, number, number], lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler, channel?: PropInspectionChannel): void;
459
476
  }
@@ -6,13 +6,20 @@
6
6
  // ─────────────────────────────────────────────────────────────────────────────
7
7
  // The cull reuses the SAME plane extraction the rest of the engine uses. A second, local copy of
8
8
  // Gribb-Hartmann is exactly how a cull ends up disagreeing with the projection it is culling for.
9
+ import { WET_RIND_WGSL } from './wetRind.js';
10
+ export { WET_RIND_WGSL } from './wetRind.js';
11
+ import { INTERIOR_LIGHT_WGSL } from './interiorLight.js';
12
+ export { INTERIOR_LIGHT_WGSL } from './interiorLight.js';
9
13
  import { frustumPlanes } from '../mat4';
10
14
  import { FORWARD_DEPTH, nearerCompare, } from '../depthConvention.js';
15
+ import { inspectionFragment, propInspectionChannels, PropInspectionGeometry, } from './propInspection.js';
16
+ import { THIN_TISSUE_WGSL } from './thinTissue.js';
17
+ export { THIN_TISSUE_WGSL } from './thinTissue.js';
11
18
  export const MAX_CASCADES = 4; // must match gpuShadow's
12
19
  export const MAX_PROP_POINT_LIGHTS = 8;
13
20
  const POINT_LIGHT_WORDS = 4 + MAX_PROP_POINT_LIGHTS * 16;
14
21
  const PROP_UNIFORM_WORDS = 72 + 16 * MAX_CASCADES + 8 + POINT_LIGHT_WORDS;
15
- const SHADER = /* wgsl */ `
22
+ const drawShader = (inspect) => /* wgsl */ `
16
23
  // wind = (dirX, dirZ, amplitude, phase) — sway, amplitude scaled by the world's air density
17
24
  // surf = (grainScale, grainDepth, roughness, emissive)
18
25
  // grade = (hueShift, saturation, valueLift, unused)
@@ -45,7 +52,7 @@ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: v
45
52
  // alpha-test cutoff (0 ⇒ no test, which is every model that predates it).
46
53
  // mat = opacity, cutoff, roughness (-1 = legacy), metalness.
47
54
  // coat = clearcoat, reflection strength, unused, unused.
48
- struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32>, paint: vec4<f32>, optics: vec4<f32> };
55
+ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32>, paint: vec4<f32>, optics: vec4<f32>, medium: vec4<f32> };
49
56
  @group(2) @binding(2) var<uniform> mtl: Mat;
50
57
  @group(2) @binding(3) var environmentTex: texture_2d<f32>;
51
58
  @group(2) @binding(4) var normalTex: texture_2d<f32>;
@@ -55,7 +62,7 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
55
62
  // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
56
63
  // sampled: look.z and look.w are forced to 0 on the CPU without it.
57
64
  @group(1) @binding(2) var sceneEnvTex: texture_2d<f32>;
58
- 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> };
65
+ 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> ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<f32>' : ''} };
59
66
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
60
67
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
61
68
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -117,7 +124,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
117
124
  let ca = cos(a); let sa = sin(a);
118
125
  return normalize(vec3(v.x * ca - v.z * sa, v.y, v.x * sa + v.z * ca));
119
126
  }
120
- @vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @location(3) uv: vec2<f32>, @builtin(instance_index) ii: u32) -> VO {
127
+ @vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @location(3) uv: vec2<f32>, @builtin(instance_index) ii: u32 ${inspect ? ', @builtin(vertex_index) vi:u32' : ''}) -> VO {
121
128
  let inst = models[ii];
122
129
  let m = inst.m;
123
130
  let lp = deformLocal(p, inst.d0, inst.d1, inst.d2);
@@ -127,7 +134,9 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
127
134
  let sc = length(m[0].xyz);
128
135
  world = sway(lp, world, upv, sc * inst.d2.w);
129
136
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
130
- o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv; return o;
137
+ o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
138
+ ${inspect ? 'o.bary = vec3<f32>(f32(vi%3u==0u),f32(vi%3u==1u),f32(vi%3u==2u));' : ''}
139
+ return o;
131
140
  }
132
141
  // same fixed directional FILL as the terrain cubes (gpuShadow.fixedFill) so plants/rocks read the same 3D shape,
133
142
  // day or night, under one shared light. up.w > 0.5 signals a valid local-up was supplied (else fall back to flat).
@@ -348,6 +357,26 @@ fn srgbToLinear(c: vec3<f32>) -> vec3<f32> {
348
357
  fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
349
358
  return select(c * 12.92, 1.055 * pow(max(c, vec3(0.0)), vec3(1.0/2.4)) - 0.055, c > vec3(0.0031308));
350
359
  }
360
+ ${INTERIOR_LIGHT_WGSL}
361
+ fn propEmission(tex: vec3<f32>, pigment: vec3<f32>, normal: vec3<f32>, world: vec3<f32>) -> vec3<f32> {
362
+ if (mtl.medium.x <= 0.0) { return tex*pigment; }
363
+ let view = normalize(u.cam.xyz-world);
364
+ return tex*srgbToLinear(max(pigment,vec3(0.0)))*buriedLightEscape(dot(normal,view),mtl.medium.x);
365
+ }
366
+ ${WET_RIND_WGSL}
367
+ fn effectiveRoughness(orm:vec3<f32>, localY:f32) -> f32 {
368
+ let dry = clamp(mtl.mat.z * select(1.0,orm.g,mtl.maps.y>0.5), 0.045, 1.0);
369
+ if (mtl.medium.y > 0.0) { return wetRindRoughness(dry,wetRindCoverage(localY,mtl.medium.y,dry)); }
370
+ return dry;
371
+ }
372
+ fn effectiveAO(orm:vec3<f32>) -> f32 { return select(1.0,orm.r,mtl.maps.y>0.5); }
373
+ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
374
+ if (mtl.optics.x <= 0.0) { return mtl.mat.x; }
375
+ let nv = clamp(abs(dot(n,normalize(u.cam.xyz-world))),0.0,1.0);
376
+ let F = 0.04 + 0.96*pow(1.0-nv,5.0);
377
+ return clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
378
+ }
379
+ ${THIN_TISSUE_WGSL}
351
380
  @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
352
381
  var N = normalize(i.n);
353
382
  let materialUV=i.uv*mtl.maps.w;
@@ -384,6 +413,11 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
384
413
  base = base * (1.0 - u.surf.y * 0.5 + u.surf.y * grain);
385
414
  }
386
415
  base = hsvShift(base, u.grade.x, max(u.grade.y, 0.0), max(u.grade.z, 0.0));
416
+ ${inspect ? inspectionFragment : ''}
417
+ if (mtl.optics.y > 1.5) {
418
+ let fog = clamp(1.0-exp(-length(i.world-u.cam.xyz)*u.fog.w),0.0,1.0);
419
+ return vec4(mix(propEmission(tex.rgb,i.c,normalize(i.n),i.world),u.fog.xyz,fog),mtl.mat.x);
420
+ }
387
421
  let spec = u.surf.z;
388
422
  var lit = base * (u.amb.xyz * ff + d * u.sunCol.xyz * sh * (1.0 + spec * 0.6))
389
423
  + base * u.surf.w; // emissive — bioluminescence on dark worlds
@@ -398,7 +432,7 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
398
432
  let nl = max(dot(N, L), 0.0);
399
433
  let nh = max(dot(N, H), 0.0);
400
434
  let vh = max(dot(V, H), 0.0);
401
- let rough = clamp(mtl.mat.z * select(1.0,orm.g,mtl.maps.y>0.5), 0.045, 1.0);
435
+ let rough = effectiveRoughness(orm, i.l.y);
402
436
  let metal = clamp(mtl.mat.w * select(1.0,orm.b,mtl.maps.y>0.5), 0.0, 1.0);
403
437
  // Vertex/instance tints are display sRGB, while albedo textures use sRGB GPU
404
438
  // formats (and arrive decoded). Legacy props keep their historical path.
@@ -410,8 +444,11 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
410
444
  + pearlTint * mtl.paint.z * (0.035 + 0.13*pow(1.0-nv,2.0));
411
445
  let F = fresnel(f0, vh);
412
446
  let kd = (vec3(1.0)-F) * (1.0-metal);
413
- let diffuseCosine = mix(nl,max(-dot(N,L),0.0),mtl.optics.z);
414
- let direct = (kd * albedo * diffuseCosine / 3.14159265 + F * ggx(nh,nv,nl,rough) * nl) * u.sunCol.xyz * sh * 2.5;
447
+ var diffuseLight = albedo * nl;
448
+ if (mtl.optics.z > 0.0) {
449
+ diffuseLight = thinTissueDiffuse(albedo, nl, normalize(i.n), L, V, mtl.optics.z);
450
+ }
451
+ let direct = (kd * diffuseLight / 3.14159265 + F * ggx(nh,nv,nl,rough) * nl) * u.sunCol.xyz * sh * 2.5;
415
452
  let R = reflect(-V,N);
416
453
  let env = environment(R,rough) * mtl.coat.y;
417
454
  let reflected = env * fresnel(f0,nv) * (1.0-rough*0.6);
@@ -423,11 +460,11 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
423
460
  ambient=textureSampleLevel(sceneEnvTex,albedoSamp,equirectUV(N),u.look2.w).rgb*u.look.z;
424
461
  skyOcclusion=1.0;
425
462
  }
426
- let ao=select(1.0,orm.r,mtl.maps.y>0.5);
463
+ let ao=effectiveAO(orm);
427
464
  let diffuse = albedo * ambient * skyOcclusion * (1.0-metal)*ao;
428
465
  let coatF = fresnel(vec3(0.04),nv) * mtl.coat.x;
429
466
  var coating = environment(R,mtl.surface.z) * coatF * mtl.coat.y;
430
- if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0) {
467
+ if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0 && mtl.optics.x <= 0.0) {
431
468
  // A wet film reflects the directional key as well as the environment.
432
469
  // The key follows incident radiance and receiver shadows in world space.
433
470
  let amount = mtl.coat.x*mtl.optics.w*directCoat(N,nh,nv,nl,mtl.surface.z);
@@ -482,19 +519,31 @@ fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
482
519
  let f = clamp(1.0 - exp(-dist * u.fog.w), 0.0, 1.0);
483
520
  // mtl.mat.x is the model's opacity, 1 for every model that does not set it — the same constant
484
521
  // this returned before, so the opaque pipeline draws exactly what it always did.
485
- var opacity = mtl.mat.x;
522
+ var opacity = surfaceOpacity(N,i.world);
486
523
  // Thin glazing reflects more at grazing angles and transmits the rendered
487
524
  // scene at normal incidence. This does not approximate thick-glass refraction.
488
525
  if (mtl.optics.x > 0.0) {
489
526
  let V = normalize(u.cam.xyz-i.world);
490
- let nv = clamp(abs(dot(N,V)),0.0,1.0);
491
- let F = 0.04 + 0.96*pow(1.0-nv,5.0);
492
- opacity = clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
493
- let radiance = environment(reflect(-V,N),max(mtl.mat.z,0.045));
527
+ var radiance = environment(reflect(-V,N),max(mtl.mat.z,0.045));
528
+ if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0) {
529
+ let L = -normalize(u.sun.xyz);
530
+ let halfVector = L+V;
531
+ let H = halfVector*inverseSqrt(max(dot(halfVector,halfVector),0.00000001));
532
+ let nl = max(dot(N,L),0.0);
533
+ let nv = max(dot(N,V),0.001);
534
+ let spec = directCoat(N,max(dot(N,H),0.0),nv,nl,mtl.surface.z);
535
+ let keyReflection = u.sunCol.xyz*(sh*2.5*mtl.optics.w*mtl.coat.x*spec)
536
+ *fresnel(vec3(0.04),max(dot(V,H),0.0));
537
+ // Express the bright key lobe as coverage on an LDR blended target.
538
+ // Otherwise its peak clips before the small Fresnel alpha is applied.
539
+ let glint = 1.0-exp(-max(keyReflection.r,max(keyReflection.g,keyReflection.b))*u.look.y);
540
+ let combined = opacity+(1.0-opacity)*glint;
541
+ radiance = (radiance*opacity+keyReflection)/max(combined,0.04);
542
+ opacity = combined;
543
+ }
494
544
  lit = toneMap(radiance);
495
545
  }
496
546
  // A display-referred render texture (rear-view camera) is already lit.
497
- if (mtl.optics.y > 1.5) { return vec4(mix(tex.rgb * i.c, u.fog.xyz, f), mtl.mat.x); }
498
547
  if (mtl.optics.y > 0.5) { return vec4(tex.rgb, mtl.mat.x); }
499
548
  return vec4(mix(lit, u.fog.xyz, f), opacity);
500
549
  }`;
@@ -648,6 +697,9 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
648
697
  `;
649
698
  export class GpuPropsRenderer {
650
699
  device;
700
+ inspection;
701
+ srgbTarget;
702
+ inspectionGeometry;
651
703
  pipe;
652
704
  /**
653
705
  * The same pipeline with source-alpha blending and depth writes off, for models with `alpha < 1`.
@@ -805,7 +857,7 @@ export class GpuPropsRenderer {
805
857
  }
806
858
  constructor(device, format, options = {}) {
807
859
  this.device = device;
808
- const { sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', ...look } = options;
860
+ const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', ...look } = options;
809
861
  // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
810
862
  if (![1, 4].includes(sampleCount))
811
863
  throw new RangeError(`Unsupported prop sampleCount ${String(sampleCount)}`);
@@ -814,7 +866,9 @@ export class GpuPropsRenderer {
814
866
  this.sampleCount = sampleCount;
815
867
  this.depth = depth;
816
868
  this.setLook(look);
817
- const sm = device.createShaderModule({ code: SHADER });
869
+ this.inspection = inspection;
870
+ this.srgbTarget = format.endsWith('-srgb');
871
+ const sm = device.createShaderModule({ code: drawShader(inspection) });
818
872
  // The three groups the SHADER declares, written out so BOTH render pipelines share them. Under
819
873
  // `layout: 'auto'` each pipeline would mint its own and the bind groups built elsewhere in this
820
874
  // class could only ever be used by one of them.
@@ -1127,6 +1181,9 @@ export class GpuPropsRenderer {
1127
1181
  this.device.queue.writeBuffer(packed.matBuf, 0, packed.materialValues);
1128
1182
  }
1129
1183
  setModels(meshes) {
1184
+ this.inspectionGeometry?.destroy();
1185
+ if (this.inspection)
1186
+ this.inspectionGeometry = new PropInspectionGeometry(this.device, meshes);
1130
1187
  const dev = this.device, U = GPUBufferUsage;
1131
1188
  for (const p of this.models) {
1132
1189
  // Geometry is no longer per model — the shared arena is freed once, below, after the new one
@@ -1212,7 +1269,7 @@ export class GpuPropsRenderer {
1212
1269
  dev.queue.writeBuffer(buffer, offset, data);
1213
1270
  };
1214
1271
  let vCursor = 0, iCursor = 0;
1215
- this.models = meshes.map((m) => {
1272
+ this.models = meshes.map((m, modelIndex) => {
1216
1273
  const verts = m.positions.length / 3;
1217
1274
  const baseVertex = vCursor, firstIndex = iCursor;
1218
1275
  upload(this.geo.pos, baseVertex * 12, m.positions);
@@ -1235,7 +1292,7 @@ export class GpuPropsRenderer {
1235
1292
  const alpha = m.alpha ?? 1;
1236
1293
  const cutout = m.cutout ?? 0;
1237
1294
  const matBuf = dev.createBuffer({
1238
- size: 96,
1295
+ size: 112,
1239
1296
  usage: U.UNIFORM | U.COPY_DST,
1240
1297
  });
1241
1298
  const materialValues = new Float32Array([
@@ -1258,11 +1315,15 @@ export class GpuPropsRenderer {
1258
1315
  Math.max(0, Math.min(1, m.metalFlakes ?? 0)),
1259
1316
  Math.max(1, m.flakeScale ?? 320),
1260
1317
  Math.max(0, Math.min(1, m.pearlStrength ?? 0)),
1261
- 0,
1318
+ modelIndex,
1262
1319
  Math.max(0, Math.min(1, m.transmission ?? 0)),
1263
1320
  m.unlit ? 1 : m.glow ? 2 : 0,
1264
1321
  Math.max(0, Math.min(1, m.diffuseTransmission ?? 0)),
1265
1322
  Math.max(0, Math.min(1, m.directClearcoat ?? 0)),
1323
+ Math.max(0, Math.min(8, m.interiorOpticalDepth ?? 0)),
1324
+ Math.max(0, m.wetRindHeight ?? 0),
1325
+ 0,
1326
+ 0,
1266
1327
  ]);
1267
1328
  dev.queue.writeBuffer(matBuf, 0, materialValues);
1268
1329
  return {
@@ -1579,7 +1640,10 @@ export class GpuPropsRenderer {
1579
1640
  frame(enc, colorView, depthView, camVP, sunDir, sunCol, amb, camPos, fog, fogDensity, up,
1580
1641
  // Optional sun shadow-receive: pass the terrain's lightVP + shadow-map view + comparison sampler and props sit
1581
1642
  // in the same shadow. Omit all three (the demo path) → no shadowing, byte-identical to before.
1582
- lightVP, shadowView, shadowSamp) {
1643
+ lightVP, shadowView, shadowSamp, channel = 'lit') {
1644
+ if (channel !== 'lit' && !this.inspection)
1645
+ throw new Error('Prop inspection must be enabled at construction.');
1646
+ const topology = channel === 'wireframe' || channel === 'density';
1583
1647
  const receive = !!(lightVP && shadowView && shadowSamp);
1584
1648
  const mats = lightVP ? (Array.isArray(lightVP) ? lightVP : [lightVP]) : [];
1585
1649
  const u = new Float32Array(PROP_UNIFORM_WORDS);
@@ -1597,7 +1661,12 @@ export class GpuPropsRenderer {
1597
1661
  const w = this.world;
1598
1662
  u.set([w.windDir[0], w.windDir[1], w.windAmp, this.phase], 56);
1599
1663
  u.set([w.grainScale, w.grainDepth, w.roughness, w.emissive], 60);
1600
- u.set([w.hueShift, w.saturation, w.valueLift, 0], 64);
1664
+ u.set([
1665
+ w.hueShift,
1666
+ w.saturation,
1667
+ w.valueLift,
1668
+ this.inspection ? propInspectionChannels.indexOf(channel) : 0,
1669
+ ], 64);
1601
1670
  // csm.x = how many cascades are live; the matrices follow. Zero when not receiving, so the
1602
1671
  // selection loop exits at once and returns fully lit — the old no-shadow path exactly.
1603
1672
  u[68] = receive ? Math.min(MAX_CASCADES, mats.length) : 0;
@@ -1620,6 +1689,8 @@ export class GpuPropsRenderer {
1620
1689
  Math.max(0, Math.min(envMaxLod, look.environmentDiffuseLod ?? envMaxLod - 3)),
1621
1690
  ], lookAt);
1622
1691
  u.set(this.pointLightWords, lookAt + 8);
1692
+ if (this.inspection)
1693
+ u[lookAt + 9] = Number(this.srgbTarget);
1623
1694
  this.device.queue.writeBuffer(this.uBuf, 0, u);
1624
1695
  // group 1: the shadow map + comparison sampler (dummy when not receiving). Rebuild only when the view changes.
1625
1696
  const sv = shadowView ?? this.dummyShadowView, ss = shadowSamp ?? this.dummyShadowSamp;
@@ -1649,7 +1720,9 @@ export class GpuPropsRenderer {
1649
1720
  });
1650
1721
  rp.setBindGroup(1, this.shadowBG);
1651
1722
  // The arena, bound once for every model in both loops below.
1652
- if (this.geo) {
1723
+ if (topology)
1724
+ this.inspectionGeometry?.bind(rp);
1725
+ else if (this.geo) {
1653
1726
  rp.setVertexBuffer(0, this.geo.pos);
1654
1727
  rp.setVertexBuffer(1, this.geo.nrm);
1655
1728
  rp.setVertexBuffer(2, this.geo.col);
@@ -1663,7 +1736,10 @@ export class GpuPropsRenderer {
1663
1736
  rp.setBindGroup(0, bg);
1664
1737
  rp.setBindGroup(2, mdl.matBG);
1665
1738
  // Geometry is bound ONCE for the whole pass; a model is a range inside it.
1666
- rp.drawIndexed(mdl.idxCount, this.counts[m], mdl.firstIndex, mdl.baseVertex);
1739
+ if (topology)
1740
+ rp.draw(mdl.idxCount, this.counts[m], mdl.firstIndex);
1741
+ else
1742
+ rp.drawIndexed(mdl.idxCount, this.counts[m], mdl.firstIndex, mdl.baseVertex);
1667
1743
  };
1668
1744
  // OPAQUE FIRST, then the blended models — the whole point of the second pass. A translucent
1669
1745
  // crystal drawn before an opaque rock composites against whatever the sky left in the target and
@@ -1674,9 +1750,10 @@ export class GpuPropsRenderer {
1674
1750
  for (const blended of [false, true]) {
1675
1751
  for (let m = 0; m < this.models.length; m++) {
1676
1752
  const model = this.models[m];
1677
- if (model.alpha < 1 !== blended || this.counts[m] === 0)
1753
+ const clay = channel === 'clay';
1754
+ if ((model.alpha < 1 && !clay) !== blended || this.counts[m] === 0)
1678
1755
  continue;
1679
- const pipeline = this.drawPipeline(blended, model.cullMode, model.depthWrite);
1756
+ const pipeline = this.drawPipeline(blended, model.cullMode, clay || model.depthWrite);
1680
1757
  if (pipeline !== activePipeline) {
1681
1758
  rp.setPipeline(pipeline);
1682
1759
  activePipeline = pipeline;
@@ -0,0 +1,4 @@
1
+ /** Beer–Lambert escape through a thin non-emitting rind around a luminous
2
+ * chamber. At grazing incidence the tangent path is limited to eight times
3
+ * the normal thickness; real curved layers have a finite tangent chord. */
4
+ export declare const INTERIOR_LIGHT_WGSL = "\nfn buriedLightEscape(viewCosine: f32, opticalDepth: f32) -> f32 {\n return exp(-opticalDepth / max(abs(viewCosine), 0.125));\n}\n";
@@ -0,0 +1,8 @@
1
+ /** Beer–Lambert escape through a thin non-emitting rind around a luminous
2
+ * chamber. At grazing incidence the tangent path is limited to eight times
3
+ * the normal thickness; real curved layers have a finite tangent chord. */
4
+ export const INTERIOR_LIGHT_WGSL = /* wgsl */ `
5
+ fn buriedLightEscape(viewCosine: f32, opticalDepth: f32) -> f32 {
6
+ return exp(-opticalDepth / max(abs(viewCosine), 0.125));
7
+ }
8
+ `;
@@ -0,0 +1,15 @@
1
+ import type { PropMesh } from './gpuProps.js';
2
+ export declare const propInspectionChannels: readonly ["lit", "albedo", "normal", "roughness", "emissive", "ao", "clay", "wireframe", "density", "uv", "batch"];
3
+ export type PropInspectionChannel = (typeof propInspectionChannels)[number];
4
+ export declare const inspectionFragment = "\n if (u.grade.w > 0.5) {\n let channel = u32(u.grade.w);\n let opacity = surfaceOpacity(N,i.world);\n let albedo = select(base, srgbToLinear(i.c) * tex.rgb, mtl.mat.z >= 0.0);\n var display = vec3(0.0);\n switch channel {\n case 1u: { return vec4(select(albedo, tex.rgb, mtl.optics.y == 1.0),opacity); }\n case 2u: {\n let backTissue = mtl.optics.z>0.0 && dot(i.n,u.cam.xyz-i.world)<0.0;\n display=select(N,-N,backTissue)*0.5+0.5;\n }\n case 3u: { display=vec3(select(1.0,effectiveRoughness(orm, i.l.y),mtl.mat.z>=0.0)); }\n case 4u: {\n var emission = select(vec3(0.0), base*u.surf.w, mtl.mat.z<0.0);\n if (mtl.optics.y > 1.5) { emission = propEmission(tex.rgb,i.c,normalize(i.n),i.world); }\n return vec4(emission,opacity);\n }\n case 5u: { display=vec3(select(1.0,effectiveAO(orm),mtl.mat.z>=0.0)); }\n case 6u: {\n // White diffuse clay shows the smooth geometry normals alone.\n let geoN = normalize(i.n);\n let nl = max(0.0,dot(geoN,-normalize(u.sun.xyz)));\n var ambient = u.amb.xyz * (0.6+0.4*max(geoN.y,0.0));\n if (u.look.z>0.0) { ambient=textureSampleLevel(sceneEnvTex,albedoSamp,equirectUV(geoN),u.look2.w).rgb*u.look.z; }\n return vec4(toneMap(vec3(0.76)*(ambient+u.sunCol.xyz*nl*sh*2.5/3.14159265)),1.0);\n }\n case 7u: {\n let dx=dpdx(i.bary); let dy=dpdy(i.bary);\n let dist=i.bary / max(sqrt(dx*dx+dy*dy),vec3(1e-6));\n let edge=1.0-smoothstep(0.0,1.15,min(dist.x,min(dist.y,dist.z)));\n display=mix(vec3(0.12,0.15,0.18),vec3(0.87,0.96,1.0),edge);\n }\n case 8u: {\n // The determinant maps one screen pixel to a fraction of the unit barycentric triangle (area 0.5).\n // A <=1 px\u00B2 triangle is hot, >=256 px\u00B2 cool. Area follows the actual posed projection.\n let dx=dpdx(i.bary.xy); let dy=dpdy(i.bary.xy);\n let area=0.5/max(abs(dx.x*dy.y-dx.y*dy.x),1e-10);\n let t=clamp(log2(max(area,1.0))/8.0,0.0,1.0);\n display=mix(mix(vec3(1.0,0.22,0.12),vec3(1.0,0.88,0.23),clamp(t*2.0,0.0,1.0)),\n vec3(0.12,0.36,0.87),clamp(t*2.0-1.0,0.0,1.0));\n }\n case 9u: {\n let uv=i.uv * mtl.surface.w;\n let q=uv*8.0;\n let w=clamp(fwidth(q),vec2(0.001),vec2(1.0));\n let band=clamp((abs(fract(q*0.5+0.25)-0.5)*4.0-1.0)/w,vec2(-1.0),vec2(1.0));\n let checker = 0.5+0.5*band.x*band.y;\n display=mix(vec3(0.14,0.18,0.24),vec3(0.77,0.85,0.92),checker);\n }\n default: {\n display = vec3(0.55)+0.37*cos(6.2831853*(mtl.paint.w*0.618034+vec3(0.0,0.34,0.66)));\n }\n }\n return vec4(select(display,srgbToLinear(display),u.pointMeta.y>0.5),opacity);\n }\n";
5
+ export declare class PropInspectionGeometry {
6
+ private readonly device;
7
+ private readonly meshes;
8
+ private streams;
9
+ constructor(device: GPUDevice, meshes: readonly PropMesh[]);
10
+ /** Only topology views need unshared triangle corners. Other channels keep
11
+ * using the indexed production geometry. vertex_index % 3 gives a corner
12
+ * once indexed vertex streams have been expanded in original draw order. */
13
+ bind(pass: GPURenderPassEncoder): void;
14
+ destroy(): void;
15
+ }
@@ -0,0 +1,119 @@
1
+ export const propInspectionChannels = [
2
+ 'lit',
3
+ 'albedo',
4
+ 'normal',
5
+ 'roughness',
6
+ 'emissive',
7
+ 'ao',
8
+ 'clay',
9
+ 'wireframe',
10
+ 'density',
11
+ 'uv',
12
+ 'batch',
13
+ ];
14
+ // Shared by the diagnostic-only version of the production prop shader. The
15
+ // regular renderer compiles no additional varyings, derivatives or branches.
16
+ export const inspectionFragment = /* wgsl */ `
17
+ if (u.grade.w > 0.5) {
18
+ let channel = u32(u.grade.w);
19
+ let opacity = surfaceOpacity(N,i.world);
20
+ let albedo = select(base, srgbToLinear(i.c) * tex.rgb, mtl.mat.z >= 0.0);
21
+ var display = vec3(0.0);
22
+ switch channel {
23
+ case 1u: { return vec4(select(albedo, tex.rgb, mtl.optics.y == 1.0),opacity); }
24
+ case 2u: {
25
+ let backTissue = mtl.optics.z>0.0 && dot(i.n,u.cam.xyz-i.world)<0.0;
26
+ display=select(N,-N,backTissue)*0.5+0.5;
27
+ }
28
+ case 3u: { display=vec3(select(1.0,effectiveRoughness(orm, i.l.y),mtl.mat.z>=0.0)); }
29
+ case 4u: {
30
+ var emission = select(vec3(0.0), base*u.surf.w, mtl.mat.z<0.0);
31
+ if (mtl.optics.y > 1.5) { emission = propEmission(tex.rgb,i.c,normalize(i.n),i.world); }
32
+ return vec4(emission,opacity);
33
+ }
34
+ case 5u: { display=vec3(select(1.0,effectiveAO(orm),mtl.mat.z>=0.0)); }
35
+ case 6u: {
36
+ // White diffuse clay shows the smooth geometry normals alone.
37
+ let geoN = normalize(i.n);
38
+ let nl = max(0.0,dot(geoN,-normalize(u.sun.xyz)));
39
+ var ambient = u.amb.xyz * (0.6+0.4*max(geoN.y,0.0));
40
+ if (u.look.z>0.0) { ambient=textureSampleLevel(sceneEnvTex,albedoSamp,equirectUV(geoN),u.look2.w).rgb*u.look.z; }
41
+ return vec4(toneMap(vec3(0.76)*(ambient+u.sunCol.xyz*nl*sh*2.5/3.14159265)),1.0);
42
+ }
43
+ case 7u: {
44
+ let dx=dpdx(i.bary); let dy=dpdy(i.bary);
45
+ let dist=i.bary / max(sqrt(dx*dx+dy*dy),vec3(1e-6));
46
+ let edge=1.0-smoothstep(0.0,1.15,min(dist.x,min(dist.y,dist.z)));
47
+ display=mix(vec3(0.12,0.15,0.18),vec3(0.87,0.96,1.0),edge);
48
+ }
49
+ case 8u: {
50
+ // The determinant maps one screen pixel to a fraction of the unit barycentric triangle (area 0.5).
51
+ // A <=1 px² triangle is hot, >=256 px² cool. Area follows the actual posed projection.
52
+ let dx=dpdx(i.bary.xy); let dy=dpdy(i.bary.xy);
53
+ let area=0.5/max(abs(dx.x*dy.y-dx.y*dy.x),1e-10);
54
+ let t=clamp(log2(max(area,1.0))/8.0,0.0,1.0);
55
+ display=mix(mix(vec3(1.0,0.22,0.12),vec3(1.0,0.88,0.23),clamp(t*2.0,0.0,1.0)),
56
+ vec3(0.12,0.36,0.87),clamp(t*2.0-1.0,0.0,1.0));
57
+ }
58
+ case 9u: {
59
+ let uv=i.uv * mtl.surface.w;
60
+ let q=uv*8.0;
61
+ let w=clamp(fwidth(q),vec2(0.001),vec2(1.0));
62
+ let band=clamp((abs(fract(q*0.5+0.25)-0.5)*4.0-1.0)/w,vec2(-1.0),vec2(1.0));
63
+ let checker = 0.5+0.5*band.x*band.y;
64
+ display=mix(vec3(0.14,0.18,0.24),vec3(0.77,0.85,0.92),checker);
65
+ }
66
+ default: {
67
+ display = vec3(0.55)+0.37*cos(6.2831853*(mtl.paint.w*0.618034+vec3(0.0,0.34,0.66)));
68
+ }
69
+ }
70
+ return vec4(select(display,srgbToLinear(display),u.pointMeta.y>0.5),opacity);
71
+ }
72
+ `;
73
+ export class PropInspectionGeometry {
74
+ device;
75
+ meshes;
76
+ streams = [];
77
+ constructor(device, meshes) {
78
+ this.device = device;
79
+ this.meshes = meshes;
80
+ }
81
+ /** Only topology views need unshared triangle corners. Other channels keep
82
+ * using the indexed production geometry. vertex_index % 3 gives a corner
83
+ * once indexed vertex streams have been expanded in original draw order. */
84
+ bind(pass) {
85
+ if (!this.streams.length) {
86
+ const count = this.meshes.reduce((n, mesh) => n + mesh.indices.length, 0);
87
+ for (const [key, size] of [
88
+ ['positions', 3],
89
+ ['normals', 3],
90
+ ['colors', 3],
91
+ ['uvs', 2],
92
+ ]) {
93
+ const values = new Float32Array(count * size);
94
+ let at = 0;
95
+ for (const mesh of this.meshes) {
96
+ const source = mesh[key];
97
+ for (const index of mesh.indices) {
98
+ for (let c = 0; c < size; c++)
99
+ values[at++] = source?.[index * size + c] ?? 0;
100
+ }
101
+ }
102
+ const buffer = this.device.createBuffer({
103
+ size: Math.max(4, values.byteLength),
104
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
105
+ });
106
+ if (values.length)
107
+ this.device.queue.writeBuffer(buffer, 0, values);
108
+ this.streams.push(buffer);
109
+ }
110
+ }
111
+ for (const [slot, buffer] of this.streams.entries())
112
+ pass.setVertexBuffer(slot, buffer);
113
+ }
114
+ destroy() {
115
+ for (const buffer of this.streams)
116
+ buffer.destroy();
117
+ this.streams = [];
118
+ }
119
+ }
@@ -0,0 +1,4 @@
1
+ /** Single-scattering approximation for a pigmented sheet. Input pigment and
2
+ * output are linear RGB; the caller supplies light colour, visibility and its
3
+ * BRDF normalisation. This term has no energy source in darkness. */
4
+ export declare const THIN_TISSUE_WGSL = "\nfn thinTissueDiffuse(pigment: vec3<f32>, detailCosine: f32, geometricNormal: vec3<f32>,\n lightDir: vec3<f32>, viewDir: vec3<f32>, amount: f32) -> vec3<f32> {\n let N = faceForward(geometricNormal, -viewDir, geometricNormal);\n let back = max(-dot(N, lightDir), 0.0);\n let reflected = pigment * detailCosine * (1.0 - amount);\n // The incident and exit paths through tissue grow at grazing incidence.\n // A bounded rational attenuation preserves the pigment's absorption hue\n // while avoiding a thickness texture or high-frequency normal-map shimmer.\n let exitCos = abs(dot(N, viewDir));\n let excessPath = (1.0 - back) / (0.35 + back) + 0.5 * (1.0 - exitCos) / (0.35 + exitCos);\n let dye = clamp(pigment, vec3<f32>(0.0), vec3<f32>(1.0));\n let peak = max(max(dye.r, dye.g), dye.b);\n let transmitted = dye * inverseSqrt(max(peak, 0.12)) / (1.0 + (1.0 - dye) * (0.25 + excessPath));\n // A broad forward lobe makes a lamp seen through a membrane read\n // differently from a lamp reflected off it.\n let forward = max(-dot(lightDir, viewDir), 0.0);\n let phase = 0.68 + 1.16 * forward * forward;\n return reflected + transmitted * (amount * back * phase);\n}";
@@ -0,0 +1,23 @@
1
+ /** Single-scattering approximation for a pigmented sheet. Input pigment and
2
+ * output are linear RGB; the caller supplies light colour, visibility and its
3
+ * BRDF normalisation. This term has no energy source in darkness. */
4
+ export const THIN_TISSUE_WGSL = /* wgsl */ `
5
+ fn thinTissueDiffuse(pigment: vec3<f32>, detailCosine: f32, geometricNormal: vec3<f32>,
6
+ lightDir: vec3<f32>, viewDir: vec3<f32>, amount: f32) -> vec3<f32> {
7
+ let N = faceForward(geometricNormal, -viewDir, geometricNormal);
8
+ let back = max(-dot(N, lightDir), 0.0);
9
+ let reflected = pigment * detailCosine * (1.0 - amount);
10
+ // The incident and exit paths through tissue grow at grazing incidence.
11
+ // A bounded rational attenuation preserves the pigment's absorption hue
12
+ // while avoiding a thickness texture or high-frequency normal-map shimmer.
13
+ let exitCos = abs(dot(N, viewDir));
14
+ let excessPath = (1.0 - back) / (0.35 + back) + 0.5 * (1.0 - exitCos) / (0.35 + exitCos);
15
+ let dye = clamp(pigment, vec3<f32>(0.0), vec3<f32>(1.0));
16
+ let peak = max(max(dye.r, dye.g), dye.b);
17
+ let transmitted = dye * inverseSqrt(max(peak, 0.12)) / (1.0 + (1.0 - dye) * (0.25 + excessPath));
18
+ // A broad forward lobe makes a lamp seen through a membrane read
19
+ // differently from a lamp reflected off it.
20
+ let forward = max(-dot(lightDir, viewDir), 0.0);
21
+ let phase = 0.68 + 1.16 * forward * forward;
22
+ return reflected + transmitted * (amount * back * phase);
23
+ }`;
@@ -0,0 +1,4 @@
1
+ /** Capillary contact near the base of grounded material. The incoming dry
2
+ * roughness varies the width of the wet front and leaves grains visible
3
+ * through the film. Caller supplies local height above the support plane. */
4
+ export declare const WET_RIND_WGSL = "\nfn wetRindCoverage(localY: f32, rindHeight: f32, dryRoughness: f32) -> f32 {\n return 1.0 - smoothstep(0.68 + 0.32 * dryRoughness, 1.14 + 0.32 * dryRoughness, localY / max(rindHeight, 0.00001));\n}\nfn wetRindRoughness(dry: f32, coverage: f32) -> f32 {\n return mix(dry, min(dry, 0.14 + dry * 0.16), coverage);\n}\n";
@@ -0,0 +1,11 @@
1
+ /** Capillary contact near the base of grounded material. The incoming dry
2
+ * roughness varies the width of the wet front and leaves grains visible
3
+ * through the film. Caller supplies local height above the support plane. */
4
+ export const WET_RIND_WGSL = /* wgsl */ `
5
+ fn wetRindCoverage(localY: f32, rindHeight: f32, dryRoughness: f32) -> f32 {
6
+ return 1.0 - smoothstep(0.68 + 0.32 * dryRoughness, 1.14 + 0.32 * dryRoughness, localY / max(rindHeight, 0.00001));
7
+ }
8
+ fn wetRindRoughness(dry: f32, coverage: f32) -> f32 {
9
+ return mix(dry, min(dry, 0.14 + dry * 0.16), coverage);
10
+ }
11
+ `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.73",
3
+ "version": "0.15.75",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {