ugly-game 0.15.4 → 0.15.6

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.
@@ -82,6 +82,39 @@ export declare const CUBE: {
82
82
  pos: string;
83
83
  nrm: string;
84
84
  };
85
+ /** Vertex counts for the two cube geometries the camera pass can draw. */
86
+ export declare const SHARP_VERTS = 36;
87
+ export declare const BEVEL_VERTS = 132;
88
+ export interface BevelCube {
89
+ /** Which of the 8 sharp corners each vertex sits on — always (±0.5, ±0.5, ±0.5). */
90
+ corner: [number, number, number][];
91
+ /** The face normal each vertex belongs to. Doubles as its shading normal AND the anchor
92
+ * every one of its bevel gates is measured from. */
93
+ home: [number, number, number][];
94
+ cornerWgsl: string;
95
+ homeWgsl: string;
96
+ }
97
+ export declare const BEVEL: BevelCube;
98
+ /** Is the neighbour at offset `o` solid, per the 27-bit mask? 1 = solid. Mirrors `occAt` in WGSL. */
99
+ export declare function occSolid(mask: number, o: readonly [number, number, number]): number;
100
+ /**
101
+ * Is the edge between faces `a` and `b` exposed — and therefore beveled?
102
+ *
103
+ * ⚠️ THE DIAGONAL TERM IS NOT OPTIONAL. Two blocks that touch only along a diagonal (a stair step)
104
+ * each see air on both of the faces meeting at that edge, so on the two-face test alone both would
105
+ * cut it back and open a diamond-shaped hole straight through the terrain. The third cell is the
106
+ * one that knows the other block is there.
107
+ */
108
+ export declare function edgeOpen(mask: number, a: readonly [number, number, number], b: readonly [number, number, number]): number;
109
+ /**
110
+ * THE VERTEX RULE, in JS — the oracle `gpuShadow.bevel.test.mts` checks and the exact thing
111
+ * `bevelPos()` in COMMON_WGSL does. Kept in step with it by hand; the test is what notices.
112
+ *
113
+ * A vertex's pull along a free axis `k` is inward (`-sign(corner[k])`), gated by the edge between
114
+ * its home face and the face whose normal is `sign(corner[k]) * e_k`. Both primitives sharing a
115
+ * vertex resolve the same face/axis pair, which is where watertightness comes from.
116
+ */
117
+ export declare function bevelVertex(corner: readonly [number, number, number], home: readonly [number, number, number], mask: number, bevel: number): [number, number, number];
85
118
  export declare class GpuShadowRenderer {
86
119
  private device;
87
120
  private instBuf;
@@ -136,6 +169,7 @@ export declare class GpuShadowRenderer {
136
169
  private matQuality;
137
170
  private matCutoff;
138
171
  private eye;
172
+ private bevel;
139
173
  private alphaPipe;
140
174
  private alphaBGL;
141
175
  private overlayBuf;
@@ -226,12 +260,56 @@ export declare class GpuShadowRenderer {
226
260
  * highlight will sit somewhere else entirely.
227
261
  */
228
262
  setEye(x: number, y: number, z: number): void;
263
+ /**
264
+ * ROUND THE EXPOSED EDGES of every cube that supplies a `CubeInstance.occ` mask, by `amount`
265
+ * block-fractions (0.06 is a subtle rim; 0.2 is pebble-like). 0 — the default — is the sharp cube.
266
+ *
267
+ * Only edges open to air on BOTH adjacent faces and on the cell diagonally between them are cut
268
+ * back, so blocks that touch still meet flush and a stair step cannot open a hole. An instance
269
+ * without a mask (`occ` absent ⇒ 0, the "unknown" sentinel) is never beveled, which is why the far
270
+ * field, sky-body shells, ships, creatures and props stay sharp with no work on their part.
271
+ *
272
+ * ⚠️ NOT FREE WHILE IT IS ON. A non-zero amount draws 132 vertices per instance instead of 36 in
273
+ * the CAMERA pass — for every instance, beveled or not, because they all ride one indirect draw.
274
+ * The shadow pass keeps the sharp cube either way. At 0 the vertex count drops back to 36, so
275
+ * leaving this alone costs exactly what it cost before the feature existed.
276
+ */
277
+ setBevel(amount: number): void;
229
278
  setAtlas(tex: GPUTexture, layout: AtlasLayout): void;
230
279
  /** Static scene: sizes the buffer to exactly these instances. */
231
280
  setScene(instances: CubeInstance[]): void;
232
281
  /** Dynamic scene: pre-allocate for `cap` instances; call updateInstances() each frame. */
233
282
  setCapacity(cap: number): void;
234
283
  updateInstances(instances: CubeInstance[]): void;
284
+ /**
285
+ * Rewrite ONE RANGE of the instance buffer and leave the rest of it alone.
286
+ *
287
+ * `updateInstances` repacks and re-uploads EVERYTHING, so a caller whose scene is mostly static pays for
288
+ * all of it to move one cube. In a voxel game that is the whole cost: measured in all-mine-sky, a 63 000
289
+ * instance scene costs ~7 ms of main thread per frame to repack and write, and the only thing changing on
290
+ * a typical frame is a first-person viewmodel of a few dozen cubes. The pack is linear in instance count
291
+ * — ~0.1 µs each — so the fix is to not do it for instances that did not change.
292
+ *
293
+ * The contract is deliberately dumb: this writes `instances` starting at slot `first` and nothing else.
294
+ * It does not move the draw count (use `setInstanceCount`), and it does not know what your segments are.
295
+ * The caller owns the layout, because only the caller knows which of its sources changed.
296
+ *
297
+ * // ground 0..47999, sky 48000..62999, dynamic 63000..
298
+ * if (skyMoved) r.updateInstanceRange(sky, 48000)
299
+ * r.updateInstanceRange(dynamic, 63000)
300
+ * r.setInstanceCount(63000 + dynamic.length)
301
+ *
302
+ * ⚠️ SLOTS ARE NOT REORDERED. A range write leaves whatever was in the untouched slots exactly as it was,
303
+ * so a layout whose segment offsets shift when one segment resizes must re-upload from the first moved
304
+ * slot onward. Reserving fixed capacity per segment avoids that; packing tight does not.
305
+ *
306
+ * Out-of-range and empty writes are no-ops rather than errors: a caller assembling a frame should not
307
+ * have to special-case "this segment happens to be empty right now".
308
+ */
309
+ updateInstanceRange(instances: CubeInstance[], first: number): void;
310
+ /** How many instances the cull + draw passes consider, whatever is in the buffer past that. Pairs with
311
+ * `updateInstanceRange`: shrinking the dynamic tail is a count change, not an upload. */
312
+ setInstanceCount(n: number): void;
235
313
  /** Translucent overlay cubes drawn over the opaque scene; `emissive` carries per-cube alpha (0..1). The buffer
236
314
  * GROWS to fit (no hard cap). Pass `eye` to SORT the cubes back-to-front (farthest first) so overlapping
237
315
  * translucent cubes blend in the correct order — required for anything denser than the place ghost. By default
package/dist/gpuShadow.js CHANGED
@@ -69,6 +69,150 @@ function buildCube() {
69
69
  }
70
70
  /** The 36-vertex cube as WGSL array-literal bodies (pos + per-face normal). Shared by shadow modules. */
71
71
  export const CUBE = buildCube();
72
+ /** Vertex counts for the two cube geometries the camera pass can draw. */
73
+ export const SHARP_VERTS = 36;
74
+ export const BEVEL_VERTS = 132; // 6 face quads (36) + 12 bevel bands (72) + 8 corner tris (24)
75
+ // THE CHAMFERED CUBE — a cube with all twelve edges cut back, where each cut COLLAPSES to a sharp
76
+ // corner unless that edge is actually exposed to air or water.
77
+ //
78
+ // Every vertex is one of the 8 corners displaced inward along up to three axes, and each
79
+ // displacement is gated by exactly one edge. That is the whole design, and three properties fall
80
+ // out of it rather than having to be engineered:
81
+ //
82
+ // WATERTIGHT — a face quad, its bevel bands and its corner tri re-derive a shared vertex from the
83
+ // same (corner, home) pair under the same gate, so they cannot disagree and no crack can open.
84
+ //
85
+ // FLUSH — a buried edge has a solid face-neighbour, its gate is false, and it collapses. Blocks
86
+ // that touch still meet exactly as they did before this existed.
87
+ //
88
+ // FREE WHEN UNKNOWN — occ == 0 (every non-terrain caller: the far field, sky bodies, the ship,
89
+ // creatures, props, the place ghost) makes every gate false, so all 132 vertices land on the 8
90
+ // sharp corners and the geometry is identical to buildCube()'s.
91
+ //
92
+ // ⚠️ FACE QUADS ARE EMITTED FIRST, AND THAT ORDERING IS LOAD-BEARING. Vertices 0..35 are byte-for-
93
+ // byte buildCube()'s cube, which is what lets the camera pass draw 36 instead of 132 whenever the
94
+ // bevel is off — so turning the feature off costs exactly what it cost before the feature existed,
95
+ // rather than merely looking the same while paying for 96 degenerate vertices per instance.
96
+ function buildBevelCube() {
97
+ // The same six faces, in the same order, as buildCube().
98
+ const faces = [
99
+ { n: [1, 0, 0], u: [0, 0, 1], v: [0, 1, 0] },
100
+ { n: [-1, 0, 0], u: [0, 0, 1], v: [0, 1, 0] },
101
+ { n: [0, 1, 0], u: [1, 0, 0], v: [0, 0, 1] },
102
+ { n: [0, -1, 0], u: [1, 0, 0], v: [0, 0, 1] },
103
+ { n: [0, 0, 1], u: [1, 0, 0], v: [0, 1, 0] },
104
+ { n: [0, 0, -1], u: [1, 0, 0], v: [0, 1, 0] },
105
+ ];
106
+ const quad = [
107
+ [-0.5, -0.5],
108
+ [0.5, -0.5],
109
+ [0.5, 0.5],
110
+ [-0.5, -0.5],
111
+ [0.5, 0.5],
112
+ [-0.5, 0.5],
113
+ ];
114
+ const corner = [];
115
+ const home = [];
116
+ const push = (c, h) => {
117
+ corner.push(c);
118
+ home.push(h);
119
+ };
120
+ const axisOf = (n) => (n[0] !== 0 ? 0 : n[1] !== 0 ? 1 : 2);
121
+ // ── 1. FACE QUADS (vertices 0..35) — identical to buildCube(), see the ordering warning above.
122
+ for (const f of faces)
123
+ for (const [cu, cv] of quad)
124
+ push([
125
+ f.n[0] * 0.5 + f.u[0] * cu + f.v[0] * cv,
126
+ f.n[1] * 0.5 + f.u[1] * cu + f.v[1] * cv,
127
+ f.n[2] * 0.5 + f.u[2] * cu + f.v[2] * cv,
128
+ ], [...f.n]);
129
+ // ── 2. BEVEL BANDS (36..107) — one quad per edge, 12 edges.
130
+ // Each band spans two faces, so its two long sides carry DIFFERENT home normals; interpolating
131
+ // between them across the band is what makes a 45° cut read as a curve instead of a facet.
132
+ //
133
+ // ⚠️ THE OWNING FACE'S VERTEX GOES FIRST IN EVERY TRIANGLE. `objN` is flat-interpolated and
134
+ // WebGPU's provoking vertex is the FIRST, so vertex order is what decides which of the two faces'
135
+ // atlas tile and in-face axes the whole band samples. Emitting them in the other order silently
136
+ // hands the band to the neighbouring face.
137
+ for (let ai = 0; ai < faces.length; ai++)
138
+ for (let bi = ai + 1; bi < faces.length; bi++) {
139
+ const a = faces[ai].n, b = faces[bi].n;
140
+ const axA = axisOf(a), axB = axisOf(b);
141
+ if (axA === axB)
142
+ continue; // opposite faces share no edge
143
+ const axE = 3 - axA - axB; // the third axis: the one the edge runs along
144
+ const at = (t, h) => {
145
+ const c = [0, 0, 0];
146
+ c[axA] = a[axA] * 0.5;
147
+ c[axB] = b[axB] * 0.5;
148
+ c[axE] = t;
149
+ push(c, h);
150
+ };
151
+ // two triangles, A-side vertex first in each
152
+ at(-0.5, [...a]);
153
+ at(-0.5, [...b]);
154
+ at(0.5, [...b]);
155
+ at(-0.5, [...a]);
156
+ at(0.5, [...b]);
157
+ at(0.5, [...a]);
158
+ }
159
+ // ── 3. CORNER TRIS (108..131) — one triangle per corner, closing the three-way junction.
160
+ // With all three edges beveled this is the classic chamfer corner; with only some of them beveled
161
+ // it is exactly the leftover gap between a band's end and an unbeveled face corner. The same rule
162
+ // produces both, which is why the mixed cases need no special handling.
163
+ for (const sx of [-0.5, 0.5])
164
+ for (const sy of [-0.5, 0.5])
165
+ for (const sz of [-0.5, 0.5]) {
166
+ const c = [sx, sy, sz];
167
+ push([...c], [Math.sign(sx), 0, 0]);
168
+ push([...c], [0, Math.sign(sy), 0]);
169
+ push([...c], [0, 0, Math.sign(sz)]);
170
+ }
171
+ const wgsl = (a) => a.map((p) => `vec3<f32>(${p[0]},${p[1]},${p[2]})`).join(', ');
172
+ return { corner, home, cornerWgsl: wgsl(corner), homeWgsl: wgsl(home) };
173
+ }
174
+ export const BEVEL = buildBevelCube();
175
+ /** Is the neighbour at offset `o` solid, per the 27-bit mask? 1 = solid. Mirrors `occAt` in WGSL. */
176
+ export function occSolid(mask, o) {
177
+ const idx = o[0] + 1 + (o[1] + 1) * 3 + (o[2] + 1) * 9;
178
+ return (mask >>> idx) & 1;
179
+ }
180
+ /**
181
+ * Is the edge between faces `a` and `b` exposed — and therefore beveled?
182
+ *
183
+ * ⚠️ THE DIAGONAL TERM IS NOT OPTIONAL. Two blocks that touch only along a diagonal (a stair step)
184
+ * each see air on both of the faces meeting at that edge, so on the two-face test alone both would
185
+ * cut it back and open a diamond-shaped hole straight through the terrain. The third cell is the
186
+ * one that knows the other block is there.
187
+ */
188
+ export function edgeOpen(mask, a, b) {
189
+ if (mask === 0)
190
+ return 0; // unknown ⇒ no bevel, same sentinel as CubeInstance.occ
191
+ const d = [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
192
+ return ((1 - occSolid(mask, a)) * (1 - occSolid(mask, b)) * (1 - occSolid(mask, d)));
193
+ }
194
+ /**
195
+ * THE VERTEX RULE, in JS — the oracle `gpuShadow.bevel.test.mts` checks and the exact thing
196
+ * `bevelPos()` in COMMON_WGSL does. Kept in step with it by hand; the test is what notices.
197
+ *
198
+ * A vertex's pull along a free axis `k` is inward (`-sign(corner[k])`), gated by the edge between
199
+ * its home face and the face whose normal is `sign(corner[k]) * e_k`. Both primitives sharing a
200
+ * vertex resolve the same face/axis pair, which is where watertightness comes from.
201
+ */
202
+ export function bevelVertex(corner, home, mask, bevel) {
203
+ const out = [corner[0], corner[1], corner[2]];
204
+ if (bevel <= 0 || mask === 0)
205
+ return out;
206
+ for (let k = 0; k < 3; k++) {
207
+ if (home[k] !== 0)
208
+ continue; // the face axis itself is never pulled
209
+ const s = Math.sign(corner[k]);
210
+ const b = [0, 0, 0];
211
+ b[k] = s;
212
+ out[k] -= s * bevel * edgeOpen(mask, home, b);
213
+ }
214
+ return out;
215
+ }
72
216
  // Shared vertex helpers + cube data. cam.sunCol.w carries the shadow-map texel size.
73
217
  const COMMON_WGSL = /* wgsl */ `
74
218
  struct Cam {
@@ -80,7 +224,7 @@ struct Cam {
80
224
  atlas: vec4<f32>, // x = useAtlas (1/0) · y = per-voxel AO surviving on textured blocks · z = MATERIAL quality (0 flat · 1 normal-mapped · 2 + parallax) · w = parallax cutoff distance in world units
81
225
  up: vec4<f32>, // xyz = local gravity up (for hemisphere face-shading readability); w = linear-HDR flag
82
226
  csm: vec4<f32>, // x = active cascade count · y = crossfade band in uv units
83
- eye: vec4<f32>, // xyz = camera position in world space (material relief + specular); w unused
227
+ eye: vec4<f32>, // xyz = camera position in world space (material relief + specular); w = edge bevel amount (0 = sharp cube)
84
228
  };
85
229
  struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> }; // pos.w = hue (<0 ⇒ ground) · scl.w = emissive/alpha · rot = quaternion · aux.x = atlas tile (<0 ⇒ hue) · aux.y = up-face code · aux.z/aux.w = CONTACT DECAL (0,0 = none) · aux2.xy = 27-bit NEIGHBOUR OCCUPANCY split 14/13 (0,0 = unknown ⇒ no corner AO) · aux2.z = per-block albedo jitter · aux2.w = texFit (≠0 ⇒ one atlas tile per face, texture coords NOT scaled by inst.scl)
86
230
  @group(0) @binding(0) var<uniform> cam: Cam;
@@ -88,6 +232,8 @@ struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, au
88
232
 
89
233
  const CUBE_POS = array<vec3<f32>, 36>(${CUBE.pos});
90
234
  const CUBE_NRM = array<vec3<f32>, 36>(${CUBE.nrm});
235
+ const BEV_CORNER = array<vec3<f32>, ${BEVEL_VERTS}>(${BEVEL.cornerWgsl});
236
+ const BEV_HOME = array<vec3<f32>, ${BEVEL_VERTS}>(${BEVEL.homeWgsl});
91
237
 
92
238
  fn qrot(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> { let t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); }
93
239
  fn worldOf(inst: Inst, vi: u32) -> vec3<f32> { return inst.pos.xyz + qrot(inst.rot, CUBE_POS[vi] * inst.scl.xyz); }
@@ -112,12 +258,38 @@ fn occAt(mask: u32, o: vec3<f32>) -> f32 {
112
258
  let idx = u32((o.x + 1.0) + (o.y + 1.0) * 3.0 + (o.z + 1.0) * 9.0);
113
259
  return f32((mask >> idx) & 1u);
114
260
  }
261
+ // ── ROUNDED EDGES ───────────────────────────────────────────────────────────────────────────────
262
+ // Is the edge between faces a and b exposed to air or water — and so beveled? The two faces AND
263
+ // the cell diagonally between them must all be clear.
264
+ //
265
+ // ⚠️ THE DIAGONAL TERM IS WHAT STOPS A STAIR STEP FROM OPENING A HOLE. Two blocks touching only
266
+ // along a diagonal each see air on both faces at that edge; cutting both back on the two-face test
267
+ // alone leaves a diamond you can see the sky through. Mirrors edgeOpen() in TS — see bevelVertex.
268
+ fn edgeOpen(mask: u32, a: vec3<f32>, b: vec3<f32>) -> f32 {
269
+ if (mask == 0u) { return 0.0; } // unknown ⇒ no bevel, see CubeInstance.occ
270
+ return (1.0 - occAt(mask, a)) * (1.0 - occAt(mask, b)) * (1.0 - occAt(mask, a + b));
271
+ }
272
+ // The vertex rule. A vertex's pull along a free axis is INWARD, gated by the edge between its home
273
+ // face and the face on that side. Both primitives that share a vertex resolve the same face/axis
274
+ // pair, so they cannot land in different places — that is where watertightness comes from, and it
275
+ // is why this takes (corner, home) rather than a vertex index.
276
+ fn bevelPos(mask: u32, c: vec3<f32>, a: vec3<f32>, bevel: f32) -> vec3<f32> {
277
+ if (bevel <= 0.0 || mask == 0u) { return c; }
278
+ let free = vec3(1.0, 1.0, 1.0) - abs(a); // the two in-face axes; the face axis is never pulled
279
+ let s = sign(c);
280
+ var d = vec3(0.0, 0.0, 0.0);
281
+ d.x = free.x * s.x * bevel * edgeOpen(mask, a, vec3(s.x, 0.0, 0.0));
282
+ d.y = free.y * s.y * bevel * edgeOpen(mask, a, vec3(0.0, s.y, 0.0));
283
+ d.z = free.z * s.z * bevel * edgeOpen(mask, a, vec3(0.0, 0.0, s.z));
284
+ return c - d;
285
+ }
115
286
  // Vertex AO for cube vertex vi, in [AO_MIN, 1]. Every cube vertex sits at a CORNER, so CUBE_POS is
116
287
  // (±0.5,±0.5,±0.5) and its sign gives the two in-plane directions once the face axis is masked off.
117
- fn cornerAO(mask: u32, vi: u32) -> f32 {
288
+ // Takes the corner and normal directly, because the BEVELED cube's vertex index no longer selects a
289
+ // corner on its own — three of its vertices can share one.
290
+ fn cornerAOAt(mask: u32, c: vec3<f32>, n: vec3<f32>) -> f32 {
118
291
  if (mask == 0u) { return 1.0; } // unknown ⇒ no AO, see CubeInstance.occ
119
- let n = CUBE_NRM[vi];
120
- let ip = sign(CUBE_POS[vi]) * (vec3(1.0, 1.0, 1.0) - abs(n));
292
+ let ip = sign(c) * (vec3(1.0, 1.0, 1.0) - abs(n));
121
293
  var a1 = vec3(0.0, 0.0, 0.0);
122
294
  var a2 = vec3(0.0, 0.0, 0.0);
123
295
  if (abs(n.x) > 0.5) { a1 = vec3(0.0, ip.y, 0.0); a2 = vec3(0.0, 0.0, ip.z); }
@@ -136,6 +308,10 @@ fn cornerAO(mask: u32, vi: u32) -> f32 {
136
308
  if (s1 > 0.5 && s2 > 0.5) { lvl = 0.0; }
137
309
  return mix(${AO_MIN}, 1.0, lvl / 3.0);
138
310
  }
311
+ // The 36-vertex cube's form, unchanged for every caller that still indexes CUBE_POS/CUBE_NRM.
312
+ fn cornerAO(mask: u32, vi: u32) -> f32 {
313
+ return cornerAOAt(mask, CUBE_POS[vi], CUBE_NRM[vi]);
314
+ }
139
315
  fn hsv(hh: f32) -> vec3<f32> {
140
316
  let h = fract(hh) * 6.0;
141
317
  let x = 1.0 - abs((h % 2.0) - 1.0);
@@ -290,10 +466,19 @@ struct GiGrid { org: vec4<f32>, dim: vec4<f32> };
290
466
  @group(0) @binding(9) var<storage, read> probes: array<vec4<f32>>;
291
467
  ${GI_WGSL}
292
468
 
469
+ // ⚠️ objN IS FLAT AND HAS TO BE. fs() picks the in-face axis pair AND the atlas top/side/bottom
470
+ // variant from the DOMINANT AXIS of objN. A bevel band spans two faces, so a smooth objN would
471
+ // sweep from one face normal to the other and flip that dominant axis halfway across — a hard seam
472
+ // straight down the middle of every rounded edge, with the tile variant changing at the same line.
473
+ // Flat gives each band one face's parameterization (the provoking vertex is the FIRST, which is why
474
+ // buildBevelCube emits the owning face's vertex first). This is a no-op for the sharp cube: all
475
+ // three vertices of a plain face triangle already carry the same objN. nrm stays smooth — that is
476
+ // the varying that does the rounding.
477
+ //
293
478
  // vao is deliberately NOT flat: per-corner AO is computed once per vertex and the rasterizer's
294
479
  // interpolation across the quad IS the gradient — that smooth ramp into a crease is the whole
295
480
  // effect, and it costs nothing.
296
- struct VOut { @builtin(position) clip: vec4<f32>, @location(0) world: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) hue: f32, @location(3) emis: f32, @location(4) blk: vec3<f32>, @location(5) objN: vec3<f32>, @location(6) tile: f32, @location(7) upc: f32, @location(8) @interpolate(flat) decal: vec2<f32>, @location(9) vao: f32, @location(10) @interpolate(flat) jit: f32 };
481
+ struct VOut { @builtin(position) clip: vec4<f32>, @location(0) world: vec3<f32>, @location(1) nrm: vec3<f32>, @location(2) hue: f32, @location(3) emis: f32, @location(4) blk: vec3<f32>, @location(5) @interpolate(flat) objN: vec3<f32>, @location(6) tile: f32, @location(7) upc: f32, @location(8) @interpolate(flat) decal: vec2<f32>, @location(9) vao: f32, @location(10) @interpolate(flat) jit: f32 };
297
482
 
298
483
  fn faceVec(code: f32) -> vec3<f32> {
299
484
  let c = i32(code);
@@ -304,11 +489,23 @@ fn faceVec(code: f32) -> vec3<f32> {
304
489
 
305
490
  @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut {
306
491
  let inst = insts[vis[ii]];
307
- let world = worldOf(inst, vi);
492
+ // The 27-bit occupancy mask, reassembled from the 14/13 split fill() had to make because an f32
493
+ // is exact only to 2^24. Drives BOTH the corner AO and the edge bevel.
494
+ let mask = u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u);
495
+ // THE BEVELED CUBE. cam.eye.w is the bevel amount; at 0 — every caller that has not opted in —
496
+ // bevelPos returns the sharp corner and this is buildCube()'s geometry exactly. The draw is only
497
+ // 36 vertices long in that case anyway (see the indirect args), so the tail is never even reached.
498
+ let sharp = BEV_CORNER[vi];
499
+ let home = BEV_HOME[vi];
500
+ let local = bevelPos(mask, sharp, home, cam.eye.w);
501
+ let world = inst.pos.xyz + qrot(inst.rot, local * inst.scl.xyz);
308
502
  var o: VOut;
309
503
  o.clip = cam.camVP * vec4(world, 1.0);
310
504
  o.world = world;
311
- o.nrm = normalize(qrot(inst.rot, CUBE_NRM[vi] / inst.scl.xyz)); // normal under non-uniform scale + rotation
505
+ // SMOOTH ACROSS THE BAND, BY DESIGN. A bevel band's two long sides carry different home normals,
506
+ // and letting the rasterizer sweep between them is the entire reason a 45° cut reads as a curve
507
+ // rather than a bright faceted line. (Normal under non-uniform scale + rotation.)
508
+ o.nrm = normalize(qrot(inst.rot, home / inst.scl.xyz));
312
509
  o.hue = inst.pos.w;
313
510
  o.emis = inst.scl.w;
314
511
  // OBJECT-space block coord (per-sub-block units, anchored to the model, NOT world) so per-block AO moves +
@@ -316,12 +513,17 @@ fn faceVec(code: f32) -> vec3<f32> {
316
513
  // by inst.scl so a merged LOD cube (scl>1) still shows its sub-blocks — UNLESS aux2.w (texFit) says the
317
514
  // instance is ONE block drawn at a registered scale, where the multiply would just repeat its tile scale×.
318
515
  let tscl = select(inst.scl.xyz, vec3<f32>(1.0, 1.0, 1.0), vec3<bool>(inst.aux2.w != 0.0));
319
- o.blk = (CUBE_POS[vi] + vec3(0.5, 0.5, 0.5)) * tscl;
320
- o.objN = CUBE_NRM[vi]; // objN = pre-rotation face normal
516
+ // ⚠️ FROM THE BEVELED POSITION, NOT THE SHARP CORNER. Deriving blk from the sharp corner makes it
517
+ // CONSTANT across a band's width, and a face's far corner gives blk = 1.0, so fract(1.0) = 0.0
518
+ // would make every band sample the tile's OPPOSITE edge — a visibly wrong sliver on every rounded
519
+ // edge in the world. From the beveled position the mapping is continuous and covers the tile
520
+ // exactly once: the face spans [b, 1-b] and the two bands take [0, b] and [1-b, 1].
521
+ o.blk = (local + vec3(0.5, 0.5, 0.5)) * tscl;
522
+ o.objN = home; // objN = pre-rotation face normal, FLAT — see VOut
321
523
  o.tile = inst.aux.x; o.upc = inst.aux.y; o.decal = inst.aux.zw;
322
- // The 27-bit occupancy mask, reassembled from the 14/13 split fill() had to make because an f32
323
- // is exact only to 2^24.
324
- o.vao = cornerAO(u32(inst.aux2.x) | (u32(inst.aux2.y) << 14u), vi);
524
+ // ⚠️ AO READS THE SHARP CORNER. It is a property of that corner's neighbourhood, and its sign()
525
+ // derivation needs components that are exactly ±0.5 — a beveled position would round to nothing.
526
+ o.vao = cornerAOAt(mask, sharp, home);
325
527
  o.jit = inst.aux2.z;
326
528
  return o;
327
529
  }
@@ -682,6 +884,7 @@ export class GpuShadowRenderer {
682
884
  matQuality = 0; // see setMaterialQuality — 0 keeps the pre-material look exactly
683
885
  matCutoff = 28; // world units; parallax fades out before here
684
886
  eye = new Float32Array(3);
887
+ bevel = 0; // see setBevel — 0 keeps the sharp cube exactly, and draws only 36 vertices
685
888
  alphaPipe;
686
889
  alphaBGL; // kept so the overlay buffer can grow and rebind on demand
687
890
  overlayBuf;
@@ -1097,9 +1300,11 @@ export class GpuShadowRenderer {
1097
1300
  this.lightCullBG = this.lightArgs.map((a, i) => this.cullBG(a, this.lightVis[i], this.lightCull[i]));
1098
1301
  }
1099
1302
  scratch = new Float32Array(0);
1100
- fill(scratch, instances, n) {
1303
+ fill(scratch, instances, n,
1304
+ /** Destination slot of `instances[0]`. Non-zero only for `updateInstanceRange`. */
1305
+ at = 0) {
1101
1306
  for (let i = 0; i < n; i++) {
1102
- const c = instances[i], o = i * INST_F, r = c.rot;
1307
+ const c = instances[i], o = (at + i) * INST_F, r = c.rot;
1103
1308
  scratch[o] = c.x;
1104
1309
  scratch[o + 1] = c.y;
1105
1310
  scratch[o + 2] = c.z;
@@ -1206,6 +1411,23 @@ export class GpuShadowRenderer {
1206
1411
  this.eye[1] = y;
1207
1412
  this.eye[2] = z;
1208
1413
  }
1414
+ /**
1415
+ * ROUND THE EXPOSED EDGES of every cube that supplies a `CubeInstance.occ` mask, by `amount`
1416
+ * block-fractions (0.06 is a subtle rim; 0.2 is pebble-like). 0 — the default — is the sharp cube.
1417
+ *
1418
+ * Only edges open to air on BOTH adjacent faces and on the cell diagonally between them are cut
1419
+ * back, so blocks that touch still meet flush and a stair step cannot open a hole. An instance
1420
+ * without a mask (`occ` absent ⇒ 0, the "unknown" sentinel) is never beveled, which is why the far
1421
+ * field, sky-body shells, ships, creatures and props stay sharp with no work on their part.
1422
+ *
1423
+ * ⚠️ NOT FREE WHILE IT IS ON. A non-zero amount draws 132 vertices per instance instead of 36 in
1424
+ * the CAMERA pass — for every instance, beveled or not, because they all ride one indirect draw.
1425
+ * The shadow pass keeps the sharp cube either way. At 0 the vertex count drops back to 36, so
1426
+ * leaving this alone costs exactly what it cost before the feature existed.
1427
+ */
1428
+ setBevel(amount) {
1429
+ this.bevel = Math.max(0, amount);
1430
+ }
1209
1431
  setAtlas(tex, layout) {
1210
1432
  this.atlasView = tex.createView({ dimension: '2d-array' });
1211
1433
  const ids = Object.keys(layout.tiles).map(Number);
@@ -1257,6 +1479,50 @@ export class GpuShadowRenderer {
1257
1479
  this.device.queue.writeBuffer(this.instBuf, 0, this.scratch, 0, n * INST_F);
1258
1480
  this.count = n;
1259
1481
  }
1482
+ /**
1483
+ * Rewrite ONE RANGE of the instance buffer and leave the rest of it alone.
1484
+ *
1485
+ * `updateInstances` repacks and re-uploads EVERYTHING, so a caller whose scene is mostly static pays for
1486
+ * all of it to move one cube. In a voxel game that is the whole cost: measured in all-mine-sky, a 63 000
1487
+ * instance scene costs ~7 ms of main thread per frame to repack and write, and the only thing changing on
1488
+ * a typical frame is a first-person viewmodel of a few dozen cubes. The pack is linear in instance count
1489
+ * — ~0.1 µs each — so the fix is to not do it for instances that did not change.
1490
+ *
1491
+ * The contract is deliberately dumb: this writes `instances` starting at slot `first` and nothing else.
1492
+ * It does not move the draw count (use `setInstanceCount`), and it does not know what your segments are.
1493
+ * The caller owns the layout, because only the caller knows which of its sources changed.
1494
+ *
1495
+ * // ground 0..47999, sky 48000..62999, dynamic 63000..
1496
+ * if (skyMoved) r.updateInstanceRange(sky, 48000)
1497
+ * r.updateInstanceRange(dynamic, 63000)
1498
+ * r.setInstanceCount(63000 + dynamic.length)
1499
+ *
1500
+ * ⚠️ SLOTS ARE NOT REORDERED. A range write leaves whatever was in the untouched slots exactly as it was,
1501
+ * so a layout whose segment offsets shift when one segment resizes must re-upload from the first moved
1502
+ * slot onward. Reserving fixed capacity per segment avoids that; packing tight does not.
1503
+ *
1504
+ * Out-of-range and empty writes are no-ops rather than errors: a caller assembling a frame should not
1505
+ * have to special-case "this segment happens to be empty right now".
1506
+ */
1507
+ updateInstanceRange(instances, first) {
1508
+ const capN = (this.scratch.length / INST_F) | 0;
1509
+ if (first < 0 || first >= capN)
1510
+ return;
1511
+ const n = Math.min(instances.length, capN - first);
1512
+ if (n <= 0)
1513
+ return;
1514
+ this.fill(this.scratch, instances, n, first);
1515
+ this.device.queue.writeBuffer(this.instBuf, first * INST_F * 4, // byte offset — INST_F floats per instance, 4 bytes each
1516
+ this.scratch, first * INST_F, // element offset into scratch
1517
+ n * INST_F);
1518
+ if (first + n > this.count)
1519
+ this.count = first + n;
1520
+ }
1521
+ /** How many instances the cull + draw passes consider, whatever is in the buffer past that. Pairs with
1522
+ * `updateInstanceRange`: shrinking the dynamic tail is a count change, not an upload. */
1523
+ setInstanceCount(n) {
1524
+ this.count = Math.max(0, Math.min(n, (this.scratch.length / INST_F) | 0));
1525
+ }
1260
1526
  /** Translucent overlay cubes drawn over the opaque scene; `emissive` carries per-cube alpha (0..1). The buffer
1261
1527
  * GROWS to fit (no hard cap). Pass `eye` to SORT the cubes back-to-front (farthest first) so overlapping
1262
1528
  * translucent cubes blend in the correct order — required for anything denser than the place ghost. By default
@@ -1434,6 +1700,7 @@ export class GpuShadowRenderer {
1434
1700
  this.cam[S + 24] = this.eye[0];
1435
1701
  this.cam[S + 25] = this.eye[1];
1436
1702
  this.cam[S + 26] = this.eye[2];
1703
+ this.cam[S + 27] = this.bevel; // eye.w — the edge bevel amount, see setBevel
1437
1704
  this.device.queue.writeBuffer(this.camBuf, 0, this.cam);
1438
1705
  // Each cascade's shadow pass reads its OWN copy with that cascade's matrix parked at lightVP[0].
1439
1706
  for (let i = 0; i < nc; i++) {
@@ -1447,10 +1714,15 @@ export class GpuShadowRenderer {
1447
1714
  // GPU-DRIVEN CULL: reset each frustum's indirect args ([vertexCount=36, instanceCount=0, 0, 0]), then compute-cull
1448
1715
  // — main pass vs the camera frustum (+ Hi-Z occlusion), shadow pass vs the light frustum. Each dispatch atomically
1449
1716
  // compacts its survivors into a visible list + counts them in instanceCount, which the matching drawIndirect consumes.
1450
- const resetArgs = new Uint32Array([36, 0, 0, 0]);
1451
- this.device.queue.writeBuffer(this.camArgs, 0, resetArgs);
1717
+ // ⚠️ TWO RESETS, NOT ONE, AND THE VERTEX COUNTS DIFFER ON PURPOSE. The camera pass draws the
1718
+ // beveled cube's 132 vertices only while a bevel is actually set; at 0 it draws the first 36,
1719
+ // which buildBevelCube guarantees ARE the sharp cube. The shadow pass always draws 36 — a 6% cut
1720
+ // is invisible in a shadow map and there is no reason to quadruple the cascades' vertex work.
1721
+ const camVerts = this.bevel > 0 ? BEVEL_VERTS : SHARP_VERTS;
1722
+ this.device.queue.writeBuffer(this.camArgs, 0, new Uint32Array([camVerts, 0, 0, 0]));
1723
+ const lightReset = new Uint32Array([SHARP_VERTS, 0, 0, 0]);
1452
1724
  for (const a of this.lightArgs)
1453
- this.device.queue.writeBuffer(a, 0, resetArgs);
1725
+ this.device.queue.writeBuffer(a, 0, lightReset);
1454
1726
  this.writeCull(this.camCull, camVP, occludeNow);
1455
1727
  for (let i = 0; i < nc; i++)
1456
1728
  this.writeCull(this.lightCull[i], mats[i], false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.4",
3
+ "version": "0.15.6",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {