@thoughts-on-things/vantage-mc 0.1.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.
@@ -0,0 +1,2605 @@
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, parseManifest, parseTextureArray } from './chunk-X7ZJUHP2.js';
2
+ import * as THREE2 from 'three';
3
+
4
+ var SKY_TOP = [0.3, 0.52, 0.84];
5
+ var SKY_HORIZON = [0.72, 0.83, 0.95];
6
+ var VERT = (
7
+ /* glsl */
8
+ `
9
+ in float alayer;
10
+ in vec4 atint;
11
+ in float abiome;
12
+ #ifdef QUANTIZED
13
+ // Streaming fast path: attributes arrive in the tile's on-disk encoding and
14
+ // are dequantized HERE \u2014 u16 positions (world = uPosMin + q \xB7 uPosScale),
15
+ // int8 normal with the packed light byte riding in .w, biome colour looked
16
+ // up from the world palette texture. Decoding a tile costs the CPU nothing
17
+ // per vertex, which is what keeps streaming stutter-free.
18
+ in vec4 anrm;
19
+ uniform vec3 uPosMin;
20
+ uniform vec3 uPosScale;
21
+ uniform sampler2D uPalette;
22
+ #else
23
+ in vec3 abcol;
24
+ in float alight; // packed (sky<<4)|block, 0..255
25
+ #endif
26
+ uniform vec2 uFogCenter; // streaming focus (world XZ)
27
+ uniform float uFogRadial; // 1 = fog by XZ distance from
28
+ // uFogCenter, 0 = view depth
29
+ out vec2 vUv;
30
+ out vec4 vTint;
31
+ out vec3 vBcol;
32
+ flat out float vLayer;
33
+ flat out float vBiome;
34
+ out vec3 vN;
35
+ out float vFog;
36
+ out float vSky; // saved sky light, 0..1
37
+ out float vBlk; // saved block light, 0..1
38
+ void main() {
39
+ vUv = uv;
40
+ vTint = atint;
41
+ vLayer = alayer;
42
+ vBiome = abiome;
43
+ #ifdef QUANTIZED
44
+ vec3 pos = uPosMin + position * uPosScale;
45
+ vec3 nrm = anrm.xyz;
46
+ // The light byte was stored as the int8 normal's 4th lane; undo the sign.
47
+ float light = anrm.w < 0.0 ? anrm.w + 256.0 : anrm.w;
48
+ vBcol = texelFetch(uPalette, ivec2(int(abiome + 0.5), 0), 0).rgb;
49
+ #else
50
+ vec3 pos = position;
51
+ vec3 nrm = normal;
52
+ float light = alight;
53
+ vBcol = abcol;
54
+ #endif
55
+ float sky = floor(light / 16.0);
56
+ vSky = sky / 15.0;
57
+ vBlk = (light - sky * 16.0) / 15.0;
58
+ // Water surface waves come from real mesh geometry (Minecraft flowing-water
59
+ // heights, baked in the mesher) \u2014 the normal here carries the slope, so the
60
+ // waves catch light. No vertex animation \u2014 the water is static.
61
+ vN = normalize(mat3(modelMatrix) * nrm);
62
+ vec4 wp = modelMatrix * vec4(pos, 1.0);
63
+ vec4 mv = viewMatrix * wp;
64
+ // Streamed worlds fog by horizontal distance from the streaming focus \u2014
65
+ // exactly the ring where tiles stop \u2014 so looking straight down from any
66
+ // height never hazes the resident map (view-depth fog did).
67
+ vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
68
+ gl_Position = projectionMatrix * mv;
69
+ }
70
+ `
71
+ );
72
+ var FRAG = (
73
+ /* glsl */
74
+ `
75
+ precision highp float;
76
+ precision highp sampler2DArray;
77
+ uniform sampler2DArray map;
78
+ uniform vec3 lightDir;
79
+ uniform float uBiomeMix; // 0 = textured, 1 = biome layer
80
+ uniform float uHi; // highlighted biome id, or -1
81
+ uniform vec3 uFogColor;
82
+ uniform vec2 uFog; // (near, far)
83
+ uniform float uAlpha; // terrain opacity (1)
84
+ uniform float uWater; // 1 = this is the water pass
85
+ uniform float uDay; // daylight 0..1 (scales sky light; 1 = noon)
86
+ uniform float uAmbient; // brightness floor at zero light (map readability)
87
+ uniform float uExposure; // overall brightness/tone multiplier (1 = neutral)
88
+ uniform float uSharpness; // texture mip LOD bias (>0 = crisper distance, more shimmer)
89
+ uniform float uAoStrength; // baked AO darkening scale (1 = as-baked, 0 = off)
90
+ uniform float uSaturation; // colour saturation (1 = neutral)
91
+ uniform float uContrast; // colour contrast around mid grey (1 = neutral)
92
+ uniform float uFogDensity; // atmospheric haze amount (1 = full, 0 = clear)
93
+ in vec2 vUv;
94
+ in vec4 vTint;
95
+ in vec3 vBcol;
96
+ flat in float vLayer;
97
+ flat in float vBiome;
98
+ in vec3 vN;
99
+ in float vFog;
100
+ in float vSky;
101
+ in float vBlk;
102
+ out vec4 frag;
103
+ const vec3 SKY = vec3(0.62, 0.72, 0.88); // hemispheric sky ambient
104
+ const vec3 GND = vec3(0.34, 0.31, 0.27); // hemispheric ground ambient
105
+ const vec3 SUN = vec3(1.0, 0.95, 0.84); // warm key light
106
+ const vec3 TORCH = vec3(1.0, 0.80, 0.52); // warm tint where block light leads
107
+
108
+ // Baked sky+block light -> a (brightness, colour) pair. Effective level is the
109
+ // brighter of (sky * daylight) and block light, eased and floored so caves read
110
+ // on a map; block-lit areas pick up a warm cast that sunlit ones don't.
111
+ void bakedLight(out float amt, out vec3 col) {
112
+ float sky = vSky * uDay;
113
+ float lvl = max(sky, vBlk);
114
+ // Minecraft's exact lightmap curve: brightness = l / (4 - 3l) (LightTexture).
115
+ // Concave \u2014 far darker in the midtones than a smoothstep (a light-7 nook is
116
+ // ~0.18, not ~0.5). Surface terrain is full skylight (l=1 \u2192 1.0); the curve
117
+ // only deepens shaded overhangs and caves, matching the game.
118
+ float curve = lvl / (4.0 - 3.0 * lvl);
119
+ amt = mix(uAmbient, 1.0, curve);
120
+ col = mix(vec3(1.0), TORCH, 0.6 * clamp(vBlk - sky, 0.0, 1.0));
121
+ }
122
+
123
+ // Pixel-art textures + the colour uniforms are authored in sRGB; decode to
124
+ // linear so lighting is correct, then re-encode at the end (raw ShaderMaterial
125
+ // bypasses three's colour management, and we render straight to the canvas).
126
+ vec3 toLinear(vec3 c) {
127
+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
128
+ }
129
+ // Linear -> display sRGB (the OETF). Done in-shader since there's no OutputPass.
130
+ vec3 toSRGB(vec3 c) {
131
+ c = max(c, vec3(0.0));
132
+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
133
+ }
134
+
135
+ // Minecraft's fixed face-direction brightness \u2014 the signature relief cue the
136
+ // game bakes into every block's vertex colour: top 1.0, bottom 0.5, north/south
137
+ // (\xB1Z) 0.8, east/west (\xB1X) 0.6. Full-cube faces have axis-aligned normals so the
138
+ // pick is exact; this reads as Minecraft far more than a soft sun dot-product.
139
+ float faceShade(vec3 n) {
140
+ vec3 a = abs(n);
141
+ if (a.y >= a.x && a.y >= a.z) return n.y >= 0.0 ? 1.0 : 0.5; // top / bottom
142
+ if (a.x >= a.z) return 0.6; // east / west
143
+ return 0.8; // north / south
144
+ }
145
+
146
+ // Final colour grade: saturation then contrast around mid grey. Cheap pop/clarity
147
+ // controls so the look is tunable without re-baking. Neutral at (1, 1).
148
+ vec3 grade(vec3 c) {
149
+ float l = dot(c, vec3(0.299, 0.587, 0.114));
150
+ c = mix(vec3(l), c, uSaturation);
151
+ c = (c - 0.5) * uContrast + 0.5;
152
+ return max(c, vec3(0.0));
153
+ }
154
+
155
+ void main() {
156
+ float lightAmt; vec3 lightCol;
157
+ bakedLight(lightAmt, lightCol);
158
+ vec4 t = texture(map, vec3(vUv, vLayer), -uSharpness); // negative bias = sharper
159
+ if (t.a < 0.05) discard; // drop only fully-empty texels; the
160
+ // fractional edge becomes MSAA coverage
161
+ t.rgb = toLinear(t.rgb); // work in linear; encode at the end
162
+ vec3 fogCol = toLinear(uFogColor);
163
+ vec3 N = normalize(vN);
164
+
165
+ // Water pass: a semi-transparent blue tint over the normally-lit seabed.
166
+ // The depth read comes from the SEABED darkening (sky light is
167
+ // attenuated through water in the light pass), seen through the clear surface,
168
+ // NOT from fading the water to opaque. So keep the surface fairly transparent
169
+ // so sand/gravel/seagrass show through; the wave look is the real flowing-water
170
+ // mesh geometry, whose sloped normal (vN) catches light.
171
+ if (uWater > 0.5) {
172
+ float depth = vTint.a;
173
+ vec3 wcol = toLinear(vTint.rgb);
174
+ wcol = mix(wcol, wcol * vec3(0.55, 0.66, 0.85), depth * 0.7); // deep water cools + deepens
175
+ vec3 Nw = normalize(vN);
176
+ float ndl2 = max(dot(Nw, normalize(lightDir)), 0.0);
177
+ // Flat-lit (mostly the water colour \xD7 baked light); only a small
178
+ // directional term so the wave-slope normals read, no blown-out sun sheen.
179
+ vec3 wlit = grade(wcol * (0.62 + 0.28 * SUN * ndl2) * lightAmt * lightCol * uExposure);
180
+ float wf = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
181
+ float wa = mix(0.5, 0.74, depth); // blue tint, seabed still reads through
182
+ frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa);
183
+ return;
184
+ }
185
+
186
+ float ao = 1.0 - (1.0 - vTint.a) * uAoStrength; // baked AO (colour alpha), strength-scaled
187
+ vec3 texcol = t.rgb * toLinear(vTint.rgb);
188
+ float luma = dot(texcol, vec3(0.299, 0.587, 0.114));
189
+ // Biome view keeps terrain relief by modulating the flat biome colour by luma.
190
+ vec3 biomecol = toLinear(vBcol) * (0.45 + 0.65 * luma);
191
+ vec3 base = mix(texcol, biomecol, uBiomeMix);
192
+ if (uBiomeMix > 0.5 && uHi >= 0.0 && abs(vBiome - uHi) > 0.5) {
193
+ float g = dot(base, vec3(0.299, 0.587, 0.114));
194
+ base = mix(base, vec3(g) * 0.55, 0.82); // fade biomes other than the selected one
195
+ }
196
+ // Relief from Minecraft's per-face brightness (not a soft sun dot), times the
197
+ // baked sky/block light and AO \u2014 i.e. the game's own shading formula. A faint
198
+ // hemispheric colour cast (sky above / earth below) keeps the atmosphere
199
+ // without washing out the crisp face steps.
200
+ float fshade = faceShade(N);
201
+ vec3 hemi = mix(GND, SKY, 0.5 + 0.5 * N.y);
202
+ vec3 shade = mix(vec3(1.0), hemi, 0.16) * fshade;
203
+ vec3 lit = grade(base * shade * ao * lightAmt * lightCol * uExposure);
204
+ float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity; // aerial depth into the horizon
205
+ frag = vec4(toSRGB(mix(lit, fogCol, f)), uAlpha * t.a); // alpha \u2192 MSAA coverage (foliage AA)
206
+ }
207
+ `
208
+ );
209
+ function paletteTexture(palette) {
210
+ const n = Math.max(1, palette.length);
211
+ const data = new Uint8Array(4 * n);
212
+ for (let i = 0; i < palette.length; i++) {
213
+ const c = palette[i];
214
+ data[i * 4 + 0] = Math.round(c[0] * 255);
215
+ data[i * 4 + 1] = Math.round(c[1] * 255);
216
+ data[i * 4 + 2] = Math.round(c[2] * 255);
217
+ data[i * 4 + 3] = 255;
218
+ }
219
+ const tex = new THREE2.DataTexture(data, n, 1, THREE2.RGBAFormat, THREE2.UnsignedByteType);
220
+ tex.magFilter = THREE2.NearestFilter;
221
+ tex.minFilter = THREE2.NearestFilter;
222
+ tex.needsUpdate = true;
223
+ return tex;
224
+ }
225
+ function createTerrainMaterial(texData, opts = {}) {
226
+ const tex = new THREE2.DataArrayTexture(texData.pixels, texData.width, texData.height, texData.layers);
227
+ tex.format = THREE2.RGBAFormat;
228
+ tex.type = THREE2.UnsignedByteType;
229
+ tex.magFilter = THREE2.NearestFilter;
230
+ tex.minFilter = THREE2.LinearMipmapLinearFilter;
231
+ tex.generateMipmaps = true;
232
+ tex.anisotropy = 16;
233
+ tex.wrapS = THREE2.RepeatWrapping;
234
+ tex.wrapT = THREE2.RepeatWrapping;
235
+ tex.needsUpdate = true;
236
+ return new THREE2.ShaderMaterial({
237
+ glslVersion: THREE2.GLSL3,
238
+ defines: opts.quantized ? { QUANTIZED: "" } : {},
239
+ uniforms: {
240
+ map: { value: tex },
241
+ // Per-tile dequantization transform, set per-mesh in onBeforeRender
242
+ // (quantized path only; inert otherwise).
243
+ uPosMin: { value: new THREE2.Vector3() },
244
+ uPosScale: { value: new THREE2.Vector3(1, 1, 1) },
245
+ uPalette: { value: opts.quantized ? paletteTexture(opts.palette ?? []) : null },
246
+ uFogCenter: { value: new THREE2.Vector2() },
247
+ // streaming focus (world XZ)
248
+ uFogRadial: { value: 0 },
249
+ // 1 = radial fog around uFogCenter (streaming)
250
+ lightDir: { value: new THREE2.Vector3(0.55, 1, 0.4).normalize() },
251
+ uBiomeMix: { value: 0 },
252
+ uHi: { value: -1 },
253
+ uFogColor: { value: new THREE2.Vector3(...SKY_HORIZON) },
254
+ uFog: { value: new THREE2.Vector2(1e6, 2e6) },
255
+ // set from terrain extent
256
+ uAlpha: { value: 1 },
257
+ uWater: { value: 0 },
258
+ uDay: { value: 1 },
259
+ // noon; a day/night control can drive this
260
+ uAmbient: { value: 0.12 },
261
+ // caves stay readable rather than pure black
262
+ uExposure: { value: 1 },
263
+ // overall brightness/tone (live-tunable)
264
+ uSharpness: { value: 0 },
265
+ // texture mip LOD bias (0 = smooth, >0 = crisper)
266
+ uAoStrength: { value: 1 },
267
+ // baked AO darkening scale (1 = as-baked)
268
+ uSaturation: { value: 1 },
269
+ // colour saturation (1 = neutral)
270
+ uContrast: { value: 1 },
271
+ // colour contrast (1 = neutral)
272
+ uFogDensity: { value: 1 }
273
+ // atmospheric haze amount (1 = full)
274
+ },
275
+ vertexShader: VERT,
276
+ fragmentShader: FRAG,
277
+ // Alpha-to-coverage turns the (mip-averaged, fractional) cutout edge of leaves
278
+ // and grass into MSAA sample coverage instead of a hard discard — the standard
279
+ // fix for the foliage shimmer/"noise" you get when moving the camera. Needs the
280
+ // renderer's MSAA (antialias:true), which is on. Opaque blocks (alpha 1) are
281
+ // unaffected. The water material stays transparent and ignores this.
282
+ alphaToCoverage: true
283
+ });
284
+ }
285
+ function createWaterMaterial(terrain) {
286
+ const u = {};
287
+ for (const k in terrain.uniforms) u[k] = terrain.uniforms[k];
288
+ u["uWater"] = { value: 1 };
289
+ return new THREE2.ShaderMaterial({
290
+ glslVersion: THREE2.GLSL3,
291
+ defines: { ...terrain.defines },
292
+ // keep QUANTIZED in lock-step
293
+ uniforms: u,
294
+ vertexShader: VERT,
295
+ fragmentShader: FRAG,
296
+ transparent: true,
297
+ depthWrite: false
298
+ });
299
+ }
300
+ function createLowresMaterial(terrain) {
301
+ const t = terrain.uniforms;
302
+ return new THREE2.ShaderMaterial({
303
+ glslVersion: THREE2.GLSL3,
304
+ uniforms: {
305
+ uFogColor: t["uFogColor"],
306
+ uFog: t["uFog"],
307
+ uFogCenter: t["uFogCenter"],
308
+ uFogRadial: t["uFogRadial"],
309
+ uFogDensity: t["uFogDensity"],
310
+ uExposure: t["uExposure"],
311
+ uSaturation: t["uSaturation"],
312
+ uContrast: t["uContrast"]
313
+ },
314
+ vertexShader: (
315
+ /* glsl */
316
+ `
317
+ in vec3 acol;
318
+ uniform vec2 uFogCenter;
319
+ uniform float uFogRadial;
320
+ out vec3 vCol;
321
+ out float vFog;
322
+ void main() {
323
+ vCol = acol;
324
+ vec4 wp = modelMatrix * vec4(position, 1.0);
325
+ vec4 mv = viewMatrix * wp;
326
+ vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
327
+ gl_Position = projectionMatrix * mv;
328
+ }
329
+ `
330
+ ),
331
+ fragmentShader: (
332
+ /* glsl */
333
+ `
334
+ precision highp float;
335
+ uniform vec3 uFogColor;
336
+ uniform vec2 uFog;
337
+ uniform float uFogDensity;
338
+ uniform float uExposure;
339
+ uniform float uSaturation;
340
+ uniform float uContrast;
341
+ in vec3 vCol;
342
+ in float vFog;
343
+ out vec4 frag;
344
+ vec3 toLinear(vec3 c) {
345
+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
346
+ }
347
+ vec3 toSRGB(vec3 c) {
348
+ c = max(c, vec3(0.0));
349
+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
350
+ }
351
+ void main() {
352
+ vec3 c = toLinear(vCol) * uExposure;
353
+ float l = dot(c, vec3(0.299, 0.587, 0.114));
354
+ c = mix(vec3(l), c, uSaturation);
355
+ c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
356
+ float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
357
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
358
+ }
359
+ `
360
+ )
361
+ });
362
+ }
363
+ function createSky() {
364
+ const mat = new THREE2.ShaderMaterial({
365
+ glslVersion: THREE2.GLSL3,
366
+ side: THREE2.BackSide,
367
+ depthWrite: false,
368
+ depthTest: false,
369
+ vertexShader: (
370
+ /* glsl */
371
+ `
372
+ out vec3 vDir;
373
+ void main() { vDir = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
374
+ `
375
+ ),
376
+ fragmentShader: (
377
+ /* glsl */
378
+ `
379
+ precision highp float;
380
+ uniform vec3 uTop; uniform vec3 uHorizon;
381
+ in vec3 vDir; out vec4 frag;
382
+ void main() {
383
+ float t = smoothstep(-0.08, 0.5, vDir.y);
384
+ frag = vec4(mix(uHorizon, uTop, t), 1.0); // authored sRGB, straight to the canvas
385
+ }
386
+ `
387
+ ),
388
+ uniforms: {
389
+ uTop: { value: new THREE2.Vector3(...SKY_TOP) },
390
+ uHorizon: { value: new THREE2.Vector3(...SKY_HORIZON) }
391
+ }
392
+ });
393
+ const sky = new THREE2.Mesh(new THREE2.SphereGeometry(10, 24, 16), mat);
394
+ sky.renderOrder = -1e3;
395
+ sky.frustumCulled = false;
396
+ return sky;
397
+ }
398
+
399
+ // src/three/terrain.ts
400
+ function biomeColors(biome, vertexCount, palette, fallback) {
401
+ const out = new Float32Array(3 * vertexCount);
402
+ for (let i = 0; i < vertexCount; i++) {
403
+ const c = palette[biome[i] | 0] ?? fallback;
404
+ out[i * 3 + 0] = c[0];
405
+ out[i * 3 + 1] = c[1];
406
+ out[i * 3 + 2] = c[2];
407
+ }
408
+ return out;
409
+ }
410
+ function applyTexturedAttributes(geom, section, palette, waterFallback) {
411
+ geom.setAttribute("uv", new THREE2.BufferAttribute(section.uv, 2));
412
+ geom.setAttribute("alayer", new THREE2.BufferAttribute(section.layer, 1));
413
+ geom.setAttribute("atint", new THREE2.BufferAttribute(section.colors, 4, true));
414
+ const light = section.light ?? new Uint8Array(section.vertexCount).fill(240);
415
+ const lightF = new Float32Array(light);
416
+ geom.setAttribute("alight", new THREE2.BufferAttribute(lightF, 1));
417
+ if (section.biome) {
418
+ geom.setAttribute("abiome", new THREE2.BufferAttribute(section.biome, 1));
419
+ geom.setAttribute("abcol", new THREE2.BufferAttribute(biomeColors(section.biome, section.vertexCount, palette, waterFallback), 3));
420
+ } else {
421
+ geom.setAttribute("abiome", new THREE2.BufferAttribute(new Float32Array(section.vertexCount), 1));
422
+ geom.setAttribute("abcol", new THREE2.BufferAttribute(new Float32Array(3 * section.vertexCount), 3));
423
+ }
424
+ }
425
+ function baseGeometry(section) {
426
+ const geom = new THREE2.BufferGeometry();
427
+ geom.setAttribute("position", new THREE2.BufferAttribute(section.positions, 3));
428
+ geom.setAttribute("normal", new THREE2.BufferAttribute(section.normals, 3));
429
+ geom.setIndex(new THREE2.BufferAttribute(section.indices, 1));
430
+ return geom;
431
+ }
432
+ var WATER_FALLBACK = [0.3, 0.5, 0.85];
433
+ function buildTileMeshes(tile, palette, material, waterMaterial) {
434
+ const geom = baseGeometry(tile);
435
+ applyTexturedAttributes(geom, tile, palette, WATER_FALLBACK);
436
+ geom.computeBoundingBox();
437
+ const terrain = new THREE2.Mesh(geom, material);
438
+ const bounds = geom.boundingBox.clone();
439
+ let water;
440
+ if (tile.fluid && tile.fluid.vertexCount > 0) {
441
+ const wg = baseGeometry(tile.fluid);
442
+ applyTexturedAttributes(wg, tile.fluid, palette, WATER_FALLBACK);
443
+ wg.computeBoundingBox();
444
+ bounds.union(wg.boundingBox);
445
+ water = new THREE2.Mesh(wg, waterMaterial);
446
+ water.renderOrder = 1;
447
+ }
448
+ return { terrain, water, bounds };
449
+ }
450
+ function quantizedBox(sec) {
451
+ const [mx, my, mz] = sec.posMin;
452
+ const [sx, sy, sz] = sec.posScale;
453
+ return new THREE2.Box3(new THREE2.Vector3(mx, my, mz), new THREE2.Vector3(mx + 65535 * sx, my + 65535 * sy, mz + 65535 * sz));
454
+ }
455
+ function quantizedMesh(sec, material) {
456
+ const geom = new THREE2.BufferGeometry();
457
+ geom.setAttribute("position", new THREE2.BufferAttribute(sec.positions, 3, false));
458
+ geom.setAttribute("anrm", new THREE2.BufferAttribute(sec.normals, 4, false));
459
+ geom.setAttribute("uv", new THREE2.BufferAttribute(sec.uv, 2));
460
+ geom.setAttribute("atint", new THREE2.BufferAttribute(sec.colors, 4, true));
461
+ geom.setAttribute("alayer", new THREE2.BufferAttribute(sec.layer, 1, false));
462
+ geom.setAttribute("abiome", new THREE2.BufferAttribute(sec.biome, 1, false));
463
+ geom.setIndex(new THREE2.BufferAttribute(sec.indices, 1));
464
+ const box = quantizedBox(sec);
465
+ geom.boundingBox = box;
466
+ const sphere = new THREE2.Sphere();
467
+ box.getBoundingSphere(sphere);
468
+ geom.boundingSphere = sphere;
469
+ const mesh = new THREE2.Mesh(geom, material);
470
+ const posMin = new THREE2.Vector3(...sec.posMin);
471
+ const posScale = new THREE2.Vector3(...sec.posScale);
472
+ mesh.onBeforeRender = (_r, _s, _c, _g, mat) => {
473
+ const m = mat;
474
+ m.uniforms["uPosMin"].value.copy(posMin);
475
+ m.uniforms["uPosScale"].value.copy(posScale);
476
+ m.uniformsNeedUpdate = true;
477
+ };
478
+ return mesh;
479
+ }
480
+ function buildQuantizedTileMeshes(tile, material, waterMaterial) {
481
+ const terrain = quantizedMesh(tile.solid, material);
482
+ const bounds = terrain.geometry.boundingBox.clone();
483
+ let water;
484
+ if (tile.fluid.vertexCount > 0) {
485
+ water = quantizedMesh(tile.fluid, waterMaterial);
486
+ water.renderOrder = 1;
487
+ bounds.union(water.geometry.boundingBox);
488
+ }
489
+ return { terrain, water, bounds };
490
+ }
491
+ function buildTerrain(tile, texData) {
492
+ const palette = biomePalette(tile.biomeNames?.length ?? 1);
493
+ if (tile.textured) {
494
+ if (!texData) throw new Error("vantage: textured tile requires a texture array");
495
+ const shader = createTerrainMaterial(texData);
496
+ const { terrain: terrain2, water, bounds } = buildTileMeshes(tile, palette, shader, createWaterMaterial(shader));
497
+ return { terrain: terrain2, water, material: shader, shader, bounds, palette, requiresSceneLights: false };
498
+ }
499
+ const geom = baseGeometry(tile);
500
+ geom.setAttribute("color", new THREE2.BufferAttribute(tile.colors, 4, true));
501
+ geom.computeBoundingBox();
502
+ const material = new THREE2.MeshLambertMaterial({ vertexColors: true });
503
+ const terrain = new THREE2.Mesh(geom, material);
504
+ return { terrain, material, bounds: geom.boundingBox.clone(), palette, requiresSceneLights: true };
505
+ }
506
+ function buildLowresMesh(tile, material) {
507
+ const { width, depth, heights, rgb, originX, originZ, span } = tile;
508
+ const n = width * depth;
509
+ const dipBase = Math.min(0.5 + 0.25 * span, 4);
510
+ const pos = new Float32Array(3 * n);
511
+ let minY = Infinity;
512
+ let maxY = -Infinity;
513
+ for (let j = 0; j < depth; j++) {
514
+ for (let i = 0; i < width; i++) {
515
+ const s = j * width + i;
516
+ const h = heights[s];
517
+ let y = 0;
518
+ if (h !== LOWRES_EMPTY) {
519
+ let slope = 0;
520
+ if (i > 0 && heights[s - 1] !== LOWRES_EMPTY) slope = Math.max(slope, Math.abs(h - heights[s - 1]));
521
+ if (i + 1 < width && heights[s + 1] !== LOWRES_EMPTY) slope = Math.max(slope, Math.abs(h - heights[s + 1]));
522
+ if (j > 0 && heights[s - width] !== LOWRES_EMPTY) slope = Math.max(slope, Math.abs(h - heights[s - width]));
523
+ if (j + 1 < depth && heights[s + width] !== LOWRES_EMPTY) slope = Math.max(slope, Math.abs(h - heights[s + width]));
524
+ y = h + 1 - dipBase - Math.min(slope, 12);
525
+ if (y < minY) minY = y;
526
+ if (y > maxY) maxY = y;
527
+ }
528
+ pos[3 * s + 0] = originX + (i + 0.5) * span;
529
+ pos[3 * s + 1] = y;
530
+ pos[3 * s + 2] = originZ + (j + 0.5) * span;
531
+ }
532
+ }
533
+ if (!Number.isFinite(minY)) return null;
534
+ const idx = [];
535
+ for (let j = 0; j + 1 < depth; j++) {
536
+ for (let i = 0; i + 1 < width; i++) {
537
+ const a = j * width + i;
538
+ const b = a + 1;
539
+ const c = a + width;
540
+ const d = c + 1;
541
+ if (heights[a] === LOWRES_EMPTY || heights[b] === LOWRES_EMPTY || heights[c] === LOWRES_EMPTY || heights[d] === LOWRES_EMPTY) continue;
542
+ idx.push(a, c, d, a, d, b);
543
+ }
544
+ }
545
+ if (idx.length === 0) return null;
546
+ const geom = new THREE2.BufferGeometry();
547
+ geom.setAttribute("position", new THREE2.BufferAttribute(pos, 3));
548
+ geom.setAttribute("acol", new THREE2.BufferAttribute(rgb, 3, true));
549
+ const IndexArray = n > 65535 ? Uint32Array : Uint16Array;
550
+ geom.setIndex(new THREE2.BufferAttribute(new IndexArray(idx), 1));
551
+ const box = new THREE2.Box3(
552
+ new THREE2.Vector3(originX, minY, originZ),
553
+ new THREE2.Vector3(originX + width * span, maxY, originZ + depth * span)
554
+ );
555
+ geom.boundingBox = box;
556
+ const sphere = new THREE2.Sphere();
557
+ box.getBoundingSphere(sphere);
558
+ geom.boundingSphere = sphere;
559
+ return new THREE2.Mesh(geom, material);
560
+ }
561
+
562
+ // src/three/emitter.ts
563
+ var Emitter = class {
564
+ listeners = /* @__PURE__ */ new Map();
565
+ on(event, listener) {
566
+ let set = this.listeners.get(event);
567
+ if (!set) {
568
+ set = /* @__PURE__ */ new Set();
569
+ this.listeners.set(event, set);
570
+ }
571
+ set.add(listener);
572
+ return () => set.delete(listener);
573
+ }
574
+ emit(event, payload) {
575
+ const set = this.listeners.get(event);
576
+ if (!set) return;
577
+ for (const listener of set) listener(payload);
578
+ }
579
+ clear() {
580
+ this.listeners.clear();
581
+ }
582
+ };
583
+
584
+ // src/three/tiles.ts
585
+ function recKey(level, x, z) {
586
+ return level === 0 ? tileKey(x, z) : `l${level}:${x},${z}`;
587
+ }
588
+ function releaseAfterUpload(geom) {
589
+ function release() {
590
+ this.array = null;
591
+ }
592
+ for (const name of Object.keys(geom.attributes)) {
593
+ geom.getAttribute(name).onUpload(release);
594
+ }
595
+ if (geom.index) geom.index.onUpload(release);
596
+ }
597
+ var TileManager = class {
598
+ opts;
599
+ lowresMaterial;
600
+ index = /* @__PURE__ */ new Map();
601
+ records = /* @__PURE__ */ new Map();
602
+ emitter = new Emitter();
603
+ tileBlocks;
604
+ /** Lowres pyramid levels, finest first ([] when the manifest has none). */
605
+ lowLevels;
606
+ /** Tile-existence index per lowres level (for the coverage pass). */
607
+ lowIndex = /* @__PURE__ */ new Map();
608
+ /** Set when residency changed and lowres visibility needs recomputing. */
609
+ coverageDirty = false;
610
+ queue = [];
611
+ /** Built tiles awaiting scene insertion — flushed ONE per update() call so
612
+ * multi-MB GPU uploads never pile into a single frame. */
613
+ pendingAdd = [];
614
+ inFlight = 0;
615
+ lastFocusX = Infinity;
616
+ lastFocusZ = Infinity;
617
+ disposed = false;
618
+ /** Fetch-failure counts per record key, surviving record deletion so retry
619
+ * backoff escalates; cleared on success or unload (a fresh pan-in retries). */
620
+ failCounts = /* @__PURE__ */ new Map();
621
+ nextRetrySweep = 0;
622
+ biomesCache = null;
623
+ statsCache = null;
624
+ /** Y range of everything loaded so far, for ray-march bounds. */
625
+ minY = 0;
626
+ maxY = 320;
627
+ constructor(options) {
628
+ const { lowresMaterial, ...rest } = options;
629
+ this.opts = {
630
+ viewDistance: 768,
631
+ // Sized to fill the whole view-distance disc for 128-block tiles
632
+ // (π·(768/128)² ≈ 113) with a little slack — and to match the settings
633
+ // panel's "med" preset exactly.
634
+ maxTiles: 120,
635
+ concurrency: 4,
636
+ ...rest
637
+ };
638
+ this.lowresMaterial = lowresMaterial ?? null;
639
+ this.tileBlocks = options.manifest.tileBlocks;
640
+ for (const t of options.manifest.tiles) this.index.set(tileKey(t.x, t.z), t);
641
+ this.lowLevels = this.lowresMaterial ? [...options.manifest.lowres?.levels ?? []].sort((a, b) => a.level - b.level) : [];
642
+ for (const lvl of this.lowLevels) {
643
+ this.lowIndex.set(lvl.level, new Set(lvl.tiles.map((t) => tileKey(t.x, t.z))));
644
+ }
645
+ }
646
+ /** Tile span in blocks at a pyramid level (0 = hires). */
647
+ levelBlocks(level) {
648
+ if (level === 0) return this.tileBlocks;
649
+ return this.lowLevels.find((l) => l.level === level)?.tileBlocks ?? this.tileBlocks * 2 ** level;
650
+ }
651
+ /** Squared distance from the focus to a tile centre. The re-plan compares
652
+ * and sorts distances over every manifest tile (potentially 10⁵ on a big
653
+ * world), so it stays in squared space — one sqrt per tile is the single
654
+ * hottest thing the planner does. */
655
+ distSqTo(t, level, x, z) {
656
+ const tb = this.levelBlocks(level);
657
+ const dx = (t.x + 0.5) * tb - x;
658
+ const dz = (t.z + 0.5) * tb - z;
659
+ return dx * dx + dz * dz;
660
+ }
661
+ /**
662
+ * Re-plan streaming around the focus point (the controls' pivot / the fly
663
+ * camera). Call every frame — it no-ops until the focus has moved a quarter
664
+ * tile, so the cost is a cheap distance check.
665
+ */
666
+ update(focusX, focusZ) {
667
+ if (this.disposed) return;
668
+ this.flushOne();
669
+ this.retrySweep();
670
+ if (this.coverageDirty) this.applyCoverage();
671
+ const moved = Math.hypot(focusX - this.lastFocusX, focusZ - this.lastFocusZ);
672
+ if (moved < this.tileBlocks / 4) {
673
+ this.pump();
674
+ return;
675
+ }
676
+ this.lastFocusX = focusX;
677
+ this.lastFocusZ = focusZ;
678
+ const { viewDistance, maxTiles } = this.opts;
679
+ const desired = [];
680
+ const viewDistSq = viewDistance * viewDistance;
681
+ for (const t of this.index.values()) {
682
+ const d = this.distSqTo(t, 0, focusX, focusZ);
683
+ if (d <= viewDistSq) desired.push({ t, d });
684
+ }
685
+ desired.sort((a, b) => a.d - b.d);
686
+ if (desired.length > maxTiles) desired.length = maxTiles;
687
+ const desiredKeys = new Set(desired.map(({ t }) => recKey(0, t.x, t.z)));
688
+ const lowDesired = [];
689
+ for (let i = 0; i < this.lowLevels.length; i++) {
690
+ const lvl = this.lowLevels[i];
691
+ const top = i === this.lowLevels.length - 1;
692
+ const outer = top ? Infinity : (viewDistance * 2 ** lvl.level) ** 2;
693
+ const inner = top || i === 0 ? 0 : (viewDistance * 2 ** (lvl.level - 1) * 0.85) ** 2;
694
+ const ring = [];
695
+ for (const t of lvl.tiles) {
696
+ const d = this.distSqTo(t, lvl.level, focusX, focusZ);
697
+ if (d <= outer && d >= inner) ring.push({ ref: t, level: lvl.level, d });
698
+ }
699
+ ring.sort((a, b) => a.d - b.d);
700
+ if (ring.length > 160) ring.length = 160;
701
+ for (const r of ring) {
702
+ lowDesired.push(r);
703
+ desiredKeys.add(recKey(r.level, r.ref.x, r.ref.z));
704
+ }
705
+ }
706
+ for (const [key, rec] of this.records) {
707
+ if (desiredKeys.has(key)) continue;
708
+ const top = this.lowLevels.length > 0 && rec.level === this.lowLevels[this.lowLevels.length - 1].level;
709
+ if (top) continue;
710
+ const d = this.distSqTo(rec.ref, rec.level, focusX, focusZ);
711
+ const keep = rec.level === 0 ? viewDistance * 1.25 : viewDistance * 2 ** rec.level * 1.25;
712
+ if (d > keep * keep) this.unload(key, rec);
713
+ }
714
+ const missing = (level, refs) => refs.filter(({ ref }) => !this.records.has(recKey(level, ref.x, ref.z)));
715
+ const topLevel = this.lowLevels.length > 0 ? this.lowLevels[this.lowLevels.length - 1].level : -1;
716
+ this.queue = [
717
+ ...missing(topLevel, lowDesired.filter((r) => r.level === topLevel)).map((r) => ({ ref: r.ref, level: topLevel })),
718
+ ...missing(0, desired.map((e) => ({ ref: e.t }))).map((r) => ({ ref: r.ref, level: 0 })),
719
+ ...lowDesired.filter((r) => r.level !== topLevel && !this.records.has(recKey(r.level, r.ref.x, r.ref.z))).sort((a, b) => a.level - b.level || a.d - b.d).map((r) => ({ ref: r.ref, level: r.level }))
720
+ ];
721
+ this.pump();
722
+ }
723
+ pump() {
724
+ while (this.inFlight < this.opts.concurrency && this.queue.length > 0) {
725
+ const { ref, level } = this.queue.shift();
726
+ if (level === 0) void this.loadTile(ref);
727
+ else void this.loadLowres(ref, level);
728
+ }
729
+ }
730
+ /** Insert built tiles into the scene at a bounded per-frame rate (via
731
+ * update()), so GPU buffer uploads are spread across frames instead of
732
+ * bursting. Normally one per frame; when a backlog builds (a big preset
733
+ * loading hundreds of tiles) it drains faster so the map sharpens in a
734
+ * couple of seconds instead of many. */
735
+ flushOne() {
736
+ let budget = this.pendingAdd.length > 24 ? 3 : this.pendingAdd.length > 8 ? 2 : 1;
737
+ while (this.pendingAdd.length > 0 && budget > 0) {
738
+ const key = this.pendingAdd.shift();
739
+ const rec = this.records.get(key);
740
+ if (!rec || rec.state !== "built") continue;
741
+ rec.state = "ready";
742
+ this.opts.scene.add(rec.terrain);
743
+ if (rec.water) this.opts.scene.add(rec.water);
744
+ this.coverageDirty = true;
745
+ this.invalidate();
746
+ this.emitter.emit("change", this.stats);
747
+ budget--;
748
+ }
749
+ }
750
+ /**
751
+ * Hide every lowres tile whose footprint is fully SHOWN by finer data.
752
+ * "Shown" is transitive, computed bottom-up: a hires tile shows its area by
753
+ * being resident; a lowres tile's area is shown if the tile is resident OR
754
+ * all of its existing children's areas are shown (so a coarse blanket tile
755
+ * hides when hires covers it even if the middle rings were never fetched).
756
+ *
757
+ * This is what keeps the underlay honest: a smooth interpolated heightfield
758
+ * coexisting with real voxel terrain leaks through everything hires
759
+ * deliberately opens — cave-culled pockets, ravines, underwater cliffs,
760
+ * gaps in tree canopies. Where finer data is on screen, the underlay is
761
+ * simply switched off; it reappears the moment coverage breaks (unload,
762
+ * ring edge, loading).
763
+ */
764
+ applyCoverage() {
765
+ this.coverageDirty = false;
766
+ let shown = /* @__PURE__ */ new Set();
767
+ for (const rec of this.records.values()) {
768
+ if (rec.level === 0 && rec.state === "ready") shown.add(tileKey(rec.ref.x, rec.ref.z));
769
+ }
770
+ let finerIndex = this.index;
771
+ for (const lvl of this.lowLevels) {
772
+ const shownHere = /* @__PURE__ */ new Set();
773
+ for (const t of lvl.tiles) {
774
+ let covered = true;
775
+ for (let dz = 0; dz < 2 && covered; dz++) {
776
+ for (let dx = 0; dx < 2 && covered; dx++) {
777
+ const childKey = tileKey(t.x * 2 + dx, t.z * 2 + dz);
778
+ if (finerIndex.has(childKey) && !shown.has(childKey)) covered = false;
779
+ }
780
+ }
781
+ const rec = this.records.get(recKey(lvl.level, t.x, t.z));
782
+ const ready = rec?.state === "ready";
783
+ if (ready && rec.terrain) rec.terrain.visible = !covered;
784
+ if (ready || covered) shownHere.add(tileKey(t.x, t.z));
785
+ }
786
+ shown = shownHere;
787
+ finerIndex = this.lowIndex.get(lvl.level) ?? /* @__PURE__ */ new Set();
788
+ }
789
+ }
790
+ /** Live-tune streaming (view distance, tile budget, fetch concurrency).
791
+ * Takes effect on the next update(): the plan is recomputed from scratch. */
792
+ configure(settings) {
793
+ if (settings.viewDistance !== void 0) this.opts.viewDistance = settings.viewDistance;
794
+ if (settings.maxTiles !== void 0) this.opts.maxTiles = settings.maxTiles;
795
+ if (settings.concurrency !== void 0) this.opts.concurrency = settings.concurrency;
796
+ this.lastFocusX = Infinity;
797
+ this.lastFocusZ = Infinity;
798
+ }
799
+ /** The current stream-in radius, in blocks. */
800
+ get viewDistance() {
801
+ return this.opts.viewDistance;
802
+ }
803
+ /** The current resident-tile budget. */
804
+ get maxTiles() {
805
+ return this.opts.maxTiles;
806
+ }
807
+ /** Fetch + decode one lowres LOD tile into a heightfield mesh. */
808
+ async loadLowres(ref, level) {
809
+ const key = recKey(level, ref.x, ref.z);
810
+ if (this.records.has(key) || !this.lowresMaterial) return;
811
+ const abort = new AbortController();
812
+ const rec = { ref, level, state: "loading", abort, vertexCount: 0, triangleCount: 0 };
813
+ this.records.set(key, rec);
814
+ this.inFlight++;
815
+ try {
816
+ const url = new URL(ref.path, this.opts.baseUrl).toString();
817
+ const res = await fetch(url, { signal: abort.signal });
818
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
819
+ const tile = parseLowresTile(await maybeInflate(await res.arrayBuffer()));
820
+ if (this.disposed || rec.state !== "loading") return;
821
+ const mesh = buildLowresMesh(tile, this.lowresMaterial);
822
+ if (!mesh) {
823
+ rec.state = "empty";
824
+ return;
825
+ }
826
+ mesh.renderOrder = -level;
827
+ releaseAfterUpload(mesh.geometry);
828
+ rec.terrain = mesh;
829
+ rec.low = {
830
+ originX: tile.originX,
831
+ originZ: tile.originZ,
832
+ span: tile.span,
833
+ width: tile.width,
834
+ depth: tile.depth,
835
+ heights: tile.heights.slice()
836
+ };
837
+ rec.vertexCount = tile.width * tile.depth;
838
+ rec.triangleCount = mesh.geometry.index.count / 3;
839
+ rec.state = "built";
840
+ this.failCounts.delete(key);
841
+ this.pendingAdd.push(key);
842
+ this.invalidate();
843
+ this.emitter.emit("change", this.stats);
844
+ } catch (e) {
845
+ if (e.name !== "AbortError") {
846
+ this.markFailed(key, rec);
847
+ console.warn(`vantage: lowres tile ${key} failed to load:`, e);
848
+ }
849
+ } finally {
850
+ this.inFlight--;
851
+ this.pump();
852
+ }
853
+ }
854
+ /** A transient failure (network blip, 5xx) retries with exponential backoff
855
+ * while the tile stays in view — otherwise one blip is a permanent hole in
856
+ * the map until the user pans away and back. Capped so a genuinely bad tile
857
+ * (corrupt file, future format) settles instead of hammering the server.
858
+ * Attempt counts live outside the record because a retry deletes it. */
859
+ markFailed(key, rec) {
860
+ rec.state = "failed";
861
+ const attempts = (this.failCounts.get(key) ?? 0) + 1;
862
+ this.failCounts.set(key, attempts);
863
+ rec.retryAt = attempts >= 5 ? Infinity : performance.now() + 2e3 * 2 ** (attempts - 1);
864
+ }
865
+ /** Re-queue failed records whose backoff has expired (cheap; throttled). */
866
+ retrySweep() {
867
+ const now = performance.now();
868
+ if (now < this.nextRetrySweep) return;
869
+ this.nextRetrySweep = now + 500;
870
+ for (const [key, rec] of this.records) {
871
+ if (rec.state !== "failed" || now < (rec.retryAt ?? Infinity)) continue;
872
+ this.records.delete(key);
873
+ this.queue.push({ ref: rec.ref, level: rec.level });
874
+ }
875
+ }
876
+ async loadTile(ref) {
877
+ const key = tileKey(ref.x, ref.z);
878
+ if (this.records.has(key)) return;
879
+ const abort = new AbortController();
880
+ const rec = { ref, level: 0, state: "loading", abort, vertexCount: 0, triangleCount: 0 };
881
+ this.records.set(key, rec);
882
+ this.inFlight++;
883
+ try {
884
+ const url = new URL(ref.path, this.opts.baseUrl).toString();
885
+ const res = await fetch(url, { signal: abort.signal });
886
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
887
+ const buffer = await maybeInflate(await res.arrayBuffer());
888
+ if (this.disposed || rec.state !== "loading") return;
889
+ let meshes;
890
+ const q = parseTileQuantized(buffer);
891
+ if (q) {
892
+ rec.biomes = summarizeSurfaceBiomes(q.surface, q.biomeNames, this.opts.palette);
893
+ rec.surface = { ...q.surface, biome: q.surface.biome.slice(), height: q.surface.height.slice() };
894
+ meshes = buildQuantizedTileMeshes(q, this.opts.material, this.opts.waterMaterial);
895
+ rec.vertexCount = q.solid.vertexCount + q.fluid.vertexCount;
896
+ rec.triangleCount = (q.solid.indexCount + q.fluid.indexCount) / 3;
897
+ } else {
898
+ const tile = parseTile(buffer);
899
+ rec.biomes = summarizeBiomes(tile, this.opts.palette);
900
+ rec.surface = tile.surface ? { ...tile.surface, biome: tile.surface.biome.slice(), height: tile.surface.height.slice() } : void 0;
901
+ meshes = buildTileMeshes(tile, this.opts.palette, this.opts.material, this.opts.waterMaterial);
902
+ meshes.terrain.geometry.computeBoundingSphere();
903
+ meshes.water?.geometry.computeBoundingSphere();
904
+ rec.vertexCount = tile.vertexCount + (tile.fluid?.vertexCount ?? 0);
905
+ rec.triangleCount = (tile.indexCount + (tile.fluid?.indexCount ?? 0)) / 3;
906
+ }
907
+ releaseAfterUpload(meshes.terrain.geometry);
908
+ if (meshes.water) releaseAfterUpload(meshes.water.geometry);
909
+ rec.terrain = meshes.terrain;
910
+ rec.water = meshes.water;
911
+ this.minY = Math.min(this.minY, meshes.bounds.min.y);
912
+ this.maxY = Math.max(this.maxY, meshes.bounds.max.y);
913
+ rec.state = "built";
914
+ this.failCounts.delete(key);
915
+ this.pendingAdd.push(key);
916
+ this.invalidate();
917
+ this.emitter.emit("change", this.stats);
918
+ } catch (e) {
919
+ if (e.name !== "AbortError") {
920
+ this.markFailed(key, rec);
921
+ console.warn(`vantage: tile ${key} failed to load:`, e);
922
+ }
923
+ } finally {
924
+ this.inFlight--;
925
+ this.pump();
926
+ }
927
+ }
928
+ unload(key, rec) {
929
+ rec.abort?.abort();
930
+ for (const mesh of [rec.terrain, rec.water]) {
931
+ if (!mesh) continue;
932
+ this.opts.scene.remove(mesh);
933
+ mesh.geometry.dispose();
934
+ }
935
+ this.records.delete(key);
936
+ this.failCounts.delete(key);
937
+ this.coverageDirty = true;
938
+ this.invalidate();
939
+ this.emitter.emit("change", this.stats);
940
+ }
941
+ invalidate() {
942
+ this.biomesCache = null;
943
+ this.statsCache = null;
944
+ }
945
+ // --- world-level queries ---------------------------------------------------
946
+ /** Live totals across resident tiles. */
947
+ get stats() {
948
+ if (this.statsCache) return this.statsCache;
949
+ let loaded = 0;
950
+ let loading = 0;
951
+ let lowres = 0;
952
+ let vertexCount = 0;
953
+ let triangleCount = 0;
954
+ let bytes = 0;
955
+ for (const rec of this.records.values()) {
956
+ if (rec.state === "ready") {
957
+ if (rec.level === 0) loaded++;
958
+ else lowres++;
959
+ vertexCount += rec.vertexCount;
960
+ triangleCount += rec.triangleCount;
961
+ bytes += rec.ref.bytes;
962
+ } else if (rec.state === "loading" || rec.state === "built") loading++;
963
+ }
964
+ this.statsCache = { loaded, loading, total: this.index.size, lowres, vertexCount, triangleCount, bytes };
965
+ return this.statsCache;
966
+ }
967
+ /** Aggregated biome share across every resident tile, most common first. */
968
+ get biomes() {
969
+ if (this.biomesCache) return this.biomesCache;
970
+ const byId = /* @__PURE__ */ new Map();
971
+ let total = 0;
972
+ for (const rec of this.records.values()) {
973
+ if (!rec.biomes) continue;
974
+ for (const e of rec.biomes) {
975
+ const agg = byId.get(e.id);
976
+ if (agg) agg.count += e.count;
977
+ else byId.set(e.id, { ...e });
978
+ total += e.count;
979
+ }
980
+ }
981
+ const out = [...byId.values()].sort((a, b) => b.count - a.count);
982
+ const denom = total || 1;
983
+ for (const e of out) e.fraction = e.count / denom;
984
+ this.biomesCache = out;
985
+ return out;
986
+ }
987
+ /** The surface map cell under world (x,z), from whichever tile owns it. */
988
+ surfaceAt(x, z) {
989
+ const rec = this.records.get(tileKey(Math.floor(x / this.tileBlocks), Math.floor(z / this.tileBlocks)));
990
+ const surf = rec?.state === "ready" ? rec.surface : void 0;
991
+ if (!surf) return null;
992
+ const cx = Math.floor(x - surf.originX);
993
+ const cz = Math.floor(z - surf.originZ);
994
+ if (cx < 0 || cz < 0 || cx >= surf.width || cz >= surf.depth) return null;
995
+ return { surf, idx: cz * surf.width + cx };
996
+ }
997
+ /** Lightly smoothed terrain height at world (x,z) for the terrain-riding
998
+ * pivot; falls back to the lowres heightfields (finest resident level)
999
+ * beyond the hires ring, so the pivot still rides the terrain when zoomed
1000
+ * out. Null when nothing at all is resident there. */
1001
+ heightAt = (x, z) => {
1002
+ const R = 2;
1003
+ let sum = 0;
1004
+ let n = 0;
1005
+ for (let dz = -R; dz <= R; dz++) {
1006
+ for (let dx = -R; dx <= R; dx++) {
1007
+ const hit = this.surfaceAt(x + dx, z + dz);
1008
+ if (!hit) continue;
1009
+ const h = hit.surf.height[hit.idx];
1010
+ if (h < 1) continue;
1011
+ sum += h;
1012
+ n++;
1013
+ }
1014
+ }
1015
+ if (n > 0) return sum / n;
1016
+ return this.lowresHeightAt(x, z);
1017
+ };
1018
+ /** Height from the finest resident lowres level covering (x,z), or null. */
1019
+ lowresHeightAt(x, z) {
1020
+ for (const lvl of this.lowLevels) {
1021
+ const tb = lvl.tileBlocks;
1022
+ const rec = this.records.get(recKey(lvl.level, Math.floor(x / tb), Math.floor(z / tb)));
1023
+ const low = rec?.state === "ready" ? rec.low : void 0;
1024
+ if (!low) continue;
1025
+ const cx = Math.min(Math.max(Math.floor((x - low.originX) / low.span), 0), low.width - 1);
1026
+ const cz = Math.min(Math.max(Math.floor((z - low.originZ) / low.span), 0), low.depth - 1);
1027
+ const h = low.heights[cz * low.width + cx];
1028
+ if (h !== LOWRES_EMPTY) return h;
1029
+ }
1030
+ return null;
1031
+ }
1032
+ /** March the ray across resident tiles' surface maps; the biome id at the
1033
+ * first column the ray drops below, or -1. O(ray length), tile-count-free. */
1034
+ pickBiome(ray) {
1035
+ let t = 0;
1036
+ if (ray.origin.y > this.maxY + 2 && ray.direction.y < 0) {
1037
+ t = (this.maxY + 2 - ray.origin.y) / ray.direction.y;
1038
+ }
1039
+ const span = this.opts.viewDistance * 2.5;
1040
+ for (; t <= span; t += 0.5) {
1041
+ const x = ray.origin.x + ray.direction.x * t;
1042
+ const y = ray.origin.y + ray.direction.y * t;
1043
+ const z = ray.origin.z + ray.direction.z * t;
1044
+ if (y < this.minY - 2 && ray.direction.y < 0) return -1;
1045
+ const hit = this.surfaceAt(x, z);
1046
+ if (!hit) continue;
1047
+ const h = hit.surf.height[hit.idx];
1048
+ if (h >= 1 && y <= h + 1) return hit.surf.biome[hit.idx];
1049
+ }
1050
+ return -1;
1051
+ }
1052
+ // --- events / lifecycle ----------------------------------------------------
1053
+ on(event, listener) {
1054
+ return this.emitter.on(event, listener);
1055
+ }
1056
+ /** Abort every fetch, remove and dispose every mesh. */
1057
+ dispose() {
1058
+ this.disposed = true;
1059
+ this.queue = [];
1060
+ this.pendingAdd = [];
1061
+ for (const [key, rec] of [...this.records]) this.unload(key, rec);
1062
+ this.emitter.clear();
1063
+ }
1064
+ };
1065
+ var _entry = new THREE2.Vector3();
1066
+ function pickBiome(ray, surf, bounds) {
1067
+ let t = 0;
1068
+ if (!bounds.containsPoint(ray.origin)) {
1069
+ if (!ray.intersectBox(bounds, _entry)) return -1;
1070
+ t = ray.origin.distanceTo(_entry);
1071
+ }
1072
+ const maxT = t + bounds.min.distanceTo(bounds.max) + 4;
1073
+ for (; t <= maxT; t += 0.5) {
1074
+ const x = ray.origin.x + ray.direction.x * t;
1075
+ const y = ray.origin.y + ray.direction.y * t;
1076
+ const z = ray.origin.z + ray.direction.z * t;
1077
+ const cxi = Math.floor(x - surf.originX);
1078
+ const czi = Math.floor(z - surf.originZ);
1079
+ if (cxi < 0 || czi < 0 || cxi >= surf.width || czi >= surf.depth) continue;
1080
+ const idx = czi * surf.width + cxi;
1081
+ if (y <= surf.height[idx] + 1) return surf.biome[idx];
1082
+ }
1083
+ return -1;
1084
+ }
1085
+ var HALF_PI = Math.PI * 0.5;
1086
+ var HALF_PI_DIV = 1 / HALF_PI;
1087
+ function clamp(v, lo, hi) {
1088
+ return v < lo ? lo : v > hi ? hi : v;
1089
+ }
1090
+ function softMin(v, min, k) {
1091
+ return v >= min ? v : v + (min - v) * k;
1092
+ }
1093
+ function softMax(v, max, k) {
1094
+ return v <= max ? v : v - (v - max) * k;
1095
+ }
1096
+ function softClamp(v, min, max, k) {
1097
+ return softMax(softMin(v, min, k), max, k);
1098
+ }
1099
+ function softSet(v, target, k) {
1100
+ return softClamp(v, target, target, k);
1101
+ }
1102
+ var MapControls = class _MapControls {
1103
+ camera;
1104
+ domElement;
1105
+ // --- the state model -------------------------------------------------------
1106
+ /** The look-at pivot in world space (camera orbits and zooms about this). */
1107
+ position = new THREE2.Vector3();
1108
+ /** Camera-to-pivot distance: this IS the zoom level. */
1109
+ distance = 300;
1110
+ /** Azimuth in radians; 0 looks toward −Z (north). Wrapped to [−π, π]. */
1111
+ rotation = 0;
1112
+ /** Pitch in radians; 0 = straight top-down, π/2 = horizon, π = straight up. */
1113
+ angle = 0;
1114
+ /** Active control scheme. `'map'` orbits/pans a ground pivot (distance > 0);
1115
+ * `'fly'` is a free-flight spectator camera — the eye sits AT `position`
1116
+ * (distance 0), full perspective, pitch free across the whole sky. Both
1117
+ * modes share one camera state. */
1118
+ mode = "map";
1119
+ /** Free-flight move speed; the wheel scales it (0.05‥5) while in `'fly'`. */
1120
+ moveSpeed = 0.5;
1121
+ // --- bounds & wiring -------------------------------------------------------
1122
+ minDistance;
1123
+ maxDistance;
1124
+ /** Optional terrain sampler; when set the pivot rides the surface. */
1125
+ heightAt = null;
1126
+ /** Pivot Y the view relaxes toward when zoomed far out (set by the framer). */
1127
+ floorY = 0;
1128
+ /** Master enable. */
1129
+ enabled = true;
1130
+ // --- input buffers (summed by events, drained by `update`) -----------------
1131
+ panBuf = new THREE2.Vector2();
1132
+ rotBuf = 0;
1133
+ angleBuf = 0;
1134
+ zoomBuf = 0;
1135
+ // Free-flight input: `lookBuf` accumulates pointer/key px deltas (yaw, pitch);
1136
+ // `moveBuf` accumulates WASD/▲▼/space-shift direction. Both drain through the
1137
+ // same inertia model as the map buffers, so fly motion glides like the map.
1138
+ lookBuf = new THREE2.Vector2();
1139
+ moveBuf = new THREE2.Vector3();
1140
+ lastLook = new THREE2.Vector2();
1141
+ pointerLocked = false;
1142
+ flyPointerDown = false;
1143
+ savedDistance = 0;
1144
+ // map dolly remembered across a fly excursion
1145
+ // Pointer-drag bookkeeping.
1146
+ pointers = /* @__PURE__ */ new Map();
1147
+ lastPan = new THREE2.Vector2();
1148
+ lastOrbit = new THREE2.Vector2();
1149
+ orbiting = false;
1150
+ // right-drag / alt-left-drag is rotating+tilting
1151
+ panning = false;
1152
+ // left-drag is moving the pivot
1153
+ startDistance = 0;
1154
+ // dolly at orbit start, for the coupled tilt↔zoom
1155
+ dynamicDistance = false;
1156
+ // tilt pulls the camera in (only when close)
1157
+ moved = false;
1158
+ // any drag actually moved (vs. a click) — for tap detect
1159
+ downPos = new THREE2.Vector2();
1160
+ // Scratch for cursor→ground projection (the anchored pan). `panBuf` holds a
1161
+ // WORLD-space shift (not pixels): the amount that keeps the grabbed ground
1162
+ // point pinned under the cursor, accumulated per event and drained with inertia.
1163
+ _ndc = new THREE2.Vector3();
1164
+ // Scratch for updateCamera() — it runs every frame, so no per-call allocs.
1165
+ _orbitV = new THREE2.Vector3();
1166
+ _orbitAxis = new THREE2.Vector3();
1167
+ _gpA = new THREE2.Vector2();
1168
+ _gpB = new THREE2.Vector2();
1169
+ // Two-finger touch pinch/rotate bookkeeping.
1170
+ touchDist = 0;
1171
+ touchAngle = 0;
1172
+ keys = /* @__PURE__ */ new Set();
1173
+ // dt smoothing: clamp spikes and EMA the frame time.
1174
+ avgDt = 16;
1175
+ // Terrain-follow state, temporally smoothed: the
1176
+ // surface height under the pivot, and the surface height under the camera (for
1177
+ // the min-camera-height clearance term).
1178
+ targetHeight = 0;
1179
+ cameraHeight = 0;
1180
+ // An optional eased target (compass "reset north", zoom buttons, home), drained
1181
+ // each frame and cleared on any fresh user input.
1182
+ goal = null;
1183
+ listeners = {
1184
+ start: /* @__PURE__ */ new Set(),
1185
+ end: /* @__PURE__ */ new Set(),
1186
+ change: /* @__PURE__ */ new Set()
1187
+ };
1188
+ // Bound handlers, kept for removal in dispose().
1189
+ onPointerDown;
1190
+ onPointerMove;
1191
+ onPointerUp;
1192
+ onWheel;
1193
+ onContextMenu;
1194
+ onKeyDown;
1195
+ onKeyUp;
1196
+ onBlur;
1197
+ onPointerLockChange;
1198
+ constructor(camera, domElement, options = {}) {
1199
+ this.camera = camera;
1200
+ this.domElement = domElement;
1201
+ this.minDistance = options.minDistance ?? 4;
1202
+ this.maxDistance = options.maxDistance ?? 1e5;
1203
+ this.onPointerDown = (e) => this.pointerDown(e);
1204
+ this.onPointerMove = (e) => this.pointerMove(e);
1205
+ this.onPointerUp = (e) => this.pointerUp(e);
1206
+ this.onWheel = (e) => this.wheel(e);
1207
+ this.onContextMenu = (e) => e.preventDefault();
1208
+ this.onKeyDown = (e) => this.keyDown(e);
1209
+ this.onKeyUp = (e) => this.keyUp(e);
1210
+ this.onBlur = () => {
1211
+ this.keys.clear();
1212
+ this.pointers.clear();
1213
+ this.endDrag();
1214
+ };
1215
+ this.onPointerLockChange = () => {
1216
+ this.pointerLocked = document.pointerLockElement === this.domElement;
1217
+ if (!this.pointerLocked) this.lookBuf.set(0, 0);
1218
+ };
1219
+ const dom = domElement;
1220
+ dom.style.touchAction = "none";
1221
+ dom.addEventListener("pointerdown", this.onPointerDown);
1222
+ window.addEventListener("pointermove", this.onPointerMove, { passive: false });
1223
+ window.addEventListener("pointerup", this.onPointerUp);
1224
+ window.addEventListener("pointercancel", this.onPointerUp);
1225
+ dom.addEventListener("wheel", this.onWheel, { passive: false });
1226
+ dom.addEventListener("contextmenu", this.onContextMenu);
1227
+ window.addEventListener("keydown", this.onKeyDown);
1228
+ window.addEventListener("keyup", this.onKeyUp);
1229
+ window.addEventListener("blur", this.onBlur);
1230
+ document.addEventListener("pointerlockchange", this.onPointerLockChange);
1231
+ this.updateCamera();
1232
+ }
1233
+ // --- public API ------------------------------------------------------------
1234
+ addEventListener(type, fn) {
1235
+ this.listeners[type]?.add(fn);
1236
+ }
1237
+ removeEventListener(type, fn) {
1238
+ this.listeners[type]?.delete(fn);
1239
+ }
1240
+ emit(type) {
1241
+ for (const fn of this.listeners[type]) fn();
1242
+ }
1243
+ /** Compatibility alias: the look-at pivot (some callers still read `.target`). */
1244
+ get target() {
1245
+ return this.position;
1246
+ }
1247
+ /** True while a drag (pan or orbit) is in progress. */
1248
+ get isInteracting() {
1249
+ return this.panning || this.orbiting;
1250
+ }
1251
+ /** Smoothly zoom by `steps` notches (positive = in, negative = out) — the same
1252
+ * unit as a wheel notch, so the zoom buttons match scrolling. */
1253
+ zoom(steps) {
1254
+ this.zoomBuf -= steps;
1255
+ this.dynamicDistance = false;
1256
+ this.goal = null;
1257
+ }
1258
+ /** True when the free-flight (spectator) camera is active. */
1259
+ get flyMode() {
1260
+ return this.mode === "fly";
1261
+ }
1262
+ /** Whether the pointer is currently captured for mouse-look. */
1263
+ get isPointerLocked() {
1264
+ return this.pointerLocked;
1265
+ }
1266
+ /** Switch control scheme, transitioning the camera continuously. Entering
1267
+ * `'fly'` reinterprets the current eye as the free-flight position (the view
1268
+ * doesn't jump); exiting drops the orbit pivot back onto the point the eye
1269
+ * looks at, at the remembered dolly distance. */
1270
+ setMode(mode) {
1271
+ if (mode === this.mode) return;
1272
+ this.endDrag();
1273
+ this.goal = null;
1274
+ if (mode === "fly") {
1275
+ this.savedDistance = this.distance;
1276
+ this.position.copy(this.camera.position);
1277
+ this.distance = 0;
1278
+ this.moveBuf.set(0, 0, 0);
1279
+ this.lookBuf.set(0, 0);
1280
+ this.mode = "fly";
1281
+ } else {
1282
+ this.mode = "map";
1283
+ const dist = this.savedDistance > this.minDistance ? this.savedDistance : 200;
1284
+ this.distance = clamp(dist, this.minDistance, this.maxDistance);
1285
+ this.angle = clamp(this.angle, 0, this.maxAngleForDistance(this.distance));
1286
+ this.position.add(this.lookDir().multiplyScalar(this.distance));
1287
+ this.targetHeight = this.cameraHeight = this.position.y;
1288
+ this.exitPointerLock();
1289
+ }
1290
+ this.updateCamera();
1291
+ }
1292
+ /** Toggle between map and free-flight. */
1293
+ toggleFly() {
1294
+ this.setMode(this.mode === "fly" ? "map" : "fly");
1295
+ }
1296
+ /** The unit forward (look) direction from yaw `rotation` + pitch `angle`. */
1297
+ lookDir() {
1298
+ const sa = Math.sin(this.angle);
1299
+ return new THREE2.Vector3(Math.sin(this.rotation) * sa, -Math.cos(this.angle), -Math.cos(this.rotation) * sa);
1300
+ }
1301
+ /** Capture the pointer for mouse-look (free-flight). Prefers raw/unaccelerated
1302
+ * movement, falling back to standard capture where unsupported. */
1303
+ requestPointerLock() {
1304
+ const el = this.domElement;
1305
+ try {
1306
+ const r = el.requestPointerLock?.({ unadjustedMovement: true });
1307
+ if (r && typeof r.catch === "function") {
1308
+ r.catch(() => {
1309
+ try {
1310
+ el.requestPointerLock?.();
1311
+ } catch {
1312
+ }
1313
+ });
1314
+ }
1315
+ } catch {
1316
+ }
1317
+ }
1318
+ exitPointerLock() {
1319
+ if (document.pointerLockElement === this.domElement) document.exitPointerLock?.();
1320
+ }
1321
+ /** Ease the view toward a partial target state (rotation/angle/distance/pivot),
1322
+ * e.g. compass→north or a home re-frame. Cancelled by any drag, key, or wheel. */
1323
+ animateTo(goal) {
1324
+ this.goal = {
1325
+ ...goal,
1326
+ position: goal.position ? goal.position.clone() : void 0
1327
+ };
1328
+ }
1329
+ /** Jump the view to an explicit state and stop all motion (used for framing).
1330
+ * `angle`/`distance` are clamped to the legal tilt envelope. */
1331
+ setView(state) {
1332
+ this.goal = null;
1333
+ this.position.copy(state.position);
1334
+ this.distance = clamp(state.distance, this.minDistance, this.maxDistance);
1335
+ this.rotation = state.rotation;
1336
+ this.angle = clamp(state.angle, 0, this.maxAngleForDistance(this.distance));
1337
+ if (state.floorY !== void 0) this.floorY = state.floorY;
1338
+ this.targetHeight = this.position.y;
1339
+ this.cameraHeight = this.position.y;
1340
+ this.panBuf.set(0, 0);
1341
+ this.rotBuf = this.angleBuf = this.zoomBuf = 0;
1342
+ this.updateCamera();
1343
+ }
1344
+ /** Advance the simulation by `deltaMs` and update the camera. Returns whether
1345
+ * anything moved this frame. */
1346
+ update(deltaMs) {
1347
+ const dt = deltaMs > 50 ? 50 : deltaMs <= 0 ? 16 : deltaMs;
1348
+ this.avgDt = this.avgDt * 0.9 + dt * 0.1;
1349
+ const d = this.avgDt;
1350
+ const before = this.changeKey();
1351
+ if (this.mode === "fly") {
1352
+ this.feedKeys(d);
1353
+ this.applyFlyLook(d);
1354
+ this.applyFlyMove(d);
1355
+ this.applyGoal(d);
1356
+ this.applyFlyBounds();
1357
+ } else {
1358
+ this.feedKeys(d);
1359
+ this.applyPan(d);
1360
+ this.applyRotate(d);
1361
+ this.applyAngle(d);
1362
+ this.applyZoom(d);
1363
+ this.applyDynamicDistance();
1364
+ this.applyGoal(d);
1365
+ this.applyBounds();
1366
+ this.applyHeight(d);
1367
+ }
1368
+ this.updateCamera();
1369
+ const changed = this.changeKey() !== before;
1370
+ if (changed) this.emit("change");
1371
+ return changed;
1372
+ }
1373
+ dispose() {
1374
+ const dom = this.domElement;
1375
+ dom.removeEventListener("pointerdown", this.onPointerDown);
1376
+ window.removeEventListener("pointermove", this.onPointerMove);
1377
+ window.removeEventListener("pointerup", this.onPointerUp);
1378
+ window.removeEventListener("pointercancel", this.onPointerUp);
1379
+ dom.removeEventListener("wheel", this.onWheel);
1380
+ dom.removeEventListener("contextmenu", this.onContextMenu);
1381
+ window.removeEventListener("keydown", this.onKeyDown);
1382
+ window.removeEventListener("keyup", this.onKeyUp);
1383
+ window.removeEventListener("blur", this.onBlur);
1384
+ document.removeEventListener("pointerlockchange", this.onPointerLockChange);
1385
+ if (this.pointerLocked) document.exitPointerLock?.();
1386
+ for (const set of Object.values(this.listeners)) set.clear();
1387
+ }
1388
+ // --- per-frame smoothing factor --------------------------------------------
1389
+ /** `stiffness` is the per-frame lerp at 60fps, scaled by
1390
+ * the (averaged) frame time so feel is frame-rate independent. */
1391
+ smoothing(stiffness, dt) {
1392
+ return clamp(stiffness / (16.666 / dt), 0, 1);
1393
+ }
1394
+ /** Max tilt (radians from top-down) allowed at a dolly distance, scaled to
1395
+ * *this* world's zoom range: full tilt up close, eased to a flat top-down
1396
+ * exactly at `maxDistance` — so zooming all the way out always levels the
1397
+ * view, whatever the world's size. */
1398
+ maxAngleForDistance(distance) {
1399
+ const span = Math.max(this.maxDistance - this.minDistance, 1);
1400
+ const t = clamp((distance - this.minDistance) / span, 0, 1);
1401
+ return clamp((1 - Math.sqrt(t)) * HALF_PI, 0, HALF_PI);
1402
+ }
1403
+ /** Inverse: the farthest distance at which `angle` is still a legal tilt. */
1404
+ maxDistanceForAngle(angle) {
1405
+ const t = Math.pow(clamp(1 - angle * HALF_PI_DIV, 0, 1), 2);
1406
+ return this.minDistance + t * (this.maxDistance - this.minDistance);
1407
+ }
1408
+ // --- motion application (drains the buffers) -------------------------------
1409
+ applyPan(dt) {
1410
+ if (this.panBuf.lengthSq() < 1e-9) {
1411
+ this.panBuf.set(0, 0);
1412
+ return;
1413
+ }
1414
+ const s = this.smoothing(0.55, dt);
1415
+ this.position.x += this.panBuf.x * s;
1416
+ this.position.z += this.panBuf.y * s;
1417
+ this.panBuf.multiplyScalar(1 - s);
1418
+ }
1419
+ applyRotate(dt) {
1420
+ if (this.rotBuf === 0) return;
1421
+ const s = this.smoothing(0.3, dt);
1422
+ const w = this.domElement.clientWidth || 1;
1423
+ this.rotation += this.rotBuf * s * 6 / w;
1424
+ this.rotBuf *= 1 - s;
1425
+ if (Math.abs(this.rotBuf) < 1e-4) this.rotBuf = 0;
1426
+ }
1427
+ applyAngle(dt) {
1428
+ if (this.angleBuf === 0) return;
1429
+ const s = this.smoothing(0.3, dt);
1430
+ const h = this.domElement.clientHeight || 1;
1431
+ this.angle += this.angleBuf * s * 3 / h;
1432
+ this.angleBuf *= 1 - s;
1433
+ if (Math.abs(this.angleBuf) < 1e-4) this.angleBuf = 0;
1434
+ }
1435
+ applyZoom(dt) {
1436
+ if (this.zoomBuf === 0) return;
1437
+ const s = this.smoothing(0.2, dt);
1438
+ this.distance *= Math.pow(1.5, this.zoomBuf * s);
1439
+ this.angle = Math.min(this.angle, this.maxAngleForDistance(this.distance));
1440
+ this.zoomBuf *= 1 - s;
1441
+ if (Math.abs(this.zoomBuf) < 1e-4) this.zoomBuf = 0;
1442
+ }
1443
+ /** While orbiting from a close-in view, tilting toward the horizon also dollies
1444
+ * the camera in so the requested tilt becomes legal (a coupled dolly+pitch).
1445
+ * A wheel event cancels it (you asked for a specific distance). */
1446
+ applyDynamicDistance() {
1447
+ if (!this.orbiting || !this.dynamicDistance) return;
1448
+ let target = Math.min(this.startDistance, this.maxDistanceForAngle(this.angle));
1449
+ target = Math.max(target, this.minDistance);
1450
+ this.distance = softSet(this.distance, target, 0.4);
1451
+ this.angle = softMax(this.angle, this.maxAngleForDistance(target), 0.8);
1452
+ }
1453
+ // --- free-flight motion ----------------------------------------------------
1454
+ /** Drain the look buffer into yaw/pitch (mouse-look + Q/E/R/F keys), smoothed
1455
+ * like every other motion. Pixel deltas are normalized to screen height so
1456
+ * sensitivity is resolution-independent. */
1457
+ applyFlyLook(dt) {
1458
+ if (this.lookBuf.lengthSq() < 1e-6) {
1459
+ this.lookBuf.set(0, 0);
1460
+ return;
1461
+ }
1462
+ const s = this.smoothing(0.5, dt);
1463
+ const h = this.domElement.clientHeight || 1;
1464
+ const k = 1.5 / h * s;
1465
+ this.rotation += this.lookBuf.x * k;
1466
+ this.angle -= this.lookBuf.y * k;
1467
+ this.lookBuf.multiplyScalar(1 - s);
1468
+ }
1469
+ /** Drain the move buffer into the eye position: WASD strafes/advances on the
1470
+ * heading plane (yaw only — looking down doesn't sink you),
1471
+ * space/shift raise/lower. The `dt·0.06` factor makes the steady-state speed
1472
+ * frame-rate independent. */
1473
+ applyFlyMove(dt) {
1474
+ if (this.moveBuf.lengthSq() < 1e-8) {
1475
+ this.moveBuf.set(0, 0, 0);
1476
+ return;
1477
+ }
1478
+ const s = this.smoothing(0.3, dt);
1479
+ const f = s * this.moveSpeed * dt * 0.06;
1480
+ const sinr = Math.sin(this.rotation);
1481
+ const cosr = Math.cos(this.rotation);
1482
+ this.position.x += (cosr * this.moveBuf.x + sinr * this.moveBuf.z) * f;
1483
+ this.position.z += (sinr * this.moveBuf.x - cosr * this.moveBuf.z) * f;
1484
+ this.position.y += this.moveBuf.y * f;
1485
+ this.moveBuf.multiplyScalar(1 - s);
1486
+ }
1487
+ /** Free-flight bounds: pitch spans nearly the whole sky (just shy of the poles
1488
+ * to dodge the gimbal flip), distance is pinned to the eye, azimuth wraps. */
1489
+ applyFlyBounds() {
1490
+ this.distance = 0;
1491
+ this.angle = clamp(this.angle, 0.02, Math.PI - 0.02);
1492
+ if (this.rotation > Math.PI) this.rotation -= 2 * Math.PI;
1493
+ else if (this.rotation < -Math.PI) this.rotation += 2 * Math.PI;
1494
+ }
1495
+ /** Ease toward an animation goal (frame-rate-normalized), clearing it once the
1496
+ * view has settled close enough. */
1497
+ applyGoal(dt) {
1498
+ if (!this.goal) return;
1499
+ const k = clamp(0.12 * (dt / 16.666), 0, 1);
1500
+ const g = this.goal;
1501
+ let done = true;
1502
+ if (g.rotation !== void 0) {
1503
+ let dr = g.rotation - this.rotation;
1504
+ if (dr > Math.PI) dr -= 2 * Math.PI;
1505
+ else if (dr < -Math.PI) dr += 2 * Math.PI;
1506
+ this.rotation += dr * k;
1507
+ if (Math.abs(dr) > 3e-3) done = false;
1508
+ }
1509
+ if (g.angle !== void 0) {
1510
+ this.angle += (g.angle - this.angle) * k;
1511
+ if (Math.abs(g.angle - this.angle) > 3e-3) done = false;
1512
+ }
1513
+ if (g.distance !== void 0) {
1514
+ this.distance += (g.distance - this.distance) * k;
1515
+ if (Math.abs(g.distance - this.distance) > this.distance * 4e-3) done = false;
1516
+ }
1517
+ if (g.position) {
1518
+ this.position.lerp(g.position, k);
1519
+ if (this.position.distanceToSquared(g.position) > 0.04) done = false;
1520
+ }
1521
+ if (done) this.goal = null;
1522
+ }
1523
+ applyBounds() {
1524
+ this.distance = softClamp(this.distance, this.minDistance, this.maxDistance, 0.8);
1525
+ this.angle = softClamp(this.angle, 0, HALF_PI, 0.8);
1526
+ this.angle = softMax(this.angle, this.maxAngleForDistance(this.distance), 0.8);
1527
+ if (this.rotation > Math.PI) this.rotation -= 2 * Math.PI;
1528
+ else if (this.rotation < -Math.PI) this.rotation += 2 * Math.PI;
1529
+ }
1530
+ /** Keep the orbit pivot on the terrain surface so the view rotates and tilts
1531
+ * about the ground under the screen centre.
1532
+ *
1533
+ * The pivot Y rides the single-column surface height + 3, temporally smoothed
1534
+ * (so panning over uneven ground glides, doesn't bob). A `minCameraHeight`
1535
+ * term lifts the pivot just enough that the orbiting camera clears the terrain
1536
+ * it hovers over at steep tilt (no dipping below ground / staring into the
1537
+ * void). Riding the surface is harmless zoomed out, where the view is forced
1538
+ * near top-down (insensitive to pivot Y). */
1539
+ applyHeight(dt) {
1540
+ if (!this.heightAt) return;
1541
+ const ts = clamp(0.15 * (dt / 16.666), 0, 1);
1542
+ const hp = this.heightAt(this.position.x, this.position.z);
1543
+ const targetTerrain = (hp === null ? this.floorY : hp) + 3;
1544
+ this.targetHeight += (targetTerrain - this.targetHeight) * ts;
1545
+ if (Math.abs(targetTerrain - this.targetHeight) < 0.01) this.targetHeight = targetTerrain;
1546
+ let suggested = this.targetHeight;
1547
+ const maxAngle = this.maxAngleForDistance(this.distance);
1548
+ if (maxAngle >= 0.1) {
1549
+ const cs = clamp(0.2 * (dt / 16.666), 0, 1);
1550
+ const hc = this.heightAt(this.camera.position.x, this.camera.position.z);
1551
+ const cameraTerrain = hc === null ? this.floorY : hc;
1552
+ this.cameraHeight += (cameraTerrain - this.cameraHeight) * cs;
1553
+ const maxAngleHeight = Math.cos(maxAngle) * this.distance;
1554
+ const minCameraHeight = this.cameraHeight - maxAngleHeight + 1;
1555
+ suggested = Math.max(suggested, minCameraHeight);
1556
+ }
1557
+ this.position.y = suggested;
1558
+ }
1559
+ // --- keyboard integration --------------------------------------------------
1560
+ /** Translate held keys into the same input buffers the mouse fills, in
1561
+ * pixel-equivalent units scaled by frame time. Holding a key tops the buffer
1562
+ * up to a steady velocity; releasing lets it decay, so key moves glide and
1563
+ * feel identical to a drag — no separate code path. */
1564
+ feedKeys(dt) {
1565
+ if (this.keys.size === 0) return;
1566
+ this.goal = null;
1567
+ const k = this.keys;
1568
+ const fr = dt / 16.666;
1569
+ if (this.mode === "fly") {
1570
+ const f = (k.has("w") || k.has("arrowup") ? 1 : 0) - (k.has("s") || k.has("arrowdown") ? 1 : 0);
1571
+ const strafeKey = (k.has("d") || k.has("arrowright") ? 1 : 0) - (k.has("a") || k.has("arrowleft") ? 1 : 0);
1572
+ const vert = (k.has(" ") ? 1 : 0) - (k.has("shift") ? 1 : 0);
1573
+ this.moveBuf.x += strafeKey;
1574
+ this.moveBuf.y += vert;
1575
+ this.moveBuf.z += f;
1576
+ const rot2 = (k.has("e") ? 1 : 0) - (k.has("q") ? 1 : 0);
1577
+ if (rot2) this.rotation += rot2 * 0.028 * fr;
1578
+ const tilt2 = (k.has("r") ? 1 : 0) - (k.has("f") ? 1 : 0);
1579
+ if (tilt2) this.angle += tilt2 * 0.028 * fr;
1580
+ return;
1581
+ }
1582
+ const boost = k.has("shift") ? 2.4 : 1;
1583
+ const fwd = (k.has("w") || k.has("arrowup") ? 1 : 0) - (k.has("s") || k.has("arrowdown") ? 1 : 0);
1584
+ const strafe = (k.has("d") || k.has("arrowright") ? 1 : 0) - (k.has("a") || k.has("arrowleft") ? 1 : 0);
1585
+ if (fwd || strafe) {
1586
+ const sp = this.distance * 0.025 * fr * boost;
1587
+ const cs = Math.cos(this.rotation);
1588
+ const sn = Math.sin(this.rotation);
1589
+ const sx = strafe;
1590
+ const sy = -fwd;
1591
+ this.panBuf.x += (sx * cs - sy * sn) * sp;
1592
+ this.panBuf.y += (sx * sn + sy * cs) * sp;
1593
+ }
1594
+ const rot = (k.has("q") ? 1 : 0) - (k.has("e") ? 1 : 0);
1595
+ if (rot) this.rotBuf += rot * 7 * fr;
1596
+ const tilt = (k.has("f") ? 1 : 0) - (k.has("r") ? 1 : 0);
1597
+ if (tilt) this.angleBuf += tilt * 6 * fr;
1598
+ const zoom = (k.has("-") || k.has("_") ? 1 : 0) - (k.has("=") || k.has("+") ? 1 : 0);
1599
+ if (zoom) this.zoomBuf += zoom * 0.08 * fr;
1600
+ }
1601
+ // --- camera derivation -----------------------------------------------------
1602
+ /** Project a screen-pixel point onto the horizontal plane at world height
1603
+ * `planeY`, writing the world (x, z) into `out`. Returns false when the ray
1604
+ * runs parallel to / away from the plane (e.g. aimed above the horizon). This
1605
+ * is what anchors the pan to the cursor: the world point under the cursor is
1606
+ * recoverable, so we can keep it pinned there. */
1607
+ groundPoint(screen, planeY, out) {
1608
+ const w = this.domElement.clientWidth || 1;
1609
+ const h = this.domElement.clientHeight || 1;
1610
+ this._ndc.set(screen.x / w * 2 - 1, -(screen.y / h * 2 - 1), 0.5).unproject(this.camera);
1611
+ const ox = this.camera.position.x;
1612
+ const oy = this.camera.position.y;
1613
+ const oz = this.camera.position.z;
1614
+ const dy = this._ndc.y - oy;
1615
+ if (Math.abs(dy) < 1e-6) return false;
1616
+ const t = (planeY - oy) / dy;
1617
+ if (t <= 0) return false;
1618
+ out.set(ox + (this._ndc.x - ox) * t, oz + (this._ndc.z - oz) * t);
1619
+ return true;
1620
+ }
1621
+ updateCamera() {
1622
+ const rv = this._orbitV.set(Math.sin(this.rotation), 0, -Math.cos(this.rotation));
1623
+ const axis = this._orbitAxis.set(0, 1, 0).cross(rv).normalize();
1624
+ rv.applyAxisAngle(axis, HALF_PI - this.angle);
1625
+ rv.multiplyScalar(this.distance);
1626
+ this.camera.position.copy(this.position).sub(rv);
1627
+ this.camera.rotation.set(this.angle - HALF_PI, -this.rotation, 0, "YXZ");
1628
+ }
1629
+ /** A cheap scalar that changes iff the view changed (skips redundant emits). */
1630
+ changeKey() {
1631
+ return this.position.x + this.position.y * 1.1 + this.position.z * 1.3 + this.distance * 2.7 + this.rotation * 5.1 + this.angle * 7.3;
1632
+ }
1633
+ // --- pointer input ---------------------------------------------------------
1634
+ localXY(e) {
1635
+ const rect = this.domElement.getBoundingClientRect();
1636
+ return new THREE2.Vector2(e.clientX - rect.left, e.clientY - rect.top);
1637
+ }
1638
+ pointerDown(e) {
1639
+ if (!this.enabled) return;
1640
+ this.goal = null;
1641
+ const p = this.localXY(e);
1642
+ this.pointers.set(e.pointerId, p);
1643
+ this.downPos.copy(p);
1644
+ this.moved = false;
1645
+ if (this.mode === "fly") {
1646
+ this.flyPointerDown = true;
1647
+ this.lastLook.copy(p);
1648
+ this.emit("start");
1649
+ return;
1650
+ }
1651
+ if (this.pointers.size === 1) {
1652
+ const orbit = e.button === 2 || e.altKey || e.ctrlKey || e.metaKey;
1653
+ if (orbit) {
1654
+ this.beginOrbit(p);
1655
+ } else if (e.button === 0 || e.pointerType !== "mouse") {
1656
+ this.panning = true;
1657
+ this.lastPan.copy(p);
1658
+ }
1659
+ this.emit("start");
1660
+ } else if (this.pointers.size === 2) {
1661
+ this.panning = false;
1662
+ this.orbiting = false;
1663
+ const [a, b] = [...this.pointers.values()];
1664
+ this.touchDist = a.distanceTo(b);
1665
+ this.touchAngle = Math.atan2(b.y - a.y, b.x - a.x);
1666
+ }
1667
+ try {
1668
+ this.domElement.setPointerCapture?.(e.pointerId);
1669
+ } catch {
1670
+ }
1671
+ }
1672
+ beginOrbit(p) {
1673
+ this.orbiting = true;
1674
+ this.lastOrbit.copy(p);
1675
+ this.startDistance = this.distance;
1676
+ this.dynamicDistance = this.distance < 1e3;
1677
+ }
1678
+ pointerMove(e) {
1679
+ if (this.mode === "fly" && this.pointerLocked) {
1680
+ this.lookBuf.x += e.movementX || 0;
1681
+ this.lookBuf.y += e.movementY || 0;
1682
+ return;
1683
+ }
1684
+ if (!this.pointers.has(e.pointerId)) return;
1685
+ const p = this.localXY(e);
1686
+ if (this.mode === "fly") {
1687
+ if (this.flyPointerDown) {
1688
+ if (p.distanceToSquared(this.downPos) > 9) this.moved = true;
1689
+ this.lookBuf.x += p.x - this.lastLook.x;
1690
+ this.lookBuf.y += p.y - this.lastLook.y;
1691
+ this.lastLook.copy(p);
1692
+ }
1693
+ this.pointers.set(e.pointerId, p);
1694
+ e.preventDefault();
1695
+ return;
1696
+ }
1697
+ this.pointers.get(e.pointerId);
1698
+ if (this.pointers.size >= 2) {
1699
+ this.pointers.set(e.pointerId, p);
1700
+ this.pinch();
1701
+ return;
1702
+ }
1703
+ if (p.distanceToSquared(this.downPos) > 9) this.moved = true;
1704
+ if (this.panning) {
1705
+ const planeY = this.position.y;
1706
+ if (this.groundPoint(this.lastPan, planeY, this._gpA) && this.groundPoint(p, planeY, this._gpB)) {
1707
+ this.panBuf.x += this._gpA.x - this._gpB.x;
1708
+ this.panBuf.y += this._gpA.y - this._gpB.y;
1709
+ }
1710
+ this.lastPan.copy(p);
1711
+ } else if (this.orbiting) {
1712
+ this.rotBuf += p.x - this.lastOrbit.x;
1713
+ this.angleBuf -= p.y - this.lastOrbit.y;
1714
+ this.lastOrbit.copy(p);
1715
+ }
1716
+ this.pointers.set(e.pointerId, p);
1717
+ e.preventDefault();
1718
+ }
1719
+ /** Two-finger pinch (zoom) + twist (rotate). */
1720
+ pinch() {
1721
+ const [a, b] = [...this.pointers.values()];
1722
+ const dist = a.distanceTo(b);
1723
+ const ang = Math.atan2(b.y - a.y, b.x - a.x);
1724
+ if (this.touchDist > 0) {
1725
+ this.zoomBuf += (this.touchDist - dist) * 0.01;
1726
+ let dA = ang - this.touchAngle;
1727
+ if (dA > Math.PI) dA -= 2 * Math.PI;
1728
+ else if (dA < -Math.PI) dA += 2 * Math.PI;
1729
+ this.rotation -= dA;
1730
+ }
1731
+ this.touchDist = dist;
1732
+ this.touchAngle = ang;
1733
+ }
1734
+ pointerUp(e) {
1735
+ if (!this.pointers.has(e.pointerId)) return;
1736
+ this.pointers.delete(e.pointerId);
1737
+ try {
1738
+ this.domElement.releasePointerCapture?.(e.pointerId);
1739
+ } catch {
1740
+ }
1741
+ if (this.mode === "fly") {
1742
+ const wasClick = this.flyPointerDown && !this.moved;
1743
+ this.flyPointerDown = false;
1744
+ this.emit("end");
1745
+ if (wasClick && !this.pointerLocked) this.requestPointerLock();
1746
+ return;
1747
+ }
1748
+ if (this.pointers.size === 0) this.endDrag();
1749
+ else if (this.pointers.size === 1) {
1750
+ const [only] = [...this.pointers.values()];
1751
+ this.panning = true;
1752
+ this.lastPan.copy(only);
1753
+ }
1754
+ }
1755
+ endDrag() {
1756
+ const was = this.panning || this.orbiting;
1757
+ this.panning = false;
1758
+ this.orbiting = false;
1759
+ this.dynamicDistance = false;
1760
+ if (was) this.emit("end");
1761
+ }
1762
+ wheel(e) {
1763
+ if (!this.enabled) return;
1764
+ e.preventDefault();
1765
+ let delta = e.deltaY;
1766
+ if (e.deltaMode === 1) delta *= 16;
1767
+ else if (e.deltaMode === 2) delta *= 100;
1768
+ if (this.mode === "fly") {
1769
+ this.moveSpeed = clamp(this.moveSpeed * Math.pow(1.0016, -delta), 0.05, 5);
1770
+ return;
1771
+ }
1772
+ this.zoomBuf += delta * 0.01;
1773
+ this.dynamicDistance = false;
1774
+ this.goal = null;
1775
+ }
1776
+ // --- keyboard input --------------------------------------------------------
1777
+ static MOVE_KEYS = /* @__PURE__ */ new Set([
1778
+ "w",
1779
+ "a",
1780
+ "s",
1781
+ "d",
1782
+ "q",
1783
+ "e",
1784
+ "r",
1785
+ "f",
1786
+ "shift",
1787
+ " ",
1788
+ "arrowup",
1789
+ "arrowdown",
1790
+ "arrowleft",
1791
+ "arrowright",
1792
+ "-",
1793
+ "_",
1794
+ "=",
1795
+ "+"
1796
+ ]);
1797
+ isTyping() {
1798
+ const el = document.activeElement;
1799
+ return !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable);
1800
+ }
1801
+ keyDown(e) {
1802
+ if (!this.enabled || e.metaKey || e.ctrlKey || e.altKey || this.isTyping()) return;
1803
+ const k = e.key.toLowerCase();
1804
+ if (k === "escape") {
1805
+ if (this.mode === "fly" && !this.pointerLocked) this.setMode("map");
1806
+ return;
1807
+ }
1808
+ if (_MapControls.MOVE_KEYS.has(k)) {
1809
+ this.keys.add(k);
1810
+ if (k !== "shift") e.preventDefault();
1811
+ }
1812
+ }
1813
+ keyUp(e) {
1814
+ this.keys.delete(e.key.toLowerCase());
1815
+ }
1816
+ };
1817
+ var DEFAULT_LIGHT = { ambient: 0.12, daylight: 1, exposure: 1 };
1818
+ var VANILLA_DISPLAY = {
1819
+ sharpness: 0,
1820
+ ao: 1,
1821
+ saturation: 1,
1822
+ contrast: 1,
1823
+ fog: 1,
1824
+ renderScale: 1
1825
+ };
1826
+ var DEFAULT_DISPLAY = { ...VANILLA_DISPLAY };
1827
+ var DEFAULT_ORBIT_ANGLE = 0.42;
1828
+ async function fetchBuffer(url) {
1829
+ const r = await fetch(url);
1830
+ if (!r.ok) throw new Error(`${r.status} ${r.statusText} for ${url}`);
1831
+ return r.arrayBuffer();
1832
+ }
1833
+ async function resolveTile(src) {
1834
+ if (typeof src === "string") return parseTile(await maybeInflate(await fetchBuffer(src)));
1835
+ if (src instanceof ArrayBuffer) return parseTile(await maybeInflate(src));
1836
+ return src;
1837
+ }
1838
+ async function resolveTextures(src) {
1839
+ if (typeof src === "string") return parseTextureArray(await maybeInflate(await fetchBuffer(src)));
1840
+ if (src instanceof ArrayBuffer) return parseTextureArray(await maybeInflate(src));
1841
+ return src;
1842
+ }
1843
+ function resolveContainer(container) {
1844
+ const el = typeof container === "string" ? document.querySelector(container) : container;
1845
+ if (!el) throw new Error(`vantage: container not found: ${String(container)}`);
1846
+ return el;
1847
+ }
1848
+ function makeHeightSampler(surface) {
1849
+ if (!surface) return null;
1850
+ const { width, depth, originX, originZ, height } = surface;
1851
+ const R = 2;
1852
+ return (x, z) => {
1853
+ const cx = Math.floor(x - originX);
1854
+ const cz = Math.floor(z - originZ);
1855
+ let sum = 0;
1856
+ let n = 0;
1857
+ for (let dz = -R; dz <= R; dz++) {
1858
+ const zz = cz + dz;
1859
+ if (zz < 0 || zz >= depth) continue;
1860
+ const row = zz * width;
1861
+ for (let dx = -R; dx <= R; dx++) {
1862
+ const xx = cx + dx;
1863
+ if (xx < 0 || xx >= width) continue;
1864
+ const h = height[row + xx];
1865
+ if (h < 1) continue;
1866
+ sum += h;
1867
+ n++;
1868
+ }
1869
+ }
1870
+ return n === 0 ? null : sum / n;
1871
+ };
1872
+ }
1873
+ var VantageViewer = class _VantageViewer {
1874
+ renderer;
1875
+ scene;
1876
+ camera;
1877
+ controls;
1878
+ container;
1879
+ options;
1880
+ emitter = new Emitter();
1881
+ sky;
1882
+ resizeObserver;
1883
+ // Anti-aliasing: the scene renders into an 8× multisampled offscreen target,
1884
+ // then a fullscreen pass copies the resolved result to the canvas. 8× (vs the
1885
+ // default framebuffer's driver-chosen ~4×) is what keeps high-frequency foliage
1886
+ // silhouettes and the alpha-to-coverage cutouts from crawling as the camera
1887
+ // moves. No GTAO/bloom/tonemap — purely AA + present.
1888
+ msaa;
1889
+ present = new THREE2.Scene();
1890
+ presentCamera = new THREE2.Camera();
1891
+ presentMaterial;
1892
+ // Current tile state (single-tile mode).
1893
+ tile = null;
1894
+ shader = null;
1895
+ bounds = new THREE2.Box3();
1896
+ current = null;
1897
+ _biomes = [];
1898
+ // Streamed-world state (world/manifest mode). `tiles` doubles as the mode flag.
1899
+ tiles = null;
1900
+ manifest = null;
1901
+ waterShader = null;
1902
+ lowresShader = null;
1903
+ /** Populated world extent (max of X/Z spans), for whole-world zoom limits. */
1904
+ worldSpan = 0;
1905
+ tilesUnsub = null;
1906
+ lastBiomesEmit = 0;
1907
+ // Biome layer state machine.
1908
+ biomeEnabled = false;
1909
+ highlight = null;
1910
+ mixTarget = 0;
1911
+ mixCurrent = 0;
1912
+ // Live lighting appearance (applied to the shader on load and on change).
1913
+ light = { ...DEFAULT_LIGHT };
1914
+ // Live display fidelity (shader uniforms + render scale).
1915
+ display = { ...DEFAULT_DISPLAY };
1916
+ // Hover picking.
1917
+ raycaster = new THREE2.Raycaster();
1918
+ ndc = new THREE2.Vector2();
1919
+ pointerInside = false;
1920
+ pointerDirty = false;
1921
+ dragging = false;
1922
+ lastHover = -2;
1923
+ // sentinel distinct from -1 (off-terrain)
1924
+ // Last-frame timestamp, for frame-rate-independent control inertia.
1925
+ lastFrameMs = 0;
1926
+ // The framing the current tile loaded into, so the UI can re-home to it.
1927
+ framedState = null;
1928
+ // URL-hash deep links (urlState option): debounce handle for hash writes and
1929
+ // the last hash we wrote (so a hashchange we caused isn't re-applied).
1930
+ hashTimer = null;
1931
+ lastWrittenHash = "";
1932
+ urlUnsub = null;
1933
+ constructor(container, options = {}) {
1934
+ this.container = resolveContainer(container);
1935
+ this.options = {
1936
+ view: options.view ?? "orbit",
1937
+ antialias: options.antialias ?? true,
1938
+ maxPixelRatio: options.maxPixelRatio ?? 2,
1939
+ light: options.light ?? {},
1940
+ display: options.display ?? {},
1941
+ streaming: options.streaming ?? {},
1942
+ urlState: options.urlState ?? false
1943
+ };
1944
+ if (options.light) this.light = { ...this.light, ...options.light };
1945
+ if (options.display) this.display = { ...this.display, ...options.display };
1946
+ this.renderer = new THREE2.WebGLRenderer({ antialias: false });
1947
+ this.renderer.setPixelRatio(this.targetPixelRatio());
1948
+ this.renderer.outputColorSpace = THREE2.SRGBColorSpace;
1949
+ this.renderer.autoClear = false;
1950
+ this.container.appendChild(this.renderer.domElement);
1951
+ this.buildAA();
1952
+ this.scene = new THREE2.Scene();
1953
+ this.scene.background = new THREE2.Color(...SKY_HORIZON);
1954
+ this.sky = createSky();
1955
+ this.scene.add(this.sky);
1956
+ this.camera = new THREE2.PerspectiveCamera(75, 1, 0.5, 8e3);
1957
+ this.controls = new MapControls(this.camera, this.renderer.domElement, { minDistance: 3 });
1958
+ this.bindInput();
1959
+ if (this.options.urlState) this.bindUrlState();
1960
+ this.resizeObserver = new ResizeObserver(() => this.resize());
1961
+ this.resizeObserver.observe(this.container);
1962
+ this.resize();
1963
+ this.renderer.setAnimationLoop(() => this.frame());
1964
+ }
1965
+ /** Build the offscreen multisampled target and the fullscreen present pass.
1966
+ * The scene already writes display-ready sRGB, so present is a raw passthrough
1967
+ * drawn over one oversized clip-space triangle. */
1968
+ buildAA() {
1969
+ const size = this.renderer.getDrawingBufferSize(new THREE2.Vector2());
1970
+ this.msaa = new THREE2.WebGLRenderTarget(Math.max(1, size.x), Math.max(1, size.y), {
1971
+ samples: this.options.antialias ? 8 : 0,
1972
+ type: THREE2.UnsignedByteType,
1973
+ depthBuffer: true
1974
+ });
1975
+ this.msaa.texture.colorSpace = THREE2.NoColorSpace;
1976
+ this.msaa.texture.minFilter = THREE2.LinearFilter;
1977
+ this.msaa.texture.magFilter = THREE2.LinearFilter;
1978
+ const geo = new THREE2.BufferGeometry();
1979
+ geo.setAttribute("position", new THREE2.BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));
1980
+ this.presentMaterial = new THREE2.RawShaderMaterial({
1981
+ glslVersion: THREE2.GLSL3,
1982
+ uniforms: { tSrc: { value: this.msaa.texture } },
1983
+ depthTest: false,
1984
+ depthWrite: false,
1985
+ vertexShader: (
1986
+ /* glsl */
1987
+ `
1988
+ in vec3 position; out vec2 vUv;
1989
+ void main() { vUv = position.xy * 0.5 + 0.5; gl_Position = vec4(position.xy, 0.0, 1.0); }
1990
+ `
1991
+ ),
1992
+ fragmentShader: (
1993
+ /* glsl */
1994
+ `
1995
+ precision highp float; uniform sampler2D tSrc; in vec2 vUv; out vec4 frag;
1996
+ void main() { frag = texture(tSrc, vUv); }
1997
+ `
1998
+ )
1999
+ });
2000
+ this.present.add(new THREE2.Mesh(geo, this.presentMaterial));
2001
+ }
2002
+ /** Construct a viewer and load a tile in one call. */
2003
+ static async mount(container, options) {
2004
+ const { tile, textures, view, ...rest } = options;
2005
+ const viewer = new _VantageViewer(container, { ...rest, ...view ? { view } : {} });
2006
+ await viewer.load({ tile, textures, view });
2007
+ return viewer;
2008
+ }
2009
+ /** Load (fetch/decode as needed), build, and frame a tile or a streamed world. */
2010
+ async load(opts) {
2011
+ if (opts.world) return this.loadWorld(opts.world, opts.view ?? this.options.view);
2012
+ if (!opts.tile) throw new Error("vantage: load needs a `world` manifest URL or a `tile` source");
2013
+ const tile = await resolveTile(opts.tile);
2014
+ const textures = opts.textures ? await resolveTextures(opts.textures) : void 0;
2015
+ this.setTile(tile, textures, opts.view ?? this.options.view);
2016
+ }
2017
+ /** Stream a tiled world render from its `manifest.json`. Tiles load around
2018
+ * the camera as it moves and unload behind it; the whole world is reachable
2019
+ * without ever holding more than the streaming budget in memory. */
2020
+ async loadWorld(url, view) {
2021
+ const abs = new URL(url, typeof document !== "undefined" ? document.baseURI : void 0).toString();
2022
+ const res = await fetch(abs);
2023
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${abs}`);
2024
+ const manifest = parseManifest(await res.json());
2025
+ const texData = parseTextureArray(await maybeInflate(await fetchBuffer(new URL(manifest.textures, abs).toString())));
2026
+ this.disposeCurrent();
2027
+ const palette = biomePalette(manifest.biomes.length);
2028
+ const shader = createTerrainMaterial(texData, { quantized: true, palette });
2029
+ const waterShader = createWaterMaterial(shader);
2030
+ shader.uniforms["uFogRadial"].value = 1;
2031
+ const lowresShader = manifest.lowres ? createLowresMaterial(shader) : void 0;
2032
+ this.shader = shader;
2033
+ this.waterShader = waterShader;
2034
+ this.lowresShader = lowresShader ?? null;
2035
+ this.manifest = manifest;
2036
+ this.tile = null;
2037
+ this.tiles = new TileManager({
2038
+ manifest,
2039
+ baseUrl: abs,
2040
+ scene: this.scene,
2041
+ material: shader,
2042
+ waterMaterial: waterShader,
2043
+ ...lowresShader ? { lowresMaterial: lowresShader } : {},
2044
+ palette,
2045
+ ...this.options.streaming
2046
+ });
2047
+ this.controls.heightAt = this.tiles.heightAt;
2048
+ this.tilesUnsub = this.tiles.on("change", (stats) => {
2049
+ this.emitter.emit("stats", stats);
2050
+ const now = performance.now();
2051
+ if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
2052
+ this.lastBiomesEmit = now;
2053
+ this._biomes = this.tiles.biomes;
2054
+ this.emitter.emit("biomes", this._biomes);
2055
+ }
2056
+ });
2057
+ this.frameWorld(manifest, view);
2058
+ if (this.options.urlState) this.applyViewHash(window.location.hash);
2059
+ this.applyBiomeUniforms();
2060
+ this.applyLight();
2061
+ this.applyDisplay();
2062
+ this.tiles.update(this.controls.position.x, this.controls.position.z);
2063
+ const size = new THREE2.Vector3();
2064
+ this.bounds.getSize(size);
2065
+ this._biomes = [];
2066
+ this.emitter.emit("load", {
2067
+ magic: "VTL6",
2068
+ vertexCount: 0,
2069
+ triangleCount: 0,
2070
+ size,
2071
+ biomes: this._biomes
2072
+ });
2073
+ }
2074
+ /** Frame a streamed world: pivot on the spawn point when the manifest has
2075
+ * one (that's where the builds are), else the centre of the tile extents.
2076
+ * Distances are tied to the streaming view distance, not the world size —
2077
+ * a 100k×100k world frames the same as a village. */
2078
+ frameWorld(manifest, view) {
2079
+ const tb = manifest.tileBlocks;
2080
+ let minX = Infinity;
2081
+ let minZ = Infinity;
2082
+ let maxX = -Infinity;
2083
+ let maxZ = -Infinity;
2084
+ for (const t of manifest.tiles) {
2085
+ minX = Math.min(minX, t.x * tb);
2086
+ minZ = Math.min(minZ, t.z * tb);
2087
+ maxX = Math.max(maxX, (t.x + 1) * tb);
2088
+ maxZ = Math.max(maxZ, (t.z + 1) * tb);
2089
+ }
2090
+ if (!Number.isFinite(minX)) {
2091
+ minX = minZ = 0;
2092
+ maxX = maxZ = tb;
2093
+ }
2094
+ this.bounds.set(new THREE2.Vector3(minX, -64, minZ), new THREE2.Vector3(maxX, 320, maxZ));
2095
+ this.worldSpan = Math.max(maxX - minX, maxZ - minZ);
2096
+ const viewDistance = this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768;
2097
+ const spawn = manifest.spawn;
2098
+ const pivot = spawn ? new THREE2.Vector3(spawn.x, spawn.y, spawn.z) : new THREE2.Vector3((minX + maxX) / 2, 80, (minZ + maxZ) / 2);
2099
+ const span = Math.min(Math.max(maxX - minX, maxZ - minZ), viewDistance * 1.1);
2100
+ let distance;
2101
+ let angle;
2102
+ if (view === "top") {
2103
+ distance = this.fitDistance(span) * 1.04;
2104
+ angle = 0;
2105
+ } else {
2106
+ distance = this.fitDistance(Math.min(span, 560)) * 0.72;
2107
+ angle = DEFAULT_ORBIT_ANGLE;
2108
+ }
2109
+ const h = this.controls.heightAt?.(pivot.x, pivot.z);
2110
+ if (h != null) pivot.y = h + 3;
2111
+ this.controls.setView({ position: pivot, distance, rotation: 0, angle, floorY: pivot.y });
2112
+ this.framedState = { position: pivot.clone(), distance, rotation: 0, angle, floorY: pivot.y };
2113
+ this.applyViewLimits();
2114
+ }
2115
+ /** The radius hires tiles are actually guaranteed resident to: the view
2116
+ * distance, unless the tile budget runs out first (nearest-first fill ⇒ a
2117
+ * disc of maxTiles tiles ⇒ radius tb·√(maxTiles/π)). */
2118
+ streamRadius() {
2119
+ const vd = this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768;
2120
+ const mt = this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120;
2121
+ const tb = this.manifest?.tileBlocks ?? 128;
2122
+ return Math.min(vd, tb * Math.sqrt(mt / Math.PI));
2123
+ }
2124
+ /** Zoom range, far plane, and fog for a streamed world.
2125
+ *
2126
+ * With a lowres pyramid (format 2) the whole world is drawable, so zoom-out
2127
+ * is bounded by the world extent, the far plane covers it, and the radial
2128
+ * fog retreats to the world edge — a faint horizon haze, never a wall. The
2129
+ * hires→lowres seam needs no hiding: finer data simply overlays coarser.
2130
+ *
2131
+ * Without one (format 1), zoom and fog hug the hires ring so the map never
2132
+ * becomes a field of holes: solid haze right where tiles stop. */
2133
+ applyViewLimits() {
2134
+ if (!this.tiles || !this.shader) return;
2135
+ const viewDistance = this.tiles.viewDistance;
2136
+ const fog = this.shader.uniforms["uFog"].value;
2137
+ if (this.manifest?.lowres) {
2138
+ const span = Math.max(this.worldSpan, viewDistance * 2);
2139
+ this.controls.maxDistance = Math.min(Math.max(span * 0.9, viewDistance * 2.2), 6e4);
2140
+ this.camera.far = Math.min(Math.max(8e3, span * 2.5), 25e4);
2141
+ fog.set(span * 0.9, span * 1.8);
2142
+ } else {
2143
+ const r = this.streamRadius();
2144
+ this.controls.maxDistance = viewDistance * 2.2;
2145
+ this.camera.far = Math.max(8e3, viewDistance * 6);
2146
+ fog.set(r * 0.72, r * 1.05);
2147
+ }
2148
+ this.camera.updateProjectionMatrix();
2149
+ }
2150
+ setTile(tile, textures, view) {
2151
+ this.disposeCurrent();
2152
+ const built = buildTerrain(tile, textures);
2153
+ this.tile = tile;
2154
+ this.shader = built.shader ?? null;
2155
+ this.bounds = built.bounds;
2156
+ this.scene.add(built.terrain);
2157
+ if (built.water) this.scene.add(built.water);
2158
+ this.current = { terrain: built.terrain, water: built.water };
2159
+ if (built.requiresSceneLights) {
2160
+ const hemi = new THREE2.HemisphereLight(12376063, 4867638, 1);
2161
+ const sun = new THREE2.DirectionalLight(16773848, 1.6);
2162
+ sun.position.set(0.6, 1, 0.35);
2163
+ this.scene.add(hemi, sun);
2164
+ this.current.lights = [hemi, sun];
2165
+ }
2166
+ this.controls.heightAt = makeHeightSampler(tile.surface);
2167
+ this._biomes = summarizeBiomes(tile, built.palette);
2168
+ this.frameCamera(view);
2169
+ if (this.options.urlState) this.applyViewHash(window.location.hash);
2170
+ this.applyBiomeUniforms();
2171
+ this.applyLight();
2172
+ this.applyDisplay();
2173
+ const size = new THREE2.Vector3();
2174
+ this.bounds.getSize(size);
2175
+ this.emitter.emit("load", {
2176
+ magic: tile.magic,
2177
+ vertexCount: tile.vertexCount + (tile.fluid?.vertexCount ?? 0),
2178
+ triangleCount: (tile.indexCount + (tile.fluid?.indexCount ?? 0)) / 3,
2179
+ size,
2180
+ biomes: this._biomes
2181
+ });
2182
+ }
2183
+ /** Where the *land* is, from the surface heightmap: the elevation-weighted
2184
+ * centroid (so flat ocean is ignored) and the span of the elevated region.
2185
+ * Falls back to the geometric centre for tiles without a surface map. Keeps
2186
+ * the demo's first frame on the interesting terrain, not out over the water. */
2187
+ landTarget(center, size) {
2188
+ const s = this.tile?.surface;
2189
+ const names = this.tile?.biomeNames;
2190
+ const fallback = { x: center.x, z: center.z, span: Math.max(size.x, size.z) };
2191
+ if (!s) return fallback;
2192
+ const { width, depth, originX, originZ, height, biome } = s;
2193
+ let n = 0;
2194
+ let sx = 0;
2195
+ let sz = 0;
2196
+ let minx = Infinity;
2197
+ let maxx = -Infinity;
2198
+ let minz = Infinity;
2199
+ let maxz = -Infinity;
2200
+ for (let z = 0; z < depth; z++) {
2201
+ for (let x = 0; x < width; x++) {
2202
+ const i = z * width + x;
2203
+ if (height[i] < 1) continue;
2204
+ const nm = names?.[biome[i]] ?? "";
2205
+ if (nm.includes("ocean") || nm.includes("river")) continue;
2206
+ const wx = originX + x;
2207
+ const wz = originZ + z;
2208
+ n++;
2209
+ sx += wx;
2210
+ sz += wz;
2211
+ if (wx < minx) minx = wx;
2212
+ if (wx > maxx) maxx = wx;
2213
+ if (wz < minz) minz = wz;
2214
+ if (wz > maxz) maxz = wz;
2215
+ }
2216
+ }
2217
+ if (n < 16) return fallback;
2218
+ return { x: sx / n, z: sz / n, span: Math.max(maxx - minx, maxz - minz, 48) * 1.15 };
2219
+ }
2220
+ /** Camera-to-pivot distance that vertically fits a world span of `s` blocks at
2221
+ * the current FOV, so framing is FOV-independent: widening the lens (60→75)
2222
+ * doesn't silently zoom the load view out. The callers' multipliers preserve
2223
+ * the previously-tuned on-screen framing. */
2224
+ fitDistance(s) {
2225
+ return s * 0.5 / Math.tan(THREE2.MathUtils.degToRad(this.camera.fov / 2));
2226
+ }
2227
+ frameCamera(view) {
2228
+ const center = new THREE2.Vector3();
2229
+ const size = new THREE2.Vector3();
2230
+ this.bounds.getCenter(center);
2231
+ this.bounds.getSize(size);
2232
+ const maxDim = Math.max(size.x, size.y, size.z);
2233
+ this.controls.maxDistance = maxDim * 4;
2234
+ const pivot = new THREE2.Vector3();
2235
+ let distance;
2236
+ let rotation;
2237
+ let angle;
2238
+ if (view === "top") {
2239
+ const span = Math.max(size.x, size.z);
2240
+ pivot.set(center.x, this.bounds.max.y, center.z);
2241
+ distance = this.fitDistance(span) * 1.04;
2242
+ rotation = 0;
2243
+ angle = 0;
2244
+ } else {
2245
+ const land = this.landTarget(center, size);
2246
+ const surfaceY = this.bounds.max.y - size.y * 0.18;
2247
+ pivot.set(land.x, surfaceY, land.z);
2248
+ distance = this.fitDistance(land.span) * 0.72;
2249
+ rotation = 0;
2250
+ angle = DEFAULT_ORBIT_ANGLE;
2251
+ }
2252
+ const h = this.controls.heightAt?.(pivot.x, pivot.z);
2253
+ if (h != null) pivot.y = h + 3;
2254
+ this.controls.setView({ position: pivot, distance, rotation, angle, floorY: pivot.y });
2255
+ this.framedState = { position: pivot.clone(), distance, rotation, angle, floorY: pivot.y };
2256
+ this.camera.far = maxDim * 12;
2257
+ this.camera.updateProjectionMatrix();
2258
+ if (this.shader) this.shader.uniforms["uFog"].value.set(maxDim * 1.2, maxDim * 3.2);
2259
+ }
2260
+ // --- biome layer ----------------------------------------------------------
2261
+ /** Biomes present in the current tile, most common first. */
2262
+ get biomes() {
2263
+ return this._biomes;
2264
+ }
2265
+ /** Whether the biome recolour layer is active. */
2266
+ get biomeLayerEnabled() {
2267
+ return this.biomeEnabled;
2268
+ }
2269
+ /** The currently isolated biome id, or `null`. */
2270
+ get highlightedBiome() {
2271
+ return this.highlight;
2272
+ }
2273
+ /** Turn the biome recolour layer on or off (crossfades). */
2274
+ setBiomeLayer(enabled) {
2275
+ if (this.biomeEnabled === enabled) return;
2276
+ this.biomeEnabled = enabled;
2277
+ if (!enabled) this.highlight = null;
2278
+ this.mixTarget = enabled ? 1 : 0;
2279
+ this.applyBiomeUniforms();
2280
+ this.emitter.emit("biomelayer", { enabled, highlight: this.highlight });
2281
+ }
2282
+ toggleBiomeLayer() {
2283
+ this.setBiomeLayer(!this.biomeEnabled);
2284
+ }
2285
+ /** Isolate a biome by id (fades the rest); `null` clears. Enables the layer. */
2286
+ setHighlightedBiome(id) {
2287
+ if (id !== null && !this.biomeEnabled) this.setBiomeLayer(true);
2288
+ this.highlight = id;
2289
+ this.applyBiomeUniforms();
2290
+ this.emitter.emit("biomelayer", { enabled: this.biomeEnabled, highlight: id });
2291
+ }
2292
+ applyBiomeUniforms() {
2293
+ if (!this.shader) return;
2294
+ this.shader.uniforms["uHi"].value = this.biomeEnabled && this.highlight !== null ? this.highlight : -1;
2295
+ }
2296
+ // --- lighting appearance ---------------------------------------------------
2297
+ /** The current live lighting appearance. */
2298
+ get lightSettings() {
2299
+ return { ...this.light };
2300
+ }
2301
+ /** Update the live lighting appearance (merges with current; takes effect
2302
+ * immediately, no re-bake). */
2303
+ setLight(settings) {
2304
+ this.light = { ...this.light, ...settings };
2305
+ this.applyLight();
2306
+ }
2307
+ applyLight() {
2308
+ if (!this.shader) return;
2309
+ this.shader.uniforms["uAmbient"].value = this.light.ambient;
2310
+ this.shader.uniforms["uDay"].value = this.light.daylight;
2311
+ this.shader.uniforms["uExposure"].value = this.light.exposure;
2312
+ }
2313
+ // --- display fidelity ------------------------------------------------------
2314
+ /** The current live display fidelity (sharpness, colour grade, fog, scale). */
2315
+ get displaySettings() {
2316
+ return { ...this.display };
2317
+ }
2318
+ /** Update the live display fidelity (merges with current; immediate, no
2319
+ * re-bake). `renderScale` resizes the framebuffer; the rest are shader uniforms. */
2320
+ setDisplay(settings) {
2321
+ const scaleChanged = settings.renderScale !== void 0 && settings.renderScale !== this.display.renderScale;
2322
+ this.display = { ...this.display, ...settings };
2323
+ this.applyDisplay();
2324
+ if (scaleChanged) {
2325
+ this.renderer.setPixelRatio(this.targetPixelRatio());
2326
+ this.resize();
2327
+ }
2328
+ }
2329
+ /** devicePixelRatio × renderScale, capped by maxPixelRatio (and a hard 4 so a
2330
+ * fat-fingered scale can't allocate a giant framebuffer). */
2331
+ targetPixelRatio() {
2332
+ const want = window.devicePixelRatio * this.display.renderScale;
2333
+ return Math.min(want, this.options.maxPixelRatio * Math.max(1, this.display.renderScale), 4);
2334
+ }
2335
+ applyDisplay() {
2336
+ if (!this.shader) return;
2337
+ const d = this.display;
2338
+ this.shader.uniforms["uSharpness"].value = d.sharpness;
2339
+ this.shader.uniforms["uAoStrength"].value = d.ao;
2340
+ this.shader.uniforms["uSaturation"].value = d.saturation;
2341
+ this.shader.uniforms["uContrast"].value = d.contrast;
2342
+ this.shader.uniforms["uFogDensity"].value = d.fog;
2343
+ }
2344
+ // --- streaming -------------------------------------------------------------
2345
+ /** The current streaming settings (view distance, tile budget, concurrency). */
2346
+ get streamingSettings() {
2347
+ return {
2348
+ viewDistance: this.tiles?.viewDistance ?? this.options.streaming.viewDistance ?? 768,
2349
+ maxTiles: this.tiles?.maxTiles ?? this.options.streaming.maxTiles ?? 120,
2350
+ concurrency: this.options.streaming.concurrency ?? 4
2351
+ };
2352
+ }
2353
+ /** Live-tune streaming: view distance, resident-tile budget, concurrency.
2354
+ * Applies immediately to a streamed world (tiles re-plan, fog and camera
2355
+ * range follow) and persists for future loads. The fidelity dial: raise
2356
+ * viewDistance/maxTiles to see farther, lower them on weak hardware. */
2357
+ setStreaming(settings) {
2358
+ this.options.streaming = { ...this.options.streaming, ...settings };
2359
+ if (!this.tiles) return;
2360
+ this.tiles.configure(settings);
2361
+ this.applyViewLimits();
2362
+ }
2363
+ // --- URL-hash deep links ----------------------------------------------------
2364
+ /** The current view serialized as a `#@x,y,z,dist,rot,tilt` hash fragment —
2365
+ * paste-able into any URL serving the same world. */
2366
+ getViewHash() {
2367
+ const p = this.controls.position;
2368
+ const r1 = (v) => Math.round(v * 10) / 10;
2369
+ const r3 = (v) => Math.round(v * 1e3) / 1e3;
2370
+ return `#@${r1(p.x)},${r1(p.y)},${r1(p.z)},${r1(this.controls.distance)},${r3(this.controls.rotation)},${r3(this.controls.angle)}`;
2371
+ }
2372
+ /** Apply a `#@x,y,z,dist,rot,tilt` hash to the camera (leading `#` optional).
2373
+ * Returns whether the hash parsed. */
2374
+ applyViewHash(hash) {
2375
+ const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)$/.exec(hash);
2376
+ if (!m) return false;
2377
+ const [x, y, z, distance, rotation, angle] = m.slice(1).map(Number);
2378
+ if (![x, y, z, distance, rotation, angle].every(Number.isFinite)) return false;
2379
+ this.controls.setView({
2380
+ position: new THREE2.Vector3(x, y, z),
2381
+ distance,
2382
+ rotation,
2383
+ angle,
2384
+ floorY: y
2385
+ });
2386
+ return true;
2387
+ }
2388
+ /** Debounced camera→hash sync plus hashchange→camera (pasted links apply
2389
+ * live). `history.replaceState` avoids history spam and hashchange echo. */
2390
+ bindUrlState() {
2391
+ const onChange = () => {
2392
+ if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2393
+ this.hashTimer = setTimeout(() => this.writeHash(), 250);
2394
+ };
2395
+ this.controls.addEventListener("change", onChange);
2396
+ const onHash = () => {
2397
+ if (window.location.hash === this.lastWrittenHash) return;
2398
+ this.applyViewHash(window.location.hash);
2399
+ };
2400
+ window.addEventListener("hashchange", onHash);
2401
+ this.urlUnsub = () => {
2402
+ this.controls.removeEventListener("change", onChange);
2403
+ window.removeEventListener("hashchange", onHash);
2404
+ if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2405
+ this.hashTimer = null;
2406
+ };
2407
+ }
2408
+ writeHash() {
2409
+ const hash = this.getViewHash();
2410
+ if (hash === this.lastWrittenHash) return;
2411
+ this.lastWrittenHash = hash;
2412
+ history.replaceState(null, "", hash);
2413
+ }
2414
+ // --- camera / navigation ---------------------------------------------------
2415
+ /** Smoothly zoom by `steps` wheel-notches (positive = in). Drives the same
2416
+ * inertial zoom as the wheel, so on-screen buttons feel identical. */
2417
+ zoomBy(steps) {
2418
+ this.controls.zoom(steps);
2419
+ }
2420
+ /** Smoothly rotate the view back to north, keeping the current tilt and
2421
+ * position. For the compass click. */
2422
+ resetNorth() {
2423
+ this.controls.animateTo({ rotation: 0 });
2424
+ }
2425
+ /** Smoothly set the pitch (radians off top-down): `0` = top-down map ("2D"),
2426
+ * {@link DEFAULT_ORBIT_ANGLE} = the gentle aerial ("3D"). The tilt control. */
2427
+ setTilt(angle) {
2428
+ this.controls.animateTo({ angle });
2429
+ }
2430
+ /** Smoothly drop to a clean, north-up top-down map (the "2D" toggle): levels
2431
+ * the tilt and straightens the heading so the world is axis-aligned. */
2432
+ flatten() {
2433
+ this.controls.animateTo({ angle: 0, rotation: 0 });
2434
+ }
2435
+ /** The current pitch in radians (0 = top-down), for a tilt toggle's state. */
2436
+ get tilt() {
2437
+ return this.controls.angle;
2438
+ }
2439
+ /** Smoothly return to the framing the tile loaded into (the home button). */
2440
+ resetView() {
2441
+ if (this.framedState) this.controls.animateTo(this.framedState);
2442
+ }
2443
+ /** Whether the free-flight (spectator) camera is active. */
2444
+ get isFlying() {
2445
+ return this.controls.flyMode;
2446
+ }
2447
+ /** Enter or leave free-flight. In fly mode the camera becomes a first-person
2448
+ * spectator: WASD to move, space/shift up-down, mouse (click to capture) to
2449
+ * look, wheel to trim speed. Emits `'mode'`. */
2450
+ setFlyMode(on) {
2451
+ if (this.controls.flyMode === on) return;
2452
+ this.controls.setMode(on ? "fly" : "map");
2453
+ if (on) this.emitHover(-1);
2454
+ this.emitter.emit("mode", { fly: on });
2455
+ }
2456
+ /** Toggle free-flight on/off. */
2457
+ toggleFly() {
2458
+ this.setFlyMode(!this.controls.flyMode);
2459
+ }
2460
+ // --- events ---------------------------------------------------------------
2461
+ on(event, listener) {
2462
+ return this.emitter.on(event, listener);
2463
+ }
2464
+ // --- internals ------------------------------------------------------------
2465
+ bindInput() {
2466
+ const dom = this.renderer.domElement;
2467
+ dom.style.cursor = "grab";
2468
+ dom.style.touchAction = "none";
2469
+ dom.addEventListener("pointermove", (e) => {
2470
+ const rect = dom.getBoundingClientRect();
2471
+ this.ndc.x = (e.clientX - rect.left) / rect.width * 2 - 1;
2472
+ this.ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
2473
+ this.pointerInside = true;
2474
+ this.pointerDirty = true;
2475
+ });
2476
+ dom.addEventListener("pointerleave", () => {
2477
+ this.pointerInside = false;
2478
+ this.pointerDirty = true;
2479
+ });
2480
+ this.controls.addEventListener("start", () => {
2481
+ this.dragging = true;
2482
+ dom.style.cursor = "grabbing";
2483
+ this.emitHover(-1);
2484
+ });
2485
+ this.controls.addEventListener("end", () => {
2486
+ this.dragging = false;
2487
+ dom.style.cursor = "grab";
2488
+ });
2489
+ }
2490
+ emitHover(id) {
2491
+ if (id === this.lastHover) return;
2492
+ this.lastHover = id;
2493
+ this.emitter.emit("hover", id < 0 ? null : id);
2494
+ }
2495
+ pickHover() {
2496
+ if (this.controls.flyMode) {
2497
+ this.emitHover(-1);
2498
+ return;
2499
+ }
2500
+ if (this.dragging || !this.pointerDirty) return;
2501
+ this.pointerDirty = false;
2502
+ if (!this.pointerInside) {
2503
+ this.emitHover(-1);
2504
+ return;
2505
+ }
2506
+ if (this.tiles) {
2507
+ this.raycaster.setFromCamera(this.ndc, this.camera);
2508
+ this.emitHover(this.tiles.pickBiome(this.raycaster.ray));
2509
+ return;
2510
+ }
2511
+ const surface = this.tile?.surface;
2512
+ if (!surface) {
2513
+ this.emitHover(-1);
2514
+ return;
2515
+ }
2516
+ this.raycaster.setFromCamera(this.ndc, this.camera);
2517
+ this.emitHover(pickBiome(this.raycaster.ray, surface, this.bounds));
2518
+ }
2519
+ frame() {
2520
+ const now = performance.now();
2521
+ const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
2522
+ this.lastFrameMs = now;
2523
+ this.controls.update(dtMs);
2524
+ this.sky.position.copy(this.camera.position);
2525
+ if (this.tiles) {
2526
+ const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
2527
+ this.tiles.update(focus.x, focus.z);
2528
+ if (this.shader) this.shader.uniforms["uFogCenter"].value.set(focus.x, focus.z);
2529
+ }
2530
+ if (this.shader) {
2531
+ this.mixCurrent += (this.mixTarget - this.mixCurrent) * 0.2;
2532
+ if (Math.abs(this.mixCurrent - this.mixTarget) < 15e-4) this.mixCurrent = this.mixTarget;
2533
+ this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2534
+ }
2535
+ this.pickHover();
2536
+ this.renderer.setRenderTarget(this.msaa);
2537
+ this.renderer.clear();
2538
+ this.renderer.render(this.scene, this.camera);
2539
+ this.renderer.setRenderTarget(null);
2540
+ this.renderer.render(this.present, this.presentCamera);
2541
+ }
2542
+ resize() {
2543
+ const w = this.container.clientWidth || window.innerWidth;
2544
+ const h = this.container.clientHeight || window.innerHeight;
2545
+ this.camera.aspect = w / h;
2546
+ this.camera.updateProjectionMatrix();
2547
+ this.renderer.setPixelRatio(this.targetPixelRatio());
2548
+ this.renderer.setSize(w, h, false);
2549
+ const size = this.renderer.getDrawingBufferSize(new THREE2.Vector2());
2550
+ this.msaa.setSize(Math.max(1, size.x), Math.max(1, size.y));
2551
+ }
2552
+ disposeCurrent() {
2553
+ if (this.current) {
2554
+ for (const mesh of [this.current.terrain, this.current.water]) {
2555
+ if (!mesh) continue;
2556
+ this.scene.remove(mesh);
2557
+ mesh.geometry.dispose();
2558
+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) m.dispose();
2559
+ }
2560
+ for (const light of this.current.lights ?? []) this.scene.remove(light);
2561
+ this.current = null;
2562
+ }
2563
+ if (this.tiles) {
2564
+ this.tilesUnsub?.();
2565
+ this.tilesUnsub = null;
2566
+ this.tiles.dispose();
2567
+ this.tiles = null;
2568
+ this.manifest = null;
2569
+ }
2570
+ if (this.shader) {
2571
+ this.shader.uniforms["map"]?.value?.dispose();
2572
+ this.shader.uniforms["uPalette"]?.value?.dispose();
2573
+ this.shader.dispose();
2574
+ this.shader = null;
2575
+ }
2576
+ if (this.waterShader) {
2577
+ this.waterShader.dispose();
2578
+ this.waterShader = null;
2579
+ }
2580
+ if (this.lowresShader) {
2581
+ this.lowresShader.dispose();
2582
+ this.lowresShader = null;
2583
+ }
2584
+ this.controls.heightAt = null;
2585
+ }
2586
+ /** Tear down the renderer, controls, observers, and remove the canvas. */
2587
+ dispose() {
2588
+ this.renderer.setAnimationLoop(null);
2589
+ this.resizeObserver.disconnect();
2590
+ this.urlUnsub?.();
2591
+ this.urlUnsub = null;
2592
+ this.controls.dispose();
2593
+ this.disposeCurrent();
2594
+ this.present.traverse((o) => {
2595
+ if (o instanceof THREE2.Mesh) o.geometry.dispose();
2596
+ });
2597
+ this.presentMaterial.dispose();
2598
+ this.msaa.dispose();
2599
+ this.emitter.clear();
2600
+ this.renderer.dispose();
2601
+ this.renderer.domElement.remove();
2602
+ }
2603
+ };
2604
+
2605
+ export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome };