ugly-game 0.8.0 → 0.8.1

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.
@@ -25,6 +25,19 @@ export interface PropMesh {
25
25
  normals: Float32Array;
26
26
  colors: Float32Array;
27
27
  indices: Uint32Array;
28
+ /**
29
+ * Optional UVs. Omitted ⇒ the model renders exactly as it did before textures existed, because a
30
+ * zero-filled buffer is bound in their place and the 1x1 white fallback texture samples to 1.
31
+ */
32
+ uvs?: Float32Array;
33
+ /**
34
+ * Optional base-colour map, already decoded.
35
+ *
36
+ * Decoding is the caller's job: a Worker has no ImageBitmap for a URL and the renderer has no
37
+ * business fetching. Providers ship a full PBR set (albedo, metallic-roughness, normal); only
38
+ * albedo is consumed today, and the rest follow once tangents or a derivative TBN land.
39
+ */
40
+ albedo?: ImageBitmap;
28
41
  }
29
42
  /**
30
43
  * Per-instance deformation. Every field is neutral at its default, so an instance that supplies none
@@ -71,6 +84,10 @@ export declare class GpuPropsRenderer {
71
84
  private bgs;
72
85
  private occBGs;
73
86
  private counts;
87
+ /** Shared across every model — one sampler is all a prop atlas needs. */
88
+ private sampler;
89
+ /** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
90
+ private white;
74
91
  private dummyShadowView;
75
92
  private dummyShadowSamp;
76
93
  private shadowBG;
@@ -88,6 +105,19 @@ export declare class GpuPropsRenderer {
88
105
  /** Advance the wind phase. Pass the frame delta; sway is skipped entirely when windAmp is 0. */
89
106
  tick(dt: number): void;
90
107
  constructor(device: GPUDevice, format: GPUTextureFormat);
108
+ /**
109
+ * Upload a decoded base-colour map with a full mip chain.
110
+ *
111
+ * WebGPU has no generateMipmap, so the chain is built by successive half-scale blits through the
112
+ * device's own copyExternalImageToTexture — cheap, because it happens once at load rather than per
113
+ * frame. Skipping mips is not an option here: props are drawn at tens of thousands of instances
114
+ * stretching to the horizon, and an unmipped texture aliases into shimmering noise at distance,
115
+ * which looks markedly worse than the flat vertex colours it replaced.
116
+ *
117
+ * sRGB format, because a base-colour map is authored in sRGB and the shader works in linear —
118
+ * getting this wrong is the classic washed-out-albedo bug.
119
+ */
120
+ private uploadAlbedo;
91
121
  setModels(meshes: PropMesh[]): void;
92
122
  /**
93
123
  * Group instances by model and upload the per-model instance buffers.
@@ -18,9 +18,11 @@ struct U { mvp: mat4x4<f32>, lightVP: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<
18
18
  // d2 = (yaw, valueJitter, 1/halfWidth, unused)
19
19
  struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32> };
20
20
  @group(0) @binding(1) var<storage,read> models: array<Inst>;
21
+ @group(2) @binding(0) var albedoTex: texture_2d<f32>;
22
+ @group(2) @binding(1) var albedoSamp: sampler;
21
23
  @group(1) @binding(0) var shadowMap: texture_depth_2d; // the SAME sun shadow map the terrain cubes sample
22
24
  @group(1) @binding(1) var shadowSamp: sampler_comparison;
23
- 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> };
25
+ 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> };
24
26
  // WIND SWAY. Displacement is weighted by height above the instance's own anchor, so a trunk stays
25
27
  // planted while the canopy moves, and the phase is offset by world position so a grove never sways
26
28
  // in unison. Amplitude comes from the world's air density: an airless world is perfectly, eerily
@@ -82,7 +84,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
82
84
  let ca = cos(a); let sa = sin(a);
83
85
  return normalize(vec3(v.x * ca - v.z * sa, v.y, v.x * sa + v.z * ca));
84
86
  }
85
- @vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @builtin(instance_index) ii: u32) -> VO {
87
+ @vertex fn vs(@location(0) p: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) col: vec3<f32>, @location(3) uv: vec2<f32>, @builtin(instance_index) ii: u32) -> VO {
86
88
  let inst = models[ii];
87
89
  let m = inst.m;
88
90
  let lp = deformLocal(p, inst.d0, inst.d1, inst.d2);
@@ -92,7 +94,7 @@ fn deformNormal(n: vec3<f32>, py: f32, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f3
92
94
  let sc = length(m[0].xyz);
93
95
  world = sway(lp, world, upv, sc);
94
96
  var o: VO; o.pos = u.mvp * vec4(world, 1.0); o.world = world; o.n = (m * vec4(ln, 0.0)).xyz;
95
- o.c = col * inst.d2.y; o.l = lp; return o;
97
+ o.c = col * inst.d2.y; o.l = lp; o.uv = uv; return o;
96
98
  }
97
99
  // same fixed directional FILL as the terrain cubes (gpuShadow.fixedFill) so plants/rocks read the same 3D shape,
98
100
  // day or night, under one shared light. up.w > 0.5 signals a valid local-up was supplied (else fall back to flat).
@@ -163,7 +165,10 @@ fn hsvShift(c: vec3<f32>, hue: f32, sat: f32, val: f32) -> vec3<f32> {
163
165
  let d = clamp(dot(N, -normalize(u.sun.xyz)), 0.0, 1.0);
164
166
  let sh = mix(1.0, shadowFactor(i.world, d), u.sun.w); // u.sun.w = shadow-receive enable (0 ⇒ off, byte-identical for demo)
165
167
  // procedural grain modulates the role colour; the per-world grade then re-tints the whole planet
166
- var base = i.c;
168
+ // Albedo modulates the vertex colour rather than replacing it, so the StyleGuide role tint and the
169
+ // per-instance hue jitter still act on a textured prop — and an untextured one samples the 1x1
170
+ // white fallback and is unchanged.
171
+ var base = i.c * textureSample(albedoTex, albedoSamp, i.uv).rgb;
167
172
  if (u.surf.x > 0.0) {
168
173
  let grain = triplanar(i.l, N, u.surf.x);
169
174
  base = base * (1.0 - u.surf.y * 0.5 + u.surf.y * grain);
@@ -240,6 +245,10 @@ export class GpuPropsRenderer {
240
245
  bgs = [];
241
246
  occBGs = [];
242
247
  counts = [];
248
+ /** Shared across every model — one sampler is all a prop atlas needs. */
249
+ sampler = null;
250
+ /** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
251
+ white = null;
243
252
  // shadow-receive (group 1): a dummy 1×1 depth map when no sun shadow is supplied (demo path), else the terrain's
244
253
  // shared shadow map. The bind group is cached and only rebuilt when the supplied view/sampler identity changes.
245
254
  dummyShadowView;
@@ -294,6 +303,12 @@ export class GpuPropsRenderer {
294
303
  arrayStride: 12,
295
304
  attributes: [{ shaderLocation: 2, offset: 0, format: 'float32x3' }],
296
305
  },
306
+ {
307
+ // UVs. Always bound — a model without them gets a zero-filled buffer, which samples the
308
+ // 1x1 white fallback and leaves its appearance byte-identical to before textures existed.
309
+ arrayStride: 8,
310
+ attributes: [{ shaderLocation: 3, offset: 0, format: 'float32x2' }],
311
+ },
297
312
  ],
298
313
  },
299
314
  fragment: { module: sm, entryPoint: 'fs', targets: [{ format }] },
@@ -340,27 +355,120 @@ export class GpuPropsRenderer {
340
355
  this.dummyShadowView = dummy.createView();
341
356
  this.dummyShadowSamp = device.createSampler({ compare: 'less' });
342
357
  }
358
+ /**
359
+ * Upload a decoded base-colour map with a full mip chain.
360
+ *
361
+ * WebGPU has no generateMipmap, so the chain is built by successive half-scale blits through the
362
+ * device's own copyExternalImageToTexture — cheap, because it happens once at load rather than per
363
+ * frame. Skipping mips is not an option here: props are drawn at tens of thousands of instances
364
+ * stretching to the horizon, and an unmipped texture aliases into shimmering noise at distance,
365
+ * which looks markedly worse than the flat vertex colours it replaced.
366
+ *
367
+ * sRGB format, because a base-colour map is authored in sRGB and the shader works in linear —
368
+ * getting this wrong is the classic washed-out-albedo bug.
369
+ */
370
+ uploadAlbedo(src) {
371
+ const dev = this.device;
372
+ const w = src.width, h = src.height;
373
+ let levels = 1;
374
+ for (let d = Math.max(w, h); d > 1; d = d >> 1)
375
+ levels++;
376
+ const tex = dev.createTexture({
377
+ size: [w, h],
378
+ format: 'rgba8unorm-srgb',
379
+ mipLevelCount: levels,
380
+ usage: GPUTextureUsage.TEXTURE_BINDING |
381
+ GPUTextureUsage.COPY_DST |
382
+ GPUTextureUsage.RENDER_ATTACHMENT,
383
+ });
384
+ dev.queue.copyExternalImageToTexture({ source: src }, { texture: tex }, [
385
+ w,
386
+ h,
387
+ ]);
388
+ // Downsample by re-encoding the bitmap at each level. Uses the platform's own resampler via
389
+ // createImageBitmap rather than a render pass, which keeps this out of the render graph
390
+ // entirely — it is a load-time cost, not a frame cost.
391
+ let lw = w, lh = h;
392
+ for (let lvl = 1; lvl < levels; lvl++) {
393
+ lw = Math.max(1, lw >> 1);
394
+ lh = Math.max(1, lh >> 1);
395
+ void createImageBitmap(src, {
396
+ resizeWidth: lw,
397
+ resizeHeight: lh,
398
+ resizeQuality: 'high',
399
+ })
400
+ .then((bm) => {
401
+ dev.queue.copyExternalImageToTexture({ source: bm }, { texture: tex, mipLevel: lvl }, [bm.width, bm.height]);
402
+ bm.close();
403
+ })
404
+ // A failed mip leaves that level undefined rather than killing the frame: the base level is
405
+ // already uploaded, so the prop renders — just with more aliasing at distance.
406
+ .catch(() => {
407
+ // deliberately swallowed — see above
408
+ });
409
+ }
410
+ return tex;
411
+ }
343
412
  setModels(meshes) {
344
413
  const dev = this.device, U = GPUBufferUsage;
345
414
  for (const p of this.models) {
346
415
  p.posB.destroy();
347
416
  p.nrmB.destroy();
348
417
  p.colB.destroy();
418
+ p.uvB.destroy();
349
419
  p.idxB.destroy();
420
+ p.tex?.destroy();
350
421
  }
351
422
  const mk = (d, u) => {
352
423
  const b = dev.createBuffer({ size: d.byteLength, usage: u });
353
424
  dev.queue.writeBuffer(b, 0, d);
354
425
  return b;
355
426
  };
356
- this.models = meshes.map((m) => ({
357
- posB: mk(m.positions, U.VERTEX | U.COPY_DST),
358
- nrmB: mk(m.normals, U.VERTEX | U.COPY_DST),
359
- colB: mk(m.colors, U.VERTEX | U.COPY_DST),
360
- idxB: mk(m.indices, U.INDEX | U.COPY_DST),
361
- idxCount: m.indices.length,
362
- extent: measureExtent(m.positions),
363
- }));
427
+ // One sampler for every prop. Repeat + trilinear: props are UV-mapped charts, not tiled
428
+ // surfaces, but mipmapping is not optional — at tens of thousands of instances an unmipped
429
+ // texture aliases into noise at distance, which looks worse than the vertex colours it replaced.
430
+ this.sampler ??= dev.createSampler({
431
+ magFilter: 'linear',
432
+ minFilter: 'linear',
433
+ mipmapFilter: 'linear',
434
+ addressModeU: 'repeat',
435
+ addressModeV: 'repeat',
436
+ });
437
+ // A 1x1 white texture stands in for every model without a map, so the pipeline binds the same
438
+ // resources either way and an untextured prop multiplies by 1 — byte-identical to before.
439
+ this.white ??= (() => {
440
+ const t = dev.createTexture({
441
+ size: [1, 1],
442
+ format: 'rgba8unorm-srgb',
443
+ usage: GPUTextureUsage.TEXTURE_BINDING |
444
+ GPUTextureUsage.COPY_DST |
445
+ GPUTextureUsage.RENDER_ATTACHMENT,
446
+ });
447
+ dev.queue.writeTexture({ texture: t }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
448
+ return t;
449
+ })();
450
+ this.models = meshes.map((m) => {
451
+ const verts = m.positions.length / 3;
452
+ const tex = m.albedo ? this.uploadAlbedo(m.albedo) : null;
453
+ return {
454
+ posB: mk(m.positions, U.VERTEX | U.COPY_DST),
455
+ nrmB: mk(m.normals, U.VERTEX | U.COPY_DST),
456
+ colB: mk(m.colors, U.VERTEX | U.COPY_DST),
457
+ // zero-filled when absent: the shader still reads location 3, and white x anything is anything
458
+ uvB: mk(m.uvs ?? new Float32Array(verts * 2), U.VERTEX | U.COPY_DST),
459
+ idxB: mk(m.indices, U.INDEX | U.COPY_DST),
460
+ idxCount: m.indices.length,
461
+ extent: measureExtent(m.positions),
462
+ tex,
463
+ matBG: dev.createBindGroup({
464
+ layout: this.pipe.getBindGroupLayout(2),
465
+ entries: [
466
+ { binding: 0, resource: (tex ?? this.white).createView() },
467
+ { binding: 1, resource: this.sampler },
468
+ ],
469
+ }),
470
+ };
471
+ });
364
472
  this.caps = meshes.map(() => 0);
365
473
  this.instBufs = meshes.map(() => null);
366
474
  this.bgs = meshes.map(() => null);
@@ -506,6 +614,8 @@ export class GpuPropsRenderer {
506
614
  rp.setVertexBuffer(0, mdl.posB);
507
615
  rp.setVertexBuffer(1, mdl.nrmB);
508
616
  rp.setVertexBuffer(2, mdl.colB);
617
+ rp.setVertexBuffer(3, mdl.uvB);
618
+ rp.setBindGroup(2, mdl.matBG);
509
619
  rp.setIndexBuffer(mdl.idxB, 'uint32');
510
620
  rp.drawIndexed(mdl.idxCount, this.counts[m]);
511
621
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {