@thoughts-on-things/vantage-mc 0.3.0 → 0.5.0

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.
@@ -1,4 +1,4 @@
1
- import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-M6KVJXCR.js';
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-EVPUXVSB.js';
2
2
  import * as THREE2 from 'three';
3
3
 
4
4
  var SKY_TOP = [0.3, 0.52, 0.84];
@@ -26,7 +26,7 @@ var VERT = (
26
26
  in float alight; // packed (sky<<4)|block, 0..255
27
27
  #endif
28
28
  #ifdef LIGHTMAP
29
- // Atlas-lit geometry (VTL8's greedy tail): baked light + AO come from a
29
+ // Atlas-lit geometry (VTL8+'s greedy tail): baked light + AO come from a
30
30
  // per-tile texture sampled in the fragment shader \u2014 per-BLOCK gradients on
31
31
  // arbitrarily large merged quads \u2014 instead of per-vertex values.
32
32
  in vec2 almuv; // half-texel atlas coords
@@ -45,6 +45,7 @@ var VERT = (
45
45
  out float vFog;
46
46
  out float vSky; // saved sky light, 0..1
47
47
  out float vBlk; // saved block light, 0..1
48
+ out float vWorldY; // world-space Y, for the depth slice
48
49
  void main() {
49
50
  vTint = atint;
50
51
  vLayer = alayer;
@@ -75,6 +76,7 @@ var VERT = (
75
76
  // texture frames (see the fragment shader's uAnim/uTime).
76
77
  vN = normalize(mat3(modelMatrix) * nrm);
77
78
  vec4 wp = modelMatrix * vec4(pos, 1.0);
79
+ vWorldY = wp.y;
78
80
  vec4 mv = viewMatrix * wp;
79
81
  // Streamed worlds fog by horizontal distance from the streaming focus \u2014
80
82
  // exactly the ring where tiles stop \u2014 so looking straight down from any
@@ -107,6 +109,12 @@ var FRAG = (
107
109
  uniform float uSaturation; // colour saturation (1 = neutral)
108
110
  uniform float uContrast; // colour contrast around mid grey (1 = neutral)
109
111
  uniform float uFogDensity; // atmospheric haze amount (1 = full, 0 = clear)
112
+ uniform float uClipY; // depth-slice plane: fragments above this world Y
113
+ // are cut away (1e9 = slice off). See setSlice().
114
+ uniform float uFade; // per-tile stream-in fade (set per mesh, 0..1):
115
+ // alpha-to-coverage dithers it under MSAA, so new
116
+ // tiles dissolve in over the lowres placeholder
117
+ // instead of popping their lighting on.
110
118
  in vec2 vUv;
111
119
  in vec4 vTint;
112
120
  in vec3 vBcol;
@@ -116,8 +124,10 @@ var FRAG = (
116
124
  in float vFog;
117
125
  in float vSky;
118
126
  in float vBlk;
127
+ in float vWorldY;
119
128
  #ifdef LIGHTMAP
120
129
  uniform sampler2D uLightmap; // per-tile baked light+AO atlas
130
+ uniform float uLmPacked; // 1 = VTL9 packed RG8
121
131
  in vec2 vLmUv;
122
132
  #endif
123
133
  out vec4 frag;
@@ -173,7 +183,18 @@ var FRAG = (
173
183
  return max(c, vec3(0.0));
174
184
  }
175
185
 
186
+ #ifdef LIGHTMAP
187
+ vec3 decodePackedLight(vec2 rg) {
188
+ float packed = floor(rg.r * 255.0 + 0.5);
189
+ return vec3(floor(packed / 16.0), mod(packed, 16.0), rg.g);
190
+ }
191
+ #endif
192
+
176
193
  void main() {
194
+ // Depth slice (cave view): cut everything above the clip plane. With
195
+ // backface culling on, the first thing visible below the cut is a cave
196
+ // FLOOR (ceilings face away) \u2014 exactly the readable cave-map view.
197
+ if (vWorldY > uClipY) discard;
177
198
  // Light + AO source: per-vertex (interpolated), or \u2014 for atlas-lit
178
199
  // geometry \u2014 the tile lightmap, whose bilinear filter reproduces the
179
200
  // per-block-corner values exactly and keeps gradients inside big quads.
@@ -181,10 +202,32 @@ var FRAG = (
181
202
  float blkL = vBlk;
182
203
  float aoV = vTint.a;
183
204
  #ifdef LIGHTMAP
184
- vec3 lmS = texture(uLightmap, vLmUv).rgb;
185
- skyL = lmS.r;
186
- blkL = lmS.g;
187
- aoV = lmS.b;
205
+ if (uLmPacked > 0.5) {
206
+ // Packing sky/block into one byte is lossless, but filtering that byte
207
+ // before unpacking would mix the nibbles. Fetch and decode the four
208
+ // neighbours first, then reproduce bilinear interpolation exactly.
209
+ vec2 p = vLmUv * vec2(textureSize(uLightmap, 0)) - 0.5;
210
+ ivec2 base = ivec2(floor(p));
211
+ vec2 f = fract(p);
212
+ ivec2 hi = textureSize(uLightmap, 0) - 1;
213
+ vec2 s00 = texelFetch(uLightmap, clamp(base, ivec2(0), hi), 0).rg;
214
+ vec2 s10 = texelFetch(uLightmap, clamp(base + ivec2(1, 0), ivec2(0), hi), 0).rg;
215
+ vec2 s01 = texelFetch(uLightmap, clamp(base + ivec2(0, 1), ivec2(0), hi), 0).rg;
216
+ vec2 s11 = texelFetch(uLightmap, clamp(base + ivec2(1, 1), ivec2(0), hi), 0).rg;
217
+ vec3 l00 = decodePackedLight(s00);
218
+ vec3 l10 = decodePackedLight(s10);
219
+ vec3 l01 = decodePackedLight(s01);
220
+ vec3 l11 = decodePackedLight(s11);
221
+ vec3 lmS = mix(mix(l00, l10, f.x), mix(l01, l11, f.x), f.y);
222
+ skyL = lmS.r / 15.0;
223
+ blkL = lmS.g / 15.0;
224
+ aoV = lmS.b;
225
+ } else {
226
+ vec3 lmS = texture(uLightmap, vLmUv).rgb;
227
+ skyL = lmS.r;
228
+ blkL = lmS.g;
229
+ aoV = lmS.b;
230
+ }
188
231
  #endif
189
232
  float lightAmt; vec3 lightCol;
190
233
  bakedLight(skyL, blkL, lightAmt, lightCol);
@@ -232,7 +275,7 @@ var FRAG = (
232
275
  vec3 wlit = grade(wcol * (0.62 + 0.28 * SUN * ndl2) * lightAmt * lightCol * uExposure);
233
276
  float wf = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
234
277
  float wa = mix(0.5, 0.74, depth); // blue tint, seabed still reads through
235
- frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa);
278
+ frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa * uFade);
236
279
  return;
237
280
  }
238
281
 
@@ -254,8 +297,13 @@ var FRAG = (
254
297
  vec3 hemi = mix(GND, SKY, 0.5 + 0.5 * N.y);
255
298
  vec3 shade = mix(vec3(1.0), hemi, 0.16) * fshade;
256
299
  vec3 lit = grade(base * shade * ao * lightAmt * lightCol * uExposure);
300
+ // Depth-slice cut edge: a thin warm rim on the top ~1.5 blocks below the
301
+ // clip plane outlines the section like a CAD cutaway. Free when the slice
302
+ // is off \u2014 uClipY sits ~1e9 above any terrain, so cut is exactly 0.
303
+ float cut = 1.0 - smoothstep(0.0, 1.5, uClipY - vWorldY);
304
+ lit += vec3(1.0, 0.72, 0.35) * (0.2 * cut);
257
305
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity; // aerial depth into the horizon
258
- frag = vec4(toSRGB(mix(lit, fogCol, f)), uAlpha * t.a); // alpha \u2192 MSAA coverage (foliage AA)
306
+ frag = vec4(toSRGB(mix(lit, fogCol, f)), uAlpha * t.a * uFade); // alpha \u2192 MSAA coverage (foliage AA)
259
307
  }
260
308
  `
261
309
  );
@@ -293,7 +341,7 @@ function paletteTexture(palette) {
293
341
  tex.needsUpdate = true;
294
342
  return tex;
295
343
  }
296
- function createTerrainMaterial(texData, opts = {}) {
344
+ function buildArrayTexture(texData) {
297
345
  const tex = new THREE2.DataArrayTexture(texData.pixels, texData.width, texData.height, texData.layers);
298
346
  tex.format = THREE2.RGBAFormat;
299
347
  tex.type = THREE2.UnsignedByteType;
@@ -304,6 +352,22 @@ function createTerrainMaterial(texData, opts = {}) {
304
352
  tex.wrapS = THREE2.RepeatWrapping;
305
353
  tex.wrapT = THREE2.RepeatWrapping;
306
354
  tex.needsUpdate = true;
355
+ return tex;
356
+ }
357
+ function updateTerrainTextures(material, texData) {
358
+ const mapU = material.uniforms["map"];
359
+ if (mapU) {
360
+ mapU.value?.dispose();
361
+ mapU.value = buildArrayTexture(texData);
362
+ }
363
+ const animU = material.uniforms["uAnim"];
364
+ if (animU) {
365
+ animU.value?.dispose();
366
+ animU.value = animLutTexture(texData.layers, texData.anims ?? []);
367
+ }
368
+ }
369
+ function createTerrainMaterial(texData, opts = {}) {
370
+ const tex = buildArrayTexture(texData);
307
371
  return new THREE2.ShaderMaterial({
308
372
  glslVersion: THREE2.GLSL3,
309
373
  defines: opts.quantized ? { QUANTIZED: "" } : {},
@@ -321,6 +385,7 @@ function createTerrainMaterial(texData, opts = {}) {
321
385
  // material — see createLightmappedMaterial; inert here).
322
386
  uLightmap: { value: null },
323
387
  uLmSize: { value: new THREE2.Vector2(1, 1) },
388
+ uLmPacked: { value: 0 },
324
389
  uPalette: { value: opts.quantized ? paletteTexture(opts.palette ?? []) : null },
325
390
  uFogCenter: { value: new THREE2.Vector2() },
326
391
  // streaming focus (world XZ)
@@ -348,8 +413,12 @@ function createTerrainMaterial(texData, opts = {}) {
348
413
  // colour saturation (1 = neutral)
349
414
  uContrast: { value: 1 },
350
415
  // colour contrast (1 = neutral)
351
- uFogDensity: { value: 1 }
416
+ uFogDensity: { value: 1 },
352
417
  // atmospheric haze amount (1 = full)
418
+ uClipY: { value: 1e9 },
419
+ // depth-slice plane (1e9 = off)
420
+ uFade: { value: 1 }
421
+ // stream-in fade; written per mesh each draw
353
422
  },
354
423
  vertexShader: VERT,
355
424
  fragmentShader: FRAG,
@@ -400,7 +469,11 @@ function createLowresMaterial(terrain) {
400
469
  uFogDensity: t["uFogDensity"],
401
470
  uExposure: t["uExposure"],
402
471
  uSaturation: t["uSaturation"],
403
- uContrast: t["uContrast"]
472
+ uContrast: t["uContrast"],
473
+ uClipY: t["uClipY"],
474
+ // Own fade uniform (not the terrain's ref): both are rewritten per mesh
475
+ // each draw, but separate objects keep the two materials independent.
476
+ uFade: { value: 1 }
404
477
  },
405
478
  vertexShader: (
406
479
  /* glsl */
@@ -410,9 +483,11 @@ function createLowresMaterial(terrain) {
410
483
  uniform float uFogRadial;
411
484
  out vec3 vCol;
412
485
  out float vFog;
486
+ out float vWorldY;
413
487
  void main() {
414
488
  vCol = acol;
415
489
  vec4 wp = modelMatrix * vec4(position, 1.0);
490
+ vWorldY = wp.y;
416
491
  vec4 mv = viewMatrix * wp;
417
492
  vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
418
493
  gl_Position = projectionMatrix * mv;
@@ -429,8 +504,11 @@ function createLowresMaterial(terrain) {
429
504
  uniform float uExposure;
430
505
  uniform float uSaturation;
431
506
  uniform float uContrast;
507
+ uniform float uClipY;
508
+ uniform float uFade;
432
509
  in vec3 vCol;
433
510
  in float vFog;
511
+ in float vWorldY;
434
512
  out vec4 frag;
435
513
  vec3 toLinear(vec3 c) {
436
514
  return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
@@ -440,15 +518,21 @@ function createLowresMaterial(terrain) {
440
518
  return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
441
519
  }
442
520
  void main() {
521
+ // The lowres rings clip with the hires terrain (shared uClipY), so the
522
+ // depth slice cuts the whole world, not just the streamed disc.
523
+ if (vWorldY > uClipY) discard;
443
524
  vec3 c = toLinear(vCol) * uExposure;
444
525
  float l = dot(c, vec3(0.299, 0.587, 0.114));
445
526
  c = mix(vec3(l), c, uSaturation);
446
527
  c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
447
528
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
448
- frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
529
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), uFade);
449
530
  }
450
531
  `
451
- )
532
+ ),
533
+ // Turns the stream-in fade's fractional alpha into MSAA coverage (the
534
+ // material is otherwise fully opaque, so this costs nothing once faded).
535
+ alphaToCoverage: true
452
536
  });
453
537
  }
454
538
  function createSky() {
@@ -522,12 +606,17 @@ function baseGeometry(section) {
522
606
  }
523
607
  var WATER_FALLBACK = [0.3, 0.5, 0.85];
524
608
  function lightmapTexture(lm) {
525
- const tex = new THREE2.DataTexture(lm.pixels, lm.width, lm.height, THREE2.RGBAFormat, THREE2.UnsignedByteType);
526
- tex.magFilter = THREE2.LinearFilter;
527
- tex.minFilter = THREE2.LinearFilter;
609
+ const format = lm.packed ? THREE2.RGFormat : THREE2.RGBAFormat;
610
+ const tex = new THREE2.DataTexture(lm.pixels, lm.width, lm.height, format, THREE2.UnsignedByteType);
611
+ tex.magFilter = lm.packed ? THREE2.NearestFilter : THREE2.LinearFilter;
612
+ tex.minFilter = lm.packed ? THREE2.NearestFilter : THREE2.LinearFilter;
528
613
  tex.wrapS = THREE2.ClampToEdgeWrapping;
529
614
  tex.wrapT = THREE2.ClampToEdgeWrapping;
530
615
  tex.generateMipmaps = false;
616
+ tex.userData["vantageGpuBytes"] = lm.pixels.byteLength;
617
+ tex.onUpdate = () => {
618
+ tex.image.data = null;
619
+ };
531
620
  tex.needsUpdate = true;
532
621
  return tex;
533
622
  }
@@ -619,6 +708,7 @@ function quantizedMesh(sec, material, lm) {
619
708
  if (lm) {
620
709
  m.uniforms["uLightmap"].value = lm.tex;
621
710
  m.uniforms["uLmSize"].value.copy(lm.size);
711
+ m.uniforms["uLmPacked"].value = lm.packed ? 1 : 0;
622
712
  }
623
713
  m.uniformsNeedUpdate = true;
624
714
  };
@@ -637,7 +727,11 @@ function buildQuantizedTileMeshes(tile, material, waterMaterial, lmMaterial) {
637
727
  const lm = tile.lightmap;
638
728
  lightmapTex = lightmapTexture(lm);
639
729
  const tail = sliceSection(solid, lmStart, solid.vertexCount);
640
- terrainLm = quantizedMesh(tail, lmMaterial, { tex: lightmapTex, size: new THREE2.Vector2(lm.width, lm.height) });
730
+ terrainLm = quantizedMesh(tail, lmMaterial, {
731
+ tex: lightmapTex,
732
+ size: new THREE2.Vector2(lm.width, lm.height),
733
+ packed: lm.packed
734
+ });
641
735
  terrainLm.geometry.setAttribute("almuv", new THREE2.BufferAttribute(solid.lmuv, 2, false));
642
736
  }
643
737
  let water;
@@ -741,6 +835,46 @@ var Emitter = class {
741
835
  }
742
836
  };
743
837
 
838
+ // src/three/streaming.ts
839
+ function nearbyTiles(index, tileBlocks, focusX, focusZ, radius, predictedX = focusX, predictedZ = focusZ) {
840
+ const radiusSq = radius * radius;
841
+ const minX = Math.floor((focusX - radius) / tileBlocks - 0.5);
842
+ const maxX = Math.ceil((focusX + radius) / tileBlocks - 0.5);
843
+ const minZ = Math.floor((focusZ - radius) / tileBlocks - 0.5);
844
+ const maxZ = Math.ceil((focusZ + radius) / tileBlocks - 0.5);
845
+ const out = [];
846
+ for (let z = minZ; z <= maxZ; z++) {
847
+ for (let x = minX; x <= maxX; x++) {
848
+ const ref = index.get(tileKey(x, z));
849
+ if (!ref) continue;
850
+ const cx = (x + 0.5) * tileBlocks;
851
+ const cz = (z + 0.5) * tileBlocks;
852
+ const dx = cx - focusX;
853
+ const dz = cz - focusZ;
854
+ const distanceSq = dx * dx + dz * dz;
855
+ if (distanceSq > radiusSq) continue;
856
+ const px = cx - predictedX;
857
+ const pz = cz - predictedZ;
858
+ const priority = distanceSq * 0.72 + (px * px + pz * pz) * 0.28;
859
+ out.push({ ref, distanceSq, priority });
860
+ }
861
+ }
862
+ out.sort((a, b) => a.priority - b.priority || a.distanceSq - b.distanceSq);
863
+ return out;
864
+ }
865
+ function admitTiles(candidates, maxTiles, maxBytes, estimateBytes) {
866
+ const admitted = [];
867
+ let bytes = 0;
868
+ for (const candidate of candidates) {
869
+ if (admitted.length >= maxTiles) break;
870
+ const weight = Math.max(1, estimateBytes(candidate.ref));
871
+ if (admitted.length > 0 && bytes + weight > maxBytes) continue;
872
+ admitted.push(candidate);
873
+ bytes += weight;
874
+ }
875
+ return admitted;
876
+ }
877
+
744
878
  // src/three/tiles.ts
745
879
  function recKey(level, x, z) {
746
880
  return level === 0 ? tileKey(x, z) : `l${level}:${x},${z}`;
@@ -754,10 +888,32 @@ function releaseAfterUpload(geom) {
754
888
  }
755
889
  if (geom.index && !isSharedQuadIndex(geom.index)) geom.index.onUpload(release);
756
890
  }
757
- var TileManager = class {
891
+ function arrayBytes(value) {
892
+ return ArrayBuffer.isView(value) ? value.byteLength : 0;
893
+ }
894
+ function geometryBytes(geom) {
895
+ let bytes = 0;
896
+ for (const name of Object.keys(geom.attributes)) {
897
+ bytes += arrayBytes(geom.getAttribute(name).array);
898
+ }
899
+ if (geom.index && !isSharedQuadIndex(geom.index)) bytes += arrayBytes(geom.index.array);
900
+ return bytes;
901
+ }
902
+ function textureBytes(texture) {
903
+ if (!texture) return 0;
904
+ const gpuBytes = texture.userData["vantageGpuBytes"];
905
+ return typeof gpuBytes === "number" ? gpuBytes : arrayBytes(texture.image.data);
906
+ }
907
+ var TileManager = class _TileManager {
758
908
  opts;
759
909
  lowresMaterial;
760
910
  lmMaterial;
911
+ /** Widens the shared atlas to cover a tile's layers before it's drawn (live
912
+ * renders only); null when the atlas is complete. */
913
+ ensureAtlas;
914
+ /** Best-known covered atlas layer count. `Infinity` disables the gate — a
915
+ * static render never grows its atlas. */
916
+ atlasLayers;
761
917
  index = /* @__PURE__ */ new Map();
762
918
  records = /* @__PURE__ */ new Map();
763
919
  emitter = new Emitter();
@@ -768,10 +924,15 @@ var TileManager = class {
768
924
  lowIndex = /* @__PURE__ */ new Map();
769
925
  /** Set when residency changed and lowres visibility needs recomputing. */
770
926
  coverageDirty = false;
927
+ /** Tiles mid stream-in fade; drained by update(), keeps the viewer drawing. */
928
+ fadingKeys = /* @__PURE__ */ new Set();
771
929
  queue = [];
772
930
  /** Built tiles awaiting scene insertion — flushed ONE per update() call so
773
931
  * multi-MB GPU uploads never pile into a single frame. */
774
932
  pendingAdd = [];
933
+ /** Built records still holding upload-pending typed arrays. Pumping pauses at
934
+ * one concurrency-window so decode cannot outrun GPU submission. */
935
+ pendingBuilt = 0;
775
936
  inFlight = 0;
776
937
  lastFocusX = Infinity;
777
938
  lastFocusZ = Infinity;
@@ -780,13 +941,18 @@ var TileManager = class {
780
941
  * backoff escalates; cleared on success or unload (a fresh pan-in retries). */
781
942
  failCounts = /* @__PURE__ */ new Map();
782
943
  nextRetrySweep = 0;
944
+ /** Learned tile weights survive eviction and make future admission byte-aware. */
945
+ sizeHints = /* @__PURE__ */ new Map();
946
+ averageHiresBytes = 12 * 1024 * 1024;
947
+ focusX = 0;
948
+ focusZ = 0;
783
949
  biomesCache = null;
784
950
  statsCache = null;
785
951
  /** Y range of everything loaded so far, for ray-march bounds. */
786
952
  minY = 0;
787
953
  maxY = 320;
788
954
  constructor(options) {
789
- const { lowresMaterial, lmMaterial, ...rest } = options;
955
+ const { lowresMaterial, lmMaterial, ensureAtlas, ...rest } = options;
790
956
  this.opts = {
791
957
  viewDistance: 768,
792
958
  // Sized to fill the whole view-distance disc for 128-block tiles
@@ -794,16 +960,19 @@ var TileManager = class {
794
960
  // panel's "med" preset exactly.
795
961
  maxTiles: 120,
796
962
  concurrency: 4,
963
+ maxBytes: 512 * 1024 * 1024,
797
964
  ...rest
798
965
  };
799
966
  this.lowresMaterial = lowresMaterial ?? null;
800
967
  this.lmMaterial = lmMaterial ?? null;
968
+ this.ensureAtlas = ensureAtlas ?? null;
969
+ this.atlasLayers = ensureAtlas ? options.manifest.textureLayers ?? 0 : Infinity;
801
970
  this.tileBlocks = options.manifest.tileBlocks;
802
971
  if (options.manifest.maxSectionVerts) sharedQuadIndex(options.manifest.maxSectionVerts);
803
972
  for (const t of options.manifest.tiles) this.index.set(tileKey(t.x, t.z), t);
804
973
  this.lowLevels = this.lowresMaterial ? [...options.manifest.lowres?.levels ?? []].sort((a, b) => a.level - b.level) : [];
805
974
  for (const lvl of this.lowLevels) {
806
- this.lowIndex.set(lvl.level, new Set(lvl.tiles.map((t) => tileKey(t.x, t.z))));
975
+ this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
807
976
  }
808
977
  }
809
978
  /** Tile span in blocks at a pyramid level (0 = hires). */
@@ -828,37 +997,57 @@ var TileManager = class {
828
997
  */
829
998
  update(focusX, focusZ) {
830
999
  if (this.disposed) return;
1000
+ this.focusX = focusX;
1001
+ this.focusZ = focusZ;
831
1002
  this.flushOne();
832
1003
  this.retrySweep();
1004
+ if (this.fadingKeys.size > 0) {
1005
+ const now = performance.now();
1006
+ for (const key of this.fadingKeys) {
1007
+ const rec = this.records.get(key);
1008
+ if (!rec || rec.fadeStart === void 0 || now - rec.fadeStart >= _TileManager.FADE_MS) {
1009
+ this.fadingKeys.delete(key);
1010
+ this.coverageDirty = true;
1011
+ }
1012
+ }
1013
+ }
833
1014
  if (this.coverageDirty) this.applyCoverage();
834
- const moved = Math.hypot(focusX - this.lastFocusX, focusZ - this.lastFocusZ);
1015
+ const priorX = this.lastFocusX;
1016
+ const priorZ = this.lastFocusZ;
1017
+ const moved = Math.hypot(focusX - priorX, focusZ - priorZ);
835
1018
  if (moved < this.tileBlocks / 4) {
836
1019
  this.pump();
837
1020
  return;
838
1021
  }
1022
+ const finitePrior = Number.isFinite(priorX) && Number.isFinite(priorZ);
1023
+ const dx = finitePrior ? focusX - priorX : 0;
1024
+ const dz = finitePrior ? focusZ - priorZ : 0;
1025
+ const travel = Math.hypot(dx, dz);
1026
+ const lookahead = travel > 0 ? Math.min(2, this.tileBlocks * 2 / travel) : 0;
1027
+ const predictedX = focusX + dx * lookahead;
1028
+ const predictedZ = focusZ + dz * lookahead;
839
1029
  this.lastFocusX = focusX;
840
1030
  this.lastFocusZ = focusZ;
841
- const { viewDistance, maxTiles } = this.opts;
842
- const desired = [];
843
- const viewDistSq = viewDistance * viewDistance;
844
- for (const t of this.index.values()) {
845
- const d = this.distSqTo(t, 0, focusX, focusZ);
846
- if (d <= viewDistSq) desired.push({ t, d });
847
- }
848
- desired.sort((a, b) => a.d - b.d);
849
- if (desired.length > maxTiles) desired.length = maxTiles;
1031
+ const { viewDistance, maxTiles, maxBytes } = this.opts;
1032
+ let lowBytes = 0;
1033
+ for (const rec of this.records.values()) if (rec.level > 0) lowBytes += rec.memoryBytes;
1034
+ const hiresBytes = Math.max(1, maxBytes - lowBytes);
1035
+ const desired = admitTiles(
1036
+ nearbyTiles(this.index, this.tileBlocks, focusX, focusZ, viewDistance, predictedX, predictedZ),
1037
+ maxTiles,
1038
+ hiresBytes,
1039
+ (t) => this.sizeHints.get(tileKey(t.x, t.z)) ?? Math.max(this.averageHiresBytes, t.bytes * 20)
1040
+ ).map((candidate) => ({ t: candidate.ref, d: candidate.distanceSq }));
850
1041
  const desiredKeys = new Set(desired.map(({ t }) => recKey(0, t.x, t.z)));
851
1042
  const lowDesired = [];
852
1043
  for (let i = 0; i < this.lowLevels.length; i++) {
853
1044
  const lvl = this.lowLevels[i];
854
1045
  const top = i === this.lowLevels.length - 1;
855
- const outer = top ? Infinity : (viewDistance * 2 ** lvl.level) ** 2;
1046
+ const outerDistance = viewDistance * 2 ** lvl.level;
1047
+ const outer = top ? Infinity : outerDistance ** 2;
856
1048
  const inner = top || i === 0 ? 0 : (viewDistance * 2 ** (lvl.level - 1) * 0.85) ** 2;
857
- const ring = [];
858
- for (const t of lvl.tiles) {
859
- const d = this.distSqTo(t, lvl.level, focusX, focusZ);
860
- if (d <= outer && d >= inner) ring.push({ ref: t, level: lvl.level, d });
861
- }
1049
+ const candidates = top ? lvl.tiles.map((ref) => ({ ref, distanceSq: this.distSqTo(ref, lvl.level, focusX, focusZ), priority: 0 })) : nearbyTiles(this.lowIndex.get(lvl.level), lvl.tileBlocks, focusX, focusZ, outerDistance, predictedX, predictedZ);
1050
+ const ring = candidates.filter((candidate) => candidate.distanceSq <= outer && candidate.distanceSq >= inner).map((candidate) => ({ ref: candidate.ref, level: lvl.level, d: candidate.distanceSq }));
862
1051
  ring.sort((a, b) => a.d - b.d);
863
1052
  if (ring.length > 160) ring.length = 160;
864
1053
  for (const r of ring) {
@@ -868,10 +1057,14 @@ var TileManager = class {
868
1057
  }
869
1058
  for (const [key, rec] of this.records) {
870
1059
  if (desiredKeys.has(key)) continue;
1060
+ if (rec.level === 0) {
1061
+ this.unload(key, rec);
1062
+ continue;
1063
+ }
871
1064
  const top = this.lowLevels.length > 0 && rec.level === this.lowLevels[this.lowLevels.length - 1].level;
872
1065
  if (top) continue;
873
1066
  const d = this.distSqTo(rec.ref, rec.level, focusX, focusZ);
874
- const keep = rec.level === 0 ? viewDistance * 1.25 : viewDistance * 2 ** rec.level * 1.25;
1067
+ const keep = viewDistance * 2 ** rec.level * 1.25;
875
1068
  if (d > keep * keep) this.unload(key, rec);
876
1069
  }
877
1070
  const missing = (level, refs) => refs.filter(({ ref }) => !this.records.has(recKey(level, ref.x, ref.z)));
@@ -880,12 +1073,12 @@ var TileManager = class {
880
1073
  ...missing(topLevel, lowDesired.filter((r) => r.level === topLevel)).map((r) => ({ ref: r.ref, level: topLevel })),
881
1074
  ...missing(0, desired.map((e) => ({ ref: e.t }))).map((r) => ({ ref: r.ref, level: 0 })),
882
1075
  ...lowDesired.filter((r) => r.level !== topLevel && !this.records.has(recKey(r.level, r.ref.x, r.ref.z))).sort((a, b) => a.level - b.level || a.d - b.d).map((r) => ({ ref: r.ref, level: r.level }))
883
- ];
1076
+ ].reverse();
884
1077
  this.pump();
885
1078
  }
886
1079
  pump() {
887
- while (this.inFlight < this.opts.concurrency && this.queue.length > 0) {
888
- const { ref, level } = this.queue.shift();
1080
+ while (this.inFlight < this.opts.concurrency && this.inFlight + this.pendingBuilt < this.opts.concurrency && this.queue.length > 0) {
1081
+ const { ref, level } = this.queue.pop();
889
1082
  if (level === 0) void this.loadTile(ref);
890
1083
  else void this.loadLowres(ref, level);
891
1084
  }
@@ -902,6 +1095,9 @@ var TileManager = class {
902
1095
  const rec = this.records.get(key);
903
1096
  if (!rec || rec.state !== "built") continue;
904
1097
  rec.state = "ready";
1098
+ this.pendingBuilt--;
1099
+ rec.fadeStart = performance.now();
1100
+ this.fadingKeys.add(key);
905
1101
  this.opts.scene.add(rec.terrain);
906
1102
  if (rec.terrainLm) this.opts.scene.add(rec.terrainLm);
907
1103
  if (rec.water) this.opts.scene.add(rec.water);
@@ -910,6 +1106,29 @@ var TileManager = class {
910
1106
  this.emitter.emit("change", this.stats);
911
1107
  budget--;
912
1108
  }
1109
+ this.pump();
1110
+ }
1111
+ /** Stream-in fade length. Long enough to read as a dissolve, short enough
1112
+ * that a fast pan still feels instant. */
1113
+ static FADE_MS = 280;
1114
+ /** Whether any tile is mid stream-in fade — the viewer keeps drawing while
1115
+ * true so the dissolve actually animates under render-on-demand. */
1116
+ get fading() {
1117
+ return this.fadingKeys.size > 0;
1118
+ }
1119
+ /** Chain a per-draw uFade write onto each mesh's onBeforeRender (after the
1120
+ * dequantize-uniform hook terrain.ts installs). Every TileManager mesh gets
1121
+ * one — the materials are shared, so each draw must set its own fade. */
1122
+ attachFade(rec, ...meshes) {
1123
+ for (const mesh of meshes) {
1124
+ if (!mesh) continue;
1125
+ const orig = mesh.onBeforeRender;
1126
+ mesh.onBeforeRender = (renderer, scene, camera, geometry, material, group) => {
1127
+ orig.call(mesh, renderer, scene, camera, geometry, material, group);
1128
+ const u = material.uniforms?.["uFade"];
1129
+ if (u) u.value = rec.fadeStart === void 0 ? 1 : Math.min(1, (performance.now() - rec.fadeStart) / _TileManager.FADE_MS);
1130
+ };
1131
+ }
913
1132
  }
914
1133
  /**
915
1134
  * Hide every lowres tile whose footprint is fully SHOWN by finer data.
@@ -928,8 +1147,8 @@ var TileManager = class {
928
1147
  applyCoverage() {
929
1148
  this.coverageDirty = false;
930
1149
  let shown = /* @__PURE__ */ new Set();
931
- for (const rec of this.records.values()) {
932
- if (rec.level === 0 && rec.state === "ready") shown.add(tileKey(rec.ref.x, rec.ref.z));
1150
+ for (const [key, rec] of this.records) {
1151
+ if (rec.level === 0 && rec.state === "ready" && !this.fadingKeys.has(key)) shown.add(tileKey(rec.ref.x, rec.ref.z));
933
1152
  }
934
1153
  let finerIndex = this.index;
935
1154
  for (const lvl of this.lowLevels) {
@@ -951,12 +1170,47 @@ var TileManager = class {
951
1170
  finerIndex = this.lowIndex.get(lvl.level) ?? /* @__PURE__ */ new Set();
952
1171
  }
953
1172
  }
1173
+ /** Ingest tiles a progressive render has newly published. Unknown tiles join
1174
+ * the streaming index and force a re-plan so they stream in on the next
1175
+ * update(); already-known tiles are ignored. Returns whether anything was
1176
+ * added. */
1177
+ addTiles(tiles) {
1178
+ let added = false;
1179
+ for (const t of tiles) {
1180
+ const k = tileKey(t.x, t.z);
1181
+ if (!this.index.has(k)) {
1182
+ this.index.set(k, t);
1183
+ added = true;
1184
+ }
1185
+ }
1186
+ if (added) {
1187
+ this.lastFocusX = Infinity;
1188
+ this.lastFocusZ = Infinity;
1189
+ this.invalidate();
1190
+ this.emitter.emit("change", this.stats);
1191
+ }
1192
+ return added;
1193
+ }
1194
+ /** Install the lowres pyramid once a progressive render finishes (its earlier
1195
+ * manifests carried no lowres). No-op without a lowres material, or if a
1196
+ * pyramid is already present. Forces a re-plan so the coarse rings stream in. */
1197
+ ingestLowres(lowres) {
1198
+ if (!this.lowresMaterial || this.lowLevels.length > 0) return;
1199
+ const levels = [...lowres.levels].sort((a, b) => a.level - b.level);
1200
+ this.lowLevels.push(...levels);
1201
+ for (const lvl of levels) this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
1202
+ this.lastFocusX = Infinity;
1203
+ this.lastFocusZ = Infinity;
1204
+ this.coverageDirty = true;
1205
+ this.invalidate();
1206
+ }
954
1207
  /** Live-tune streaming (view distance, tile budget, fetch concurrency).
955
1208
  * Takes effect on the next update(): the plan is recomputed from scratch. */
956
1209
  configure(settings) {
957
1210
  if (settings.viewDistance !== void 0) this.opts.viewDistance = settings.viewDistance;
958
1211
  if (settings.maxTiles !== void 0) this.opts.maxTiles = settings.maxTiles;
959
1212
  if (settings.concurrency !== void 0) this.opts.concurrency = settings.concurrency;
1213
+ if (settings.maxBytes !== void 0) this.opts.maxBytes = settings.maxBytes;
960
1214
  this.lastFocusX = Infinity;
961
1215
  this.lastFocusZ = Infinity;
962
1216
  }
@@ -968,12 +1222,16 @@ var TileManager = class {
968
1222
  get maxTiles() {
969
1223
  return this.opts.maxTiles;
970
1224
  }
1225
+ /** The current estimated CPU+GPU residency budget. */
1226
+ get maxBytes() {
1227
+ return this.opts.maxBytes;
1228
+ }
971
1229
  /** Fetch + decode one lowres LOD tile into a heightfield mesh. */
972
1230
  async loadLowres(ref, level) {
973
1231
  const key = recKey(level, ref.x, ref.z);
974
1232
  if (this.records.has(key) || !this.lowresMaterial) return;
975
1233
  const abort = new AbortController();
976
- const rec = { ref, level, state: "loading", abort, vertexCount: 0, triangleCount: 0 };
1234
+ const rec = { ref, level, state: "loading", abort, vertexCount: 0, triangleCount: 0, memoryBytes: 0 };
977
1235
  this.records.set(key, rec);
978
1236
  this.inFlight++;
979
1237
  try {
@@ -987,6 +1245,7 @@ var TileManager = class {
987
1245
  mesh.renderOrder = -level;
988
1246
  releaseAfterUpload(mesh.geometry);
989
1247
  rec.terrain = mesh;
1248
+ this.attachFade(rec, mesh);
990
1249
  rec.low = {
991
1250
  originX: tile.originX,
992
1251
  originZ: tile.originZ,
@@ -997,7 +1256,9 @@ var TileManager = class {
997
1256
  };
998
1257
  rec.vertexCount = tile.width * tile.depth;
999
1258
  rec.triangleCount = mesh.geometry.index.count / 3;
1259
+ rec.memoryBytes = geometryBytes(mesh.geometry) + rec.low.heights.byteLength;
1000
1260
  rec.state = "built";
1261
+ this.pendingBuilt++;
1001
1262
  this.failCounts.delete(key);
1002
1263
  this.pendingAdd.push(key);
1003
1264
  this.invalidate();
@@ -1038,15 +1299,29 @@ var TileManager = class {
1038
1299
  const key = tileKey(ref.x, ref.z);
1039
1300
  if (this.records.has(key)) return;
1040
1301
  const abort = new AbortController();
1041
- const rec = { ref, level: 0, state: "loading", abort, vertexCount: 0, triangleCount: 0 };
1302
+ const rec = { ref, level: 0, state: "loading", abort, vertexCount: 0, triangleCount: 0, memoryBytes: 0 };
1042
1303
  this.records.set(key, rec);
1043
1304
  this.inFlight++;
1044
1305
  try {
1045
1306
  const buffer = await maybeInflate(await this.opts.fetch(ref.path, abort.signal));
1046
1307
  if (this.disposed || rec.state !== "loading") return;
1308
+ if (buffer.byteLength === 0) {
1309
+ rec.state = "empty";
1310
+ return;
1311
+ }
1047
1312
  let meshes;
1048
1313
  const q = parseTileQuantized(buffer);
1049
1314
  if (q) {
1315
+ if (this.ensureAtlas) {
1316
+ let need = 0;
1317
+ for (const arr of [q.solid.layer, q.fluid.layer]) {
1318
+ for (let i = 0; i < arr.length; i++) if (arr[i] >= need) need = arr[i] + 1;
1319
+ }
1320
+ if (need > this.atlasLayers) {
1321
+ this.atlasLayers = await this.ensureAtlas(need);
1322
+ if (this.disposed || rec.state !== "loading") return;
1323
+ }
1324
+ }
1050
1325
  rec.biomes = summarizeSurfaceBiomes(q.surface, q.biomeNames, this.opts.palette);
1051
1326
  rec.surface = { ...q.surface, biome: q.surface.biome.slice(), height: q.surface.height.slice() };
1052
1327
  meshes = buildQuantizedTileMeshes(q, this.opts.material, this.opts.waterMaterial, this.lmMaterial ?? void 0);
@@ -1069,11 +1344,17 @@ var TileManager = class {
1069
1344
  rec.terrainLm = meshes.terrainLm;
1070
1345
  rec.lightmapTex = meshes.lightmapTex;
1071
1346
  rec.water = meshes.water;
1347
+ this.attachFade(rec, meshes.terrain, meshes.terrainLm, meshes.water);
1072
1348
  this.minY = Math.min(this.minY, meshes.bounds.min.y);
1073
1349
  this.maxY = Math.max(this.maxY, meshes.bounds.max.y);
1350
+ rec.memoryBytes = geometryBytes(meshes.terrain.geometry) + (meshes.terrainLm ? geometryBytes(meshes.terrainLm.geometry) : 0) + (meshes.water ? geometryBytes(meshes.water.geometry) : 0) + textureBytes(meshes.lightmapTex) + (rec.surface ? rec.surface.biome.byteLength + rec.surface.height.byteLength : 0);
1351
+ this.sizeHints.set(key, rec.memoryBytes);
1352
+ this.averageHiresBytes = this.averageHiresBytes * 0.875 + rec.memoryBytes * 0.125;
1074
1353
  rec.state = "built";
1354
+ this.pendingBuilt++;
1075
1355
  this.failCounts.delete(key);
1076
1356
  this.pendingAdd.push(key);
1357
+ this.trimToMemoryBudget();
1077
1358
  this.invalidate();
1078
1359
  this.emitter.emit("change", this.stats);
1079
1360
  } catch (e) {
@@ -1088,6 +1369,7 @@ var TileManager = class {
1088
1369
  }
1089
1370
  unload(key, rec) {
1090
1371
  rec.abort?.abort();
1372
+ if (rec.state === "built") this.pendingBuilt--;
1091
1373
  for (const mesh of [rec.terrain, rec.terrainLm, rec.water]) {
1092
1374
  if (!mesh) continue;
1093
1375
  this.opts.scene.remove(mesh);
@@ -1097,10 +1379,35 @@ var TileManager = class {
1097
1379
  rec.lightmapTex?.dispose();
1098
1380
  this.records.delete(key);
1099
1381
  this.failCounts.delete(key);
1382
+ this.fadingKeys.delete(key);
1100
1383
  this.coverageDirty = true;
1101
1384
  this.invalidate();
1102
1385
  this.emitter.emit("change", this.stats);
1103
1386
  }
1387
+ /** Correct estimation misses after a tile is decoded. Farthest hires records
1388
+ * leave first; one nearest tile is always kept so an oversized outlier does
1389
+ * not create an unload/refetch loop. Learned weights make the next plan fit. */
1390
+ trimToMemoryBudget() {
1391
+ let total = 0;
1392
+ const hires = [];
1393
+ for (const [key, rec] of this.records) {
1394
+ total += rec.memoryBytes;
1395
+ if (rec.level === 0 && rec.state !== "failed" && rec.state !== "empty") {
1396
+ hires.push({ key, rec, d: this.distSqTo(rec.ref, 0, this.focusX, this.focusZ) });
1397
+ }
1398
+ }
1399
+ if (total <= this.opts.maxBytes || hires.length <= 1) return;
1400
+ hires.sort((a, b) => b.d - a.d);
1401
+ let remaining = hires.length;
1402
+ for (const entry of hires) {
1403
+ if (total <= this.opts.maxBytes || remaining <= 1) break;
1404
+ total -= entry.rec.memoryBytes;
1405
+ remaining--;
1406
+ this.unload(entry.key, entry.rec);
1407
+ }
1408
+ this.lastFocusX = Infinity;
1409
+ this.lastFocusZ = Infinity;
1410
+ }
1104
1411
  invalidate() {
1105
1412
  this.biomesCache = null;
1106
1413
  this.statsCache = null;
@@ -1115,7 +1422,9 @@ var TileManager = class {
1115
1422
  let vertexCount = 0;
1116
1423
  let triangleCount = 0;
1117
1424
  let bytes = 0;
1425
+ let residentBytes = 0;
1118
1426
  for (const rec of this.records.values()) {
1427
+ residentBytes += rec.memoryBytes;
1119
1428
  if (rec.state === "ready") {
1120
1429
  if (rec.level === 0) loaded++;
1121
1430
  else lowres++;
@@ -1124,7 +1433,7 @@ var TileManager = class {
1124
1433
  bytes += rec.ref.bytes;
1125
1434
  } else if (rec.state === "loading" || rec.state === "built") loading++;
1126
1435
  }
1127
- this.statsCache = { loaded, loading, total: this.index.size, lowres, vertexCount, triangleCount, bytes };
1436
+ this.statsCache = { loaded, loading, total: this.index.size, lowres, vertexCount, triangleCount, bytes, residentBytes };
1128
1437
  return this.statsCache;
1129
1438
  }
1130
1439
  /** Aggregated biome share across every resident tile, most common first. */
@@ -2067,11 +2376,32 @@ var VantageViewer = class _VantageViewer {
2067
2376
  worldSpan = 0;
2068
2377
  tilesUnsub = null;
2069
2378
  lastBiomesEmit = 0;
2379
+ // Progressive render (manifest.rendering): the manager whose live bake we're
2380
+ // polling for, and the atlas layer count last uploaded — a growing count
2381
+ // triggers a texture-array re-fetch. Cleared when the render finishes or the
2382
+ // world reloads (the poll checks its manager is still current).
2383
+ progressiveManager = null;
2384
+ lastTextureLayers = 0;
2385
+ /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
2386
+ * poll coalesce onto one request instead of racing separate fetches. */
2387
+ atlasRefresh = null;
2070
2388
  // Biome layer state machine.
2071
2389
  biomeEnabled = false;
2072
2390
  highlight = null;
2073
2391
  mixTarget = 0;
2074
2392
  mixCurrent = 0;
2393
+ // Depth slice (cave view): everything above the clip plane is cut away,
2394
+ // revealing cave floors below. `sliceTarget` is where the user set it (null =
2395
+ // off); `sliceCurrent` eases toward it each frame, so toggling peels the
2396
+ // world open instead of popping. `sliceActive` stays true through the
2397
+ // toggle-off ease until the plane has lifted clear.
2398
+ sliceTarget = null;
2399
+ sliceCurrent = 0;
2400
+ sliceActive = false;
2401
+ /** The last depth used, so re-opening the cave view returns there. */
2402
+ lastSliceY = null;
2403
+ /** The dark "unexplored rock" floor under a sliced world. */
2404
+ slicePlane = null;
2075
2405
  // Live lighting appearance (applied to the shader on load and on change).
2076
2406
  light = { ...DEFAULT_LIGHT };
2077
2407
  // Live display fidelity (shader uniforms + render scale).
@@ -2086,6 +2416,15 @@ var VantageViewer = class _VantageViewer {
2086
2416
  // sentinel distinct from -1 (off-terrain)
2087
2417
  // Last-frame timestamp, for frame-rate-independent control inertia.
2088
2418
  lastFrameMs = 0;
2419
+ // Render-on-demand: a frame draws only when this is set (camera moved, tiles
2420
+ // changed, a setting changed, …) or the idle animation tick fires. See
2421
+ // `invalidate()`.
2422
+ needsRender = true;
2423
+ // Whether the loaded texture array animates (water/lava frames) — drives the
2424
+ // idle tick. Set on load from the decoded anim table.
2425
+ hasAnims = false;
2426
+ // When the last frame actually rendered, for the idle animation cadence.
2427
+ lastRenderMs = 0;
2089
2428
  // The framing the current tile loaded into, so the UI can re-home to it.
2090
2429
  framedState = null;
2091
2430
  // URL-hash deep links (urlState option): debounce handle for hash writes and
@@ -2102,7 +2441,8 @@ var VantageViewer = class _VantageViewer {
2102
2441
  light: options.light ?? {},
2103
2442
  display: options.display ?? {},
2104
2443
  streaming: options.streaming ?? {},
2105
- urlState: options.urlState ?? false
2444
+ urlState: options.urlState ?? false,
2445
+ renderOnDemand: options.renderOnDemand ?? true
2106
2446
  };
2107
2447
  if (options.light) this.light = { ...this.light, ...options.light };
2108
2448
  if (options.display) this.display = { ...this.display, ...options.display };
@@ -2190,11 +2530,13 @@ var VantageViewer = class _VantageViewer {
2190
2530
  const waterShader = createWaterMaterial(shader);
2191
2531
  shader.uniforms["uFogRadial"].value = 1;
2192
2532
  const lmShader = manifest.format >= 4 ? createLightmappedMaterial(shader) : void 0;
2193
- const lowresShader = manifest.lowres ? createLowresMaterial(shader) : void 0;
2533
+ const lowresShader = manifest.lowres || manifest.rendering ? createLowresMaterial(shader) : void 0;
2194
2534
  this.shader = shader;
2195
2535
  this.waterShader = waterShader;
2196
2536
  this.lowresShader = lowresShader ?? null;
2197
2537
  this.manifest = manifest;
2538
+ this.hasAnims = texData.anims.length > 0;
2539
+ this.lastTextureLayers = manifest.textureLayers ?? texData.layers;
2198
2540
  this.tile = null;
2199
2541
  this.tiles = new TileManager({
2200
2542
  manifest,
@@ -2205,10 +2547,15 @@ var VantageViewer = class _VantageViewer {
2205
2547
  ...lmShader ? { lmMaterial: lmShader } : {},
2206
2548
  ...lowresShader ? { lowresMaterial: lowresShader } : {},
2207
2549
  palette,
2550
+ // A live/progressive render grows its atlas as tiles bake; gate each
2551
+ // tile's insertion on the atlas covering its layers (a no-op once the
2552
+ // atlas is complete). Returns the layer count now loaded.
2553
+ ...manifest.rendering ? { ensureAtlas: (n) => this.ensureAtlasLayers(source, n).then(() => this.lastTextureLayers) } : {},
2208
2554
  ...this.options.streaming
2209
2555
  });
2210
- this.controls.heightAt = this.tiles.heightAt;
2556
+ this.setHeightSampler(this.tiles.heightAt);
2211
2557
  this.tilesUnsub = this.tiles.on("change", (stats) => {
2558
+ this.needsRender = true;
2212
2559
  this.emitter.emit("stats", stats);
2213
2560
  const now = performance.now();
2214
2561
  if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
@@ -2222,24 +2569,97 @@ var VantageViewer = class _VantageViewer {
2222
2569
  this.applyBiomeUniforms();
2223
2570
  this.applyLight();
2224
2571
  this.applyDisplay();
2572
+ this.applySlice();
2225
2573
  this.tiles.update(this.controls.position.x, this.controls.position.z);
2226
2574
  const size = new THREE2.Vector3();
2227
2575
  this.bounds.getSize(size);
2228
2576
  this._biomes = [];
2229
2577
  this.emitter.emit("load", {
2230
2578
  // Streamed worlds: the tile format follows the manifest schema version.
2231
- magic: manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
2579
+ magic: manifest.format >= 5 ? "VTL9" : manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
2232
2580
  vertexCount: 0,
2233
2581
  triangleCount: 0,
2234
2582
  size,
2235
2583
  biomes: this._biomes
2236
2584
  });
2585
+ if (manifest.rendering) {
2586
+ this.progressiveManager = this.tiles;
2587
+ this.emitProgress(manifest);
2588
+ void this.pollProgressive(source, this.tiles);
2589
+ }
2590
+ }
2591
+ /** Emit a `progress` event from a manifest (falling back to the tile count
2592
+ * when the generator didn't include a `progress` block). */
2593
+ emitProgress(m) {
2594
+ this.emitter.emit("progress", {
2595
+ done: m.progress?.done ?? m.tiles.length,
2596
+ total: m.progress?.total ?? m.tiles.length,
2597
+ rendering: m.rendering ?? false
2598
+ });
2237
2599
  }
2238
- /** Frame a streamed world: pivot on the spawn point when the manifest has
2239
- * one (that's where the builds are), else the centre of the tile extents.
2240
- * Distances are tied to the streaming view distance, not the world size —
2241
- * a 100k×100k world frames the same as a village. */
2242
- frameWorld(manifest, view) {
2600
+ /** Follow a live (`rendering: true`) render: re-fetch the manifest on an
2601
+ * interval, stream newly-baked tiles in, widen the texture array when the
2602
+ * atlas grows, and install the lowres pyramid once the bake completes. Runs
2603
+ * until the render finishes or the world is replaced. */
2604
+ async pollProgressive(source, manager) {
2605
+ const dec = new TextDecoder();
2606
+ for (; ; ) {
2607
+ await new Promise((r) => setTimeout(r, 1200));
2608
+ if (this.tiles !== manager || this.progressiveManager !== manager) return;
2609
+ let m;
2610
+ try {
2611
+ m = parseManifest(JSON.parse(dec.decode(await source.fetch("manifest.json"))));
2612
+ } catch {
2613
+ continue;
2614
+ }
2615
+ if ((m.textureLayers ?? 0) > this.lastTextureLayers) {
2616
+ await this.ensureAtlasLayers(source, m.textureLayers ?? 0);
2617
+ if (this.tiles !== manager) return;
2618
+ }
2619
+ manager.addTiles(m.tiles);
2620
+ this.emitProgress(m);
2621
+ if (!m.rendering) {
2622
+ this.manifest = m;
2623
+ if (m.lowres) manager.ingestLowres(m.lowres);
2624
+ this.updateWorldBounds(m);
2625
+ this.applyViewLimits();
2626
+ this.progressiveManager = null;
2627
+ this.needsRender = true;
2628
+ return;
2629
+ }
2630
+ }
2631
+ }
2632
+ /** Ensure the terrain atlas covers at least `layers` texture-array layers,
2633
+ * re-fetching `terrain.vtexarr` if it's behind. Coalesces concurrent callers
2634
+ * — the on-demand tile-insert gate and the progressive poll — onto one
2635
+ * request. Resolves once the atlas is current (or the fetch failed and the
2636
+ * old atlas stands, to be retried by a later gate/poll). */
2637
+ async ensureAtlasLayers(source, layers) {
2638
+ if (this.lastTextureLayers >= layers) return;
2639
+ await (this.atlasRefresh ??= this.refetchAtlas(source));
2640
+ if (this.lastTextureLayers < layers && !this.atlasRefresh) {
2641
+ await (this.atlasRefresh ??= this.refetchAtlas(source));
2642
+ }
2643
+ }
2644
+ /** Re-fetch `terrain.vtexarr` and widen every shared material's atlas (they
2645
+ * share the sampler uniform objects, so one update reaches all). */
2646
+ async refetchAtlas(source) {
2647
+ try {
2648
+ const td = parseTextureArray(await maybeInflate(await source.fetch(this.manifest.textures)));
2649
+ if (!this.shader) return;
2650
+ updateTerrainTextures(this.shader, td);
2651
+ this.hasAnims = td.anims.length > 0;
2652
+ this.lastTextureLayers = Math.max(this.lastTextureLayers, td.layers);
2653
+ this.needsRender = true;
2654
+ } catch {
2655
+ } finally {
2656
+ this.atlasRefresh = null;
2657
+ }
2658
+ }
2659
+ /** Set the world bounds + span from a manifest's tile extents, without moving
2660
+ * the camera. Used to frame a world on load and to widen the extent when a
2661
+ * progressive render finishes and the full size is finally known. */
2662
+ updateWorldBounds(manifest) {
2243
2663
  const tb = manifest.tileBlocks;
2244
2664
  let minX = Infinity;
2245
2665
  let minZ = Infinity;
@@ -2257,6 +2677,17 @@ var VantageViewer = class _VantageViewer {
2257
2677
  }
2258
2678
  this.bounds.set(new THREE2.Vector3(minX, -64, minZ), new THREE2.Vector3(maxX, 320, maxZ));
2259
2679
  this.worldSpan = Math.max(maxX - minX, maxZ - minZ);
2680
+ }
2681
+ /** Frame a streamed world: pivot on the spawn point when the manifest has
2682
+ * one (that's where the builds are), else the centre of the tile extents.
2683
+ * Distances are tied to the streaming view distance, not the world size —
2684
+ * a 100k×100k world frames the same as a village. */
2685
+ frameWorld(manifest, view) {
2686
+ this.updateWorldBounds(manifest);
2687
+ const minX = this.bounds.min.x;
2688
+ const minZ = this.bounds.min.z;
2689
+ const maxX = this.bounds.max.x;
2690
+ const maxZ = this.bounds.max.z;
2260
2691
  const viewDistance = this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768;
2261
2692
  const spawn = manifest.spawn;
2262
2693
  const pivot = spawn ? new THREE2.Vector3(spawn.x, spawn.y, spawn.z) : new THREE2.Vector3((minX + maxX) / 2, 80, (minZ + maxZ) / 2);
@@ -2315,6 +2746,7 @@ var VantageViewer = class _VantageViewer {
2315
2746
  this.disposeCurrent();
2316
2747
  const built = buildTerrain(tile, textures);
2317
2748
  this.tile = tile;
2749
+ this.hasAnims = (textures?.anims.length ?? 0) > 0;
2318
2750
  this.shader = built.shader ?? null;
2319
2751
  this.bounds = built.bounds;
2320
2752
  this.scene.add(built.terrain);
@@ -2327,13 +2759,14 @@ var VantageViewer = class _VantageViewer {
2327
2759
  this.scene.add(hemi, sun);
2328
2760
  this.current.lights = [hemi, sun];
2329
2761
  }
2330
- this.controls.heightAt = makeHeightSampler(tile.surface);
2762
+ this.setHeightSampler(makeHeightSampler(tile.surface));
2331
2763
  this._biomes = summarizeBiomes(tile, built.palette);
2332
2764
  this.frameCamera(view);
2333
2765
  if (this.options.urlState) this.applyViewHash(window.location.hash);
2334
2766
  this.applyBiomeUniforms();
2335
2767
  this.applyLight();
2336
2768
  this.applyDisplay();
2769
+ this.applySlice();
2337
2770
  const size = new THREE2.Vector3();
2338
2771
  this.bounds.getSize(size);
2339
2772
  this.emitter.emit("load", {
@@ -2455,7 +2888,9 @@ var VantageViewer = class _VantageViewer {
2455
2888
  }
2456
2889
  applyBiomeUniforms() {
2457
2890
  if (!this.shader) return;
2891
+ this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2458
2892
  this.shader.uniforms["uHi"].value = this.biomeEnabled && this.highlight !== null ? this.highlight : -1;
2893
+ this.needsRender = true;
2459
2894
  }
2460
2895
  // --- lighting appearance ---------------------------------------------------
2461
2896
  /** The current live lighting appearance. */
@@ -2470,9 +2905,156 @@ var VantageViewer = class _VantageViewer {
2470
2905
  }
2471
2906
  applyLight() {
2472
2907
  if (!this.shader) return;
2473
- this.shader.uniforms["uAmbient"].value = this.light.ambient;
2908
+ const ambient = this.sliceActive ? Math.max(this.light.ambient, 0.32) : this.light.ambient;
2909
+ this.shader.uniforms["uAmbient"].value = ambient;
2474
2910
  this.shader.uniforms["uDay"].value = this.light.daylight;
2475
2911
  this.shader.uniforms["uExposure"].value = this.light.exposure;
2912
+ this.needsRender = true;
2913
+ }
2914
+ // --- depth slice (cave view) -------------------------------------------------
2915
+ /** Whether the loaded world was baked with full cave geometry
2916
+ * (`vantage render --caves full`) — i.e. the depth slice has real caves to
2917
+ * reveal. The slice API works regardless; this is the "show the UI?" bit. */
2918
+ get hasCaves() {
2919
+ return this.manifest?.caves ?? false;
2920
+ }
2921
+ /** The world-Y bounds for the depth slice, from the manifest's baked extent
2922
+ * (falling back to the loaded bounds / vanilla build limits). */
2923
+ get sliceRange() {
2924
+ const yr = this.manifest?.yRange;
2925
+ if (yr) return { min: yr.min, max: yr.max };
2926
+ if (Number.isFinite(this.bounds.min.y) && this.bounds.min.y < this.bounds.max.y) {
2927
+ return { min: this.bounds.min.y, max: this.bounds.max.y };
2928
+ }
2929
+ return { min: -64, max: 320 };
2930
+ }
2931
+ /** The current depth-slice Y, or `null` when the cave view is off. */
2932
+ get slice() {
2933
+ return this.sliceTarget;
2934
+ }
2935
+ /** Slice the world at world-Y `y` (everything above is cut away, exposing
2936
+ * the caves below — the cave / X-ray view); `null` turns it off. The plane
2937
+ * eases to its target, so toggling peels the world open. Emits `'slice'`. */
2938
+ setSlice(y) {
2939
+ const r = this.sliceRange;
2940
+ const target = y === null ? null : Math.min(Math.max(y, r.min + 2), r.max);
2941
+ if (target === this.sliceTarget) return;
2942
+ if (target !== null) {
2943
+ if (!this.sliceActive) this.sliceCurrent = r.max + 24;
2944
+ this.sliceActive = true;
2945
+ this.lastSliceY = target;
2946
+ }
2947
+ this.sliceTarget = target;
2948
+ this.applySlice();
2949
+ this.queueHashWrite();
2950
+ this.emitter.emit("slice", { y: target });
2951
+ }
2952
+ /** Toggle the cave view: off → the last used depth (or a sensible cave
2953
+ * depth on first open), on → off. */
2954
+ toggleSlice() {
2955
+ if (this.sliceTarget !== null) {
2956
+ this.setSlice(null);
2957
+ return;
2958
+ }
2959
+ const r = this.sliceRange;
2960
+ this.setSlice(this.lastSliceY ?? Math.round(r.min + (r.max - r.min) * 0.25));
2961
+ }
2962
+ /** Push slice state to the shader + scene: clip uniform, ambient floor, and
2963
+ * the void floor's presence. Also called on (re)load to seed a fresh shader. */
2964
+ applySlice() {
2965
+ if (!this.shader) return;
2966
+ this.shader.uniforms["uClipY"].value = this.sliceActive ? this.sliceCurrent : 1e9;
2967
+ if (this.sliceActive && !this.slicePlane) {
2968
+ this.slicePlane = this.buildSlicePlane();
2969
+ this.scene.add(this.slicePlane);
2970
+ } else if (!this.sliceActive && this.slicePlane) {
2971
+ this.scene.remove(this.slicePlane);
2972
+ this.slicePlane.geometry.dispose();
2973
+ this.slicePlane.material.dispose();
2974
+ this.slicePlane = null;
2975
+ }
2976
+ this.applyLight();
2977
+ }
2978
+ /** The "unexplored rock" floor under a sliced world: a huge dark plane at
2979
+ * the world's bottom, so solid ground reads as solid where no cave is
2980
+ * exposed (instead of sky bleeding through the planet). Carries a faint
2981
+ * 16-block chunk grid for scale and shares the terrain's fog uniforms so
2982
+ * its distance haze matches. Follows the camera focus each frame. */
2983
+ buildSlicePlane() {
2984
+ const t = this.shader.uniforms;
2985
+ const mat = new THREE2.ShaderMaterial({
2986
+ glslVersion: THREE2.GLSL3,
2987
+ uniforms: {
2988
+ uFogColor: t["uFogColor"],
2989
+ uFog: t["uFog"],
2990
+ uFogCenter: t["uFogCenter"],
2991
+ uFogRadial: t["uFogRadial"],
2992
+ uFogDensity: t["uFogDensity"]
2993
+ },
2994
+ vertexShader: (
2995
+ /* glsl */
2996
+ `
2997
+ out vec2 vXZ;
2998
+ out float vViewZ;
2999
+ void main() {
3000
+ vec4 wp = modelMatrix * vec4(position, 1.0);
3001
+ vXZ = wp.xz;
3002
+ vec4 mv = viewMatrix * wp;
3003
+ vViewZ = -mv.z;
3004
+ gl_Position = projectionMatrix * mv;
3005
+ }
3006
+ `
3007
+ ),
3008
+ fragmentShader: (
3009
+ /* glsl */
3010
+ `
3011
+ precision highp float;
3012
+ uniform vec3 uFogColor;
3013
+ uniform vec2 uFog;
3014
+ uniform vec2 uFogCenter;
3015
+ uniform float uFogRadial;
3016
+ uniform float uFogDensity;
3017
+ in vec2 vXZ;
3018
+ in float vViewZ;
3019
+ out vec4 frag;
3020
+ void main() {
3021
+ // A faint 16-block chunk grid, antialiased via screen-space
3022
+ // derivatives and faded with the fog so it never shimmers.
3023
+ vec2 cell = vXZ / 16.0;
3024
+ vec2 q = abs(fract(cell) - 0.5);
3025
+ vec2 w = max(fwidth(cell), vec2(1e-5));
3026
+ vec2 d = (0.5 - q) / w;
3027
+ float g = 1.0 - smoothstep(0.8, 2.2, min(d.x, d.y));
3028
+ // Radial fog must be computed HERE, not in the vertex shader: this
3029
+ // plane is two screen-covering triangles, and distance() is not
3030
+ // affine \u2014 interpolating it from far-away corners fogs the whole
3031
+ // interior solid. The view-depth term IS affine, so it interpolates
3032
+ // exactly as a varying.
3033
+ float fogd = mix(vViewZ, distance(vXZ, uFogCenter), uFogRadial);
3034
+ float f = smoothstep(uFog.x, uFog.y, fogd) * uFogDensity;
3035
+ // Authored sRGB, straight to the canvas (like the sky dome).
3036
+ vec3 c = mix(vec3(0.055, 0.06, 0.075), vec3(0.115, 0.125, 0.155), g * (1.0 - f));
3037
+ frag = vec4(mix(c, uFogColor, f), 1.0);
3038
+ }
3039
+ `
3040
+ )
3041
+ });
3042
+ const mesh = new THREE2.Mesh(new THREE2.PlaneGeometry(1, 1), mat);
3043
+ mesh.rotation.x = -Math.PI / 2;
3044
+ mesh.scale.setScalar(4e5);
3045
+ mesh.frustumCulled = false;
3046
+ return mesh;
3047
+ }
3048
+ /** Install the terrain-follow height source, wrapped so the controls' pivot
3049
+ * never rides the (now invisible) surface above an open depth slice —
3050
+ * zooming in descends to the exposed cave level instead of stopping at the
3051
+ * clipped-away hilltops. */
3052
+ setHeightSampler(base) {
3053
+ this.controls.heightAt = base ? (x, z) => {
3054
+ const h = base(x, z);
3055
+ if (h == null || this.sliceTarget == null) return h;
3056
+ return Math.min(h, this.sliceTarget);
3057
+ } : null;
2476
3058
  }
2477
3059
  // --- display fidelity ------------------------------------------------------
2478
3060
  /** The current live display fidelity (sharpness, colour grade, fog, scale). */
@@ -2491,10 +3073,14 @@ var VantageViewer = class _VantageViewer {
2491
3073
  }
2492
3074
  }
2493
3075
  /** devicePixelRatio × renderScale, capped by maxPixelRatio (and a hard 4 so a
2494
- * fat-fingered scale can't allocate a giant framebuffer). */
3076
+ * fat-fingered scale can't allocate a giant framebuffer). Floored at 0.25:
3077
+ * a hidden/headless window can report devicePixelRatio 0, which would
3078
+ * otherwise zero the framebuffer and break screenshot() and the first
3079
+ * visible frame. */
2495
3080
  targetPixelRatio() {
2496
- const want = window.devicePixelRatio * this.display.renderScale;
2497
- return Math.min(want, this.options.maxPixelRatio * Math.max(1, this.display.renderScale), 4);
3081
+ const dpr = window.devicePixelRatio || 1;
3082
+ const want = dpr * this.display.renderScale;
3083
+ return Math.max(0.25, Math.min(want, this.options.maxPixelRatio * Math.max(1, this.display.renderScale), 4));
2498
3084
  }
2499
3085
  applyDisplay() {
2500
3086
  if (!this.shader) return;
@@ -2504,41 +3090,47 @@ var VantageViewer = class _VantageViewer {
2504
3090
  this.shader.uniforms["uSaturation"].value = d.saturation;
2505
3091
  this.shader.uniforms["uContrast"].value = d.contrast;
2506
3092
  this.shader.uniforms["uFogDensity"].value = d.fog;
3093
+ this.needsRender = true;
2507
3094
  }
2508
3095
  // --- streaming -------------------------------------------------------------
2509
- /** The current streaming settings (view distance, tile budget, concurrency). */
3096
+ /** The current streaming settings (view distance, tile/byte budgets, concurrency). */
2510
3097
  get streamingSettings() {
2511
3098
  return {
2512
3099
  viewDistance: this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768,
2513
3100
  maxTiles: this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120,
2514
- concurrency: this.options.streaming.concurrency ?? 4
3101
+ concurrency: this.options.streaming.concurrency ?? 4,
3102
+ maxBytes: this.tiles?.maxBytes ?? this.options.streaming.maxBytes ?? 512 * 1024 * 1024
2515
3103
  };
2516
3104
  }
2517
- /** Live-tune streaming: view distance, resident-tile budget, concurrency.
3105
+ /** Live-tune streaming: view distance, resident tile/byte budgets, concurrency.
2518
3106
  * Applies immediately to a streamed world (tiles re-plan, fog and camera
2519
3107
  * range follow) and persists for future loads. The fidelity dial: raise
2520
- * viewDistance/maxTiles to see farther, lower them on weak hardware. */
3108
+ * viewDistance/maxTiles/maxBytes to see farther, lower them on weak hardware. */
2521
3109
  setStreaming(settings) {
2522
3110
  this.options.streaming = { ...this.options.streaming, ...settings };
2523
3111
  if (!this.tiles) return;
2524
3112
  this.tiles.configure(settings);
2525
3113
  this.applyViewLimits();
3114
+ this.needsRender = true;
2526
3115
  }
2527
3116
  // --- URL-hash deep links ----------------------------------------------------
2528
- /** The current view serialized as a `#@x,y,z,dist,rot,tilt` hash fragment —
2529
- * paste-able into any URL serving the same world. */
3117
+ /** The current view serialized as a `#@x,y,z,dist,rot,tilt[,sliceY]` hash
3118
+ * fragment — paste-able into any URL serving the same world. The trailing
3119
+ * component appears only while the cave view is open, so those deep links
3120
+ * reopen sliced at the same depth. */
2530
3121
  getViewHash() {
2531
3122
  const p = this.controls.position;
2532
3123
  const r1 = (v) => Math.round(v * 10) / 10;
2533
3124
  const r3 = (v) => Math.round(v * 1e3) / 1e3;
2534
- return `#@${r1(p.x)},${r1(p.y)},${r1(p.z)},${r1(this.controls.distance)},${r3(this.controls.rotation)},${r3(this.controls.angle)}`;
3125
+ const slice = this.sliceTarget !== null ? `,${r1(this.sliceTarget)}` : "";
3126
+ return `#@${r1(p.x)},${r1(p.y)},${r1(p.z)},${r1(this.controls.distance)},${r3(this.controls.rotation)},${r3(this.controls.angle)}${slice}`;
2535
3127
  }
2536
- /** Apply a `#@x,y,z,dist,rot,tilt` hash to the camera (leading `#` optional).
2537
- * Returns whether the hash parsed. */
3128
+ /** Apply a `#@x,y,z,dist,rot,tilt[,sliceY]` hash to the camera (leading `#`
3129
+ * optional). Returns whether the hash parsed. */
2538
3130
  applyViewHash(hash) {
2539
- const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)$/.exec(hash);
3131
+ const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)(?:,(-?[\d.]+))?$/.exec(hash);
2540
3132
  if (!m) return false;
2541
- const [x, y, z, distance, rotation, angle] = m.slice(1).map(Number);
3133
+ const [x, y, z, distance, rotation, angle] = m.slice(1, 7).map(Number);
2542
3134
  if (![x, y, z, distance, rotation, angle].every(Number.isFinite)) return false;
2543
3135
  this.controls.setView({
2544
3136
  position: new THREE2.Vector3(x, y, z),
@@ -2547,15 +3139,15 @@ var VantageViewer = class _VantageViewer {
2547
3139
  angle,
2548
3140
  floorY: y
2549
3141
  });
3142
+ const slice = m[7] !== void 0 ? Number(m[7]) : null;
3143
+ this.setSlice(Number.isFinite(slice) ? slice : null);
3144
+ this.needsRender = true;
2550
3145
  return true;
2551
3146
  }
2552
3147
  /** Debounced camera→hash sync plus hashchange→camera (pasted links apply
2553
3148
  * live). `history.replaceState` avoids history spam and hashchange echo. */
2554
3149
  bindUrlState() {
2555
- const onChange = () => {
2556
- if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2557
- this.hashTimer = setTimeout(() => this.writeHash(), 250);
2558
- };
3150
+ const onChange = () => this.queueHashWrite();
2559
3151
  this.controls.addEventListener("change", onChange);
2560
3152
  const onHash = () => {
2561
3153
  if (window.location.hash === this.lastWrittenHash) return;
@@ -2569,6 +3161,12 @@ var VantageViewer = class _VantageViewer {
2569
3161
  this.hashTimer = null;
2570
3162
  };
2571
3163
  }
3164
+ /** Debounce a hash write — camera motion and slice changes funnel here. */
3165
+ queueHashWrite() {
3166
+ if (!this.options.urlState) return;
3167
+ if (this.hashTimer !== null) clearTimeout(this.hashTimer);
3168
+ this.hashTimer = setTimeout(() => this.writeHash(), 250);
3169
+ }
2572
3170
  writeHash() {
2573
3171
  const hash = this.getViewHash();
2574
3172
  if (hash === this.lastWrittenHash) return;
@@ -2615,6 +3213,7 @@ var VantageViewer = class _VantageViewer {
2615
3213
  if (this.controls.flyMode === on) return;
2616
3214
  this.controls.setMode(on ? "fly" : "map");
2617
3215
  if (on) this.emitHover(-1);
3216
+ this.needsRender = true;
2618
3217
  this.emitter.emit("mode", { fly: on });
2619
3218
  }
2620
3219
  /** Toggle free-flight on/off. */
@@ -2680,31 +3279,76 @@ var VantageViewer = class _VantageViewer {
2680
3279
  this.raycaster.setFromCamera(this.ndc, this.camera);
2681
3280
  this.emitHover(pickBiome(this.raycaster.ray, surface, this.bounds));
2682
3281
  }
3282
+ /** Request a redraw on the next animation frame. The viewer invalidates
3283
+ * itself for everything it owns (camera motion, tile streaming, settings,
3284
+ * the biome layer); call this only if you mutate the scene from outside. */
3285
+ invalidate() {
3286
+ this.needsRender = true;
3287
+ }
3288
+ /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
3289
+ * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
3290
+ static ANIM_TICK_MS = 100;
2683
3291
  frame() {
2684
3292
  const now = performance.now();
2685
3293
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
2686
3294
  this.lastFrameMs = now;
2687
- this.controls.update(dtMs);
2688
- this.sky.position.copy(this.camera.position);
3295
+ if (this.controls.update(dtMs)) this.needsRender = true;
2689
3296
  if (this.tiles) {
2690
3297
  const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
2691
3298
  this.tiles.update(focus.x, focus.z);
3299
+ if (this.tiles.fading) this.needsRender = true;
2692
3300
  if (this.shader) this.shader.uniforms["uFogCenter"].value.set(focus.x, focus.z);
2693
3301
  }
2694
- if (this.shader) {
3302
+ if (this.shader && this.mixCurrent !== this.mixTarget) {
2695
3303
  this.mixCurrent += (this.mixTarget - this.mixCurrent) * 0.2;
2696
3304
  if (Math.abs(this.mixCurrent - this.mixTarget) < 15e-4) this.mixCurrent = this.mixTarget;
2697
3305
  this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2698
- this.shader.uniforms["uTime"].value = now / 1e3 % 3600;
3306
+ this.needsRender = true;
3307
+ }
3308
+ if (this.sliceActive && this.shader) {
3309
+ const goal = this.sliceTarget ?? this.sliceRange.max + 24;
3310
+ if (this.sliceCurrent !== goal) {
3311
+ this.sliceCurrent += (goal - this.sliceCurrent) * (1 - Math.exp(-dtMs / 110));
3312
+ if (Math.abs(this.sliceCurrent - goal) < 0.05) this.sliceCurrent = goal;
3313
+ this.needsRender = true;
3314
+ }
3315
+ if (this.sliceTarget === null && this.sliceCurrent === goal) {
3316
+ this.sliceActive = false;
3317
+ this.applySlice();
3318
+ } else {
3319
+ this.shader.uniforms["uClipY"].value = this.sliceCurrent;
3320
+ if (this.slicePlane) {
3321
+ const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
3322
+ this.slicePlane.position.set(focus.x, this.sliceRange.min - 0.4, focus.z);
3323
+ }
3324
+ }
2699
3325
  }
2700
3326
  this.pickHover();
3327
+ if (this.hasAnims && now - this.lastRenderMs >= _VantageViewer.ANIM_TICK_MS) this.needsRender = true;
3328
+ if (!this.options.renderOnDemand) this.needsRender = true;
3329
+ if (!this.needsRender) return;
3330
+ this.needsRender = false;
3331
+ this.lastRenderMs = now;
3332
+ this.draw(now);
3333
+ }
3334
+ draw(now) {
3335
+ this.sky.position.copy(this.camera.position);
3336
+ if (this.shader) this.shader.uniforms["uTime"].value = now / 1e3 % 3600;
2701
3337
  this.renderer.setRenderTarget(this.msaa);
2702
3338
  this.renderer.clear();
2703
3339
  this.renderer.render(this.scene, this.camera);
2704
3340
  this.renderer.setRenderTarget(null);
2705
3341
  this.renderer.render(this.present, this.presentCamera);
2706
3342
  }
3343
+ /** Draw a fresh frame and return the canvas as a PNG data URL, for a
3344
+ * screenshot button / download link. Draws synchronously first because the
3345
+ * default framebuffer is not preserved between the on-demand renders. */
3346
+ screenshot() {
3347
+ this.draw(performance.now());
3348
+ return this.renderer.domElement.toDataURL("image/png");
3349
+ }
2707
3350
  resize() {
3351
+ this.needsRender = true;
2708
3352
  const w = this.container.clientWidth || window.innerWidth;
2709
3353
  const h = this.container.clientHeight || window.innerHeight;
2710
3354
  this.camera.aspect = w / h;
@@ -2715,6 +3359,14 @@ var VantageViewer = class _VantageViewer {
2715
3359
  this.msaa.setSize(Math.max(1, size.x), Math.max(1, size.y));
2716
3360
  }
2717
3361
  disposeCurrent() {
3362
+ if (this.slicePlane) {
3363
+ this.scene.remove(this.slicePlane);
3364
+ this.slicePlane.geometry.dispose();
3365
+ this.slicePlane.material.dispose();
3366
+ this.slicePlane = null;
3367
+ }
3368
+ this.sliceTarget = null;
3369
+ this.sliceActive = false;
2718
3370
  if (this.current) {
2719
3371
  for (const mesh of [this.current.terrain, this.current.water]) {
2720
3372
  if (!mesh) continue;
@@ -2731,6 +3383,7 @@ var VantageViewer = class _VantageViewer {
2731
3383
  this.tiles.dispose();
2732
3384
  this.tiles = null;
2733
3385
  this.manifest = null;
3386
+ this.progressiveManager = null;
2734
3387
  }
2735
3388
  if (this.shader) {
2736
3389
  this.shader.uniforms["map"]?.value?.dispose();