ugly-game 0.14.20 → 0.14.21

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.
@@ -147,6 +147,15 @@ export declare const CROWD_MATERIALS: {
147
147
  };
148
148
  /** Rows in the WGSL `MATS` table — the bound `writeCrowdRecord` checks a material against. */
149
149
  export declare const CROWD_MATERIAL_COUNT = 5;
150
+ /**
151
+ * Materials whose shader row has a non-zero REFRACTION strength (`c.y` in `MATS`).
152
+ *
153
+ * ⚠️ Must agree with that table, and `gpuCrowd.gpu.mjs` checks the two against each other on a real
154
+ * device. It exists so `needsScene` can answer without the CPU restating the shader's numbers, and
155
+ * so a material given refraction later cannot be forgotten here — which would leave it sampling a
156
+ * 1×1 dummy and looking merely flat.
157
+ */
158
+ export declare const REFRACTING_MATERIALS: ReadonlySet<number>;
150
159
  /** Which LOD bucket a contiguous run of instance records belongs to. */
151
160
  export interface CrowdBucket {
152
161
  lod: number;
@@ -477,6 +486,13 @@ export declare const CROWD_BINDINGS: {
477
486
  readonly sampleType: "float";
478
487
  readonly viewDimension: "2d-array";
479
488
  };
489
+ }, {
490
+ readonly binding: 3;
491
+ readonly visibility: 2;
492
+ readonly texture: {
493
+ readonly sampleType: "float";
494
+ readonly viewDimension: "2d";
495
+ };
480
496
  }];
481
497
  /**
482
498
  * group 3 — the pooled geometry and the instance records, per rung.
@@ -615,6 +631,17 @@ export declare class GpuCrowdRenderer {
615
631
  */
616
632
  private matTex;
617
633
  private ownsMat;
634
+ /**
635
+ * The 1×1 stand-in bound at group 2 binding 3 when no scene copy is supplied, and the view the
636
+ * `matBG` currently holds — group 2 is rebuilt only when that view actually changes, so a steady
637
+ * frame does no bind-group work.
638
+ */
639
+ private dummyScene;
640
+ private dummySceneView;
641
+ private lastSceneView;
642
+ private skinArrayView;
643
+ /** Whether any packed instance refracts — see `needsScene`. Recomputed on every setInstances. */
644
+ private refracting;
618
645
  private plan;
619
646
  /** The CPU-side morph library. It never reaches the GPU — see `mergeTargets`. */
620
647
  private targets;
@@ -668,6 +695,22 @@ export declare class GpuCrowdRenderer {
668
695
  * per-character or per-frame; a character is a slot plus a record, and that is the whole point.
669
696
  */
670
697
  setAssets(a: CrowdAssets): void;
698
+ /**
699
+ * Group 2 — the two atlases and the scene copy.
700
+ *
701
+ * Rebuilt when the SCENE VIEW changes and not otherwise: the two atlases belong to the kit, so a
702
+ * steady frame with a stable scene texture does no bind-group work at all.
703
+ */
704
+ private buildMatBG;
705
+ /**
706
+ * Does any instance currently packed actually REFRACT?
707
+ *
708
+ * ⚠️ THE WHOLE POINT OF THIS METHOD is to let a caller skip the scene-colour copy. A copy is a
709
+ * full-screen blit; paying for one every frame so that a crowd of skin can ignore it is exactly
710
+ * the cost that must not be added. Read straight off the records the renderer holds, so it cannot
711
+ * disagree with what is about to be drawn.
712
+ */
713
+ needsScene(): boolean;
671
714
  private allocMergeBuffers;
672
715
  private rebuildLodBindGroups;
673
716
  /**
@@ -714,5 +757,18 @@ export declare class GpuCrowdRenderer {
714
757
  * fauna standing next to it. `load = true` composites over whatever is already there; `false`
715
758
  * clears to `clear`.
716
759
  */
717
- 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, clear: [number, number, number], load?: boolean, lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler): void;
760
+ 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, clear: [number, number, number], load?: boolean, lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler,
761
+ /**
762
+ * A COPY of the colour target as it stood before this pass, plus its pixel size, so refracting
763
+ * materials can sample what is behind a body.
764
+ *
765
+ * ⚠️ ONLY WORTH SUPPLYING WHEN `needsScene()` IS TRUE. A copy is a full-screen blit; taking one
766
+ * every frame for a crowd with no glass in it is exactly the cost that must not be paid. Omit
767
+ * this and refraction is off — glass falls back to its fresnel rim, which is what 0.14.20 did.
768
+ */
769
+ scene?: {
770
+ view: GPUTextureView;
771
+ width: number;
772
+ height: number;
773
+ }): void;
718
774
  }
@@ -72,6 +72,17 @@ export const CROWD_MATERIALS = {
72
72
  };
73
73
  /** Rows in the WGSL `MATS` table — the bound `writeCrowdRecord` checks a material against. */
74
74
  export const CROWD_MATERIAL_COUNT = 5;
75
+ /**
76
+ * Materials whose shader row has a non-zero REFRACTION strength (`c.y` in `MATS`).
77
+ *
78
+ * ⚠️ Must agree with that table, and `gpuCrowd.gpu.mjs` checks the two against each other on a real
79
+ * device. It exists so `needsScene` can answer without the CPU restating the shader's numbers, and
80
+ * so a material given refraction later cannot be forgotten here — which would leave it sampling a
81
+ * 1×1 dummy and looking merely flat.
82
+ */
83
+ export const REFRACTING_MATERIALS = new Set([
84
+ CROWD_MATERIALS.glass,
85
+ ]);
75
86
  // ─────────────────────────────────────────────────────────────────────────────
76
87
  // PURE ARITHMETIC. Everything below this line down to the WGSL is a plain function over plain
77
88
  // arrays, with no GPUDevice anywhere — because there is no GPU in CI and "the proof is a picture"
@@ -604,6 +615,15 @@ export const CROWD_BINDINGS = {
604
615
  visibility: VIS_FRAGMENT,
605
616
  texture: { sampleType: 'float', viewDimension: '2d-array' },
606
617
  },
618
+ // A COPY of the scene colour as it stood before this pass, for refraction. Plain 2d, not an
619
+ // array. Bound to a 1×1 dummy when the caller supplies none, and then `csm.w` is 0 and the
620
+ // shader never samples it — see `needsScene`, which is how a frame with no glass in it pays
621
+ // for none of this.
622
+ {
623
+ binding: 3,
624
+ visibility: VIS_FRAGMENT,
625
+ texture: { sampleType: 'float', viewDimension: '2d' },
626
+ },
607
627
  ],
608
628
  /**
609
629
  * group 3 — the pooled geometry and the instance records, per rung.
@@ -803,6 +823,9 @@ struct U { viewProj: mat4x4f, sun: vec4f, sunCol: vec4f, amb: vec4f, cam: vec4f,
803
823
  // white array is bound when a caller supplies none, so white x colour = colour and the untextured
804
824
  // path is byte-identical to before this existed.
805
825
  @group(2) @binding(2) var matTex: texture_2d_array<f32>;
826
+ // The scene as it stood BEFORE this pass, for refraction. u.csm.w is 1 when it is real and 0 when
827
+ // it is the 1x1 dummy; u.csm.yz is the viewport in pixels, so a fragment can find itself in it.
828
+ @group(2) @binding(3) var sceneTex: texture_2d<f32>;
806
829
  @group(3) @binding(0) var<storage,read> def: array<vec4f>;
807
830
  @group(3) @binding(1) var<storage,read> defN: array<vec4f>;
808
831
  @group(3) @binding(2) var<storage,read> uvs: array<vec2f>;
@@ -902,13 +925,15 @@ const LUMA_GAIN: f32 = 1.2428;
902
925
  // exp and scale are written as 1 on the rows that do not use them: a WGSL const array has no empty
903
926
  // cell, and pow(0, 0) is a value nobody should have to reason about.
904
927
  // b.w is the PROJECTION MODE for the material texture: 0 = triplanar, 1 = cylindrical about the
905
- // body's long axis. c.x is how far FRESNEL drives the output ALPHA - see the glass note in fs.
928
+ // body's long axis. c.x is how far FRESNEL drives the output ALPHA and c.y is REFRACTION strength in
929
+ // screen widths - see the glass note in fs. c.y is 0 on every row but glass, and it is the flag that
930
+ // keeps every other material out of the scene-colour sample entirely.
906
931
  const MATS = array<vec4f, 15>(
907
- vec4f(0.00, 1.0, 0.00, 0.0), vec4f(0.00, -1.0, 1.000, 0.0), vec4f(0.00, 0.0, 0.0, 0.0),
908
- vec4f(0.35, 64.0, 0.50, 0.0), vec4f(0.60, -1.0, 1.000, 0.0), vec4f(0.00, 0.0, 0.0, 0.0),
909
- vec4f(0.90, 128.0, 0.80, 1.0), vec4f(1.00, 0.0, 0.333, 0.0), vec4f(0.00, 0.0, 0.0, 0.0),
910
- vec4f(0.90, 256.0, 1.00, 0.0), vec4f(1.00, -1.0, 1.000, 0.0), vec4f(1.00, 0.0, 0.0, 0.0),
911
- vec4f(0.08, 16.0, 0.15, 0.0), vec4f(1.00, 1.0, 0.300, 1.0), vec4f(0.00, 0.0, 0.0, 0.0),
932
+ vec4f(0.00, 1.0, 0.00, 0.0), vec4f(0.00, -1.0, 1.000, 0.0), vec4f(0.00, 0.000, 0.0, 0.0),
933
+ vec4f(0.35, 64.0, 0.50, 0.0), vec4f(0.60, -1.0, 1.000, 0.0), vec4f(0.00, 0.000, 0.0, 0.0),
934
+ vec4f(0.90, 128.0, 0.80, 1.0), vec4f(1.00, 0.0, 0.333, 0.0), vec4f(0.00, 0.000, 0.0, 0.0),
935
+ vec4f(0.90, 256.0, 1.00, 0.0), vec4f(1.00, -1.0, 1.000, 0.0), vec4f(1.00, 0.045, 0.0, 0.0),
936
+ vec4f(0.08, 16.0, 0.15, 0.0), vec4f(1.00, 1.0, 0.300, 1.0), vec4f(0.00, 0.000, 0.0, 0.0),
912
937
  );
913
938
  // ⚠️ Wood's tile scale is 0.22, not 0.5, and that was set by LOOKING. A shipped human stands ~16.6
914
939
  // kit units, so 0.5 repeats the grain about eight times head to foot — fine enough that at any
@@ -1056,8 +1081,45 @@ fn cylindrical(layer: i32, p: vec3f, dx: vec3f, dy: vec3f) -> vec3f {
1056
1081
  // c.x is 0 for every other row, so alpha is exactly tint.w for them - and material 0 is
1057
1082
  // untouched, which is the invariant the whole table is built around.
1058
1083
  let rim = select(0.0, fres / max(a.z, 1e-4), a.z > 0.0);
1059
- let alpha = clamp(mix(i.tint.w, 1.0, c.x * rim), 0.0, 1.0);
1060
- return vec4f(mix(lit, u.fog.xyz, f), alpha);
1084
+ var alpha = clamp(mix(i.tint.w, 1.0, c.x * rim), 0.0, 1.0);
1085
+ var outCol = lit;
1086
+
1087
+ // ── REFRACTION ────────────────────────────────────────────────────────────
1088
+ //
1089
+ // ⚠️ GATED ON c.y, WHICH IS ZERO ON EVERY ROW BUT GLASS. Nothing else reaches the sample, so a
1090
+ // crowd of skin costs exactly what it did; and the caller only copies the scene at all when
1091
+ // needsScene() says a refracting instance is actually on screen, so a frame with no glass in it
1092
+ // pays for neither the copy nor the bind.
1093
+ //
1094
+ // ⚠️ textureSampleLevel, not textureSample. A screen-space lookup wants mip 0 anyway, and an
1095
+ // explicit level takes no implicit derivatives - which is what makes it legal inside this
1096
+ // non-uniform branch. Same constraint the material atlas hit, solved the cheaper way because
1097
+ // there is no mip chain to want here.
1098
+ if (c.y > 0.0 && u.csm.w > 0.5) {
1099
+ let vp = vec2f(max(u.csm.y, 1.0), max(u.csm.z, 1.0));
1100
+ // pos is in FRAMEBUFFER pixels, so this is already the sample's own place in the copy.
1101
+ let here = i.pos.xy / vp;
1102
+ // The surface normal's direction ON SCREEN. viewProj applied to a direction (w = 0) gives its
1103
+ // clip-space heading; the y is negated because clip space runs +y UP and a texture's v runs
1104
+ // DOWN. Getting that flip wrong bends the background the wrong way, which reads as glass with
1105
+ // an odd tilt rather than as anything obviously broken.
1106
+ let nd = (u.viewProj * vec4f(n, 0.0)).xy;
1107
+ let off = vec2f(nd.x, -nd.y) * c.y;
1108
+ // Clamped so a grazing fragment cannot reach outside the copy and smear its edge texel across
1109
+ // the body.
1110
+ let suv = clamp(here + off, vec2f(0.0), vec2f(1.0));
1111
+ let behind = textureSampleLevel(sceneTex, skinSamp, suv, 0.0).rgb;
1112
+ // The transmitted background takes the glass's own colour, then the lit surface is layered over
1113
+ // it by the SAME fresnel rim that drove the alpha: clear in the middle, bright at the edge.
1114
+ outCol = mix(behind * base, lit, clamp(c.x * rim, 0.0, 1.0));
1115
+ // ⚠️ ALPHA 1 once we have composited the background OURSELVES. The blended pipeline would
1116
+ // otherwise mix our result with the UNDISTORTED scene underneath and half the refraction would
1117
+ // be cancelled straight back out. The record still carries tint.w < 1, so splitByAlpha still
1118
+ // routes glass to that pipeline and still gets its back-face cull and depth-write-off - this
1119
+ // only makes the blend itself a pass-through.
1120
+ alpha = 1.0;
1121
+ }
1122
+ return vec4f(mix(outCol, u.fog.xyz, f), alpha);
1061
1123
  }`;
1062
1124
  const INITIAL_MERGE_ENTRIES = 4096;
1063
1125
  export class GpuCrowdRenderer {
@@ -1108,6 +1170,17 @@ export class GpuCrowdRenderer {
1108
1170
  */
1109
1171
  matTex = null;
1110
1172
  ownsMat = false;
1173
+ /**
1174
+ * The 1×1 stand-in bound at group 2 binding 3 when no scene copy is supplied, and the view the
1175
+ * `matBG` currently holds — group 2 is rebuilt only when that view actually changes, so a steady
1176
+ * frame does no bind-group work.
1177
+ */
1178
+ dummyScene = null;
1179
+ dummySceneView = null;
1180
+ lastSceneView = null;
1181
+ skinArrayView = null;
1182
+ /** Whether any packed instance refracts — see `needsScene`. Recomputed on every setInstances. */
1183
+ refracting = false;
1111
1184
  plan = null;
1112
1185
  /** The CPU-side morph library. It never reaches the GPU — see `mergeTargets`. */
1113
1186
  targets = [];
@@ -1334,19 +1407,56 @@ export class GpuCrowdRenderer {
1334
1407
  // group 2 is the kit's atlas, so it changes exactly when the kit does. ARRAY-dimensioned even
1335
1408
  // for a single-layer texture: the shader samples texture_2d_array unconditionally, and a plain
1336
1409
  // 2d view against that binding is a validation error rather than a fallback.
1337
- this.matBG = dev.createBindGroup({
1410
+ // The 1×1 stand-in for the scene copy. Created once per kit and destroyed with it; `csm.w` is 0
1411
+ // whenever it is what is bound, so the shader never reads it.
1412
+ if (!this.dummyScene) {
1413
+ const t = dev.createTexture({
1414
+ size: { width: 1, height: 1 },
1415
+ format: 'rgba8unorm',
1416
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
1417
+ });
1418
+ dev.queue.writeTexture({ texture: t }, new Uint8Array([0, 0, 0, 255]), { bytesPerRow: 4 }, { width: 1, height: 1 });
1419
+ this.dummyScene = t;
1420
+ this.dummySceneView = t.createView();
1421
+ }
1422
+ this.skinArrayView = a.skin.createView({ dimension: '2d-array' });
1423
+ this.buildMatBG(this.dummySceneView);
1424
+ this.rebuildLodBindGroups();
1425
+ this.frameBGDirty = true;
1426
+ }
1427
+ /**
1428
+ * Group 2 — the two atlases and the scene copy.
1429
+ *
1430
+ * Rebuilt when the SCENE VIEW changes and not otherwise: the two atlases belong to the kit, so a
1431
+ * steady frame with a stable scene texture does no bind-group work at all.
1432
+ */
1433
+ buildMatBG(sceneView) {
1434
+ if (!this.skinArrayView || !this.matTex)
1435
+ return;
1436
+ this.matBG = this.device.createBindGroup({
1338
1437
  layout: this.drawBGL[2],
1339
1438
  entries: [
1340
- { binding: 0, resource: a.skin.createView({ dimension: '2d-array' }) },
1439
+ { binding: 0, resource: this.skinArrayView },
1341
1440
  { binding: 1, resource: this.skinSamp },
1342
1441
  {
1343
1442
  binding: 2,
1344
1443
  resource: this.matTex.createView({ dimension: '2d-array' }),
1345
1444
  },
1445
+ { binding: 3, resource: sceneView },
1346
1446
  ],
1347
1447
  });
1348
- this.rebuildLodBindGroups();
1349
- this.frameBGDirty = true;
1448
+ this.lastSceneView = sceneView;
1449
+ }
1450
+ /**
1451
+ * Does any instance currently packed actually REFRACT?
1452
+ *
1453
+ * ⚠️ THE WHOLE POINT OF THIS METHOD is to let a caller skip the scene-colour copy. A copy is a
1454
+ * full-screen blit; paying for one every frame so that a crowd of skin can ignore it is exactly
1455
+ * the cost that must not be added. Read straight off the records the renderer holds, so it cannot
1456
+ * disagree with what is about to be drawn.
1457
+ */
1458
+ needsScene() {
1459
+ return this.refracting;
1350
1460
  }
1351
1461
  allocMergeBuffers() {
1352
1462
  const dev = this.device, U = GPUBufferUsage;
@@ -1468,6 +1578,13 @@ export class GpuCrowdRenderer {
1468
1578
  this.matTex?.destroy();
1469
1579
  this.matTex = null;
1470
1580
  this.ownsMat = false;
1581
+ // Ours, always — the caller never supplies the stand-in. Not freeing it leaks one 1×1 texture
1582
+ // per kit swap, which is small and still a leak.
1583
+ this.dummyScene?.destroy();
1584
+ this.dummyScene = null;
1585
+ this.dummySceneView = null;
1586
+ this.skinArrayView = null;
1587
+ this.lastSceneView = null;
1471
1588
  }
1472
1589
  /**
1473
1590
  * Shape one character into its pool slot. Called at spawn, on a LOD change, and on a slider drag
@@ -1532,6 +1649,15 @@ export class GpuCrowdRenderer {
1532
1649
  const total = validateBuckets(records, byLod, this.lodGpu.length);
1533
1650
  this.buckets = byLod.filter((b) => b.count > 0);
1534
1651
  this.draws = splitByAlpha(records, this.buckets);
1652
+ // ⚠️ Computed HERE, once per upload, not per `needsScene` call — that is asked every frame and
1653
+ // the record set only changes when this runs. One pass over the records the renderer is about to
1654
+ // hold, so the answer cannot disagree with what gets drawn.
1655
+ this.refracting = false;
1656
+ for (let i = 0; i < total; i++)
1657
+ if (REFRACTING_MATERIALS.has(records[i * CROWD_RECORD_FLOATS + CROWD_REC_MATERIAL] ?? 0)) {
1658
+ this.refracting = true;
1659
+ break;
1660
+ }
1535
1661
  if (!total)
1536
1662
  return;
1537
1663
  const dev = this.device;
@@ -1584,7 +1710,16 @@ export class GpuCrowdRenderer {
1584
1710
  frame(enc, colorView, depthView, camVP, sunDir, sunCol, amb, camPos, fog, fogDensity, clear, load = false,
1585
1711
  // Optional sun shadow-receive: pass the terrain's cascade matrices + shadow-map view +
1586
1712
  // comparison sampler and characters sit in the same shadow. Omit all three ⇒ no shadowing.
1587
- lightVP, shadowView, shadowSamp) {
1713
+ lightVP, shadowView, shadowSamp,
1714
+ /**
1715
+ * A COPY of the colour target as it stood before this pass, plus its pixel size, so refracting
1716
+ * materials can sample what is behind a body.
1717
+ *
1718
+ * ⚠️ ONLY WORTH SUPPLYING WHEN `needsScene()` IS TRUE. A copy is a full-screen blit; taking one
1719
+ * every frame for a crowd with no glass in it is exactly the cost that must not be paid. Omit
1720
+ * this and refraction is off — glass falls back to its fresnel rim, which is what 0.14.20 did.
1721
+ */
1722
+ scene) {
1588
1723
  const dev = this.device;
1589
1724
  const ready = this.ensureFrameBindGroups() && this.draws.length > 0;
1590
1725
  // ── SKIN. One dispatch per bucket, BEFORE the render pass. WebGPU orders passes within an
@@ -1616,6 +1751,20 @@ export class GpuCrowdRenderer {
1616
1751
  // csm.x = how many cascades are live. Zero ⇒ shadowFactor's loop exits at once and returns
1617
1752
  // fully lit, which is exactly the no-shadow path.
1618
1753
  u[36] = live;
1754
+ // csm.yz = the viewport in pixels, csm.w = whether the scene copy is real. All three ride spare
1755
+ // components of an existing vec4, so CROWD_U_FLOATS does not move and no caller's uniform
1756
+ // layout changes.
1757
+ u[37] = scene?.width ?? 0;
1758
+ u[38] = scene?.height ?? 0;
1759
+ u[39] = scene ? 1 : 0;
1760
+ // Rebind group 2 only when the scene view actually changed — a steady frame, with or without a
1761
+ // copy, does no bind-group work here.
1762
+ // ⚠️ The dummy VIEW is cached, not recreated. createView() returns a fresh object every call, so
1763
+ // building one here would never equal lastSceneView and would rebuild group 2 on every frame —
1764
+ // the precise per-frame cost this gating exists to avoid.
1765
+ const wantScene = scene?.view ?? this.dummySceneView;
1766
+ if (wantScene && wantScene !== this.lastSceneView)
1767
+ this.buildMatBG(wantScene);
1619
1768
  for (let i = 0; i < live; i++)
1620
1769
  u.set(mats[i], 40 + i * 16);
1621
1770
  dev.queue.writeBuffer(this.uBuf, 0, u);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.14.20",
3
+ "version": "0.14.21",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {