Merge pull request #1173 from Rohilalala/fix/geo-distance-dateline

fix(geo): wrap longitude differences across the antimeridian
This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-10-16 15:46:27 -07:00
commit 5a79a4d246
12 files changed
+167 -35

No files matched your search

@@ -0,0 +1,10 @@
- Flights' ground floor works across the antimeridian. The viewer-distance
check behind the 150 km floor radius and its copy in the photoreal mesh-floor
sampler subtracted longitudes without wrapping, so two points 21 km apart
across 180° measured about 38,000 km and low or grounded aircraft just across
the line from the viewer were never floored. A contact's display corridor
walked a segment across 180° the long way round, spending its cell budget on
ground behind the contact, and a contact on the seam lost its cell hysteresis.
SEARCH NEARBY SITES on a view across 180° searched Google Places around
longitude 0, on the far side of the globe, with a radius sized from the view's
height alone; it now searches the view (Aditya, @Rohilalala, #1173).
+6 -2
View File
@@ -3221,7 +3221,11 @@ test:track` 43 tracking invariants · headless QA harnesses under
> metres low. `qa-floor-verify.mjs` now **exits non-zero on FAIL** (1 = FAIL, > metres low. `qa-floor-verify.mjs` now **exits non-zero on FAIL** (1 = FAIL,
> 2 = INCONCLUSIVE); it previously exited 0 on every verdict, which is how the > 2 = INCONCLUSIVE); it previously exited 0 on every verdict, which is how the
> burial stayed invisible. It also honours `QA_BASE_URL` and puppeteer's > burial stayed invisible. It also honours `QA_BASE_URL` and puppeteer's
> pinned Chrome-for-Testing, like the other harnesses. > pinned Chrome-for-Testing, like the other harnesses. The viewer-distance
> gate, the corridor walk and cell hysteresis take the short way across 180°
> (`src/data/approxDistance.js` is the one distance both the flights records
> and the mesh-floor sampler use), so contacts just across the antimeridian
> are floored like any other.
> - **2026-07-16:** the FIRMS Active Fires layer is **LIVE** — > - **2026-07-16:** the FIRMS Active Fires layer is **LIVE** —
> the bundled 2026-05-25 snapshot (58 MB) is deleted; a new `/api/firms` proxy > the bundled 2026-05-25 snapshot (58 MB) is deleted; a new `/api/firms` proxy
> (vite.config.js) merges VIIRS NOAA-20/NOAA-21/Suomi-NPP NRT world CSVs > (vite.config.js) merges VIIRS NOAA-20/NOAA-21/Suomi-NPP NRT world CSVs
@@ -4249,7 +4253,7 @@ silently demoting every later lookup for the session.
- The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected. - The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected.
- The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies. - The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies.
- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. - If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft.
- `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. - `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width.
- The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset. - The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset.
- Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`. - Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`.
- Space Missions is replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally. - Space Missions is replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally.
+8 -1
View File
@@ -901,6 +901,7 @@
"src/data/aircraftIcons.js", "src/data/aircraftIcons.js",
"src/data/aircraftMeta.js", "src/data/aircraftMeta.js",
"src/data/aircraftNearbyPolicy.js", "src/data/aircraftNearbyPolicy.js",
"src/data/approxDistance.js",
"src/data/cockpitAirLod.js", "src/data/cockpitAirLod.js",
"src/data/cockpitContactDot.js", "src/data/cockpitContactDot.js",
"src/data/contactMatch.js", "src/data/contactMatch.js",
@@ -1649,6 +1650,7 @@
"src/ui/radioPanelPlacement.js", "src/ui/radioPanelPlacement.js",
"src/cyberSonarGpu.js", "src/cyberSonarGpu.js",
"src/scenes/nepalEvidencePack.js", "src/scenes/nepalEvidencePack.js",
"src/data/approxDistance.js",
"src/data/bhoteKoshiEvent.js", "src/data/bhoteKoshiEvent.js",
"src/ui/imagerySplit.js", "src/ui/imagerySplit.js",
"src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiEmbeddedMedia.js",
@@ -2500,6 +2502,7 @@
"exports": ["./application/layers"], "exports": ["./application/layers"],
"modules": [ "modules": [
"src/cyberSonar.js", "src/cyberSonar.js",
"src/data/approxDistance.js",
"src/data/bhoteKoshiEvent.js", "src/data/bhoteKoshiEvent.js",
"src/ui/imagerySplit.js", "src/ui/imagerySplit.js",
"src/maps/imageryComparison.js", "src/maps/imageryComparison.js",
@@ -3067,6 +3070,7 @@
"src/app/operations.js", "src/app/operations.js",
"src/sources/sourceSlot.js", "src/sources/sourceSlot.js",
"src/app/surfaceServices.js", "src/app/surfaceServices.js",
"src/data/approxDistance.js",
"src/data/dataCredits.js", "src/data/dataCredits.js",
"src/data/geoid.js", "src/data/geoid.js",
"src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/marine.json",
@@ -3226,6 +3230,7 @@
"src/layers/flights/records.js", "src/layers/flights/records.js",
"src/layers/flights/recordPolicy.js", "src/layers/flights/recordPolicy.js",
"src/data/aircraftMeta.js", "src/data/aircraftMeta.js",
"src/data/approxDistance.js",
"src/data/renderAltitude.js", "src/data/renderAltitude.js",
"src/data/aircraftClass.js", "src/data/aircraftClass.js",
"src/data/aircraftEmergency.js" "src/data/aircraftEmergency.js"
@@ -3236,7 +3241,8 @@
"exports": ["./layers/flights/ingestion"], "exports": ["./layers/flights/ingestion"],
"modules": [ "modules": [
"src/layers/flights/ingestion.js", "src/layers/flights/ingestion.js",
"src/layers/flights/recordPolicy.js" "src/layers/flights/recordPolicy.js",
"src/data/approxDistance.js"
], ],
"external": [] "external": []
}, },
@@ -3547,6 +3553,7 @@
"src/cyberSonar.js", "src/cyberSonar.js",
"src/app/sourceSlot.js", "src/app/sourceSlot.js",
"src/celestialRing.js", "src/celestialRing.js",
"src/data/approxDistance.js",
"src/data/cameraSensitivity.js", "src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
+12
View File
@@ -0,0 +1,12 @@
/**
* Local equirectangular distance in km, for viewer-proximity gates. Takes the
* short way round, so points either side of 180° stay close.
*/
export function approxDistanceKm(lat1, lon1, lat2, lon2) {
const dLat = (lat2 - lat1) * 111.32;
let dLonDeg = lon2 - lon1;
dLonDeg -= 360 * Math.round(dLonDeg / 360);
const dLon =
dLonDeg * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
return Math.hypot(dLat, dLon);
}
+26
View File
@@ -257,6 +257,32 @@ test('stickyFloorCell does not stick to a far-away stale cell', () => {
assert.deepEqual(stickyFloorCell(30.2004, -97.6604, prev), { lat: 30.2, lon: -97.66 }); assert.deepEqual(stickyFloorCell(30.2004, -97.6604, prev), { lat: 30.2, lon: -97.66 });
}); });
// --- Antimeridian ------------------------------------------------------------
// Raw longitude arithmetic walks a segment across 180° the long way round and
// reads a contact on the seam as half a world from its previous cell.
test('corridorFloorCells walks across the antimeridian, not the long way round', () => {
for (const [from, to, across, behind] of [
[179.999, -179.998, -179.999, 179.998],
[-179.999, 179.998, 179.999, -179.998],
]) {
const cells = corridorFloorCells([{ lat: -16.69, lon: from }, { lat: -16.69, lon: to }]);
const lons = cells.map((c) => c.lon);
assert.equal(lons[0], from);
assert.equal(lons.at(-1), to);
assert.ok(lons.includes(across), `crosses through ${across}: ${lons}`);
assert.ok(!lons.includes(behind), `never walks back through ${behind}: ${lons}`);
assert.ok(lons.every((lon) => Math.abs(lon) <= 180), `normalised: ${lons}`);
}
});
test('stickyFloorCell holds across the antimeridian', () => {
for (const [prevLon, lon] of [[180, -179.9998], [-180, 179.9998]]) {
const prev = { lat: -16.69, lon: prevLon };
assert.deepEqual(stickyFloorCell(-16.69, lon, prev), prev);
}
});
// --- F2: corridor budget fairness ------------------------------------------ // --- F2: corridor budget fairness ------------------------------------------
// The first cut spent the budget in Map insertion order and decremented it // The first cut spent the budget in Map insertion order and decremented it
// BEFORE deduping, so parked contacts (whose corridor is the fix cell the poll // BEFORE deduping, so parked contacts (whose corridor is the fix cell the poll
+9
View File
@@ -128,3 +128,12 @@ test('sampler: outside the google-3d regime nothing is sampled at all', () => {
setMeshFloorPreferred(true); setMeshFloorPreferred(true);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), null); assert.equal(cachedMeshFloor(cell.lat, cell.lon), null);
}); });
test('sampler: a cell just across the antimeridian is still near the viewer', () => {
reset();
let calls = 0;
const scene = fakeScene(() => { calls += 1; return undefined; });
sampleMeshFloorCells(scene, [{ lat: -16.8, lon: -179.999 }], { viewerLat: -16.8, viewerLon: 179.999 });
sampleMeshFloorCells(scene, [{ lat: -16.81, lon: 179.999 }], { viewerLat: -16.81, viewerLon: -179.999 });
assert.equal(calls, 2, 'about 200 m apart, so both cells are probed');
});
+1 -6
View File
@@ -13,9 +13,4 @@ export const MISSING_POLL_LIMIT = 3;
export const ERROR_BACKOFF_INTERVAL = 20000; export const ERROR_BACKOFF_INTERVAL = 20000;
/** Local equirectangular distance used for viewer-proximate floor sampling. */ /** Local equirectangular distance used for viewer-proximate floor sampling. */
export function approxDistanceKm(lat1, lon1, lat2, lon2) { export { approxDistanceKm } from '../../data/approxDistance.js';
const dLat = (lat2 - lat1) * 111.32;
const dLon =
(lon2 - lon1) * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
return Math.hypot(dLat, dLon);
}
+18
View File
@@ -0,0 +1,18 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
approxDistanceKm,
GROUND_FLOOR_CLAMP_RADIUS_KM,
} from './recordPolicy.js';
test('approximate distance takes the short way across the antimeridian', () => {
// 0.2° of longitude at Taveuni, Fiji (16.8° S) is about 21 km.
for (const [lon1, lon2] of [
[179.9, -179.9],
[-179.9, 179.9],
]) {
const km = approxDistanceKm(-16.8, lon1, -16.8, lon2);
assert.ok(Math.abs(km - 21.31) < 0.01, `${lon1} → ${lon2}: ${km} km`);
assert.ok(km <= GROUND_FLOOR_CLAMP_RADIUS_KM);
}
});
+5 -4
View File
@@ -134,15 +134,16 @@ export function createIngestion({
let placesError = null; let placesError = null;
if (layerState.googleSearchRequested) { if (layerState.googleSearchRequested) {
layerState.googleSearchRequested = false; layerState.googleSearchRequested = false;
// A view across 180° has west > east; its width runs through 180°.
const lonSpan = box.east - box.west + (box.east < box.west ? 360 : 0);
const latitude = (box.south + box.north) / 2; const latitude = (box.south + box.north) / 2;
const longitude = (box.west + box.east) / 2; let longitude = box.west + lonSpan / 2;
if (longitude > 180) longitude -= 360;
const radiusM = Math.min( const radiusM = Math.min(
50000, 50000,
Math.max( Math.max(
1000, 1000,
Math.round( Math.round(Math.max(box.north - box.south, lonSpan) * 55_000),
Math.max(box.north - box.south, box.east - box.west) * 55_000,
),
), ),
); );
try { try {
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createIngestion } from './ingestion.js';
// Taveuni, Fiji: Cesium reports a view across 180° with west > east. Each view
// is 0.4° wide and 0.2° tall; the last one does not cross 180°.
for (const [west, east, centre] of [
[179.7, -179.9, 179.9],
[179.9, -179.7, -179.9],
[179.5, 179.9, 179.7],
])
test(`a nearby search is centred on the view at ${centre}`, async () => {
const box = { south: -17, west, north: -16.8, east };
const searches = [];
const state = {
enabled: true,
viewer: {},
records: [],
googleSearchRequested: true,
};
const ingestion = createIngestion({
state,
source: {
getMappedSites: async () => ({ records: [], wide: true }),
searchNearby: async (query) => {
searches.push(query);
return { places: [] };
},
},
services: {
render: { governorRequestRender() {} },
ground: { resolveGroundFloorCellsBounded: async () => {} },
},
parts: {
viewport: {
loadArea: () => ({ box, coverage: {} }),
clearUnavailableRetry() {},
scheduleUnavailableRetry() {},
},
model: { installationWithinViewport: () => true },
rendering: { renderRecords() {}, warmInstallationFloors() {} },
},
});
await ingestion.loadInstallations();
assert.equal(searches.length, 1);
const { latitude, longitude, radiusM } = searches[0];
assert.ok(Math.abs(latitude + 16.9) < 1e-9);
assert.ok(Math.abs(longitude - centre) < 1e-9, `longitude ${longitude}`);
// The width, not the height, sets the radius.
assert.equal(radiusM, 22000);
});
+18 -11
View File
@@ -204,12 +204,16 @@ export function createGroundFloor({ terrain, signal }) {
* @returns {{lat: number, lon: number}} The cell to read. * @returns {{lat: number, lon: number}} The cell to read.
*/ */
function stickyFloorCell(lat, lon, previousCell) { function stickyFloorCell(lat, lon, previousCell) {
if ( if (previousCell) {
previousCell && // The short way round, so a contact on the 180° seam keeps its cell.
Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG && let dLon = lon - previousCell.lon;
Math.abs(lon - previousCell.lon) <= 0.0005 + CELL_HYSTERESIS_DEG dLon -= 360 * Math.round(dLon / 360);
) { if (
return previousCell; Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG &&
Math.abs(dLon) <= 0.0005 + CELL_HYSTERESIS_DEG
) {
return previousCell;
}
} }
return coarseFloorCoord(lat, lon); return coarseFloorCoord(lat, lon);
} }
@@ -269,17 +273,20 @@ export function createGroundFloor({ terrain, signal }) {
const a = points[s]; const a = points[s];
const b = points[s + 1]; const b = points[s + 1];
if (![a?.lat, a?.lon, b?.lat, b?.lon].every(Number.isFinite)) continue; if (![a?.lat, a?.lon, b?.lat, b?.lon].every(Number.isFinite)) continue;
// The short way round, so a segment across 180° walks across it.
let dLon = b.lon - a.lon;
dLon -= 360 * Math.round(dLon / 360);
const steps = Math.ceil( const steps = Math.ceil(
Math.max(Math.abs(b.lat - a.lat), Math.abs(b.lon - a.lon)) / Math.max(Math.abs(b.lat - a.lat), Math.abs(dLon)) /
CORRIDOR_WALK_STEP_DEG, CORRIDOR_WALK_STEP_DEG,
); );
for (let i = 1; i <= steps; i++) { for (let i = 1; i <= steps; i++) {
if (out.length >= prefixLimit) break walk; if (out.length >= prefixLimit) break walk;
const t = i / steps; const t = i / steps;
const cell = coarseFloorCoord( let lon = a.lon + dLon * t;
a.lat + (b.lat - a.lat) * t, if (lon > 180) lon -= 360;
a.lon + (b.lon - a.lon) * t, else if (lon < -180) lon += 360;
); const cell = coarseFloorCoord(a.lat + (b.lat - a.lat) * t, lon);
const key = `${cell.lat},${cell.lon}`; const key = `${cell.lat},${cell.lon}`;
if (seen.has(key) || key === destKey) continue; if (seen.has(key) || key === destKey) continue;
seen.add(key); seen.add(key);
+3 -11
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { approxDistanceKm } from '../data/approxDistance.js';
/** Construct an instance-owned meshFloorSampler service with explicit dependencies. */ /** Construct an instance-owned meshFloorSampler service with explicit dependencies. */
export function createMeshFloorSampler({ export function createMeshFloorSampler({
@@ -79,16 +80,6 @@ export function createMeshFloorSampler({
return false; return false;
} }
/**
* Equirectangular distance (km) — same approximation the flights clamp uses.
*/
function _approxKm(lat1, lon1, lat2, lon2) {
const dLat = (lat2 - lat1) * 111.32;
const dLon =
(lon2 - lon1) * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
return Math.hypot(dLat, dLon);
}
/** /**
* Samples the rendered mesh height for the coarse cells containing `points`, * Samples the rendered mesh height for the coarse cells containing `points`,
* one-shot per cell, budget-capped, viewer-proximity-gated. Call ONCE per * one-shot per cell, budget-capped, viewer-proximity-gated. Call ONCE per
@@ -133,7 +124,8 @@ export function createMeshFloorSampler({
if ( if (
Number.isFinite(viewerLat) && Number.isFinite(viewerLat) &&
Number.isFinite(viewerLon) && Number.isFinite(viewerLon) &&
_approxKm(viewerLat, viewerLon, cell.lat, cell.lon) > MAX_SAMPLE_DIST_KM approxDistanceKm(viewerLat, viewerLon, cell.lat, cell.lon) >
MAX_SAMPLE_DIST_KM
) { ) {
continue; // too far: tiles not streamed there, probe would be a guaranteed miss continue; // too far: tiles not streamed there, probe would be a guaranteed miss
} }