@thoughts-on-things/vantage-mc 0.6.0 → 0.8.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-EVPUXVSB.js';
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-LZCXJU4U.js';
2
2
  import * as THREE2 from 'three';
3
3
 
4
4
  var SKY_TOP = [0.3, 0.52, 0.84];
@@ -677,6 +677,16 @@ function sharedQuadIndex(vertexCount) {
677
677
  function isSharedQuadIndex(attr) {
678
678
  return attr !== null && attr === sharedQuadIndexAttr;
679
679
  }
680
+ var CAVE_RANGE = "vantageCaveRange";
681
+ function tagCaveRange(mesh, fullVerts, surfaceVerts) {
682
+ if (surfaceVerts >= fullVerts) return;
683
+ mesh.geometry.userData[CAVE_RANGE] = { full: fullVerts / 4 * 6, surface: surfaceVerts / 4 * 6 };
684
+ }
685
+ function applyCaveRange(mesh, showCaves) {
686
+ const range = mesh?.geometry.userData[CAVE_RANGE];
687
+ if (!range) return;
688
+ mesh.geometry.setDrawRange(0, showCaves ? range.full : range.surface);
689
+ }
680
690
  function quantizedMesh(sec, material, lm) {
681
691
  const geom = new THREE2.BufferGeometry();
682
692
  geom.setAttribute("position", new THREE2.BufferAttribute(sec.positions, 3, false));
@@ -721,6 +731,9 @@ function buildQuantizedTileMeshes(tile, material, waterMaterial, lmMaterial) {
721
731
  const head = hasLm ? sliceSection(solid, 0, lmStart) : solid;
722
732
  const terrain = quantizedMesh(head, material);
723
733
  const bounds = terrain.geometry.boundingBox.clone();
734
+ if (solid.caveStart !== void 0 && head.vertexCount === lmStart) {
735
+ tagCaveRange(terrain, lmStart, solid.caveStart);
736
+ }
724
737
  let terrainLm;
725
738
  let lightmapTex;
726
739
  if (hasLm) {
@@ -733,12 +746,18 @@ function buildQuantizedTileMeshes(tile, material, waterMaterial, lmMaterial) {
733
746
  packed: lm.packed
734
747
  });
735
748
  terrainLm.geometry.setAttribute("almuv", new THREE2.BufferAttribute(solid.lmuv, 2, false));
749
+ if (solid.caveLmStart !== void 0) {
750
+ tagCaveRange(terrainLm, solid.vertexCount - lmStart, solid.caveLmStart - lmStart);
751
+ }
736
752
  }
737
753
  let water;
738
754
  if (tile.fluid.vertexCount > 0) {
739
755
  water = quantizedMesh(tile.fluid, waterMaterial);
740
756
  water.renderOrder = 1;
741
757
  bounds.union(water.geometry.boundingBox);
758
+ if (tile.fluid.caveStart !== void 0) {
759
+ tagCaveRange(water, tile.fluid.vertexCount, tile.fluid.caveStart);
760
+ }
742
761
  }
743
762
  return { terrain, terrainLm, lightmapTex, water, bounds };
744
763
  }
@@ -834,6 +853,564 @@ var Emitter = class {
834
853
  this.listeners.clear();
835
854
  }
836
855
  };
856
+ var GRID = 16;
857
+ var SLOTS = 32;
858
+ var MAX_QUEUE = 12;
859
+ var SKIRT = 12;
860
+ var EDGES = [
861
+ [1, 0],
862
+ [-1, 0],
863
+ [0, 1],
864
+ [0, -1]
865
+ ];
866
+ function disposeCapture(meshes) {
867
+ for (const mesh of [meshes.terrain, meshes.terrainLm, meshes.water]) {
868
+ if (!mesh) continue;
869
+ mesh.removeFromParent();
870
+ if (isSharedQuadIndex(mesh.geometry.index)) mesh.geometry.setIndex(null);
871
+ mesh.geometry.dispose();
872
+ }
873
+ meshes.lightmapTex?.dispose();
874
+ }
875
+ var ImpostorLayer = class _ImpostorLayer {
876
+ renderer;
877
+ scene;
878
+ tileBlocks;
879
+ resolution;
880
+ rt;
881
+ material;
882
+ /** The shared terrain material — captures neutralize its grade/fog/clip
883
+ * uniforms for one render, and the impostor material re-applies the live
884
+ * values every frame, so display tuning keeps tracking remembered tiles. */
885
+ terrain;
886
+ /** Surface map of a still-resident hires tile, when the manager has one —
887
+ * lets a landing snapshot stitch its rim to the LIVE terrain it borders. */
888
+ liveSurface;
889
+ captureScene = new THREE2.Scene();
890
+ camera = new THREE2.OrthographicCamera();
891
+ queue = [];
892
+ byKey = /* @__PURE__ */ new Map();
893
+ freeSlots = [];
894
+ retired = false;
895
+ constructor(renderer, scene, terrainMaterial, tileBlocks, resolution, liveSurface = () => void 0) {
896
+ this.renderer = renderer;
897
+ this.scene = scene;
898
+ this.terrain = terrainMaterial;
899
+ this.tileBlocks = tileBlocks;
900
+ this.resolution = resolution;
901
+ this.liveSurface = liveSurface;
902
+ for (let i = SLOTS * SLOTS - 1; i >= 0; i--) this.freeSlots.push(i);
903
+ const size = SLOTS * resolution;
904
+ this.rt = new THREE2.WebGLRenderTarget(size, size, {
905
+ format: THREE2.RGBAFormat,
906
+ // Mipmaps keep far-zoom minification calm; regenerated by three after
907
+ // each capture render. The shader clamps its sampling LOD so slots
908
+ // never blend into each other (see uMaxLod).
909
+ generateMipmaps: true,
910
+ minFilter: THREE2.LinearMipmapLinearFilter,
911
+ magFilter: THREE2.LinearFilter,
912
+ depthBuffer: true
913
+ });
914
+ this.camera.up.set(0, 0, -1);
915
+ const t = terrainMaterial.uniforms;
916
+ this.material = new THREE2.ShaderMaterial({
917
+ glslVersion: THREE2.GLSL3,
918
+ uniforms: {
919
+ uMap: { value: this.rt.texture },
920
+ uAtlasPx: { value: SLOTS * resolution },
921
+ // Never sample past this mip: deeper levels average across atlas
922
+ // slots, which smears grazing-angle views into one murky colour.
923
+ uMaxLod: { value: Math.log2(resolution) - 2 },
924
+ // The guaranteed-hires radius; aerial haze never intrudes inside it.
925
+ uHazeMin: { value: 768 },
926
+ uFogColor: t["uFogColor"],
927
+ uFog: t["uFog"],
928
+ uFogCenter: t["uFogCenter"],
929
+ uFogRadial: t["uFogRadial"],
930
+ uFogDensity: t["uFogDensity"],
931
+ uExposure: t["uExposure"],
932
+ uSaturation: t["uSaturation"],
933
+ uContrast: t["uContrast"],
934
+ uClipY: t["uClipY"]
935
+ },
936
+ vertexShader: (
937
+ /* glsl */
938
+ `
939
+ uniform vec2 uFogCenter;
940
+ uniform float uFogRadial;
941
+ out vec2 vUv;
942
+ out float vFog;
943
+ out vec3 vWorld;
944
+ void main() {
945
+ vUv = uv;
946
+ vec4 wp = modelMatrix * vec4(position, 1.0);
947
+ vWorld = wp.xyz;
948
+ vec4 mv = viewMatrix * wp;
949
+ vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
950
+ gl_Position = projectionMatrix * mv;
951
+ }
952
+ `
953
+ ),
954
+ fragmentShader: (
955
+ /* glsl */
956
+ `
957
+ precision highp float;
958
+ uniform sampler2D uMap;
959
+ uniform float uAtlasPx;
960
+ uniform float uMaxLod;
961
+ uniform float uHazeMin;
962
+ uniform vec3 uFogColor;
963
+ uniform vec2 uFog;
964
+ uniform float uFogDensity;
965
+ uniform float uExposure;
966
+ uniform float uSaturation;
967
+ uniform float uContrast;
968
+ uniform float uClipY;
969
+ in vec2 vUv;
970
+ in float vFog;
971
+ in vec3 vWorld;
972
+ out vec4 frag;
973
+ vec3 toLinear(vec3 c) {
974
+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
975
+ }
976
+ vec3 toSRGB(vec3 c) {
977
+ c = max(c, vec3(0.0));
978
+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
979
+ }
980
+ void main() {
981
+ if (vWorld.y > uClipY) discard;
982
+ // Explicit LOD, clamped: grazing views drive the derivative-based
983
+ // mip selection deep enough to blend unrelated atlas slots (the
984
+ // "distant blue wall" smear). Capped, a slot only ever mixes with
985
+ // itself.
986
+ vec2 px = vUv * uAtlasPx;
987
+ vec2 ddx = dFdx(px);
988
+ vec2 ddy = dFdy(px);
989
+ float lod = 0.5 * log2(max(dot(ddx, ddx), max(dot(ddy, ddy), 1.0)));
990
+ vec4 t = textureLod(uMap, vUv, min(lod, uMaxLod));
991
+ if (t.a < 0.5) discard; // void columns captured as transparent
992
+ // Snapshots are captured with a NEUTRAL grade, so the live display
993
+ // settings apply here exactly like they do to hires terrain.
994
+ vec3 c = toLinear(t.rgb) * uExposure;
995
+ float l = dot(c, vec3(0.299, 0.587, 0.114));
996
+ c = mix(vec3(l), c, uSaturation);
997
+ c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
998
+ // Aerial perspective for remembered terrain: a top-down snapshot
999
+ // can't hold up viewed edge-on, so haze it by HORIZONTAL distance
1000
+ // from the eye, scaled by how high the eye sits \u2014 top-down map
1001
+ // views stay crystal clear, while a ground-level camera sees
1002
+ // remembered mountains fade into the horizon like real draw
1003
+ // distance instead of standing raw against the sky.
1004
+ float camXZ = distance(vWorld.xz, cameraPosition.xz);
1005
+ float above = max(cameraPosition.y - vWorld.y, 0.0);
1006
+ float hazeNear = max(uHazeMin, above * 2.0);
1007
+ float haze = smoothstep(hazeNear, hazeNear * 2.2, camXZ);
1008
+ float f = clamp(max(smoothstep(uFog.x, uFog.y, vFog), haze) * uFogDensity, 0.0, 1.0);
1009
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
1010
+ }
1011
+ `
1012
+ ),
1013
+ alphaToCoverage: true,
1014
+ // Skirt quads hang off each tile's rim; double-sided keeps them visible
1015
+ // from every orbit angle without winding gymnastics.
1016
+ side: THREE2.DoubleSide,
1017
+ // Impostors sit at TRUE surface height. Where hires geometry coexists
1018
+ // (the stream-in fade, the ring boundary) the depth offset pushes the
1019
+ // impostor behind it — the decal trick — so there is no geometric dip
1020
+ // and therefore no sunken step around the live disc.
1021
+ polygonOffset: true,
1022
+ polygonOffsetFactor: 2,
1023
+ polygonOffsetUnits: 4
1024
+ });
1025
+ }
1026
+ /** Remembered-tile count (for stats readouts). */
1027
+ get count() {
1028
+ return this.byKey.size;
1029
+ }
1030
+ /** Snapshot resolution in pixels per tile. */
1031
+ get resolutionPx() {
1032
+ return this.resolution;
1033
+ }
1034
+ /** The radius hires tiles are guaranteed resident to — the impostor shader
1035
+ * keeps its grazing-angle aerial haze outside this ring. */
1036
+ setHazeFloor(radius) {
1037
+ this.material.uniforms["uHazeMin"].value = Math.max(radius, 1);
1038
+ }
1039
+ /** How far remembered terrain reaches from (x,z), in blocks — the radius the
1040
+ * viewer's zoom range and fog frontier should keep visible. 0 = nothing
1041
+ * remembered. */
1042
+ extentFrom(x, z) {
1043
+ let extent = 0;
1044
+ for (const imp of this.byKey.values()) {
1045
+ const d = Math.hypot(imp.cx - x, imp.cz - z);
1046
+ if (d > extent) extent = d;
1047
+ }
1048
+ return extent === 0 ? 0 : extent + this.tileBlocks;
1049
+ }
1050
+ /** Fixed GPU cost of the atlas (RGBA + mip chain), plus the small meshes. */
1051
+ get gpuBytes() {
1052
+ const size = SLOTS * this.resolution;
1053
+ return Math.round(size * size * 4 * 1.34) + this.byKey.size * 8192;
1054
+ }
1055
+ /** Queue an evicted tile's meshes for snapshotting. Takes OWNERSHIP of the
1056
+ * meshes — they are rendered once on a later update() tick, then disposed.
1057
+ * A full queue drops its oldest entry (its meshes are simply disposed). */
1058
+ capture(tileX, tileZ, meshes, surface, minY, maxY) {
1059
+ if (this.retired) {
1060
+ disposeCapture(meshes);
1061
+ return;
1062
+ }
1063
+ const key = tileKey(tileX, tileZ);
1064
+ const queued = this.queue.findIndex((p) => p.key === key);
1065
+ if (queued >= 0) disposeCapture(this.queue.splice(queued, 1)[0].meshes);
1066
+ this.queue.push({ key, tileX, tileZ, meshes, surface, minY, maxY });
1067
+ if (this.queue.length > MAX_QUEUE) disposeCapture(this.queue.shift().meshes);
1068
+ }
1069
+ /** Forget a tile (it was removed from the manifest). */
1070
+ remove(key) {
1071
+ const queued = this.queue.findIndex((p) => p.key === key);
1072
+ if (queued >= 0) disposeCapture(this.queue.splice(queued, 1)[0].meshes);
1073
+ const imp = this.byKey.get(key);
1074
+ if (imp) this.releaseImpostor(imp);
1075
+ }
1076
+ /** Drain one pending capture (bounded per frame so a ring of evictions
1077
+ * never stacks its snapshot renders into one frame). Returns whether the
1078
+ * scene changed (the caller redraws + re-runs coverage). */
1079
+ update(focusX, focusZ) {
1080
+ const p = this.queue.shift();
1081
+ if (!p) return false;
1082
+ this.snapshot(p, focusX, focusZ);
1083
+ disposeCapture(p.meshes);
1084
+ return true;
1085
+ }
1086
+ /** Hide impostors whose hires tile is resident and fully faded in. */
1087
+ applyCoverage(shownHires) {
1088
+ for (const imp of this.byKey.values()) imp.mesh.visible = !shownHires.has(imp.key);
1089
+ }
1090
+ /** A hires tile just entered the scene: snap the facing rims of any
1091
+ * impostor neighbours onto its REAL surface heights, so the boundary
1092
+ * between the live disc and remembered terrain meets instead of stepping. */
1093
+ onHiresReady(tileX, tileZ, surface) {
1094
+ if (!surface || this.byKey.size === 0) return;
1095
+ for (const [dx, dz] of EDGES) {
1096
+ const imp = this.byKey.get(tileKey(tileX + dx, tileZ + dz));
1097
+ if (!imp) continue;
1098
+ if (this.stitchEdgeToSurface(imp, -dx, -dz, surface)) this.rebuild(imp);
1099
+ }
1100
+ }
1101
+ /** Remembered surface height under world (x,z), for the pivot fallback. */
1102
+ heightAt(x, z) {
1103
+ const tb = this.tileBlocks;
1104
+ const imp = this.byKey.get(tileKey(Math.floor(x / tb), Math.floor(z / tb)));
1105
+ if (!imp) return null;
1106
+ const step = tb / GRID;
1107
+ const i = Math.min(Math.max(Math.round((x - imp.originX) / step), 0), GRID);
1108
+ const j = Math.min(Math.max(Math.round((z - imp.originZ) / step), 0), GRID);
1109
+ const h = imp.heights[j * (GRID + 1) + i];
1110
+ return h < 1 ? null : h;
1111
+ }
1112
+ /** Drop every impostor and stop accepting captures — called when a lowres
1113
+ * pyramid arrives (a finished progressive bake): the baked rings cover the
1114
+ * whole world and supersede anything remembered. */
1115
+ retire() {
1116
+ this.retired = true;
1117
+ for (const p of this.queue.splice(0)) disposeCapture(p.meshes);
1118
+ for (const imp of [...this.byKey.values()]) this.releaseImpostor(imp);
1119
+ }
1120
+ dispose() {
1121
+ this.retire();
1122
+ this.rt.dispose();
1123
+ this.material.dispose();
1124
+ }
1125
+ releaseImpostor(imp) {
1126
+ this.scene.remove(imp.mesh);
1127
+ imp.mesh.geometry.dispose();
1128
+ this.byKey.delete(imp.key);
1129
+ this.freeSlots.push(imp.slot);
1130
+ }
1131
+ /** A free atlas slot, reusing the remembered tile farthest from the focus
1132
+ * when the atlas is full — the same nearest-wins policy streaming uses. */
1133
+ allocSlot(focusX, focusZ) {
1134
+ const free = this.freeSlots.pop();
1135
+ if (free !== void 0) return free;
1136
+ let victim = null;
1137
+ let worst = -1;
1138
+ for (const imp of this.byKey.values()) {
1139
+ const dx = imp.cx - focusX;
1140
+ const dz = imp.cz - focusZ;
1141
+ const d = dx * dx + dz * dz;
1142
+ if (d > worst) {
1143
+ worst = d;
1144
+ victim = imp;
1145
+ }
1146
+ }
1147
+ this.releaseImpostor(victim);
1148
+ return this.freeSlots.pop();
1149
+ }
1150
+ /** Windowed mean of a surface map's heights around world (wx, wz), clamped
1151
+ * into the map. Surface heights track the TOPMOST block (canopy, water
1152
+ * surface), so point samples spike whole cells wherever a tree stands —
1153
+ * the neighbourhood mean keeps impostors at believable height. Returns 0
1154
+ * (the empty sentinel) when no populated column falls in the window. */
1155
+ static meanAt(surf, wx, wz) {
1156
+ const bx = Math.round(wx) - surf.originX;
1157
+ const bz = Math.round(wz) - surf.originZ;
1158
+ let sum = 0;
1159
+ let count = 0;
1160
+ for (let dz = -4; dz <= 4; dz += 2) {
1161
+ for (let dx = -4; dx <= 4; dx += 2) {
1162
+ const cx = Math.min(Math.max(bx + dx, 0), surf.width - 1);
1163
+ const cz = Math.min(Math.max(bz + dz, 0), surf.depth - 1);
1164
+ const h = surf.height[cz * surf.width + cx];
1165
+ if (h < 1) continue;
1166
+ sum += h;
1167
+ count++;
1168
+ }
1169
+ }
1170
+ return count === 0 ? 0 : Math.round(sum / count);
1171
+ }
1172
+ /** Index of the k-th vertex (0..GRID) along an impostor's edge toward
1173
+ * (dx,dz), into its (GRID+1)² height/vertex grid. */
1174
+ static edgeIndex(dx, dz, k) {
1175
+ const n = GRID + 1;
1176
+ if (dx === 1) return k * n + GRID;
1177
+ if (dx === -1) return k * n;
1178
+ if (dz === 1) return GRID * n + k;
1179
+ return k;
1180
+ }
1181
+ /** Stitch one edge of `imp` to a live hires neighbour's surface map: each
1182
+ * rim vertex adopts the neighbour-side windowed mean at the shared world
1183
+ * position (real terrain doesn't move to meet a snapshot). Returns whether
1184
+ * anything changed. */
1185
+ stitchEdgeToSurface(imp, dx, dz, surface) {
1186
+ const tb = this.tileBlocks;
1187
+ const step = tb / GRID;
1188
+ let changed = false;
1189
+ for (let k = 0; k <= GRID; k++) {
1190
+ const idx = _ImpostorLayer.edgeIndex(dx, dz, k);
1191
+ if (imp.heights[idx] < 1) continue;
1192
+ const wx = dx === 1 ? imp.originX + tb : dx === -1 ? imp.originX : imp.originX + k * step;
1193
+ const wz = dz === 1 ? imp.originZ + tb : dz === -1 ? imp.originZ : imp.originZ + k * step;
1194
+ const h = _ImpostorLayer.meanAt(surface, wx, wz);
1195
+ if (h < 1 || h === imp.heights[idx]) continue;
1196
+ imp.heights[idx] = h;
1197
+ changed = true;
1198
+ }
1199
+ return changed;
1200
+ }
1201
+ /** Stitch every edge of a freshly-landed impostor: impostor neighbours meet
1202
+ * in the middle (both rims set to the average — the exact same values, so
1203
+ * the seam closes), live hires neighbours are adopted verbatim. Returns
1204
+ * the neighbours whose geometry must be rebuilt. */
1205
+ stitchAll(imp) {
1206
+ const dirty = [];
1207
+ for (const [dx, dz] of EDGES) {
1208
+ const nKey = tileKey(imp.tileX + dx, imp.tileZ + dz);
1209
+ const neighbour = this.byKey.get(nKey);
1210
+ if (neighbour) {
1211
+ let changed = false;
1212
+ for (let k = 0; k <= GRID; k++) {
1213
+ const a = _ImpostorLayer.edgeIndex(dx, dz, k);
1214
+ const b = _ImpostorLayer.edgeIndex(-dx, -dz, k);
1215
+ const ha = imp.heights[a];
1216
+ const hb = neighbour.heights[b];
1217
+ if (ha < 1 || hb < 1 || ha === hb) continue;
1218
+ const avg = Math.round((ha + hb) / 2);
1219
+ imp.heights[a] = avg;
1220
+ if (neighbour.heights[b] !== avg) {
1221
+ neighbour.heights[b] = avg;
1222
+ changed = true;
1223
+ }
1224
+ }
1225
+ if (changed) dirty.push(neighbour);
1226
+ continue;
1227
+ }
1228
+ const live = this.liveSurface(nKey);
1229
+ if (live) this.stitchEdgeToSurface(imp, dx, dz, live);
1230
+ }
1231
+ return dirty;
1232
+ }
1233
+ /** Build (or rebuild) an impostor's heightfield geometry from its stored
1234
+ * heights + atlas slot: true-height grid, atlas UVs inset half a texel
1235
+ * against slot bleed, rim skirts. Returns null for a mesh with no
1236
+ * drawable cell. */
1237
+ buildGeometry(imp) {
1238
+ const tb = this.tileBlocks;
1239
+ const res = this.resolution;
1240
+ const n = GRID + 1;
1241
+ const { heights, originX, originZ, slot } = imp;
1242
+ const sx = slot % SLOTS * res;
1243
+ const sy = Math.floor(slot / SLOTS) * res;
1244
+ const pos = [];
1245
+ const uv = [];
1246
+ const atlasPx = SLOTS * res;
1247
+ const u0 = (sx + 0.5) / atlasPx;
1248
+ const v0 = (sy + 0.5) / atlasPx;
1249
+ const span = (res - 1) / atlasPx;
1250
+ let minH = Infinity;
1251
+ let maxH = -Infinity;
1252
+ for (let j = 0; j < n; j++) {
1253
+ for (let i = 0; i < n; i++) {
1254
+ const h = heights[j * n + i];
1255
+ pos.push(originX + i * tb / GRID, h < 1 ? 0 : h, originZ + j * tb / GRID);
1256
+ if (h >= 1) {
1257
+ if (h < minH) minH = h;
1258
+ if (h > maxH) maxH = h;
1259
+ }
1260
+ uv.push(u0 + i / GRID * span, v0 + (1 - j / GRID) * span);
1261
+ }
1262
+ }
1263
+ if (!Number.isFinite(minH)) return null;
1264
+ const idx = [];
1265
+ for (let j = 0; j < GRID; j++) {
1266
+ for (let i = 0; i < GRID; i++) {
1267
+ const a = j * n + i;
1268
+ const b = a + 1;
1269
+ const c = a + n;
1270
+ const d = c + 1;
1271
+ if (heights[a] < 1 || heights[b] < 1 || heights[c] < 1 || heights[d] < 1) continue;
1272
+ idx.push(a, c, d, a, d, b);
1273
+ }
1274
+ }
1275
+ if (idx.length === 0) return null;
1276
+ const addSkirt = (a, b) => {
1277
+ if (heights[a] < 1 || heights[b] < 1) return;
1278
+ const base = pos.length / 3;
1279
+ for (const s of [a, b]) {
1280
+ pos.push(pos[s * 3], pos[s * 3 + 1] - SKIRT, pos[s * 3 + 2]);
1281
+ uv.push(uv[s * 2], uv[s * 2 + 1]);
1282
+ }
1283
+ idx.push(a, b, base + 1, a, base + 1, base);
1284
+ };
1285
+ for (let k = 0; k < GRID; k++) {
1286
+ addSkirt(k, k + 1);
1287
+ addSkirt(GRID * n + k, GRID * n + k + 1);
1288
+ addSkirt(k * n, (k + 1) * n);
1289
+ addSkirt(k * n + GRID, (k + 1) * n + GRID);
1290
+ }
1291
+ const geom = new THREE2.BufferGeometry();
1292
+ geom.setAttribute("position", new THREE2.BufferAttribute(new Float32Array(pos), 3));
1293
+ geom.setAttribute("uv", new THREE2.BufferAttribute(new Float32Array(uv), 2));
1294
+ geom.setIndex(idx);
1295
+ const box = new THREE2.Box3(new THREE2.Vector3(originX, minH - SKIRT, originZ), new THREE2.Vector3(originX + tb, maxH, originZ + tb));
1296
+ geom.boundingBox = box;
1297
+ const sphere = new THREE2.Sphere();
1298
+ box.getBoundingSphere(sphere);
1299
+ geom.boundingSphere = sphere;
1300
+ return geom;
1301
+ }
1302
+ /** Swap in freshly-built geometry after a stitch adjusted stored heights. */
1303
+ rebuild(imp) {
1304
+ const geom = this.buildGeometry(imp);
1305
+ if (!geom) return;
1306
+ imp.mesh.geometry.dispose();
1307
+ imp.mesh.geometry = geom;
1308
+ }
1309
+ /** Render the tile's meshes top-down into its atlas slot and swap in the
1310
+ * stitched heightfield impostor. */
1311
+ snapshot(p, focusX, focusZ) {
1312
+ const meshes = [p.meshes.terrain, p.meshes.terrainLm, p.meshes.water].filter(Boolean);
1313
+ if (meshes.length === 0) return;
1314
+ const tb = this.tileBlocks;
1315
+ const originX = p.tileX * tb;
1316
+ const originZ = p.tileZ * tb;
1317
+ const n = GRID + 1;
1318
+ const heights = new Int16Array(n * n);
1319
+ for (let j = 0; j < n; j++) {
1320
+ for (let i = 0; i < n; i++) {
1321
+ heights[j * n + i] = _ImpostorLayer.meanAt(p.surface, originX + i * tb / GRID, originZ + j * tb / GRID);
1322
+ }
1323
+ }
1324
+ let drawable = false;
1325
+ outer: for (let j = 0; j < GRID; j++) {
1326
+ for (let i = 0; i < GRID; i++) {
1327
+ const a = j * n + i;
1328
+ if (heights[a] >= 1 && heights[a + 1] >= 1 && heights[a + n] >= 1 && heights[a + n + 1] >= 1) {
1329
+ drawable = true;
1330
+ break outer;
1331
+ }
1332
+ }
1333
+ }
1334
+ if (!drawable) return;
1335
+ const existing = this.byKey.get(p.key);
1336
+ if (existing) this.releaseImpostor(existing);
1337
+ const slot = this.allocSlot(focusX, focusZ);
1338
+ const res = this.resolution;
1339
+ const sx = slot % SLOTS * res;
1340
+ const sy = Math.floor(slot / SLOTS) * res;
1341
+ const u = this.terrain.uniforms;
1342
+ const saved = /* @__PURE__ */ new Map();
1343
+ const neutral = [
1344
+ ["uFogDensity", 0],
1345
+ ["uBiomeMix", 0],
1346
+ ["uHi", -1],
1347
+ ["uClipY", 1e9],
1348
+ ["uExposure", 1],
1349
+ ["uSaturation", 1],
1350
+ ["uContrast", 1]
1351
+ ];
1352
+ for (const [k, v] of neutral) {
1353
+ if (!u[k]) continue;
1354
+ saved.set(k, u[k].value);
1355
+ u[k].value = v;
1356
+ }
1357
+ for (const mesh of meshes) this.captureScene.add(mesh);
1358
+ const cam = this.camera;
1359
+ cam.left = originX;
1360
+ cam.right = originX + tb;
1361
+ cam.top = -originZ;
1362
+ cam.bottom = -(originZ + tb);
1363
+ cam.near = 1;
1364
+ cam.far = p.maxY - p.minY + 32;
1365
+ cam.position.set(0, p.maxY + 16, 0);
1366
+ cam.lookAt(0, 0, 0);
1367
+ cam.updateProjectionMatrix();
1368
+ for (const mesh of meshes) mesh.frustumCulled = false;
1369
+ const renderer = this.renderer;
1370
+ const prevTarget = renderer.getRenderTarget();
1371
+ const prevAutoClear = renderer.autoClear;
1372
+ const prevColor = renderer.getClearColor(new THREE2.Color());
1373
+ const prevAlpha = renderer.getClearAlpha();
1374
+ this.rt.viewport.set(sx, sy, res, res);
1375
+ this.rt.scissor.set(sx, sy, res, res);
1376
+ this.rt.scissorTest = true;
1377
+ renderer.setRenderTarget(this.rt);
1378
+ renderer.setClearColor(0, 0);
1379
+ renderer.autoClear = false;
1380
+ renderer.clear(true, true);
1381
+ renderer.render(this.captureScene, cam);
1382
+ renderer.setRenderTarget(prevTarget);
1383
+ renderer.setClearColor(prevColor, prevAlpha);
1384
+ renderer.autoClear = prevAutoClear;
1385
+ for (const [k, v] of saved) u[k].value = v;
1386
+ this.terrain.uniformsNeedUpdate = true;
1387
+ const imp = {
1388
+ key: p.key,
1389
+ tileX: p.tileX,
1390
+ tileZ: p.tileZ,
1391
+ slot,
1392
+ mesh: new THREE2.Mesh(void 0, this.material),
1393
+ heights,
1394
+ originX,
1395
+ originZ,
1396
+ cx: originX + tb / 2,
1397
+ cz: originZ + tb / 2
1398
+ };
1399
+ this.byKey.set(p.key, imp);
1400
+ const dirty = this.stitchAll(imp);
1401
+ const geom = this.buildGeometry(imp);
1402
+ if (!geom) {
1403
+ this.byKey.delete(p.key);
1404
+ this.freeSlots.push(slot);
1405
+ return;
1406
+ }
1407
+ imp.mesh.geometry.dispose();
1408
+ imp.mesh.geometry = geom;
1409
+ imp.mesh.renderOrder = -1;
1410
+ this.scene.add(imp.mesh);
1411
+ for (const neighbour of dirty) this.rebuild(neighbour);
1412
+ }
1413
+ };
837
1414
 
838
1415
  // src/three/streaming.ts
839
1416
  function nearbyTiles(index, tileBlocks, focusX, focusZ, radius, predictedX = focusX, predictedZ = focusZ) {
@@ -908,6 +1485,11 @@ var TileManager = class _TileManager {
908
1485
  opts;
909
1486
  lowresMaterial;
910
1487
  lmMaterial;
1488
+ /** Map memory (impostor snapshots of evicted tiles); null when the world
1489
+ * ships a lowres pyramid, when disabled, or without a renderer. */
1490
+ impostors = null;
1491
+ /** Kept for live map-memory reconfiguration (resolution changes). */
1492
+ renderer;
911
1493
  /** Widens the shared atlas to cover a tile's layers before it's drawn (live
912
1494
  * renders only); null when the atlas is complete. */
913
1495
  ensureAtlas;
@@ -944,6 +1526,10 @@ var TileManager = class _TileManager {
944
1526
  /** Learned tile weights survive eviction and make future admission byte-aware. */
945
1527
  sizeHints = /* @__PURE__ */ new Map();
946
1528
  averageHiresBytes = 12 * 1024 * 1024;
1529
+ /** Whether resident tiles draw their cave-dark tails (VTLA). The viewer's
1530
+ * cave policy toggles this off while the camera is above ground with the
1531
+ * depth slice closed. */
1532
+ caveGeometry = true;
947
1533
  focusX = 0;
948
1534
  focusZ = 0;
949
1535
  biomesCache = null;
@@ -952,7 +1538,7 @@ var TileManager = class _TileManager {
952
1538
  minY = 0;
953
1539
  maxY = 320;
954
1540
  constructor(options) {
955
- const { lowresMaterial, lmMaterial, ensureAtlas, ...rest } = options;
1541
+ const { lowresMaterial, lmMaterial, ensureAtlas, renderer, mapMemory, ...rest } = options;
956
1542
  this.opts = {
957
1543
  viewDistance: 768,
958
1544
  // Sized to fill the whole view-distance disc for 128-block tiles
@@ -974,6 +1560,23 @@ var TileManager = class _TileManager {
974
1560
  for (const lvl of this.lowLevels) {
975
1561
  this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
976
1562
  }
1563
+ this.renderer = renderer ?? null;
1564
+ const res = mapMemory ?? 64;
1565
+ if (renderer && res > 0 && !options.manifest.lowres) {
1566
+ this.impostors = new ImpostorLayer(renderer, options.scene, options.material, this.tileBlocks, res, this.readySurface);
1567
+ this.applyHazeFloor();
1568
+ }
1569
+ }
1570
+ /** Surface map of a fully-streamed resident hires tile (the impostor layer
1571
+ * stitches remembered rims onto live terrain with it). */
1572
+ readySurface = (key) => {
1573
+ const rec = this.records.get(key);
1574
+ return rec?.level === 0 && rec.state === "ready" ? rec.surface : void 0;
1575
+ };
1576
+ /** Keep the impostor haze floor tracking the guaranteed-hires radius (the
1577
+ * view distance, unless the tile budget's disc runs out first). */
1578
+ applyHazeFloor() {
1579
+ this.impostors?.setHazeFloor(Math.min(this.opts.viewDistance, this.tileBlocks * Math.sqrt(this.opts.maxTiles / Math.PI)));
977
1580
  }
978
1581
  /** Tile span in blocks at a pyramid level (0 = hires). */
979
1582
  levelBlocks(level) {
@@ -1001,6 +1604,11 @@ var TileManager = class _TileManager {
1001
1604
  this.focusZ = focusZ;
1002
1605
  this.flushOne();
1003
1606
  this.retrySweep();
1607
+ if (this.impostors?.update(focusX, focusZ)) {
1608
+ this.coverageDirty = true;
1609
+ this.invalidate();
1610
+ this.emitter.emit("change", this.stats);
1611
+ }
1004
1612
  if (this.fadingKeys.size > 0) {
1005
1613
  const now = performance.now();
1006
1614
  for (const key of this.fadingKeys) {
@@ -1029,7 +1637,7 @@ var TileManager = class _TileManager {
1029
1637
  this.lastFocusX = focusX;
1030
1638
  this.lastFocusZ = focusZ;
1031
1639
  const { viewDistance, maxTiles, maxBytes } = this.opts;
1032
- let lowBytes = 0;
1640
+ let lowBytes = this.impostors?.gpuBytes ?? 0;
1033
1641
  for (const rec of this.records.values()) if (rec.level > 0) lowBytes += rec.memoryBytes;
1034
1642
  const hiresBytes = Math.max(1, maxBytes - lowBytes);
1035
1643
  const desired = admitTiles(
@@ -1079,6 +1687,7 @@ var TileManager = class _TileManager {
1079
1687
  pump() {
1080
1688
  while (this.inFlight < this.opts.concurrency && this.inFlight + this.pendingBuilt < this.opts.concurrency && this.queue.length > 0) {
1081
1689
  const { ref, level } = this.queue.pop();
1690
+ if (level === 0 && this.index.get(tileKey(ref.x, ref.z)) !== ref) continue;
1082
1691
  if (level === 0) void this.loadTile(ref);
1083
1692
  else void this.loadLowres(ref, level);
1084
1693
  }
@@ -1101,6 +1710,7 @@ var TileManager = class _TileManager {
1101
1710
  this.opts.scene.add(rec.terrain);
1102
1711
  if (rec.terrainLm) this.opts.scene.add(rec.terrainLm);
1103
1712
  if (rec.water) this.opts.scene.add(rec.water);
1713
+ if (rec.level === 0) this.impostors?.onHiresReady(rec.ref.x, rec.ref.z, rec.surface);
1104
1714
  this.coverageDirty = true;
1105
1715
  this.invalidate();
1106
1716
  this.emitter.emit("change", this.stats);
@@ -1150,6 +1760,7 @@ var TileManager = class _TileManager {
1150
1760
  for (const [key, rec] of this.records) {
1151
1761
  if (rec.level === 0 && rec.state === "ready" && !this.fadingKeys.has(key)) shown.add(tileKey(rec.ref.x, rec.ref.z));
1152
1762
  }
1763
+ this.impostors?.applyCoverage(shown);
1153
1764
  let finerIndex = this.index;
1154
1765
  for (const lvl of this.lowLevels) {
1155
1766
  const shownHere = /* @__PURE__ */ new Set();
@@ -1175,21 +1786,50 @@ var TileManager = class _TileManager {
1175
1786
  * update(); already-known tiles are ignored. Returns whether anything was
1176
1787
  * added. */
1177
1788
  addTiles(tiles) {
1178
- let added = false;
1789
+ return this.reconcileTiles(tiles, false);
1790
+ }
1791
+ /** Reconcile the complete hires index from a continuous server manifest.
1792
+ * Revision changes evict only affected resident tiles; removed coordinates
1793
+ * disappear. Unchanged terrain remains on the GPU without a network fetch. */
1794
+ syncTiles(tiles) {
1795
+ return this.reconcileTiles(tiles, true);
1796
+ }
1797
+ reconcileTiles(tiles, prune) {
1798
+ let changed = false;
1799
+ const incoming = prune ? new Set(tiles.map((tile) => tileKey(tile.x, tile.z))) : null;
1800
+ if (incoming) {
1801
+ for (const [key] of this.index) {
1802
+ if (incoming.has(key)) continue;
1803
+ this.index.delete(key);
1804
+ const rec = this.records.get(key);
1805
+ if (rec) this.unload(key, rec);
1806
+ this.impostors?.remove(key);
1807
+ changed = true;
1808
+ }
1809
+ }
1179
1810
  for (const t of tiles) {
1180
1811
  const k = tileKey(t.x, t.z);
1181
- if (!this.index.has(k)) {
1812
+ const previous = this.index.get(k);
1813
+ if (!previous) {
1182
1814
  this.index.set(k, t);
1183
- added = true;
1815
+ changed = true;
1816
+ } else if (t.revision !== previous.revision) {
1817
+ this.index.set(k, t);
1818
+ const rec = this.records.get(k);
1819
+ if (rec) this.unload(k, rec);
1820
+ changed = true;
1821
+ } else {
1822
+ previous.path = t.path;
1823
+ previous.bytes = t.bytes;
1184
1824
  }
1185
1825
  }
1186
- if (added) {
1826
+ if (changed) {
1187
1827
  this.lastFocusX = Infinity;
1188
1828
  this.lastFocusZ = Infinity;
1189
1829
  this.invalidate();
1190
1830
  this.emitter.emit("change", this.stats);
1191
1831
  }
1192
- return added;
1832
+ return changed;
1193
1833
  }
1194
1834
  /** Install the lowres pyramid once a progressive render finishes (its earlier
1195
1835
  * manifests carried no lowres). No-op without a lowres material, or if a
@@ -1199,21 +1839,60 @@ var TileManager = class _TileManager {
1199
1839
  const levels = [...lowres.levels].sort((a, b) => a.level - b.level);
1200
1840
  this.lowLevels.push(...levels);
1201
1841
  for (const lvl of levels) this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
1842
+ this.impostors?.dispose();
1843
+ this.impostors = null;
1202
1844
  this.lastFocusX = Infinity;
1203
1845
  this.lastFocusZ = Infinity;
1204
1846
  this.coverageDirty = true;
1205
1847
  this.invalidate();
1206
1848
  }
1207
- /** Live-tune streaming (view distance, tile budget, fetch concurrency).
1208
- * Takes effect on the next update(): the plan is recomputed from scratch. */
1849
+ /** Show or hide every resident tile's cave-dark geometry (VTLA tiles order
1850
+ * it as a contiguous tail per mesh, so hiding is a shorter draw range —
1851
+ * same draw calls, fewer vertices shaded). Tiles built while hidden come up
1852
+ * hidden. Tiles without a cave tail (older formats, all-surface tiles) are
1853
+ * untouched. Returns whether anything changed (the caller redraws). */
1854
+ setCaveGeometry(visible) {
1855
+ if (this.caveGeometry === visible) return false;
1856
+ this.caveGeometry = visible;
1857
+ for (const rec of this.records.values()) {
1858
+ if (rec.level !== 0) continue;
1859
+ applyCaveRange(rec.terrain, visible);
1860
+ applyCaveRange(rec.terrainLm, visible);
1861
+ applyCaveRange(rec.water, visible);
1862
+ }
1863
+ return true;
1864
+ }
1865
+ /** Live-tune streaming (view distance, tile budget, fetch concurrency,
1866
+ * map-memory resolution). Takes effect on the next update(): the plan is
1867
+ * recomputed from scratch. Changing `mapMemory` rebuilds the impostor
1868
+ * atlas, which forgets remembered terrain (it re-accumulates as you pan). */
1209
1869
  configure(settings) {
1210
1870
  if (settings.viewDistance !== void 0) this.opts.viewDistance = settings.viewDistance;
1211
1871
  if (settings.maxTiles !== void 0) this.opts.maxTiles = settings.maxTiles;
1212
1872
  if (settings.concurrency !== void 0) this.opts.concurrency = settings.concurrency;
1213
1873
  if (settings.maxBytes !== void 0) this.opts.maxBytes = settings.maxBytes;
1874
+ if (settings.mapMemory !== void 0 && settings.mapMemory !== this.mapMemoryResolution) {
1875
+ this.impostors?.dispose();
1876
+ this.impostors = null;
1877
+ if (this.renderer && settings.mapMemory > 0 && this.lowLevels.length === 0) {
1878
+ this.impostors = new ImpostorLayer(this.renderer, this.opts.scene, this.opts.material, this.tileBlocks, settings.mapMemory, this.readySurface);
1879
+ }
1880
+ this.invalidate();
1881
+ }
1882
+ this.applyHazeFloor();
1214
1883
  this.lastFocusX = Infinity;
1215
1884
  this.lastFocusZ = Infinity;
1216
1885
  }
1886
+ /** The active map-memory impostor resolution (0 = off/unavailable). */
1887
+ get mapMemoryResolution() {
1888
+ return this.impostors?.resolutionPx ?? 0;
1889
+ }
1890
+ /** How far remembered (impostor) terrain reaches from (x,z), in blocks —
1891
+ * 0 without map memory. The viewer sizes zoom range and fog off this so
1892
+ * the remembered map is actually visible. */
1893
+ mapMemoryExtent(x, z) {
1894
+ return this.impostors?.extentFrom(x, z) ?? 0;
1895
+ }
1217
1896
  /** The current stream-in radius, in blocks. */
1218
1897
  get viewDistance() {
1219
1898
  return this.opts.viewDistance;
@@ -1340,6 +2019,11 @@ var TileManager = class _TileManager {
1340
2019
  releaseAfterUpload(meshes.terrain.geometry);
1341
2020
  if (meshes.terrainLm) releaseAfterUpload(meshes.terrainLm.geometry);
1342
2021
  if (meshes.water) releaseAfterUpload(meshes.water.geometry);
2022
+ if (!this.caveGeometry) {
2023
+ applyCaveRange(meshes.terrain, false);
2024
+ applyCaveRange(meshes.terrainLm, false);
2025
+ applyCaveRange(meshes.water, false);
2026
+ }
1343
2027
  rec.terrain = meshes.terrain;
1344
2028
  rec.terrainLm = meshes.terrainLm;
1345
2029
  rec.lightmapTex = meshes.lightmapTex;
@@ -1368,15 +2052,31 @@ var TileManager = class _TileManager {
1368
2052
  }
1369
2053
  }
1370
2054
  unload(key, rec) {
2055
+ const priorState = rec.state;
2056
+ rec.state = "empty";
1371
2057
  rec.abort?.abort();
1372
- if (rec.state === "built") this.pendingBuilt--;
2058
+ if (priorState === "built") this.pendingBuilt--;
2059
+ const remember = this.impostors !== null && rec.level === 0 && priorState === "ready" && rec.terrain !== void 0 && rec.surface !== void 0;
1373
2060
  for (const mesh of [rec.terrain, rec.terrainLm, rec.water]) {
1374
2061
  if (!mesh) continue;
1375
2062
  this.opts.scene.remove(mesh);
2063
+ if (remember) continue;
1376
2064
  if (isSharedQuadIndex(mesh.geometry.index)) mesh.geometry.setIndex(null);
1377
2065
  mesh.geometry.dispose();
1378
2066
  }
1379
- rec.lightmapTex?.dispose();
2067
+ if (remember) {
2068
+ rec.fadeStart = void 0;
2069
+ this.impostors.capture(
2070
+ rec.ref.x,
2071
+ rec.ref.z,
2072
+ { terrain: rec.terrain, terrainLm: rec.terrainLm, water: rec.water, lightmapTex: rec.lightmapTex },
2073
+ rec.surface,
2074
+ this.minY,
2075
+ this.maxY
2076
+ );
2077
+ } else {
2078
+ rec.lightmapTex?.dispose();
2079
+ }
1380
2080
  this.records.delete(key);
1381
2081
  this.failCounts.delete(key);
1382
2082
  this.fadingKeys.delete(key);
@@ -1388,7 +2088,7 @@ var TileManager = class _TileManager {
1388
2088
  * leave first; one nearest tile is always kept so an oversized outlier does
1389
2089
  * not create an unload/refetch loop. Learned weights make the next plan fit. */
1390
2090
  trimToMemoryBudget() {
1391
- let total = 0;
2091
+ let total = this.impostors?.gpuBytes ?? 0;
1392
2092
  const hires = [];
1393
2093
  for (const [key, rec] of this.records) {
1394
2094
  total += rec.memoryBytes;
@@ -1433,7 +2133,9 @@ var TileManager = class _TileManager {
1433
2133
  bytes += rec.ref.bytes;
1434
2134
  } else if (rec.state === "loading" || rec.state === "built") loading++;
1435
2135
  }
1436
- this.statsCache = { loaded, loading, total: this.index.size, lowres, vertexCount, triangleCount, bytes, residentBytes };
2136
+ const remembered = this.impostors?.count ?? 0;
2137
+ if (this.impostors) residentBytes += this.impostors.gpuBytes;
2138
+ this.statsCache = { loaded, loading, total: this.index.size, lowres, remembered, vertexCount, triangleCount, bytes, residentBytes };
1437
2139
  return this.statsCache;
1438
2140
  }
1439
2141
  /** Aggregated biome share across every resident tile, most common first. */
@@ -1485,7 +2187,7 @@ var TileManager = class _TileManager {
1485
2187
  }
1486
2188
  }
1487
2189
  if (n > 0) return sum / n;
1488
- return this.lowresHeightAt(x, z);
2190
+ return this.lowresHeightAt(x, z) ?? this.impostors?.heightAt(x, z) ?? null;
1489
2191
  };
1490
2192
  /** Height from the finest resident lowres level covering (x,z), or null. */
1491
2193
  lowresHeightAt(x, z) {
@@ -1530,6 +2232,8 @@ var TileManager = class _TileManager {
1530
2232
  this.disposed = true;
1531
2233
  this.queue = [];
1532
2234
  this.pendingAdd = [];
2235
+ this.impostors?.dispose();
2236
+ this.impostors = null;
1533
2237
  for (const [key, rec] of [...this.records]) this.unload(key, rec);
1534
2238
  this.emitter.clear();
1535
2239
  }
@@ -2382,6 +3086,8 @@ var VantageViewer = class _VantageViewer {
2382
3086
  // world reloads (the poll checks its manager is still current).
2383
3087
  progressiveManager = null;
2384
3088
  lastTextureLayers = 0;
3089
+ /** Last progress payload emitted, for deduplication across identical polls. */
3090
+ lastProgress = null;
2385
3091
  /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
2386
3092
  * poll coalesce onto one request instead of racing separate fetches. */
2387
3093
  atlasRefresh = null;
@@ -2402,6 +3108,10 @@ var VantageViewer = class _VantageViewer {
2402
3108
  lastSliceY = null;
2403
3109
  /** The dark "unexplored rock" floor under a sliced world. */
2404
3110
  slicePlane = null;
3111
+ // Cave-geometry draw policy (VTLA tiles): whether cave-dark tails are in the
3112
+ // draw ranges right now, re-evaluated each frame under 'auto'.
3113
+ caveMode = "auto";
3114
+ cavesShown = true;
2405
3115
  // Live lighting appearance (applied to the shader on load and on change).
2406
3116
  light = { ...DEFAULT_LIGHT };
2407
3117
  // Live display fidelity (shader uniforms + render scale).
@@ -2442,8 +3152,10 @@ var VantageViewer = class _VantageViewer {
2442
3152
  display: options.display ?? {},
2443
3153
  streaming: options.streaming ?? {},
2444
3154
  urlState: options.urlState ?? false,
2445
- renderOnDemand: options.renderOnDemand ?? true
3155
+ renderOnDemand: options.renderOnDemand ?? true,
3156
+ caveGeometry: options.caveGeometry ?? "auto"
2446
3157
  };
3158
+ this.caveMode = this.options.caveGeometry;
2447
3159
  if (options.light) this.light = { ...this.light, ...options.light };
2448
3160
  if (options.display) this.display = { ...this.display, ...options.display };
2449
3161
  this.renderer = new THREE2.WebGLRenderer({ antialias: false });
@@ -2538,6 +3250,7 @@ var VantageViewer = class _VantageViewer {
2538
3250
  this.hasAnims = texData.anims.length > 0;
2539
3251
  this.lastTextureLayers = manifest.textureLayers ?? texData.layers;
2540
3252
  this.tile = null;
3253
+ this.cavesShown = true;
2541
3254
  this.tiles = new TileManager({
2542
3255
  manifest,
2543
3256
  fetch: source.fetch,
@@ -2551,11 +3264,15 @@ var VantageViewer = class _VantageViewer {
2551
3264
  // tile's insertion on the atlas covering its layers (a no-op once the
2552
3265
  // atlas is complete). Returns the layer count now loaded.
2553
3266
  ...manifest.rendering ? { ensureAtlas: (n) => this.ensureAtlasLayers(source, n).then(() => this.lastTextureLayers) } : {},
3267
+ // Map memory: pyramid-less worlds snapshot evicted tiles so explored
3268
+ // terrain persists on the zoomed-out map (see StreamingSettings).
3269
+ renderer: this.renderer,
2554
3270
  ...this.options.streaming
2555
3271
  });
2556
3272
  this.setHeightSampler(this.tiles.heightAt);
2557
3273
  this.tilesUnsub = this.tiles.on("change", (stats) => {
2558
3274
  this.needsRender = true;
3275
+ if (!this.manifest?.lowres) this.applyViewLimits();
2559
3276
  this.emitter.emit("stats", stats);
2560
3277
  const now = performance.now();
2561
3278
  if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
@@ -2576,7 +3293,7 @@ var VantageViewer = class _VantageViewer {
2576
3293
  this._biomes = [];
2577
3294
  this.emitter.emit("load", {
2578
3295
  // Streamed worlds: the tile format follows the manifest schema version.
2579
- magic: manifest.format >= 5 ? "VTL9" : manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
3296
+ magic: manifest.format >= 6 ? "VTLA" : manifest.format >= 5 ? "VTL9" : manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
2580
3297
  vertexCount: 0,
2581
3298
  triangleCount: 0,
2582
3299
  size,
@@ -2584,40 +3301,64 @@ var VantageViewer = class _VantageViewer {
2584
3301
  });
2585
3302
  if (manifest.rendering) {
2586
3303
  this.progressiveManager = this.tiles;
3304
+ this.lastProgress = null;
2587
3305
  this.emitProgress(manifest);
2588
3306
  void this.pollProgressive(source, this.tiles);
2589
3307
  }
2590
3308
  }
2591
3309
  /** Emit a `progress` event from a manifest (falling back to the tile count
2592
- * when the generator didn't include a `progress` block). */
3310
+ * when the generator didn't include a `progress` block). Deduplicated: a
3311
+ * continuous server reports the same numbers poll after poll, and repeating
3312
+ * them would tick every listener (React state, HUDs) for nothing. Returns
3313
+ * whether anything actually changed (and was emitted). */
2593
3314
  emitProgress(m) {
2594
- this.emitter.emit("progress", {
3315
+ const progress = {
2595
3316
  done: m.progress?.done ?? m.tiles.length,
2596
3317
  total: m.progress?.total ?? m.tiles.length,
2597
3318
  rendering: m.rendering ?? false
2598
- });
3319
+ };
3320
+ const last = this.lastProgress;
3321
+ if (last && last.done === progress.done && last.total === progress.total && last.rendering === progress.rendering) return false;
3322
+ this.lastProgress = progress;
3323
+ this.emitter.emit("progress", progress);
3324
+ return true;
2599
3325
  }
2600
3326
  /** 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. */
3327
+ * interval, stream new/revised tiles in, widen the texture array when the
3328
+ * atlas grows, and install the lowres pyramid once a batch bake completes.
3329
+ * Continuous sources run until the world is replaced. */
2604
3330
  async pollProgressive(source, manager) {
2605
3331
  const dec = new TextDecoder();
3332
+ let delay = _VantageViewer.POLL_MS;
3333
+ let manifestEtag;
2606
3334
  for (; ; ) {
2607
- await new Promise((r) => setTimeout(r, 1200));
3335
+ await new Promise((r) => setTimeout(r, delay));
2608
3336
  if (this.tiles !== manager || this.progressiveManager !== manager) return;
2609
3337
  let m;
2610
3338
  try {
2611
- m = parseManifest(JSON.parse(dec.decode(await source.fetch("manifest.json"))));
3339
+ if (source.fetchConditional) {
3340
+ const res = await source.fetchConditional("manifest.json", manifestEtag);
3341
+ if (res === "unchanged") {
3342
+ delay = Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
3343
+ continue;
3344
+ }
3345
+ m = parseManifest(JSON.parse(dec.decode(res.buffer)));
3346
+ manifestEtag = res.etag;
3347
+ } else {
3348
+ m = parseManifest(JSON.parse(dec.decode(await source.fetch("manifest.json"))));
3349
+ }
2612
3350
  } catch {
3351
+ delay = Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
2613
3352
  continue;
2614
3353
  }
2615
- if ((m.textureLayers ?? 0) > this.lastTextureLayers) {
3354
+ const atlasGrew = (m.textureLayers ?? 0) > this.lastTextureLayers;
3355
+ if (atlasGrew) {
2616
3356
  await this.ensureAtlasLayers(source, m.textureLayers ?? 0);
2617
3357
  if (this.tiles !== manager) return;
2618
3358
  }
2619
- manager.addTiles(m.tiles);
2620
- this.emitProgress(m);
3359
+ const changed = m.dynamic ? manager.syncTiles(m.tiles) : manager.addTiles(m.tiles);
3360
+ const progressed = this.emitProgress(m);
3361
+ delay = !m.dynamic || changed || atlasGrew || progressed ? _VantageViewer.POLL_MS : Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
2621
3362
  if (!m.rendering) {
2622
3363
  this.manifest = m;
2623
3364
  if (m.lowres) manager.ingestLowres(m.lowres);
@@ -2723,8 +3464,15 @@ var VantageViewer = class _VantageViewer {
2723
3464
  * fog retreats to the world edge — a faint horizon haze, never a wall. The
2724
3465
  * hires→lowres seam needs no hiding: finer data simply overlays coarser.
2725
3466
  *
2726
- * Without one (format 1), zoom and fog hug the hires ring so the map never
2727
- * becomes a field of holes: solid haze right where tiles stop. */
3467
+ * Without one, zoom and fog hug the drawable frontier: the hires ring on a
3468
+ * fresh session (so the map never becomes a field of holes — solid haze
3469
+ * right where tiles stop), growing to the remembered map-memory extent as
3470
+ * the camera explores. Re-applied on tile 'change' events, so the fog wall
3471
+ * recedes as snapshots land.
3472
+ *
3473
+ * Both branches share hard sanity ceilings (60k zoom, 250k far plane):
3474
+ * beyond them depth precision and control feel degrade faster than any
3475
+ * real overview gains — a 60k-block eye already frames a 100k-block map. */
2728
3476
  applyViewLimits() {
2729
3477
  if (!this.tiles || !this.shader) return;
2730
3478
  const viewDistance = this.tiles.viewDistance;
@@ -2735,10 +3483,11 @@ var VantageViewer = class _VantageViewer {
2735
3483
  this.camera.far = Math.min(Math.max(8e3, span * 2.5), 25e4);
2736
3484
  fog.set(span * 0.9, span * 1.8);
2737
3485
  } else {
2738
- const r = this.streamRadius();
2739
- this.controls.maxDistance = viewDistance * 2.2;
2740
- this.camera.far = Math.max(8e3, viewDistance * 6);
2741
- fog.set(r * 0.72, r * 1.05);
3486
+ const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
3487
+ const reach = Math.max(this.streamRadius(), this.tiles.mapMemoryExtent(focus.x, focus.z));
3488
+ this.controls.maxDistance = Math.min(Math.max(reach * 2.2, viewDistance * 2.2), 6e4);
3489
+ this.camera.far = Math.min(Math.max(8e3, reach * 6), 25e4);
3490
+ fog.set(reach * 0.72, reach * 1.05);
2742
3491
  }
2743
3492
  this.camera.updateProjectionMatrix();
2744
3493
  }
@@ -3099,7 +3848,8 @@ var VantageViewer = class _VantageViewer {
3099
3848
  viewDistance: this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768,
3100
3849
  maxTiles: this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120,
3101
3850
  concurrency: this.options.streaming.concurrency ?? 4,
3102
- maxBytes: this.tiles?.maxBytes ?? this.options.streaming.maxBytes ?? 512 * 1024 * 1024
3851
+ maxBytes: this.tiles?.maxBytes ?? this.options.streaming.maxBytes ?? 512 * 1024 * 1024,
3852
+ mapMemory: this.options.streaming.mapMemory ?? 64
3103
3853
  };
3104
3854
  }
3105
3855
  /** Live-tune streaming: view distance, resident tile/byte budgets, concurrency.
@@ -3285,9 +4035,47 @@ var VantageViewer = class _VantageViewer {
3285
4035
  invalidate() {
3286
4036
  this.needsRender = true;
3287
4037
  }
4038
+ /** Set the cave-geometry draw policy (see the option of the same name).
4039
+ * Takes effect on the next frame. */
4040
+ setCaveGeometry(mode) {
4041
+ this.caveMode = mode;
4042
+ this.invalidate();
4043
+ }
4044
+ /** The current cave-geometry draw policy. */
4045
+ get caveGeometry() {
4046
+ return this.caveMode;
4047
+ }
4048
+ /** Re-evaluate whether cave-dark tails belong in the draw ranges. Above
4049
+ * ground with the depth slice closed they are provably behind terrain from
4050
+ * the camera's side of the surface, so 'auto' trims every tile's draw range
4051
+ * to its surface prefix; opening the slice or descending underground brings
4052
+ * them straight back. The underground test rides the streamed surface maps
4053
+ * (the same data the terrain-following pivot uses) with a couple of blocks
4054
+ * of hysteresis so skimming the terrain doesn't flicker the ranges. */
4055
+ applyCavePolicy() {
4056
+ if (!this.tiles) return;
4057
+ let show = true;
4058
+ if (this.caveMode === "always" || this.sliceActive) {
4059
+ show = true;
4060
+ } else {
4061
+ const cam = this.camera.position;
4062
+ const ground = this.tiles.heightAt(cam.x, cam.z);
4063
+ const margin = this.cavesShown ? 2.5 : 0.5;
4064
+ show = ground !== null && cam.y < ground + margin;
4065
+ }
4066
+ if (show !== this.cavesShown) {
4067
+ this.cavesShown = show;
4068
+ if (this.tiles.setCaveGeometry(show)) this.needsRender = true;
4069
+ }
4070
+ }
3288
4071
  /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
3289
4072
  * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
3290
4073
  static ANIM_TICK_MS = 100;
4074
+ /** Manifest poll cadence (ms) while a render is streaming in. */
4075
+ static POLL_MS = 1200;
4076
+ /** Ceiling the poll cadence relaxes to while a continuous server reports no
4077
+ * changes — a saved world edit still shows up within ~one ceiling. */
4078
+ static POLL_MAX_MS = 5e3;
3291
4079
  frame() {
3292
4080
  const now = performance.now();
3293
4081
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
@@ -3323,6 +4111,7 @@ var VantageViewer = class _VantageViewer {
3323
4111
  }
3324
4112
  }
3325
4113
  }
4114
+ this.applyCavePolicy();
3326
4115
  this.pickHover();
3327
4116
  if (this.hasAnims && now - this.lastRenderMs >= _VantageViewer.ANIM_TICK_MS) this.needsRender = true;
3328
4117
  if (!this.options.renderOnDemand) this.needsRender = true;
@@ -3420,4 +4209,4 @@ var VantageViewer = class _VantageViewer {
3420
4209
  }
3421
4210
  };
3422
4211
 
3423
- export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome };
4212
+ export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, applyCaveRange, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome };