ugly-game 0.14.22 → 0.14.24

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.
@@ -1118,9 +1118,15 @@ fn cylindrical(layer: i32, p: vec3f, dx: vec3f, dy: vec3f) -> vec3f {
1118
1118
  // the body.
1119
1119
  let suv = clamp(here + off, vec2f(0.0), vec2f(1.0));
1120
1120
  let behind = textureSampleLevel(sceneTex, skinSamp, suv, 0.0).rgb;
1121
- // The transmitted background takes the glass's own colour, then the lit surface is layered over
1122
- // it by the SAME fresnel rim that drove the alpha: clear in the middle, bright at the edge.
1123
- outCol = mix(behind * base, lit, clamp(c.x * rim, 0.0, 1.0));
1121
+ // ⚠️ TINTED BY THE COLOUR, NOT MULTIPLIED BY base, and that distinction is the whole
1122
+ // difference between glass and a dark blob. base carries the skin atlas's luminance detail -
1123
+ // around 0.5 - and running transmitted light through it halves everything seen through the body,
1124
+ // so the figure came out DARKER than the world behind it. Detail belongs to the surface shading;
1125
+ // what passes through a pane is attenuated only by the pane's own colour.
1126
+ let transmit = behind * i.tint.rgb;
1127
+ // The lit surface is then layered over it by the SAME fresnel rim that drove the alpha: clear in
1128
+ // the middle, bright at the edge.
1129
+ outCol = mix(transmit, lit, clamp(c.x * rim, 0.0, 1.0));
1124
1130
  // ⚠️ ALPHA 1 once we have composited the background OURSELVES. The blended pipeline would
1125
1131
  // otherwise mix our result with the UNDISTORTED scene underneath and half the refraction would
1126
1132
  // be cancelled straight back out. The record still carries tint.w < 1, so splitByAlpha still
@@ -82,6 +82,40 @@ export interface SkinCreature {
82
82
  indices: Uint32Array;
83
83
  palette: Float32Array;
84
84
  model: Float32Array;
85
+ /**
86
+ * Draw this creature MANY times — one mesh, one draw call, a skeleton each.
87
+ *
88
+ * ⚠️ WHAT THIS IS FOR, and why a crowd could not have it before. Every creature in `setCreatures`
89
+ * costs its own compute dispatch, its own `drawIndexed`, five vertex-buffer binds and two
90
+ * bind-group sets — and `setCreatures` DESTROYS AND REBUILDS every buffer it owns on each call,
91
+ * which all-mine-sky makes every frame. That is fine for the handful of creatures the API was
92
+ * built for and quadratic misery for a thousand: dressing a 1000-character crowd in a suit and
93
+ * shoes is ~2,000 draws a frame, ~2,000 more in the shadow pass, and ~16,000 buffer
94
+ * create+write pairs. The allocation churn bites before the draw calls do.
95
+ *
96
+ * With `instances`, all the characters wearing the same garment at the same LOD share one set of
97
+ * geometry buffers and one draw, and differ only by a palette and a model matrix — the two things
98
+ * that are genuinely per character.
99
+ *
100
+ * ⚠️ `palettes` IS jointCount MATRICES PER INSTANCE, back to back, and jointCount is derived as
101
+ * `palettes.length / count / 16`. It has to divide exactly; a mismatched pair would silently index
102
+ * one instance's bones through another's offset and every character after the first would wear a
103
+ * skeleton belonging to somebody else.
104
+ *
105
+ * ⚠️ THE SKINNING IS PER INSTANCE BUT THE REST POSE IS SHARED. These instances are the same mesh
106
+ * posed differently — they are NOT per-character shapes. A garment that has to follow a
107
+ * particular BODY's proportions still needs its own conform and its own creature.
108
+ *
109
+ * Omitted ⇒ a single instance drawn exactly as before, through the original pipeline. Every
110
+ * existing caller is untouched.
111
+ */
112
+ instances?: {
113
+ count: number;
114
+ /** `count · jointCount · 16`, column-major, instance-major. */
115
+ palettes: Float32Array;
116
+ /** `count · 16`, column-major world placement per instance. */
117
+ models: Float32Array;
118
+ };
85
119
  }
86
120
  export declare const MAX_CASCADES = 4;
87
121
  export declare class GpuSkinRenderer {
@@ -97,6 +131,16 @@ export declare class GpuSkinRenderer {
97
131
  * `setCreatures` and reused by whichever pipeline draws it.
98
132
  */
99
133
  private blendPipe;
134
+ /**
135
+ * The same two pipelines with the INSTANCED vertex stage — see `VS_INST`.
136
+ *
137
+ * Built unconditionally rather than lazily: a render pipeline is compiled once at construction and
138
+ * a lazy one would compile mid-frame the first time a crowd got dressed, which is a hitch exactly
139
+ * when the scene is busiest.
140
+ */
141
+ private instPipe;
142
+ private instBlendPipe;
143
+ private instBGL;
100
144
  /** The explicit group 0/1/2 layouts, shared by both render pipelines. */
101
145
  private drawBGL;
102
146
  private packed;
@@ -15,13 +15,67 @@ const SKIN = /* wgsl */ `
15
15
  @group(0) @binding(6) var<storage,read> restN: array<vec4f>;
16
16
  @group(0) @binding(7) var<storage,read_write> defN: array<vec4f>;
17
17
  fn rot(m: mat4x4f, v: vec3f) -> vec3f { return mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * v; }
18
+ // ⚠️ ONE PIPELINE FOR BOTH the single and the instanced case, because the single case IS the
19
+ // instanced one with a count of 1. P.x is the TOTAL invocation count (verts x instances), P.y the
20
+ // verts per instance, P.z the jointCount that strides the palette. With one instance P.x == P.y,
21
+ // inst is 0 and po is 0, so every index below reduces to what it was and the untouched callers
22
+ // get byte-identical vertices out.
18
23
  @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) g: vec3u){
19
- let i=g.x; if(i>=P.x){return;} let p=vec4f(rest[i].xyz,1.0); let j=joints[i]; let w=weights[i]; let nn=restN[i].xyz;
20
- var a=vec4f(0.0); a+=w.x*(palette[j.x]*p); a+=w.y*(palette[j.y]*p); a+=w.z*(palette[j.z]*p); a+=w.w*(palette[j.w]*p);
21
- var b=vec3f(0.0); b+=w.x*rot(palette[j.x],nn); b+=w.y*rot(palette[j.y],nn); b+=w.z*rot(palette[j.z],nn); b+=w.w*rot(palette[j.w],nn);
24
+ let i=g.x; if(i>=P.x){return;}
25
+ let v=i%P.y; let inst=i/P.y; let po=inst*P.z;
26
+ let p=vec4f(rest[v].xyz,1.0); let j=joints[v]; let w=weights[v]; let nn=restN[v].xyz;
27
+ var a=vec4f(0.0); a+=w.x*(palette[po+j.x]*p); a+=w.y*(palette[po+j.y]*p); a+=w.z*(palette[po+j.z]*p); a+=w.w*(palette[po+j.w]*p);
28
+ var b=vec3f(0.0); b+=w.x*rot(palette[po+j.x],nn); b+=w.y*rot(palette[po+j.y],nn); b+=w.z*rot(palette[po+j.z],nn); b+=w.w*rot(palette[po+j.w],nn);
22
29
  deformed[i]=vec4f(a.xyz,1.0); defN[i]=vec4f(normalize(b),0.0);
23
30
  }`;
24
- const DRAW = /* wgsl */ `
31
+ /**
32
+ * The ORIGINAL vertex stage: deformed positions arrive as vertex attributes, one instance.
33
+ *
34
+ * `u.mvp` is `camVP·model` here, precomputed on the CPU, which is why the position needs no model
35
+ * multiply of its own.
36
+ */
37
+ const VS_ATTR = /* wgsl */ `
38
+ @vertex fn vs(@location(0) p: vec3<f32>, @location(1) c: vec3<f32>, @location(2) nrm: vec3<f32>, @location(3) uv: vec2<f32>, @location(4) uv2: vec2<f32>) -> VOut { var o: VOut; o.pos=u.mvp*vec4(p,1.0); o.world=(u.model*vec4(p,1.0)).xyz; o.col=c; o.n=nrm; o.uv=uv; o.uv2=uv2; return o; }`;
39
+ /**
40
+ * The INSTANCED vertex stage: deformed positions come out of storage, one skeleton per instance.
41
+ *
42
+ * ⚠️ STORAGE, NOT A VERTEX BUFFER, and that is forced rather than chosen. The deform pass writes
43
+ * `instance·n + vertex` positions into one buffer, and WebGPU cannot offset a vertex buffer per
44
+ * instance — `stepMode: 'instance'` advances one element per instance, not n. Reading the array
45
+ * directly is the only way to give each instance its own posed copy of a shared mesh.
46
+ *
47
+ * ⚠️ `u.mvp` IS `camVP` ALONE on this pipeline, not `camVP·model`. There is no single model matrix
48
+ * to fold in — that is the point — so the multiply moves into the shader and the CPU writes the
49
+ * plain camera matrix.
50
+ *
51
+ * ⚠️ AND THE NORMAL IS ROTATED BY THE MODEL, which the attribute path above does NOT do. A single
52
+ * creature is placed by a matrix the caller usually leaves unrotated, so it never showed; a crowd
53
+ * is a thousand people FACING different ways, and lighting them all as though they faced the same
54
+ * way is a field of characters lit from the wrong side. Only the rotation is taken — a normal
55
+ * ignores translation.
56
+ */
57
+ const VS_INST = /* wgsl */ `
58
+ @group(3) @binding(0) var<storage,read> iPos: array<vec4f>;
59
+ @group(3) @binding(1) var<storage,read> iNrm: array<vec4f>;
60
+ @group(3) @binding(2) var<storage,read> iCol: array<f32>;
61
+ @group(3) @binding(3) var<storage,read> iUv: array<f32>;
62
+ @group(3) @binding(4) var<storage,read> iUv2: array<f32>;
63
+ @group(3) @binding(5) var<storage,read> iModel: array<mat4x4<f32>>;
64
+ @group(3) @binding(6) var<uniform> IP: vec4<u32>;
65
+ @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut {
66
+ var o: VOut;
67
+ let k = ii * IP.x + vi;
68
+ let m = iModel[ii];
69
+ let w = (m * vec4(iPos[k].xyz, 1.0)).xyz;
70
+ o.pos = u.mvp * vec4(w, 1.0);
71
+ o.world = w;
72
+ o.col = vec3<f32>(iCol[vi*3u], iCol[vi*3u+1u], iCol[vi*3u+2u]);
73
+ o.n = normalize((m * vec4(iNrm[k].xyz, 0.0)).xyz);
74
+ o.uv = vec2<f32>(iUv[vi*2u], iUv[vi*2u+1u]);
75
+ o.uv2 = vec2<f32>(iUv2[vi*2u], iUv2[vi*2u+1u]);
76
+ return o;
77
+ }`;
78
+ const drawWgsl = (VS) => /* wgsl */ `
25
79
  // csm + cascades are APPENDED so every field above keeps its byte offset — a caller that knows
26
80
  // nothing about cascades writes exactly the bytes it always did. lightVP stays as the legacy slot.
27
81
  struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<f32>, amb: vec4<f32>, cam: vec4<f32>, fog: vec4<f32>, model: mat4x4<f32>, csm: vec4<f32>, cascades: array<mat4x4<f32>, ${MAX_CASCADES}>, blend: vec4<f32> };
@@ -39,7 +93,7 @@ struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<
39
93
  struct VOut { @builtin(position) pos: vec4<f32>, @location(0) world: vec3<f32>, @location(1) col: vec3<f32>, @location(2) n: vec3<f32>, @location(3) uv: vec2<f32>, @location(4) uv2: vec2<f32> };
40
94
  // o.world must be the WORLD position (model·p), not the local deformed p — else the fog distance is computed
41
95
  // against the world-space camera and blows up on a planet surface (huge coords), washing creatures into the fog.
42
- @vertex fn vs(@location(0) p: vec3<f32>, @location(1) c: vec3<f32>, @location(2) nrm: vec3<f32>, @location(3) uv: vec2<f32>, @location(4) uv2: vec2<f32>) -> VOut { var o: VOut; o.pos=u.mvp*vec4(p,1.0); o.world=(u.model*vec4(p,1.0)).xyz; o.col=c; o.n=nrm; o.uv=uv; o.uv2=uv2; return o; }
96
+ ${VS}
43
97
  // PCF 3×3 sun shadow — mirrors gpuShadow.shadowFactor so creatures sit in the SAME shadow as the terrain. 1 = lit, 0 = shadowed.
44
98
  fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>) -> f32 {
45
99
  let lp = u.cascades[layer] * vec4(world, 1.0);
@@ -91,6 +145,8 @@ fn shadowFactor(world: vec3<f32>, ndl: f32) -> f32 {
91
145
  // returned before, so the opaque pipeline is unchanged.
92
146
  return vec4(mix(lit, u.fog.xyz, f), u.blend.y);
93
147
  }`;
148
+ const DRAW = drawWgsl(VS_ATTR);
149
+ const DRAW_INST = drawWgsl(VS_INST);
94
150
  export class GpuSkinRenderer {
95
151
  device;
96
152
  skinPipe;
@@ -104,6 +160,16 @@ export class GpuSkinRenderer {
104
160
  * `setCreatures` and reused by whichever pipeline draws it.
105
161
  */
106
162
  blendPipe;
163
+ /**
164
+ * The same two pipelines with the INSTANCED vertex stage — see `VS_INST`.
165
+ *
166
+ * Built unconditionally rather than lazily: a render pipeline is compiled once at construction and
167
+ * a lazy one would compile mid-frame the first time a crowd got dressed, which is a hitch exactly
168
+ * when the scene is busiest.
169
+ */
170
+ instPipe;
171
+ instBlendPipe;
172
+ instBGL;
107
173
  /** The explicit group 0/1/2 layouts, shared by both render pipelines. */
108
174
  drawBGL;
109
175
  packed = [];
@@ -193,6 +259,25 @@ export class GpuSkinRenderer {
193
259
  const layout = device.createPipelineLayout({
194
260
  bindGroupLayouts: this.drawBGL,
195
261
  });
262
+ // GROUP 3 — the instanced vertex stage's storage. Only the instanced pipelines declare it, so
263
+ // the single-instance path keeps the exact three-group layout it has always had and every bind
264
+ // group `setCreatures` already builds stays valid for it.
265
+ const ro = { type: 'read-only-storage' };
266
+ const bgl3 = device.createBindGroupLayout({
267
+ entries: [
268
+ ...[0, 1, 2, 3, 4, 5].map((binding) => ({
269
+ binding,
270
+ visibility: GPUShaderStage.VERTEX,
271
+ buffer: ro,
272
+ })),
273
+ {
274
+ binding: 6,
275
+ visibility: GPUShaderStage.VERTEX,
276
+ buffer: { type: 'uniform' },
277
+ },
278
+ ],
279
+ });
280
+ this.instBGL = bgl3;
196
281
  const common = {
197
282
  layout,
198
283
  vertex: {
@@ -274,6 +359,52 @@ export class GpuSkinRenderer {
274
359
  depthCompare: 'less',
275
360
  },
276
361
  });
362
+ // ⚠️ ITS OWN LAYOUT WITH A FOURTH GROUP, and its own shader module. The instanced vertex stage
363
+ // takes no vertex buffers at all — every attribute is read out of storage — so `buffers` is
364
+ // empty and the draw supplies only an index buffer.
365
+ const im = device.createShaderModule({ code: DRAW_INST });
366
+ const instLayout = device.createPipelineLayout({
367
+ bindGroupLayouts: [...this.drawBGL, bgl3],
368
+ });
369
+ const instCommon = {
370
+ layout: instLayout,
371
+ vertex: { module: im, entryPoint: 'vs', buffers: [] },
372
+ primitive: { topology: 'triangle-list', cullMode: 'none' },
373
+ };
374
+ this.instPipe = device.createRenderPipeline({
375
+ ...instCommon,
376
+ fragment: { module: im, entryPoint: 'fs', targets: [{ format }] },
377
+ depthStencil: {
378
+ format: 'depth24plus',
379
+ depthWriteEnabled: true,
380
+ depthCompare: 'less',
381
+ },
382
+ });
383
+ this.instBlendPipe = device.createRenderPipeline({
384
+ ...instCommon,
385
+ primitive: { ...instCommon.primitive, cullMode: 'back' },
386
+ fragment: {
387
+ module: im,
388
+ entryPoint: 'fs',
389
+ targets: [
390
+ {
391
+ format,
392
+ blend: {
393
+ color: {
394
+ srcFactor: 'src-alpha',
395
+ dstFactor: 'one-minus-src-alpha',
396
+ },
397
+ alpha: { srcFactor: 'zero', dstFactor: 'one' },
398
+ },
399
+ },
400
+ ],
401
+ },
402
+ depthStencil: {
403
+ format: 'depth24plus',
404
+ depthWriteEnabled: false,
405
+ depthCompare: 'less',
406
+ },
407
+ });
277
408
  const dummy = device.createTexture({
278
409
  size: [1, 1],
279
410
  format: 'depth32float',
@@ -306,6 +437,8 @@ export class GpuSkinRenderer {
306
437
  p.idxB.destroy();
307
438
  p.uBuf.destroy();
308
439
  p.palB.destroy();
440
+ p.instModelB?.destroy();
441
+ p.instParamB?.destroy();
309
442
  }
310
443
  this.packed = list.map((c) => {
311
444
  const n = c.rest.length / 3;
@@ -329,10 +462,12 @@ export class GpuSkinRenderer {
329
462
  return b;
330
463
  };
331
464
  const restB = mk(rest, U.STORAGE | U.COPY_DST), restNB = mk(restN, U.STORAGE | U.COPY_DST), jointsB = mk(joints, U.STORAGE | U.COPY_DST), weightsB = mk(weights, U.STORAGE | U.COPY_DST);
332
- const colB = mk(c.colors, U.VERTEX | U.COPY_DST), idxB = mk(c.indices, U.INDEX | U.COPY_DST);
465
+ // ⚠️ `| U.STORAGE` so the instanced vertex stage can read them as arrays. Adding a usage to a
466
+ // buffer that is still bound the same way on the original path changes nothing about it.
467
+ const colB = mk(c.colors, U.VERTEX | U.STORAGE | U.COPY_DST), idxB = mk(c.indices, U.INDEX | U.COPY_DST);
333
468
  // A zero-filled UV buffer when the caller has none: the white fallback samples to 1 at any
334
469
  // coordinate, so the attribute still has to EXIST but its contents cannot matter.
335
- const uvB = mk(c.uvs && c.uvs.length >= n * 2 ? c.uvs : new Float32Array(n * 2), U.VERTEX | U.COPY_DST);
470
+ const uvB = mk(c.uvs && c.uvs.length >= n * 2 ? c.uvs : new Float32Array(n * 2), U.VERTEX | U.STORAGE | U.COPY_DST);
336
471
  // ⚠️ NULL when the caller has no `uvs2` — NOT a second buffer holding a copy of `uvs`.
337
472
  //
338
473
  // `setCreatures` tears down and rebuilds every buffer on each call and all-mine-sky calls it
@@ -342,7 +477,7 @@ export class GpuSkinRenderer {
342
477
  // tint the 1x1 white samples to 1 at any coordinate. The attribute still has to EXIST, so
343
478
  // slot 4 binds `uvB` instead; WebGPU is happy to see the same GPUBuffer in two vertex slots.
344
479
  const uv2B = c.uvs2 && c.uvs2.length >= n * 2
345
- ? mk(c.uvs2, U.VERTEX | U.COPY_DST)
480
+ ? mk(c.uvs2, U.VERTEX | U.STORAGE | U.COPY_DST)
346
481
  : null;
347
482
  const tex = c.tex ?? this.whiteTex;
348
483
  const tex2 = c.tex2 ?? this.whiteTex;
@@ -363,17 +498,37 @@ export class GpuSkinRenderer {
363
498
  });
364
499
  this.matBGs.set(matKey, matBG);
365
500
  }
501
+ // ── INSTANCING ────────────────────────────────────────────────────────────────────────────
502
+ // `count` of 1 with no `instances` is the original path exactly: one palette, one deformed
503
+ // copy, P = [n, n, jointCount], which makes the compute shader's inst and po both zero.
504
+ const inst = c.instances;
505
+ const count = Math.max(1, inst?.count ?? 1);
506
+ const palSrc = inst ? inst.palettes : c.palette;
507
+ // ⚠️ DERIVED, NOT ASSUMED. jointCount strides the palette per instance, and getting it wrong
508
+ // does not throw — it indexes one character's bones through another's offset, so everybody
509
+ // after the first wears somebody else's skeleton. Checked against the array length so a
510
+ // caller whose palettes do not divide by count is told, rather than rendered wrongly.
511
+ const jointCount = Math.floor(palSrc.length / count / 16);
512
+ if (inst && jointCount * count * 16 !== palSrc.length)
513
+ throw new Error(`gpuSkin: palettes is ${palSrc.length} floats, which is not count(${count}) x jointCount x 16`);
366
514
  const palB = dev.createBuffer({
367
- size: c.palette.length * 4,
515
+ size: palSrc.length * 4,
368
516
  usage: U.STORAGE | U.COPY_DST,
369
517
  });
370
- dev.queue.writeBuffer(palB, 0, c.palette);
518
+ dev.queue.writeBuffer(palB, 0, palSrc);
519
+ // ⚠️ STORAGE **and** VERTEX on both paths. The instanced vertex stage reads these as arrays
520
+ // while the original binds them as vertex buffers, and declaring both usages on one buffer
521
+ // costs nothing — it is the same memory, read two ways.
371
522
  const defB = dev.createBuffer({
372
- size: n * 16,
523
+ size: n * 16 * count,
373
524
  usage: U.STORAGE | U.VERTEX,
374
- }), defNB = dev.createBuffer({ size: n * 16, usage: U.STORAGE | U.VERTEX });
525
+ }), defNB = dev.createBuffer({
526
+ size: n * 16 * count,
527
+ usage: U.STORAGE | U.VERTEX,
528
+ });
375
529
  const pB = dev.createBuffer({ size: 16, usage: U.UNIFORM | U.COPY_DST });
376
- dev.queue.writeBuffer(pB, 0, new Uint32Array([n, 0, 0, 0]));
530
+ // P.x total invocations, P.y verts per instance, P.z the palette stride.
531
+ dev.queue.writeBuffer(pB, 0, new Uint32Array([n * count, n, jointCount, 0]));
377
532
  const skinBG = dev.createBindGroup({
378
533
  layout: this.skinPipe.getBindGroupLayout(0),
379
534
  entries: [
@@ -395,7 +550,39 @@ export class GpuSkinRenderer {
395
550
  layout: this.drawBGL[0],
396
551
  entries: [{ binding: 0, resource: { buffer: uBuf } }],
397
552
  });
553
+ // Group 3 exists only for an instanced creature — the single-instance pipeline never binds it.
554
+ let instBG = null;
555
+ let instModelB = null;
556
+ let instParamB = null;
557
+ if (inst) {
558
+ instModelB = dev.createBuffer({
559
+ size: count * 64,
560
+ usage: U.STORAGE | U.COPY_DST,
561
+ });
562
+ dev.queue.writeBuffer(instModelB, 0, inst.models);
563
+ instParamB = dev.createBuffer({
564
+ size: 16,
565
+ usage: U.UNIFORM | U.COPY_DST,
566
+ });
567
+ dev.queue.writeBuffer(instParamB, 0, new Uint32Array([n, 0, 0, 0]));
568
+ instBG = dev.createBindGroup({
569
+ layout: this.instBGL,
570
+ entries: [
571
+ { binding: 0, resource: { buffer: defB } },
572
+ { binding: 1, resource: { buffer: defNB } },
573
+ { binding: 2, resource: { buffer: colB } },
574
+ { binding: 3, resource: { buffer: uvB } },
575
+ { binding: 4, resource: { buffer: uv2B ?? uvB } },
576
+ { binding: 5, resource: { buffer: instModelB } },
577
+ { binding: 6, resource: { buffer: instParamB } },
578
+ ],
579
+ });
580
+ }
398
581
  return {
582
+ count,
583
+ instBG,
584
+ instModelB,
585
+ instParamB,
399
586
  defB,
400
587
  defNB,
401
588
  colB,
@@ -428,12 +615,16 @@ export class GpuSkinRenderer {
428
615
  cp.setPipeline(this.skinPipe);
429
616
  for (const p of this.packed) {
430
617
  cp.setBindGroup(0, p.skinBG);
431
- cp.dispatchWorkgroups(Math.ceil(p.n / 64));
618
+ // n x count invocations: one deformed copy of the mesh per instance.
619
+ cp.dispatchWorkgroups(Math.ceil((p.n * p.count) / 64));
432
620
  }
433
621
  cp.end();
434
622
  for (const p of this.packed) {
435
623
  const u = new Float32Array(68 + 4 + 16 * MAX_CASCADES + 4);
436
- u.set(mul16(camVP, p.model), 0);
624
+ // ⚠️ `camVP` ALONE for an instanced creature. There is no one model matrix to fold in — each
625
+ // instance carries its own and the vertex stage applies it — so folding `p.model` here would
626
+ // apply a placement twice for one instance and wrongly for all the others.
627
+ u.set(p.instBG ? camVP : mul16(camVP, p.model), 0);
437
628
  u.set(mats[0] ?? IDENTITY4, 16); // legacy cascade-0 slot, kept so the offsets above never move
438
629
  u.set([sunDir[0], sunDir[1], sunDir[2], receive ? 1 : 0], 32); // sun.w = shadow-receive enable
439
630
  u.set([sunCol[0], sunCol[1], sunCol[2], 0], 36);
@@ -506,21 +697,46 @@ export class GpuSkinRenderer {
506
697
  rp.setIndexBuffer(p.idxB, 'uint32');
507
698
  rp.drawIndexed(p.idxCount);
508
699
  };
700
+ /** The instanced twin: no vertex buffers at all, group 3, and one draw for every instance. */
701
+ const drawInst = (p) => {
702
+ rp.setBindGroup(0, p.uBG);
703
+ rp.setBindGroup(2, p.matBG);
704
+ rp.setBindGroup(3, p.instBG);
705
+ rp.setIndexBuffer(p.idxB, 'uint32');
706
+ rp.drawIndexed(p.idxCount, p.count);
707
+ };
509
708
  // ⚠️ OPAQUE FIRST, in two passes over the list rather than one. The translucent creatures do not
510
709
  // write depth, so anything opaque drawn after them would still appear — but they must blend
511
710
  // against a colour buffer that already HAS the opaque scene in it, or they composite over the
512
711
  // background and the thing behind them is simply missing. With no `alpha` set anywhere the
513
712
  // second loop is empty and this is the original single loop.
514
- rp.setPipeline(this.drawPipe);
515
- for (const p of this.packed)
516
- if (p.alpha >= 1)
517
- drawOne(p);
713
+ // ⚠️ FOUR GROUPS, NOT TWO, because instanced and single-instance creatures are different
714
+ // PIPELINES and switching pipeline mid-loop per creature would undo the batching this exists
715
+ // for. Opaque still precedes translucent overall, which is the ordering rule that matters.
716
+ const opaque = this.packed.filter((p) => p.alpha >= 1);
518
717
  const translucent = this.packed.filter((p) => p.alpha < 1);
519
- if (translucent.length) {
718
+ const single = (l) => l.filter((p) => !p.instBG);
719
+ const many = (l) => l.filter((p) => p.instBG);
720
+ if (single(opaque).length) {
721
+ rp.setPipeline(this.drawPipe);
722
+ for (const p of single(opaque))
723
+ drawOne(p);
724
+ }
725
+ if (many(opaque).length) {
726
+ rp.setPipeline(this.instPipe);
727
+ for (const p of many(opaque))
728
+ drawInst(p);
729
+ }
730
+ if (single(translucent).length) {
520
731
  rp.setPipeline(this.blendPipe);
521
- for (const p of translucent)
732
+ for (const p of single(translucent))
522
733
  drawOne(p);
523
734
  }
735
+ if (many(translucent).length) {
736
+ rp.setPipeline(this.instBlendPipe);
737
+ for (const p of many(translucent))
738
+ drawInst(p);
739
+ }
524
740
  rp.end();
525
741
  }
526
742
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.14.22",
3
+ "version": "0.14.24",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {