@thoughts-on-things/vantage-mc 0.7.0 → 0.9.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-QQJHRHBC.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,582 @@ var Emitter = class {
834
853
  this.listeners.clear();
835
854
  }
836
855
  };
856
+ var GRID = 24;
857
+ var SLOTS = 32;
858
+ var MAX_QUEUE = 256;
859
+ var CAPTURES_PER_FRAME = 4;
860
+ var SKIRT = 12;
861
+ var EDGES = [
862
+ [1, 0],
863
+ [-1, 0],
864
+ [0, 1],
865
+ [0, -1]
866
+ ];
867
+ function disposeCapture(meshes) {
868
+ for (const mesh of [meshes.terrain, meshes.terrainLm, meshes.water]) {
869
+ if (!mesh) continue;
870
+ mesh.removeFromParent();
871
+ if (isSharedQuadIndex(mesh.geometry.index)) mesh.geometry.setIndex(null);
872
+ mesh.geometry.dispose();
873
+ }
874
+ meshes.lightmapTex?.dispose();
875
+ }
876
+ var ImpostorLayer = class _ImpostorLayer {
877
+ renderer;
878
+ scene;
879
+ tileBlocks;
880
+ resolution;
881
+ rt;
882
+ material;
883
+ /** The shared terrain material — captures neutralize its grade/fog/clip
884
+ * uniforms for one render, and the impostor material re-applies the live
885
+ * values every frame, so display tuning keeps tracking remembered tiles. */
886
+ terrain;
887
+ /** Surface map of a still-resident hires tile, when the manager has one —
888
+ * lets a landing snapshot stitch its rim to the LIVE terrain it borders. */
889
+ liveSurface;
890
+ captureScene = new THREE2.Scene();
891
+ camera = new THREE2.OrthographicCamera();
892
+ queue = [];
893
+ byKey = /* @__PURE__ */ new Map();
894
+ freeSlots = [];
895
+ retired = false;
896
+ constructor(renderer, scene, terrainMaterial, tileBlocks, resolution, liveSurface = () => void 0) {
897
+ this.renderer = renderer;
898
+ this.scene = scene;
899
+ this.terrain = terrainMaterial;
900
+ this.tileBlocks = tileBlocks;
901
+ this.resolution = resolution;
902
+ this.liveSurface = liveSurface;
903
+ for (let i = SLOTS * SLOTS - 1; i >= 0; i--) this.freeSlots.push(i);
904
+ const size = SLOTS * resolution;
905
+ this.rt = new THREE2.WebGLRenderTarget(size, size, {
906
+ format: THREE2.RGBAFormat,
907
+ // Mipmaps keep far-zoom minification calm; regenerated by three after
908
+ // each capture render. The shader clamps its sampling LOD so slots
909
+ // never blend into each other (see uMaxLod).
910
+ generateMipmaps: true,
911
+ minFilter: THREE2.LinearMipmapLinearFilter,
912
+ magFilter: THREE2.LinearFilter,
913
+ depthBuffer: true
914
+ });
915
+ this.camera.up.set(0, 0, -1);
916
+ const t = terrainMaterial.uniforms;
917
+ this.material = new THREE2.ShaderMaterial({
918
+ glslVersion: THREE2.GLSL3,
919
+ uniforms: {
920
+ uMap: { value: this.rt.texture },
921
+ uAtlasPx: { value: SLOTS * resolution },
922
+ // Never sample past this mip: deeper levels average across atlas
923
+ // slots, which smears grazing-angle views into one murky colour.
924
+ uMaxLod: { value: Math.log2(resolution) - 2 },
925
+ // The guaranteed-hires radius; aerial haze never intrudes inside it.
926
+ uHazeMin: { value: 768 },
927
+ uFogColor: t["uFogColor"],
928
+ uFog: t["uFog"],
929
+ uFogCenter: t["uFogCenter"],
930
+ uFogRadial: t["uFogRadial"],
931
+ uFogDensity: t["uFogDensity"],
932
+ uExposure: t["uExposure"],
933
+ uSaturation: t["uSaturation"],
934
+ uContrast: t["uContrast"],
935
+ uClipY: t["uClipY"]
936
+ },
937
+ vertexShader: (
938
+ /* glsl */
939
+ `
940
+ uniform vec2 uFogCenter;
941
+ uniform float uFogRadial;
942
+ out vec2 vUv;
943
+ out float vFog;
944
+ out vec3 vWorld;
945
+ void main() {
946
+ vUv = uv;
947
+ vec4 wp = modelMatrix * vec4(position, 1.0);
948
+ vWorld = wp.xyz;
949
+ vec4 mv = viewMatrix * wp;
950
+ vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
951
+ gl_Position = projectionMatrix * mv;
952
+ }
953
+ `
954
+ ),
955
+ fragmentShader: (
956
+ /* glsl */
957
+ `
958
+ precision highp float;
959
+ uniform sampler2D uMap;
960
+ uniform float uAtlasPx;
961
+ uniform float uMaxLod;
962
+ uniform float uHazeMin;
963
+ uniform vec3 uFogColor;
964
+ uniform vec2 uFog;
965
+ uniform float uFogDensity;
966
+ uniform float uExposure;
967
+ uniform float uSaturation;
968
+ uniform float uContrast;
969
+ uniform float uClipY;
970
+ in vec2 vUv;
971
+ in float vFog;
972
+ in vec3 vWorld;
973
+ out vec4 frag;
974
+ vec3 toLinear(vec3 c) {
975
+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
976
+ }
977
+ vec3 toSRGB(vec3 c) {
978
+ c = max(c, vec3(0.0));
979
+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
980
+ }
981
+ void main() {
982
+ if (vWorld.y > uClipY) discard;
983
+ // Explicit LOD, clamped: grazing views drive the derivative-based
984
+ // mip selection deep enough to blend unrelated atlas slots (the
985
+ // "distant blue wall" smear). Capped, a slot only ever mixes with
986
+ // itself.
987
+ vec2 px = vUv * uAtlasPx;
988
+ vec2 ddx = dFdx(px);
989
+ vec2 ddy = dFdy(px);
990
+ float lod = 0.5 * log2(max(dot(ddx, ddx), max(dot(ddy, ddy), 1.0)));
991
+ vec4 t = textureLod(uMap, vUv, min(lod, uMaxLod));
992
+ if (t.a < 0.5) discard; // void columns captured as transparent
993
+ // Snapshots are captured with a NEUTRAL grade, so the live display
994
+ // settings apply here exactly like they do to hires terrain.
995
+ vec3 c = toLinear(t.rgb) * uExposure;
996
+ float l = dot(c, vec3(0.299, 0.587, 0.114));
997
+ c = mix(vec3(l), c, uSaturation);
998
+ c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
999
+ // Aerial perspective for remembered terrain: a top-down snapshot
1000
+ // can't hold up viewed edge-on, so haze it by HORIZONTAL distance
1001
+ // from the eye, scaled by how high the eye sits \u2014 top-down map
1002
+ // views stay crystal clear, while a ground-level camera sees
1003
+ // remembered mountains fade into the horizon like real draw
1004
+ // distance instead of standing raw against the sky.
1005
+ float camXZ = distance(vWorld.xz, cameraPosition.xz);
1006
+ float above = max(cameraPosition.y - vWorld.y, 0.0);
1007
+ float hazeNear = max(uHazeMin, above * 2.0);
1008
+ // A tight ramp: from a tilted camera the remembered band should
1009
+ // read as distance haze soon after the hires frontier, not stand
1010
+ // vivid for another whole frontier-width beyond it.
1011
+ float haze = smoothstep(hazeNear, hazeNear * 1.8, camXZ);
1012
+ float f = clamp(max(smoothstep(uFog.x, uFog.y, vFog), haze) * uFogDensity, 0.0, 1.0);
1013
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
1014
+ }
1015
+ `
1016
+ ),
1017
+ alphaToCoverage: true,
1018
+ // Skirt quads hang off each tile's rim; double-sided keeps them visible
1019
+ // from every orbit angle without winding gymnastics.
1020
+ side: THREE2.DoubleSide,
1021
+ // Impostors sit at TRUE surface height. Where hires geometry coexists
1022
+ // (the stream-in fade, the ring boundary) the depth offset pushes the
1023
+ // impostor behind it — the decal trick — so there is no geometric dip
1024
+ // and therefore no sunken step around the live disc.
1025
+ polygonOffset: true,
1026
+ polygonOffsetFactor: 2,
1027
+ polygonOffsetUnits: 4
1028
+ });
1029
+ }
1030
+ /** Remembered-tile count (for stats readouts). */
1031
+ get count() {
1032
+ return this.byKey.size;
1033
+ }
1034
+ /** Snapshot resolution in pixels per tile. */
1035
+ get resolutionPx() {
1036
+ return this.resolution;
1037
+ }
1038
+ /** The radius hires tiles are guaranteed resident to — the impostor shader
1039
+ * keeps its grazing-angle aerial haze outside this ring. */
1040
+ setHazeFloor(radius) {
1041
+ this.material.uniforms["uHazeMin"].value = Math.max(radius, 1);
1042
+ }
1043
+ /** How far remembered terrain reaches from (x,z), in blocks — the radius the
1044
+ * viewer's zoom range and fog frontier should keep visible. 0 = nothing
1045
+ * remembered. */
1046
+ extentFrom(x, z) {
1047
+ let extent = 0;
1048
+ for (const imp of this.byKey.values()) {
1049
+ const d = Math.hypot(imp.cx - x, imp.cz - z);
1050
+ if (d > extent) extent = d;
1051
+ }
1052
+ return extent === 0 ? 0 : extent + this.tileBlocks;
1053
+ }
1054
+ /** Fixed GPU cost of the atlas (RGBA + mip chain), plus the small meshes. */
1055
+ get gpuBytes() {
1056
+ const size = SLOTS * this.resolution;
1057
+ return Math.round(size * size * 4 * 1.34) + this.byKey.size * 8192;
1058
+ }
1059
+ /** Whether a tile is remembered — or about to be (its capture is queued).
1060
+ * The manager uses this as its "underlay exists" test when deciding
1061
+ * whether a streaming-in tile has anything to dissolve over. */
1062
+ has(key) {
1063
+ if (this.byKey.has(key)) return true;
1064
+ for (const p of this.queue) if (p.key === key) return true;
1065
+ return false;
1066
+ }
1067
+ /** Queue an evicted tile's meshes for snapshotting. Takes OWNERSHIP of the
1068
+ * meshes — including their SCENE membership: the caller leaves them in the
1069
+ * scene, and they keep drawing (real terrain, live uniforms) until the
1070
+ * snapshot render reparents them away in the same tick their impostor
1071
+ * appears. That closed-form swap is what keeps a pan's eviction wake free
1072
+ * of background-colored holes. A full queue drops its oldest entry (its
1073
+ * meshes are removed and disposed). */
1074
+ capture(tileX, tileZ, meshes, surface, minY, maxY) {
1075
+ if (this.retired) {
1076
+ disposeCapture(meshes);
1077
+ return;
1078
+ }
1079
+ const key = tileKey(tileX, tileZ);
1080
+ const queued = this.queue.findIndex((p) => p.key === key);
1081
+ if (queued >= 0) disposeCapture(this.queue.splice(queued, 1)[0].meshes);
1082
+ this.queue.push({ key, tileX, tileZ, meshes, surface, minY, maxY });
1083
+ if (this.queue.length > MAX_QUEUE) disposeCapture(this.queue.shift().meshes);
1084
+ }
1085
+ /** Forget a tile (it was removed from the manifest). */
1086
+ remove(key) {
1087
+ const queued = this.queue.findIndex((p) => p.key === key);
1088
+ if (queued >= 0) disposeCapture(this.queue.splice(queued, 1)[0].meshes);
1089
+ const imp = this.byKey.get(key);
1090
+ if (imp) this.releaseImpostor(imp);
1091
+ }
1092
+ /** Drain a few pending captures (bounded per frame so a ring of evictions
1093
+ * never stacks its snapshot renders into one frame). Returns whether the
1094
+ * scene changed (the caller redraws + re-runs coverage). */
1095
+ update(focusX, focusZ) {
1096
+ if (this.queue.length === 0) return false;
1097
+ const batch = this.queue.splice(0, CAPTURES_PER_FRAME);
1098
+ for (const p of batch) {
1099
+ this.snapshot(p, focusX, focusZ);
1100
+ disposeCapture(p.meshes);
1101
+ }
1102
+ return true;
1103
+ }
1104
+ /** Hide impostors whose hires tile is resident and fully faded in. */
1105
+ applyCoverage(shownHires) {
1106
+ for (const imp of this.byKey.values()) imp.mesh.visible = !shownHires.has(imp.key);
1107
+ }
1108
+ /** A hires tile just entered the scene: snap the facing rims of any
1109
+ * impostor neighbours onto its REAL surface heights, so the boundary
1110
+ * between the live disc and remembered terrain meets instead of stepping. */
1111
+ onHiresReady(tileX, tileZ, surface) {
1112
+ if (!surface || this.byKey.size === 0) return;
1113
+ for (const [dx, dz] of EDGES) {
1114
+ const imp = this.byKey.get(tileKey(tileX + dx, tileZ + dz));
1115
+ if (!imp) continue;
1116
+ if (this.stitchEdgeToSurface(imp, -dx, -dz, surface)) this.rebuild(imp);
1117
+ }
1118
+ }
1119
+ /** Remembered surface height under world (x,z), for the pivot fallback. */
1120
+ heightAt(x, z) {
1121
+ const tb = this.tileBlocks;
1122
+ const imp = this.byKey.get(tileKey(Math.floor(x / tb), Math.floor(z / tb)));
1123
+ if (!imp) return null;
1124
+ const step = tb / GRID;
1125
+ const i = Math.min(Math.max(Math.round((x - imp.originX) / step), 0), GRID);
1126
+ const j = Math.min(Math.max(Math.round((z - imp.originZ) / step), 0), GRID);
1127
+ const h = imp.heights[j * (GRID + 1) + i];
1128
+ return h < 1 ? null : h;
1129
+ }
1130
+ /** Drop every impostor and stop accepting captures — called when a lowres
1131
+ * pyramid arrives (a finished progressive bake): the baked rings cover the
1132
+ * whole world and supersede anything remembered. */
1133
+ retire() {
1134
+ this.retired = true;
1135
+ for (const p of this.queue.splice(0)) disposeCapture(p.meshes);
1136
+ for (const imp of [...this.byKey.values()]) this.releaseImpostor(imp);
1137
+ }
1138
+ dispose() {
1139
+ this.retire();
1140
+ this.rt.dispose();
1141
+ this.material.dispose();
1142
+ }
1143
+ releaseImpostor(imp) {
1144
+ this.scene.remove(imp.mesh);
1145
+ imp.mesh.geometry.dispose();
1146
+ this.byKey.delete(imp.key);
1147
+ this.freeSlots.push(imp.slot);
1148
+ }
1149
+ /** A free atlas slot, reusing the remembered tile farthest from the focus
1150
+ * when the atlas is full — the same nearest-wins policy streaming uses. */
1151
+ allocSlot(focusX, focusZ) {
1152
+ const free = this.freeSlots.pop();
1153
+ if (free !== void 0) return free;
1154
+ let victim = null;
1155
+ let worst = -1;
1156
+ for (const imp of this.byKey.values()) {
1157
+ const dx = imp.cx - focusX;
1158
+ const dz = imp.cz - focusZ;
1159
+ const d = dx * dx + dz * dz;
1160
+ if (d > worst) {
1161
+ worst = d;
1162
+ victim = imp;
1163
+ }
1164
+ }
1165
+ this.releaseImpostor(victim);
1166
+ return this.freeSlots.pop();
1167
+ }
1168
+ /** Windowed mean of a surface map's heights around world (wx, wz), clamped
1169
+ * into the map. Surface heights track the TOPMOST block (canopy, water
1170
+ * surface), so point samples spike whole cells wherever a tree stands —
1171
+ * the neighbourhood mean keeps impostors at believable height. Returns 0
1172
+ * (the empty sentinel) when no populated column falls in the window. */
1173
+ static meanAt(surf, wx, wz) {
1174
+ const bx = Math.round(wx) - surf.originX;
1175
+ const bz = Math.round(wz) - surf.originZ;
1176
+ let sum = 0;
1177
+ let count = 0;
1178
+ for (let dz = -4; dz <= 4; dz += 2) {
1179
+ for (let dx = -4; dx <= 4; dx += 2) {
1180
+ const cx = Math.min(Math.max(bx + dx, 0), surf.width - 1);
1181
+ const cz = Math.min(Math.max(bz + dz, 0), surf.depth - 1);
1182
+ const h = surf.height[cz * surf.width + cx];
1183
+ if (h < 1) continue;
1184
+ sum += h;
1185
+ count++;
1186
+ }
1187
+ }
1188
+ return count === 0 ? 0 : Math.round(sum / count);
1189
+ }
1190
+ /** Index of the k-th vertex (0..GRID) along an impostor's edge toward
1191
+ * (dx,dz), into its (GRID+1)² height/vertex grid. */
1192
+ static edgeIndex(dx, dz, k) {
1193
+ const n = GRID + 1;
1194
+ if (dx === 1) return k * n + GRID;
1195
+ if (dx === -1) return k * n;
1196
+ if (dz === 1) return GRID * n + k;
1197
+ return k;
1198
+ }
1199
+ /** Stitch one edge of `imp` to a live hires neighbour's surface map: each
1200
+ * rim vertex adopts the neighbour-side windowed mean at the shared world
1201
+ * position (real terrain doesn't move to meet a snapshot). Returns whether
1202
+ * anything changed. */
1203
+ stitchEdgeToSurface(imp, dx, dz, surface) {
1204
+ const tb = this.tileBlocks;
1205
+ const step = tb / GRID;
1206
+ let changed = false;
1207
+ for (let k = 0; k <= GRID; k++) {
1208
+ const idx = _ImpostorLayer.edgeIndex(dx, dz, k);
1209
+ if (imp.heights[idx] < 1) continue;
1210
+ const wx = dx === 1 ? imp.originX + tb : dx === -1 ? imp.originX : imp.originX + k * step;
1211
+ const wz = dz === 1 ? imp.originZ + tb : dz === -1 ? imp.originZ : imp.originZ + k * step;
1212
+ const h = _ImpostorLayer.meanAt(surface, wx, wz);
1213
+ if (h < 1 || h === imp.heights[idx]) continue;
1214
+ imp.heights[idx] = h;
1215
+ changed = true;
1216
+ }
1217
+ return changed;
1218
+ }
1219
+ /** Stitch every edge of a freshly-landed impostor: impostor neighbours meet
1220
+ * in the middle (both rims set to the average — the exact same values, so
1221
+ * the seam closes), live hires neighbours are adopted verbatim. Returns
1222
+ * the neighbours whose geometry must be rebuilt. */
1223
+ stitchAll(imp) {
1224
+ const dirty = [];
1225
+ for (const [dx, dz] of EDGES) {
1226
+ const nKey = tileKey(imp.tileX + dx, imp.tileZ + dz);
1227
+ const neighbour = this.byKey.get(nKey);
1228
+ if (neighbour) {
1229
+ let changed = false;
1230
+ for (let k = 0; k <= GRID; k++) {
1231
+ const a = _ImpostorLayer.edgeIndex(dx, dz, k);
1232
+ const b = _ImpostorLayer.edgeIndex(-dx, -dz, k);
1233
+ const ha = imp.heights[a];
1234
+ const hb = neighbour.heights[b];
1235
+ if (ha < 1 || hb < 1 || ha === hb) continue;
1236
+ const avg = Math.round((ha + hb) / 2);
1237
+ imp.heights[a] = avg;
1238
+ if (neighbour.heights[b] !== avg) {
1239
+ neighbour.heights[b] = avg;
1240
+ changed = true;
1241
+ }
1242
+ }
1243
+ if (changed) dirty.push(neighbour);
1244
+ continue;
1245
+ }
1246
+ const live = this.liveSurface(nKey);
1247
+ if (live) this.stitchEdgeToSurface(imp, dx, dz, live);
1248
+ }
1249
+ return dirty;
1250
+ }
1251
+ /** Build (or rebuild) an impostor's heightfield geometry from its stored
1252
+ * heights + atlas slot: true-height grid, atlas UVs inset half a texel
1253
+ * against slot bleed, rim skirts. Returns null for a mesh with no
1254
+ * drawable cell. */
1255
+ buildGeometry(imp) {
1256
+ const tb = this.tileBlocks;
1257
+ const res = this.resolution;
1258
+ const n = GRID + 1;
1259
+ const { heights, originX, originZ, slot } = imp;
1260
+ const sx = slot % SLOTS * res;
1261
+ const sy = Math.floor(slot / SLOTS) * res;
1262
+ const pos = [];
1263
+ const uv = [];
1264
+ const atlasPx = SLOTS * res;
1265
+ const u0 = (sx + 0.5) / atlasPx;
1266
+ const v0 = (sy + 0.5) / atlasPx;
1267
+ const span = (res - 1) / atlasPx;
1268
+ let minH = Infinity;
1269
+ let maxH = -Infinity;
1270
+ for (let j = 0; j < n; j++) {
1271
+ for (let i = 0; i < n; i++) {
1272
+ const h = heights[j * n + i];
1273
+ pos.push(originX + i * tb / GRID, h < 1 ? 0 : h, originZ + j * tb / GRID);
1274
+ if (h >= 1) {
1275
+ if (h < minH) minH = h;
1276
+ if (h > maxH) maxH = h;
1277
+ }
1278
+ uv.push(u0 + i / GRID * span, v0 + (1 - j / GRID) * span);
1279
+ }
1280
+ }
1281
+ if (!Number.isFinite(minH)) return null;
1282
+ const idx = [];
1283
+ for (let j = 0; j < GRID; j++) {
1284
+ for (let i = 0; i < GRID; i++) {
1285
+ const a = j * n + i;
1286
+ const b = a + 1;
1287
+ const c = a + n;
1288
+ const d = c + 1;
1289
+ if (heights[a] < 1 || heights[b] < 1 || heights[c] < 1 || heights[d] < 1) continue;
1290
+ idx.push(a, c, d, a, d, b);
1291
+ }
1292
+ }
1293
+ if (idx.length === 0) return null;
1294
+ const addSkirt = (a, b) => {
1295
+ if (heights[a] < 1 || heights[b] < 1) return;
1296
+ const base = pos.length / 3;
1297
+ for (const s of [a, b]) {
1298
+ pos.push(pos[s * 3], pos[s * 3 + 1] - SKIRT, pos[s * 3 + 2]);
1299
+ uv.push(uv[s * 2], uv[s * 2 + 1]);
1300
+ }
1301
+ idx.push(a, b, base + 1, a, base + 1, base);
1302
+ };
1303
+ for (let k = 0; k < GRID; k++) {
1304
+ addSkirt(k, k + 1);
1305
+ addSkirt(GRID * n + k, GRID * n + k + 1);
1306
+ addSkirt(k * n, (k + 1) * n);
1307
+ addSkirt(k * n + GRID, (k + 1) * n + GRID);
1308
+ }
1309
+ const geom = new THREE2.BufferGeometry();
1310
+ geom.setAttribute("position", new THREE2.BufferAttribute(new Float32Array(pos), 3));
1311
+ geom.setAttribute("uv", new THREE2.BufferAttribute(new Float32Array(uv), 2));
1312
+ geom.setIndex(idx);
1313
+ const box = new THREE2.Box3(new THREE2.Vector3(originX, minH - SKIRT, originZ), new THREE2.Vector3(originX + tb, maxH, originZ + tb));
1314
+ geom.boundingBox = box;
1315
+ const sphere = new THREE2.Sphere();
1316
+ box.getBoundingSphere(sphere);
1317
+ geom.boundingSphere = sphere;
1318
+ return geom;
1319
+ }
1320
+ /** Swap in freshly-built geometry after a stitch adjusted stored heights. */
1321
+ rebuild(imp) {
1322
+ const geom = this.buildGeometry(imp);
1323
+ if (!geom) return;
1324
+ imp.mesh.geometry.dispose();
1325
+ imp.mesh.geometry = geom;
1326
+ }
1327
+ /** Render the tile's meshes top-down into its atlas slot and swap in the
1328
+ * stitched heightfield impostor. */
1329
+ snapshot(p, focusX, focusZ) {
1330
+ const meshes = [p.meshes.terrain, p.meshes.terrainLm, p.meshes.water].filter(Boolean);
1331
+ if (meshes.length === 0) return;
1332
+ const tb = this.tileBlocks;
1333
+ const originX = p.tileX * tb;
1334
+ const originZ = p.tileZ * tb;
1335
+ const n = GRID + 1;
1336
+ const heights = new Int16Array(n * n);
1337
+ for (let j = 0; j < n; j++) {
1338
+ for (let i = 0; i < n; i++) {
1339
+ heights[j * n + i] = _ImpostorLayer.meanAt(p.surface, originX + i * tb / GRID, originZ + j * tb / GRID);
1340
+ }
1341
+ }
1342
+ let drawable = false;
1343
+ outer: for (let j = 0; j < GRID; j++) {
1344
+ for (let i = 0; i < GRID; i++) {
1345
+ const a = j * n + i;
1346
+ if (heights[a] >= 1 && heights[a + 1] >= 1 && heights[a + n] >= 1 && heights[a + n + 1] >= 1) {
1347
+ drawable = true;
1348
+ break outer;
1349
+ }
1350
+ }
1351
+ }
1352
+ if (!drawable) return;
1353
+ const existing = this.byKey.get(p.key);
1354
+ if (existing) this.releaseImpostor(existing);
1355
+ const slot = this.allocSlot(focusX, focusZ);
1356
+ const res = this.resolution;
1357
+ const sx = slot % SLOTS * res;
1358
+ const sy = Math.floor(slot / SLOTS) * res;
1359
+ const u = this.terrain.uniforms;
1360
+ const saved = /* @__PURE__ */ new Map();
1361
+ const neutral = [
1362
+ ["uFogDensity", 0],
1363
+ ["uBiomeMix", 0],
1364
+ ["uHi", -1],
1365
+ ["uClipY", 1e9],
1366
+ ["uExposure", 1],
1367
+ ["uSaturation", 1],
1368
+ ["uContrast", 1]
1369
+ ];
1370
+ for (const [k, v] of neutral) {
1371
+ if (!u[k]) continue;
1372
+ saved.set(k, u[k].value);
1373
+ u[k].value = v;
1374
+ }
1375
+ for (const mesh of meshes) this.captureScene.add(mesh);
1376
+ const cam = this.camera;
1377
+ cam.left = originX;
1378
+ cam.right = originX + tb;
1379
+ cam.top = -originZ;
1380
+ cam.bottom = -(originZ + tb);
1381
+ cam.near = 1;
1382
+ cam.far = p.maxY - p.minY + 32;
1383
+ cam.position.set(0, p.maxY + 16, 0);
1384
+ cam.lookAt(0, 0, 0);
1385
+ cam.updateProjectionMatrix();
1386
+ for (const mesh of meshes) mesh.frustumCulled = false;
1387
+ const renderer = this.renderer;
1388
+ const prevTarget = renderer.getRenderTarget();
1389
+ const prevAutoClear = renderer.autoClear;
1390
+ const prevColor = renderer.getClearColor(new THREE2.Color());
1391
+ const prevAlpha = renderer.getClearAlpha();
1392
+ this.rt.viewport.set(sx, sy, res, res);
1393
+ this.rt.scissor.set(sx, sy, res, res);
1394
+ this.rt.scissorTest = true;
1395
+ renderer.setRenderTarget(this.rt);
1396
+ renderer.setClearColor(0, 0);
1397
+ renderer.autoClear = false;
1398
+ renderer.clear(true, true);
1399
+ renderer.render(this.captureScene, cam);
1400
+ renderer.setRenderTarget(prevTarget);
1401
+ renderer.setClearColor(prevColor, prevAlpha);
1402
+ renderer.autoClear = prevAutoClear;
1403
+ for (const [k, v] of saved) u[k].value = v;
1404
+ this.terrain.uniformsNeedUpdate = true;
1405
+ const imp = {
1406
+ key: p.key,
1407
+ tileX: p.tileX,
1408
+ tileZ: p.tileZ,
1409
+ slot,
1410
+ mesh: new THREE2.Mesh(void 0, this.material),
1411
+ heights,
1412
+ originX,
1413
+ originZ,
1414
+ cx: originX + tb / 2,
1415
+ cz: originZ + tb / 2
1416
+ };
1417
+ this.byKey.set(p.key, imp);
1418
+ const dirty = this.stitchAll(imp);
1419
+ const geom = this.buildGeometry(imp);
1420
+ if (!geom) {
1421
+ this.byKey.delete(p.key);
1422
+ this.freeSlots.push(slot);
1423
+ return;
1424
+ }
1425
+ imp.mesh.geometry.dispose();
1426
+ imp.mesh.geometry = geom;
1427
+ imp.mesh.renderOrder = -1;
1428
+ this.scene.add(imp.mesh);
1429
+ for (const neighbour of dirty) this.rebuild(neighbour);
1430
+ }
1431
+ };
837
1432
 
838
1433
  // src/three/streaming.ts
839
1434
  function nearbyTiles(index, tileBlocks, focusX, focusZ, radius, predictedX = focusX, predictedZ = focusZ) {
@@ -866,15 +1461,92 @@ function admitTiles(candidates, maxTiles, maxBytes, estimateBytes) {
866
1461
  const admitted = [];
867
1462
  let bytes = 0;
868
1463
  for (const candidate of candidates) {
869
- if (admitted.length >= maxTiles) break;
1464
+ if (admitted.length >= maxTiles) return { admitted, cutoffSq: candidate.distanceSq };
870
1465
  const weight = Math.max(1, estimateBytes(candidate.ref));
871
- if (admitted.length > 0 && bytes + weight > maxBytes) continue;
1466
+ if (admitted.length > 0 && bytes + weight > maxBytes) {
1467
+ return { admitted, cutoffSq: candidate.distanceSq };
1468
+ }
872
1469
  admitted.push(candidate);
873
1470
  bytes += weight;
874
1471
  }
875
- return admitted;
1472
+ return { admitted, cutoffSq: null };
876
1473
  }
877
1474
 
1475
+ // src/three/tilecache.ts
1476
+ var TileByteCache = class _TileByteCache {
1477
+ /** Cap on retained entries, independent of their bytes. */
1478
+ static MAX_ENTRIES = 4096;
1479
+ /** Insertion-ordered, and every hit re-inserts — so the front of the map is
1480
+ * always the least recently used entry. */
1481
+ entries = /* @__PURE__ */ new Map();
1482
+ bytes = 0;
1483
+ budget;
1484
+ constructor(budget) {
1485
+ this.budget = budget;
1486
+ }
1487
+ /** Retained payload bytes. */
1488
+ get size() {
1489
+ return this.bytes;
1490
+ }
1491
+ /** Retained entry count. */
1492
+ get count() {
1493
+ return this.entries.size;
1494
+ }
1495
+ /** Resize the byte budget, evicting immediately to fit it. `0` (or less)
1496
+ * disables the cache and drops everything: the setting is a memory
1497
+ * ceiling, so lowering it must take effect now rather than whenever the
1498
+ * next insertion happens to evict. */
1499
+ setBudget(budget) {
1500
+ this.budget = budget;
1501
+ if (budget <= 0) {
1502
+ this.clear();
1503
+ return;
1504
+ }
1505
+ this.trim();
1506
+ }
1507
+ /** The payload for `key` if it was cached at exactly `revision` (a revised
1508
+ * tile is different terrain, not a stale copy of the same). A hit counts
1509
+ * as a use and moves to the back of the LRU. */
1510
+ get(key, revision) {
1511
+ const hit = this.entries.get(key);
1512
+ if (!hit || hit.revision !== revision) return void 0;
1513
+ this.entries.delete(key);
1514
+ this.entries.set(key, hit);
1515
+ return hit.buffer;
1516
+ }
1517
+ /** Retain a payload, evicting least-recently-used entries to fit. Ignores
1518
+ * payloads larger than the whole budget, and empty ones: a tile that
1519
+ * meshes to nothing re-fetches as a 0-byte body without ever reaching a
1520
+ * bake, so caching it would only accumulate entries the byte budget can
1521
+ * never evict. */
1522
+ put(key, buffer, revision) {
1523
+ if (this.budget <= 0 || buffer.byteLength === 0 || buffer.byteLength > this.budget) return;
1524
+ this.drop(key);
1525
+ this.entries.set(key, { buffer, revision });
1526
+ this.bytes += buffer.byteLength;
1527
+ this.trim();
1528
+ }
1529
+ /** Forget one tile (its revision changed, it left the manifest, or its
1530
+ * bytes failed to parse and must not be served from here again). */
1531
+ drop(key) {
1532
+ const prev = this.entries.get(key);
1533
+ if (!prev) return;
1534
+ this.entries.delete(key);
1535
+ this.bytes -= prev.buffer.byteLength;
1536
+ }
1537
+ clear() {
1538
+ this.entries.clear();
1539
+ this.bytes = 0;
1540
+ }
1541
+ trim() {
1542
+ for (const [key, entry] of this.entries) {
1543
+ if (this.bytes <= this.budget && this.entries.size <= _TileByteCache.MAX_ENTRIES) break;
1544
+ this.entries.delete(key);
1545
+ this.bytes -= entry.buffer.byteLength;
1546
+ }
1547
+ }
1548
+ };
1549
+
878
1550
  // src/three/tiles.ts
879
1551
  function recKey(level, x, z) {
880
1552
  return level === 0 ? tileKey(x, z) : `l${level}:${x},${z}`;
@@ -908,6 +1580,11 @@ var TileManager = class _TileManager {
908
1580
  opts;
909
1581
  lowresMaterial;
910
1582
  lmMaterial;
1583
+ /** Map memory (impostor snapshots of evicted tiles); null when the world
1584
+ * ships a lowres pyramid, when disabled, or without a renderer. */
1585
+ impostors = null;
1586
+ /** Kept for live map-memory reconfiguration (resolution changes). */
1587
+ renderer;
911
1588
  /** Widens the shared atlas to cover a tile's layers before it's drawn (live
912
1589
  * renders only); null when the atlas is complete. */
913
1590
  ensureAtlas;
@@ -944,6 +1621,19 @@ var TileManager = class _TileManager {
944
1621
  /** Learned tile weights survive eviction and make future admission byte-aware. */
945
1622
  sizeHints = /* @__PURE__ */ new Map();
946
1623
  averageHiresBytes = 12 * 1024 * 1024;
1624
+ /** Distance² where the last plan ran out of budget (null = nothing cut).
1625
+ * Derives {@link admittedRadius} — the honest hires frontier. */
1626
+ planCutoffSq = null;
1627
+ /** When the last plan ran, so byte-estimate learning re-plans at a bounded
1628
+ * rate instead of once per tile load. */
1629
+ lastPlanMs = 0;
1630
+ /** Compressed tile payloads kept after eviction. A revisit rebuilds from
1631
+ * here — no network fetch, no server re-bake. */
1632
+ byteCache;
1633
+ /** Whether resident tiles draw their cave-dark tails (VTLA). The viewer's
1634
+ * cave policy toggles this off while the camera is above ground with the
1635
+ * depth slice closed. */
1636
+ caveGeometry = true;
947
1637
  focusX = 0;
948
1638
  focusZ = 0;
949
1639
  biomesCache = null;
@@ -952,17 +1642,19 @@ var TileManager = class _TileManager {
952
1642
  minY = 0;
953
1643
  maxY = 320;
954
1644
  constructor(options) {
955
- const { lowresMaterial, lmMaterial, ensureAtlas, ...rest } = options;
1645
+ const { lowresMaterial, lmMaterial, ensureAtlas, renderer, mapMemory, ...rest } = options;
956
1646
  this.opts = {
957
1647
  viewDistance: 768,
958
1648
  // Sized to fill the whole view-distance disc for 128-block tiles
959
1649
  // (π·(768/128)² ≈ 113) with a little slack — and to match the settings
960
1650
  // panel's "med" preset exactly.
961
1651
  maxTiles: 120,
962
- concurrency: 4,
1652
+ concurrency: 6,
963
1653
  maxBytes: 512 * 1024 * 1024,
1654
+ tileCacheBytes: 192 * 1024 * 1024,
964
1655
  ...rest
965
1656
  };
1657
+ this.byteCache = new TileByteCache(this.opts.tileCacheBytes);
966
1658
  this.lowresMaterial = lowresMaterial ?? null;
967
1659
  this.lmMaterial = lmMaterial ?? null;
968
1660
  this.ensureAtlas = ensureAtlas ?? null;
@@ -974,6 +1666,31 @@ var TileManager = class _TileManager {
974
1666
  for (const lvl of this.lowLevels) {
975
1667
  this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
976
1668
  }
1669
+ this.renderer = renderer ?? null;
1670
+ const res = mapMemory ?? 64;
1671
+ if (renderer && res > 0 && !options.manifest.lowres) {
1672
+ this.impostors = new ImpostorLayer(renderer, options.scene, options.material, this.tileBlocks, res, this.readySurface);
1673
+ this.applyHazeFloor();
1674
+ }
1675
+ }
1676
+ /** Surface map of a fully-streamed resident hires tile (the impostor layer
1677
+ * stitches remembered rims onto live terrain with it). */
1678
+ readySurface = (key) => {
1679
+ const rec = this.records.get(key);
1680
+ return rec?.level === 0 && rec.state === "ready" ? rec.surface : void 0;
1681
+ };
1682
+ /** The radius hires tiles are actually resident to: the view distance,
1683
+ * capped by whichever budget ran out first — the tile-count disc, or the
1684
+ * byte budget's cut in the last admission plan. The viewer sizes fog and
1685
+ * zoom off this so the frontier always reads as haze, never a cliff. */
1686
+ get admittedRadius() {
1687
+ const countRadius = this.tileBlocks * Math.sqrt(this.opts.maxTiles / Math.PI);
1688
+ const planRadius = this.planCutoffSq === null ? Infinity : Math.sqrt(this.planCutoffSq);
1689
+ return Math.min(this.opts.viewDistance, countRadius, planRadius);
1690
+ }
1691
+ /** Keep the impostor haze floor tracking the guaranteed-hires radius. */
1692
+ applyHazeFloor() {
1693
+ this.impostors?.setHazeFloor(this.admittedRadius);
977
1694
  }
978
1695
  /** Tile span in blocks at a pyramid level (0 = hires). */
979
1696
  levelBlocks(level) {
@@ -1001,6 +1718,11 @@ var TileManager = class _TileManager {
1001
1718
  this.focusZ = focusZ;
1002
1719
  this.flushOne();
1003
1720
  this.retrySweep();
1721
+ if (this.impostors?.update(focusX, focusZ)) {
1722
+ this.coverageDirty = true;
1723
+ this.invalidate();
1724
+ this.emitter.emit("change", this.stats);
1725
+ }
1004
1726
  if (this.fadingKeys.size > 0) {
1005
1727
  const now = performance.now();
1006
1728
  for (const key of this.fadingKeys) {
@@ -1029,15 +1751,19 @@ var TileManager = class _TileManager {
1029
1751
  this.lastFocusX = focusX;
1030
1752
  this.lastFocusZ = focusZ;
1031
1753
  const { viewDistance, maxTiles, maxBytes } = this.opts;
1032
- let lowBytes = 0;
1754
+ let lowBytes = this.impostors?.gpuBytes ?? 0;
1033
1755
  for (const rec of this.records.values()) if (rec.level > 0) lowBytes += rec.memoryBytes;
1034
1756
  const hiresBytes = Math.max(1, maxBytes - lowBytes);
1035
- const desired = admitTiles(
1757
+ const plan = admitTiles(
1036
1758
  nearbyTiles(this.index, this.tileBlocks, focusX, focusZ, viewDistance, predictedX, predictedZ),
1037
1759
  maxTiles,
1038
1760
  hiresBytes,
1039
1761
  (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 }));
1762
+ );
1763
+ this.planCutoffSq = plan.cutoffSq;
1764
+ this.lastPlanMs = performance.now();
1765
+ this.applyHazeFloor();
1766
+ const desired = plan.admitted.map((candidate) => ({ t: candidate.ref, d: candidate.distanceSq }));
1041
1767
  const desiredKeys = new Set(desired.map(({ t }) => recKey(0, t.x, t.z)));
1042
1768
  const lowDesired = [];
1043
1769
  for (let i = 0; i < this.lowLevels.length; i++) {
@@ -1058,6 +1784,10 @@ var TileManager = class _TileManager {
1058
1784
  for (const [key, rec] of this.records) {
1059
1785
  if (desiredKeys.has(key)) continue;
1060
1786
  if (rec.level === 0) {
1787
+ if (rec.state === "ready") {
1788
+ const keep2 = this.admittedRadius * 1.15 + this.tileBlocks * 0.5;
1789
+ if (this.distSqTo(rec.ref, 0, focusX, focusZ) <= keep2 * keep2) continue;
1790
+ }
1061
1791
  this.unload(key, rec);
1062
1792
  continue;
1063
1793
  }
@@ -1077,13 +1807,25 @@ var TileManager = class _TileManager {
1077
1807
  this.pump();
1078
1808
  }
1079
1809
  pump() {
1080
- while (this.inFlight < this.opts.concurrency && this.inFlight + this.pendingBuilt < this.opts.concurrency && this.queue.length > 0) {
1810
+ const maxPendingBuilt = Math.max(8, this.opts.concurrency * 2);
1811
+ while (this.inFlight < this.opts.concurrency && this.pendingBuilt < maxPendingBuilt && this.queue.length > 0) {
1081
1812
  const { ref, level } = this.queue.pop();
1082
1813
  if (level === 0 && this.index.get(tileKey(ref.x, ref.z)) !== ref) continue;
1083
1814
  if (level === 0) void this.loadTile(ref);
1084
1815
  else void this.loadLowres(ref, level);
1085
1816
  }
1086
1817
  }
1818
+ /** Whether anything already draws terrain under hires tile (x,z) — a
1819
+ * remembered/queued impostor, or a resident lowres ring covering it. */
1820
+ hasUnderlay(x, z) {
1821
+ if (this.impostors?.has(tileKey(x, z))) return true;
1822
+ for (const lvl of this.lowLevels) {
1823
+ const f = 2 ** lvl.level;
1824
+ const rec = this.records.get(recKey(lvl.level, Math.floor(x / f), Math.floor(z / f)));
1825
+ if (rec?.state === "ready") return true;
1826
+ }
1827
+ return false;
1828
+ }
1087
1829
  /** Insert built tiles into the scene at a bounded per-frame rate (via
1088
1830
  * update()), so GPU buffer uploads are spread across frames instead of
1089
1831
  * bursting. Normally one per frame; when a backlog builds (a big preset
@@ -1097,11 +1839,14 @@ var TileManager = class _TileManager {
1097
1839
  if (!rec || rec.state !== "built") continue;
1098
1840
  rec.state = "ready";
1099
1841
  this.pendingBuilt--;
1100
- rec.fadeStart = performance.now();
1101
- this.fadingKeys.add(key);
1842
+ if (rec.level !== 0 || this.hasUnderlay(rec.ref.x, rec.ref.z)) {
1843
+ rec.fadeStart = performance.now();
1844
+ this.fadingKeys.add(key);
1845
+ }
1102
1846
  this.opts.scene.add(rec.terrain);
1103
1847
  if (rec.terrainLm) this.opts.scene.add(rec.terrainLm);
1104
1848
  if (rec.water) this.opts.scene.add(rec.water);
1849
+ if (rec.level === 0) this.impostors?.onHiresReady(rec.ref.x, rec.ref.z, rec.surface);
1105
1850
  this.coverageDirty = true;
1106
1851
  this.invalidate();
1107
1852
  this.emitter.emit("change", this.stats);
@@ -1151,6 +1896,7 @@ var TileManager = class _TileManager {
1151
1896
  for (const [key, rec] of this.records) {
1152
1897
  if (rec.level === 0 && rec.state === "ready" && !this.fadingKeys.has(key)) shown.add(tileKey(rec.ref.x, rec.ref.z));
1153
1898
  }
1899
+ this.impostors?.applyCoverage(shown);
1154
1900
  let finerIndex = this.index;
1155
1901
  for (const lvl of this.lowLevels) {
1156
1902
  const shownHere = /* @__PURE__ */ new Set();
@@ -1193,6 +1939,8 @@ var TileManager = class _TileManager {
1193
1939
  this.index.delete(key);
1194
1940
  const rec = this.records.get(key);
1195
1941
  if (rec) this.unload(key, rec);
1942
+ this.impostors?.remove(key);
1943
+ this.byteCache.drop(key);
1196
1944
  changed = true;
1197
1945
  }
1198
1946
  }
@@ -1206,6 +1954,7 @@ var TileManager = class _TileManager {
1206
1954
  this.index.set(k, t);
1207
1955
  const rec = this.records.get(k);
1208
1956
  if (rec) this.unload(k, rec);
1957
+ this.byteCache.drop(k);
1209
1958
  changed = true;
1210
1959
  } else {
1211
1960
  previous.path = t.path;
@@ -1228,21 +1977,64 @@ var TileManager = class _TileManager {
1228
1977
  const levels = [...lowres.levels].sort((a, b) => a.level - b.level);
1229
1978
  this.lowLevels.push(...levels);
1230
1979
  for (const lvl of levels) this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
1980
+ this.impostors?.dispose();
1981
+ this.impostors = null;
1231
1982
  this.lastFocusX = Infinity;
1232
1983
  this.lastFocusZ = Infinity;
1233
1984
  this.coverageDirty = true;
1234
1985
  this.invalidate();
1235
1986
  }
1236
- /** Live-tune streaming (view distance, tile budget, fetch concurrency).
1237
- * Takes effect on the next update(): the plan is recomputed from scratch. */
1987
+ /** Show or hide every resident tile's cave-dark geometry (VTLA tiles order
1988
+ * it as a contiguous tail per mesh, so hiding is a shorter draw range —
1989
+ * same draw calls, fewer vertices shaded). Tiles built while hidden come up
1990
+ * hidden. Tiles without a cave tail (older formats, all-surface tiles) are
1991
+ * untouched. Returns whether anything changed (the caller redraws). */
1992
+ setCaveGeometry(visible) {
1993
+ if (this.caveGeometry === visible) return false;
1994
+ this.caveGeometry = visible;
1995
+ for (const rec of this.records.values()) {
1996
+ if (rec.level !== 0) continue;
1997
+ applyCaveRange(rec.terrain, visible);
1998
+ applyCaveRange(rec.terrainLm, visible);
1999
+ applyCaveRange(rec.water, visible);
2000
+ }
2001
+ return true;
2002
+ }
2003
+ /** Live-tune streaming (view distance, tile budget, fetch concurrency,
2004
+ * map-memory resolution). Takes effect on the next update(): the plan is
2005
+ * recomputed from scratch. Changing `mapMemory` rebuilds the impostor
2006
+ * atlas, which forgets remembered terrain (it re-accumulates as you pan). */
1238
2007
  configure(settings) {
1239
2008
  if (settings.viewDistance !== void 0) this.opts.viewDistance = settings.viewDistance;
1240
2009
  if (settings.maxTiles !== void 0) this.opts.maxTiles = settings.maxTiles;
1241
2010
  if (settings.concurrency !== void 0) this.opts.concurrency = settings.concurrency;
1242
2011
  if (settings.maxBytes !== void 0) this.opts.maxBytes = settings.maxBytes;
2012
+ if (settings.tileCacheBytes !== void 0) {
2013
+ this.opts.tileCacheBytes = settings.tileCacheBytes;
2014
+ this.byteCache.setBudget(settings.tileCacheBytes);
2015
+ }
2016
+ if (settings.mapMemory !== void 0 && settings.mapMemory !== this.mapMemoryResolution) {
2017
+ this.impostors?.dispose();
2018
+ this.impostors = null;
2019
+ if (this.renderer && settings.mapMemory > 0 && this.lowLevels.length === 0) {
2020
+ this.impostors = new ImpostorLayer(this.renderer, this.opts.scene, this.opts.material, this.tileBlocks, settings.mapMemory, this.readySurface);
2021
+ }
2022
+ this.invalidate();
2023
+ }
2024
+ this.applyHazeFloor();
1243
2025
  this.lastFocusX = Infinity;
1244
2026
  this.lastFocusZ = Infinity;
1245
2027
  }
2028
+ /** The active map-memory impostor resolution (0 = off/unavailable). */
2029
+ get mapMemoryResolution() {
2030
+ return this.impostors?.resolutionPx ?? 0;
2031
+ }
2032
+ /** How far remembered (impostor) terrain reaches from (x,z), in blocks —
2033
+ * 0 without map memory. The viewer sizes zoom range and fog off this so
2034
+ * the remembered map is actually visible. */
2035
+ mapMemoryExtent(x, z) {
2036
+ return this.impostors?.extentFrom(x, z) ?? 0;
2037
+ }
1246
2038
  /** The current stream-in radius, in blocks. */
1247
2039
  get viewDistance() {
1248
2040
  return this.opts.viewDistance;
@@ -1332,7 +2124,11 @@ var TileManager = class _TileManager {
1332
2124
  this.records.set(key, rec);
1333
2125
  this.inFlight++;
1334
2126
  try {
1335
- const buffer = await maybeInflate(await this.opts.fetch(ref.path, abort.signal));
2127
+ const cached = this.byteCache.get(key, ref.revision);
2128
+ const raw = cached ?? await this.opts.fetch(ref.path, abort.signal);
2129
+ if (this.disposed || rec.state !== "loading") return;
2130
+ if (!cached) this.byteCache.put(key, raw, ref.revision);
2131
+ const buffer = await maybeInflate(raw);
1336
2132
  if (this.disposed || rec.state !== "loading") return;
1337
2133
  if (buffer.byteLength === 0) {
1338
2134
  rec.state = "empty";
@@ -1369,6 +2165,11 @@ var TileManager = class _TileManager {
1369
2165
  releaseAfterUpload(meshes.terrain.geometry);
1370
2166
  if (meshes.terrainLm) releaseAfterUpload(meshes.terrainLm.geometry);
1371
2167
  if (meshes.water) releaseAfterUpload(meshes.water.geometry);
2168
+ if (!this.caveGeometry) {
2169
+ applyCaveRange(meshes.terrain, false);
2170
+ applyCaveRange(meshes.terrainLm, false);
2171
+ applyCaveRange(meshes.water, false);
2172
+ }
1372
2173
  rec.terrain = meshes.terrain;
1373
2174
  rec.terrainLm = meshes.terrainLm;
1374
2175
  rec.lightmapTex = meshes.lightmapTex;
@@ -1379,6 +2180,10 @@ var TileManager = class _TileManager {
1379
2180
  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);
1380
2181
  this.sizeHints.set(key, rec.memoryBytes);
1381
2182
  this.averageHiresBytes = this.averageHiresBytes * 0.875 + rec.memoryBytes * 0.125;
2183
+ if (this.planCutoffSq !== null && performance.now() - this.lastPlanMs > 250) {
2184
+ this.lastFocusX = Infinity;
2185
+ this.lastFocusZ = Infinity;
2186
+ }
1382
2187
  rec.state = "built";
1383
2188
  this.pendingBuilt++;
1384
2189
  this.failCounts.delete(key);
@@ -1388,6 +2193,7 @@ var TileManager = class _TileManager {
1388
2193
  this.emitter.emit("change", this.stats);
1389
2194
  } catch (e) {
1390
2195
  if (e.name !== "AbortError") {
2196
+ this.byteCache.drop(key);
1391
2197
  this.markFailed(key, rec);
1392
2198
  console.warn(`vantage: tile ${key} failed to load:`, e);
1393
2199
  }
@@ -1401,13 +2207,27 @@ var TileManager = class _TileManager {
1401
2207
  rec.state = "empty";
1402
2208
  rec.abort?.abort();
1403
2209
  if (priorState === "built") this.pendingBuilt--;
2210
+ const remember = this.impostors !== null && rec.level === 0 && priorState === "ready" && rec.terrain !== void 0 && rec.surface !== void 0;
1404
2211
  for (const mesh of [rec.terrain, rec.terrainLm, rec.water]) {
1405
2212
  if (!mesh) continue;
2213
+ if (remember) continue;
1406
2214
  this.opts.scene.remove(mesh);
1407
2215
  if (isSharedQuadIndex(mesh.geometry.index)) mesh.geometry.setIndex(null);
1408
2216
  mesh.geometry.dispose();
1409
2217
  }
1410
- rec.lightmapTex?.dispose();
2218
+ if (remember) {
2219
+ rec.fadeStart = void 0;
2220
+ this.impostors.capture(
2221
+ rec.ref.x,
2222
+ rec.ref.z,
2223
+ { terrain: rec.terrain, terrainLm: rec.terrainLm, water: rec.water, lightmapTex: rec.lightmapTex },
2224
+ rec.surface,
2225
+ this.minY,
2226
+ this.maxY
2227
+ );
2228
+ } else {
2229
+ rec.lightmapTex?.dispose();
2230
+ }
1411
2231
  this.records.delete(key);
1412
2232
  this.failCounts.delete(key);
1413
2233
  this.fadingKeys.delete(key);
@@ -1419,7 +2239,7 @@ var TileManager = class _TileManager {
1419
2239
  * leave first; one nearest tile is always kept so an oversized outlier does
1420
2240
  * not create an unload/refetch loop. Learned weights make the next plan fit. */
1421
2241
  trimToMemoryBudget() {
1422
- let total = 0;
2242
+ let total = this.impostors?.gpuBytes ?? 0;
1423
2243
  const hires = [];
1424
2244
  for (const [key, rec] of this.records) {
1425
2245
  total += rec.memoryBytes;
@@ -1427,11 +2247,12 @@ var TileManager = class _TileManager {
1427
2247
  hires.push({ key, rec, d: this.distSqTo(rec.ref, 0, this.focusX, this.focusZ) });
1428
2248
  }
1429
2249
  }
1430
- if (total <= this.opts.maxBytes || hires.length <= 1) return;
2250
+ const maxResident = Math.ceil(this.opts.maxTiles * 1.25);
2251
+ if (total <= this.opts.maxBytes && hires.length <= maxResident || hires.length <= 1) return;
1431
2252
  hires.sort((a, b) => b.d - a.d);
1432
2253
  let remaining = hires.length;
1433
2254
  for (const entry of hires) {
1434
- if (total <= this.opts.maxBytes || remaining <= 1) break;
2255
+ if (total <= this.opts.maxBytes && remaining <= maxResident || remaining <= 1) break;
1435
2256
  total -= entry.rec.memoryBytes;
1436
2257
  remaining--;
1437
2258
  this.unload(entry.key, entry.rec);
@@ -1464,7 +2285,9 @@ var TileManager = class _TileManager {
1464
2285
  bytes += rec.ref.bytes;
1465
2286
  } else if (rec.state === "loading" || rec.state === "built") loading++;
1466
2287
  }
1467
- this.statsCache = { loaded, loading, total: this.index.size, lowres, vertexCount, triangleCount, bytes, residentBytes };
2288
+ const remembered = this.impostors?.count ?? 0;
2289
+ if (this.impostors) residentBytes += this.impostors.gpuBytes;
2290
+ this.statsCache = { loaded, loading, total: this.index.size, lowres, remembered, vertexCount, triangleCount, bytes, residentBytes, cachedBytes: this.byteCache.size };
1468
2291
  return this.statsCache;
1469
2292
  }
1470
2293
  /** Aggregated biome share across every resident tile, most common first. */
@@ -1516,7 +2339,7 @@ var TileManager = class _TileManager {
1516
2339
  }
1517
2340
  }
1518
2341
  if (n > 0) return sum / n;
1519
- return this.lowresHeightAt(x, z);
2342
+ return this.lowresHeightAt(x, z) ?? this.impostors?.heightAt(x, z) ?? null;
1520
2343
  };
1521
2344
  /** Height from the finest resident lowres level covering (x,z), or null. */
1522
2345
  lowresHeightAt(x, z) {
@@ -1561,7 +2384,10 @@ var TileManager = class _TileManager {
1561
2384
  this.disposed = true;
1562
2385
  this.queue = [];
1563
2386
  this.pendingAdd = [];
2387
+ this.impostors?.dispose();
2388
+ this.impostors = null;
1564
2389
  for (const [key, rec] of [...this.records]) this.unload(key, rec);
2390
+ this.byteCache.clear();
1565
2391
  this.emitter.clear();
1566
2392
  }
1567
2393
  };
@@ -2435,6 +3261,10 @@ var VantageViewer = class _VantageViewer {
2435
3261
  lastSliceY = null;
2436
3262
  /** The dark "unexplored rock" floor under a sliced world. */
2437
3263
  slicePlane = null;
3264
+ // Cave-geometry draw policy (VTLA tiles): whether cave-dark tails are in the
3265
+ // draw ranges right now, re-evaluated each frame under 'auto'.
3266
+ caveMode = "auto";
3267
+ cavesShown = true;
2438
3268
  // Live lighting appearance (applied to the shader on load and on change).
2439
3269
  light = { ...DEFAULT_LIGHT };
2440
3270
  // Live display fidelity (shader uniforms + render scale).
@@ -2475,8 +3305,10 @@ var VantageViewer = class _VantageViewer {
2475
3305
  display: options.display ?? {},
2476
3306
  streaming: options.streaming ?? {},
2477
3307
  urlState: options.urlState ?? false,
2478
- renderOnDemand: options.renderOnDemand ?? true
3308
+ renderOnDemand: options.renderOnDemand ?? true,
3309
+ caveGeometry: options.caveGeometry ?? "auto"
2479
3310
  };
3311
+ this.caveMode = this.options.caveGeometry;
2480
3312
  if (options.light) this.light = { ...this.light, ...options.light };
2481
3313
  if (options.display) this.display = { ...this.display, ...options.display };
2482
3314
  this.renderer = new THREE2.WebGLRenderer({ antialias: false });
@@ -2571,6 +3403,7 @@ var VantageViewer = class _VantageViewer {
2571
3403
  this.hasAnims = texData.anims.length > 0;
2572
3404
  this.lastTextureLayers = manifest.textureLayers ?? texData.layers;
2573
3405
  this.tile = null;
3406
+ this.cavesShown = true;
2574
3407
  this.tiles = new TileManager({
2575
3408
  manifest,
2576
3409
  fetch: source.fetch,
@@ -2584,11 +3417,15 @@ var VantageViewer = class _VantageViewer {
2584
3417
  // tile's insertion on the atlas covering its layers (a no-op once the
2585
3418
  // atlas is complete). Returns the layer count now loaded.
2586
3419
  ...manifest.rendering ? { ensureAtlas: (n) => this.ensureAtlasLayers(source, n).then(() => this.lastTextureLayers) } : {},
3420
+ // Map memory: pyramid-less worlds snapshot evicted tiles so explored
3421
+ // terrain persists on the zoomed-out map (see StreamingSettings).
3422
+ renderer: this.renderer,
2587
3423
  ...this.options.streaming
2588
3424
  });
2589
3425
  this.setHeightSampler(this.tiles.heightAt);
2590
3426
  this.tilesUnsub = this.tiles.on("change", (stats) => {
2591
3427
  this.needsRender = true;
3428
+ if (!this.manifest?.lowres) this.applyViewLimits();
2592
3429
  this.emitter.emit("stats", stats);
2593
3430
  const now = performance.now();
2594
3431
  if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
@@ -2609,7 +3446,7 @@ var VantageViewer = class _VantageViewer {
2609
3446
  this._biomes = [];
2610
3447
  this.emitter.emit("load", {
2611
3448
  // Streamed worlds: the tile format follows the manifest schema version.
2612
- magic: manifest.format >= 5 ? "VTL9" : manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
3449
+ magic: manifest.format >= 6 ? "VTLA" : manifest.format >= 5 ? "VTL9" : manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
2613
3450
  vertexCount: 0,
2614
3451
  triangleCount: 0,
2615
3452
  size,
@@ -2765,11 +3602,13 @@ var VantageViewer = class _VantageViewer {
2765
3602
  this.applyViewLimits();
2766
3603
  }
2767
3604
  /** The radius hires tiles are actually guaranteed resident to: the view
2768
- * distance, unless the tile budget runs out first (nearest-first fill ⇒ a
2769
- * disc of maxTiles tiles ⇒ radius tb·√(maxTiles/π)). */
3605
+ * distance, unless a budget runs out first. The manager reports its honest
3606
+ * frontier (tile count AND byte budget), so fog hugs where data really
3607
+ * stops — a budget cut reads as distance haze, not a cliff into the sky. */
2770
3608
  streamRadius() {
2771
- const vd = this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768;
2772
- const mt = this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120;
3609
+ if (this.tiles) return this.tiles.admittedRadius;
3610
+ const vd = this.options.streaming.viewDistance ?? 768;
3611
+ const mt = this.options.streaming.maxTiles ?? 120;
2773
3612
  const tb = this.manifest?.tileBlocks ?? 128;
2774
3613
  return Math.min(vd, tb * Math.sqrt(mt / Math.PI));
2775
3614
  }
@@ -2780,8 +3619,15 @@ var VantageViewer = class _VantageViewer {
2780
3619
  * fog retreats to the world edge — a faint horizon haze, never a wall. The
2781
3620
  * hires→lowres seam needs no hiding: finer data simply overlays coarser.
2782
3621
  *
2783
- * Without one (format 1), zoom and fog hug the hires ring so the map never
2784
- * becomes a field of holes: solid haze right where tiles stop. */
3622
+ * Without one, zoom and fog hug the drawable frontier: the hires ring on a
3623
+ * fresh session (so the map never becomes a field of holes — solid haze
3624
+ * right where tiles stop), growing to the remembered map-memory extent as
3625
+ * the camera explores. Re-applied on tile 'change' events, so the fog wall
3626
+ * recedes as snapshots land.
3627
+ *
3628
+ * Both branches share hard sanity ceilings (60k zoom, 250k far plane):
3629
+ * beyond them depth precision and control feel degrade faster than any
3630
+ * real overview gains — a 60k-block eye already frames a 100k-block map. */
2785
3631
  applyViewLimits() {
2786
3632
  if (!this.tiles || !this.shader) return;
2787
3633
  const viewDistance = this.tiles.viewDistance;
@@ -2792,10 +3638,11 @@ var VantageViewer = class _VantageViewer {
2792
3638
  this.camera.far = Math.min(Math.max(8e3, span * 2.5), 25e4);
2793
3639
  fog.set(span * 0.9, span * 1.8);
2794
3640
  } else {
2795
- const r = this.streamRadius();
2796
- this.controls.maxDistance = viewDistance * 2.2;
2797
- this.camera.far = Math.max(8e3, viewDistance * 6);
2798
- fog.set(r * 0.72, r * 1.05);
3641
+ const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
3642
+ const reach = Math.max(this.streamRadius(), this.tiles.mapMemoryExtent(focus.x, focus.z));
3643
+ this.controls.maxDistance = Math.min(Math.max(reach * 2.2, viewDistance * 2.2), 6e4);
3644
+ this.camera.far = Math.min(Math.max(8e3, reach * 6), 25e4);
3645
+ fog.set(reach * 0.72, reach * 1.05);
2799
3646
  }
2800
3647
  this.camera.updateProjectionMatrix();
2801
3648
  }
@@ -3155,8 +4002,10 @@ var VantageViewer = class _VantageViewer {
3155
4002
  return {
3156
4003
  viewDistance: this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768,
3157
4004
  maxTiles: this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120,
3158
- concurrency: this.options.streaming.concurrency ?? 4,
3159
- maxBytes: this.tiles?.maxBytes ?? this.options.streaming.maxBytes ?? 512 * 1024 * 1024
4005
+ concurrency: this.options.streaming.concurrency ?? 6,
4006
+ maxBytes: this.tiles?.maxBytes ?? this.options.streaming.maxBytes ?? 512 * 1024 * 1024,
4007
+ tileCacheBytes: this.options.streaming.tileCacheBytes ?? 192 * 1024 * 1024,
4008
+ mapMemory: this.options.streaming.mapMemory ?? 64
3160
4009
  };
3161
4010
  }
3162
4011
  /** Live-tune streaming: view distance, resident tile/byte budgets, concurrency.
@@ -3342,6 +4191,39 @@ var VantageViewer = class _VantageViewer {
3342
4191
  invalidate() {
3343
4192
  this.needsRender = true;
3344
4193
  }
4194
+ /** Set the cave-geometry draw policy (see the option of the same name).
4195
+ * Takes effect on the next frame. */
4196
+ setCaveGeometry(mode) {
4197
+ this.caveMode = mode;
4198
+ this.invalidate();
4199
+ }
4200
+ /** The current cave-geometry draw policy. */
4201
+ get caveGeometry() {
4202
+ return this.caveMode;
4203
+ }
4204
+ /** Re-evaluate whether cave-dark tails belong in the draw ranges. Above
4205
+ * ground with the depth slice closed they are provably behind terrain from
4206
+ * the camera's side of the surface, so 'auto' trims every tile's draw range
4207
+ * to its surface prefix; opening the slice or descending underground brings
4208
+ * them straight back. The underground test rides the streamed surface maps
4209
+ * (the same data the terrain-following pivot uses) with a couple of blocks
4210
+ * of hysteresis so skimming the terrain doesn't flicker the ranges. */
4211
+ applyCavePolicy() {
4212
+ if (!this.tiles) return;
4213
+ let show = true;
4214
+ if (this.caveMode === "always" || this.sliceActive) {
4215
+ show = true;
4216
+ } else {
4217
+ const cam = this.camera.position;
4218
+ const ground = this.tiles.heightAt(cam.x, cam.z);
4219
+ const margin = this.cavesShown ? 2.5 : 0.5;
4220
+ show = ground !== null && cam.y < ground + margin;
4221
+ }
4222
+ if (show !== this.cavesShown) {
4223
+ this.cavesShown = show;
4224
+ if (this.tiles.setCaveGeometry(show)) this.needsRender = true;
4225
+ }
4226
+ }
3345
4227
  /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
3346
4228
  * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
3347
4229
  static ANIM_TICK_MS = 100;
@@ -3385,6 +4267,7 @@ var VantageViewer = class _VantageViewer {
3385
4267
  }
3386
4268
  }
3387
4269
  }
4270
+ this.applyCavePolicy();
3388
4271
  this.pickHover();
3389
4272
  if (this.hasAnims && now - this.lastRenderMs >= _VantageViewer.ANIM_TICK_MS) this.needsRender = true;
3390
4273
  if (!this.options.renderOnDemand) this.needsRender = true;
@@ -3482,4 +4365,4 @@ var VantageViewer = class _VantageViewer {
3482
4365
  }
3483
4366
  };
3484
4367
 
3485
- export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome };
4368
+ export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, applyCaveRange, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome };