ugly-game 0.15.76 → 0.15.78

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.
@@ -141,6 +141,12 @@ export interface PropMesh {
141
141
  normalMap?: GPUTexture;
142
142
  /** Thin-glass transmission [0,1]. Use alpha < 1 and depthWrite false. */
143
143
  transmission?: number;
144
+ /** Optical path in unscaled model units. With a frame's copyable scene
145
+ * texture, bend its real pixels through this thickness. Requires a blended
146
+ * transmissive surface. Without a snapshot, thin-glass blending is used. */
147
+ glassThickness?: number;
148
+ /** Dielectric index used for bending and Fresnel coverage. Defaults to 1.5. */
149
+ glassIOR?: number;
144
150
  /** Display-referred albedo render texture, bypassing lighting/tone mapping. */
145
151
  unlit?: boolean;
146
152
  /**
@@ -309,7 +315,16 @@ export interface PropInstance {
309
315
  }
310
316
  export declare class GpuPropsRenderer {
311
317
  private device;
318
+ private format;
312
319
  private inspection;
320
+ private glassInstances;
321
+ private glassVP;
322
+ private snapshots;
323
+ /** Number of source pixels copied by the most recent scene and late passes. */
324
+ readonly glassCopyPixels: {
325
+ scene: number;
326
+ presentation: number;
327
+ };
313
328
  private srgbTarget;
314
329
  private presentation?;
315
330
  private sceneCounts;
@@ -362,6 +377,9 @@ export declare class GpuPropsRenderer {
362
377
  * the LOD system rather than merely to the encoder.
363
378
  */
364
379
  private geo;
380
+ private geometrySlots;
381
+ private geometryVertices;
382
+ private geometryIndices;
365
383
  private cullVis;
366
384
  private cullBGs;
367
385
  /** Survivor lists are per (model, cascade) but packed into one buffer per model at this stride. */
@@ -432,7 +450,15 @@ export declare class GpuPropsRenderer {
432
450
  * `setModels` had been given that alpha; back at 1 it is opaque and casts again.
433
451
  */
434
452
  setMaterial(model: number, surface: Pick<PropMesh, 'alpha' | 'roughness' | 'metalness' | 'clearcoat' | 'clearcoatRoughness' | 'directClearcoat' | 'reflectionStrength' | 'specularIntensity' | 'metalFlakes' | 'flakeScale' | 'pearlStrength'>): void;
435
- setModels(meshes: PropMesh[]): void;
453
+ /**
454
+ * Replace the draw list and report the geometry bytes written by this call.
455
+ * Pass retainGeometry for immutable meshes whose identities survive draw-list
456
+ * changes. The arena appends new geometry until full, then compacts to the
457
+ * active list. Callers with mutable mesh arrays use the default upload path.
458
+ */
459
+ setModels(meshes: PropMesh[], retainGeometry?: boolean): number;
460
+ /** Allocated geometry only. Includes unused arena capacity. */
461
+ geometryBufferBytes(): number;
436
462
  /**
437
463
  * Group instances by model and upload the per-model instance buffers.
438
464
  *
@@ -487,9 +513,12 @@ export declare class GpuPropsRenderer {
487
513
  * a single shared uniform written once per cascade during encoding does not work — see `lightBufs`.
488
514
  */
489
515
  shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
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;
516
+ 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, sceneTexture?: GPUTexture): void;
491
517
  /** Draw over the presented compositor result, testing its final depth.
492
518
  * Reuses the same uploaded instances, material bindings and frame uniforms. */
493
- framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView): void;
519
+ framePresentation(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, sceneTexture?: GPUTexture): void;
494
520
  private encodeColor;
521
+ /** Release renderer-owned backdrop storage on teardown or after a resize. */
522
+ releaseGlassSnapshots(): void;
523
+ private colorPass;
495
524
  }
@@ -6,6 +6,7 @@
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 { glassBounds, glassCopyRegion, } from './propGlass.js';
9
10
  import { WET_RIND_WGSL } from './wetRind.js';
10
11
  export { WET_RIND_WGSL } from './wetRind.js';
11
12
  import { INTERIOR_LIGHT_WGSL } from './interiorLight.js';
@@ -62,7 +63,8 @@ struct Mat { mat: vec4<f32>, coat: vec4<f32>, maps: vec4<f32>, surface: vec4<f32
62
63
  // Renderer-wide linear HDR equirect (PropLook.environment). A 1×1 dummy when unset, and then never
63
64
  // sampled: look.z and look.w are forced to 0 on the CPU without it.
64
65
  @group(1) @binding(2) var sceneEnvTex: texture_2d<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>' : ''} };
66
+ @group(1) @binding(3) var transmittedScene: texture_2d<f32>;
67
+ 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>, @location(7) glassScale:f32 ${split ? ', @location(6) clipDistance: f32' : ''} ${inspect ? ', @location(5) @interpolate(linear) bary:vec3<f32>' : ''} };
66
68
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
67
69
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
68
70
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -135,7 +137,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
135
137
  world = sway(lp, world, upv, sc * inst.d2.w);
136
138
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
137
139
  ${split ? 'o.clipDistance = dot(world,vec3(m[0].w,m[1].w,m[2].w))+inst.d3.w;' : ''}
138
- o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
140
+ o.glassScale = sc; o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv;
139
141
  ${inspect ? 'o.bary = vec3<f32>(f32(vi%3u==0u),f32(vi%3u==1u),f32(vi%3u==2u));' : ''}
140
142
  return o;
141
143
  }
@@ -374,7 +376,10 @@ fn effectiveAO(orm:vec3<f32>) -> f32 { return select(1.0,orm.r,mtl.maps.y>0.5);
374
376
  fn surfaceOpacity(n:vec3<f32>, world:vec3<f32>) -> f32 {
375
377
  if (mtl.optics.x <= 0.0) { return mtl.mat.x; }
376
378
  let nv = clamp(abs(dot(n,normalize(u.cam.xyz-world))),0.0,1.0);
377
- let F = 0.04 + 0.96*pow(1.0-nv,5.0);
379
+ let eta = max(1.0,mtl.medium.z);
380
+ let r = (eta-1.0)/(eta+1.0);
381
+ let f0 = select(0.04,r*r,mtl.medium.w>0.0);
382
+ let F = f0 + (1.0-f0)*pow(1.0-nv,5.0);
378
383
  return clamp(1.0-mtl.optics.x*(1.0-F),0.0,1.0);
379
384
  }
380
385
  ${THIN_TISSUE_WGSL}
@@ -552,7 +557,23 @@ fn shade(i: VO) -> vec4<f32> {
552
557
  }
553
558
  @fragment fn fs(i: VO) -> @location(0) vec4<f32> {
554
559
  let color = shade(i);
555
- return ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
560
+ let output = ${transfer ? 'vec4(encodePropPresentation(color.rgb),color.a)' : 'color'};
561
+ if (mtl.medium.w > 0.0 && textureDimensions(transmittedScene).x > 1u) {
562
+ let size = vec2<f32>(textureDimensions(transmittedScene));
563
+ let V = normalize(u.cam.xyz-i.world);
564
+ let N = faceForward(normalize(i.n),-V,normalize(i.n));
565
+ let ray = refract(-V,N,1.0/mtl.medium.z);
566
+ let path = mtl.medium.w*i.glassScale;
567
+ let clear = u.mvp*vec4(i.world-V*path,1.0);
568
+ let bent = u.mvp*vec4(i.world+ray*path,1.0);
569
+ let shift = (bent.xy/max(0.001,bent.w)-clear.xy/max(0.001,clear.w))*vec2(0.5,-0.5);
570
+ let coord = clamp(i.pos.xy/size+shift,0.5/size,1.0-0.5/size);
571
+ let through = textureSampleLevel(transmittedScene,albedoSamp,coord,0.0).rgb;
572
+ let density = vec3(1.0)-clamp(srgbToLinear(i.c),vec3(0.0),vec3(1.0));
573
+ let absorb = exp(-density*mtl.medium.w/max(0.35,-dot(ray,N)));
574
+ return vec4(mix(through*absorb,output.rgb,output.a),1.0);
575
+ }
576
+ return output;
556
577
  }`;
557
578
  // Depth-only occluder pass: instanced prop depth from the sun's ortho view (so trees/rocks cast shadows).
558
579
  // Depth-only occluder. It MUST apply the identical sway, or the shadows stay put while the leaves
@@ -704,7 +725,13 @@ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
704
725
  `;
705
726
  export class GpuPropsRenderer {
706
727
  device;
728
+ format;
707
729
  inspection;
730
+ glassInstances = [];
731
+ glassVP = new Float32Array(16);
732
+ snapshots = [];
733
+ /** Number of source pixels copied by the most recent scene and late passes. */
734
+ glassCopyPixels = { scene: 0, presentation: 0 };
708
735
  srgbTarget;
709
736
  presentation;
710
737
  sceneCounts = new Uint32Array(0);
@@ -761,6 +788,9 @@ export class GpuPropsRenderer {
761
788
  * the LOD system rather than merely to the encoder.
762
789
  */
763
790
  geo = null;
791
+ geometrySlots = new WeakMap();
792
+ geometryVertices = 0;
793
+ geometryIndices = 0;
764
794
  cullVis = []; // survivor list — per MODEL, see cullPass
765
795
  cullBGs = [];
766
796
  /** Survivor lists are per (model, cascade) but packed into one buffer per model at this stride. */
@@ -868,6 +898,7 @@ export class GpuPropsRenderer {
868
898
  }
869
899
  constructor(device, format, options = {}) {
870
900
  this.device = device;
901
+ this.format = format;
871
902
  const { inspection = false, sampleCount = 1, depth = FORWARD_DEPTH, shadowDepthFormat = 'depth32float', presentation, ...look } = options;
872
903
  // Runtime guard for untyped callers: WebGPU only guarantees 1 and 4.
873
904
  if (![1, 4].includes(sampleCount))
@@ -917,6 +948,11 @@ export class GpuPropsRenderer {
917
948
  visibility: GPUShaderStage.FRAGMENT,
918
949
  texture: { sampleType: 'float' },
919
950
  },
951
+ {
952
+ binding: 3,
953
+ visibility: GPUShaderStage.FRAGMENT,
954
+ texture: { sampleType: 'float' },
955
+ },
920
956
  ],
921
957
  });
922
958
  const bgl2 = device.createBindGroupLayout({
@@ -1220,7 +1256,16 @@ export class GpuPropsRenderer {
1220
1256
  if (changed)
1221
1257
  this.device.queue.writeBuffer(packed.matBuf, 0, packed.materialValues);
1222
1258
  }
1223
- setModels(meshes) {
1259
+ /**
1260
+ * Replace the draw list and report the geometry bytes written by this call.
1261
+ * Pass retainGeometry for immutable meshes whose identities survive draw-list
1262
+ * changes. The arena appends new geometry until full, then compacts to the
1263
+ * active list. Callers with mutable mesh arrays use the default upload path.
1264
+ */
1265
+ setModels(meshes, retainGeometry = false) {
1266
+ this.glassInstances.length = 0;
1267
+ if (!meshes.some((m) => m.glassThickness))
1268
+ this.releaseGlassSnapshots();
1224
1269
  this.inspectionGeometry?.destroy();
1225
1270
  if (this.inspection)
1226
1271
  this.inspectionGeometry = new PropInspectionGeometry(this.device, meshes);
@@ -1273,54 +1318,86 @@ export class GpuPropsRenderer {
1273
1318
  // Indices stay MODEL-LOCAL and are offset by `baseVertex` at draw time rather than being rewritten
1274
1319
  // — rewriting them would work equally well for the camera pass and would silently break the
1275
1320
  // occluder pass, whose index buffer is fed to `drawIndexedIndirect` with args the GPU writes.
1276
- const totalVerts = meshes.reduce((n, m) => n + m.positions.length / 3, 0);
1277
- const totalIdx = meshes.reduce((n, m) => n + m.indices.length, 0);
1278
- // Cooked streams already have the GPU layout. Upload them directly to their
1279
- // arena offsets instead of allocating/copying five more CPU-sized arenas.
1280
- this.geo?.destroy();
1281
- this.geo = {
1282
- pos: dev.createBuffer({
1283
- size: Math.max(12, totalVerts * 12),
1284
- usage: U.VERTEX | U.COPY_DST,
1285
- }),
1286
- nrm: dev.createBuffer({
1287
- size: Math.max(12, totalVerts * 12),
1288
- usage: U.VERTEX | U.COPY_DST,
1289
- }),
1290
- col: dev.createBuffer({
1291
- size: Math.max(12, totalVerts * 12),
1292
- usage: U.VERTEX | U.COPY_DST,
1293
- }),
1294
- uv: dev.createBuffer({
1295
- size: Math.max(8, totalVerts * 8),
1296
- usage: U.VERTEX | U.COPY_DST,
1297
- }),
1298
- idx: dev.createBuffer({
1299
- size: Math.max(4, totalIdx * 4),
1300
- usage: U.INDEX | U.COPY_DST,
1301
- }),
1302
- destroy() {
1303
- for (const buffer of [this.pos, this.nrm, this.col, this.uv, this.idx])
1304
- buffer.destroy();
1305
- },
1306
- };
1321
+ const missing = retainGeometry
1322
+ ? [...new Set(meshes.filter((mesh) => !this.geometrySlots.has(mesh)))]
1323
+ : meshes;
1324
+ const newVertices = missing.reduce((n, m) => n + m.positions.length / 3, 0);
1325
+ const newIndices = missing.reduce((n, m) => n + m.indices.length, 0);
1326
+ const reuseArena = retainGeometry &&
1327
+ meshes.length > 0 &&
1328
+ this.geo &&
1329
+ this.geometryVertices + newVertices <= this.geo.pos.size / 12 &&
1330
+ this.geometryIndices + newIndices <= this.geo.idx.size / 4;
1331
+ if (!reuseArena) {
1332
+ const headroom = retainGeometry ? 2 : 1;
1333
+ const active = retainGeometry ? [...new Set(meshes)] : meshes;
1334
+ const vertices = active.reduce((n, m) => n + m.positions.length / 3, 0);
1335
+ const indices = active.reduce((n, m) => n + m.indices.length, 0);
1336
+ const maxBuffer = dev.limits.maxBufferSize;
1337
+ const vertexCapacity = Math.max(vertices, Math.min(vertices * headroom, Math.floor(maxBuffer / 12)));
1338
+ const indexCapacity = Math.max(indices, Math.min(indices * headroom, Math.floor(maxBuffer / 4)));
1339
+ this.geometrySlots = new WeakMap();
1340
+ this.geometryVertices = 0;
1341
+ this.geometryIndices = 0;
1342
+ this.geo?.destroy();
1343
+ this.geo = {
1344
+ pos: dev.createBuffer({
1345
+ size: Math.max(12, vertexCapacity * 12),
1346
+ usage: U.VERTEX | U.COPY_DST,
1347
+ }),
1348
+ nrm: dev.createBuffer({
1349
+ size: Math.max(12, vertexCapacity * 12),
1350
+ usage: U.VERTEX | U.COPY_DST,
1351
+ }),
1352
+ col: dev.createBuffer({
1353
+ size: Math.max(12, vertexCapacity * 12),
1354
+ usage: U.VERTEX | U.COPY_DST,
1355
+ }),
1356
+ uv: dev.createBuffer({
1357
+ size: Math.max(8, vertexCapacity * 8),
1358
+ usage: U.VERTEX | U.COPY_DST,
1359
+ }),
1360
+ idx: dev.createBuffer({
1361
+ size: Math.max(4, indexCapacity * 4),
1362
+ usage: U.INDEX | U.COPY_DST,
1363
+ }),
1364
+ destroy() {
1365
+ for (const buffer of [
1366
+ this.pos,
1367
+ this.nrm,
1368
+ this.col,
1369
+ this.uv,
1370
+ this.idx,
1371
+ ])
1372
+ buffer.destroy();
1373
+ },
1374
+ };
1375
+ }
1376
+ let uploadedBytes = 0;
1307
1377
  const upload = (buffer, offset, data) => {
1308
- if (data.byteLength)
1309
- dev.queue.writeBuffer(buffer, offset, data);
1378
+ if (!data.byteLength)
1379
+ return;
1380
+ dev.queue.writeBuffer(buffer, offset, data);
1381
+ uploadedBytes += data.byteLength;
1310
1382
  };
1311
- let vCursor = 0, iCursor = 0;
1312
1383
  this.models = meshes.map((m, modelIndex) => {
1313
- const verts = m.positions.length / 3;
1314
- const baseVertex = vCursor, firstIndex = iCursor;
1315
- upload(this.geo.pos, baseVertex * 12, m.positions);
1316
- upload(this.geo.nrm, baseVertex * 12, m.normals);
1317
- upload(this.geo.col, baseVertex * 12, m.colors);
1318
- // Fresh WebGPU allocations are zero initialized, including absent UVs.
1319
- if (m.uvs)
1320
- upload(this.geo.uv, baseVertex * 8, m.uvs);
1321
- upload(this.geo.idx, firstIndex * 4, m.indices);
1322
- vCursor += verts;
1323
- iCursor += m.indices.length;
1384
+ let slot = retainGeometry ? this.geometrySlots.get(m) : undefined;
1385
+ if (!slot) {
1386
+ const baseVertex = this.geometryVertices;
1387
+ const firstIndex = this.geometryIndices;
1388
+ slot = { baseVertex, firstIndex };
1389
+ upload(this.geo.pos, baseVertex * 12, m.positions);
1390
+ upload(this.geo.nrm, baseVertex * 12, m.normals);
1391
+ upload(this.geo.col, baseVertex * 12, m.colors);
1392
+ // Appended ranges are still zero initialized, including absent UVs.
1393
+ if (m.uvs)
1394
+ upload(this.geo.uv, baseVertex * 8, m.uvs);
1395
+ upload(this.geo.idx, firstIndex * 4, m.indices);
1396
+ this.geometryVertices += m.positions.length / 3;
1397
+ this.geometryIndices += m.indices.length;
1398
+ if (retainGeometry)
1399
+ this.geometrySlots.set(m, slot);
1400
+ }
1324
1401
  // A GPUTexture is already uploaded and already mipped (the KTX2 path) — bind it directly.
1325
1402
  // Only an ImageBitmap needs uploadAlbedo's hand-rolled half-scale mip chain.
1326
1403
  const ownsTex = !!m.albedo && !(m.albedo instanceof GPUTexture);
@@ -1362,20 +1439,25 @@ export class GpuPropsRenderer {
1362
1439
  Math.max(0, Math.min(1, m.directClearcoat ?? 0)),
1363
1440
  Math.max(0, Math.min(8, m.interiorOpticalDepth ?? 0)),
1364
1441
  Math.max(0, m.wetRindHeight ?? 0),
1365
- 0,
1366
- 0,
1442
+ Math.min(2.8, Math.max(1, m.glassIOR ?? 1.5)),
1443
+ Math.max(0, m.glassThickness ?? 0),
1367
1444
  ]);
1368
1445
  dev.queue.writeBuffer(matBuf, 0, materialValues);
1369
1446
  return {
1370
1447
  alpha,
1448
+ ...(m.glassThickness &&
1449
+ m.glassThickness > 0 &&
1450
+ m.transmission &&
1451
+ alpha < 1
1452
+ ? { glassBounds: glassBounds(m.positions, m.glassThickness) }
1453
+ : {}),
1371
1454
  cullMode: m.cullMode ?? 'none',
1372
1455
  depthWrite: m.depthWrite ?? true,
1373
1456
  cutout,
1374
1457
  matBuf,
1375
1458
  materialValues,
1376
1459
  ownsTex,
1377
- firstIndex,
1378
- baseVertex,
1460
+ ...slot,
1379
1461
  idxCount: m.indices.length,
1380
1462
  extent: m.extent ?? measureExtent(m.positions),
1381
1463
  tex,
@@ -1395,6 +1477,16 @@ export class GpuPropsRenderer {
1395
1477
  }),
1396
1478
  };
1397
1479
  });
1480
+ for (const buffer of this.instBufs)
1481
+ buffer?.destroy();
1482
+ for (const buffer of this.cullVis)
1483
+ buffer?.destroy();
1484
+ for (const cascade of this.cullU)
1485
+ for (const buffer of cascade)
1486
+ buffer?.destroy();
1487
+ for (const cascade of this.cullArgs)
1488
+ for (const buffer of cascade)
1489
+ buffer?.destroy();
1398
1490
  this.caps = meshes.map(() => 0);
1399
1491
  this.instBufs = meshes.map(() => null);
1400
1492
  this.bgs = meshes.map(() => null);
@@ -1407,6 +1499,14 @@ export class GpuPropsRenderer {
1407
1499
  this.cullVis = meshes.map(() => null);
1408
1500
  this.visStride = meshes.map(() => 0);
1409
1501
  this.cullReady = false;
1502
+ return uploadedBytes;
1503
+ }
1504
+ /** Allocated geometry only. Includes unused arena capacity. */
1505
+ geometryBufferBytes() {
1506
+ const { geo } = this;
1507
+ return geo
1508
+ ? geo.pos.size + geo.nrm.size + geo.col.size + geo.uv.size + geo.idx.size
1509
+ : 0;
1410
1510
  }
1411
1511
  /**
1412
1512
  * Group instances by model and upload the per-model instance buffers.
@@ -1417,6 +1517,7 @@ export class GpuPropsRenderer {
1417
1517
  * re-allocating a megabyte of storage buffers per frame would cost more than the LOD saves.
1418
1518
  */
1419
1519
  setInstances(instances) {
1520
+ this.glassInstances.length = 0;
1420
1521
  const dev = this.device;
1421
1522
  const n = this.models.length;
1422
1523
  const counts = new Uint32Array(n);
@@ -1451,6 +1552,14 @@ export class GpuPropsRenderer {
1451
1552
  for (const it of instances) {
1452
1553
  if (it.model < 0 || it.model >= n)
1453
1554
  continue;
1555
+ const bounds = this.models[it.model].glassBounds;
1556
+ if (bounds)
1557
+ this.glassInstances.push({
1558
+ bounds,
1559
+ mat: it.mat,
1560
+ early: !split || it.presentation !== true,
1561
+ late: split && !!it.presentation,
1562
+ });
1454
1563
  const arr = arrays[it.model];
1455
1564
  const cursor = !split || !it.presentation
1456
1565
  ? cursors
@@ -1717,7 +1826,10 @@ export class GpuPropsRenderer {
1717
1826
  frame(enc, colorView, depthView, camVP, sunDir, sunCol, amb, camPos, fog, fogDensity, up,
1718
1827
  // Optional sun shadow-receive: pass the terrain's lightVP + shadow-map view + comparison sampler and props sit
1719
1828
  // in the same shadow. Omit all three (the demo path) → no shadowing, byte-identical to before.
1720
- lightVP, shadowView, shadowSamp, channel = 'lit') {
1829
+ lightVP, shadowView, shadowSamp, channel = 'lit', sceneTexture) {
1830
+ if (this.glassInstances.length)
1831
+ this.glassVP.set(camVP);
1832
+ this.glassCopyPixels.scene = this.glassCopyPixels.presentation = 0;
1721
1833
  if (channel !== 'lit' && !this.inspection)
1722
1834
  throw new Error('Prop inspection must be enabled at construction.');
1723
1835
  const receive = !!(lightVP && shadowView && shadowSamp);
@@ -1780,21 +1892,73 @@ export class GpuPropsRenderer {
1780
1892
  { binding: 0, resource: sv },
1781
1893
  { binding: 1, resource: ss },
1782
1894
  { binding: 2, resource: (env ?? this.dummyEnv).createView() },
1895
+ { binding: 3, resource: this.dummyEnv.createView() },
1783
1896
  ],
1784
1897
  });
1785
1898
  this.lastSV = sv;
1786
1899
  this.lastSS = ss;
1787
1900
  this.lastEnv = env;
1788
1901
  }
1789
- this.encodeColor(enc, colorView, depthView, channel, false);
1902
+ this.encodeColor(enc, colorView, depthView, channel, false, sceneTexture);
1790
1903
  }
1791
1904
  /** Draw over the presented compositor result, testing its final depth.
1792
1905
  * Reuses the same uploaded instances, material bindings and frame uniforms. */
1793
- framePresentation(enc, colorView, depthView) {
1906
+ framePresentation(enc, colorView, depthView, sceneTexture) {
1794
1907
  if (this.hasPresentation && this.presentation)
1795
- this.encodeColor(enc, colorView, depthView, 'lit', true);
1908
+ this.encodeColor(enc, colorView, depthView, 'lit', true, sceneTexture);
1796
1909
  }
1797
- encodeColor(enc, colorView, depthView, channel, late) {
1910
+ encodeColor(enc, colorView, depthView, channel, late, source) {
1911
+ const crop = source &&
1912
+ channel === 'lit' &&
1913
+ source.sampleCount === 1 &&
1914
+ this.glassInstances.length
1915
+ ? glassCopyRegion(this.glassInstances, this.glassVP, source.width, source.height, late)
1916
+ : undefined;
1917
+ this.colorPass(enc, colorView, depthView, channel, late, this.shadowBG, crop ? 'background' : 'all');
1918
+ if (!crop || !source)
1919
+ return;
1920
+ const format = late ? this.presentation.format : this.format;
1921
+ const slot = Number(late);
1922
+ let entry = this.snapshots[slot];
1923
+ if (entry?.texture.width !== source.width ||
1924
+ entry.texture.height !== source.height ||
1925
+ entry.texture.format !== format) {
1926
+ entry?.texture.destroy();
1927
+ const texture = this.device.createTexture({
1928
+ label: 'prop-glass-backdrop',
1929
+ format,
1930
+ size: [source.width, source.height],
1931
+ usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
1932
+ });
1933
+ this.snapshots[slot] = entry = { texture, view: texture.createView() };
1934
+ }
1935
+ enc.copyTextureToTexture({ texture: source, origin: crop.origin }, { texture: entry.texture, origin: crop.origin }, crop.size);
1936
+ this.glassCopyPixels[late ? 'presentation' : 'scene'] =
1937
+ crop.size.width * crop.size.height;
1938
+ if (!entry.group || entry.shadow !== this.shadowBG) {
1939
+ entry.shadow = this.shadowBG;
1940
+ entry.group = this.device.createBindGroup({
1941
+ layout: this.drawBGL[1],
1942
+ entries: [
1943
+ { binding: 0, resource: this.lastSV },
1944
+ { binding: 1, resource: this.lastSS },
1945
+ {
1946
+ binding: 2,
1947
+ resource: (this.lastEnv ?? this.dummyEnv).createView(),
1948
+ },
1949
+ { binding: 3, resource: entry.view },
1950
+ ],
1951
+ });
1952
+ }
1953
+ this.colorPass(enc, colorView, depthView, channel, late, entry.group, 'glass');
1954
+ }
1955
+ /** Release renderer-owned backdrop storage on teardown or after a resize. */
1956
+ releaseGlassSnapshots() {
1957
+ for (const snapshot of this.snapshots)
1958
+ snapshot?.texture.destroy();
1959
+ this.snapshots = [];
1960
+ }
1961
+ colorPass(enc, colorView, depthView, channel, late, lighting, selection) {
1798
1962
  const topology = channel === 'wireframe' || channel === 'density';
1799
1963
  const rp = enc.beginRenderPass({
1800
1964
  colorAttachments: [{ view: colorView, loadOp: 'load', storeOp: 'store' }],
@@ -1804,7 +1968,7 @@ export class GpuPropsRenderer {
1804
1968
  depthStoreOp: 'store',
1805
1969
  },
1806
1970
  });
1807
- rp.setBindGroup(1, this.shadowBG);
1971
+ rp.setBindGroup(1, lighting);
1808
1972
  // The arena, bound once for every model in both loops below.
1809
1973
  if (topology)
1810
1974
  this.inspectionGeometry?.bind(rp);
@@ -1836,6 +2000,9 @@ export class GpuPropsRenderer {
1836
2000
  for (const blended of [false, true]) {
1837
2001
  for (let m = 0; m < this.models.length; m++) {
1838
2002
  const model = this.models[m];
2003
+ if (selection !== 'all' &&
2004
+ !!model.glassBounds !== (selection === 'glass'))
2005
+ continue;
1839
2006
  const clay = channel === 'clay';
1840
2007
  const first = late ? this.presentationFirst[m] : 0;
1841
2008
  const count = this.presentation
@@ -0,0 +1,23 @@
1
+ /** Local bounds expanded to include the exit point of a refracted ray. */
2
+ export declare function glassBounds(positions: Float32Array, thickness: number): {
3
+ low: number[];
4
+ high: number[];
5
+ };
6
+ export interface GlassBoundsInstance {
7
+ bounds: ReturnType<typeof glassBounds>;
8
+ mat: Float32Array;
9
+ early: boolean;
10
+ late: boolean;
11
+ }
12
+ /** The copy keeps original pixel coordinates inside a retained scratch texture.
13
+ * Sampling is clamped to the viewport, including when a lens crosses its edge. */
14
+ export declare function glassCopyRegion(instances: readonly GlassBoundsInstance[], vp: Float32Array, width: number, height: number, late: boolean): {
15
+ origin: {
16
+ x: number;
17
+ y: number;
18
+ };
19
+ size: {
20
+ width: number;
21
+ height: number;
22
+ };
23
+ } | undefined;
@@ -0,0 +1,57 @@
1
+ /** Local bounds expanded to include the exit point of a refracted ray. */
2
+ export function glassBounds(positions, thickness) {
3
+ const low = [Infinity, Infinity, Infinity];
4
+ const high = [-Infinity, -Infinity, -Infinity];
5
+ for (let i = 0; i < positions.length; i += 3) {
6
+ for (let k = 0; k < 3; k++) {
7
+ low[k] = Math.min(low[k], positions[i + k] - thickness * 2);
8
+ high[k] = Math.max(high[k], positions[i + k] + thickness * 2);
9
+ }
10
+ }
11
+ return { low, high };
12
+ }
13
+ /** The copy keeps original pixel coordinates inside a retained scratch texture.
14
+ * Sampling is clamped to the viewport, including when a lens crosses its edge. */
15
+ export function glassCopyRegion(instances, vp, width, height, late) {
16
+ let left = width, right = 0, top = height, bottom = 0;
17
+ for (const instance of instances) {
18
+ if (!(late ? instance.late : instance.early))
19
+ continue;
20
+ const m = instance.mat, { low, high } = instance.bounds;
21
+ let l = width, r = 0, t = height, b = 0;
22
+ let inFront = false, behind = false;
23
+ for (let corner = 0; corner < 8; corner++) {
24
+ const x = corner & 1 ? high[0] : low[0], y = corner & 2 ? high[1] : low[1], z = corner & 4 ? high[2] : low[2];
25
+ const wx = m[0] * x + m[4] * y + m[8] * z + m[12];
26
+ const wy = m[1] * x + m[5] * y + m[9] * z + m[13];
27
+ const wz = m[2] * x + m[6] * y + m[10] * z + m[14];
28
+ const w = vp[3] * wx + vp[7] * wy + vp[11] * wz + vp[15];
29
+ if (w <= 0.001) {
30
+ behind = true;
31
+ continue;
32
+ }
33
+ inFront = true;
34
+ const sx = (0.5 + (0.5 * (vp[0] * wx + vp[4] * wy + vp[8] * wz + vp[12])) / w) *
35
+ width;
36
+ const sy = (0.5 - (0.5 * (vp[1] * wx + vp[5] * wy + vp[9] * wz + vp[13])) / w) *
37
+ height;
38
+ l = Math.min(l, sx);
39
+ r = Math.max(r, sx);
40
+ t = Math.min(t, sy);
41
+ b = Math.max(b, sy);
42
+ }
43
+ if (!inFront)
44
+ continue;
45
+ if (behind)
46
+ return { origin: { x: 0, y: 0 }, size: { width, height } };
47
+ left = Math.min(left, l);
48
+ right = Math.max(right, r);
49
+ top = Math.min(top, t);
50
+ bottom = Math.max(bottom, b);
51
+ }
52
+ const x = Math.max(0, Math.floor(left) - 2), y = Math.max(0, Math.floor(top) - 2);
53
+ const w = Math.min(width, Math.ceil(right) + 2) - x, h = Math.min(height, Math.ceil(bottom) + 2) - y;
54
+ return w > 0 && h > 0
55
+ ? { origin: { x, y }, size: { width: w, height: h } }
56
+ : undefined;
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.76",
3
+ "version": "0.15.78",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {