forked from linkong/planet
763 lines
25 KiB
JavaScript
763 lines
25 KiB
JavaScript
// spherical-tile-layer.js - Quadtree frustum-culled spherical LOD tiles with parent persistence
|
|
|
|
import * as THREE from "three";
|
|
import { earthTextureImages } from "./earth-texture-image.js";
|
|
import { configureColorTexture } from "./texture-colors.js";
|
|
|
|
const DEFAULT_SEGMENTS = 10;
|
|
const RAD_TO_DEG = 180 / Math.PI;
|
|
const DEG_TO_RAD = Math.PI / 180;
|
|
const FADE_DURATION_MS = 180;
|
|
|
|
function tileYToLat(y, n) {
|
|
const merc = Math.PI * (1 - (2 * y) / n);
|
|
return Math.atan(Math.sinh(merc)) * RAD_TO_DEG;
|
|
}
|
|
|
|
function latLonToLocalUnit(latDeg, lonDeg) {
|
|
const phi = (90 - latDeg) * DEG_TO_RAD;
|
|
const theta = (lonDeg + 180) * DEG_TO_RAD;
|
|
const sinPhi = Math.sin(phi);
|
|
return new THREE.Vector3(
|
|
-sinPhi * Math.cos(theta),
|
|
Math.cos(phi),
|
|
sinPhi * Math.sin(theta),
|
|
);
|
|
}
|
|
|
|
function createSphericalTileGeometry(z, x, y, radius, segments = DEFAULT_SEGMENTS) {
|
|
const n = 1 << z;
|
|
const lonMin = (x / n) * 360 - 180;
|
|
const lonMax = ((x + 1) / n) * 360 - 180;
|
|
|
|
const vertCount = (segments + 1) * (segments + 1);
|
|
const positions = new Float32Array(vertCount * 3);
|
|
const uvs = new Float32Array(vertCount * 2);
|
|
const globalUvs = new Float32Array(vertCount * 2);
|
|
const indices = [];
|
|
|
|
let ptr = 0;
|
|
let uvPtr = 0;
|
|
for (let j = 0; j <= segments; j += 1) {
|
|
const vFrac = j / segments;
|
|
// j runs North -> South while WebGL V=1 at north, V=0 at south
|
|
const ty = y + vFrac;
|
|
const lat = tileYToLat(ty, n);
|
|
const phi = (90 - lat) * DEG_TO_RAD;
|
|
const sinPhi = Math.sin(phi);
|
|
const cosPhi = Math.cos(phi);
|
|
const vCoord = 1 - vFrac;
|
|
const globalV = (lat + 90) / 180;
|
|
|
|
for (let i = 0; i <= segments; i += 1) {
|
|
const uFrac = i / segments;
|
|
const lon = lonMin + (lonMax - lonMin) * uFrac;
|
|
const theta = (lon + 180) * DEG_TO_RAD;
|
|
|
|
positions[ptr] = -(radius * sinPhi * Math.cos(theta));
|
|
positions[ptr + 1] = radius * cosPhi;
|
|
positions[ptr + 2] = radius * sinPhi * Math.sin(theta);
|
|
ptr += 3;
|
|
|
|
uvs[uvPtr] = uFrac;
|
|
uvs[uvPtr + 1] = vCoord;
|
|
globalUvs[uvPtr] = (lon + 180) / 360;
|
|
globalUvs[uvPtr + 1] = globalV;
|
|
uvPtr += 2;
|
|
}
|
|
}
|
|
|
|
const stride = segments + 1;
|
|
for (let j = 0; j < segments; j += 1) {
|
|
for (let i = 0; i < segments; i += 1) {
|
|
const a = j * stride + i;
|
|
const b = a + 1;
|
|
const c = (j + 1) * stride + i;
|
|
const d = c + 1;
|
|
// CCW outward winding for Three.js FrontSide on negative-x/positive-z sphere
|
|
indices.push(a, c, b);
|
|
indices.push(b, c, d);
|
|
}
|
|
}
|
|
|
|
const geom = new THREE.BufferGeometry();
|
|
geom.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
|
geom.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
|
|
geom.setAttribute("globalUv", new THREE.BufferAttribute(globalUvs, 2));
|
|
geom.setIndex(indices);
|
|
geom.computeVertexNormals();
|
|
return geom;
|
|
}
|
|
|
|
function buildTileMetadata(z, x, y, radius) {
|
|
const n = 1 << z;
|
|
const lonMin = (x / n) * 360 - 180;
|
|
const lonMax = ((x + 1) / n) * 360 - 180;
|
|
const latMax = tileYToLat(y, n);
|
|
const latMin = tileYToLat(y + 1, n);
|
|
const centerLat = (latMax + latMin) * 0.5;
|
|
const centerLon = (lonMin + lonMax) * 0.5;
|
|
const centerNormalLocal = latLonToLocalUnit(centerLat, centerLon);
|
|
const cornerVec = latLonToLocalUnit(latMax, lonMin);
|
|
const angRadius = Math.acos(Math.max(-1, Math.min(1, centerNormalLocal.dot(cornerVec))));
|
|
const chordDiameter = 2 * radius * Math.sin(Math.min(Math.PI * 0.49, angRadius));
|
|
return {
|
|
z,
|
|
x,
|
|
y,
|
|
key: `${z}/${x}/${y}`,
|
|
centerNormalLocal,
|
|
centerLocal: centerNormalLocal.clone().multiplyScalar(radius),
|
|
angRadius,
|
|
chordDiameter,
|
|
};
|
|
}
|
|
|
|
export function createSphericalTileLayer({
|
|
earthObj,
|
|
radius,
|
|
renderOrder,
|
|
name,
|
|
transparent = true,
|
|
opacity = 1.0,
|
|
minZoom = 5,
|
|
maxZoom = 7,
|
|
lodSwitchAltitude = 1.85,
|
|
maxConcurrent = 8,
|
|
maxCachedTiles = 512,
|
|
refineThresholdPx = 300,
|
|
createMaterial = null,
|
|
}) {
|
|
// Use plain Object3D without group.renderOrder so Three.js keeps groupOrder=0
|
|
// and sorts child tile meshes strictly against borders, cables, clouds, and satellites.
|
|
const group = new THREE.Object3D();
|
|
group.name = name;
|
|
group.visible = false;
|
|
group.raycast = () => {};
|
|
earthObj.add(group);
|
|
|
|
const cullRootZoom = Math.min(2, minZoom);
|
|
let _urlTemplate = null;
|
|
let _layerVisible = false;
|
|
let _maxZoom = maxZoom;
|
|
let _lodSwitchAltitude = lodSwitchAltitude;
|
|
let _generation = 0;
|
|
let _activeLoads = 0;
|
|
let _lastSelectAt = 0;
|
|
let _activeCoverage = 0;
|
|
let _lightingVersion = 1;
|
|
let _hasLightingApplied = false;
|
|
const _tmpVec = new THREE.Vector3();
|
|
|
|
let _lightingState = {
|
|
sunDirection: new THREE.Vector3(1, 0, 0),
|
|
dayNightEnabled: true,
|
|
landMask: null,
|
|
landMaskAvailable: 0,
|
|
maskOcean: new THREE.Vector3(),
|
|
maskLand: new THREE.Vector3(1, 1, 1),
|
|
opacity,
|
|
surfaceBrightness: 1.0,
|
|
baseDayMap: null,
|
|
colorGradeConfig: null,
|
|
};
|
|
|
|
const _cache = new Map(); // key -> { z, mesh, texture, geometry, material, lastUsed, state, readyAt, fade, hadSettled, wanted, score, abortController }
|
|
const _metaCache = new Map();
|
|
const _pendingQueue = [];
|
|
|
|
const _camLocal = new THREE.Vector3();
|
|
const _camDirLocal = new THREE.Vector3();
|
|
const _projViewMatrix = new THREE.Matrix4();
|
|
const _frustum = new THREE.Frustum();
|
|
const _tileSphere = new THREE.Sphere();
|
|
const _tileCenterWorld = new THREE.Vector3();
|
|
const _parentVisibleKeys = new Set();
|
|
const _childFallbackKeys = new Set();
|
|
|
|
function getTileMeta(z, x, y) {
|
|
const key = `${z}/${x}/${y}`;
|
|
let meta = _metaCache.get(key);
|
|
if (!meta) {
|
|
meta = buildTileMetadata(z, x, y, radius);
|
|
if (_metaCache.size < 4096) {
|
|
_metaCache.set(key, meta);
|
|
}
|
|
}
|
|
return meta;
|
|
}
|
|
|
|
function applyLightingToMaterial(mat, tileOpacity = null) {
|
|
if (!mat?.uniforms) return;
|
|
const u = mat.uniforms;
|
|
if (u.uSunDirectionWorld?.value) {
|
|
u.uSunDirectionWorld.value.copy(_lightingState.sunDirection);
|
|
}
|
|
if (u.uDayNightEnabled) {
|
|
u.uDayNightEnabled.value = _lightingState.dayNightEnabled ? 1 : 0;
|
|
}
|
|
if (u.uLandMask) {
|
|
u.uLandMask.value = _lightingState.landMask || null;
|
|
}
|
|
if (u.uLandMaskAvailable) {
|
|
u.uLandMaskAvailable.value = _lightingState.landMask ? 1 : 0;
|
|
}
|
|
if (u.uBaseDayMap) {
|
|
u.uBaseDayMap.value = _lightingState.baseDayMap || null;
|
|
}
|
|
if (u.uBaseDayMapAvailable) {
|
|
u.uBaseDayMapAvailable.value = _lightingState.baseDayMap ? 1 : 0;
|
|
}
|
|
if (u.uMaskOcean?.value && _lightingState.maskOcean) {
|
|
u.uMaskOcean.value.copy(_lightingState.maskOcean);
|
|
}
|
|
if (u.uMaskLand?.value && _lightingState.maskLand) {
|
|
u.uMaskLand.value.copy(_lightingState.maskLand);
|
|
}
|
|
if (u.uOpacity && Number.isFinite(Number(_lightingState.opacity))) {
|
|
u.uOpacity.value = Number(_lightingState.opacity);
|
|
}
|
|
if (u.uSurfaceBrightness && Number.isFinite(Number(_lightingState.surfaceBrightness))) {
|
|
u.uSurfaceBrightness.value = Number(_lightingState.surfaceBrightness);
|
|
}
|
|
const grade = _lightingState.colorGradeConfig;
|
|
if (grade) {
|
|
if (u.uExposure && Number.isFinite(Number(grade.exposure))) {
|
|
u.uExposure.value = Number(grade.exposure);
|
|
}
|
|
if (u.uLandSaturation && Number.isFinite(Number(grade.landSaturation))) {
|
|
u.uLandSaturation.value = Number(grade.landSaturation);
|
|
}
|
|
if (u.uLandGradeGain && Number.isFinite(Number(grade.landGradeGain))) {
|
|
u.uLandGradeGain.value = Number(grade.landGradeGain);
|
|
}
|
|
if (u.uLandCoolBias?.value && Array.isArray(grade.landCoolBias)) {
|
|
u.uLandCoolBias.value.set(grade.landCoolBias[0], grade.landCoolBias[1], grade.landCoolBias[2]);
|
|
}
|
|
if (u.uOceanAbsorption && Number.isFinite(Number(grade.oceanAbsorption))) {
|
|
u.uOceanAbsorption.value = Number(grade.oceanAbsorption);
|
|
}
|
|
if (u.uOceanDeepColor?.value && Array.isArray(grade.oceanDeepColor)) {
|
|
u.uOceanDeepColor.value.set(grade.oceanDeepColor[0], grade.oceanDeepColor[1], grade.oceanDeepColor[2]);
|
|
}
|
|
if (u.uLandReliefStrength && Number.isFinite(Number(grade.landReliefStrength))) {
|
|
u.uLandReliefStrength.value = Number(grade.landReliefStrength);
|
|
}
|
|
if (u.uDiffuseFloor && Number.isFinite(Number(grade.diffuseFloor))) {
|
|
u.uDiffuseFloor.value = Number(grade.diffuseFloor);
|
|
}
|
|
if (u.uToneMapMode && Number.isFinite(Number(grade.toneMapMode))) {
|
|
u.uToneMapMode.value = Number(grade.toneMapMode);
|
|
}
|
|
}
|
|
if (u.uTileOpacity && tileOpacity !== null) {
|
|
u.uTileOpacity.value = tileOpacity;
|
|
}
|
|
}
|
|
|
|
function disposeEntry(entry) {
|
|
if (!entry) return;
|
|
entry.abortController?.abort();
|
|
entry.abortController = null;
|
|
if (entry.mesh) group.remove(entry.mesh);
|
|
entry.texture?.dispose?.();
|
|
entry.geometry?.dispose?.();
|
|
entry.material?.dispose?.();
|
|
}
|
|
|
|
function evictIfNeeded() {
|
|
if (_cache.size <= maxCachedTiles) return;
|
|
const entries = [..._cache.entries()]
|
|
.filter(([, entry]) => entry.mesh && !entry.mesh.visible && entry.z > minZoom)
|
|
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
|
|
for (const [key, entry] of entries) {
|
|
if (_cache.size <= maxCachedTiles) break;
|
|
disposeEntry(entry);
|
|
_cache.delete(key);
|
|
}
|
|
if (_cache.size > maxCachedTiles) {
|
|
const remaining = [..._cache.entries()]
|
|
.filter(([, entry]) => entry.mesh && !entry.mesh.visible)
|
|
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
|
|
for (const [key, entry] of remaining) {
|
|
if (_cache.size <= maxCachedTiles) break;
|
|
disposeEntry(entry);
|
|
_cache.delete(key);
|
|
}
|
|
}
|
|
}
|
|
|
|
function clearAll() {
|
|
_generation += 1;
|
|
_pendingQueue.length = 0;
|
|
_activeCoverage = 0;
|
|
for (const entry of _cache.values()) {
|
|
disposeEntry(entry);
|
|
}
|
|
_cache.clear();
|
|
}
|
|
|
|
function buildEntryMaterial(texture, z) {
|
|
const polyOffset = -1 - Math.max(0, z - minZoom);
|
|
if (typeof createMaterial === "function") {
|
|
const mat = createMaterial({
|
|
texture,
|
|
polygonOffsetFactor: polyOffset,
|
|
tileOpacity: 0.0,
|
|
lighting: _lightingState,
|
|
});
|
|
applyLightingToMaterial(mat, 0.0);
|
|
return mat;
|
|
}
|
|
return new THREE.MeshBasicMaterial({
|
|
map: texture,
|
|
transparent: true,
|
|
opacity: 0.0,
|
|
depthTest: true,
|
|
depthWrite: false,
|
|
toneMapped: false,
|
|
polygonOffset: true,
|
|
polygonOffsetFactor: polyOffset,
|
|
polygonOffsetUnits: polyOffset,
|
|
});
|
|
}
|
|
|
|
function setMeshFade(entry, fade) {
|
|
entry.fade = fade;
|
|
if (fade >= 1) {
|
|
entry.hadSettled = true;
|
|
}
|
|
if (!entry.mesh?.material) return;
|
|
const mat = entry.mesh.material;
|
|
if (mat.uniforms?.uTileOpacity) {
|
|
mat.uniforms.uTileOpacity.value = fade;
|
|
} else {
|
|
mat.opacity = opacity * fade;
|
|
}
|
|
}
|
|
|
|
function queueTile(meta, score, now) {
|
|
const existing = _cache.get(meta.key);
|
|
if (existing) {
|
|
existing.lastUsed = now;
|
|
existing.score = score;
|
|
return existing;
|
|
}
|
|
const entry = {
|
|
z: meta.z,
|
|
state: "queued",
|
|
lastUsed: now,
|
|
score,
|
|
wanted: true,
|
|
readyAt: 0,
|
|
fade: 0,
|
|
hadSettled: false,
|
|
abortController: null,
|
|
mesh: null,
|
|
texture: null,
|
|
geometry: null,
|
|
material: null,
|
|
};
|
|
_cache.set(meta.key, entry);
|
|
_pendingQueue.push({
|
|
z: meta.z,
|
|
x: meta.x,
|
|
y: meta.y,
|
|
key: meta.key,
|
|
generation: _generation,
|
|
});
|
|
return entry;
|
|
}
|
|
|
|
function pumpQueue() {
|
|
if (_pendingQueue.length > 1) {
|
|
_pendingQueue.sort((a, b) => {
|
|
const ea = _cache.get(a.key);
|
|
const eb = _cache.get(b.key);
|
|
const pa = ea ? ea.z * 0.25 + ea.score : 999;
|
|
const pb = eb ? eb.z * 0.25 + eb.score : 999;
|
|
return pa - pb;
|
|
});
|
|
}
|
|
while (_activeLoads < maxConcurrent && _pendingQueue.length > 0) {
|
|
const job = _pendingQueue.shift();
|
|
if (!job || job.generation !== _generation || !_urlTemplate) continue;
|
|
const entry = _cache.get(job.key);
|
|
if (!entry || entry.state !== "queued" || !entry.wanted) {
|
|
if (entry && entry.state === "queued" && !entry.wanted) {
|
|
_cache.delete(job.key);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
entry.state = "loading";
|
|
const abortController = typeof AbortController === "function" ? new AbortController() : null;
|
|
entry.abortController = abortController;
|
|
_activeLoads += 1;
|
|
const url = _urlTemplate
|
|
.replace("{z}", String(job.z))
|
|
.replace("{x}", String(job.x))
|
|
.replace("{y}", String(job.y));
|
|
|
|
earthTextureImages
|
|
.load(url, { signal: abortController?.signal })
|
|
.then((image) => {
|
|
if (
|
|
abortController?.signal?.aborted ||
|
|
job.generation !== _generation ||
|
|
_cache.get(job.key) !== entry
|
|
) {
|
|
if (typeof image?.close === "function") image.close();
|
|
return;
|
|
}
|
|
const texture = new THREE.Texture(image);
|
|
if (typeof image.close === "function") {
|
|
texture.flipY = false;
|
|
texture.addEventListener("dispose", () => image.close());
|
|
}
|
|
configureColorTexture(texture);
|
|
texture.wrapS = THREE.ClampToEdgeWrapping;
|
|
texture.wrapT = THREE.ClampToEdgeWrapping;
|
|
texture.minFilter = THREE.LinearFilter;
|
|
texture.magFilter = THREE.LinearFilter;
|
|
texture.needsUpdate = true;
|
|
|
|
const geometry = createSphericalTileGeometry(job.z, job.x, job.y, radius);
|
|
const material = buildEntryMaterial(texture, job.z);
|
|
const mesh = new THREE.Mesh(geometry, material);
|
|
mesh.renderOrder = renderOrder + job.z * 0.00005;
|
|
mesh.raycast = () => {};
|
|
mesh.visible = Boolean(_layerVisible && entry.wanted);
|
|
|
|
entry.texture = texture;
|
|
entry.geometry = geometry;
|
|
entry.material = material;
|
|
entry.mesh = mesh;
|
|
entry.lightingVersion = _lightingVersion;
|
|
entry.state = "ready";
|
|
entry.readyAt = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
entry.fade = 0;
|
|
group.add(mesh);
|
|
evictIfNeeded();
|
|
})
|
|
.catch(() => {
|
|
if (_cache.get(job.key) === entry) {
|
|
_cache.delete(job.key);
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (entry.abortController === abortController) {
|
|
entry.abortController = null;
|
|
}
|
|
_activeLoads = Math.max(0, _activeLoads - 1);
|
|
pumpQueue();
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
group,
|
|
getActiveCoverage() {
|
|
return _layerVisible && _urlTemplate ? _activeCoverage : 0;
|
|
},
|
|
setLighting({
|
|
sunDirection,
|
|
dayNightEnabled,
|
|
landMask,
|
|
maskOcean,
|
|
maskLand,
|
|
opacity: nextOpacity,
|
|
surfaceBrightness,
|
|
baseDayMap,
|
|
colorGradeConfig,
|
|
} = {}) {
|
|
let changed = !_hasLightingApplied;
|
|
if (sunDirection) {
|
|
_tmpVec.copy(sunDirection);
|
|
if (_tmpVec.lengthSq() > 1e-12) {
|
|
_tmpVec.normalize();
|
|
if (_lightingState.sunDirection.distanceToSquared(_tmpVec) > 1e-10) {
|
|
_lightingState.sunDirection.copy(_tmpVec);
|
|
changed = true;
|
|
}
|
|
}
|
|
}
|
|
if (typeof dayNightEnabled === "boolean" && _lightingState.dayNightEnabled !== dayNightEnabled) {
|
|
_lightingState.dayNightEnabled = dayNightEnabled;
|
|
changed = true;
|
|
}
|
|
if (landMask !== undefined) {
|
|
const nextMask = landMask || null;
|
|
if (_lightingState.landMask !== nextMask) {
|
|
_lightingState.landMask = nextMask;
|
|
_lightingState.landMaskAvailable = nextMask ? 1 : 0;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (baseDayMap !== undefined) {
|
|
const nextBase = baseDayMap || null;
|
|
if (_lightingState.baseDayMap !== nextBase) {
|
|
_lightingState.baseDayMap = nextBase;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (colorGradeConfig !== undefined) {
|
|
const nextGrade = colorGradeConfig || null;
|
|
if (_lightingState.colorGradeConfig !== nextGrade) {
|
|
_lightingState.colorGradeConfig = nextGrade;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (maskOcean !== undefined && _lightingState.maskOcean) {
|
|
if (typeof maskOcean === "number") {
|
|
_tmpVec.set(((maskOcean >> 16) & 255) / 255, ((maskOcean >> 8) & 255) / 255, (maskOcean & 255) / 255);
|
|
if (_lightingState.maskOcean.distanceToSquared(_tmpVec) > 1e-10) {
|
|
_lightingState.maskOcean.copy(_tmpVec);
|
|
changed = true;
|
|
}
|
|
} else if (maskOcean?.isVector3 && _lightingState.maskOcean.distanceToSquared(maskOcean) > 1e-10) {
|
|
_lightingState.maskOcean.copy(maskOcean);
|
|
changed = true;
|
|
}
|
|
}
|
|
if (maskLand !== undefined && _lightingState.maskLand) {
|
|
if (typeof maskLand === "number") {
|
|
_tmpVec.set(((maskLand >> 16) & 255) / 255, ((maskLand >> 8) & 255) / 255, (maskLand & 255) / 255);
|
|
if (_lightingState.maskLand.distanceToSquared(_tmpVec) > 1e-10) {
|
|
_lightingState.maskLand.copy(_tmpVec);
|
|
changed = true;
|
|
}
|
|
} else if (maskLand?.isVector3 && _lightingState.maskLand.distanceToSquared(maskLand) > 1e-10) {
|
|
_lightingState.maskLand.copy(maskLand);
|
|
changed = true;
|
|
}
|
|
}
|
|
if (Number.isFinite(Number(nextOpacity))) {
|
|
const op = Number(nextOpacity);
|
|
if (_lightingState.opacity !== op) {
|
|
_lightingState.opacity = op;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (Number.isFinite(Number(surfaceBrightness))) {
|
|
const sb = Number(surfaceBrightness);
|
|
if (_lightingState.surfaceBrightness !== sb) {
|
|
_lightingState.surfaceBrightness = sb;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (!changed) return;
|
|
|
|
_hasLightingApplied = true;
|
|
_lightingVersion += 1;
|
|
for (const entry of _cache.values()) {
|
|
if (entry.mesh?.visible && entry.mesh.material) {
|
|
applyLightingToMaterial(entry.mesh.material, null);
|
|
entry.lightingVersion = _lightingVersion;
|
|
}
|
|
}
|
|
},
|
|
setTemplate(urlTemplate, { maxZoom: nextMaxZoom, lodSwitchAltitude: nextLod } = {}) {
|
|
const normalized = urlTemplate || null;
|
|
if (Number.isFinite(Number(nextMaxZoom))) _maxZoom = Math.max(minZoom, Math.round(Number(nextMaxZoom)));
|
|
if (Number.isFinite(Number(nextLod))) _lodSwitchAltitude = Math.max(1.1, Number(nextLod));
|
|
if (normalized === _urlTemplate) return;
|
|
_urlTemplate = normalized;
|
|
clearAll();
|
|
group.visible = Boolean(_layerVisible && _urlTemplate);
|
|
},
|
|
setVisible(visible) {
|
|
_layerVisible = Boolean(visible);
|
|
group.visible = Boolean(_layerVisible && _urlTemplate);
|
|
if (!_layerVisible) {
|
|
_activeCoverage = 0;
|
|
for (const entry of _cache.values()) {
|
|
if (entry.mesh) entry.mesh.visible = false;
|
|
}
|
|
}
|
|
},
|
|
update(camera, globeObj = earthObj) {
|
|
if (!_layerVisible || !_urlTemplate || !camera || !globeObj) {
|
|
group.visible = false;
|
|
_activeCoverage = 0;
|
|
return;
|
|
}
|
|
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
const camDist = camera.position.length();
|
|
const altRatio = camDist / Math.max(1, radius);
|
|
if (altRatio > _lodSwitchAltitude) {
|
|
group.visible = false;
|
|
_activeCoverage = 0;
|
|
return;
|
|
}
|
|
group.visible = true;
|
|
|
|
// Advance active tile fades smoothly every frame without rebuilding quadtree
|
|
for (const entry of _cache.values()) {
|
|
if (entry.state === "ready" && entry.mesh?.visible) {
|
|
if (entry.hadSettled) {
|
|
if (entry.fade < 1) setMeshFade(entry, 1.0);
|
|
} else if (entry.fade < 1) {
|
|
const nextFade = Math.min(1, (now - entry.readyAt) / FADE_DURATION_MS);
|
|
setMeshFade(entry, nextFade);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (now - _lastSelectAt < 32) return;
|
|
_lastSelectAt = now;
|
|
|
|
globeObj.worldToLocal(_camLocal.copy(camera.position));
|
|
_camDirLocal.copy(_camLocal).normalize();
|
|
const cosHorizon = Math.min(0.99, radius / Math.max(radius + 0.1, camDist));
|
|
const horizonRad = Math.acos(cosHorizon);
|
|
|
|
const fovRad = ((camera.fov || 45) * Math.PI) / 180;
|
|
const viewportHeight = (typeof window !== "undefined" && window.innerHeight) ? window.innerHeight : 900;
|
|
const pxPerUnitAtDist1 = viewportHeight / (2 * Math.tan(fovRad * 0.5));
|
|
|
|
let useFrustum = false;
|
|
if (camera.projectionMatrix && camera.matrixWorldInverse) {
|
|
_projViewMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
|
|
_frustum.setFromProjectionMatrix(_projViewMatrix);
|
|
useFrustum = true;
|
|
}
|
|
|
|
const isTileVisible = (meta) => {
|
|
const dotCenter = meta.centerNormalLocal.dot(_camDirLocal);
|
|
const maxAngle = horizonRad + meta.angRadius * 1.15;
|
|
if (maxAngle < Math.PI && dotCenter < Math.cos(maxAngle)) {
|
|
return false;
|
|
}
|
|
if (useFrustum) {
|
|
_tileCenterWorld.copy(meta.centerLocal).applyMatrix4(globeObj.matrixWorld);
|
|
_tileSphere.set(_tileCenterWorld, meta.chordDiameter * 0.58);
|
|
if (!_frustum.intersectsSphere(_tileSphere)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
};
|
|
|
|
_parentVisibleKeys.clear();
|
|
_childFallbackKeys.clear();
|
|
let leafCount = 0;
|
|
let leafReadyCount = 0;
|
|
|
|
const visitNode = (meta) => {
|
|
if (!isTileVisible(meta)) return null;
|
|
|
|
if (meta.z < minZoom) {
|
|
const cz = meta.z + 1;
|
|
for (let dy = 0; dy < 2; dy += 1) {
|
|
for (let dx = 0; dx < 2; dx += 1) {
|
|
const childMeta = getTileMeta(cz, meta.x * 2 + dx, meta.y * 2 + dy);
|
|
if (isTileVisible(childMeta)) {
|
|
visitNode(childMeta);
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
const score = 1 - meta.centerNormalLocal.dot(_camDirLocal);
|
|
const distToCamera = Math.max(radius * 0.05, _camLocal.distanceTo(meta.centerLocal));
|
|
const screenPx = (meta.chordDiameter / distToCamera) * pxPerUnitAtDist1;
|
|
const shouldRefine = meta.z < _maxZoom && screenPx > refineThresholdPx;
|
|
|
|
if (!shouldRefine) {
|
|
const entry = queueTile(meta, score, now);
|
|
_parentVisibleKeys.add(meta.key);
|
|
leafCount += 1;
|
|
if (entry.state === "ready") leafReadyCount += 1;
|
|
return entry.state === "ready" && (entry.hadSettled || entry.fade >= 1);
|
|
}
|
|
|
|
const parentEntry = meta.z === minZoom ? queueTile(meta, score, now) : _cache.get(meta.key);
|
|
if (parentEntry) {
|
|
parentEntry.lastUsed = now;
|
|
parentEntry.score = score;
|
|
}
|
|
|
|
const cz = meta.z + 1;
|
|
let allVisibleChildrenSettled = true;
|
|
let visibleChildCount = 0;
|
|
|
|
for (let dy = 0; dy < 2; dy += 1) {
|
|
for (let dx = 0; dx < 2; dx += 1) {
|
|
const childMeta = getTileMeta(cz, meta.x * 2 + dx, meta.y * 2 + dy);
|
|
if (!isTileVisible(childMeta)) continue;
|
|
visibleChildCount += 1;
|
|
const childSettled = visitNode(childMeta);
|
|
if (!childSettled) {
|
|
allVisibleChildrenSettled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Keep parent visible at full opacity until EVERY visible descendant has faded to 1.0
|
|
if (visibleChildCount > 0 && !allVisibleChildrenSettled && parentEntry) {
|
|
_childFallbackKeys.add(meta.key);
|
|
}
|
|
return allVisibleChildrenSettled;
|
|
};
|
|
|
|
const rootDim = 1 << cullRootZoom;
|
|
for (let ry = 0; ry < rootDim; ry += 1) {
|
|
for (let rx = 0; rx < rootDim; rx += 1) {
|
|
visitNode(getTileMeta(cullRootZoom, rx, ry));
|
|
}
|
|
}
|
|
|
|
for (const [key, entry] of _cache.entries()) {
|
|
const keepWanted = _parentVisibleKeys.has(key) || _childFallbackKeys.has(key);
|
|
entry.wanted = keepWanted;
|
|
if (!keepWanted) {
|
|
if (entry.state === "queued") {
|
|
_cache.delete(key);
|
|
continue;
|
|
}
|
|
if (entry.state === "loading") {
|
|
entry.abortController?.abort();
|
|
entry.abortController = null;
|
|
_cache.delete(key);
|
|
continue;
|
|
}
|
|
}
|
|
if (entry.mesh) {
|
|
entry.mesh.visible = keepWanted;
|
|
if (keepWanted) {
|
|
if (entry.lightingVersion !== _lightingVersion && entry.mesh.material) {
|
|
applyLightingToMaterial(entry.mesh.material, null);
|
|
entry.lightingVersion = _lightingVersion;
|
|
}
|
|
if (_childFallbackKeys.has(key) && !_parentVisibleKeys.has(key)) {
|
|
setMeshFade(entry, 1.0);
|
|
} else if (entry.hadSettled) {
|
|
setMeshFade(entry, 1.0);
|
|
} else if (entry.state === "ready" && entry.fade < 1) {
|
|
setMeshFade(entry, Math.min(1, (now - entry.readyAt) / FADE_DURATION_MS));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (let i = _pendingQueue.length - 1; i >= 0; i -= 1) {
|
|
const job = _pendingQueue[i];
|
|
const entry = _cache.get(job.key);
|
|
if (!entry || entry.state !== "queued" || !entry.wanted) {
|
|
_pendingQueue.splice(i, 1);
|
|
}
|
|
}
|
|
|
|
_activeCoverage = leafCount > 0 ? leafReadyCount / leafCount : 0;
|
|
pumpQueue();
|
|
evictIfNeeded();
|
|
},
|
|
dispose() {
|
|
clearAll();
|
|
earthObj.remove(group);
|
|
},
|
|
};
|
|
}
|