ugly-game 0.15.74 → 0.15.76

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,7 +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';
3
5
  import { type PropInspectionChannel } from './propInspection.js';
4
6
  export type { PropInspectionChannel } from './propInspection.js';
7
+ export { THIN_TISSUE_WGSL } from './thinTissue.js';
5
8
  export declare const MAX_CASCADES = 4;
6
9
  export declare const MAX_PROP_POINT_LIGHTS = 8;
7
10
  /** Caller-selected local lights, in the same rebased coordinates as frame().
@@ -93,6 +96,13 @@ export interface PropLook {
93
96
  }
94
97
  /** Constructor options. All optional; omitting them is the historical renderer. */
95
98
  export interface PropRendererOptions extends Partial<PropLook> {
99
+ /** Optional second colour attachment for translucent props layered after a
100
+ * compositor. The caller supplies WGSL defining encodePropPresentation(rgb:
101
+ * vec3<f32>) -> vec3<f32>. Use linear tone mapping for a scene-linear input. */
102
+ presentation?: {
103
+ format: GPUTextureFormat;
104
+ transferWGSL: string;
105
+ };
96
106
  /** Compile material/topology inspection channels. Off by default. On the
97
107
  * first topology view, an expanded corner stream is built for wire/density. */
98
108
  inspection?: boolean;
@@ -139,6 +149,12 @@ export interface PropMesh {
139
149
  * with distance. Unlike `unlit`, vertex colours count.
140
150
  */
141
151
  glow?: boolean;
152
+ /** Normal-incidence optical depth of the clear or tissue rind over a luminous
153
+ * source. On glow materials a positive value attenuates its linear radiance
154
+ * by the viewing path length. Zero keeps the display-referred glow path. */
155
+ interiorOpticalDepth?: number;
156
+ /** Local height of the wet contact zone above model y=0. Omitted for dry material. */
157
+ wetRindHeight?: number;
142
158
  /** Caller-owned linear occlusion/roughness/metalness map (RGB). */
143
159
  ormMap?: GPUTexture;
144
160
  normalScale?: number;
@@ -282,6 +298,10 @@ export interface PropDeform {
282
298
  tint?: readonly [number, number, number];
283
299
  }
284
300
  export interface PropInstance {
301
+ /** Draw after the compositor, or split at a plane in the same rebased world
302
+ * coordinates as mat. Positive distances go to presentation, negative to
303
+ * the original scene. The default remains wholly in the original scene. */
304
+ presentation?: true | readonly [number, number, number, number];
285
305
  model: number;
286
306
  mat: Float32Array;
287
307
  /** Optional per-instance deform. Omitted ⇒ the mesh is drawn exactly as authored. */
@@ -291,6 +311,10 @@ export declare class GpuPropsRenderer {
291
311
  private device;
292
312
  private inspection;
293
313
  private srgbTarget;
314
+ private presentation?;
315
+ private sceneCounts;
316
+ private presentationFirst;
317
+ private hasPresentation;
294
318
  private inspectionGeometry?;
295
319
  private pipe;
296
320
  /**
@@ -464,4 +488,8 @@ export declare class GpuPropsRenderer {
464
488
  */
465
489
  shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
466
490
  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;
491
+ /** Draw over the presented compositor result, testing its final depth.
492
+ * Reuses the same uploaded instances, material bindings and frame uniforms. */
493
+ framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView): void;
494
+ private encodeColor;
467
495
  }
@@ -6,14 +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';
11
15
  import { inspectionFragment, propInspectionChannels, PropInspectionGeometry, } from './propInspection.js';
16
+ import { THIN_TISSUE_WGSL } from './thinTissue.js';
17
+ export { THIN_TISSUE_WGSL } from './thinTissue.js';
12
18
  export const MAX_CASCADES = 4; // must match gpuShadow's
13
19
  export const MAX_PROP_POINT_LIGHTS = 8;
14
20
  const POINT_LIGHT_WORDS = 4 + MAX_PROP_POINT_LIGHTS * 16;
15
21
  const PROP_UNIFORM_WORDS = 72 + 16 * MAX_CASCADES + 8 + POINT_LIGHT_WORDS;
16
- const drawShader = (inspect) => /* wgsl */ `
22
+ const drawShader = (inspect, split, transfer = '') => /* wgsl */ `
17
23
  // wind = (dirX, dirZ, amplitude, phase) — sway, amplitude scaled by the world's air density
18
24
  // surf = (grainScale, grainDepth, roughness, emissive)
19
25
  // grade = (hueShift, saturation, valueLift, unused)
@@ -46,7 +52,7 @@ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: v
46
52
  // alpha-test cutoff (0 ⇒ no test, which is every model that predates it).
47
53
  // mat = opacity, cutoff, roughness (-1 = legacy), metalness.
48
54
  // coat = clearcoat, reflection strength, unused, unused.
49
- 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> };
50
56
  @group(2) @binding(2) var<uniform> mtl: Mat;
51
57
  @group(2) @binding(3) var environmentTex: texture_2d<f32>;
52
58
  @group(2) @binding(4) var normalTex: texture_2d<f32>;
@@ -56,7 +62,7 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
56
62
  // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
57
63
  // sampled: look.z and look.w are forced to 0 on the CPU without it.
58
64
  @group(1) @binding(2) var sceneEnvTex: texture_2d<f32>;
59
- 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>' : ''} };
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> ${split ? ', @location(6) clipDistance: f32' : ''} ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<f32>' : ''} };
60
66
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
61
67
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
62
68
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -128,6 +134,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
128
134
  let sc = length(m[0].xyz);
129
135
  world = sway(lp, world, upv, sc * inst.d2.w);
130
136
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
137
+ ${split ? 'o.clipDistance = dot(world,vec3(m[0].w,m[1].w,m[2].w))+inst.d3.w;' : ''}
131
138
  o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
132
139
  ${inspect ? 'o.bary = vec3<f32>(f32(vi%3u==0u),f32(vi%3u==1u),f32(vi%3u==2u));' : ''}
133
140
  return o;
@@ -351,8 +358,17 @@ fn srgbToLinear(c: vec3<f32>) -> vec3<f32> {
351
358
  fn linearToSrgb(c: vec3<f32>) -> vec3<f32> {
352
359
  return select(c * 12.92, 1.055 * pow(max(c, vec3(0.0)), vec3(1.0/2.4)) - 0.055, c > vec3(0.0031308));
353
360
  }
354
- fn effectiveRoughness(orm:vec3<f32>) -> f32 {
355
- return clamp(mtl.mat.z * select(1.0,orm.g,mtl.maps.y>0.5), 0.045, 1.0);
361
+ ${INTERIOR_LIGHT_WGSL}
362
+ fn propEmission(tex: vec3<f32>, pigment: vec3<f32>, normal: vec3<f32>, world: vec3<f32>) -> vec3<f32> {
363
+ if (mtl.medium.x <= 0.0) { return tex*pigment; }
364
+ let view = normalize(u.cam.xyz-world);
365
+ return tex*srgbToLinear(max(pigment,vec3(0.0)))*buriedLightEscape(dot(normal,view),mtl.medium.x);
366
+ }
367
+ ${WET_RIND_WGSL}
368
+ fn effectiveRoughness(orm:vec3<f32>, localY:f32) -> f32 {
369
+ let dry = clamp(mtl.mat.z * select(1.0,orm.g,mtl.maps.y>0.5), 0.045, 1.0);
370
+ if (mtl.medium.y > 0.0) { return wetRindRoughness(dry,wetRindCoverage(localY,mtl.medium.y,dry)); }
371
+ return dry;
356
372
  }
357
373
  fn effectiveAO(orm:vec3<f32>) -> f32 { return select(1.0,orm.r,mtl.maps.y>0.5); }
358
374
  fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
@@ -361,7 +377,10 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
361
377
  let F = 0.04 + 0.96*pow(1.0-nv,5.0);
362
378
  return clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
363
379
  }
364
- @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
380
+ ${THIN_TISSUE_WGSL}
381
+ ${transfer}
382
+ fn shade(i: VO) -> vec4<f32> {
383
+ ${split ? (transfer ? 'if (i.clipDistance < 0.0) { discard; }' : 'if (i.clipDistance >= 0.0) { discard; }') : ''}
365
384
  var N = normalize(i.n);
366
385
  let materialUV=i.uv*mtl.maps.w;
367
386
  let px=dpdx(i.world); let py=dpdy(i.world);
@@ -398,6 +417,10 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
398
417
  }
399
418
  base = hsvShift(base, u.grade.x, max(u.grade.y, 0.0), max(u.grade.z, 0.0));
400
419
  ${inspect ? inspectionFragment : ''}
420
+ if (mtl.optics.y > 1.5) {
421
+ let fog = clamp(1.0-exp(-length(i.world-u.cam.xyz)*u.fog.w),0.0,1.0);
422
+ return vec4(mix(propEmission(tex.rgb,i.c,normalize(i.n),i.world),u.fog.xyz,fog),mtl.mat.x);
423
+ }
401
424
  let spec = u.surf.z;
402
425
  var lit = base * (u.amb.xyz * ff + d * u.sunCol.xyz * sh * (1.0 + spec * 0.6))
403
426
  + base * u.surf.w; // emissive — bioluminescence on dark worlds
@@ -412,7 +435,7 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
412
435
  let nl = max(dot(N, L), 0.0);
413
436
  let nh = max(dot(N, H), 0.0);
414
437
  let vh = max(dot(V, H), 0.0);
415
- let rough = effectiveRoughness(orm);
438
+ let rough = effectiveRoughness(orm, i.l.y);
416
439
  let metal = clamp(mtl.mat.w * select(1.0,orm.b,mtl.maps.y>0.5), 0.0, 1.0);
417
440
  // Vertex/instance tints are display sRGB, while albedo textures use sRGB GPU
418
441
  // formats (and arrive decoded). Legacy props keep their historical path.
@@ -424,8 +447,11 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
424
447
  + pearlTint * mtl.paint.z * (0.035 + 0.13*pow(1.0-nv,2.0));
425
448
  let F = fresnel(f0, vh);
426
449
  let kd = (vec3(1.0)-F) * (1.0-metal);
427
- let diffuseCosine = mix(nl,max(-dot(N,L),0.0),mtl.optics.z);
428
- let direct = (kd * albedo * diffuseCosine / 3.14159265 + F * ggx(nh,nv,nl,rough) * nl) * u.sunCol.xyz * sh * 2.5;
450
+ var diffuseLight = albedo * nl;
451
+ if (mtl.optics.z > 0.0) {
452
+ diffuseLight = thinTissueDiffuse(albedo, nl, normalize(i.n), L, V, mtl.optics.z);
453
+ }
454
+ let direct = (kd * diffuseLight / 3.14159265 + F * ggx(nh,nv,nl,rough) * nl) * u.sunCol.xyz * sh * 2.5;
429
455
  let R = reflect(-V,N);
430
456
  let env = environment(R,rough) * mtl.coat.y;
431
457
  let reflected = env * fresnel(f0,nv) * (1.0-rough*0.6);
@@ -441,7 +467,7 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
441
467
  let diffuse = albedo * ambient * skyOcclusion * (1.0-metal)*ao;
442
468
  let coatF = fresnel(vec3(0.04),nv) * mtl.coat.x;
443
469
  var coating = environment(R,mtl.surface.z) * coatF * mtl.coat.y;
444
- if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0) {
470
+ if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0 && mtl.optics.x <= 0.0) {
445
471
  // A wet film reflects the directional key as well as the environment.
446
472
  // The key follows incident radiance and receiver shadows in world space.
447
473
  let amount = mtl.coat.x*mtl.optics.w*directCoat(N,nh,nv,nl,mtl.surface.z);
@@ -496,18 +522,37 @@ fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
496
522
  let f = clamp(1.0 - exp(-dist * u.fog.w), 0.0, 1.0);
497
523
  // mtl.mat.x is the model's opacity, 1 for every model that does not set it — the same constant
498
524
  // this returned before, so the opaque pipeline draws exactly what it always did.
499
- let opacity = surfaceOpacity(N,i.world);
525
+ var opacity = surfaceOpacity(N,i.world);
500
526
  // Thin glazing reflects more at grazing angles and transmits the rendered
501
527
  // scene at normal incidence. This does not approximate thick-glass refraction.
502
528
  if (mtl.optics.x > 0.0) {
503
529
  let V = normalize(u.cam.xyz-i.world);
504
- let radiance = environment(reflect(-V,N),max(mtl.mat.z,0.045));
530
+ var radiance = environment(reflect(-V,N),max(mtl.mat.z,0.045));
531
+ if (mtl.optics.w > 0.0 && mtl.coat.x > 0.0) {
532
+ let L = -normalize(u.sun.xyz);
533
+ let halfVector = L+V;
534
+ let H = halfVector*inverseSqrt(max(dot(halfVector,halfVector),0.00000001));
535
+ let nl = max(dot(N,L),0.0);
536
+ let nv = max(dot(N,V),0.001);
537
+ let spec = directCoat(N,max(dot(N,H),0.0),nv,nl,mtl.surface.z);
538
+ let keyReflection = u.sunCol.xyz*(sh*2.5*mtl.optics.w*mtl.coat.x*spec)
539
+ *fresnel(vec3(0.04),max(dot(V,H),0.0));
540
+ // Express the bright key lobe as coverage on an LDR blended target.
541
+ // Otherwise its peak clips before the small Fresnel alpha is applied.
542
+ let glint = 1.0-exp(-max(keyReflection.r,max(keyReflection.g,keyReflection.b))*u.look.y);
543
+ let combined = opacity+(1.0-opacity)*glint;
544
+ radiance = (radiance*opacity+keyReflection)/max(combined,0.04);
545
+ opacity = combined;
546
+ }
505
547
  lit = toneMap(radiance);
506
548
  }
507
549
  // A display-referred render texture (rear-view camera) is already lit.
508
- if (mtl.optics.y > 1.5) { return vec4(mix(tex.rgb * i.c, u.fog.xyz, f), mtl.mat.x); }
509
550
  if (mtl.optics.y > 0.5) { return vec4(tex.rgb, mtl.mat.x); }
510
551
  return vec4(mix(lit, u.fog.xyz, f), opacity);
552
+ }
553
+ @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
554
+ let color = shade(i);
555
+ return ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
511
556
  }`;
512
557
  // Depth-only occluder pass: instanced prop depth from the sun's ortho view (so trees/rocks cast shadows).
513
558
  // Depth-only occluder. It MUST apply the identical sway, or the shadows stay put while the leaves
@@ -661,6 +706,10 @@ export class GpuPropsRenderer {
661
706
  device;
662
707
  inspection;
663
708
  srgbTarget;
709
+ presentation;
710
+ sceneCounts = new Uint32Array(0);
711
+ presentationFirst = new Uint32Array(0);
712
+ hasPresentation = false;
664
713
  inspectionGeometry;
665
714
  pipe;
666
715
  /**
@@ -819,7 +868,7 @@ export class GpuPropsRenderer {
819
868
  }
820
869
  constructor(device, format, options = {}) {
821
870
  this.device = device;
822
- const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', ...look } = options;
871
+ const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', presentation, ...look } = options;
823
872
  // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
824
873
  if (![1, 4].includes(sampleCount))
825
874
  throw new RangeError(`Unsupported prop sampleCount ${String(sampleCount)}`);
@@ -827,10 +876,13 @@ export class GpuPropsRenderer {
827
876
  throw new RangeError(`Unsupported prop shadowDepthFormat ${shadowDepthFormat}`);
828
877
  this.sampleCount = sampleCount;
829
878
  this.depth = depth;
879
+ this.presentation = presentation;
830
880
  this.setLook(look);
831
881
  this.inspection = inspection;
832
882
  this.srgbTarget = format.endsWith('-srgb');
833
- const sm = device.createShaderModule({ code: drawShader(inspection) });
883
+ const sm = device.createShaderModule({
884
+ code: drawShader(inspection, !!presentation),
885
+ });
834
886
  // The three groups the SHADER declares, written out so BOTH render pipelines share them. Under
835
887
  // `layout: 'auto'` each pipeline would mint its own and the bind groups built elsewhere in this
836
888
  // class could only ever be used by one of them.
@@ -971,13 +1023,39 @@ export class GpuPropsRenderer {
971
1023
  ['false:none:true', this.pipe],
972
1024
  ['true:none:true', this.blendPipe],
973
1025
  ]);
974
- this.drawPipeline = (blend, cull, depthWrite) => {
975
- const key = `${blend}:${cull}:${depthWrite}`;
1026
+ let presentationModule;
1027
+ this.drawPipeline = (blend, cull, depthWrite, late = false) => {
1028
+ const key = `${blend}:${cull}:${depthWrite}${late ? ':presentation' : ''}`;
976
1029
  let pipeline = variants.get(key);
977
1030
  if (!pipeline) {
978
1031
  const base = blend ? blendDescriptor : opaqueDescriptor;
979
1032
  pipeline = device.createRenderPipeline({
980
1033
  ...base,
1034
+ ...(late && presentation
1035
+ ? {
1036
+ fragment: {
1037
+ ...base.fragment,
1038
+ module: (presentationModule ??= device.createShaderModule({
1039
+ code: drawShader(inspection, true, presentation.transferWGSL),
1040
+ })),
1041
+ targets: [
1042
+ {
1043
+ format: presentation.format,
1044
+ blend: {
1045
+ color: {
1046
+ srcFactor: 'src-alpha',
1047
+ dstFactor: 'one-minus-src-alpha',
1048
+ },
1049
+ alpha: {
1050
+ srcFactor: 'one',
1051
+ dstFactor: 'one-minus-src-alpha',
1052
+ },
1053
+ },
1054
+ },
1055
+ ],
1056
+ },
1057
+ }
1058
+ : {}),
981
1059
  primitive: { ...base.primitive, cullMode: cull },
982
1060
  depthStencil: {
983
1061
  ...base.depthStencil,
@@ -1254,7 +1332,7 @@ export class GpuPropsRenderer {
1254
1332
  const alpha = m.alpha ?? 1;
1255
1333
  const cutout = m.cutout ?? 0;
1256
1334
  const matBuf = dev.createBuffer({
1257
- size: 96,
1335
+ size: 112,
1258
1336
  usage: U.UNIFORM | U.COPY_DST,
1259
1337
  });
1260
1338
  const materialValues = new Float32Array([
@@ -1282,6 +1360,10 @@ export class GpuPropsRenderer {
1282
1360
  m.unlit ? 1 : m.glow ? 2 : 0,
1283
1361
  Math.max(0, Math.min(1, m.diffuseTransmission ?? 0)),
1284
1362
  Math.max(0, Math.min(1, m.directClearcoat ?? 0)),
1363
+ Math.max(0, Math.min(8, m.interiorOpticalDepth ?? 0)),
1364
+ Math.max(0, m.wetRindHeight ?? 0),
1365
+ 0,
1366
+ 0,
1285
1367
  ]);
1286
1368
  dev.queue.writeBuffer(matBuf, 0, materialValues);
1287
1369
  return {
@@ -1318,6 +1400,7 @@ export class GpuPropsRenderer {
1318
1400
  this.bgs = meshes.map(() => null);
1319
1401
  this.occBGs = meshes.map(() => []);
1320
1402
  this.counts = meshes.map(() => 0);
1403
+ this.hasPresentation = false;
1321
1404
  this.cullU = meshes.map(() => []);
1322
1405
  this.cullArgs = meshes.map(() => []);
1323
1406
  this.cullBGs = meshes.map(() => []);
@@ -1337,10 +1420,31 @@ export class GpuPropsRenderer {
1337
1420
  const dev = this.device;
1338
1421
  const n = this.models.length;
1339
1422
  const counts = new Uint32Array(n);
1340
- for (const it of instances)
1341
- if (it.model >= 0 && it.model < n)
1342
- counts[it.model]++;
1423
+ this.hasPresentation = false;
1424
+ const split = !!this.presentation;
1425
+ if (this.presentation) {
1426
+ this.sceneCounts = new Uint32Array(n);
1427
+ this.presentationFirst = new Uint32Array(n);
1428
+ }
1429
+ for (const it of instances) {
1430
+ if (it.model < 0 || it.model >= n)
1431
+ continue;
1432
+ counts[it.model]++;
1433
+ if (!split)
1434
+ continue;
1435
+ if (!it.presentation)
1436
+ this.presentationFirst[it.model]++;
1437
+ else {
1438
+ this.hasPresentation = true;
1439
+ }
1440
+ if (it.presentation !== true)
1441
+ this.sceneCounts[it.model]++;
1442
+ }
1443
+ // Scene-only, split, presentation-only: each stage has one contiguous draw
1444
+ // per model. A crossing instance appears in both ranges at its single GPU address.
1343
1445
  const cursors = new Uint32Array(n);
1446
+ const splitCursors = split ? this.presentationFirst.slice() : cursors;
1447
+ const lateCursors = split ? this.sceneCounts.slice() : cursors;
1344
1448
  const arrays = new Array(n);
1345
1449
  for (let m = 0; m < n; m++)
1346
1450
  arrays[m] = counts[m] ? new Float32Array(counts[m] * INST_FLOATS) : null;
@@ -1348,9 +1452,24 @@ export class GpuPropsRenderer {
1348
1452
  if (it.model < 0 || it.model >= n)
1349
1453
  continue;
1350
1454
  const arr = arrays[it.model];
1351
- const o = cursors[it.model]++ * INST_FLOATS;
1455
+ const cursor = !split || !it.presentation
1456
+ ? cursors
1457
+ : it.presentation === true
1458
+ ? lateCursors
1459
+ : splitCursors;
1460
+ const o = cursor[it.model]++ * INST_FLOATS;
1352
1461
  arr.set(it.mat.subarray(0, 16), o);
1353
1462
  writeDeform(arr, o + 16, it.deform, this.models[it.model].extent);
1463
+ if (this.presentation) {
1464
+ const plane = it.presentation && it.presentation !== true ? it.presentation : null;
1465
+ // Placement is affine. Its unused fourth row and deformation padding
1466
+ // hold the clip plane with no added per-instance bytes; all passes
1467
+ // read world position from the first three rows.
1468
+ arr[o + 3] = plane?.[0] ?? 0;
1469
+ arr[o + 7] = plane?.[1] ?? 0;
1470
+ arr[o + 11] = plane?.[2] ?? 0;
1471
+ arr[o + 31] = plane?.[3] ?? (it.presentation ? 1 : -1);
1472
+ }
1354
1473
  }
1355
1474
  for (let m = 0; m < n; m++) {
1356
1475
  const arr = arrays[m];
@@ -1601,7 +1720,6 @@ export class GpuPropsRenderer {
1601
1720
  lightVP, shadowView, shadowSamp, channel = 'lit') {
1602
1721
  if (channel !== 'lit' && !this.inspection)
1603
1722
  throw new Error('Prop inspection must be enabled at construction.');
1604
- const topology = channel === 'wireframe' || channel === 'density';
1605
1723
  const receive = !!(lightVP && shadowView && shadowSamp);
1606
1724
  const mats = lightVP ? (Array.isArray(lightVP) ? lightVP : [lightVP]) : [];
1607
1725
  const u = new Float32Array(PROP_UNIFORM_WORDS);
@@ -1668,6 +1786,16 @@ export class GpuPropsRenderer {
1668
1786
  this.lastSS = ss;
1669
1787
  this.lastEnv = env;
1670
1788
  }
1789
+ this.encodeColor(enc, colorView, depthView, channel, false);
1790
+ }
1791
+ /** Draw over the presented compositor result, testing its final depth.
1792
+ * Reuses the same uploaded instances, material bindings and frame uniforms. */
1793
+ framePresentation(enc, colorView, depthView) {
1794
+ if (this.hasPresentation && this.presentation)
1795
+ this.encodeColor(enc, colorView, depthView, 'lit', true);
1796
+ }
1797
+ encodeColor(enc, colorView, depthView, channel, late) {
1798
+ const topology = channel === 'wireframe' || channel === 'density';
1671
1799
  const rp = enc.beginRenderPass({
1672
1800
  colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }],
1673
1801
  depthStencilAttachment: {
@@ -1687,7 +1815,7 @@ export class GpuPropsRenderer {
1687
1815
  rp.setVertexBuffer(3, this.geo.uv);
1688
1816
  rp.setIndexBuffer(this.geo.idx, 'uint32');
1689
1817
  }
1690
- const drawModel = (m) => {
1818
+ const drawModel = (m, count, first) => {
1691
1819
  const bg = this.bgs[m], mdl = this.models[m];
1692
1820
  if (!bg || this.counts[m] === 0)
1693
1821
  return;
@@ -1695,9 +1823,9 @@ export class GpuPropsRenderer {
1695
1823
  rp.setBindGroup(2, mdl.matBG);
1696
1824
  // Geometry is bound ONCE for the whole pass; a model is a range inside it.
1697
1825
  if (topology)
1698
- rp.draw(mdl.idxCount, this.counts[m], mdl.firstIndex);
1826
+ rp.draw(mdl.idxCount, count, mdl.firstIndex, first);
1699
1827
  else
1700
- rp.drawIndexed(mdl.idxCount, this.counts[m], mdl.firstIndex, mdl.baseVertex);
1828
+ rp.drawIndexed(mdl.idxCount, count, mdl.firstIndex, mdl.baseVertex, first);
1701
1829
  };
1702
1830
  // OPAQUE FIRST, then the blended models — the whole point of the second pass. A translucent
1703
1831
  // crystal drawn before an opaque rock composites against whatever the sky left in the target and
@@ -1709,14 +1837,20 @@ export class GpuPropsRenderer {
1709
1837
  for (let m = 0; m < this.models.length; m++) {
1710
1838
  const model = this.models[m];
1711
1839
  const clay = channel === 'clay';
1712
- if ((model.alpha < 1 && !clay) !== blended || this.counts[m] === 0)
1840
+ const first = late ? this.presentationFirst[m] : 0;
1841
+ const count = this.presentation
1842
+ ? late
1843
+ ? this.counts[m] - first
1844
+ : this.sceneCounts[m]
1845
+ : this.counts[m];
1846
+ if ((model.alpha < 1 && !clay) !== blended || !count)
1713
1847
  continue;
1714
- const pipeline = this.drawPipeline(blended, model.cullMode, clay || model.depthWrite);
1848
+ const pipeline = this.drawPipeline(blended, model.cullMode, clay || model.depthWrite, late);
1715
1849
  if (pipeline !== activePipeline) {
1716
1850
  rp.setPipeline(pipeline);
1717
1851
  activePipeline = pipeline;
1718
1852
  }
1719
- drawModel(m);
1853
+ drawModel(m, count, first);
1720
1854
  }
1721
1855
  }
1722
1856
  rp.end();
@@ -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
+ `;
@@ -1,7 +1,7 @@
1
1
  import type { PropMesh } from './gpuProps.js';
2
2
  export declare const propInspectionChannels: readonly ["lit", "albedo", "normal", "roughness", "emissive", "ao", "clay", "wireframe", "density", "uv", "batch"];
3
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),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 = tex.rgb * i.c; }\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";
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
5
  export declare class PropInspectionGeometry {
6
6
  private readonly device;
7
7
  private readonly meshes;
@@ -25,10 +25,10 @@ export const inspectionFragment = /* wgsl */ `
25
25
  let backTissue = mtl.optics.z>0.0 && dot(i.n,u.cam.xyz-i.world)<0.0;
26
26
  display=select(N,-N,backTissue)*0.5+0.5;
27
27
  }
28
- case 3u: { display=vec3(select(1.0,effectiveRoughness(orm),mtl.mat.z>=0.0)); }
28
+ case 3u: { display=vec3(select(1.0,effectiveRoughness(orm, i.l.y),mtl.mat.z>=0.0)); }
29
29
  case 4u: {
30
30
  var emission = select(vec3(0.0), base*u.surf.w, mtl.mat.z<0.0);
31
- if (mtl.optics.y > 1.5) { emission = tex.rgb * i.c; }
31
+ if (mtl.optics.y > 1.5) { emission = propEmission(tex.rgb,i.c,normalize(i.n),i.world); }
32
32
  return vec4(emission,opacity);
33
33
  }
34
34
  case 5u: { display=vec3(select(1.0,effectiveAO(orm),mtl.mat.z>=0.0)); }
@@ -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.74",
3
+ "version": "0.15.76",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {