ugly-game 0.14.16 → 0.14.18

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.
@@ -49,6 +49,15 @@ export interface CrowdAssets {
49
49
  boneCount: number;
50
50
  /** Shared skin atlas. The CALLER owns and uploads it; this renderer never decodes anything. */
51
51
  skin: GPUTexture;
52
+ /**
53
+ * Tiling MATERIAL maps — wood grain, brushed metal — as an array texture. The caller owns and
54
+ * uploads it, exactly as with `skin`, and the material table's texture column indexes its layers.
55
+ *
56
+ * Omitted ⇒ a 1×1 white single-layer array is bound and every material draws untextured: metal
57
+ * and plastic still work off the BRDF alone and wood degrades to matte rather than failing. That
58
+ * is what lets this renderer ship before any caller has cooked one.
59
+ */
60
+ material?: GPUTexture;
52
61
  /**
53
62
  * Total vertices each pool holds. This is what BOUNDS VRAM: four pools × 16 bytes × this.
54
63
  * Must be the same budget the slot allocator was constructed with.
@@ -91,7 +100,7 @@ export interface CrowdAssets {
91
100
  wear?: number;
92
101
  }
93
102
  /**
94
- * Floats per instance record: mat4 (16) + tint (4) + layer/paletteSlot/poolSlot/pad (4).
103
+ * Floats per instance record: mat4 (16) + tint (4) + layer/paletteSlot/poolSlot/material (4).
95
104
  *
96
105
  * ⚠️ TWO slots, not one, and they are different KINDS of number. `paletteSlot` is a character
97
106
  * ORDINAL — it multiplies by boneCount to reach that character's bone matrices. `poolSlot` is a
@@ -108,6 +117,36 @@ export declare const CROWD_REC_TINT = 16;
108
117
  export declare const CROWD_REC_LAYER = 20;
109
118
  export declare const CROWD_REC_PALETTE_SLOT = 21;
110
119
  export declare const CROWD_REC_POOL_SLOT = 22;
120
+ /**
121
+ * The row of the DRAW shader's material table this instance draws with — `ids.w`, which the layout
122
+ * was already carrying as pad.
123
+ *
124
+ * ⚠️ THE RECORD DOES NOT GROW. A 25th float would move every caller's stride, the pool sizing and
125
+ * the per-frame upload bandwidth in order to carry one small integer, and there was a float here
126
+ * doing nothing. It sits one place past `CROWD_REC_POOL_SLOT`, which is a VERTEX OFFSET — see the
127
+ * warning there about what confusing the two looks like.
128
+ */
129
+ export declare const CROWD_REC_MATERIAL = 23;
130
+ /**
131
+ * Rows of the DRAW shader's material table, by name.
132
+ *
133
+ * ⚠️ Exported so a caller names a material instead of hardcoding an integer — the same reason
134
+ * `CROWD_REC_*` exists. The WGSL `MATS` array is the only other statement of this list, and
135
+ * `gpuCrowd.gpu.mjs` checks the two against each other on a real device.
136
+ *
137
+ * ⚠️ `skin` is 0 AND ITS ROW IS ALL ZEROS. That is what makes an instance which never sets a
138
+ * material draw exactly what it drew before materials existed — asserted as pixel equality in the
139
+ * GPU harness rather than argued here.
140
+ */
141
+ export declare const CROWD_MATERIALS: {
142
+ readonly skin: 0;
143
+ readonly plastic: 1;
144
+ readonly metal: 2;
145
+ readonly glass: 3;
146
+ readonly wood: 4;
147
+ };
148
+ /** Rows in the WGSL `MATS` table — the bound `writeCrowdRecord` checks a material against. */
149
+ export declare const CROWD_MATERIAL_COUNT = 5;
111
150
  /** Which LOD bucket a contiguous run of instance records belongs to. */
112
151
  export interface CrowdBucket {
113
152
  lod: number;
@@ -235,7 +274,7 @@ export declare function validateBuckets(records: Float32Array, byLod: CrowdBucke
235
274
  * `splitByAlpha` reads to route an instance to the blended pipeline, so an alpha below 1 needs
236
275
  * nothing else set anywhere.
237
276
  */
238
- export declare function writeCrowdRecord(out: Float32Array, at: number, model: ArrayLike<number>, tint: ArrayLike<number>, layer: number, paletteSlot: number, poolSlot: number): void;
277
+ export declare function writeCrowdRecord(out: Float32Array, at: number, model: ArrayLike<number>, tint: ArrayLike<number>, layer: number, paletteSlot: number, poolSlot: number, material?: number): void;
239
278
  /** One `drawIndexed` — a maximal run of records at one LOD that are all opaque or all blended. */
240
279
  export interface CrowdDraw {
241
280
  lod: number;
@@ -431,6 +470,13 @@ export declare const CROWD_BINDINGS: {
431
470
  readonly sampler: {
432
471
  readonly type: "filtering";
433
472
  };
473
+ }, {
474
+ readonly binding: 2;
475
+ readonly visibility: 2;
476
+ readonly texture: {
477
+ readonly sampleType: "float";
478
+ readonly viewDimension: "2d-array";
479
+ };
434
480
  }];
435
481
  /**
436
482
  * group 3 — the pooled geometry and the instance records, per rung.
@@ -464,6 +510,12 @@ export declare const CROWD_BINDINGS: {
464
510
  readonly buffer: {
465
511
  readonly type: "read-only-storage";
466
512
  };
513
+ }, {
514
+ readonly binding: 4;
515
+ readonly visibility: 1;
516
+ readonly buffer: {
517
+ readonly type: "read-only-storage";
518
+ };
467
519
  }];
468
520
  };
469
521
  /**
@@ -553,6 +605,16 @@ export declare class GpuCrowdRenderer {
553
605
  private skinSamp;
554
606
  /** group 2, rebuilt only when the kit's atlas changes. */
555
607
  private matBG;
608
+ /**
609
+ * The material atlas actually bound — the caller's, or the 1×1 white stand-in.
610
+ *
611
+ * ⚠️ `ownsMat` is the whole point of the pair. The skin texture is destroyed by nobody here
612
+ * because the CALLER owns it (see `releaseAssets`), but the white fallback is ours and leaks a
613
+ * texture per kit swap if it is not freed. Tracking which of the two is bound is the only way to
614
+ * free exactly one of them.
615
+ */
616
+ private matTex;
617
+ private ownsMat;
556
618
  private plan;
557
619
  /** The CPU-side morph library. It never reaches the GPU — see `mergeTargets`. */
558
620
  private targets;
@@ -25,7 +25,7 @@
25
25
  // number of cascades than the ground they stand on.
26
26
  import { MAX_CASCADES } from './gpuSkin';
27
27
  /**
28
- * Floats per instance record: mat4 (16) + tint (4) + layer/paletteSlot/poolSlot/pad (4).
28
+ * Floats per instance record: mat4 (16) + tint (4) + layer/paletteSlot/poolSlot/material (4).
29
29
  *
30
30
  * ⚠️ TWO slots, not one, and they are different KINDS of number. `paletteSlot` is a character
31
31
  * ORDINAL — it multiplies by boneCount to reach that character's bone matrices. `poolSlot` is a
@@ -42,6 +42,36 @@ export const CROWD_REC_TINT = 16;
42
42
  export const CROWD_REC_LAYER = 20;
43
43
  export const CROWD_REC_PALETTE_SLOT = 21;
44
44
  export const CROWD_REC_POOL_SLOT = 22;
45
+ /**
46
+ * The row of the DRAW shader's material table this instance draws with — `ids.w`, which the layout
47
+ * was already carrying as pad.
48
+ *
49
+ * ⚠️ THE RECORD DOES NOT GROW. A 25th float would move every caller's stride, the pool sizing and
50
+ * the per-frame upload bandwidth in order to carry one small integer, and there was a float here
51
+ * doing nothing. It sits one place past `CROWD_REC_POOL_SLOT`, which is a VERTEX OFFSET — see the
52
+ * warning there about what confusing the two looks like.
53
+ */
54
+ export const CROWD_REC_MATERIAL = 23;
55
+ /**
56
+ * Rows of the DRAW shader's material table, by name.
57
+ *
58
+ * ⚠️ Exported so a caller names a material instead of hardcoding an integer — the same reason
59
+ * `CROWD_REC_*` exists. The WGSL `MATS` array is the only other statement of this list, and
60
+ * `gpuCrowd.gpu.mjs` checks the two against each other on a real device.
61
+ *
62
+ * ⚠️ `skin` is 0 AND ITS ROW IS ALL ZEROS. That is what makes an instance which never sets a
63
+ * material draw exactly what it drew before materials existed — asserted as pixel equality in the
64
+ * GPU harness rather than argued here.
65
+ */
66
+ export const CROWD_MATERIALS = {
67
+ skin: 0,
68
+ plastic: 1,
69
+ metal: 2,
70
+ glass: 3,
71
+ wood: 4,
72
+ };
73
+ /** Rows in the WGSL `MATS` table — the bound `writeCrowdRecord` checks a material against. */
74
+ export const CROWD_MATERIAL_COUNT = 5;
45
75
  // ─────────────────────────────────────────────────────────────────────────────
46
76
  // PURE ARITHMETIC. Everything below this line down to the WGSL is a plain function over plain
47
77
  // arrays, with no GPUDevice anywhere — because there is no GPU in CI and "the proof is a picture"
@@ -345,7 +375,10 @@ export function validateBuckets(records, byLod, lodCount) {
345
375
  * `splitByAlpha` reads to route an instance to the blended pipeline, so an alpha below 1 needs
346
376
  * nothing else set anywhere.
347
377
  */
348
- export function writeCrowdRecord(out, at, model, tint, layer, paletteSlot, poolSlot) {
378
+ export function writeCrowdRecord(out, at, model, tint, layer, paletteSlot, poolSlot,
379
+ // ⚠️ OPTIONAL AND LAST, so every call site written before materials existed keeps both its
380
+ // meaning and its output. 0 is `skin`, whose table row is the all-zero one.
381
+ material = 0) {
349
382
  if (model.length !== 16)
350
383
  throw new Error(`writeCrowdRecord: model has ${model.length} floats, expected a column-major 16`);
351
384
  if (tint.length !== 4)
@@ -359,7 +392,15 @@ export function writeCrowdRecord(out, at, model, tint, layer, paletteSlot, poolS
359
392
  out[at + CROWD_REC_LAYER] = layer;
360
393
  out[at + CROWD_REC_PALETTE_SLOT] = paletteSlot;
361
394
  out[at + CROWD_REC_POOL_SLOT] = poolSlot;
362
- out[at + 23] = 0;
395
+ // ⚠️ Checked, not clamped. The shader indexes `MATS` with `u32(ids.w)` and WGSL does not
396
+ // bounds-check a constant array, so an out-of-range row reads whatever follows the table — which
397
+ // draws SOMETHING, plausibly, and is untraceable from the picture. A fraction is just as bad:
398
+ // u32(1.5) is a row nobody chose.
399
+ if (!Number.isInteger(material) ||
400
+ material < 0 ||
401
+ material >= CROWD_MATERIAL_COUNT)
402
+ throw new Error(`writeCrowdRecord: material ${material} is not one of the ${CROWD_MATERIAL_COUNT} rows in the shader's table`);
403
+ out[at + CROWD_REC_MATERIAL] = material;
363
404
  }
364
405
  /**
365
406
  * Split each bucket into maximal runs of the same blend class, preserving order.
@@ -550,6 +591,19 @@ export const CROWD_BINDINGS = {
550
591
  texture: { sampleType: 'float', viewDimension: '2d-array' },
551
592
  },
552
593
  { binding: 1, visibility: VIS_FRAGMENT, sampler: { type: 'filtering' } },
594
+ // The MATERIAL atlas: tiling maps (wood grain, brushed metal), sampled TRIPLANAR from the
595
+ // bind-space rest position rather than with the body's own UVs — that atlas is a packing
596
+ // layout, so a grain sampled through it breaks at every island seam and runs a different
597
+ // direction on each island.
598
+ //
599
+ // ⚠️ ARRAY-dimensioned even at one layer, and it shares binding 1's sampler. A 1x1 white array
600
+ // is bound when a caller supplies none, so white x colour = colour and the untextured path is
601
+ // byte-identical to before this existed.
602
+ {
603
+ binding: 2,
604
+ visibility: VIS_FRAGMENT,
605
+ texture: { sampleType: 'float', viewDimension: '2d-array' },
606
+ },
553
607
  ],
554
608
  /**
555
609
  * group 3 — the pooled geometry and the instance records, per rung.
@@ -580,6 +634,15 @@ export const CROWD_BINDINGS = {
580
634
  visibility: VIS_VERTEX,
581
635
  buffer: { type: 'read-only-storage' },
582
636
  },
637
+ // The rung's BIND-SPACE rest positions — already uploaded for the morph pass, now visible to
638
+ // the draw as well so the fragment shader has a stable object-space coordinate to project a
639
+ // material texture from. Indexed by vertex index, exactly as `uvs` is: it is a property of the
640
+ // RUNG, not of an instance, so this costs one bind-group entry and no memory at all.
641
+ {
642
+ binding: 4,
643
+ visibility: VIS_VERTEX,
644
+ buffer: { type: 'read-only-storage' },
645
+ },
583
646
  ],
584
647
  };
585
648
  /**
@@ -736,10 +799,17 @@ struct U { viewProj: mat4x4f, sun: vec4f, sunCol: vec4f, amb: vec4f, cam: vec4f,
736
799
  @group(1) @binding(1) var shadowSamp: sampler_comparison;
737
800
  @group(2) @binding(0) var skinTex: texture_2d_array<f32>;
738
801
  @group(2) @binding(1) var skinSamp: sampler;
802
+ // The MATERIAL atlas - tiling maps, sampled TRIPLANAR from the bind-space rest position. A 1x1
803
+ // white array is bound when a caller supplies none, so white x colour = colour and the untextured
804
+ // path is byte-identical to before this existed.
805
+ @group(2) @binding(2) var matTex: texture_2d_array<f32>;
739
806
  @group(3) @binding(0) var<storage,read> def: array<vec4f>;
740
807
  @group(3) @binding(1) var<storage,read> defN: array<vec4f>;
741
808
  @group(3) @binding(2) var<storage,read> uvs: array<vec2f>;
742
809
  @group(3) @binding(3) var<storage,read> recs: array<Rec>;
810
+ // BIND-SPACE rest positions, per rung. Not the deformed pool: a projection from moving geometry
811
+ // makes the pattern swim, and the grain would crawl across a walking body.
812
+ @group(3) @binding(4) var<storage,read> restPos: array<vec4f>;
743
813
  struct VOut {
744
814
  @builtin(position) pos: vec4f,
745
815
  @location(0) world: vec3f,
@@ -749,6 +819,12 @@ struct VOut {
749
819
  // FLAT. An atlas layer interpolated across a triangle is a fractional layer index, and every
750
820
  // fragment but the provoking vertex samples a blend of two skin tones - or nothing.
751
821
  @location(4) @interpolate(flat) layer: u32,
822
+ // BIND-SPACE rest position, for the triplanar projection - and for the DERIVATIVES the blend
823
+ // weights come from. See the fragment shader for why it cannot be a normal from a buffer.
824
+ @location(5) rest: vec3f,
825
+ // FLAT, for the same reason as the layer: a material index interpolated across a triangle is a
826
+ // fraction, and u32() of it is a row of the table nobody chose.
827
+ @location(6) @interpolate(flat) mat: u32,
752
828
  };
753
829
  // NO VERTEX BUFFERS. vi indexes the RUNG (uvs, and the pool relative to this instance's slot);
754
830
  // instance_index already includes drawIndexed's firstInstance, so it indexes records directly.
@@ -765,6 +841,11 @@ struct VOut {
765
841
  o.uv = uvs[vi];
766
842
  o.tint = r.tint;
767
843
  o.layer = u32(r.ids.x);
844
+ // ⚠️ restPos is indexed by vi (the RUNG), not by src (the pool). The pool holds this instance's
845
+ // DEFORMED copy; the rung holds the one shared bind-pose mesh, which is what a projection has to
846
+ // be anchored to if the pattern is to stay still while the body moves.
847
+ o.rest = restPos[vi].xyz;
848
+ o.mat = u32(r.ids.w);
768
849
  return o;
769
850
  }
770
851
  // PCF 3x3, mirroring gpuShadow.shadowFactor and gpuSkin's copy of it so a character sits in the
@@ -796,11 +877,117 @@ fn shadowFactor(world: vec3f, ndl: f32) -> f32 {
796
877
  }
797
878
  return 1.0;
798
879
  }
880
+ // 1 / p99(luma) over the twelve cooked MakeHuman skins - the gain that turns the atlas into a
881
+ // luminance DETAIL map whose midpoint sits near 1, so a colour picked off a swatch arrives at
882
+ // roughly the colour that was picked. Without it a mid-bright pick lands dark and the control reads
883
+ // as broken; the hair path records the same trap from the other side in HAIR_COLOURS.
884
+ //
885
+ // MEASURED, not guessed: 12/12 skins, 50,331,648 opaque texels, median 0.4102, p90 0.7530,
886
+ // p99 0.8046 - so 1/0.8046 = 1.2428. Re-measure with all-mine-sky's tools/creature/skinLuma.mts if
887
+ // the skin roster ever changes. p99 rather than max, because one specular texel in an eyeball
888
+ // should not set the gain for twelve whole bodies.
889
+ //
890
+ // ⚠️ Reachable only when desat > 0, so material 0 is unaffected by its value.
891
+ const LUMA_GAIN: f32 = 1.2428;
892
+ // ONE ROW PER MATERIAL, two vec4s each: (spec, exponent, fresnel, metal) then
893
+ // (desat, texture layer, tile scale, pad).
894
+ //
895
+ // ⚠️ ROW 0 IS ALL ZEROS with a -1 texture layer, and that is the load-bearing part. With spec 0,
896
+ // fresnel 0, metal 0, desat 0 and no texture, everything below collapses to
897
+ // base * (amb + d * sunCol * sh) - the shader exactly as it was before materials existed. That is
898
+ // what makes "nothing already shipped moved" a pixel-equality assertion instead of an argument, and
899
+ // it is why skin gets no sheen even though a little would flatter it. Giving skin a specular lobe
900
+ // is a separate decision that should be made by looking at it.
901
+ //
902
+ // exp and scale are written as 1 on the rows that do not use them: a WGSL const array has no empty
903
+ // cell, and pow(0, 0) is a value nobody should have to reason about.
904
+ const MATS = array<vec4f, 10>(
905
+ vec4f(0.00, 1.0, 0.00, 0.0), vec4f(0.00, -1.0, 1.000, 0.0),
906
+ vec4f(0.35, 64.0, 0.50, 0.0), vec4f(0.60, -1.0, 1.000, 0.0),
907
+ vec4f(0.90, 128.0, 0.80, 1.0), vec4f(1.00, 0.0, 0.333, 0.0),
908
+ vec4f(0.90, 256.0, 1.00, 0.0), vec4f(1.00, -1.0, 1.000, 0.0),
909
+ vec4f(0.08, 16.0, 0.15, 0.0), vec4f(1.00, 1.0, 0.500, 0.0),
910
+ );
911
+ fn luma(c: vec3f) -> f32 { return dot(c, vec3f(0.2126, 0.7152, 0.0722)); }
912
+ // TRIPLANAR: three samples of the same tiling map, blended by the bind-space normal.
913
+ //
914
+ // ⚠️ The body's own UVs cannot be used for this. That atlas is a PACKING LAYOUT - islands at
915
+ // independent scales and rotations - so a grain sampled through it breaks at every island seam and
916
+ // runs a different direction on each. The hair path paid for this lesson already.
917
+ // ⚠️ textureSampleGrad, NOT textureSample, and the gradients are handed in from OUTSIDE the branch
918
+ // that calls this. textureSample takes implicit derivatives, which WGSL only permits in uniform
919
+ // control flow - and the material row is per instance, so "sample only when this material has a
920
+ // texture" is by definition non-uniform. Dawn rejects the module outright:
921
+ //
922
+ // 'textureSample' must only be called from uniform control flow
923
+ //
924
+ // The two alternatives are worse. Sampling unconditionally makes skin - the row that is supposed to
925
+ // cost exactly what it always did - pay for three texture fetches it never uses. textureSampleLevel
926
+ // would drop the mip chain, and a tiling map with no mips on a thousand distant characters aliases
927
+ // into a shimmering mess. Explicit gradients keep both the branch and the mips.
928
+ fn triplanar(layer: i32, p: vec3f, dx: vec3f, dy: vec3f, n: vec3f) -> vec3f {
929
+ let w0 = pow(abs(n), vec3f(4.0));
930
+ let w = w0 / max(w0.x + w0.y + w0.z, 1e-5);
931
+ let x = textureSampleGrad(matTex, skinSamp, p.yz, layer, dx.yz, dy.yz).rgb;
932
+ let y = textureSampleGrad(matTex, skinSamp, p.zx, layer, dx.zx, dy.zx).rgb;
933
+ let z = textureSampleGrad(matTex, skinSamp, p.xy, layer, dx.xy, dy.xy).rgb;
934
+ return x * w.x + y * w.y + z * w.z;
935
+ }
799
936
  @fragment fn fs(i: VOut) -> @location(0) vec4f {
800
- let d = clamp(dot(normalize(i.n), -normalize(u.sun.xyz)), 0.0, 1.0);
937
+ let a = MATS[i.mat * 2u];
938
+ let b = MATS[i.mat * 2u + 1u];
939
+ let n = normalize(i.n);
940
+ let l = -normalize(u.sun.xyz);
941
+ let d = clamp(dot(n, l), 0.0, 1.0);
801
942
  let sh = mix(1.0, shadowFactor(i.world, d), u.sun.w);
802
- let base = textureSample(skinTex, skinSamp, i.uv, i.layer).rgb * i.tint.rgb;
803
- let lit = base * (u.amb.xyz + d * u.sunCol.xyz * sh);
943
+
944
+ // The skin atlas is demoted toward a LUMINANCE DETAIL map as desat rises, so a chosen colour is
945
+ // the colour rather than a muddy multiple of a photograph of somebody's face. What survives at
946
+ // desat 1 is pores, creases and anatomical shading - which is what makes a bronze figure read as
947
+ // a figure rather than as a smooth mannequin.
948
+ let skinS = textureSample(skinTex, skinSamp, i.uv, i.layer).rgb;
949
+ let detail = mix(skinS, vec3f(clamp(luma(skinS) * LUMA_GAIN, 0.0, 1.0)), b.x);
950
+ // ⚠️ The blend normal comes from the DERIVATIVES of the interpolated rest position, not from any
951
+ // normal in a buffer. There is no bind-pose normal to bind - normals are recomputed after the
952
+ // morph from the adjacency arrays - and the post-morph normal ROTATES WITH THE LIMB, so using it
953
+ // would make the grain swim on a raised arm. Faceting here is invisible: it only picks between
954
+ // three samples of the same tiling map.
955
+ //
956
+ // ⚠️ Both derivatives are taken HERE, at the top level of fs, and used twice — once for the blend
957
+ // normal and once as the explicit gradients triplanar samples with. Taking either inside the
958
+ // branch below is the same uniformity violation described on triplanar.
959
+ let rdx = dpdx(i.rest);
960
+ let rdy = dpdy(i.rest);
961
+ // ⚠️ GUARDED. A triangle whose rest position is constant in screen space - a degenerate or
962
+ // edge-on one - gives cross(0, 0), and normalize(vec3(0)) is NaN. A NaN here does not merely pick
963
+ // a wrong plane: pow(abs(NaN)) is NaN, the weights are NaN, and the whole fragment comes out NaN.
964
+ // The same trap the skin compute pass guards its normal against, three hundred lines up.
965
+ let cr = cross(rdx, rdy);
966
+ let crl = length(cr);
967
+ let bn = select(vec3f(0.0, 0.0, 1.0), cr / crl, crl > 1e-20);
968
+ var matC = vec3f(1.0);
969
+ if (i32(b.y) >= 0) { matC = triplanar(i32(b.y), i.rest * b.z, rdx * b.z, rdy * b.z, bn); }
970
+ let base = detail * matC * i.tint.rgb;
971
+
972
+ let v = normalize(u.cam.xyz - i.world);
973
+ // ⚠️ THE HALF-VECTOR IS GUARDED, and this one would have poisoned MATERIAL 0. When the view and
974
+ // the light oppose each other exactly - a backlit surface, and the configuration the GPU harness
975
+ // happens to set up - l + v is the zero vector and normalize() returns NaN. NaN then survives
976
+ // being multiplied by a zero specular strength, because NaN * 0 is NaN, so the all-zero row that
977
+ // is supposed to reproduce the old shader exactly would render as NaN instead.
978
+ //
979
+ // Zero is also the physically right answer: if the light and the eye are exactly opposed there is
980
+ // no specular reflection heading toward the camera.
981
+ let hv = l + v;
982
+ let hl = length(hv);
983
+ let ndh = select(0.0, dot(n, hv / hl), hl > 1e-6);
984
+ let fres = a.z * pow(1.0 - clamp(dot(n, v), 0.0, 1.0), 5.0);
985
+ // A metal tints its own highlight and keeps almost no diffuse. That is the whole difference
986
+ // between gold and yellow plastic with a white highlight sitting on it.
987
+ let specCol = mix(vec3f(1.0), base, a.w);
988
+ let spec = (a.x + fres) * pow(max(ndh, 0.0), a.y) * specCol * u.sunCol.xyz * sh;
989
+ let lit = base * (1.0 - a.w) * (u.amb.xyz + d * u.sunCol.xyz * sh) + spec;
990
+
804
991
  let dist = length(i.world - u.cam.xyz);
805
992
  let f = clamp(1.0 - exp(-dist * u.fog.w), 0.0, 1.0);
806
993
  // tint.w is the opacity. It is 1 for everyone on the opaque pipeline, where the target has no
@@ -846,6 +1033,16 @@ export class GpuCrowdRenderer {
846
1033
  skinSamp;
847
1034
  /** group 2, rebuilt only when the kit's atlas changes. */
848
1035
  matBG = null;
1036
+ /**
1037
+ * The material atlas actually bound — the caller's, or the 1×1 white stand-in.
1038
+ *
1039
+ * ⚠️ `ownsMat` is the whole point of the pair. The skin texture is destroyed by nobody here
1040
+ * because the CALLER owns it (see `releaseAssets`), but the white fallback is ours and leaks a
1041
+ * texture per kit swap if it is not freed. Tracking which of the two is bound is the only way to
1042
+ * free exactly one of them.
1043
+ */
1044
+ matTex = null;
1045
+ ownsMat = false;
849
1046
  plan = null;
850
1047
  /** The CPU-side morph library. It never reaches the GPU — see `mergeTargets`. */
851
1048
  targets = [];
@@ -1047,6 +1244,28 @@ export class GpuCrowdRenderer {
1047
1244
  drawBG: null,
1048
1245
  };
1049
1246
  });
1247
+ // The material atlas, or a 1×1 white stand-in for a caller that has none.
1248
+ //
1249
+ // ⚠️ ARRAY-dimensioned even at one layer, for the same reason the skin atlas is: the shader
1250
+ // samples texture_2d_array unconditionally, and a plain 2d view against that binding is a
1251
+ // validation error rather than a graceful fallback.
1252
+ //
1253
+ // ⚠️ WHITE, not black or grey. The fragment shader MULTIPLIES this over the base colour, so
1254
+ // white is the identity and an untextured material is byte-identical to one that never sampled.
1255
+ if (a.material) {
1256
+ this.matTex = a.material;
1257
+ this.ownsMat = false;
1258
+ }
1259
+ else {
1260
+ const t = dev.createTexture({
1261
+ size: { width: 1, height: 1, depthOrArrayLayers: 1 },
1262
+ format: 'rgba8unorm',
1263
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
1264
+ });
1265
+ dev.queue.writeTexture({ texture: t }, new Uint8Array([255, 255, 255, 255]), { bytesPerRow: 4 }, { width: 1, height: 1 });
1266
+ this.matTex = t;
1267
+ this.ownsMat = true;
1268
+ }
1050
1269
  // group 2 is the kit's atlas, so it changes exactly when the kit does. ARRAY-dimensioned even
1051
1270
  // for a single-layer texture: the shader samples texture_2d_array unconditionally, and a plain
1052
1271
  // 2d view against that binding is a validation error rather than a fallback.
@@ -1055,6 +1274,10 @@ export class GpuCrowdRenderer {
1055
1274
  entries: [
1056
1275
  { binding: 0, resource: a.skin.createView({ dimension: '2d-array' }) },
1057
1276
  { binding: 1, resource: this.skinSamp },
1277
+ {
1278
+ binding: 2,
1279
+ resource: this.matTex.createView({ dimension: '2d-array' }),
1280
+ },
1058
1281
  ],
1059
1282
  });
1060
1283
  this.rebuildLodBindGroups();
@@ -1131,6 +1354,11 @@ export class GpuCrowdRenderer {
1131
1354
  { binding: 1, resource: { buffer: pools.defN } },
1132
1355
  { binding: 2, resource: { buffer: l.uv } },
1133
1356
  { binding: 3, resource: { buffer: inst } },
1357
+ // ⚠️ `l.pos`, the RUNG's bind-pose mesh — NOT `pools.rest`. The pool holds a per-instance
1358
+ // copy at that instance's slot offset; this buffer is the one shared unmorphed mesh, and
1359
+ // it is what the vertex shader indexes by `vi`. Binding the pool here would index it by a
1360
+ // rung-relative vertex and project every character from somebody else's geometry.
1361
+ { binding: 4, resource: { buffer: l.pos } },
1134
1362
  ],
1135
1363
  });
1136
1364
  }
@@ -1168,6 +1396,13 @@ export class GpuCrowdRenderer {
1168
1396
  // ⚠️ NOT the skin texture. The CALLER uploaded it and still owns it — the same rule gpuProps
1169
1397
  // learned the hard way, where a second setModels freed the caller's textures and then bound them.
1170
1398
  this.skin = null;
1399
+ // ⚠️ ONLY the white stand-in, and only when WE made it. A caller-supplied material atlas is the
1400
+ // caller's, exactly like the skin above; destroying it here is that same gpuProps bug wearing a
1401
+ // different hat. Not freeing our own leaks a texture per kit swap.
1402
+ if (this.ownsMat)
1403
+ this.matTex?.destroy();
1404
+ this.matTex = null;
1405
+ this.ownsMat = false;
1171
1406
  }
1172
1407
  /**
1173
1408
  * Shape one character into its pool slot. Called at spawn, on a LOD change, and on a slider drag
@@ -66,6 +66,24 @@ export interface PropMesh {
66
66
  * map is a single depth buffer with nowhere to put a partial occluder.
67
67
  */
68
68
  alpha?: number;
69
+ /**
70
+ * Alpha-test cutoff: a fragment whose ALBEDO alpha is below this is discarded. 0 (the default)
71
+ * tests nothing.
72
+ *
73
+ * This is for cut-out sheets — hair cards, leaf planes, grass blades — where the mesh is a handful
74
+ * of rectangles and the shape lives entirely in the texture's alpha. Without it the texture's RGB
75
+ * is drawn over the whole rectangle and a hairstyle renders as a stack of opaque boxes.
76
+ *
77
+ * ⚠️ NOT `alpha`, and not a substitute for it. `alpha < 1` is a translucent MATERIAL: it moves the
78
+ * model to the blended pipeline with depth writes off, which for a cut-out sheet is wrong twice
79
+ * over — the opaque parts stop writing depth, so sheets composite in submission order and a
80
+ * character's fringe draws through the back of their own head.
81
+ *
82
+ * ⚠️ A cut-out model casts NO SUN SHADOW, exactly like a translucent one: `shadowPass` is depth-only
83
+ * and has no albedo bound, so it can only cast the rectangles. A missing shadow is a much smaller
84
+ * lie than a box-shaped one across the face.
85
+ */
86
+ cutout?: number;
69
87
  }
70
88
  /**
71
89
  * Per-instance deformation. Every field is neutral at its default, so an instance that supplies none
@@ -105,6 +123,20 @@ export interface PropDeform {
105
123
  * sway at all either way.
106
124
  */
107
125
  sway?: number;
126
+ /**
127
+ * Per-instance colour multiply, `[1,1,1]` being the mesh as authored.
128
+ *
129
+ * ⚠️ PER INSTANCE, unlike `PropMesh.alpha`, and that is the whole point: `valueJitter` next to it
130
+ * multiplies vertex colour by a SCALAR, so it can make a plant lighter or darker and can never
131
+ * make it a different colour. A crowd of characters whose hair is black, brown, blonde, auburn and
132
+ * grey is one greyscale mesh and five hues — expressible here, and expressible as five extra
133
+ * MODELS otherwise, which is five more copies of the geometry and five more draw calls per style.
134
+ *
135
+ * ⚠️ Defaults to white rather than to zero. A zero-filled instance record would multiply every
136
+ * existing prop to black, which is why `writeDeform` writes the ones explicitly instead of
137
+ * relying on the buffer's initial contents.
138
+ */
139
+ tint?: readonly [number, number, number];
108
140
  }
109
141
  export interface PropInstance {
110
142
  model: number;
@@ -20,12 +20,14 @@ struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<
20
20
  // d0 = (heightScale, girth, taper, 1/sourceHeight)
21
21
  // d1 = (bend, bendDir, twist, droop)
22
22
  // d2 = (yaw, valueJitter, 1/halfWidth, swayScale)
23
- struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32> };
23
+ // d3 = (tintR, tintG, tintB, -)
24
+ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: vec4<f32> };
24
25
  @group(0) @binding(1) var<storage,read> models: array<Inst>;
25
26
  @group(2) @binding(0) var albedoTex: texture_2d<f32>;
26
27
  @group(2) @binding(1) var albedoSamp: sampler;
27
28
  // PER-MODEL material. Group 2 is already the per-model group (the albedo lives here), so opacity
28
- // rides along rather than needing a fourth group or a dynamic offset. mat.x is alpha.
29
+ // rides along rather than needing a fourth group or a dynamic offset. mat.x is alpha, mat.y is the
30
+ // alpha-test cutoff (0 ⇒ no test, which is every model that predates it).
29
31
  struct Mat { mat: vec4<f32> };
30
32
  @group(2) @binding(2) var<uniform> mtl: Mat;
31
33
  @group(1) @binding(0) var shadowMap: texture_depth_2d_array; // the SAME cascaded sun shadow map the terrain cubes sample
@@ -102,7 +104,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
102
104
  let sc = length(m[0].xyz);
103
105
  world = sway(lp, world, upv, sc * inst.d2.w);
104
106
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
105
- o.c = col * inst.d2.y; o.l = lp; o.uv = uv; return o;
107
+ o.c = col * inst.d2.y * inst.d3.rgb; o.l = lp; o.uv = uv; return o;
106
108
  }
107
109
  // same fixed directional FILL as the terrain cubes (gpuShadow.fixedFill) so plants/rocks read the same 3D shape,
108
110
  // day or night, under one shared light. up.w > 0.5 signals a valid local-up was supplied (else fall back to flat).
@@ -190,7 +192,11 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
190
192
  // Albedo modulates the vertex colour rather than replacing it, so the StyleGuide role tint and the
191
193
  // per-instance hue jitter still act on a textured prop — and an untextured one samples the 1x1
192
194
  // white fallback and is unchanged.
193
- var base = i.c * textureSample(albedoTex, albedoSamp, i.uv).rgb;
195
+ let tex = textureSample(albedoTex, albedoSamp, i.uv);
196
+ // ALPHA TEST, before any shading is paid for. mtl.mat.y is 0 for every model that does not ask for
197
+ // one, and tex.a is 1 on the white fallback, so an untextured or opaque model never discards.
198
+ if (tex.a < mtl.mat.y) { discard; }
199
+ var base = i.c * tex.rgb;
194
200
  if (u.surf.x > 0.0) {
195
201
  let grain = triplanar(i.l, N, u.surf.x);
196
202
  base = base * (1.0 - u.surf.y * 0.5 + u.surf.y * grain);
@@ -211,7 +217,10 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
211
217
  const OCCLUDER = /* wgsl */ `
212
218
  struct OU { lightVP: mat4x4<f32>, wind: vec4<f32> };
213
219
  @group(0) @binding(0) var<uniform> o: OU;
214
- struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32> };
220
+ // ⚠️ The SAME layout as the draw pass's Inst, d3 included. Both shaders index the same storage
221
+ // buffer, so a struct that is one vec4 shorter here does not read a shorter instance — it reads the
222
+ // NEXT one's matrix, and every shadow in the scene lands under the wrong prop.
223
+ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: vec4<f32> };
215
224
  @group(0) @binding(1) var<storage,read> models: array<Inst>;
216
225
  // The occluder must apply the identical DEFORM as well as the identical sway. A deformed plant whose
217
226
  // shadow is cast from its undeformed silhouette is the same detachment bug as swaying leaves over a
@@ -254,8 +263,15 @@ fn deformLocal(p: vec3<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>) -> vec
254
263
  }
255
264
  return o.lightVP * vec4(world, 1.0);
256
265
  }`;
257
- /** Floats per instance in the storage buffer: mat4 + d0 + d1 + d2. */
258
- const INST_FLOATS = 28;
266
+ /**
267
+ * Floats per instance in the storage buffer: mat4 + d0 + d1 + d2 + d3.
268
+ *
269
+ * ⚠️ Stated in THREE places — here, `Inst` in the draw shader and `Inst` in the occluder. All three
270
+ * describe the same bytes and there is no mechanism that keeps them agreeing, so a field added to
271
+ * one must be added to all three in the same edit. A short struct does not read a truncated
272
+ * instance; it reads into the next one.
273
+ */
274
+ const INST_FLOATS = 32;
259
275
  export class GpuPropsRenderer {
260
276
  device;
261
277
  pipe;
@@ -581,13 +597,15 @@ export class GpuPropsRenderer {
581
597
  : this.uploadAlbedo(m.albedo)
582
598
  : null;
583
599
  const alpha = m.alpha ?? 1;
600
+ const cutout = m.cutout ?? 0;
584
601
  const matBuf = dev.createBuffer({
585
602
  size: 16,
586
603
  usage: U.UNIFORM | U.COPY_DST,
587
604
  });
588
- dev.queue.writeBuffer(matBuf, 0, new Float32Array([alpha, 0, 0, 0]));
605
+ dev.queue.writeBuffer(matBuf, 0, new Float32Array([alpha, cutout, 0, 0]));
589
606
  return {
590
607
  alpha,
608
+ cutout,
591
609
  matBuf,
592
610
  ownsTex,
593
611
  posB: mk(m.positions, U.VERTEX | U.COPY_DST),
@@ -700,6 +718,14 @@ export class GpuPropsRenderer {
700
718
  // none at all — and the opaque one is the more obviously wrong picture.
701
719
  if (mdl.alpha < 1)
702
720
  continue;
721
+ // ...and neither does a CUT-OUT model, for a different reason: this pass is depth-only and has
722
+ // no albedo bound, so it cannot run the alpha test the draw pass runs. What it would cast is
723
+ // the un-tested rectangles — a hairstyle's shadow as a stack of boxes across the face, which is
724
+ // far more obviously wrong than no shadow at all. Binding the texture here would fix it and is
725
+ // a bigger change than this one: the occluder would need a per-model bind group and a second
726
+ // pipeline for the tested case.
727
+ if (mdl.cutout > 0)
728
+ continue;
703
729
  pass.setBindGroup(0, bg);
704
730
  pass.setVertexBuffer(0, mdl.posB);
705
731
  pass.setIndexBuffer(mdl.idxB, 'uint32');
@@ -832,6 +858,14 @@ function writeDeform(out, o, d, e) {
832
858
  out[o + 9] = d?.valueJitter ?? 1;
833
859
  out[o + 10] = e.invHalfW;
834
860
  out[o + 11] = d?.sway ?? 1;
861
+ // ⚠️ Written unconditionally, ones and all. `arrays[m]` is a fresh zero-filled Float32Array every
862
+ // frame, so an absent tint left unwritten is BLACK, not neutral — and it would be black for every
863
+ // prop in the world, none of which has ever heard of a tint.
864
+ const t = d?.tint;
865
+ out[o + 12] = t ? t[0] : 1;
866
+ out[o + 13] = t ? t[1] : 1;
867
+ out[o + 14] = t ? t[2] : 1;
868
+ out[o + 15] = 0;
835
869
  }
836
870
  // column-major identity mat4, used for lightVP when shadow-receive is off
837
871
  const IDENTITY4 = new Float32Array([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.14.16",
3
+ "version": "0.14.18",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {