Spaces:
Running
Running
Download terrain.js from CyberMax-tools/fellwing: direct link, hf CLI and curl.
- Browser
- Download file 23.5 kB
-
https://huggingface.co/spaces/CyberMax-tools/fellwing/resolve/main/terrain.js
- Command line
-
hf download hf://spaces/CyberMax-tools/fellwing/terrain.js
-
curl -L -o terrain.js https://huggingface.co/spaces/CyberMax-tools/fellwing/resolve/main/terrain.js
23.5 kB
| // Fellwing terrain: the real shape of the Earth, streamed as a quadtree of elevation tiles straight from the public | |
| // AWS Terrain Tiles bucket (Mapzen/Tilezen "terrarium" PNG; SRTM, 3DEP, GMTED, ETOPO1 and national DEMs; free, CORS open, | |
| // no CyberMax server in the path). Each tile becomes a mesh with skirts, draped with real aerial/satellite imagery of the | |
| // same Web Mercator tile (imagery.js: NASA GIBS Landsat worldwide, national open orthophotos where they exist). Where no | |
| // photo can be had (offline, a provider down) the ground is shaded from the elevation itself (slope, altitude, latitude, | |
| // noise) tinted by NASA's Blue Marble. Runways are levelled into the mesh. The same heights drive the flight physics. | |
| // (c) 2026 CyberMax. All rights reserved. | |
| import * as THREE from 'three'; | |
| import { ATMOS_GLSL } from './atmos.js'; | |
| import { C_EARTH, lon2u, lat2v, u2lon, v2lat, AIRPORTS } from './places.js'; | |
| export const TILE_URL = (z, x, y) => `https://s3.amazonaws.com/elevation-tiles-prod/terrarium/${z}/${x}/${y}.png`; | |
| const ROOT_Z = 8; | |
| // ---------------------------------------------------------------- frame: local metres around an origin | |
| export class Frame { | |
| constructor(lat, lon) { this.set(lat, lon); } | |
| set(lat, lon) { this.lat0 = lat; this.lon0 = lon; this.u0 = lon2u(lon); this.v0 = lat2v(lat); this.k = Math.cos((lat * Math.PI) / 180); this.m = C_EARTH * this.k; } | |
| /** lat/lon -> local x (east), z (south) metres */ | |
| toLocal(lat, lon) { return [(lon2u(lon) - this.u0) * this.m, (lat2v(lat) - this.v0) * this.m]; } | |
| toLatLon(x, z) { return [v2lat(this.v0 + z / this.m), u2lon(this.u0 + x / this.m)]; } | |
| uv(x, z) { return [this.u0 + x / this.m, this.v0 + z / this.m]; } | |
| } | |
| // ---------------------------------------------------------------- runway levelling (shared by mesh + physics) | |
| // Each runway is levelled to a straight slope between its two thresholds, with a smooth blend into the hills around it. | |
| export function runwayMasks(frame) { | |
| return AIRPORTS.map((a) => { | |
| const [ax, az] = frame.toLocal(a.a[0], a.a[1]); | |
| const [bx, bz] = frame.toLocal(a.b[0], a.b[1]); | |
| const L = Math.hypot(bx - ax, bz - az); | |
| return { a, ax, az, bx, bz, L, dx: (bx - ax) / L, dz: (bz - az) / L, ea: a.a[2], eb: a.b[2], hw: a.w / 2 + 25, far: Math.hypot(ax, az) }; | |
| }); | |
| } | |
| export function levelHeight(masks, x, z, h) { | |
| for (const r of masks) { | |
| const px = x - r.ax, pz = z - r.az; | |
| const along = px * r.dx + pz * r.dz; | |
| if (along < -400 || along > r.L + 400) continue; | |
| const across = Math.abs(px * -r.dz + pz * r.dx); | |
| if (across > r.hw + 260) continue; | |
| const t = Math.max(0, Math.min(1, along / r.L)); | |
| const e = r.ea + (r.eb - r.ea) * t; | |
| const outA = Math.max(0, -along, along - r.L); | |
| const d = Math.max(0, across - r.hw) + Math.max(0, outA - 120); | |
| const w = 1 - Math.min(1, d / 240); | |
| const s = w * w * (3 - 2 * w); | |
| return h + (e - h) * s; | |
| } | |
| return h; | |
| } | |
| // ---------------------------------------------------------------- the terrain shader | |
| const VERT = /* glsl */` | |
| attribute vec2 aGeo; // Blue Marble uv (equirectangular lon/lat) | |
| uniform vec3 uCam; uniform vec4 uImgRect; | |
| varying vec3 vW; varying vec3 vN; varying vec2 vGeo; varying float vH; varying vec2 vUv; | |
| ${ATMOS_GLSL.split('vec3 skyColor')[0]} | |
| #include <common> | |
| #include <logdepthbuf_pars_vertex> | |
| void main() { | |
| vec4 w = modelMatrix * vec4(position, 1.0); | |
| vH = w.y; | |
| vW = w.xyz; | |
| vN = normal; | |
| vGeo = aGeo; | |
| vUv = uImgRect.xy + uv * uImgRect.zw; | |
| vec2 d = w.xz - uCam.xz; | |
| w.y -= dot(d, d) / (2.0 * R_EARTH); | |
| gl_Position = projectionMatrix * viewMatrix * w; | |
| #include <logdepthbuf_vertex> | |
| }`; | |
| const FRAG = /* glsl */` | |
| uniform sampler2D uEarth; uniform float uEarthOn; | |
| uniform vec3 uCam; uniform vec3 uAmbSky; uniform vec3 uAmbGnd; | |
| uniform float uLat; uniform float uSnow; uniform float uTime; | |
| uniform sampler2D uImg; uniform float uImgOn; uniform float uPhotoGain; uniform float uSat; | |
| varying vec3 vW; varying vec3 vN; varying vec2 vGeo; varying float vH; varying vec2 vUv; | |
| ${ATMOS_GLSL} | |
| float h21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } | |
| float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); | |
| return mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y); } | |
| float fbm(vec2 p) { float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++) { s += a * vnoise(p); p = p * 2.03 + 17.1; a *= 0.5; } return s; } | |
| vec3 toLin(vec3 c) { return pow(c, vec3(2.2)); } | |
| #include <logdepthbuf_pars_fragment> | |
| void main() { | |
| #include <logdepthbuf_fragment> | |
| vec3 n = normalize(vN); | |
| float dist = length(vW - uCam); | |
| // detail normal from noise (fades with distance) | |
| float fd = 1.0 - smoothstep(1500.0, 9000.0, dist); | |
| #if LOWQ == 0 | |
| if (fd > 0.0) { | |
| vec2 q = vW.xz / 38.0; | |
| float e = 0.6; | |
| float n0 = fbm(q), nx = fbm(q + vec2(0.06, 0.0)), nz = fbm(q + vec2(0.0, 0.06)); | |
| n = normalize(n + vec3(n0 - nx, 0.0, n0 - nz) * 6.0 * e * fd); | |
| } | |
| #endif | |
| float slope = 1.0 - n.y; | |
| float macro = fbm(vW.xz / 2400.0), meso = fbm(vW.xz / 310.0 + 3.1), micro = vnoise(vW.xz / 21.0); | |
| // base tint: Blue Marble where loaded, else a temperate default | |
| vec3 bm = uEarthOn > 0.5 ? toLin(texture2D(uEarth, vGeo).rgb) : vec3(0.06, 0.09, 0.04); | |
| float bmL = dot(bm, vec3(0.3, 0.55, 0.15)); | |
| vec3 grass = vec3(0.075, 0.105, 0.035); | |
| float veg = smoothstep(-0.004, 0.02, bm.g - bm.r); | |
| vec3 base = mix(bm * 1.2, mix(grass, bm * 1.15, 0.8), veg); | |
| base *= mix(0.78, 1.22, macro) * mix(0.9, 1.1, meso); | |
| vec3 forest = base * vec3(0.62, 0.72, 0.6); | |
| float fmask = smoothstep(0.42, 0.62, meso + (0.5 - macro) * 0.3) * (1.0 - smoothstep(0.25, 0.55, slope)) * smoothstep(0.02, 0.06, bm.g - bm.b * 0.6) * veg; | |
| vec3 col = mix(base, forest, fmask * 0.75); | |
| // tree line and alpine meadow | |
| float treeline = uSnow - 900.0; | |
| col = mix(col, mix(vec3(0.16, 0.15, 0.10), base, 0.4), smoothstep(treeline - 200.0, treeline + 300.0, vH + macro * 300.0) * 0.7); | |
| // rock on steep faces, with strata | |
| vec3 rockA = vec3(0.23, 0.21, 0.19), rockB = vec3(0.38, 0.34, 0.29); | |
| vec3 rock = mix(rockA, rockB, fbm(vec2(vW.xz.x / 90.0, vH / 14.0))); | |
| rock *= mix(vec3(1.0), clamp(bm / max(bmL, 0.005), vec3(0.55), vec3(1.7)), 0.7 * smoothstep(0.0, 0.025, bm.r - bm.g)); // warm deserts tint the rock (red canyons) | |
| float rk = smoothstep(0.20, 0.42, slope + (micro - 0.5) * 0.12 + (meso - 0.5) * 0.1); | |
| col = mix(col, rock, rk); | |
| // bare high ground | |
| col = mix(col, rock * 0.9, smoothstep(uSnow - 500.0, uSnow, vH) * 0.6); | |
| // snow: above the latitude snow line, on gentle enough slopes; Blue Marble ice too | |
| float sn = smoothstep(uSnow - 150.0, uSnow + 350.0, vH + (macro - 0.5) * 600.0 + (micro - 0.5) * 60.0) * (1.0 - smoothstep(0.15, 0.33, slope + (meso - 0.5) * 0.12)); | |
| sn = max(sn, smoothstep(0.62, 0.8, bmL) * smoothstep(uSnow - 900.0, uSnow - 300.0, vH) * (1.0 - smoothstep(0.18, 0.36, slope))); | |
| col = mix(col, vec3(0.86, 0.89, 0.94), sn); | |
| // beaches | |
| col = mix(col, vec3(0.45, 0.41, 0.32), (1.0 - smoothstep(0.5, 3.5, vH)) * (1.0 - smoothstep(0.08, 0.22, slope)) * 0.7); | |
| // underwater (seen through the sea) | |
| col = mix(col, vec3(0.03, 0.07, 0.07), 1.0 - smoothstep(-3.0, 0.5, vH)); | |
| // lighting: sun + sky + bounce, a soft wrap | |
| float ndl = dot(n, uSun); | |
| float diff = clamp((ndl + 0.08) / 1.08, 0.0, 1.0); | |
| float hemi = 0.5 + 0.5 * n.y; | |
| vec3 light = uSunCol * diff * 0.44 + mix(uAmbGnd, uAmbSky, hemi) * 0.55; | |
| vec3 lit = col * light; | |
| // snow sparkle / sheen toward the sun | |
| vec3 v = normalize(uCam - vW); | |
| vec3 hv = normalize(v + uSun); | |
| lit += uSunCol * pow(max(dot(n, hv), 0.0), 40.0) * 0.05 * sn; | |
| // real imagery: the photo already holds its own light and shadow, so the DEM relief only modulates it gently and the | |
| // sky colour of the chosen time of day tints it (sunset gold, night blue) | |
| if (uImgOn > 0.5) { | |
| vec4 im = texture2D(uImg, vUv); | |
| vec3 ph = toLin(im.rgb); | |
| float phL = dot(ph, vec3(0.2126, 0.7152, 0.0722)); | |
| ph = max(mix(vec3(phL), ph, uSat), 0.0) * uPhotoGain; // aerial photos are flat: a touch more colour (not Landsat) | |
| float flatD = clamp((uSun.y + 0.08) / 1.08, 0.0, 1.0); | |
| vec3 lightF = uSunCol * flatD * 0.44 + mix(uAmbGnd, uAmbSky, 1.0) * 0.55; | |
| // neutral exposure from the light level, plus a little of its colour (gold at sunset, blue at night) | |
| float E = dot(lightF, vec3(0.3, 0.55, 0.15)); | |
| vec3 tint = mix(vec3(1.0), lightF / max(E, 1e-3), 0.45); | |
| vec3 rel = light / max(lightF, vec3(0.02)); | |
| vec3 pl = ph * E * tint * mix(vec3(1.0), clamp(rel, vec3(0.55), vec3(1.4)), 0.4); | |
| // close up, a little ground grain so 5-30 m pixels do not look like a smooth print | |
| #if LOWQ == 0 | |
| pl *= mix(1.0, mix(0.9, 1.1, vnoise(vW.xz / 3.5)) * mix(0.94, 1.06, micro), fd); | |
| #endif | |
| // calm lakes and rivers: dark, bluish, dead-flat ground reflects the sky | |
| float lum = dot(ph, vec3(0.3, 0.55, 0.15)); | |
| // (near sea level any dark flat pixel is water: the coastline in the photo and in the elevation never match exactly) | |
| float dark = 1.0 - smoothstep(0.012, 0.035, lum / max(uPhotoGain, 0.01)); | |
| float blue = max(step(ph.g, ph.b * 1.25 + 0.002), 1.0 - smoothstep(1.0, 4.0, vH)); | |
| float flatW = (1.0 - smoothstep(0.0015, 0.006, slope)) * step(-1.0, vH); | |
| float sl = dot(im.rgb, vec3(0.3, 0.55, 0.15)); // photo brightness as stored (sRGB) | |
| float shore = (1.0 - smoothstep(1.2, 2.8, vH)) * (1.0 - smoothstep(0.27, 0.36, sl)); | |
| float wat = max(dark * blue, shore) * flatW; | |
| if (wat > 0.0) { | |
| vec3 rr = reflect(-v, vec3(0.0, 1.0, 0.0)); | |
| float fres = 0.03 + 0.97 * pow(1.0 - max(v.y, 0.0), 5.0); | |
| vec3 deep = vec3(0.004, 0.018, 0.03) * (uAmbSky + uSunCol * max(uSun.y, 0.0) * 0.3); | |
| vec3 wc = mix(mix(pl, deep, 0.6), skyColor(normalize(vec3(rr.x, abs(rr.y), rr.z))), fres); | |
| wc += uSunCol * pow(max(dot(rr, uSun), 0.0), 300.0) * 3.0 * (1.0 - uOvercast); | |
| pl = mix(pl, wc, wat); | |
| } | |
| lit = mix(lit, pl, im.a); | |
| } | |
| float fa; | |
| vec3 outc = aerial(lit, uCam, vW, fa); | |
| gl_FragColor = vec4(outc, 1.0); | |
| #include <tonemapping_fragment> | |
| #include <colorspace_fragment> | |
| }`; | |
| // ---------------------------------------------------------------- tile store + quadtree | |
| export class Terrain { | |
| constructor(scene, frame, opts = {}) { | |
| this.scene = scene; this.frame = frame; | |
| this.seg = opts.seg || 64; | |
| this.maxZ = opts.maxZ || 14; | |
| this.split = opts.split || 1.55; | |
| this.limit = opts.limit || 420; | |
| this.tiles = new Map(); | |
| this.queue = []; this.active = 0; this.maxActive = opts.parallel || 10; | |
| this.group = new THREE.Group(); scene.add(this.group); | |
| this.masks = runwayMasks(frame); | |
| this.loaded = 0; this.failed = 0; this.frameNo = 0; | |
| this.uniforms = opts.uniforms; // shared atmosphere uniforms | |
| this.low = !!opts.low; | |
| this.imagery = opts.imagery || null; // Imagery loader (null = shaded ground only) | |
| if (!this.uniforms.uPhotoGain) this.uniforms.uPhotoGain = { value: 1.0 }; | |
| this.mat = this.material(null, [0, 0, 1, 1]); | |
| this.idx = this.buildIndex(this.seg); | |
| } | |
| material(tex, rect, sat = 1.0) { | |
| return new THREE.ShaderMaterial({ vertexShader: VERT, fragmentShader: FRAG, side: THREE.DoubleSide, defines: { LOWQ: this.low ? 1 : 0 }, | |
| uniforms: { ...this.uniforms, uImg: { value: tex }, uImgOn: { value: tex ? 1 : 0 }, uImgRect: { value: new THREE.Vector4(...rect) }, uSat: { value: sat } } }); | |
| } | |
| reframe(frame) { // a new start far away: drop everything | |
| for (const t of this.tiles.values()) this.drop(t); | |
| this.tiles.clear(); this.queue.length = 0; this.frame = frame; this.masks = runwayMasks(frame); | |
| } | |
| key(z, x, y) { return `${z}/${x}/${y}`; } | |
| get(z, x, y, make = true) { | |
| const n = 1 << z; x = ((x % n) + n) % n; | |
| if (y < 0 || y >= n) return null; | |
| const k = this.key(z, x, y); | |
| let t = this.tiles.get(k); | |
| if (!t && make) { t = { z, x, y, k, state: 0, used: 0, mesh: null, h: null }; this.tiles.set(k, t); } | |
| return t; | |
| } | |
| request(t, pri) { | |
| if (t.state !== 0) return; | |
| t.state = 1; t.pri = pri; | |
| this.queue.push(t); | |
| } | |
| pump() { | |
| this.queue.sort((a, b) => a.pri - b.pri); | |
| while (this.active < this.maxActive && this.queue.length) { | |
| const t = this.queue.shift(); | |
| if (t.state !== 1) continue; | |
| this.active++; | |
| this.fetchTile(t).catch(() => { t.state = 4; this.failed++; }).finally(() => { this.active--; }); | |
| } | |
| } | |
| async fetchTile(t) { | |
| const res = await fetch(TILE_URL(t.z, t.x, t.y), { mode: 'cors' }); | |
| if (!res.ok) throw new Error(res.status); | |
| const bmp = await createImageBitmap(await res.blob()); | |
| if (!this.cv) { this.cv = document.createElement('canvas'); this.cv.width = this.cv.height = 256; this.cx = this.cv.getContext('2d', { willReadFrequently: true }); } | |
| this.cx.drawImage(bmp, 0, 0); bmp.close && bmp.close(); | |
| const px = this.cx.getImageData(0, 0, 256, 256).data; | |
| const raw = new Float32Array(256 * 256); | |
| for (let i = 0; i < raw.length; i++) raw[i] = px[i * 4] * 256 + px[i * 4 + 1] + px[i * 4 + 2] / 256 - 32768; | |
| if (!this.tiles.has(t.k)) return; | |
| this.build(t, raw); | |
| t.state = 2; this.loaded++; | |
| } | |
| /** World corner (NW) of a tile and its width, in the current frame. */ | |
| rect(z, x, y) { | |
| const n = 1 << z, f = this.frame; | |
| let du = x / n - f.u0; du -= Math.round(du); // wrap across the antimeridian | |
| return { x0: du * f.m, z0: (y / n - f.v0) * f.m, w: f.m / n }; | |
| } | |
| build(t, raw) { | |
| const N = this.seg, V = N + 1; | |
| const { x0, z0, w } = this.rect(t.z, t.x, t.y); | |
| const n = 1 << t.z; | |
| const h = new Float32Array(V * V); | |
| const sample = (fx, fy) => { // bilinear on pixel centres | |
| const px = Math.max(0, Math.min(255, fx * 256 - 0.5)), py = Math.max(0, Math.min(255, fy * 256 - 0.5)); | |
| const ix = Math.min(254, Math.floor(px)), iy = Math.min(254, Math.floor(py)), ax = px - ix, ay = py - iy; | |
| const a = raw[iy * 256 + ix], b = raw[iy * 256 + ix + 1], c = raw[(iy + 1) * 256 + ix], d = raw[(iy + 1) * 256 + ix + 1]; | |
| return (a * (1 - ax) + b * ax) * (1 - ay) + (c * (1 - ax) + d * ax) * ay; | |
| }; | |
| const near = this.masks.filter((r) => Math.abs(r.ax - (x0 + w / 2)) < w / 2 + 3000 && Math.abs(r.az - (z0 + w / 2)) < w / 2 + 3000); | |
| for (let j = 0; j < V; j++) for (let i = 0; i < V; i++) { | |
| let e = sample(i / N, j / N); | |
| if (e < 0.75) e = Math.min(e, 0) * 0.02 - 3; // sea (and DEM water at 0 m) sits just under the water surface | |
| if (near.length) e = levelHeight(near, x0 + (i / N) * w, z0 + (j / N) * w, e); | |
| h[j * V + i] = e; | |
| } | |
| t.h = h; t.x0 = x0; t.z0 = z0; t.w = w; | |
| // geometry: grid + skirts | |
| const skirt = 4 * N; | |
| const pos = new Float32Array((V * V + skirt + 4) * 3), nor = new Float32Array(pos.length), geo = new Float32Array((V * V + skirt + 4) * 2), uvs = new Float32Array(geo.length); | |
| const cell = w / N; | |
| let p = 0; | |
| const put = (i, j, y, nx, ny, nzv) => { | |
| pos[p * 3] = (i / N) * w; pos[p * 3 + 1] = y; pos[p * 3 + 2] = (j / N) * w; | |
| nor[p * 3] = nx; nor[p * 3 + 1] = ny; nor[p * 3 + 2] = nzv; | |
| const u = (t.x + i / N) / n, v = (t.y + j / N) / n; | |
| geo[p * 2] = u; geo[p * 2 + 1] = 0.5 + v2lat(v) / 180; | |
| uvs[p * 2] = i / N; uvs[p * 2 + 1] = j / N; | |
| p++; | |
| }; | |
| const H = (i, j) => h[Math.max(0, Math.min(N, j)) * V + Math.max(0, Math.min(N, i))]; | |
| const normals = new Float32Array(V * V * 3); | |
| for (let j = 0; j < V; j++) for (let i = 0; i < V; i++) { | |
| const dx = (H(i + 1, j) - H(i - 1, j)) / ((i > 0 && i < N ? 2 : 1) * cell); | |
| const dz = (H(i, j + 1) - H(i, j - 1)) / ((j > 0 && j < N ? 2 : 1) * cell); | |
| const l = Math.hypot(dx, 1, dz); | |
| normals[(j * V + i) * 3] = -dx / l; normals[(j * V + i) * 3 + 1] = 1 / l; normals[(j * V + i) * 3 + 2] = -dz / l; | |
| put(i, j, h[j * V + i], normals[(j * V + i) * 3], normals[(j * V + i) * 3 + 1], normals[(j * V + i) * 3 + 2]); | |
| } | |
| // skirts: a copy of each edge vertex dropped down, so cracks between detail levels never show sky | |
| const drop = Math.max(30, w * 0.02); | |
| const edge = []; | |
| for (let i = 0; i < N; i++) edge.push([i, 0]); | |
| for (let j = 0; j < N; j++) edge.push([N, j]); | |
| for (let i = N; i > 0; i--) edge.push([i, N]); | |
| for (let j = N; j > 0; j--) edge.push([0, j]); | |
| const skirtStart = p; | |
| for (const [i, j] of edge) { const o = (j * V + i) * 3; put(i, j, h[j * V + i] - drop, normals[o], normals[o + 1], normals[o + 2]); } | |
| const g = new THREE.BufferGeometry(); | |
| g.setAttribute('position', new THREE.BufferAttribute(pos.subarray(0, p * 3), 3)); | |
| g.setAttribute('normal', new THREE.BufferAttribute(nor.subarray(0, p * 3), 3)); | |
| g.setAttribute('aGeo', new THREE.BufferAttribute(geo.subarray(0, p * 2), 2)); | |
| g.setAttribute('uv', new THREE.BufferAttribute(uvs.subarray(0, p * 2), 2)); | |
| // index: grid + skirt quads | |
| const idx = this.idx.slice(); | |
| const sk = []; | |
| for (let e = 0; e < edge.length; e++) { | |
| const [i0, j0] = edge[e], [i1, j1] = edge[(e + 1) % edge.length]; | |
| const a = j0 * V + i0, b = j1 * V + i1, c = skirtStart + e, d = skirtStart + ((e + 1) % edge.length); | |
| sk.push(a, c, b, b, c, d); | |
| } | |
| const all = new Uint32Array(idx.length + sk.length); all.set(idx); all.set(sk, idx.length); | |
| g.setIndex(new THREE.BufferAttribute(all, 1)); | |
| let lo = Infinity, hi = -Infinity; for (const e of h) { if (e < lo) lo = e; if (e > hi) hi = e; } | |
| t.lo = lo; t.hi = hi; | |
| g.boundingSphere = new THREE.Sphere(new THREE.Vector3(w / 2, (lo + hi) / 2, w / 2), Math.hypot(w / 2, w / 2, (hi - lo) / 2 + drop) * 1.02); | |
| g.boundingBox = new THREE.Box3(new THREE.Vector3(0, lo - drop, 0), new THREE.Vector3(w, hi, w)); | |
| const m = new THREE.Mesh(g, this.mat); | |
| m.position.set(x0, 0, z0); | |
| // imagery: until it arrives the tile shows shaded ground; the parent stays on screen meanwhile (see update) | |
| t.img = this.imagery && !this.imagery.off ? 1 : 3; | |
| const ask = () => this.imagery.request(t, t.pri ?? t.z, (tex, rect, key, err) => { | |
| if (!t.mesh) { this.imagery.release(tex, key); return; } | |
| if (err && (t.imgTries = (t.imgTries || 0) + 1) < 3 && !this.imagery.off) { setTimeout(() => t.mesh && ask(), 600 * t.imgTries); return; } // a hiccup: try again | |
| if (tex) { t.mesh.material = this.material(tex, rect, key ? 1.0 : 1.18); t.tex = tex; t.texKey = key; } | |
| t.img = tex ? 2 : 3; | |
| }); | |
| if (t.img === 1) ask(); | |
| m.matrixAutoUpdate = false; m.updateMatrix(); | |
| m.visible = false; | |
| m.frustumCulled = true; | |
| t.mesh = m; this.group.add(m); | |
| } | |
| buildIndex(N) { | |
| const V = N + 1, a = []; | |
| for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) { | |
| const p = j * V + i; | |
| if ((i + j) % 2) a.push(p, p + V, p + 1, p + 1, p + V, p + V + 1); else a.push(p, p + V, p + V + 1, p, p + V + 1, p + 1); | |
| } | |
| return new Uint32Array(a); | |
| } | |
| drop(t) { | |
| if (this.imagery) this.imagery.cancel(t); | |
| if (t.mesh) { this.group.remove(t.mesh); t.mesh.geometry.dispose(); if (t.mesh.material !== this.mat) t.mesh.material.dispose(); t.mesh = null; } | |
| if (t.tex) { this.imagery.release(t.tex, t.texKey); t.tex = null; t.texKey = null; } | |
| t.h = null; t.state = 0; t.img = 0; | |
| } | |
| /** Pick the tiles to draw for a camera at local (cx, cy, cz). Children replace a parent only once all four are ready. */ | |
| update(cx, cy, cz) { | |
| this.frameNo++; | |
| const f = this.frame; | |
| const [u, v] = f.uv(cx, cz); | |
| const n = 1 << ROOT_Z; | |
| const rx = Math.floor(u * n), ry = Math.floor(v * n); | |
| for (const t of this.tiles.values()) if (t.mesh) t.mesh.visible = false; | |
| const want = (t) => { | |
| const r = this.rect(t.z, t.x, t.y); | |
| const mx = Math.max(r.x0, Math.min(cx, r.x0 + r.w)), mz = Math.max(r.z0, Math.min(cz, r.z0 + r.w)); | |
| const gy = t.state === 2 ? Math.max(t.lo, Math.min(cy, t.hi)) : 0; | |
| const d = Math.hypot(cx - mx, (cy - gy) * 1.0, cz - mz); | |
| return { d, w: r.w, split: t.z < this.maxZ && d < r.w * this.split }; | |
| }; | |
| const visit = (t) => { | |
| t.used = this.frameNo; | |
| const { d, w, split } = want(t); | |
| if (t.state === 0) this.request(t, t.z * 0.35 + d / w); | |
| if (split && t.state === 2) { | |
| const kids = [[0, 0], [1, 0], [0, 1], [1, 1]].map(([a, b]) => this.get(t.z + 1, t.x * 2 + a, t.y * 2 + b)); | |
| const ready = kids.every((k) => k && ((k.state === 2 && k.img >= 2) || k.state === 4)); | |
| kids.forEach((k) => { if (k) { k.used = this.frameNo; if (k.state === 0) this.request(k, k.z * 0.35 + (2 * d) / w); } }); | |
| if (ready) { kids.forEach((k) => (k.state === 2 ? visit(k) : (t.mesh && (t.mesh.visible = true)))); return; } | |
| } | |
| if (t.mesh) t.mesh.visible = true; | |
| }; | |
| for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) { const t = this.get(ROOT_Z, rx + i, ry + j); if (t) visit(t); } | |
| this.pump(); | |
| if (this.imagery) this.imagery.pump(); | |
| if (!this.offline && this.loaded === 0 && this.failed >= 9) this.offline = true; | |
| // forget tiles nobody has used for a while (keep a cache of recent ones) | |
| if (this.tiles.size > this.limit) { | |
| const old = [...this.tiles.values()].filter((t) => t.used < this.frameNo - 30 && t.z > ROOT_Z).sort((a, b) => a.used - b.used); | |
| for (const t of old.slice(0, this.tiles.size - this.limit)) { this.drop(t); this.tiles.delete(t.k); } | |
| } | |
| } | |
| /** Ground height (m) under local x, z from the most detailed tile loaded there, and whether it is sea. */ | |
| height(x, z) { | |
| const f = this.frame; | |
| const [u, v] = f.uv(x, z); | |
| for (let zz = this.maxZ; zz >= ROOT_Z - 2; zz--) { | |
| const n = 1 << zz; | |
| const t = this.get(zz, Math.floor(u * n), Math.floor(v * n), false); | |
| if (!t || t.state !== 2 || !t.h) continue; | |
| const N = this.seg, V = N + 1; | |
| const fx = Math.max(0, Math.min(N - 1e-6, ((x - t.x0) / t.w) * N)), fz = Math.max(0, Math.min(N - 1e-6, ((z - t.z0) / t.w) * N)); | |
| const i = Math.floor(fx), j = Math.floor(fz), ax = fx - i, az = fz - j; | |
| const h = t.h; | |
| // same triangle split as the mesh, so wheels sit on the drawn ground | |
| const p00 = h[j * V + i], p10 = h[j * V + i + 1], p01 = h[(j + 1) * V + i], p11 = h[(j + 1) * V + i + 1]; | |
| let e; | |
| if ((i + j) % 2) e = ax + az <= 1 ? p00 + (p10 - p00) * ax + (p01 - p00) * az : p11 + (p01 - p11) * (1 - ax) + (p10 - p11) * (1 - az); | |
| else e = ax >= az ? p00 + (p10 - p00) * ax + (p11 - p10) * az : p00 + (p01 - p00) * az + (p11 - p01) * ax; | |
| return { h: e, water: e < -1, z: zz }; | |
| } | |
| // offline (the elevation bucket cannot be reached): fly over a sea-level world with the runways still in place | |
| if (this.offline) return { h: levelHeight(this.masks, x, z, 0), water: false, z: 14, offline: true }; | |
| return { h: -1e4, water: false, z: -1 }; // nothing loaded yet | |
| } | |
| /** True once the ground under (x, z) is known at street-level detail. */ | |
| ready(x, z, minZ = 12) { return this.height(x, z).z >= minZ; } | |
| stats() { let vis = 0, tri = 0; for (const t of this.tiles.values()) if (t.mesh && t.mesh.visible) { vis++; tri += t.mesh.geometry.index.count / 3; } return { tiles: this.tiles.size, visible: vis, tri, queue: this.queue.length + (this.imagery ? this.imagery.stats().queue : 0), active: this.active + (this.imagery ? this.imagery.active : 0), loaded: this.loaded, failed: this.failed, img: this.imagery ? this.imagery.stats() : null }; } | |
| } | |