+
+ ${escapeHtml(req.action_type)} · ${escapeHtml(req.status)}
+ ${escapeHtml(req.requested_by || "system")}
+
+ ${escapeHtml((req.target_object_ids || []).join(", ") || "—")}
+ ${req.decision_reason ? `${escapeHtml(req.decision_reason)}
` : ""}
+ ${
+ editable && req.status === "pending"
+ ? `
+
+
+
+
`
+ : ""
+ }
+ `,
+ )
+ .join("");
+ };
+
+ const refresh = async (objectId = "") => {
+ const url = objectId ? `/api/v1/actions?object_id=${encodeURIComponent(objectId)}` : "/api/v1/actions?limit=100";
+ const data = await fetchEarthJson(url);
+ items = Array.isArray(data?.items) ? data.items : [];
+ render();
+ return items;
+ };
+
+ const submitAction = async ({ actionType, targetObjectIds = [], params = {}, aiSuggested = false }) => {
+ const resp = await fetchAdminWriteJson("/api/v1/actions", {
+ action_type: actionType,
+ target_object_ids: targetObjectIds,
+ params,
+ ai_suggested: aiSuggested,
+ });
+ if (!resp.ok) throw new Error(await resp.text());
+ const created = await resp.json();
+ await refresh().catch(() => {});
+ return created;
+ };
+
+ panelEl.querySelector("#actions-close-btn")?.addEventListener("click", () => {
+ panelEl.hidden = true;
+ });
+ panelEl.querySelector("#actions-refresh-btn")?.addEventListener("click", () => {
+ void refresh().catch((e) => onStatus?.(e?.message || String(e), "error"));
+ });
+
+ submitBtn?.addEventListener("click", async () => {
+ const actionType = String(typeSelect?.value || "add_to_watchlist");
+ const oid = String(targetInput?.value || "").trim();
+ const note = String(noteInput?.value || "").trim();
+ if (!oid) {
+ onStatus?.(t("请输入目标对象 ID", "Target object ID required"), "error");
+ return;
+ }
+ try {
+ const created = await submitAction({
+ actionType,
+ targetObjectIds: [oid],
+ params: { summary: note || oid, title: oid },
+ });
+ if (noteInput) noteInput.value = "";
+ onStatus?.(t(`动作已提交 (${created.status})`, `Action submitted (${created.status})`), "success");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ });
+
+ listEl?.addEventListener("click", async (event) => {
+ const btn = event?.target instanceof HTMLElement ? event.target.closest("[data-action-decide]") : null;
+ if (!(btn instanceof HTMLElement)) return;
+ const actionId = Number(btn.dataset.actionId);
+ const decide = btn.dataset.actionDecide;
+ const reasonEl = panelEl.querySelector(`[data-action-decision-reason="${actionId}"]`);
+ const reason = String(reasonEl?.value || "").trim();
+ if (!reason) {
+ onStatus?.(t("请填写审批或驳回理由", "Decision reason is required"), "error");
+ return;
+ }
+ try {
+ const resp = await fetchAdminWriteJson(`/api/v1/actions/${actionId}/${decide}`, {
+ decision_reason: reason,
+ });
+ if (!resp.ok) throw new Error(await resp.text());
+ await refresh();
+ onStatus?.(t("审批处理完成", "Action decision recorded"), "success");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ });
+
+ const open = async (objectId = "") => {
+ panelEl.hidden = false;
+ sharedHudFocusStack.focus(panelEl);
+ if (objectId && targetInput) targetInput.value = objectId;
+ await refresh(objectId).catch((e) => onStatus?.(e?.message || String(e), "error"));
+ };
+
+ return {
+ open,
+ close: () => {
+ panelEl.hidden = true;
+ },
+ refresh,
+ submitAction,
+ getItems: () => items,
+ destroy: () => {
+ hudPanel?.destroy?.();
+ panelEl.remove();
+ },
+ };
+}
diff --git a/frontend/public/earth/js/aircraft-gps-jamming.test.js b/frontend/public/earth/js/aircraft-gps-jamming.test.js
new file mode 100644
index 00000000..9c935626
--- /dev/null
+++ b/frontend/public/earth/js/aircraft-gps-jamming.test.js
@@ -0,0 +1,134 @@
+import { expect, test } from "bun:test";
+import {
+ AIRCRAFT_CATEGORY_ORDER,
+ EARTH_REAL_RADIUS_M,
+ computeHeadingBin,
+ extrapolateGreatCircleXYZ,
+ gridBucketKey,
+ latLonRadiusToXYZ,
+ lookupGridBucketCandidates,
+ unpackColumnarAircraftSnapshot,
+} from "./aircraft-math.js";
+import {
+ GPS_JAMMING_COLORS,
+ buildGpsJammingGeometryBuffers,
+} from "./gps-jamming-math.js";
+
+test("aircraft Worker math unpacks columnar rows, computes 32 heading bins, and prioritizes military/emergency on cap", () => {
+ const payload = {
+ fields: [
+ "icao24",
+ "callsign",
+ "lat",
+ "lon",
+ "altitude_m",
+ "ground_speed_ms",
+ "track_deg",
+ "vertical_rate_ms",
+ "category",
+ "is_military",
+ "is_emergency",
+ "emergency_code",
+ "on_ground",
+ "source",
+ "observed_at",
+ ],
+ rows: [
+ ["a00001", "UAL101", 37.6, -122.3, 10000, 240, 90, 0, "commercial", false, false, null, false, "opensky_aircraft", "2026-12-06T10:00:00Z"],
+ ["ae1234", "RCH401", 35.1, 139.4, 9000, 230, 180, 0, "military", true, false, null, false, "adsb_lol_aircraft", "2026-12-06T10:00:00Z"],
+ ["4ca777", "RYR777", 51.4, -0.4, 4000, 180, 270, -2, "emergency", false, true, "7700", false, "adsb_lol_aircraft", "2026-12-06T10:00:00Z"],
+ ],
+ };
+
+ expect(computeHeadingBin(0)).toBe(0);
+ expect(computeHeadingBin(90)).toBe(8);
+ expect(computeHeadingBin(180)).toBe(16);
+ expect(computeHeadingBin(270)).toBe(24);
+ expect(computeHeadingBin(359.9)).toBe(0);
+
+ // When capped at 2 items, military and emergency must survive while commercial is shed first
+ const capped = unpackColumnarAircraftSnapshot(payload, { earthRadius: 100, maxRenderCount: 2 });
+ expect(capped.count).toBe(2);
+ expect(capped.records.map((r) => r.icao24).sort()).toEqual(["4ca777", "ae1234"]);
+ expect(capped.atlasSlots[0]).toBe(24); // RYR777 270 deg
+ expect(capped.atlasSlots[1]).toBe(AIRCRAFT_CATEGORY_ORDER.indexOf("emergency"));
+ expect(capped.atlasSlots[2]).toBe(16); // RCH401 180 deg
+ expect(capped.atlasSlots[3]).toBe(AIRCRAFT_CATEGORY_ORDER.indexOf("military"));
+});
+
+test("aircraft great-circle shader extrapolation matches spherical CPU reference within float precision", () => {
+ const lat = 0.0;
+ const lon = 0.0;
+ const radius = 101.2;
+ const speedMs = 250.0;
+ const elapsedSec = 60.0;
+
+ const unpacked = unpackColumnarAircraftSnapshot({
+ fields: ["icao24", "lat", "lon", "altitude_m", "ground_speed_ms", "track_deg", "category", "is_military", "is_emergency", "on_ground"],
+ rows: [["a11111", lat, lon, 7500, speedMs, 90.0, "commercial", false, false, false]],
+ });
+
+ const pos0 = [unpacked.positions[0], unpacked.positions[1], unpacked.positions[2]];
+ const vel0 = [unpacked.velocities[0], unpacked.velocities[1], unpacked.velocities[2]];
+ const r0 = unpacked.radii[0];
+ const extrapolated = extrapolateGreatCircleXYZ(pos0, vel0, elapsedSec, r0);
+
+ // Heading 90 deg (due East) along equator changes longitude by + (speed * dt / EARTH_REAL_RADIUS_M) rad
+ const deltaLonDeg = ((speedMs * elapsedSec) / EARTH_REAL_RADIUS_M) * (180 / Math.PI);
+ const expected = latLonRadiusToXYZ(lat, deltaLonDeg, r0);
+
+ expect(Math.hypot(extrapolated[0] - expected[0], extrapolated[1] - expected[1], extrapolated[2] - expected[2])).toBeLessThan(1e-4);
+ expect(Math.hypot(extrapolated[0], extrapolated[1], extrapolated[2])).toBeCloseTo(r0, 4);
+ expect(radius).toBeGreaterThan(100);
+});
+
+test("5x5 grid bucket spatial index finds nearby candidates including across antimeridian", () => {
+ const unpacked = unpackColumnarAircraftSnapshot({
+ fields: ["icao24", "lat", "lon", "altitude_m", "ground_speed_ms", "track_deg", "category", "is_military", "is_emergency", "on_ground"],
+ rows: [
+ ["a00001", 10.0, 179.5, 5000, 200, 90, "commercial", false, false, false],
+ ["a00002", -45.0, -70.0, 5000, 200, 180, "commercial", false, false, false],
+ ],
+ });
+
+ expect(gridBucketKey(10.0, 179.5)).toBe("20:71");
+ const candidates = lookupGridBucketCandidates(10.2, -179.8, unpacked.gridBuckets);
+ expect(candidates).toEqual([0]);
+});
+
+test("GPS jamming H3 triangulation emits expected vertices and level RGBA mapping", () => {
+ const hexA = {
+ h3_index: "841fb49ffffffff",
+ observed_date: "2026-12-05",
+ lat: 35.0,
+ lon: 33.0,
+ level: "high",
+ bad_ratio: 0.25,
+ aircraft_count: 80,
+ boundary: [
+ [35.2, 32.8],
+ [35.3, 33.0],
+ [35.2, 33.2],
+ [34.8, 33.2],
+ [34.7, 33.0],
+ [34.8, 32.8],
+ ],
+ };
+ const hexB = {
+ ...hexA,
+ h3_index: "841fb4bffffffff",
+ level: "medium",
+ bad_ratio: 0.05,
+ };
+
+ const result = buildGpsJammingGeometryBuffers([hexA, hexB], { earthRadius: 100 });
+ // Two 6-sided hexagons -> 2 * 6 triangles = 12 triangles = 36 vertices
+ expect(result.vertexCount).toBe(36);
+ expect(result.positions.length).toBe(36 * 3);
+ expect(result.colors.length).toBe(36 * 4);
+ expect(result.colors[0]).toBeCloseTo(GPS_JAMMING_COLORS.high[0], 4);
+ expect(result.colors[3]).toBeCloseTo(GPS_JAMMING_COLORS.high[3], 4);
+ const bOffset = 18 * 4;
+ expect(result.colors[bOffset]).toBeCloseTo(GPS_JAMMING_COLORS.medium[0], 4);
+ expect(result.colors[bOffset + 3]).toBeCloseTo(GPS_JAMMING_COLORS.medium[3], 4);
+});
diff --git a/frontend/public/earth/js/aircraft-math.js b/frontend/public/earth/js/aircraft-math.js
new file mode 100644
index 00000000..449f70e8
--- /dev/null
+++ b/frontend/public/earth/js/aircraft-math.js
@@ -0,0 +1,259 @@
+// aircraft-math.js - Shared pure math, unpacking, great-circle extrapolation, and 5x5 grid index for aircraft ADS-B
+
+export const EARTH_REAL_RADIUS_M = 6_371_000.0;
+export const AIRCRAFT_HEADING_BINS = 32;
+
+export const AIRCRAFT_CATEGORY_ORDER = Object.freeze([
+ "commercial",
+ "cargo",
+ "military",
+ "emergency",
+ "general",
+ "helicopter",
+ "other",
+]);
+
+export const AIRCRAFT_CATEGORY_LABELS = Object.freeze({
+ commercial: "民航",
+ cargo: "货机",
+ military: "军机",
+ emergency: "紧急应答",
+ general: "通航",
+ helicopter: "直升机",
+ other: "其他",
+});
+
+export const AIRCRAFT_COLORS = Object.freeze({
+ commercial: "#38bdf8",
+ cargo: "#fb923c",
+ military: "#f43f5e",
+ emergency: "#ef4444",
+ general: "#a3e635",
+ helicopter: "#2dd4bf",
+ other: "#94a3b8",
+});
+
+const CATEGORY_INDEX_MAP = new Map(
+ AIRCRAFT_CATEGORY_ORDER.map((cat, index) => [cat, index]),
+);
+
+export function getAircraftCategoryIndex(category) {
+ return CATEGORY_INDEX_MAP.get(String(category || "other").toLowerCase()) ?? 6;
+}
+
+export function computeHeadingBin(trackDeg) {
+ if (!Number.isFinite(Number(trackDeg))) return 0;
+ const wrapped = ((Number(trackDeg) % 360) + 360) % 360;
+ return Math.round((wrapped / 360) * AIRCRAFT_HEADING_BINS) % AIRCRAFT_HEADING_BINS;
+}
+
+export function computeAircraftRadius(altitudeM, earthRadius = 100) {
+ const alt = Number.isFinite(Number(altitudeM)) ? Math.max(0, Math.min(Number(altitudeM), 15000)) : 3000;
+ const normalized = alt / 15000;
+ return earthRadius + 0.75 + normalized * 1.1;
+}
+
+export function latLonRadiusToXYZ(lat, lon, radius = 100) {
+ const phi = (90 - lat) * (Math.PI / 180);
+ const theta = (lon + 180) * (Math.PI / 180);
+ const sinPhi = Math.sin(phi);
+ return [
+ -(radius * sinPhi * Math.cos(theta)),
+ radius * Math.cos(phi),
+ radius * sinPhi * Math.sin(theta),
+ ];
+}
+
+export function computeTangentAngularVelocity(lat, lon, groundSpeedMs, trackDeg) {
+ const speed = Number(groundSpeedMs);
+ if (!Number.isFinite(speed) || speed <= 0.1) return [0, 0, 0];
+ const phi = (90 - lat) * (Math.PI / 180);
+ const theta = (lon + 180) * (Math.PI / 180);
+ const trackRad = (Number.isFinite(Number(trackDeg)) ? Number(trackDeg) : 0) * (Math.PI / 180);
+
+ const cosPhi = Math.cos(phi);
+ const cosTheta = Math.cos(theta);
+ const sinTheta = Math.sin(theta);
+
+ // Unit North tangent vector (-dP/dphi) & unit East tangent vector (+(dP/dtheta)/sin(phi))
+ const nx = cosPhi * cosTheta;
+ const ny = Math.sin(phi);
+ const nz = -cosPhi * sinTheta;
+
+ const ex = sinTheta;
+ const ey = 0;
+ const ez = cosTheta;
+
+ const cosT = Math.cos(trackRad);
+ const sinT = Math.sin(trackRad);
+ const hx = cosT * nx + sinT * ex;
+ const hy = cosT * ny + sinT * ey;
+ const hz = cosT * nz + sinT * ez;
+
+ const omega = speed / EARTH_REAL_RADIUS_M;
+ return [hx * omega, hy * omega, hz * omega];
+}
+
+export function extrapolateGreatCircleXYZ(pos3, vel3, elapsedSec, radius) {
+ const x0 = pos3[0];
+ const y0 = pos3[1];
+ const z0 = pos3[2];
+ const vx = vel3[0];
+ const vy = vel3[1];
+ const vz = vel3[2];
+ const omega = Math.hypot(vx, vy, vz);
+ if (omega <= 1e-12 || elapsedSec === 0) {
+ return [x0, y0, z0];
+ }
+ const angle = Math.min(0.25, Math.max(-0.25, omega * elapsedSec));
+ const cosA = Math.cos(angle);
+ const sinA = Math.sin(angle);
+ const invLen = radius > 0 ? 1 / radius : 1;
+ const hx = vx / omega;
+ const hy = vy / omega;
+ const hz = vz / omega;
+ const px = x0 * invLen;
+ const py = y0 * invLen;
+ const pz = z0 * invLen;
+ return [
+ radius * (cosA * px + sinA * hx),
+ radius * (cosA * py + sinA * hy),
+ radius * (cosA * pz + sinA * hz),
+ ];
+}
+
+export function gridBucketKey(lat, lon) {
+ const clampedLat = Math.max(-90, Math.min(89.999, Number(lat) || 0));
+ const wrappedLon = ((((Number(lon) || 0) + 180) % 360) + 360) % 360 - 180;
+ const latBin = Math.floor((clampedLat + 90) / 5);
+ const lonBin = Math.floor((wrappedLon + 180) / 5);
+ return `${latBin}:${lonBin}`;
+}
+
+export function lookupGridBucketCandidates(lat, lon, buckets) {
+ const clampedLat = Math.max(-90, Math.min(89.999, Number(lat) || 0));
+ const wrappedLon = ((((Number(lon) || 0) + 180) % 360) + 360) % 360 - 180;
+ const latBin = Math.floor((clampedLat + 90) / 5);
+ const lonBin = Math.floor((wrappedLon + 180) / 5);
+ const candidates = [];
+ for (let dLat = -1; dLat <= 1; dLat += 1) {
+ const lb = latBin + dLat;
+ if (lb < 0 || lb > 35) continue;
+ for (let dLon = -1; dLon <= 1; dLon += 1) {
+ const nb = ((lonBin + dLon) + 72) % 72;
+ const list = buckets[`${lb}:${nb}`];
+ if (Array.isArray(list)) {
+ for (let i = 0; i < list.length; i += 1) {
+ candidates.push(list[i]);
+ }
+ }
+ }
+ }
+ return candidates;
+}
+
+export function unpackColumnarAircraftSnapshot(payload, options = {}) {
+ const fields = Array.isArray(payload?.fields) ? payload.fields : [];
+ const rawRows = Array.isArray(payload?.rows) ? payload.rows : [];
+ const earthRadius = Number(options.earthRadius || 100);
+ const maxRenderCount = Number.isFinite(Number(options.maxRenderCount))
+ ? Math.max(1, Number(options.maxRenderCount))
+ : rawRows.length;
+
+ const idxOf = (name) => fields.indexOf(name);
+ const iIcao = idxOf("icao24");
+ const iCallsign = idxOf("callsign");
+ const iLat = idxOf("lat");
+ const iLon = idxOf("lon");
+ const iAlt = idxOf("altitude_m");
+ const iSpd = idxOf("ground_speed_ms");
+ const iTrk = idxOf("track_deg");
+ const iVrate = idxOf("vertical_rate_ms");
+ const iCat = idxOf("category");
+ const iMil = idxOf("is_military");
+ const iEmg = idxOf("is_emergency");
+ const iEmgCode = idxOf("emergency_code");
+ const iGround = idxOf("on_ground");
+ const iSource = idxOf("source");
+ const iObs = idxOf("observed_at");
+
+ const valid = [];
+ for (let r = 0; r < rawRows.length; r += 1) {
+ const row = rawRows[r];
+ if (!Array.isArray(row)) continue;
+ const lat = Number(row[iLat]);
+ const lon = Number(row[iLon]);
+ const icao24 = String(row[iIcao] || "").trim().toLowerCase();
+ if (!icao24 || !Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ const isEmergency = Boolean(row[iEmg]);
+ const isMilitary = Boolean(row[iMil]);
+ valid.push({
+ icao24,
+ callsign: row[iCallsign] || null,
+ lat,
+ lon,
+ altitudeM: row[iAlt] != null ? Number(row[iAlt]) : null,
+ groundSpeedMs: row[iSpd] != null ? Number(row[iSpd]) : null,
+ trackDeg: row[iTrk] != null ? Number(row[iTrk]) : 0,
+ verticalRateMs: row[iVrate] != null ? Number(row[iVrate]) : null,
+ category: String(row[iCat] || "other").toLowerCase(),
+ isMilitary,
+ isEmergency,
+ emergencyCode: row[iEmgCode] || null,
+ onGround: Boolean(row[iGround]),
+ source: row[iSource] || "adsb_lol_aircraft",
+ observedAt: row[iObs] || null,
+ priority: isEmergency ? 2 : isMilitary ? 1 : 0,
+ });
+ }
+
+ let selected = valid;
+ if (valid.length > maxRenderCount) {
+ selected = [...valid].sort((a, b) => b.priority - a.priority).slice(0, maxRenderCount);
+ }
+
+ const count = selected.length;
+ const positions = new Float32Array(count * 3);
+ const velocities = new Float32Array(count * 3);
+ const radii = new Float32Array(count);
+ const atlasSlots = new Float32Array(count * 2);
+ const gridBuckets = Object.create(null);
+
+ for (let i = 0; i < count; i += 1) {
+ const item = selected[i];
+ const radius = computeAircraftRadius(item.altitudeM, earthRadius);
+ const [x, y, z] = latLonRadiusToXYZ(item.lat, item.lon, radius);
+ const [vx, vy, vz] = computeTangentAngularVelocity(
+ item.lat,
+ item.lon,
+ item.onGround ? 0 : item.groundSpeedMs,
+ item.trackDeg,
+ );
+ const base3 = i * 3;
+ positions[base3] = x;
+ positions[base3 + 1] = y;
+ positions[base3 + 2] = z;
+ velocities[base3] = vx;
+ velocities[base3 + 1] = vy;
+ velocities[base3 + 2] = vz;
+ radii[i] = radius;
+
+ const base2 = i * 2;
+ atlasSlots[base2] = computeHeadingBin(item.trackDeg);
+ atlasSlots[base2 + 1] = getAircraftCategoryIndex(item.category);
+
+ const bKey = gridBucketKey(item.lat, item.lon);
+ if (!gridBuckets[bKey]) gridBuckets[bKey] = [];
+ gridBuckets[bKey].push(i);
+ }
+
+ return {
+ count,
+ positions,
+ velocities,
+ radii,
+ atlasSlots,
+ records: selected,
+ gridBuckets,
+ };
+}
diff --git a/frontend/public/earth/js/aircraft-worker.js b/frontend/public/earth/js/aircraft-worker.js
new file mode 100644
index 00000000..1ac6ef3e
--- /dev/null
+++ b/frontend/public/earth/js/aircraft-worker.js
@@ -0,0 +1,35 @@
+// aircraft-worker.js - Web Worker for columnar ADS-B unpacking & spatial bucketing
+import { unpackColumnarAircraftSnapshot } from "./aircraft-math.js";
+
+self.addEventListener("message", (event) => {
+ const { id, type, payload, options } = event.data || {};
+ if (type !== "build_snapshot") return;
+ try {
+ const unpacked = unpackColumnarAircraftSnapshot(payload, options || {});
+ self.postMessage(
+ {
+ id,
+ ok: true,
+ count: unpacked.count,
+ positions: unpacked.positions,
+ velocities: unpacked.velocities,
+ radii: unpacked.radii,
+ atlasSlots: unpacked.atlasSlots,
+ records: unpacked.records,
+ gridBuckets: unpacked.gridBuckets,
+ },
+ [
+ unpacked.positions.buffer,
+ unpacked.velocities.buffer,
+ unpacked.radii.buffer,
+ unpacked.atlasSlots.buffer,
+ ],
+ );
+ } catch (error) {
+ self.postMessage({
+ id,
+ ok: false,
+ error: error?.message || String(error),
+ });
+ }
+});
diff --git a/frontend/public/earth/js/aircraft.js b/frontend/public/earth/js/aircraft.js
new file mode 100644
index 00000000..c7d73097
--- /dev/null
+++ b/frontend/public/earth/js/aircraft.js
@@ -0,0 +1,715 @@
+// aircraft.js - Single-batch Three.js Points + Shader dead-reckoning + 3h ribbon track
+import * as THREE from "three";
+import { CONFIG, PATHS } from "./constants.js";
+import {
+ AIRCRAFT_CATEGORY_LABELS,
+ AIRCRAFT_CATEGORY_ORDER,
+ AIRCRAFT_COLORS,
+ AIRCRAFT_HEADING_BINS,
+ extrapolateGreatCircleXYZ,
+ gridBucketKey,
+ latLonRadiusToXYZ,
+ lookupGridBucketCandidates,
+ unpackColumnarAircraftSnapshot,
+} from "./aircraft-math.js";
+import { isLegendItemEnabled } from "./legend-filters.js";
+import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
+import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
+
+const AIRCRAFT_RENDER_ORDER = 4.9;
+const AIRCRAFT_TRACK_RENDER_ORDER = 4.7;
+const AIRCRAFT_SNAPSHOT_TRANSITION_MS = 300;
+const AIRCRAFT_POLL_INTERVAL_MS = 60_000;
+const AIRCRAFT_DESKTOP_MAX = 15_000;
+const AIRCRAFT_CONSTRAINED_MAX = 4_000;
+
+let showAircraft = false;
+let aircraftGroup = null;
+let aircraftPoints = null;
+let aircraftMaterial = null;
+let aircraftAtlasTexture = null;
+let activeTrackLine = null;
+let trackRequestVersion = 0;
+
+let workerInstance = null;
+let workerRequestId = 0;
+let pollTimerId = null;
+let loadGeneration = 0;
+
+let currentRecords = [];
+let currentBuckets = Object.create(null);
+let prevPosArray = new Float32Array(0);
+let prevVelArray = new Float32Array(0);
+let currPosArray = new Float32Array(0);
+let currVelArray = new Float32Array(0);
+let currRadiusArray = new Float32Array(0);
+let currAtlasArray = new Float32Array(0);
+let visibilityMaskArray = new Float32Array(0);
+
+let snapshotTimestampMs = performance.now();
+let prevSnapshotTimestampMs = performance.now();
+let transitionStartMs = 0;
+let lockedAircraftIcao24 = null;
+let lastRenderedCount = 0;
+let earthRef = null;
+
+// Pre-allocated scratch objects (zero per-frame heap allocations)
+const scratchCenterWorld = new THREE.Vector3();
+const scratchCameraLocal = new THREE.Vector3();
+const scratchPointWorld = new THREE.Vector3();
+const scratchPointLocal = new THREE.Vector3();
+const scratchScreenPos = new THREE.Vector3();
+
+function isConstrainedDevice() {
+ if (typeof window === "undefined") return false;
+ const cores = Number(navigator?.hardwareConcurrency || 8);
+ const mobile = Boolean(window.innerWidth <= 900);
+ return mobile || cores <= 4;
+}
+
+function getEffectiveRenderCap() {
+ return isConstrainedDevice() ? AIRCRAFT_CONSTRAINED_MAX : AIRCRAFT_DESKTOP_MAX;
+}
+
+function buildAircraftAtlasTexture() {
+ if (typeof document === "undefined") return null;
+ const cell = 64;
+ const cols = AIRCRAFT_HEADING_BINS;
+ const rows = AIRCRAFT_CATEGORY_ORDER.length;
+ const canvas = document.createElement("canvas");
+ canvas.width = cols * cell;
+ canvas.height = rows * cell;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+
+ for (let row = 0; row < rows; row += 1) {
+ const category = AIRCRAFT_CATEGORY_ORDER[row];
+ const color = AIRCRAFT_COLORS[category] || AIRCRAFT_COLORS.other;
+ for (let col = 0; col < cols; col += 1) {
+ const cx = col * cell + cell * 0.5;
+ const cy = row * cell + cell * 0.5;
+ const angle = (col / cols) * Math.PI * 2;
+ ctx.save();
+ ctx.translate(cx, cy);
+ ctx.rotate(angle);
+ ctx.fillStyle = color;
+ ctx.strokeStyle = "rgba(8, 13, 24, 0.85)";
+ ctx.lineWidth = 2.4;
+
+ if (category === "military") {
+ // Delta-wing interceptor silhouette
+ ctx.beginPath();
+ ctx.moveTo(0, -18);
+ ctx.lineTo(15, 10);
+ ctx.lineTo(4, 8);
+ ctx.lineTo(4, 15);
+ ctx.lineTo(-4, 15);
+ ctx.lineTo(-4, 8);
+ ctx.lineTo(-15, 10);
+ ctx.closePath();
+ } else if (category === "helicopter") {
+ // Compact rotorcraft silhouette
+ ctx.beginPath();
+ ctx.arc(0, 0, 7, 0, Math.PI * 2);
+ ctx.moveTo(-16, -10);
+ ctx.lineTo(16, 10);
+ ctx.moveTo(16, -10);
+ ctx.lineTo(-16, 10);
+ } else {
+ // Jetliner / commercial silhouette pointing UP
+ ctx.beginPath();
+ ctx.moveTo(0, -18);
+ ctx.lineTo(3, -5);
+ ctx.lineTo(17, 4);
+ ctx.lineTo(17, 8);
+ ctx.lineTo(3, 4);
+ ctx.lineTo(2.5, 13);
+ ctx.lineTo(8, 17);
+ ctx.lineTo(-8, 17);
+ ctx.lineTo(-2.5, 13);
+ ctx.lineTo(-3, 4);
+ ctx.lineTo(-17, 8);
+ ctx.lineTo(-17, 4);
+ ctx.lineTo(-3, -5);
+ ctx.closePath();
+ }
+ ctx.fill();
+ ctx.stroke();
+ ctx.restore();
+ }
+ }
+
+ const texture = new THREE.CanvasTexture(canvas);
+ texture.minFilter = THREE.LinearFilter;
+ texture.magFilter = THREE.LinearFilter;
+ texture.generateMipmaps = false;
+ texture.flipY = false;
+ texture.needsUpdate = true;
+ return texture;
+}
+
+function createAircraftShaderMaterial(atlasTexture) {
+ return new THREE.ShaderMaterial({
+ transparent: true,
+ depthTest: true,
+ depthWrite: false,
+ uniforms: {
+ uElapsedSec: { value: 0.0 },
+ uPrevElapsedSec: { value: 0.0 },
+ uTransitionMix: { value: 1.0 },
+ uPointSize: { value: 26.0 },
+ uCols: { value: AIRCRAFT_HEADING_BINS },
+ uRows: { value: AIRCRAFT_CATEGORY_ORDER.length },
+ uAtlas: { value: atlasTexture },
+ uEarthCenterWorld: { value: new THREE.Vector3() },
+ uOccRadius: { value: CONFIG.earthRadius * 0.999 },
+ },
+ vertexShader: `
+ attribute vec3 aPrevPos;
+ attribute vec3 aPrevVel;
+ attribute vec3 aCurrPos;
+ attribute vec3 aCurrVel;
+ attribute float aRadius;
+ attribute vec2 aAtlasSlot;
+ attribute float aVisibleMask;
+
+ uniform float uElapsedSec;
+ uniform float uPrevElapsedSec;
+ uniform float uTransitionMix;
+ uniform float uPointSize;
+ uniform vec3 uEarthCenterWorld;
+ uniform float uOccRadius;
+
+ varying vec2 vAtlasSlot;
+ varying float vAlpha;
+
+ vec3 extrapolateGC(vec3 pos, vec3 vel, float elapsed, float radius) {
+ float omega = length(vel);
+ if (omega <= 1e-10 || elapsed == 0.0) {
+ return pos;
+ }
+ float angle = clamp(omega * elapsed, -0.25, 0.25);
+ vec3 pUnit = pos / max(radius, 1.0);
+ vec3 hUnit = vel / omega;
+ return radius * (cos(angle) * pUnit + sin(angle) * hUnit);
+ }
+
+ void main() {
+ vAtlasSlot = aAtlasSlot;
+ if (aVisibleMask < 0.5) {
+ vAlpha = 0.0;
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ gl_PointSize = 0.0;
+ return;
+ }
+ vec3 prevP = extrapolateGC(aPrevPos, aPrevVel, uPrevElapsedSec, aRadius);
+ vec3 currP = extrapolateGC(aCurrPos, aCurrVel, uElapsedSec, aRadius);
+ float t = smoothstep(0.0, 1.0, clamp(uTransitionMix, 0.0, 1.0));
+ vec3 localPos = mix(prevP, currP, t);
+
+ vec4 worldPos = modelMatrix * vec4(localPos, 1.0);
+ vec3 fromCenter = worldPos.xyz - uEarthCenterWorld;
+ vec3 toCam = normalize(cameraPosition - worldPos.xyz);
+ float horizonDot = dot(normalize(fromCenter), toCam);
+
+ vAlpha = smoothstep(-0.08, 0.08, horizonDot);
+ gl_Position = projectionMatrix * viewMatrix * worldPos;
+ gl_PointSize = uPointSize;
+ }
+ `,
+ fragmentShader: `
+ uniform sampler2D uAtlas;
+ uniform float uCols;
+ uniform float uRows;
+
+ varying vec2 vAtlasSlot;
+ varying float vAlpha;
+
+ void main() {
+ if (vAlpha <= 0.01) discard;
+ vec2 cellUv = (vAtlasSlot + gl_PointCoord) / vec2(uCols, uRows);
+ vec4 texel = texture2D(uAtlas, cellUv);
+ float alpha = texel.a * vAlpha;
+ if (alpha <= 0.04) discard;
+ gl_FragColor = vec4(texel.rgb, alpha);
+ #include
+ }
+ `,
+ });
+}
+
+function getOrCreateWorker() {
+ if (typeof Worker === "undefined") return null;
+ if (!workerInstance) {
+ workerInstance = new Worker(new URL("./aircraft-worker.js", import.meta.url), {
+ type: "module",
+ });
+ }
+ return workerInstance;
+}
+
+function terminateWorker() {
+ if (workerInstance) {
+ workerInstance.terminate();
+ workerInstance = null;
+ }
+}
+
+async function unpackInWorkerOrMain(payload, options) {
+ const worker = getOrCreateWorker();
+ if (!worker) {
+ return unpackColumnarAircraftSnapshot(payload, options);
+ }
+ const reqId = ++workerRequestId;
+ return new Promise((resolve, reject) => {
+ const onMessage = (event) => {
+ const msg = event.data;
+ if (!msg || msg.id !== reqId) return;
+ worker.removeEventListener("message", onMessage);
+ worker.removeEventListener("error", onError);
+ if (msg.ok) resolve(msg);
+ else reject(new Error(msg.error || "Aircraft worker failed"));
+ };
+ const onError = (err) => {
+ worker.removeEventListener("message", onMessage);
+ worker.removeEventListener("error", onError);
+ reject(err);
+ };
+ worker.addEventListener("message", onMessage);
+ worker.addEventListener("error", onError);
+ worker.postMessage({ id: reqId, type: "build_snapshot", payload, options });
+ });
+}
+
+function updateLegendMaskBuffer() {
+ const count = currentRecords.length;
+ if (visibilityMaskArray.length !== count) {
+ visibilityMaskArray = new Float32Array(count);
+ }
+ for (let i = 0; i < count; i += 1) {
+ const cat = currentRecords[i].category || "other";
+ visibilityMaskArray[i] = isLegendItemEnabled("aircraft", cat) ? 1.0 : 0.0;
+ }
+ if (aircraftPoints?.geometry) {
+ const attr = aircraftPoints.geometry.getAttribute("aVisibleMask");
+ if (attr) {
+ attr.copyArray(visibilityMaskArray);
+ attr.needsUpdate = true;
+ }
+ }
+}
+
+function applyUnpackedSnapshot(unpacked, earth) {
+ if (!showAircraft || !earth) return;
+ const now = performance.now();
+ const prevMap = new Map();
+ const prevElapsed = (now - snapshotTimestampMs) * 0.001;
+ for (let i = 0; i < currentRecords.length; i += 1) {
+ prevMap.set(currentRecords[i].icao24, {
+ pos: [currPosArray[i * 3], currPosArray[i * 3 + 1], currPosArray[i * 3 + 2]],
+ vel: [currVelArray[i * 3], currVelArray[i * 3 + 1], currVelArray[i * 3 + 2]],
+ rad: currRadiusArray[i] || CONFIG.earthRadius + 1.0,
+ });
+ }
+
+ const count = unpacked.count;
+ const nextPrevPos = new Float32Array(count * 3);
+ const nextPrevVel = new Float32Array(count * 3);
+ for (let i = 0; i < count; i += 1) {
+ const rec = unpacked.records[i];
+ const old = prevMap.get(rec.icao24);
+ const b3 = i * 3;
+ if (old) {
+ const ext = extrapolateGreatCircleXYZ(old.pos, old.vel, prevElapsed, old.rad);
+ nextPrevPos[b3] = ext[0];
+ nextPrevPos[b3 + 1] = ext[1];
+ nextPrevPos[b3 + 2] = ext[2];
+ nextPrevVel[b3] = old.vel[0];
+ nextPrevVel[b3 + 1] = old.vel[1];
+ nextPrevVel[b3 + 2] = old.vel[2];
+ } else {
+ nextPrevPos[b3] = unpacked.positions[b3];
+ nextPrevPos[b3 + 1] = unpacked.positions[b3 + 1];
+ nextPrevPos[b3 + 2] = unpacked.positions[b3 + 2];
+ nextPrevVel[b3] = unpacked.velocities[b3];
+ nextPrevVel[b3 + 1] = unpacked.velocities[b3 + 1];
+ nextPrevVel[b3 + 2] = unpacked.velocities[b3 + 2];
+ }
+ }
+
+ prevSnapshotTimestampMs = now;
+ snapshotTimestampMs = now;
+ transitionStartMs = prevMap.size > 0 ? now : 0;
+
+ prevPosArray = nextPrevPos;
+ prevVelArray = nextPrevVel;
+ currPosArray = unpacked.positions;
+ currVelArray = unpacked.velocities;
+ currRadiusArray = unpacked.radii;
+ currAtlasArray = unpacked.atlasSlots;
+ currentRecords = unpacked.records;
+ currentBuckets = unpacked.gridBuckets;
+ lastRenderedCount = count;
+
+ visibilityMaskArray = new Float32Array(count);
+ for (let i = 0; i < count; i += 1) {
+ const cat = currentRecords[i].category || "other";
+ visibilityMaskArray[i] = isLegendItemEnabled("aircraft", cat) ? 1.0 : 0.0;
+ }
+
+ if (!aircraftGroup) {
+ aircraftGroup = new THREE.Group();
+ aircraftGroup.name = "aircraft-layer-group";
+ earth.add(aircraftGroup);
+ }
+ if (!aircraftAtlasTexture) {
+ aircraftAtlasTexture = buildAircraftAtlasTexture();
+ }
+ if (!aircraftMaterial) {
+ aircraftMaterial = createAircraftShaderMaterial(aircraftAtlasTexture);
+ }
+
+ const nextGeom = new THREE.BufferGeometry();
+ nextGeom.setAttribute("position", new THREE.BufferAttribute(currPosArray, 3));
+ nextGeom.setAttribute("aPrevPos", new THREE.BufferAttribute(prevPosArray, 3));
+ nextGeom.setAttribute("aPrevVel", new THREE.BufferAttribute(prevVelArray, 3));
+ nextGeom.setAttribute("aCurrPos", new THREE.BufferAttribute(currPosArray, 3));
+ nextGeom.setAttribute("aCurrVel", new THREE.BufferAttribute(currVelArray, 3));
+ nextGeom.setAttribute("aRadius", new THREE.BufferAttribute(currRadiusArray, 1));
+ nextGeom.setAttribute("aAtlasSlot", new THREE.BufferAttribute(currAtlasArray, 2));
+ nextGeom.setAttribute("aVisibleMask", new THREE.BufferAttribute(visibilityMaskArray, 1));
+ nextGeom.setDrawRange(0, count);
+
+ if (!aircraftPoints) {
+ aircraftPoints = new THREE.Points(nextGeom, aircraftMaterial);
+ aircraftPoints.renderOrder = AIRCRAFT_RENDER_ORDER;
+ aircraftPoints.frustumCulled = false;
+ aircraftPoints.raycast = () => {};
+ aircraftGroup.add(aircraftPoints);
+ } else {
+ const oldGeom = aircraftPoints.geometry;
+ aircraftPoints.geometry = nextGeom;
+ oldGeom?.dispose?.();
+ }
+ aircraftGroup.visible = showAircraft && count > 0;
+}
+
+export function getShowAircraft() {
+ return showAircraft;
+}
+
+export function getAircraftCount() {
+ return lastRenderedCount;
+}
+
+export function getAircraftRecords() {
+ return currentRecords;
+}
+
+export function getAircraftLegendItems() {
+ return AIRCRAFT_CATEGORY_ORDER.map((key) => ({
+ key,
+ label: AIRCRAFT_CATEGORY_LABELS[key] || key,
+ color: AIRCRAFT_COLORS[key] || AIRCRAFT_COLORS.other,
+ shape: "dot",
+ }));
+}
+
+export function applyAircraftLegendFilter() {
+ updateLegendMaskBuffer();
+}
+
+export function clearAircraftTrack() {
+ trackRequestVersion += 1;
+ if (activeTrackLine?.parent) {
+ activeTrackLine.parent.remove(activeTrackLine);
+ }
+ activeTrackLine?.geometry?.dispose?.();
+ activeTrackLine?.material?.dispose?.();
+ activeTrackLine = null;
+}
+
+export function clearAircraftSelection() {
+ lockedAircraftIcao24 = null;
+ clearAircraftTrack();
+}
+
+export function clearAircraftData(earth = earthRef) {
+ loadGeneration += 1;
+ if (pollTimerId) {
+ clearTimeout(pollTimerId);
+ pollTimerId = null;
+ }
+ clearAircraftSelection();
+ terminateWorker();
+ if (aircraftPoints) {
+ aircraftPoints.geometry?.dispose?.();
+ aircraftPoints.parent?.remove(aircraftPoints);
+ aircraftPoints = null;
+ }
+ if (aircraftMaterial) {
+ aircraftMaterial.dispose?.();
+ aircraftMaterial = null;
+ }
+ if (aircraftAtlasTexture) {
+ aircraftAtlasTexture.dispose?.();
+ aircraftAtlasTexture = null;
+ }
+ if (aircraftGroup) {
+ aircraftGroup.parent?.remove(aircraftGroup);
+ aircraftGroup = null;
+ }
+ if (earth && aircraftGroup?.parent === earth) {
+ earth.remove(aircraftGroup);
+ }
+ currentRecords = [];
+ currentBuckets = Object.create(null);
+ prevPosArray = new Float32Array(0);
+ prevVelArray = new Float32Array(0);
+ currPosArray = new Float32Array(0);
+ currVelArray = new Float32Array(0);
+ currRadiusArray = new Float32Array(0);
+ currAtlasArray = new Float32Array(0);
+ visibilityMaskArray = new Float32Array(0);
+ lastRenderedCount = 0;
+}
+
+export function toggleAircraft(show, earth = earthRef) {
+ showAircraft = Boolean(show);
+ if (earth) earthRef = earth;
+ if (!showAircraft) {
+ clearAircraftData(earthRef);
+ return;
+ }
+ if (aircraftGroup) aircraftGroup.visible = true;
+}
+
+export async function loadAircraft(_scene, earth, options = {}) {
+ if (earth) earthRef = earth;
+ if (!showAircraft || !earthRef) return { totalCount: 0 };
+ const gen = ++loadGeneration;
+ const maxRenderCount = Number(options.limit || getEffectiveRenderCap());
+
+ const params = new URLSearchParams({ limit: String(maxRenderCount) });
+ const response = await fetch(`${PATHS.aircraftSnapshotApi}?${params.toString()}`, {
+ cache: "no-store",
+ });
+ if (!response.ok) throw new Error(`Aircraft HTTP ${response.status}`);
+ const payload = await response.json();
+ if (gen !== loadGeneration || !showAircraft) {
+ return { totalCount: getAircraftCount() };
+ }
+
+ const unpacked = await unpackInWorkerOrMain(payload, {
+ earthRadius: CONFIG.earthRadius,
+ maxRenderCount,
+ });
+ if (gen !== loadGeneration || !showAircraft) {
+ return { totalCount: getAircraftCount() };
+ }
+ applyUnpackedSnapshot(unpacked, earthRef);
+
+ if (pollTimerId) clearTimeout(pollTimerId);
+ if (showAircraft && !options.disablePoll) {
+ pollTimerId = setTimeout(() => {
+ if (showAircraft) {
+ loadAircraft(_scene, earthRef).catch((err) => console.warn("飞机刷新失败:", err));
+ }
+ }, AIRCRAFT_POLL_INTERVAL_MS);
+ }
+ return { totalCount: unpacked.count, sourceHealth: payload?.source_health || {} };
+}
+
+export async function showAircraftTrack(icao24, earth = earthRef) {
+ clearAircraftTrack();
+ if (!icao24 || !earth || !showAircraft) return null;
+ lockedAircraftIcao24 = String(icao24).toLowerCase();
+ const ver = trackRequestVersion;
+ const resp = await fetch(PATHS.aircraftTrackApi(icao24, 3), { cache: "no-store" });
+ if (!resp.ok) throw new Error(`Aircraft track HTTP ${resp.status}`);
+ const data = await resp.json();
+ if (ver !== trackRequestVersion || !showAircraft) return null;
+
+ const rawPoints = Array.isArray(data?.points) ? data.points : [];
+ if (rawPoints.length < 2) return null;
+
+ const vecs = [];
+ for (let i = 0; i < rawPoints.length; i += 1) {
+ const pt = rawPoints[i];
+ const lat = Number(pt?.lat);
+ const lon = Number(pt?.lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ const alt = Number(pt?.altitude_m);
+ const r = CONFIG.earthRadius + 0.72 + Math.max(0, Math.min(Number.isFinite(alt) ? alt : 3000, 15000)) / 15000 * 1.1;
+ const [x, y, z] = latLonRadiusToXYZ(lat, lon, r);
+ vecs.push(new THREE.Vector3(x, y, z));
+ }
+ if (vecs.length < 2) return null;
+
+ const geom = createSurfaceRibbonGeometry(vecs);
+ const mat = createSurfaceRibbonMaterial({
+ color: 0xfef08a,
+ halfWidthPx: 3.4,
+ opacity: 0.88,
+ pulseSpeed: 0.6,
+ pulseFreq: 2.0,
+ pulseIntensity: 0.45,
+ tailFade: 1.0,
+ });
+ activeTrackLine = new THREE.Mesh(geom, mat);
+ activeTrackLine.renderOrder = AIRCRAFT_TRACK_RENDER_ORDER;
+ activeTrackLine.raycast = () => {};
+ if (!aircraftGroup) {
+ aircraftGroup = new THREE.Group();
+ aircraftGroup.name = "aircraft-layer-group";
+ earth.add(aircraftGroup);
+ }
+ aircraftGroup.add(activeTrackLine);
+ return activeTrackLine;
+}
+
+export async function fetchAircraftDetail(icao24) {
+ const resp = await fetch(PATHS.aircraftDetailApi(icao24), { cache: "no-store" });
+ if (!resp.ok) throw new Error(`Aircraft detail HTTP ${resp.status}`);
+ return resp.json();
+}
+
+export function updateAircraftVisualState(camera) {
+ if (!showAircraft || !aircraftMaterial || !earthRef) return;
+ const now = performance.now();
+ aircraftMaterial.uniforms.uElapsedSec.value = (now - snapshotTimestampMs) * 0.001;
+ aircraftMaterial.uniforms.uPrevElapsedSec.value = (now - prevSnapshotTimestampMs) * 0.001;
+ aircraftMaterial.uniforms.uTransitionMix.value =
+ transitionStartMs > 0
+ ? Math.min(1.0, Math.max(0.0, (now - transitionStartMs) / AIRCRAFT_SNAPSHOT_TRANSITION_MS))
+ : 1.0;
+
+ earthRef.getWorldPosition(scratchCenterWorld);
+ aircraftMaterial.uniforms.uEarthCenterWorld.value.copy(scratchCenterWorld);
+
+ if (camera) {
+ const zoomScale = Math.max(0.75, Math.min(1.35, 300 / Math.max(115, camera.position.length())));
+ aircraftMaterial.uniforms.uPointSize.value = 24.0 * zoomScale * Math.min(window.devicePixelRatio || 1, 2);
+ }
+ if (activeTrackLine?.material?.uniforms?.uTime) {
+ activeTrackLine.material.uniforms.uTime.value = now * 0.001;
+ }
+}
+
+export function getAircraftPointerIntersections({
+ earth,
+ camera,
+ surfaceCoords,
+ clientX,
+ clientY,
+ radiusPx = 22,
+} = {}) {
+ if (!showAircraft || !earth || !camera || !surfaceCoords || currentRecords.length === 0) {
+ return [];
+ }
+ const candidates = lookupGridBucketCandidates(surfaceCoords.lat, surfaceCoords.lon, currentBuckets);
+ if (!candidates.length) return [];
+
+ earth.updateWorldMatrix(true, false);
+ scratchCameraLocal.copy(camera.position);
+ earth.worldToLocal(scratchCameraLocal);
+
+ const elapsed = (performance.now() - snapshotTimestampMs) * 0.001;
+ const maxSq = radiusPx * radiusPx;
+ const halfW = (typeof window !== "undefined" ? window.innerWidth : 1920) * 0.5;
+ const halfH = (typeof window !== "undefined" ? window.innerHeight : 1080) * 0.5;
+ const occRadius = CONFIG.earthRadius * 0.999;
+
+ let bestIdx = -1;
+ let bestDistSq = maxSq;
+
+ for (let i = 0; i < candidates.length; i += 1) {
+ const idx = candidates[i];
+ if (visibilityMaskArray[idx] < 0.5) continue;
+ const b3 = idx * 3;
+ const rad = currRadiusArray[idx] || CONFIG.earthRadius + 1.0;
+ const ext = extrapolateGreatCircleXYZ(
+ [currPosArray[b3], currPosArray[b3 + 1], currPosArray[b3 + 2]],
+ [currVelArray[b3], currVelArray[b3 + 1], currVelArray[b3 + 2]],
+ elapsed,
+ rad,
+ );
+ scratchPointLocal.set(ext[0], ext[1], ext[2]);
+ if (!isSurfaceAnchorVisible(scratchPointLocal, scratchCameraLocal, occRadius)) continue;
+
+ scratchPointWorld.copy(scratchPointLocal).applyMatrix4(earth.matrixWorld);
+ scratchScreenPos.copy(scratchPointWorld).project(camera);
+ if (scratchScreenPos.z > 1) continue;
+
+ const sx = (scratchScreenPos.x + 1) * halfW;
+ const sy = (-scratchScreenPos.y + 1) * halfH;
+ const dx = sx - clientX;
+ const dy = sy - clientY;
+ const dSq = dx * dx + dy * dy;
+ if (dSq <= bestDistSq) {
+ bestDistSq = dSq;
+ bestIdx = idx;
+ }
+ }
+
+ if (bestIdx < 0) return [];
+ const rec = currentRecords[bestIdx];
+ return [
+ {
+ index: bestIdx,
+ distanceSq: bestDistSq,
+ object: {
+ userData: {
+ type: "aircraft",
+ id: rec.icao24,
+ icao24: rec.icao24,
+ name: rec.callsign || rec.icao24.toUpperCase(),
+ callsign: rec.callsign,
+ latitude: rec.lat,
+ longitude: rec.lon,
+ altitude_m: rec.altitudeM,
+ ground_speed_ms: rec.groundSpeedMs,
+ track_deg: rec.trackDeg,
+ vertical_rate_ms: rec.verticalRateMs,
+ category: rec.category,
+ is_military: rec.isMilitary,
+ is_emergency: rec.isEmergency,
+ emergency_code: rec.emergencyCode,
+ on_ground: rec.onGround,
+ source: rec.source,
+ observed_at: rec.observedAt,
+ },
+ },
+ },
+ ];
+}
+
+export function buildAircraftSearchItems(normalizedQuery, computeSearchScore) {
+ if (!showAircraft || !currentRecords.length) return [];
+ const matches = [];
+ for (let i = 0; i < currentRecords.length; i += 1) {
+ const rec = currentRecords[i];
+ const score = computeSearchScore(
+ normalizedQuery,
+ rec.callsign,
+ rec.icao24,
+ rec.category,
+ rec.emergencyCode,
+ "飞机 aircraft 航班 military emergency",
+ );
+ if (score < 0) continue;
+ matches.push({
+ id: `aircraft:${rec.icao24}`,
+ kind: "aircraft",
+ icon: "flight",
+ typeLabel: rec.isMilitary ? "军机" : "航空器",
+ title: rec.callsign || rec.icao24.toUpperCase(),
+ subtitle: `${rec.icao24.toUpperCase()} · ${AIRCRAFT_CATEGORY_LABELS[rec.category] || rec.category}`,
+ score,
+ entity: rec,
+ });
+ }
+ return matches.slice(0, 30);
+}
diff --git a/frontend/public/earth/js/asset-swr-cache.js b/frontend/public/earth/js/asset-swr-cache.js
new file mode 100644
index 00000000..ed8f6665
--- /dev/null
+++ b/frontend/public/earth/js/asset-swr-cache.js
@@ -0,0 +1,512 @@
+/**
+ * Unified local Stale-While-Revalidate (SWR) cache backed by Cache Storage
+ * (binary/JSON bodies) + IndexedDB (metadata, ETag/fingerprint, LRU eviction).
+ * Falls back transparently to bounded in-memory Maps when browser storage APIs
+ * are unavailable (e.g., private browsing or Node/Bun unit tests).
+ */
+
+const CACHE_PREFIX = "planet-earth-assets-v1:";
+const IDB_NAME = "planet-earth-asset-meta-v1";
+const IDB_VERSION = 1;
+const STORE_ENTRIES = "entries";
+const LEGACY_BOUNDARY_IDB = "planet-earth-boundary-tiles";
+
+export const BUCKET_LIMITS = Object.freeze({
+ "card-images": { maxBytes: 128 * 1024 * 1024, maxItems: 250 },
+ tiles: { maxBytes: 384 * 1024 * 1024, maxItems: 2400 },
+ terrain: { maxBytes: 128 * 1024 * 1024, maxItems: 700 },
+ clouds: { maxBytes: 64 * 1024 * 1024, maxItems: 8 },
+ wind: { maxBytes: 32 * 1024 * 1024, maxItems: 8 },
+ geo: { maxBytes: 64 * 1024 * 1024, maxItems: 24 },
+ meta: { maxBytes: 8 * 1024 * 1024, maxItems: 128 },
+});
+
+const memoryMeta = new Map();
+const memoryBlobs = new Map();
+let dbPromise = null;
+
+function entryId(bucket, key) {
+ return `${bucket}::${key}`;
+}
+
+function syntheticCacheUrl(bucket, key) {
+ return `https://asset.cache.local/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`;
+}
+
+function getBucketLimit(bucket) {
+ return BUCKET_LIMITS[bucket] || { maxBytes: 64 * 1024 * 1024, maxItems: 200 };
+}
+
+function hasCacheStorage() {
+ return typeof caches !== "undefined" && typeof caches?.open === "function";
+}
+
+function openMetaDb() {
+ if (typeof indexedDB === "undefined") return Promise.resolve(null);
+ if (dbPromise) return dbPromise;
+ dbPromise = new Promise((resolve) => {
+ try {
+ const req = indexedDB.open(IDB_NAME, IDB_VERSION);
+ req.onupgradeneeded = () => {
+ const db = req.result;
+ if (!db.objectStoreNames.contains(STORE_ENTRIES)) {
+ const store = db.createObjectStore(STORE_ENTRIES, { keyPath: "id" });
+ store.createIndex("bucket", "bucket", { unique: false });
+ store.createIndex("lastAccessedAt", "lastAccessedAt", { unique: false });
+ }
+ };
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => resolve(null);
+ } catch {
+ resolve(null);
+ }
+ });
+ return dbPromise;
+}
+
+async function idbGet(id) {
+ const db = await openMetaDb();
+ if (!db) return memoryMeta.get(id) || null;
+ return new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE_ENTRIES, "readonly");
+ const req = tx.objectStore(STORE_ENTRIES).get(id);
+ req.onsuccess = () => resolve(req.result || memoryMeta.get(id) || null);
+ req.onerror = () => resolve(memoryMeta.get(id) || null);
+ } catch {
+ resolve(memoryMeta.get(id) || null);
+ }
+ });
+}
+
+async function idbPut(record) {
+ memoryMeta.set(record.id, record);
+ const db = await openMetaDb();
+ if (!db) return;
+ await new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE_ENTRIES, "readwrite");
+ tx.objectStore(STORE_ENTRIES).put(record);
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => resolve();
+ } catch {
+ resolve();
+ }
+ });
+}
+
+async function idbDelete(id) {
+ memoryMeta.delete(id);
+ const db = await openMetaDb();
+ if (!db) return;
+ await new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE_ENTRIES, "readwrite");
+ tx.objectStore(STORE_ENTRIES).delete(id);
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => resolve();
+ } catch {
+ resolve();
+ }
+ });
+}
+
+async function idbListAll() {
+ const db = await openMetaDb();
+ if (!db) return Array.from(memoryMeta.values());
+ return new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE_ENTRIES, "readonly");
+ const req = tx.objectStore(STORE_ENTRIES).getAll();
+ req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
+ req.onerror = () => resolve(Array.from(memoryMeta.values()));
+ } catch {
+ resolve(Array.from(memoryMeta.values()));
+ }
+ });
+}
+
+async function idbListByBucket(bucket) {
+ const db = await openMetaDb();
+ if (!db) {
+ return Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket);
+ }
+ return new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE_ENTRIES, "readonly");
+ const index = tx.objectStore(STORE_ENTRIES).index("bucket");
+ const req = index.getAll(bucket);
+ req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
+ req.onerror = () => resolve(Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket));
+ } catch {
+ resolve(Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket));
+ }
+ });
+}
+
+async function writeBody(bucket, key, blob, contentType) {
+ const memKey = entryId(bucket, key);
+ memoryBlobs.set(memKey, blob);
+ if (memoryBlobs.size > 48 && hasCacheStorage()) {
+ const oldest = memoryBlobs.keys().next().value;
+ if (oldest) memoryBlobs.delete(oldest);
+ }
+ if (!hasCacheStorage()) return;
+ try {
+ const cache = await caches.open(`${CACHE_PREFIX}${bucket}`);
+ const response = new Response(blob, {
+ status: 200,
+ headers: {
+ "Content-Type": contentType || blob.type || "application/octet-stream",
+ },
+ });
+ await cache.put(syntheticCacheUrl(bucket, key), response);
+ } catch {
+ // Quota errors fall back gracefully to in-memory copy.
+ }
+}
+
+async function readBody(bucket, key) {
+ const memKey = entryId(bucket, key);
+ if (hasCacheStorage()) {
+ try {
+ const cache = await caches.open(`${CACHE_PREFIX}${bucket}`);
+ const hit = await cache.match(syntheticCacheUrl(bucket, key));
+ if (hit) {
+ return await hit.blob();
+ }
+ } catch {
+ // Fall through to memory cache.
+ }
+ }
+ return memoryBlobs.get(memKey) || null;
+}
+
+async function deleteBody(bucket, key) {
+ const memKey = entryId(bucket, key);
+ memoryBlobs.delete(memKey);
+ if (!hasCacheStorage()) return;
+ try {
+ const cache = await caches.open(`${CACHE_PREFIX}${bucket}`);
+ await cache.delete(syntheticCacheUrl(bucket, key));
+ } catch {
+ // Ignore Cache Storage cleanup errors.
+ }
+}
+
+async function enforceBucketLru(bucket) {
+ const { maxBytes, maxItems } = getBucketLimit(bucket);
+ const items = await idbListByBucket(bucket);
+ let totalBytes = items.reduce((sum, item) => sum + (Number(item.sizeBytes) || 0), 0);
+ if (items.length <= maxItems && totalBytes <= maxBytes) return;
+
+ items.sort((a, b) => (a.lastAccessedAt || 0) - (b.lastAccessedAt || 0));
+ let remaining = items.length;
+ for (const item of items) {
+ if (remaining <= maxItems && totalBytes <= maxBytes) break;
+ await deleteBody(bucket, item.key);
+ await idbDelete(item.id);
+ remaining -= 1;
+ totalBytes -= Number(item.sizeBytes) || 0;
+ }
+ if (!hasCacheStorage() && memoryBlobs.size > maxItems) {
+ const prefix = `${bucket}::`;
+ for (const key of Array.from(memoryMeta.keys())) {
+ if (key.startsWith(prefix) && !memoryBlobs.has(key)) memoryMeta.delete(key);
+ }
+ }
+}
+
+export function formatBytes(bytes) {
+ const n = Number(bytes) || 0;
+ if (n <= 0) return "0 B";
+ if (n < 1024) return `${Math.round(n)} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
+ return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
+}
+
+export async function getCachedAssetMeta(bucket, key) {
+ return idbGet(entryId(bucket, key));
+}
+
+export async function putCachedAssetMeta(bucket, key, metaPatch = {}) {
+ const id = entryId(bucket, key);
+ const prev = await idbGet(id);
+ const now = Date.now();
+ const next = {
+ ...(prev || {}),
+ ...metaPatch,
+ id,
+ bucket,
+ key,
+ updatedAt: metaPatch.updatedAt ?? prev?.updatedAt ?? now,
+ lastAccessedAt: now,
+ };
+ await idbPut(next);
+ return next;
+}
+
+export async function putCachedAssetBlob(bucket, key, blob, metaPatch = {}) {
+ const now = Date.now();
+ const contentType = metaPatch.contentType || blob.type || "application/octet-stream";
+ await writeBody(bucket, key, blob, contentType);
+ const record = {
+ ...(await idbGet(entryId(bucket, key))),
+ ...metaPatch,
+ id: entryId(bucket, key),
+ bucket,
+ key,
+ contentType,
+ sizeBytes: Number(blob.size) || Number(metaPatch.sizeBytes) || 0,
+ updatedAt: now,
+ lastAccessedAt: now,
+ };
+ await idbPut(record);
+ await enforceBucketLru(bucket);
+ return record;
+}
+
+export async function readCachedAssetBlob(bucket, key) {
+ const blob = await readBody(bucket, key);
+ if (!blob) return null;
+ const meta = await idbGet(entryId(bucket, key));
+ if (meta) {
+ void idbPut({ ...meta, lastAccessedAt: Date.now() });
+ }
+ return blob;
+}
+
+export async function putCachedAssetJson(bucket, key, data, metaPatch = {}) {
+ const encoded = JSON.stringify(data);
+ const blob = new Blob([encoded], { type: "application/json" });
+ return putCachedAssetBlob(bucket, key, blob, {
+ ...metaPatch,
+ contentType: "application/json",
+ sizeBytes: blob.size,
+ });
+}
+
+export async function readCachedAssetJson(bucket, key) {
+ const blob = await readCachedAssetBlob(bucket, key);
+ if (!blob) return null;
+ try {
+ const text = await blob.text();
+ return JSON.parse(text);
+ } catch {
+ await deleteCachedAsset(bucket, key);
+ return null;
+ }
+}
+
+export async function deleteCachedAsset(bucket, key) {
+ await deleteBody(bucket, key);
+ await idbDelete(entryId(bucket, key));
+}
+
+export async function fetchBinarySwr({
+ bucket,
+ key,
+ url,
+ fingerprint = "",
+ fetchImpl = globalThis.fetch?.bind(globalThis),
+ signal,
+ headers,
+}) {
+ const meta = await getCachedAssetMeta(bucket, key);
+ const matchesFingerprint = fingerprint
+ ? meta?.fingerprint === fingerprint
+ : meta?.url === url;
+ if (meta && matchesFingerprint) {
+ const cachedBlob = await readCachedAssetBlob(bucket, key);
+ if (cachedBlob) {
+ return { blob: cachedBlob, fromCache: true, meta };
+ }
+ }
+
+ const reqHeaders = new Headers(headers || {});
+ if (meta?.etag && meta.url === url && !fingerprint) {
+ reqHeaders.set("If-None-Match", meta.etag);
+ }
+ const response = await fetchImpl(url, { headers: reqHeaders, signal });
+ if (response.status === 304 && meta) {
+ const cachedBlob = await readCachedAssetBlob(bucket, key);
+ if (cachedBlob) {
+ const refreshed = await putCachedAssetMeta(bucket, key, { lastCheckedAt: Date.now() });
+ return { blob: cachedBlob, fromCache: true, meta: refreshed };
+ }
+ }
+ if (!response.ok) {
+ throw new Error(`Asset fetch failed (${response.status}): ${url}`);
+ }
+ const blob = await response.blob();
+ const nextMeta = await putCachedAssetBlob(bucket, key, blob, {
+ url,
+ fingerprint: fingerprint || response.headers.get("etag") || "",
+ etag: response.headers.get("etag") || "",
+ lastCheckedAt: Date.now(),
+ });
+ return { blob, fromCache: false, meta: nextMeta };
+}
+
+export async function fetchJsonSwr({
+ bucket = "meta",
+ key,
+ url,
+ fetchImpl = globalThis.fetch?.bind(globalThis),
+ timeoutMs = 15000,
+ headers,
+ onFresh,
+}) {
+ const existingMeta = await getCachedAssetMeta(bucket, key);
+ const existingData = existingMeta ? await readCachedAssetJson(bucket, key) : null;
+
+ const runRevalidate = async () => {
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ const timer = controller && timeoutMs > 0
+ ? setTimeout(() => controller.abort(), timeoutMs)
+ : null;
+ try {
+ const reqHeaders = new Headers(headers || {});
+ if (existingMeta?.etag) {
+ reqHeaders.set("If-None-Match", existingMeta.etag);
+ }
+ const response = await fetchImpl(url, {
+ headers: reqHeaders,
+ signal: controller?.signal,
+ cache: "no-cache",
+ });
+ if (response.status === 304 && existingData !== null) {
+ const touched = await putCachedAssetMeta(bucket, key, { lastCheckedAt: Date.now() });
+ return { data: existingData, status: 304, fromCache: true, etag: touched.etag || "" };
+ }
+ if (!response.ok) {
+ throw new Error(`JSON SWR fetch failed (${response.status}): ${url}`);
+ }
+ const nextData = await response.json();
+ const nextEtag = response.headers.get("etag") || "";
+ await putCachedAssetJson(bucket, key, nextData, {
+ url,
+ etag: nextEtag,
+ lastCheckedAt: Date.now(),
+ });
+ if (typeof onFresh === "function") {
+ onFresh(nextData, { etag: nextEtag, changed: true });
+ }
+ return { data: nextData, status: response.status, fromCache: false, etag: nextEtag };
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ };
+
+ if (existingData !== null) {
+ const revalidatePromise = runRevalidate().catch(() => ({
+ data: existingData,
+ status: 0,
+ fromCache: true,
+ etag: existingMeta?.etag || "",
+ }));
+ return {
+ data: existingData,
+ fromCache: true,
+ meta: existingMeta,
+ revalidatePromise,
+ };
+ }
+
+ const fresh = await runRevalidate();
+ return {
+ data: fresh.data,
+ fromCache: false,
+ meta: await getCachedAssetMeta(bucket, key),
+ revalidatePromise: Promise.resolve(fresh),
+ };
+}
+
+export async function getLocalCacheStats() {
+ const all = await idbListAll();
+ const buckets = {};
+ let webBytes = 0;
+ let webCount = 0;
+ for (const item of all) {
+ const name = item.bucket || "other";
+ if (!buckets[name]) buckets[name] = { bytes: 0, count: 0 };
+ const size = Number(item.sizeBytes) || 0;
+ buckets[name].bytes += size;
+ buckets[name].count += 1;
+ webBytes += size;
+ webCount += 1;
+ }
+
+ let desktop = null;
+ if (typeof window !== "undefined" && typeof window.planetDesktop?.getAssetCacheStats === "function") {
+ try {
+ desktop = await window.planetDesktop.getAssetCacheStats();
+ } catch {
+ desktop = null;
+ }
+ }
+
+ const desktopBytes = Number(desktop?.totalBytes) || 0;
+ const desktopCount = Number(desktop?.totalCount) || 0;
+ return {
+ web: { totalBytes: webBytes, totalCount: webCount, buckets },
+ desktop,
+ totalBytes: webBytes + desktopBytes,
+ totalCount: webCount + desktopCount,
+ };
+}
+
+export async function clearLocalAssetCache(buckets = null) {
+ const targetBuckets = Array.isArray(buckets) && buckets.length ? new Set(buckets) : null;
+ const all = await idbListAll();
+ for (const item of all) {
+ if (!targetBuckets || targetBuckets.has(item.bucket)) {
+ await deleteBody(item.bucket, item.key);
+ await idbDelete(item.id);
+ }
+ }
+ if (hasCacheStorage()) {
+ try {
+ const names = await caches.keys();
+ await Promise.all(
+ names
+ .filter((name) => {
+ if (!name.startsWith(CACHE_PREFIX)) return false;
+ if (!targetBuckets) return true;
+ return targetBuckets.has(name.slice(CACHE_PREFIX.length));
+ })
+ .map((name) => caches.delete(name)),
+ );
+ } catch {
+ // Ignore cache deletion failures.
+ }
+ }
+ if (!targetBuckets && typeof indexedDB !== "undefined") {
+ for (const legacyDb of [LEGACY_BOUNDARY_IDB]) {
+ try {
+ await new Promise((resolve) => {
+ const req = indexedDB.deleteDatabase(legacyDb);
+ req.onsuccess = () => resolve();
+ req.onerror = () => resolve();
+ req.onblocked = () => resolve();
+ });
+ } catch {
+ // Ignore legacy IDB cleanup failure.
+ }
+ }
+ }
+ if (typeof window !== "undefined" && typeof window.planetDesktop?.clearAssetCache === "function") {
+ try {
+ await window.planetDesktop.clearAssetCache(buckets || undefined);
+ } catch {
+ // Ignore desktop IPC error.
+ }
+ }
+ return getLocalCacheStats();
+}
+
+export function _resetMemoryCacheForTests() {
+ memoryMeta.clear();
+ memoryBlobs.clear();
+}
diff --git a/frontend/public/earth/js/asset-swr-cache.test.js b/frontend/public/earth/js/asset-swr-cache.test.js
new file mode 100644
index 00000000..5834e3af
--- /dev/null
+++ b/frontend/public/earth/js/asset-swr-cache.test.js
@@ -0,0 +1,144 @@
+import { beforeEach, expect, test } from "bun:test";
+import {
+ _resetMemoryCacheForTests,
+ clearLocalAssetCache,
+ fetchBinarySwr,
+ fetchJsonSwr,
+ formatBytes,
+ getLocalCacheStats,
+ putCachedAssetBlob,
+ readCachedAssetBlob,
+} from "./asset-swr-cache.js";
+
+beforeEach(() => {
+ _resetMemoryCacheForTests();
+});
+
+test("formatBytes formats human-readable sizes cleanly", () => {
+ expect(formatBytes(0)).toBe("0 B");
+ expect(formatBytes(512)).toBe("512 B");
+ expect(formatBytes(2048)).toBe("2.0 KB");
+ expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MB");
+});
+
+test("fetchBinarySwr returns cached blob on matching fingerprint and re-fetches only on fingerprint change", async () => {
+ let fetches = 0;
+ const fetchMock = async (url) => {
+ fetches += 1;
+ const body = fetches === 1 ? "image-v1" : "image-v2";
+ return new Response(new Blob([body], { type: "image/webp" }), {
+ status: 200,
+ headers: { "Content-Type": "image/webp", ETag: `"fp-${fetches}"` },
+ });
+ };
+
+ const first = await fetchBinarySwr({
+ bucket: "card-images",
+ key: "card:1",
+ url: "/api/v1/earth/card-images/files/v1.webp",
+ fingerprint: "fp-1",
+ fetchImpl: fetchMock,
+ });
+ expect(first.fromCache).toBe(false);
+ expect(await first.blob.text()).toBe("image-v1");
+
+ const second = await fetchBinarySwr({
+ bucket: "card-images",
+ key: "card:1",
+ url: "/api/v1/earth/card-images/files/v1.webp",
+ fingerprint: "fp-1",
+ fetchImpl: fetchMock,
+ });
+ expect(second.fromCache).toBe(true);
+ expect(await second.blob.text()).toBe("image-v1");
+ expect(fetches).toBe(1);
+
+ const third = await fetchBinarySwr({
+ bucket: "card-images",
+ key: "card:1",
+ url: "/api/v1/earth/card-images/files/v2.webp",
+ fingerprint: "fp-2",
+ fetchImpl: fetchMock,
+ });
+ expect(third.fromCache).toBe(false);
+ expect(await third.blob.text()).toBe("image-v2");
+ expect(fetches).toBe(2);
+});
+
+test("fetchJsonSwr serves cached JSON immediately and sends If-None-Match in background", async () => {
+ const seenIfNoneMatch = [];
+ let freshUpdates = 0;
+ let serverVersion = 1;
+
+ const fetchMock = async (_url, init) => {
+ seenIfNoneMatch.push(init?.headers?.get("If-None-Match") || null);
+ if (serverVersion === 1 && init?.headers?.get("If-None-Match") === '"etag-1"') {
+ return new Response(null, { status: 304, headers: { ETag: '"etag-1"' } });
+ }
+ return new Response(JSON.stringify({ version: serverVersion }), {
+ status: 200,
+ headers: { "Content-Type": "application/json", ETag: `"etag-${serverVersion}"` },
+ });
+ };
+
+ const cold = await fetchJsonSwr({
+ bucket: "meta",
+ key: "brand",
+ url: "/api/v1/earth/brand",
+ fetchImpl: fetchMock,
+ });
+ expect(cold.fromCache).toBe(false);
+ expect(cold.data.version).toBe(1);
+
+ const warmNotModified = await fetchJsonSwr({
+ bucket: "meta",
+ key: "brand",
+ url: "/api/v1/earth/brand",
+ fetchImpl: fetchMock,
+ onFresh: () => {
+ freshUpdates += 1;
+ },
+ });
+ expect(warmNotModified.fromCache).toBe(true);
+ expect(warmNotModified.data.version).toBe(1);
+ const bg1 = await warmNotModified.revalidatePromise;
+ expect(bg1.status).toBe(304);
+ expect(freshUpdates).toBe(0);
+
+ serverVersion = 2;
+ const warmUpdated = await fetchJsonSwr({
+ bucket: "meta",
+ key: "brand",
+ url: "/api/v1/earth/brand",
+ fetchImpl: fetchMock,
+ onFresh: () => {
+ freshUpdates += 1;
+ },
+ });
+ expect(warmUpdated.fromCache).toBe(true);
+ expect(warmUpdated.data.version).toBe(1);
+ const bg2 = await warmUpdated.revalidatePromise;
+ expect(bg2.status).toBe(200);
+ expect(bg2.data.version).toBe(2);
+ expect(freshUpdates).toBe(1);
+ expect(seenIfNoneMatch).toEqual([null, '"etag-1"', '"etag-1"']);
+});
+
+test("LRU eviction and stats/clear report accurate totals", async () => {
+ await putCachedAssetBlob("clouds", "c1", new Blob(["aaaa"]), { updatedAt: 1 });
+ await new Promise((r) => setTimeout(r, 5));
+ await putCachedAssetBlob("clouds", "c2", new Blob(["bbbbbb"]), { updatedAt: 2 });
+ for (let i = 0; i < 8; i += 1) {
+ await putCachedAssetBlob("clouds", `extra-${i}`, new Blob(["xx"]));
+ }
+ // clouds maxItems = 8, so c1 must have been evicted
+ expect(await readCachedAssetBlob("clouds", "c1")).toBeNull();
+
+ const stats = await getLocalCacheStats();
+ expect(stats.totalCount).toBe(8);
+ expect(stats.totalBytes).toBeGreaterThan(0);
+
+ const afterClear = await clearLocalAssetCache();
+ expect(afterClear.totalCount).toBe(0);
+ expect(afterClear.totalBytes).toBe(0);
+});
diff --git a/frontend/public/earth/js/bgp.js b/frontend/public/earth/js/bgp.js
index c4ec1d9b..b2a1ff75 100644
--- a/frontend/public/earth/js/bgp.js
+++ b/frontend/public/earth/js/bgp.js
@@ -1337,18 +1337,20 @@ export async function loadBGPAnomalies(scene, earth) {
}
const emptyPayload = { type: "FeatureCollection", features: [], count: 0 };
- const anomaliesPayload = await fetchGeoJSONWithTimeout(
- `${PATHS.bgpApi}?limit=${BGP_CONFIG.defaultFetchLimit}`,
- 5000,
- "BGP anomalies unavailable, falling back to collectors only:",
- emptyPayload,
- );
- const incidentsPayload = await fetchGeoJSONWithTimeout(
- `${PATHS.bgpIncidentsApi}?limit=${BGP_CONFIG.defaultFetchLimit}`,
- 5000,
- "BGP incidents unavailable, falling back to anomalies:",
- emptyPayload,
- );
+ const [anomaliesPayload, incidentsPayload] = await Promise.all([
+ fetchGeoJSONWithTimeout(
+ `${PATHS.bgpApi}?limit=${BGP_CONFIG.defaultFetchLimit}`,
+ 5000,
+ "BGP anomalies unavailable, falling back to collectors only:",
+ emptyPayload,
+ ),
+ fetchGeoJSONWithTimeout(
+ `${PATHS.bgpIncidentsApi}?limit=${BGP_CONFIG.defaultFetchLimit}`,
+ 5000,
+ "BGP incidents unavailable, falling back to anomalies:",
+ emptyPayload,
+ ),
+ ]);
const collectorsPayload = await collectorsResponse.json();
const collectorFeatures = Array.isArray(collectorsPayload?.features)
diff --git a/frontend/public/earth/js/brand.js b/frontend/public/earth/js/brand.js
index a14ff505..ea67564c 100644
--- a/frontend/public/earth/js/brand.js
+++ b/frontend/public/earth/js/brand.js
@@ -1,3 +1,5 @@
+import { fetchJsonSwr } from "./asset-swr-cache.js";
+
const DEFAULT_BRAND_LANGUAGE = "zh";
const EARTH_BRAND_API = "/api/v1/earth/brand";
@@ -253,11 +255,14 @@ export function mountBrand(target, configOrVariant = DEFAULT_BRAND_LANGUAGE) {
attachBrandImageResilience(target, defaults);
}
-export async function fetchEarthBrandConfig() {
- const response = await fetch(EARTH_BRAND_API, { cache: "no-store" });
- if (!response.ok) {
- throw new Error(`Earth brand config request failed: ${response.status}`);
- }
- const payload = await response.json();
- return payload?.brand ?? getDefaultBrandConfig();
+export async function fetchEarthBrandConfig(onFresh) {
+ const { data } = await fetchJsonSwr({
+ bucket: "meta",
+ key: "brand",
+ url: EARTH_BRAND_API,
+ onFresh: (fresh) => {
+ if (typeof onFresh === "function") onFresh(fresh?.brand ?? getDefaultBrandConfig());
+ },
+ });
+ return data?.brand ?? getDefaultBrandConfig();
}
diff --git a/frontend/public/earth/js/cables.js b/frontend/public/earth/js/cables.js
index 6330f5d7..ddd84ba5 100644
--- a/frontend/public/earth/js/cables.js
+++ b/frontend/public/earth/js/cables.js
@@ -18,6 +18,7 @@ import { getSurfaceMarkerCameraScale } from "./utils.js";
import { setEarthStatValue, updateEarthStats, showStatusMessage } from "./ui.js";
import { setLegendItems, setLegendMode } from "./legend.js";
import { earthMessage } from "./i18n.js";
+import { fetchJsonSwr } from "./asset-swr-cache.js";
export let cableLines = [];
export let landingPoints = [];
@@ -198,6 +199,8 @@ function createCableLine(points, color, properties) {
length: properties.length || "-",
coords: "-",
rfs: properties.rfs || "-",
+ advisories: Array.isArray(properties.advisories) ? properties.advisories : [],
+ hasAdvisory: Boolean(Array.isArray(properties.advisories) && properties.advisories.length > 0),
originalColor: color,
localCenter:
lineGeometry.boundingSphere?.center?.clone() || new THREE.Vector3(),
@@ -238,18 +241,8 @@ export function clearCableData(earthObj = null) {
clearLandingPoints(earthObj);
}
-export async function loadGeoJSONFromPath(scene, earthObj, options = {}) {
+function applyCableGeoJson(earthObj, data, options = {}) {
const { silent = false } = options;
- if (!silent) {
- showStatusMessage(earthMessage("loading.cableData"), "warning");
- }
-
- const response = await fetch(PATHS.cablesApi, { cache: "no-store" });
- if (!response.ok) {
- throw new Error(`电缆接口返回 HTTP ${response.status}`);
- }
-
- const data = await response.json();
if (!data.features || !Array.isArray(data.features)) {
throw new Error("无效的电缆 GeoJSON 格式");
}
@@ -350,15 +343,25 @@ export async function loadGeoJSONFromPath(scene, earthObj, options = {}) {
return cableLines.length;
}
-export async function loadLandingPoints(scene, earthObj, options = {}) {
+export async function loadGeoJSONFromPath(scene, earthObj, options = {}) {
const { silent = false } = options;
-
- const response = await fetch(PATHS.landingPointsApi, { cache: "no-store" });
- if (!response.ok) {
- throw new Error(`登陆点接口返回 HTTP ${response.status}`);
+ if (!silent) {
+ showStatusMessage(earthMessage("loading.cableData"), "warning");
}
- const data = await response.json();
+ const { data } = await fetchJsonSwr({
+ bucket: "geo",
+ key: "cables",
+ url: PATHS.cablesApi,
+ onFresh: (fresh) => {
+ try { applyCableGeoJson(earthObj, fresh, { silent: true }); } catch {}
+ },
+ });
+ return applyCableGeoJson(earthObj, data, options);
+}
+
+async function applyLandingPointsGeoJson(earthObj, data, options = {}) {
+ const { silent = false } = options;
if (!data.features || !Array.isArray(data.features)) {
throw new Error("无效的登陆点 GeoJSON 格式");
}
@@ -445,6 +448,18 @@ export async function loadLandingPoints(scene, earthObj, options = {}) {
return validCount;
}
+export async function loadLandingPoints(scene, earthObj, options = {}) {
+ const { data } = await fetchJsonSwr({
+ bucket: "geo",
+ key: "landing-points",
+ url: PATHS.landingPointsApi,
+ onFresh: (fresh) => {
+ void applyLandingPointsGeoJson(earthObj, fresh, { silent: true }).catch(() => {});
+ },
+ });
+ return applyLandingPointsGeoJson(earthObj, data, options);
+}
+
export function handleCableClick(cable) {
clearLockedCableRibbon();
lockedCable = cable;
diff --git a/frontend/public/earth/js/card-images.js b/frontend/public/earth/js/card-images.js
index 220dd5ba..89286483 100644
--- a/frontend/public/earth/js/card-images.js
+++ b/frontend/public/earth/js/card-images.js
@@ -1,9 +1,27 @@
import { isComputeSiteType } from "./compute-site-types.js";
+import {
+ deleteCachedAsset,
+ getCachedAssetMeta,
+ putCachedAssetBlob,
+ putCachedAssetMeta,
+ readCachedAssetBlob,
+} from "./asset-swr-cache.js";
+
// Optional imagery belongs to card selection, never to the animation loop.
-const ENDPOINT = "/api/v1/earth/card-images/resolve";
+const RESOLVE_ENDPOINT = "/api/v1/earth/card-images/resolve";
+const FINGERPRINT_ENDPOINT = "/api/v1/earth/card-images/fingerprint";
+const CARD_CACHE_BUCKET = "card-images";
+const GLOBAL_REVISION_KEY = "__global_revision__";
+const GLOBAL_REVISION_TTL_MS = 0;
export const CARD_IMAGE_REVISION_KEY = "planet.earth.card-images.revision";
-const cache = new Map();
+const memoryResolveCache = new Map();
const presenters = new Set();
+let globalRevisionState = { revision: "", checkedAt: 0, inflight: null };
+
+export function _resetCardImagesRuntimeForTests() {
+ memoryResolveCache.clear();
+ globalRevisionState = { revision: "", checkedAt: 0, inflight: null };
+}
export function cardImageIdentity(type, data) {
if (type === "satellite" && data?.norad_id != null) return {entity_type:"satellite",entity_id:String(data.norad_id)};
@@ -22,21 +40,82 @@ export function cardImageIdentity(type, data) {
return null;
}
+function identityCacheKey(identity, size) {
+ return `${identity.entity_type}:${identity.entity_id}:${size}`;
+}
+
+async function checkGlobalRevision(fetchImpl = globalThis.fetch?.bind(globalThis), { force = false } = {}) {
+ const now = Date.now();
+ if (!force && globalRevisionState.revision && now - globalRevisionState.checkedAt < GLOBAL_REVISION_TTL_MS) {
+ return globalRevisionState.revision;
+ }
+ if (globalRevisionState.inflight) return globalRevisionState.inflight;
+ globalRevisionState.inflight = (async () => {
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ const timer = controller ? setTimeout(() => controller.abort(), 5000) : null;
+ try {
+ const cachedGlobal = await getCachedAssetMeta(CARD_CACHE_BUCKET, GLOBAL_REVISION_KEY);
+ const headers = cachedGlobal?.etag ? { "If-None-Match": cachedGlobal.etag } : {};
+ const resp = await fetchImpl(FINGERPRINT_ENDPOINT, { headers, signal: controller?.signal });
+ if (resp.status === 304 && cachedGlobal?.revision) {
+ globalRevisionState = { revision: cachedGlobal.revision, checkedAt: Date.now(), inflight: null };
+ return cachedGlobal.revision;
+ }
+ if (!resp.ok) throw new Error(`Fingerprint check failed: ${resp.status}`);
+ const data = await resp.json();
+ const rev = String(data?.revision || "");
+ const etag = resp.headers.get("etag") || "";
+ await putCachedAssetMeta(CARD_CACHE_BUCKET, GLOBAL_REVISION_KEY, { revision: rev, etag });
+ globalRevisionState = { revision: rev, checkedAt: Date.now(), inflight: null };
+ return rev;
+ } catch {
+ globalRevisionState.inflight = null;
+ return globalRevisionState.revision || "";
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ })();
+ return globalRevisionState.inflight;
+}
+
+async function fetchResolveMetadata(identity, cachedFingerprint = "", fetchImpl = globalThis.fetch?.bind(globalThis)) {
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ const timer = controller ? setTimeout(() => controller.abort(), 7000) : null;
+ try {
+ const headers = cachedFingerprint ? { "If-None-Match": `"${cachedFingerprint}"` } : {};
+ const response = await fetchImpl(`${RESOLVE_ENDPOINT}?${new URLSearchParams(identity)}`, {
+ headers,
+ signal: controller?.signal,
+ });
+ if (response.status === 304) {
+ return { notModified: true, asset: null, fingerprint: cachedFingerprint, revision: "" };
+ }
+ if (response.status === 404) {
+ return { notModified: false, asset: null, fingerprint: "", revision: "" };
+ }
+ if (!response.ok) {
+ throw new Error(`Card image lookup failed: ${response.status}`);
+ }
+ const payload = await response.json();
+ return {
+ notModified: false,
+ asset: payload.image || null,
+ fingerprint: String(payload.fingerprint || response.headers.get("etag")?.replace(/"/g, "") || ""),
+ revision: String(payload.revision || ""),
+ };
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
async function resolveCardImage(identity) {
const key = `${identity.entity_type}:${identity.entity_id}`;
- const existing = cache.get(key);
+ const existing = memoryResolveCache.get(key);
if (existing && existing.expires > Date.now()) return existing.promise;
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 7000);
- const promise = fetch(`${ENDPOINT}?${new URLSearchParams(identity)}`, {signal:controller.signal})
- .then(async response => {
- if (response.status === 404) return null;
- if (!response.ok) throw new Error(`Card image lookup failed: ${response.status}`);
- return (await response.json()).image;
- }).finally(() => clearTimeout(timeout));
- cache.set(key,{promise,expires:Date.now()+30000});
- if (cache.size > 100) cache.delete(cache.keys().next().value);
- try {return await promise;} catch(error) {cache.delete(key);throw error;}
+ const promise = fetchResolveMetadata(identity, "").then((res) => res.asset);
+ memoryResolveCache.set(key, { promise, expires: Date.now() + 30000 });
+ if (memoryResolveCache.size > 100) memoryResolveCache.delete(memoryResolveCache.keys().next().value);
+ try { return await promise; } catch (error) { memoryResolveCache.delete(key); throw error; }
}
function decodeImage(url) {
@@ -46,54 +125,258 @@ function decodeImage(url) {
return image.decode();
}
-export function createCardImagePresenter({layer,image,credit,resolve=resolveCardImage,decode=decodeImage,getWidth=()=>640,onError=error=>console.warn("Card image unavailable",error)}) {
- let revision=0, identity=null;
- const clear=()=>{
- layer.hidden=true;layer.classList.remove("is-loaded");
- image.removeAttribute("src");credit.hidden=true;credit.removeAttribute("href");
- };
- async function show(next) {
- const token=++revision;identity=next;clear();
- if (!next) return;
- try {
- const asset=await resolve(next);
- if (token!==revision || !asset) return;
- const size=getWidth()<=640 ? "640" : "1280";
- const url=asset.variants?.[size] || asset.url;
- await decode(url);
- if(token!==revision) return;
- image.src=url;image.style.objectPosition=`${asset.focus_x ?? 50}% ${asset.focus_y ?? 50}%`;
- layer.hidden=false;layer.classList.add("is-loaded");
- const link=asset.source_url || asset.license_url;
- if(link) {
- credit.href=link;credit.title=[asset.title,asset.credit,asset.license].filter(Boolean).join(" · ");
- credit.setAttribute("aria-label",credit.title);credit.hidden=false;
- }
- } catch(error) {if(token===revision) {clear();onError(error);}}
+function selectVariantUrl(asset, size) {
+ return asset?.variants?.[size] || asset?.url || "";
+}
+
+function applyCredit(credit, asset) {
+ const link = asset?.source_url || asset?.license_url;
+ if (link) {
+ credit.href = link;
+ credit.title = [asset.title, asset.credit, asset.license].filter(Boolean).join(" · ");
+ credit.setAttribute("aria-label", credit.title);
+ credit.hidden = false;
+ } else {
+ credit.hidden = true;
+ credit.removeAttribute("href");
}
- return {show,refresh:()=>show(identity),hide:()=>{revision++;identity=null;clear();}};
+}
+
+export function createCardImagePresenter({
+ layer,
+ image,
+ credit,
+ resolve,
+ decode = decodeImage,
+ fetchImpl = globalThis.fetch?.bind(globalThis),
+ getWidth = () => 640,
+ onError = (error) => console.warn("Card image unavailable", error),
+}) {
+ let revision = 0;
+ let identity = null;
+ let activeObjectUrl = "";
+
+ const revokeActiveBlob = () => {
+ if (activeObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
+ try {
+ URL.revokeObjectURL(activeObjectUrl);
+ } catch {
+ // Ignore revoke errors.
+ }
+ }
+ activeObjectUrl = "";
+ };
+
+ const clear = () => {
+ layer.hidden = true;
+ layer.classList.remove("is-loaded");
+ image.removeAttribute("src");
+ credit.hidden = true;
+ credit.removeAttribute("href");
+ revokeActiveBlob();
+ };
+
+ const renderAssetAtUrl = async (asset, displayUrl, nextObjectUrl, token) => {
+ await decode(displayUrl);
+ if (token !== revision) {
+ if (nextObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
+ try { URL.revokeObjectURL(nextObjectUrl); } catch {}
+ }
+ return false;
+ }
+ const prevObjectUrl = activeObjectUrl;
+ activeObjectUrl = nextObjectUrl || "";
+ image.src = displayUrl;
+ image.style.objectPosition = `${asset.focus_x ?? 50}% ${asset.focus_y ?? 50}%`;
+ layer.hidden = false;
+ layer.classList.add("is-loaded");
+ applyCredit(credit, asset);
+ if (prevObjectUrl && prevObjectUrl !== activeObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
+ try { URL.revokeObjectURL(prevObjectUrl); } catch {}
+ }
+ return true;
+ };
+
+ const showWithCustomResolver = async (next, token) => {
+ try {
+ const asset = await resolve(next);
+ if (token !== revision || !asset) return;
+ const size = getWidth() <= 640 ? "640" : "1280";
+ const url = selectVariantUrl(asset, size);
+ await renderAssetAtUrl(asset, url, "", token);
+ } catch (error) {
+ if (token === revision) {
+ clear();
+ onError(error);
+ }
+ }
+ };
+
+ const downloadAndCacheBlob = async (cacheKey, imageUrl, metaPatch) => {
+ const resp = await fetchImpl(imageUrl);
+ if (!resp.ok) throw new Error(`Card image download failed: ${resp.status}`);
+ const blob = await resp.blob();
+ await putCachedAssetBlob(CARD_CACHE_BUCKET, cacheKey, blob, metaPatch);
+ return blob;
+ };
+
+ const toDisplayUrl = (blob, fallbackUrl) => {
+ if (blob && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
+ const objUrl = URL.createObjectURL(blob);
+ return { displayUrl: objUrl, objectUrl: objUrl };
+ }
+ return { displayUrl: fallbackUrl, objectUrl: "" };
+ };
+
+ async function show(next) {
+ const token = ++revision;
+ identity = next;
+ clear();
+ if (!next) return;
+
+ if (typeof resolve === "function") {
+ await showWithCustomResolver(next, token);
+ return;
+ }
+
+ const size = getWidth() <= 640 ? "640" : "1280";
+ const key = identityCacheKey(next, size);
+ const cachedMeta = await getCachedAssetMeta(CARD_CACHE_BUCKET, key);
+ const cachedBlob = cachedMeta?.asset ? await readCachedAssetBlob(CARD_CACHE_BUCKET, key) : null;
+ let hasDisplayedCached = false;
+
+ if (cachedMeta?.asset && cachedBlob) {
+ try {
+ const { displayUrl, objectUrl } = toDisplayUrl(cachedBlob, cachedMeta.imageUrl || selectVariantUrl(cachedMeta.asset, size));
+ hasDisplayedCached = await renderAssetAtUrl(cachedMeta.asset, displayUrl, objectUrl, token);
+ } catch {
+ hasDisplayedCached = false;
+ }
+ }
+ if (token !== revision) return;
+
+ try {
+ const globalRev = await checkGlobalRevision(fetchImpl);
+ if (token !== revision) return;
+ if (
+ hasDisplayedCached &&
+ globalRev &&
+ cachedMeta?.revision === globalRev &&
+ cachedMeta?.fingerprint
+ ) {
+ return;
+ }
+
+ const cachedFp = cachedMeta?.fingerprint || "";
+ const res = await fetchResolveMetadata(next, cachedFp, fetchImpl);
+ if (token !== revision) return;
+
+ if (res.notModified) {
+ if (cachedMeta) {
+ await putCachedAssetMeta(CARD_CACHE_BUCKET, key, {
+ revision: globalRev || cachedMeta.revision,
+ lastCheckedAt: Date.now(),
+ });
+ }
+ return;
+ }
+
+ if (!res.asset) {
+ if (cachedMeta) await deleteCachedAsset(CARD_CACHE_BUCKET, key);
+ if (hasDisplayedCached) clear();
+ return;
+ }
+
+ const targetUrl = selectVariantUrl(res.asset, size);
+ const sameFingerprint = Boolean(cachedFp && res.fingerprint && cachedFp === res.fingerprint);
+ const sameUrl = Boolean(cachedMeta?.imageUrl && cachedMeta.imageUrl === targetUrl);
+ if (hasDisplayedCached && sameFingerprint && sameUrl) {
+ await putCachedAssetMeta(CARD_CACHE_BUCKET, key, {
+ asset: res.asset,
+ revision: res.revision || globalRev,
+ lastCheckedAt: Date.now(),
+ });
+ applyCredit(credit, res.asset);
+ image.style.objectPosition = `${res.asset.focus_x ?? 50}% ${res.asset.focus_y ?? 50}%`;
+ return;
+ }
+
+ const nextBlob = await downloadAndCacheBlob(key, targetUrl, {
+ url: targetUrl,
+ imageUrl: targetUrl,
+ fingerprint: res.fingerprint,
+ revision: res.revision || globalRev,
+ asset: res.asset,
+ lastCheckedAt: Date.now(),
+ });
+ if (token !== revision) return;
+ const { displayUrl, objectUrl } = toDisplayUrl(nextBlob, targetUrl);
+ await renderAssetAtUrl(res.asset, displayUrl, objectUrl, token);
+ } catch (error) {
+ if (token !== revision) return;
+ if (!hasDisplayedCached) {
+ clear();
+ onError(error);
+ }
+ }
+ }
+
+ return {
+ show,
+ refresh: () => show(identity),
+ hide: () => {
+ revision++;
+ identity = null;
+ clear();
+ },
+ };
}
export function mountCardImage(content, header) {
- const body=document.createElement("div");body.className="card-image-body";
- content.before(body);body.append(content);content.classList.add("card-image-data");
- const layer=document.createElement("div");layer.className="card-image-layer";layer.hidden=true;
- layer.setAttribute("aria-hidden","true");
- const image=document.createElement("img");image.alt="";image.decoding="async";layer.append(image);body.prepend(layer);
- const credit=document.createElement("a");credit.className="card-image-source hud-panel__action";
- credit.hidden=true;credit.target="_blank";credit.rel="noopener noreferrer";
- const icon=document.createElement("span");icon.className="material-symbols-rounded";icon.textContent="image";icon.setAttribute("aria-hidden","true");credit.append(icon);
- if(header) {
- const anchor=header.querySelector("#info-card-workbench, .info-card-close");
- if(anchor?.parentNode) anchor.parentNode.insertBefore(credit,anchor);
+ const body = document.createElement("div");
+ body.className = "card-image-body";
+ content.before(body);
+ body.append(content);
+ content.classList.add("card-image-data");
+ const layer = document.createElement("div");
+ layer.className = "card-image-layer";
+ layer.hidden = true;
+ layer.setAttribute("aria-hidden", "true");
+ const image = document.createElement("img");
+ image.alt = "";
+ image.decoding = "async";
+ layer.append(image);
+ body.prepend(layer);
+ const credit = document.createElement("a");
+ credit.className = "card-image-source hud-panel__action";
+ credit.hidden = true;
+ credit.target = "_blank";
+ credit.rel = "noopener noreferrer";
+ const icon = document.createElement("span");
+ icon.className = "material-symbols-rounded";
+ icon.textContent = "image";
+ icon.setAttribute("aria-hidden", "true");
+ credit.append(icon);
+ if (header) {
+ const anchor = header.querySelector("#info-card-workbench, .info-card-close");
+ if (anchor?.parentNode) anchor.parentNode.insertBefore(credit, anchor);
else header.appendChild(credit);
}
- const presenter=createCardImagePresenter({layer,image,credit,getWidth:()=>body.clientWidth*(window.devicePixelRatio||1)});
+ const presenter = createCardImagePresenter({
+ layer,
+ image,
+ credit,
+ getWidth: () => body.clientWidth * (window.devicePixelRatio || 1),
+ });
presenters.add(presenter);
return presenter;
}
-if (typeof window !== "undefined" && typeof window.addEventListener === "function") window.addEventListener("storage",event=>{
- if(event.key!==CARD_IMAGE_REVISION_KEY) return;
- cache.clear();presenters.forEach(presenter=>void presenter.refresh());
-});
+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
+ window.addEventListener("storage", (event) => {
+ if (event.key !== CARD_IMAGE_REVISION_KEY) return;
+ memoryResolveCache.clear();
+ globalRevisionState = { revision: "", checkedAt: 0, inflight: null };
+ presenters.forEach((presenter) => void presenter.refresh());
+ });
+}
diff --git a/frontend/public/earth/js/card-images.test.js b/frontend/public/earth/js/card-images.test.js
index 5d7cbea5..5a64650a 100644
--- a/frontend/public/earth/js/card-images.test.js
+++ b/frontend/public/earth/js/card-images.test.js
@@ -1,10 +1,12 @@
-import {expect,test} from "bun:test";
-import {cardImageIdentity,createCardImagePresenter} from "./card-images.js";
+import {beforeEach,expect,test} from "bun:test";
+import {_resetMemoryCacheForTests} from "./asset-swr-cache.js";
+import {_resetCardImagesRuntimeForTests,cardImageIdentity,createCardImagePresenter} from "./card-images.js";
const deferred=()=>{let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return {promise,resolve,reject};};
-function fixture(resolve,decode=async()=>{}) {
+beforeEach(()=>{_resetMemoryCacheForTests();_resetCardImagesRuntimeForTests();});
+function fixture(resolve,decode=async()=>{},extra={}) {
const node=()=>({hidden:true,style:{},classList:{add(){},remove(){}},removeAttribute(key){delete this[key];},setAttribute(key,value){this[key]=value;}});
const layer=node(),image=node(),credit=node(),errors=[];
- return {layer,image,credit,errors,presenter:createCardImagePresenter({layer,image,credit,resolve,decode,onError:e=>errors.push(e)})};
+ return {layer,image,credit,errors,presenter:createCardImagePresenter({layer,image,credit,resolve,decode,onError:e=>errors.push(e),...extra})};
}
test("stable identities never use collected database row IDs",()=>{
expect(cardImageIdentity("satellite",{id:1,norad_id:123})).toEqual({entity_type:"satellite",entity_id:"123"});
@@ -28,3 +30,46 @@ test("closing while decoding and broken files cannot reveal a stale layer",async
const broken=fixture(async()=>({url:"bad.jpg"}),async()=>{throw new Error("decode failed");});
await broken.presenter.show({id:"a"});expect(broken.layer.hidden).toBe(true);expect(broken.errors).toHaveLength(1);
});
+test("SWR presenter renders cached image at 0ms, skips binary fetch on 304, swaps on fingerprint change, and preserves stale image offline",async()=>{
+ let revision="rev-1",fingerprint="fp-1",imageUrl="/earth/assets/cards/previews/v1.webp",offline=false,imageFetches=0,resolveFetches=0;
+ const decodedUrls=[];
+ const fetchMock=async(url,init)=>{
+ if (offline) throw new Error("network down");
+ if (url.startsWith("/api/v1/earth/card-images/fingerprint")) {
+ return new Response(JSON.stringify({revision}),{status:200,headers:{ETag:`"${revision}"`}});
+ }
+ if (url.startsWith("/api/v1/earth/card-images/resolve")) {
+ resolveFetches+=1;
+ if (init?.headers?.["If-None-Match"]===`"${fingerprint}"`) return new Response(null,{status:304,headers:{ETag:`"${fingerprint}"`}});
+ return new Response(JSON.stringify({revision,fingerprint,suppressed:false,image:{id:"img",title:"T",url:imageUrl,variants:{"640":imageUrl}}}),{status:200,headers:{ETag:`"${fingerprint}"`}});
+ }
+ imageFetches+=1;
+ return new Response(new Blob([`bytes:${imageUrl}`],{type:"image/webp"}),{status:200});
+ };
+ const identity={entity_type:"satellite",entity_id:"123"};
+ const f=fixture(undefined,async(u)=>{decodedUrls.push(u);},{fetchImpl:fetchMock});
+ await f.presenter.show(identity);
+ expect(f.layer.hidden).toBe(false);expect(imageFetches).toBe(1);expect(resolveFetches).toBe(1);
+
+ // Warm revisit within global revision TTL: zero /resolve or image binary calls
+ await f.presenter.show(identity);
+ expect(f.layer.hidden).toBe(false);expect(imageFetches).toBe(1);expect(resolveFetches).toBe(1);
+
+ // Revision bumps with unchanged asset -> /resolve returns 304 -> zero image binary download
+ _resetCardImagesRuntimeForTests();
+ revision="rev-2";
+ await f.presenter.show(identity);
+ expect(resolveFetches).toBe(2);expect(imageFetches).toBe(1);
+
+ // Fingerprint changes -> smooth swap to new image
+ _resetCardImagesRuntimeForTests();
+ revision="rev-3";fingerprint="fp-2";imageUrl="/earth/assets/cards/previews/v2.webp";
+ await f.presenter.show(identity);
+ expect(resolveFetches).toBe(3);expect(imageFetches).toBe(2);expect(decodedUrls.length).toBeGreaterThanOrEqual(4);
+
+ // Offline preserves stale displayed image with zero error escalation
+ _resetCardImagesRuntimeForTests();
+ offline=true;
+ await f.presenter.show(identity);
+ expect(f.layer.hidden).toBe(false);expect(f.errors).toHaveLength(0);
+});
diff --git a/frontend/public/earth/js/cases-hud.js b/frontend/public/earth/js/cases-hud.js
new file mode 100644
index 00000000..c8ec95b9
--- /dev/null
+++ b/frontend/public/earth/js/cases-hud.js
@@ -0,0 +1,270 @@
+/**
+ * §4.3 Investigation Case Board HUD
+ * Manage investigation cases, attach globe/incident evidence, freeze SHA-256 versions,
+ * export Markdown bundles, and invoke Print-CSS PDF generation.
+ */
+
+import { getEarthLocale } from "./i18n.js";
+import { createHUDPanel } from "./hud-panels.js";
+import { sharedHudFocusStack } from "./hud-focus-stack.js";
+import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js";
+import { isEditableRole } from "./geofence-editor.js";
+
+const t = (zh, en) => (getEarthLocale() === "en-US" ? en : zh);
+
+function escapeHtml(text) {
+ return String(text ?? "")
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll('"', """);
+}
+
+async function fetchEarthJson(url) {
+ const { token } = readStoredAdminAuthState();
+ const headers = token ? { Authorization: `Bearer ${token}` } : {};
+ const resp = await fetch(url, { credentials: "same-origin", headers });
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ return resp.json();
+}
+
+export function initCasesHud({
+ rootParent = typeof document !== "undefined" ? document.body : null,
+ onFocusObject = null,
+ onStatus = null,
+} = {}) {
+ const panelEl = document.createElement("aside");
+ panelEl.id = "cases-board-hud";
+ panelEl.className = "hud-panel cases-hud-panel hud-panel-draggable";
+ panelEl.hidden = true;
+ panelEl.setAttribute("role", "dialog");
+ panelEl.setAttribute("aria-modal", "false");
+ panelEl.setAttribute("aria-label", t("调查卷宗工作台", "Investigation Cases"));
+
+ panelEl.innerHTML = `
+
+
+ folder_special
+
${escapeHtml(t("调查卷宗工作台", "Investigation Cases"))}
+
+
+
+
+
+
+
+
+
+
+
+ `;
+
+ rootParent?.append?.(panelEl);
+ const hudPanel = createHUDPanel({
+ panel: panelEl,
+ header: ".hud-panel__header",
+ body: "#cases-hud-body",
+ });
+ sharedHudFocusStack.register(panelEl, { focus: false });
+
+ const bodyEl = panelEl.querySelector("#cases-hud-body");
+ const createBar = panelEl.querySelector("#cases-create-bar");
+ const titleInput = panelEl.querySelector("#case-title-input");
+ const createBtn = panelEl.querySelector("#case-create-btn");
+
+ let casesList = [];
+ let activeDetail = null;
+
+ const render = () => {
+ const editable = isEditableRole(readStoredAdminAuthState()?.user?.role);
+ if (createBar) createBar.hidden = !editable;
+ if (!bodyEl) return;
+
+ const listHtml = casesList.length
+ ? casesList
+ .map(
+ (c) => `
+
+
+ ${escapeHtml(c.status || "draft")} · v${c.current_version || 1}
+ ${escapeHtml(c.owner_name || "admin")}
+
+ ${escapeHtml(c.title)}
+
+ `,
+ )
+ .join("")
+ : `${escapeHtml(t("暂无调查卷宗,请新建或从对象详情“加入卷宗”", "No cases yet"))}
`;
+
+ let detailHtml = "";
+ if (activeDetail?.case) {
+ const c = activeDetail.case;
+ const items = activeDetail.items || [];
+ const versions = activeDetail.versions || [];
+ const latestHash = versions[0]?.content_sha256 || versions[0]?.snapshot_hash || "";
+ detailHtml = `
+
+
+ ${escapeHtml(c.title)} (v${c.current_version || 1})
+ ${escapeHtml(c.status)}
+
+ ${latestHash ? `SHA-256: ${escapeHtml(latestHash.slice(0, 16))}…
` : ""}
+
+ ${
+ editable
+ ? ``
+ : ""
+ }
+
+
+
+ ${
+ items.length
+ ? items
+ .map(
+ (it) => `
+ ${escapeHtml(it.item_type)}
+
+
`,
+ )
+ .join("")
+ : `
${escapeHtml(t("尚无挂载证据对象", "No evidence items attached yet"))}
`
+ }
+
+ `;
+ }
+
+ bodyEl.innerHTML = detailHtml + listHtml;
+ };
+
+ const refresh = async () => {
+ const payload = await fetchEarthJson("/api/v1/cases?limit=50");
+ casesList = Array.isArray(payload?.items) ? payload.items : [];
+ if (activeDetail?.case?.id) {
+ activeDetail = await fetchEarthJson(`/api/v1/cases/${activeDetail.case.id}`).catch(() => activeDetail);
+ }
+ render();
+ return casesList;
+ };
+
+ const openCase = async (caseId) => {
+ activeDetail = await fetchEarthJson(`/api/v1/cases/${caseId}`);
+ render();
+ };
+
+ const attachObject = async ({ objectId, label = "", summary = "" }) => {
+ if (!objectId) return null;
+ if (!casesList.length) await refresh().catch(() => {});
+ let targetId = activeDetail?.case?.id || casesList[0]?.id;
+ if (!targetId) {
+ const resp = await fetchAdminWriteJson("/api/v1/cases", {
+ title: t("地球研判工作卷宗", "Earth Situational Case"),
+ summary: summary || "",
+ is_shared: true,
+ });
+ if (!resp.ok) throw new Error(await resp.text());
+ const created = await resp.json();
+ targetId = created.id;
+ }
+ const resp = await fetchAdminWriteJson(`/api/v1/cases/${targetId}/items`, {
+ item_type: "object",
+ ref_id: objectId,
+ payload: { label: label || objectId, summary },
+ });
+ if (!resp.ok) throw new Error(await resp.text());
+ await openCase(targetId);
+ panelEl.hidden = false;
+ sharedHudFocusStack.focus(panelEl);
+ onStatus?.(t("已加入调查卷宗", "Added to investigation case"), "success");
+ return resp.json();
+ };
+
+ panelEl.querySelector("#cases-close-btn")?.addEventListener("click", () => {
+ panelEl.hidden = true;
+ });
+ panelEl.querySelector("#cases-refresh-btn")?.addEventListener("click", () => {
+ void refresh().catch((err) => onStatus?.(err?.message || String(err), "error"));
+ });
+
+ createBtn?.addEventListener("click", async () => {
+ const title = String(titleInput?.value || "").trim();
+ if (!title) return;
+ try {
+ const resp = await fetchAdminWriteJson("/api/v1/cases", {
+ title,
+ summary: "",
+ is_shared: true,
+ });
+ if (!resp.ok) throw new Error(await resp.text());
+ const created = await resp.json();
+ if (titleInput) titleInput.value = "";
+ await refresh();
+ await openCase(created.id);
+ onStatus?.(t("调查卷宗已创建", "Case created"), "success");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ });
+
+ bodyEl?.addEventListener("click", async (event) => {
+ const el = event?.target instanceof HTMLElement ? event.target : null;
+ if (!el) return;
+ const openBtn = el.closest("[data-case-open]");
+ if (openBtn instanceof HTMLElement) {
+ await openCase(Number(openBtn.dataset.caseOpen)).catch((e) => onStatus?.(e.message, "error"));
+ return;
+ }
+ const freezeBtn = el.closest("[data-case-freeze]");
+ if (freezeBtn instanceof HTMLElement) {
+ try {
+ const cid = Number(freezeBtn.dataset.caseFreeze);
+ const resp = await fetchAdminWriteJson(`/api/v1/cases/${cid}/freeze`, {});
+ if (!resp.ok) throw new Error(await resp.text());
+ await refresh();
+ onStatus?.(t("卷宗版本已不可变固化", "Case snapshot frozen"), "success");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ return;
+ }
+ const printBtn = el.closest("[data-case-print]");
+ if (printBtn instanceof HTMLElement) {
+ panelEl.classList.add("print-active");
+ window.print?.();
+ setTimeout(() => panelEl.classList.remove("print-active"), 500);
+ return;
+ }
+ const focusBtn = el.closest("[data-focus-object]");
+ if (focusBtn instanceof HTMLElement) {
+ onFocusObject?.(focusBtn.dataset.focusObject || "");
+ }
+ });
+
+ const open = async () => {
+ panelEl.hidden = false;
+ sharedHudFocusStack.focus(panelEl);
+ await refresh().catch((err) => onStatus?.(err?.message || String(err), "error"));
+ };
+
+ return {
+ open,
+ close: () => {
+ panelEl.hidden = true;
+ },
+ refresh,
+ openCase,
+ attachObject,
+ getCases: () => casesList,
+ destroy: () => {
+ hudPanel?.destroy?.();
+ panelEl.remove();
+ },
+ };
+}
diff --git a/frontend/public/earth/js/cloud-map.js b/frontend/public/earth/js/cloud-map.js
index 4fb22685..0cdd7aaf 100644
--- a/frontend/public/earth/js/cloud-map.js
+++ b/frontend/public/earth/js/cloud-map.js
@@ -4,8 +4,11 @@ import * as THREE from "three";
import { CLOUD_LAYER_CONFIG } from "./constants.js";
import { configureColorTexture } from "./texture-colors.js";
import { earthTextureImages } from "./earth-texture-image.js";
+import { getCachedAssetMeta, putCachedAssetJson, readCachedAssetJson } from "./asset-swr-cache.js";
const CLOUD_META_ENDPOINT = "/api/v1/earth/clouds/meta";
+const CLOUD_CACHE_BUCKET = "clouds";
+const CLOUD_META_CACHE_KEY = "latest-meta";
const CLOUD_BROADCAST_CHANNEL = "planet-earth-cloud-map";
const META_TIMEOUT_MS = 3500;
const CROSSFADE_DURATION_MS = 1800;
@@ -438,6 +441,40 @@ export async function refreshLiveCloudMap({ forceReload = false } = {}) {
let nextFlowMaxUv = 0;
const isFirstLoad = !(_getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value);
+ // Boot-time SWR: if realtime first load has a cached previous cloud frame + meta,
+ // render the cached frame immediately (0ms) before waiting on online /clouds/meta.
+ if (isFirstLoad && _mode === "realtime") {
+ try {
+ const cachedMeta = await readCachedAssetJson(CLOUD_CACHE_BUCKET, CLOUD_META_CACHE_KEY);
+ if (cachedMeta?.enabled && cachedMeta?.mode === "realtime" && cachedMeta?.image_url) {
+ const [cachedTex, cachedVis] = await Promise.all([
+ decodeCloudTexture(cachedMeta.image_url).catch(() => null),
+ cachedMeta.geocolor_enabled !== false && cachedMeta.visual_url
+ ? decodeAuxTexture(cachedMeta.visual_url, { srgb: false }).catch(() => null)
+ : Promise.resolve(null),
+ ]);
+ if (cachedTex) {
+ _lastMeta = cachedMeta;
+ _activeVersion = cachedMeta.version || cachedMeta.image_url;
+ _activeImageUrl = cachedMeta.image_url;
+ _visualUrl = cachedMeta.visual_url || null;
+ _flowUrl = cachedMeta.flow_url || null;
+ transitionCloudTexture(cachedTex, {
+ crossFadeMs: 0,
+ visualTexture: cachedVis,
+ flowTexture: null,
+ flowMaxUv: 0,
+ });
+ emitCloudMapStatus();
+ }
+ }
+ } catch {
+ // Ignore corrupt local cloud cache and fall through to online fetch.
+ }
+ }
+
+ const hadRenderedFrame = Boolean(_getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value);
+
if (_mode === "realtime") {
const meta = await fetchCloudMetaSafe();
if (meta) {
@@ -455,13 +492,21 @@ export async function refreshLiveCloudMap({ forceReload = false } = {}) {
nextVisualUrl = meta.geocolor_enabled !== false ? meta.visual_url || null : null;
nextFlowUrl = meta.optical_flow_enabled !== false ? meta.flow_url || null : null;
nextFlowMaxUv = Number(meta.flow_max_uv || 0);
+ void putCachedAssetJson(CLOUD_CACHE_BUCKET, CLOUD_META_CACHE_KEY, meta, {
+ url: CLOUD_META_ENDPOINT,
+ fingerprint: nextVersion,
+ });
}
+ } else if (hadRenderedFrame) {
+ syncTimelapseLoop();
+ emitCloudMapStatus();
+ return _getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value || null;
}
}
if (
!forceReload
- && !isFirstLoad
+ && hadRenderedFrame
&& nextVersion === _activeVersion
&& targetUrl === _activeImageUrl
&& nextVisualUrl === _visualUrl
diff --git a/frontend/public/earth/js/compute-centers.js b/frontend/public/earth/js/compute-centers.js
index 724ca049..67f54651 100644
--- a/frontend/public/earth/js/compute-centers.js
+++ b/frontend/public/earth/js/compute-centers.js
@@ -11,6 +11,7 @@ import {
import { latLonToVector3 } from "./utils.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
import { fetchAdminWriteJson } from "./admin-write-auth.js";
+import { fetchJsonSwr } from "./asset-swr-cache.js";
const COMPUTE_CENTER_RENDER_ORDER = 4.5;
const COMPUTE_CENTER_POINT_SIZE = 36;
@@ -577,30 +578,7 @@ export function getShowComputeCenters() {
return showComputeCenters;
}
-export async function loadComputeCenters(_scene, earth) {
- const generation = ++loadGeneration;
- loadController?.abort();
- loadController = new AbortController();
- const query = new URLSearchParams(computeTopicQuery || {});
- if (!query.get("year")) query.delete("year");
- const url = computeTopicQuery ? `/api/v1/data-products/compute/facilities?${query}` : PATHS.computeCentersApi;
- const separator = url.includes("?") ? "&" : "?";
- let response;
- try {
- response = await fetch(
- `${url}${separator}_=${Date.now()}`,
- { cache: "no-store", signal: loadController.signal },
- );
- } catch (error) {
- if (error?.name === "AbortError") {
- return { count: 0, stale: true, aborted: true };
- }
- throw error;
- }
- if (!response.ok) {
- throw new Error(`Compute centers HTTP ${response.status}`);
- }
- const payload = await response.json();
+async function applyComputeCentersPayload(earth, payload, generation, hasTopicQuery) {
const features = Array.isArray(payload?.features) ? payload.features : [];
const unresolved = Array.isArray(payload?.unresolved) ? payload.unresolved : [];
@@ -624,9 +602,9 @@ export async function loadComputeCenters(_scene, earth) {
computeCenterIconLayer.attach(earth);
computeCenterIconLayer.setVisible(showComputeCenters);
- if (computeTopicQuery) window.dispatchEvent(new CustomEvent("earth:compute-topic-data", { detail: payload }));
+ if (hasTopicQuery) window.dispatchEvent(new CustomEvent("earth:compute-topic-data", { detail: payload }));
return {
- topicPayload: computeTopicQuery ? payload : null,
+ topicPayload: hasTopicQuery ? payload : null,
totalCount: getComputeCenterCount(),
supercomputerCount: typeCounts.supercomputer,
gpuClusterCount: typeCounts.gpu_cluster,
@@ -637,6 +615,48 @@ export async function loadComputeCenters(_scene, earth) {
};
}
+export async function loadComputeCenters(_scene, earth) {
+ const generation = ++loadGeneration;
+ loadController?.abort();
+ loadController = new AbortController();
+ const hasTopicQuery = Boolean(computeTopicQuery);
+ if (!hasTopicQuery) {
+ const { data } = await fetchJsonSwr({
+ bucket: "geo",
+ key: "compute-centers",
+ url: PATHS.computeCentersApi,
+ onFresh: (fresh) => {
+ if (generation === loadGeneration) {
+ void applyComputeCentersPayload(earth, fresh, generation, false).catch(() => {});
+ }
+ },
+ });
+ return applyComputeCentersPayload(earth, data, generation, false);
+ }
+
+ const query = new URLSearchParams(computeTopicQuery || {});
+ if (!query.get("year")) query.delete("year");
+ const url = `/api/v1/data-products/compute/facilities?${query}`;
+ const separator = url.includes("?") ? "&" : "?";
+ let response;
+ try {
+ response = await fetch(
+ `${url}${separator}_=${Date.now()}`,
+ { cache: "no-store", signal: loadController.signal },
+ );
+ } catch (error) {
+ if (error?.name === "AbortError") {
+ return { count: 0, stale: true, aborted: true };
+ }
+ throw error;
+ }
+ if (!response.ok) {
+ throw new Error(`Compute centers HTTP ${response.status}`);
+ }
+ const payload = await response.json();
+ return applyComputeCentersPayload(earth, payload, generation, true);
+}
+
const NATIONAL_HUB_COLORS = {
eastern_demand: "#a855f7",
western_green: "#14b8a6",
diff --git a/frontend/public/earth/js/compute-topic.js b/frontend/public/earth/js/compute-topic.js
index 58dadb6e..a6b24d2f 100644
--- a/frontend/public/earth/js/compute-topic.js
+++ b/frontend/public/earth/js/compute-topic.js
@@ -1890,6 +1890,16 @@ export function initComputeTopic({
load({ refreshMap: false });
}
},
+ setReplayAsOfRevision(asOfRev, cursorIso) {
+ const nextPublishId = asOfRev?.publish_id || "";
+ const nextAsOf = nextPublishId ? "" : (cursorIso || "");
+ if (selectedPublishId === nextPublishId && asOf === nextAsOf) return;
+ selectedPublishId = nextPublishId;
+ asOf = nextAsOf;
+ if (cardsEnabled || configVisible) {
+ load({ refreshMap: false });
+ }
+ },
getState() {
return {
cardsEnabled,
diff --git a/frontend/public/earth/js/constants.js b/frontend/public/earth/js/constants.js
index 28a5e52b..5255f80e 100644
--- a/frontend/public/earth/js/constants.js
+++ b/frontend/public/earth/js/constants.js
@@ -26,6 +26,9 @@ export const CRUISE_MODULES = {
NEWS: "news",
COMPUTE_CENTERS: "computeCenters",
VESSELS: "vessels",
+ AIRCRAFT: "aircraft",
+ GPS_JAMMING: "gpsJamming",
+ DISASTERS: "disasters",
CABLES: "cables",
SATELLITES: "satellites",
};
@@ -228,11 +231,18 @@ export const COUNTRY_BOUNDARY_CONFIG = {
tilePrefetchRing: 1,
tileDebounceMs: 180,
tileCacheLimit: 640,
- // Admin-1 (province / state) lines fade in below the national borders.
- admin1MinViewZoom: 2.0,
- admin1FullViewZoom: 2.8,
- admin1LineColor: 0x9fd0ff,
- admin1LineOpacity: 0.26,
+ // Admin-1 (province / state) lines fade in smoothly as a subtle slate-white dashed
+ // ribbon with dark casing so borders remain legible on bright/dark imagery without
+ // overpowering national borders.
+ admin1MinViewZoom: 1.85,
+ admin1FullViewZoom: 2.6,
+ admin1LineColor: 0xd8e8f8,
+ admin1LineOpacity: 0.46,
+ admin1CasingColor: 0x050a14,
+ admin1CasingOpacity: 0.36,
+ admin1DashPx: 6.0,
+ admin1GapPx: 4.0,
+ admin1HalfWidthPx: 1.65,
// Keep boundary/coastline strokes on the same shell as the high-res earth
// texture overlay. A lower or higher radius creates visible parallax while
// the globe rotates.
@@ -285,6 +295,11 @@ export const PATHS = {
interactablesApi: '/api/v1/interactables/geojson',
vesselsApi: '/api/v1/vessels/snapshot',
vesselTrackApi: (mmsi) => `/api/v1/visualization/vessels/${encodeURIComponent(mmsi)}/track`,
+ aircraftSnapshotApi: '/api/v1/aircraft/snapshot',
+ aircraftDetailApi: (icao24) => `/api/v1/aircraft/${encodeURIComponent(icao24)}`,
+ aircraftTrackApi: (icao24, hours = 3) => `/api/v1/aircraft/${encodeURIComponent(icao24)}/track?hours=${hours}`,
+ gpsJammingSnapshotApi: '/api/v1/gps-jamming/snapshot',
+ disastersSnapshotApi: '/api/v1/disasters/snapshot',
bgpApi: '/api/v1/visualization/geo/bgp-anomalies',
bgpIncidentsApi: '/api/v1/visualization/geo/bgp-incidents',
bgpCollectorsApi: '/api/v1/visualization/geo/bgp-collectors',
diff --git a/frontend/public/earth/js/controls.js b/frontend/public/earth/js/controls.js
index 8859391d..1cd4bc89 100644
--- a/frontend/public/earth/js/controls.js
+++ b/frontend/public/earth/js/controls.js
@@ -8,6 +8,7 @@ import { bindToolbarHover } from "./toolbar-hover.js";
import { distanceForGlobeZoom, globeZoomForDistance, isGlobeWheelTarget } from "./globe-navigation.js";
import { EARTH_SETTINGS_STORAGE_KEY } from "./earth-settings-storage.js";
import { getCalloutLimits, setCalloutLimits } from "./callout-limits.js";
+import { clearLocalAssetCache, formatBytes, getLocalCacheStats } from "./asset-swr-cache.js";
// controls.js - Zoom, rotate and toggle controls
import * as THREE from "three";
@@ -80,6 +81,16 @@ import {
getSatellitesEnabled,
setVesselsEnabled,
getVesselsEnabled,
+ setAircraftEnabled,
+ getAircraftEnabled,
+ setGpsJammingEnabled,
+ getGpsJammingEnabled,
+ setDisastersEnabled,
+ getDisastersEnabled,
+ setGeofencesEnabled,
+ getGeofencesEnabled,
+ setFusionOverlaysEnabled,
+ getFusionOverlaysEnabled,
} from "./main.js";
import {
toggleTrails,
@@ -113,6 +124,7 @@ import {
getShowVessels,
getVesselCount,
} from "./vessels.js";
+import { getAircraftCount } from "./aircraft.js";
import {
ensureTVPanelReady,
getActiveTVTab,
@@ -3881,6 +3893,123 @@ async function setVesselsLayerEnabled(button, enabled, { persist = true, silent
}
}
+async function setAircraftLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
+ clearSelectionIfHiding(!enabled);
+ try {
+ if (enabled) {
+ setLayerButtonState(button, { active: false, loading: true, tooltip: "航空器加载中..." });
+ }
+ await setAircraftEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent });
+ setLayerButtonState(button, {
+ active: enabled,
+ loading: false,
+ tooltip: enabled ? "隐藏航空器" : "显示航空器",
+ });
+ setEarthStatValue("aircraft-count", `${getAircraftCount()} 架`);
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return enabled;
+ } catch (error) {
+ console.error("切换航空器显示失败:", error);
+ setLayerButtonState(button, { active: false, loading: false, tooltip: "显示航空器" });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return false;
+ }
+}
+
+async function setGpsJammingLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
+ try {
+ if (enabled) {
+ setLayerButtonState(button, { active: false, loading: true, tooltip: "GPS 干扰加载中..." });
+ }
+ await setGpsJammingEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent });
+ setLayerButtonState(button, {
+ active: enabled,
+ loading: false,
+ tooltip: enabled ? "隐藏 GPS 干扰" : "显示 GPS 干扰",
+ });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return enabled;
+ } catch (error) {
+ console.error("切换 GPS 干扰显示失败:", error);
+ setLayerButtonState(button, { active: false, loading: false, tooltip: "显示 GPS 干扰" });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return false;
+ }
+}
+
+async function setDisastersLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
+ try {
+ if (enabled) {
+ setLayerButtonState(button, { active: false, loading: true, tooltip: "自然灾害加载中..." });
+ }
+ await setDisastersEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent });
+ setLayerButtonState(button, {
+ active: enabled,
+ loading: false,
+ tooltip: enabled ? "隐藏自然灾害" : "显示自然灾害",
+ });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return enabled;
+ } catch (error) {
+ console.error("切换自然灾害显示失败:", error);
+ setLayerButtonState(button, { active: false, loading: false, tooltip: "显示自然灾害" });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return false;
+ }
+}
+
+async function setGeofencesLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
+ try {
+ if (enabled) {
+ setLayerButtonState(button, { active: false, loading: true, tooltip: "电子围栏加载中..." });
+ }
+ await setGeofencesEnabled(enabled, { suppressStatus: silent });
+ setLayerButtonState(button, {
+ active: enabled,
+ loading: false,
+ tooltip: enabled ? "隐藏电子围栏" : "显示电子围栏",
+ });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return enabled;
+ } catch (error) {
+ console.error("切换电子围栏显示失败:", error);
+ setLayerButtonState(button, { active: false, loading: false, tooltip: "显示电子围栏" });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return false;
+ }
+}
+
+async function setFusionOverlaysLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
+ try {
+ if (enabled) {
+ setLayerButtonState(button, { active: false, loading: true, tooltip: "关联与影响链加载中..." });
+ }
+ await setFusionOverlaysEnabled(enabled, { suppressStatus: silent });
+ setLayerButtonState(button, {
+ active: enabled,
+ loading: false,
+ tooltip: enabled ? "隐藏关联与影响链" : "显示关联与影响链",
+ });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return enabled;
+ } catch (error) {
+ console.error("切换关联与影响链失败:", error);
+ setLayerButtonState(button, { active: false, loading: false, tooltip: "显示关联与影响链" });
+ syncMobileLayerCards();
+ if (persist) persistEarthSettings();
+ return false;
+ }
+}
+
function syncTrailsDisplayControls() {
const trailsEnabled = getShowTrails();
const disabledState = getLayerDisabledState("trails");
@@ -4153,6 +4282,94 @@ function getBuiltinLayerDefinitions() {
setVisible: (visible, options = {}) =>
setVesselsLayerEnabled(getLayerButton("vessels"), visible, options),
},
+ {
+ id: "aircraft",
+ productId: "aircraft",
+ buttonId: "toggle-aircraft",
+ icon: "flight",
+ label: "航空器",
+ meta: "军机与民航 ADS-B",
+ keywords: "航空器 飞机 ads-b aircraft flights military",
+ defaultActive: false,
+ displayOrder: 46,
+ startupPriority: 66,
+ startupMode: "visible",
+ startupLabel: "航空器",
+ startupMessage: earthMessage("startup.aircraft"),
+ getVisible: () => getAircraftEnabled(),
+ setVisible: (visible, options = {}) =>
+ setAircraftLayerEnabled(getLayerButton("aircraft"), visible, options),
+ },
+ {
+ id: "gpsJamming",
+ productId: "gps_jamming",
+ buttonId: "toggle-gps-jamming",
+ icon: "radar",
+ label: "GPS 干扰",
+ meta: "GNSS 干扰监测热区",
+ keywords: "gps干扰 gnss jamming interference",
+ defaultActive: false,
+ displayOrder: 47,
+ startupPriority: 67,
+ startupMode: "visible",
+ startupLabel: "GPS 干扰",
+ startupMessage: earthMessage("startup.gpsJamming"),
+ getVisible: () => getGpsJammingEnabled(),
+ setVisible: (visible, options = {}) =>
+ setGpsJammingLayerEnabled(getLayerButton("gps-jamming"), visible, options),
+ },
+ {
+ id: "disasters",
+ productId: "disasters",
+ buttonId: "toggle-disasters",
+ icon: "warning",
+ label: "自然灾害",
+ meta: "地震、林火热点与灾难预警",
+ keywords: "自然灾害 地震 林火 气旋 disasters earthquakes wildfires",
+ defaultActive: false,
+ displayOrder: 48,
+ startupPriority: 68,
+ startupMode: "visible",
+ startupLabel: "自然灾害",
+ startupMessage: earthMessage("startup.disasters"),
+ getVisible: () => getDisastersEnabled(),
+ setVisible: (visible, options = {}) =>
+ setDisastersLayerEnabled(getLayerButton("disasters"), visible, options),
+ },
+ {
+ id: "geofences",
+ buttonId: "toggle-geofences",
+ icon: "pentagon",
+ label: "电子围栏",
+ meta: "海缆走廊与咽喉监测区",
+ keywords: "电子围栏 geofences corridors",
+ defaultActive: false,
+ displayOrder: 49,
+ startupPriority: 69,
+ startupMode: "visible",
+ startupLabel: "电子围栏",
+ startupMessage: earthMessage("startup.geofences"),
+ getVisible: () => getGeofencesEnabled(),
+ setVisible: (visible, options = {}) =>
+ setGeofencesLayerEnabled(getLayerButton("geofences"), visible, options),
+ },
+ {
+ id: "fusionOverlays",
+ buttonId: "toggle-fusion-overlays",
+ icon: "share",
+ label: "关联与影响链",
+ meta: "H3 待核查关联与海缆影响链",
+ keywords: "多域关联 影响链 fusion correlation dependency",
+ defaultActive: false,
+ displayOrder: 50,
+ startupPriority: 70,
+ startupMode: "visible",
+ startupLabel: "关联与影响链",
+ startupMessage: earthMessage("startup.fusionOverlays"),
+ getVisible: () => getFusionOverlaysEnabled(),
+ setVisible: (visible, options = {}) =>
+ setFusionOverlaysLayerEnabled(getLayerButton("fusion-overlays"), visible, options),
+ },
{
id: "satellites",
productId: "satellites",
@@ -4382,6 +4599,9 @@ export function setZoomLevel(nextZoom, camera = activeCamera) {
}
camera.updateMatrixWorld();
updateZoomDisplay(zoomLevel, camera.position.z.toFixed(0));
+ if (typeof window !== "undefined" && typeof CustomEvent === "function") {
+ window.dispatchEvent(new CustomEvent("earth:zoom-level-change", { detail: { zoomLevel } }));
+ }
}
return zoomLevel;
}
@@ -4545,6 +4765,7 @@ function openSettingsModal() {
modal.classList.add("is-opening");
modal.classList.add("is-open");
modal.setAttribute("aria-hidden", "false");
+ void refreshLocalAssetCacheUi();
requestAnimationFrame(() => {
if (sheet instanceof HTMLElement) {
@@ -4977,6 +5198,49 @@ async function setupBoundaryPrecisionControls() {
});
}
+async function refreshLocalAssetCacheUi() {
+ const els = document.querySelectorAll("[data-asset-cache-summary]");
+ if (!els.length) return;
+ try {
+ const stats = await getLocalCacheStats();
+ const text = stats.totalCount > 0
+ ? `当前占用:${formatBytes(stats.totalBytes)}(${stats.totalCount} 项)`
+ : "当前占用:0 B";
+ els.forEach((el) => {
+ if (el instanceof HTMLElement) {
+ el.textContent = text;
+ }
+ });
+ } catch {
+ els.forEach((el) => {
+ if (el instanceof HTMLElement) {
+ el.textContent = "当前占用:0 B";
+ }
+ });
+ }
+}
+
+function setupLocalAssetCacheControls() {
+ const buttons = document.querySelectorAll("[data-clear-asset-cache]");
+ buttons.forEach((btn) => {
+ if (!(btn instanceof HTMLButtonElement)) return;
+ bindListener(btn, "click", async () => {
+ const original = btn.textContent || "清理缓存";
+ btn.disabled = true;
+ btn.textContent = "正在清理…";
+ try {
+ await clearLocalAssetCache();
+ await refreshLocalAssetCacheUi();
+ showStatusMessage(earthMessage("status.cacheCleared"), "success");
+ } finally {
+ btn.disabled = false;
+ btn.textContent = original;
+ }
+ });
+ });
+ void refreshLocalAssetCacheUi();
+}
+
function setSettingsTab(root, tabId) {
if (!(root instanceof HTMLElement)) return;
const nextTab = tabId || "runtime";
@@ -4990,6 +5254,9 @@ function setSettingsTab(root, tabId) {
if (!(panel instanceof HTMLElement)) return;
panel.hidden = panel.dataset.settingsTabPanel !== nextTab;
});
+ if (nextTab === "system") {
+ void refreshLocalAssetCacheUi();
+ }
window.requestAnimationFrame(() => {
syncSegmentedControlSliders();
});
@@ -5861,6 +6128,7 @@ function setupSettingsControls() {
syncMotionDebugSkeletonOnlyToggle(motionDebugSkeletonOnly);
syncMotionGestureControls();
void setupBoundaryPrecisionControls();
+ setupLocalAssetCacheControls();
}
function syncDisplayDetailControls() {
@@ -6203,6 +6471,10 @@ function setupZoomControls(camera) {
const MAX_PERCENT = CONFIG.maxZoom * 100;
function doZoomStep(direction) {
+ if (window.__planetEarth?.is2dActive?.()) {
+ window.__planetEarth.zoom2dBy?.(direction > 0 ? 0.65 : -0.65);
+ return;
+ }
let currentPercent = Math.round(getZoomLevelFromCamera(camera) * 100);
let newPercent =
direction > 0 ? currentPercent + CLICK_STEP : currentPercent - CLICK_STEP;
@@ -6215,6 +6487,10 @@ function setupZoomControls(camera) {
}
function doContinuousZoom(direction) {
+ if (window.__planetEarth?.is2dActive?.()) {
+ window.__planetEarth.zoom2dBy?.(direction > 0 ? 0.15 : -0.15);
+ return;
+ }
let currentPercent = Math.round(getZoomLevelFromCamera(camera) * 100);
let newPercent = direction > 0 ? currentPercent + 1 : currentPercent - 1;
@@ -6284,6 +6560,10 @@ function setupZoomControls(camera) {
bindListener(zoomOut, "touchend", () => handleMouseUp(-1));
bindListener(zoomValue, "click", () => {
+ if (window.__planetEarth?.is2dActive?.()) {
+ window.__planetEarth.reset2dView?.();
+ return;
+ }
const startZoomVal = getZoomLevelFromCamera(camera);
const targetZoom = getDefaultEarthZoomLevel();
@@ -6545,6 +6825,10 @@ function setupRotateControls(camera) {
updateRotateUI();
bindListener(resetViewBtn, "click", () => {
+ if (window.__planetEarth?.is2dActive?.()) {
+ window.__planetEarth.reset2dView?.();
+ return;
+ }
resetView(camera);
});
}
diff --git a/frontend/public/earth/js/country-boundaries.js b/frontend/public/earth/js/country-boundaries.js
index 002ef111..ff6e57a4 100644
--- a/frontend/public/earth/js/country-boundaries.js
+++ b/frontend/public/earth/js/country-boundaries.js
@@ -7,7 +7,11 @@ import Pbf from "pbf";
import { CONFIG, COUNTRY_BOUNDARY_CONFIG, EARTH_MATERIAL_CONFIG } from "./constants.js";
import { screenToEarthCoords, vector3ToLatLon } from "./utils.js";
import { appendSurfaceSegments, createEarthSurfaceGeometry } from "./earth-surface.js";
-import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
+import {
+ createDashedRibbonMaterial,
+ createSurfaceRibbonGeometry,
+ createSurfaceRibbonMaterial,
+} from "./surface-ribbon.js";
import { setEarthLandMask } from "./earth.js";
import { configureColorTexture } from "./texture-colors.js";
import {
@@ -552,12 +556,33 @@ function buildClaimLines() {
return lines;
}
+function effectiveAdmin1Opacity() {
+ return _admin1Opacity <= 0.001 ? 0 : _admin1Opacity;
+}
+
+function syncAdmin1RibbonState() {
+ const effective = effectiveAdmin1Opacity();
+ if (_admin1Material) {
+ _admin1Material.uniforms.uOpacity.value = effective;
+ _admin1Material.visible = effective > 0.001;
+ }
+ if (_batchedAdmin1Lines) {
+ const count = _batchedAdmin1Lines.geometry?.drawRange?.count || 0;
+ _batchedAdmin1Lines.visible = boundaryLegendVisible() && effective > 0.001 && count > 0;
+ }
+}
+
function getAdmin1Material() {
if (_admin1Material) return _admin1Material;
- _admin1Material = new THREE.LineBasicMaterial({
- color: COUNTRY_BOUNDARY_CONFIG.admin1LineColor,
- transparent: true,
- opacity: _admin1Opacity,
+ _admin1Material = createDashedRibbonMaterial({
+ coreColor: COUNTRY_BOUNDARY_CONFIG.admin1LineColor,
+ casingColor: COUNTRY_BOUNDARY_CONFIG.admin1CasingColor,
+ opacity: effectiveAdmin1Opacity(),
+ maxOpacity: COUNTRY_BOUNDARY_CONFIG.admin1LineOpacity,
+ casingOpacity: COUNTRY_BOUNDARY_CONFIG.admin1CasingOpacity,
+ halfWidthPx: COUNTRY_BOUNDARY_CONFIG.admin1HalfWidthPx,
+ dashPx: COUNTRY_BOUNDARY_CONFIG.admin1DashPx,
+ gapPx: COUNTRY_BOUNDARY_CONFIG.admin1GapPx,
depthTest: true,
depthWrite: false,
});
@@ -605,14 +630,7 @@ function updateAdmin1Opacity(viewZoom) {
const next = admin1OpacityForViewZoom(viewZoom);
if (Math.abs(next - _admin1Opacity) < 0.001) return;
_admin1Opacity = next;
- if (_admin1Material) {
- _admin1Material.opacity = next;
- _admin1Material.visible = next > 0.001;
- }
- if (_batchedAdmin1Lines) {
- const count = _batchedAdmin1Lines.geometry?.drawRange?.count || 0;
- _batchedAdmin1Lines.visible = boundaryLegendVisible() && next > 0.001 && count > 0;
- }
+ syncAdmin1RibbonState();
}
function createBatchedLineObject(name, material, renderOrder) {
@@ -628,13 +646,26 @@ function createBatchedLineObject(name, material, renderOrder) {
return lines;
}
+function createBatchedRibbonMesh(name, material, renderOrder) {
+ const geo = new THREE.BufferGeometry();
+ geo.setDrawRange(0, 0);
+ geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), CONFIG.earthRadius + 6);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.name = name;
+ mesh.renderOrder = renderOrder;
+ mesh.visible = false;
+ mesh.frustumCulled = false;
+ mesh.raycast = () => {};
+ return mesh;
+}
+
function buildBatchedLineObjects() {
_batchedBoundaryLines = createBatchedLineObject(
"country-boundary-batch",
getBoundaryTileMaterial(),
COUNTRY_BOUNDARY_CONFIG.lineRenderOrder + 0.01,
);
- _batchedAdmin1Lines = createBatchedLineObject(
+ _batchedAdmin1Lines = createBatchedRibbonMesh(
"country-admin1-batch",
getAdmin1Material(),
COUNTRY_BOUNDARY_CONFIG.lineRenderOrder,
@@ -732,6 +763,156 @@ function uploadIndexedBatch(lineObj, buckets) {
return { vertexCount: Math.floor(totalFloats / 3), indexCount: totalIndices, drawCalls: 1 };
}
+function uploadAdmin1RibbonBatch(mesh, buckets) {
+ if (!mesh) return { vertexCount: 0, indexCount: 0, drawCalls: 0 };
+ let totalSegments = 0;
+ for (let i = 0; i < buckets.length; i += 1) {
+ const bucket = buckets[i];
+ if (!bucket?.positions?.length || !bucket?.indices?.length) continue;
+ totalSegments += bucket.indices.length >> 1;
+ }
+ const geometry = mesh.geometry;
+ if (totalSegments === 0) {
+ geometry.setDrawRange(0, 0);
+ mesh.visible = false;
+ return { vertexCount: 0, indexCount: 0, drawCalls: 0 };
+ }
+
+ const neededVerts = totalSegments * 4;
+ const neededFloats = neededVerts * 3;
+ const neededIndices = totalSegments * 6;
+
+ let posArr = mesh.userData._batchPos;
+ let otherArr = mesh.userData._batchOther;
+ let paramArr = mesh.userData._batchParams;
+ let idxArr = mesh.userData._batchIdx;
+ let vertGrew = false;
+ let idxGrew = false;
+
+ if (!posArr || !otherArr || !paramArr || posArr.length < neededFloats) {
+ let capVerts = Math.max(4096, neededVerts);
+ if (posArr) {
+ capVerts = Math.floor(posArr.length / 3);
+ while (capVerts < neededVerts) capVerts *= 2;
+ }
+ posArr = new Float32Array(capVerts * 3);
+ otherArr = new Float32Array(capVerts * 3);
+ paramArr = new Float32Array(capVerts * 3);
+ mesh.userData._batchPos = posArr;
+ mesh.userData._batchOther = otherArr;
+ mesh.userData._batchParams = paramArr;
+ vertGrew = true;
+ }
+
+ if (!idxArr || idxArr.length < neededIndices) {
+ let capIdx = Math.max(8192, neededIndices);
+ if (idxArr) {
+ capIdx = idxArr.length;
+ while (capIdx < neededIndices) capIdx *= 2;
+ }
+ idxArr = new Uint32Array(capIdx);
+ mesh.userData._batchIdx = idxArr;
+ idxGrew = true;
+ }
+
+ let vertCursor = 0;
+ let idxCursor = 0;
+ for (let i = 0; i < buckets.length; i += 1) {
+ const bucket = buckets[i];
+ const srcPos = bucket?.positions;
+ const srcIdx = bucket?.indices;
+ if (!srcPos?.length || !srcIdx?.length) continue;
+
+ let cumLen = 0;
+ let prevRawB = -1;
+ for (let k = 0; k + 1 < srcIdx.length; k += 2) {
+ const rawA = srcIdx[k];
+ const rawB = srcIdx[k + 1];
+ const pa = rawA * 3;
+ const pb = rawB * 3;
+ if (pa + 2 >= srcPos.length || pb + 2 >= srcPos.length) continue;
+
+ if (rawA !== prevRawB) {
+ cumLen = 0;
+ }
+ const ax = srcPos[pa];
+ const ay = srcPos[pa + 1];
+ const az = srcPos[pa + 2];
+ const bx = srcPos[pb];
+ const by = srcPos[pb + 1];
+ const bz = srcPos[pb + 2];
+ const segLen = Math.hypot(bx - ax, by - ay, bz - az);
+ const distA = cumLen;
+ const distB = cumLen + segLen;
+ cumLen = distB;
+ prevRawB = rawB;
+
+ const baseV = vertCursor;
+ const f0 = baseV * 3;
+ // v0: start, -1
+ posArr[f0] = ax; posArr[f0 + 1] = ay; posArr[f0 + 2] = az;
+ otherArr[f0] = bx; otherArr[f0 + 1] = by; otherArr[f0 + 2] = bz;
+ paramArr[f0] = 0; paramArr[f0 + 1] = -1; paramArr[f0 + 2] = distA;
+ // v1: start, +1
+ posArr[f0 + 3] = ax; posArr[f0 + 4] = ay; posArr[f0 + 5] = az;
+ otherArr[f0 + 3] = bx; otherArr[f0 + 4] = by; otherArr[f0 + 5] = bz;
+ paramArr[f0 + 3] = 0; paramArr[f0 + 4] = 1; paramArr[f0 + 5] = distA;
+ // v2: end, -1
+ posArr[f0 + 6] = bx; posArr[f0 + 7] = by; posArr[f0 + 8] = bz;
+ otherArr[f0 + 6] = ax; otherArr[f0 + 7] = ay; otherArr[f0 + 8] = az;
+ paramArr[f0 + 6] = 1; paramArr[f0 + 7] = -1; paramArr[f0 + 8] = distB;
+ // v3: end, +1
+ posArr[f0 + 9] = bx; posArr[f0 + 10] = by; posArr[f0 + 11] = bz;
+ otherArr[f0 + 9] = ax; otherArr[f0 + 10] = ay; otherArr[f0 + 11] = az;
+ paramArr[f0 + 9] = 1; paramArr[f0 + 10] = 1; paramArr[f0 + 11] = distB;
+ vertCursor += 4;
+
+ idxArr[idxCursor++] = baseV;
+ idxArr[idxCursor++] = baseV + 1;
+ idxArr[idxCursor++] = baseV + 2;
+ idxArr[idxCursor++] = baseV + 1;
+ idxArr[idxCursor++] = baseV + 3;
+ idxArr[idxCursor++] = baseV + 2;
+ }
+ }
+
+ if (idxCursor === 0) {
+ geometry.setDrawRange(0, 0);
+ mesh.visible = false;
+ return { vertexCount: 0, indexCount: 0, drawCalls: 0 };
+ }
+
+ for (const [attrName, arr] of [
+ ["position", posArr],
+ ["aOther", otherArr],
+ ["aParams", paramArr],
+ ]) {
+ const attr = geometry.getAttribute(attrName);
+ if (!attr || vertGrew) {
+ const nextAttr = new THREE.BufferAttribute(arr, 3);
+ nextAttr.setUsage(THREE.DynamicDrawUsage);
+ geometry.setAttribute(attrName, nextAttr);
+ } else {
+ attr.needsUpdate = true;
+ }
+ }
+
+ const idxAttr = geometry.getIndex();
+ if (!idxAttr || idxGrew) {
+ const nextIdx = new THREE.BufferAttribute(idxArr, 1);
+ nextIdx.setUsage(THREE.DynamicDrawUsage);
+ geometry.setIndex(nextIdx);
+ } else {
+ idxAttr.needsUpdate = true;
+ }
+
+ geometry.setDrawRange(0, idxCursor);
+ if (!geometry.boundingSphere) {
+ geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), CONFIG.earthRadius + 6);
+ }
+ return { vertexCount: vertCursor, indexCount: idxCursor, drawCalls: 1 };
+}
+
function uploadDashedBatch(lineObj, buckets) {
if (!lineObj) return { vertexCount: 0, drawCalls: 0 };
let totalFloats = 0;
@@ -1014,12 +1195,12 @@ function rebuildBatchedGeometry() {
}
const bRes = uploadIndexedBatch(_batchedBoundaryLines, boundaryBuckets);
- const aRes = uploadIndexedBatch(_batchedAdmin1Lines, admin1Buckets);
+ const aRes = uploadAdmin1RibbonBatch(_batchedAdmin1Lines, admin1Buckets);
const cRes = uploadDashedBatch(_batchedClaimLines, claimBuckets);
const showLines = boundaryLegendVisible();
_batchedBoundaryLines.visible = showLines && bRes.indexCount > 0;
- _batchedAdmin1Lines.visible = showLines && _admin1Opacity > 0.001 && aRes.indexCount > 0;
+ _batchedAdmin1Lines.visible = showLines && effectiveAdmin1Opacity() > 0.001 && aRes.indexCount > 0;
_batchedClaimLines.visible = showLines && cRes.vertexCount > 0;
const visibleUnionCount = new Set([...nextCoastKeys, ...nextBorderKeys]).size;
@@ -1978,6 +2159,7 @@ function setBoundaryLinesDimmed(dimmed) {
}
function updateBoundaryLineDimState() {
+ const isHoveringChina = _hoveredGroupKey === "CHN" || _hoveredGroupKey === "TWN";
if (_coastlineLines?.material) {
_coastlineLines.material.opacity = COUNTRY_BOUNDARY_CONFIG.lineOpacity;
_coastlineLines.material.needsUpdate = true;
@@ -1988,6 +2170,12 @@ function updateBoundaryLineDimState() {
? Math.max(COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity, 0.28)
: COUNTRY_BOUNDARY_CONFIG.lineOpacity;
}
+ if (_claimTileMaterial) {
+ _claimTileMaterial.opacity = (_hoveredFeature && !isHoveringChina)
+ ? COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity
+ : 0.85;
+ }
+ syncAdmin1RibbonState();
setBoundaryLinesDimmed(Boolean(_hoveredFeature) || _activeTileKeys.size > 0);
}
@@ -2056,7 +2244,21 @@ export function extractCountryHoverGeometryData(
for (const entry of coastEntries || []) collectBucket(entry?.coast);
for (const entry of borderEntries || []) collectBucket(entry?.border);
- if (totalIndices === 0 || matchedSlices.length === 0) {
+ const claimEntries = [];
+ if (codeSet.has("CHN") || codeSet.has("TWN")) {
+ const seenClaims = new Set();
+ for (const entry of borderEntries || []) {
+ const claim = entry?.claim;
+ if (!claim?.positions?.length || seenClaims.has(claim)) continue;
+ seenClaims.add(claim);
+ const segs = Math.floor(claim.positions.length / 6);
+ if (segs <= 0) continue;
+ claimEntries.push(claim);
+ totalIndices += segs * 2;
+ }
+ }
+
+ if (totalIndices === 0 || (matchedSlices.length === 0 && claimEntries.length === 0)) {
return { positions: new Float32Array(0), indices: new Uint32Array(0), polylines: [] };
}
@@ -2121,6 +2323,62 @@ export function extractCountryHoverGeometryData(
}
}
+ const ENDPOINT_EPS_SQ = 1e-10;
+ for (const claim of claimEntries) {
+ const srcPos = claim.positions;
+ const segCount = Math.floor(srcPos.length / 6);
+ let currentPoly = null;
+ let prevMapB = -1;
+ let prevBx = 0;
+ let prevBy = 0;
+ let prevBz = 0;
+
+ for (let s = 0; s < segCount; s += 1) {
+ const base = s * 6;
+ const ax = srcPos[base];
+ const ay = srcPos[base + 1];
+ const az = srcPos[base + 2];
+ const bx = srcPos[base + 3];
+ const by = srcPos[base + 4];
+ const bz = srcPos[base + 5];
+
+ const chained =
+ prevMapB !== -1 &&
+ (ax - prevBx) * (ax - prevBx) + (ay - prevBy) * (ay - prevBy) + (az - prevBz) * (az - prevBz) <=
+ ENDPOINT_EPS_SQ;
+
+ let mapA;
+ if (chained) {
+ mapA = prevMapB;
+ } else {
+ mapA = outVertCount++;
+ posList.push(ax, ay, az);
+ }
+ const mapB = outVertCount++;
+ posList.push(bx, by, bz);
+
+ outIndices[outIdxCursor++] = mapA;
+ outIndices[outIdxCursor++] = mapB;
+
+ if (chained && currentPoly) {
+ currentPoly.push(new THREE.Vector3(bx * glowScale, by * glowScale, bz * glowScale));
+ } else {
+ if (currentPoly && currentPoly.length >= 2) polylines.push(currentPoly);
+ currentPoly = [
+ new THREE.Vector3(ax * glowScale, ay * glowScale, az * glowScale),
+ new THREE.Vector3(bx * glowScale, by * glowScale, bz * glowScale),
+ ];
+ }
+ prevMapB = mapB;
+ prevBx = bx;
+ prevBy = by;
+ prevBz = bz;
+ }
+ if (currentPoly && currentPoly.length >= 2) {
+ polylines.push(currentPoly);
+ }
+ }
+
return {
positions: new Float32Array(posList),
indices: outIndices.subarray(0, outIdxCursor),
@@ -2531,6 +2789,38 @@ export function getCountryBoundaryManifest() {
return _tileManifest;
}
+export function getBoundaryPmtilesUrl() {
+ return manifestPmtilesUrl(_tileManifest);
+}
+
+export function getBoundaryPmtilesArchive() {
+ return _tileManifest ? ensurePmtilesArchive() : null;
+}
+
+export function lookupCountryGroupAtLatLon(lat, lon) {
+ if (!_loaded || !Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ const found = _features.find((f) => featureContains(lat, lon, f)) || null;
+ if (!found) return null;
+ const groupKey = getCountryHighlightGroupKey(found);
+ const members = getHighlightFeatures(found);
+ const codes = [...new Set(
+ members
+ .flatMap((feat) => {
+ const p = feat?.properties || {};
+ return [p.ADM0_A3, p.ISO_A3, p.ISO_A3_EH, p.SOV_A3];
+ })
+ .map((code) => String(code || "").trim().toUpperCase())
+ .filter((code) => code && code !== "-99"),
+ )];
+ if (codes.includes("CHN") && !codes.includes("TWN")) codes.push("TWN");
+ if (codes.includes("TWN") && !codes.includes("CHN")) codes.push("CHN");
+ return {
+ groupKey,
+ codes,
+ info: makeCountryInfo(found),
+ };
+}
+
/**
* Show or hide the country boundary lines.
* The land/ocean fill is the base earth map and stays independent from this
diff --git a/frontend/public/earth/js/country-boundaries.test.js b/frontend/public/earth/js/country-boundaries.test.js
index 576e52f4..48e4e28b 100644
--- a/frontend/public/earth/js/country-boundaries.test.js
+++ b/frontend/public/earth/js/country-boundaries.test.js
@@ -357,7 +357,7 @@ test("sortKeysCenterFirst prioritizes tiles closest to screen center", () => {
expect(sorted[1]).toBe("boundary/4/12/6");
});
-test("extractCountryHoverGeometryData merges land borders and OSM coastlines cleanly without fill mask", () => {
+test("extractCountryHoverGeometryData merges land borders, coastlines, and China claim lines without fill mask", () => {
const coastEntry = {
coast: {
// Two connected segments for CHN (0->1->2) plus one island coastline for JPN (3->4->5)
@@ -380,12 +380,25 @@ test("extractCountryHoverGeometryData merges land borders and OSM coastlines cle
CHN: new Uint32Array([0, 2]),
},
},
+ claim: {
+ positions: new Float32Array([
+ 40, 0, 0, 41, 0, 0,
+ 41, 0, 0, 42, 0, 0,
+ 50, 0, 0, 51, 0, 0,
+ ]),
+ lineDistances: new Float32Array([0, 1, 1, 2, 0, 1]),
+ },
};
const chn = extractCountryHoverGeometryData(["CHN"], [coastEntry], [borderEntry]);
- expect(chn.indices.length).toBe(6); // 4 coast indices + 2 border indices
- expect(chn.polylines).toHaveLength(2);
+ expect(chn.indices.length).toBe(12); // 4 coast + 2 border + 6 claim indices
+ expect(chn.polylines).toHaveLength(4); // 1 coast + 1 border + 2 claim chains
expect(chn.polylines[0]).toHaveLength(3); // continuous 3-point coastline
+ expect(chn.polylines[2]).toHaveLength(3); // connected 9-dash pair stitched cleanly
+
+ const twn = extractCountryHoverGeometryData(["TWN"], [coastEntry], [borderEntry]);
+ expect(twn.indices.length).toBe(6); // China POV claim lines highlight for TWN too
+ expect(twn.polylines).toHaveLength(2);
const jpn = extractCountryHoverGeometryData(["JPN"], [coastEntry], [borderEntry]);
expect(jpn.indices.length).toBe(4);
diff --git a/frontend/public/earth/js/disasters.js b/frontend/public/earth/js/disasters.js
new file mode 100644
index 00000000..9289fad5
--- /dev/null
+++ b/frontend/public/earth/js/disasters.js
@@ -0,0 +1,264 @@
+// disasters.js - Single-batch THREE.Points natural disaster overlay (R+0.52, renderOrder 4.6)
+
+import * as THREE from "three";
+import { CONFIG, PATHS } from "./constants.js";
+import { latLonToVector3 } from "./utils.js";
+
+const DISASTER_ALTITUDE_OFFSET = 0.52;
+const DISASTER_RENDER_ORDER = 4.6;
+
+const TYPE_CODES = {
+ earthquake: 0.0,
+ wildfire: 1.0,
+ cyclone: 2.0,
+ flood: 3.0,
+ volcano: 4.0,
+ drought: 5.0,
+ other: 6.0,
+};
+
+const TYPE_LABELS = {
+ earthquake: "地震",
+ wildfire: "林火热点簇",
+ cyclone: "热带气旋/风暴",
+ flood: "洪涝灾害",
+ volcano: "火山活动",
+ drought: "干旱",
+ other: "其他自然异常",
+};
+
+const SEVERITY_CODES = {
+ low: 0.0,
+ medium: 1.0,
+ high: 2.0,
+};
+
+let disastersGroup = null;
+let disastersPoints = null;
+let disasterRecords = [];
+let disasterPayloadMeta = null;
+let disastersVisible = false;
+let disastersShaderMat = null;
+
+function buildShaderMaterial() {
+ return new THREE.ShaderMaterial({
+ uniforms: {
+ uTime: { value: 0.0 },
+ uPixelRatio: {
+ value: typeof window !== "undefined" ? Math.min(window.devicePixelRatio || 1, 2) : 1,
+ },
+ },
+ vertexShader: `
+ attribute float aType;
+ attribute float aSeverity;
+ attribute float aPhase;
+ uniform float uTime;
+ uniform float uPixelRatio;
+ varying float vType;
+ varying float vSeverity;
+ varying float vPulse;
+
+ void main() {
+ vType = aType;
+ vSeverity = aSeverity;
+ float speed = aSeverity > 1.5 ? 2.8 : 1.6;
+ vPulse = 0.5 + 0.5 * sin(uTime * speed + aPhase);
+ vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
+ float baseSize = aSeverity > 1.5 ? 16.0 : (aSeverity > 0.5 ? 12.0 : 9.0);
+ float pulseScale = 1.0 + vPulse * (aSeverity > 1.5 ? 0.35 : 0.18);
+ gl_PointSize = clamp(baseSize * pulseScale * uPixelRatio * (380.0 / max(120.0, -mvPosition.z)), 6.0, 28.0);
+ gl_Position = projectionMatrix * mvPosition;
+ }
+ `,
+ fragmentShader: `
+ varying float vType;
+ varying float vSeverity;
+ varying float vPulse;
+
+ vec3 disasterColor(float typeCode, float sevCode) {
+ if (typeCode < 0.5) return sevCode > 1.5 ? vec3(0.98, 0.27, 0.27) : vec3(0.98, 0.48, 0.25); // earthquake
+ if (typeCode < 1.5) return vec3(1.00, 0.62, 0.14); // wildfire
+ if (typeCode < 2.5) return vec3(0.22, 0.74, 0.97); // cyclone
+ if (typeCode < 3.5) return vec3(0.24, 0.52, 0.98); // flood
+ if (typeCode < 4.5) return vec3(0.95, 0.32, 0.58); // volcano
+ if (typeCode < 5.5) return vec3(0.91, 0.72, 0.22); // drought
+ return vec3(0.75, 0.80, 0.86);
+ }
+
+ void main() {
+ vec2 uv = gl_PointCoord - vec2(0.5);
+ float dist = length(uv);
+ if (dist > 0.5) discard;
+ vec3 baseColor = disasterColor(vType, vSeverity);
+ float core = smoothstep(0.22, 0.04, dist);
+ float ring = smoothstep(0.49, 0.36, dist) * (1.0 - smoothstep(0.32, 0.18, dist));
+ float alpha = clamp(core * 0.95 + ring * (0.45 + 0.45 * vPulse), 0.0, 1.0);
+ vec3 color = mix(baseColor, vec3(1.0, 0.96, 0.92), core * 0.35);
+ gl_FragColor = vec4(color, alpha);
+ }
+ `,
+ transparent: true,
+ depthTest: true,
+ depthWrite: false,
+ });
+}
+
+export function buildDisasterPointAttributes(items = [], radius = CONFIG.earthRadius + DISASTER_ALTITUDE_OFFSET) {
+ const valid = Array.isArray(items)
+ ? items.filter(
+ (it) =>
+ it?.lat != null &&
+ it?.lon != null &&
+ it?.lat !== "" &&
+ it?.lon !== "" &&
+ Number.isFinite(Number(it.lat)) &&
+ Number.isFinite(Number(it.lon)),
+ )
+ : [];
+ const count = valid.length;
+ const positions = new Float32Array(count * 3);
+ const types = new Float32Array(count);
+ const severities = new Float32Array(count);
+ const phases = new Float32Array(count);
+
+ for (let i = 0; i < count; i += 1) {
+ const item = valid[i];
+ const vec = latLonToVector3(Number(item.lat), Number(item.lon), radius);
+ positions[i * 3] = vec.x;
+ positions[i * 3 + 1] = vec.y;
+ positions[i * 3 + 2] = vec.z;
+ const typeKey = String(item.event_type || "other").toLowerCase();
+ const sevKey = String(item.severity || "medium").toLowerCase();
+ types[i] = TYPE_CODES[typeKey] ?? TYPE_CODES.other;
+ severities[i] = SEVERITY_CODES[sevKey] ?? SEVERITY_CODES.medium;
+ phases[i] = (i * 1.37) % (Math.PI * 2);
+ }
+ return { valid, count, positions, types, severities, phases };
+}
+
+function disposeMesh() {
+ if (disastersPoints) {
+ disastersPoints.parent?.remove(disastersPoints);
+ disastersPoints.geometry?.dispose?.();
+ disastersPoints = null;
+ }
+ if (disastersShaderMat) {
+ disastersShaderMat.dispose?.();
+ disastersShaderMat = null;
+ }
+}
+
+export function initDisastersLayer(earth) {
+ if (!earth) return null;
+ if (!disastersGroup) {
+ disastersGroup = new THREE.Group();
+ disastersGroup.name = "disasters-layer-group";
+ disastersGroup.visible = disastersVisible;
+ earth.add(disastersGroup);
+ } else if (disastersGroup.parent !== earth) {
+ earth.add(disastersGroup);
+ }
+ return disastersGroup;
+}
+
+export function renderDisasterItems(items = [], earth) {
+ const group = initDisastersLayer(earth);
+ if (!group) return 0;
+ disposeMesh();
+
+ const built = buildDisasterPointAttributes(items);
+ disasterRecords = built.valid;
+ if (built.count === 0) {
+ return 0;
+ }
+
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute("position", new THREE.BufferAttribute(built.positions, 3));
+ geometry.setAttribute("aType", new THREE.BufferAttribute(built.types, 1));
+ geometry.setAttribute("aSeverity", new THREE.BufferAttribute(built.severities, 1));
+ geometry.setAttribute("aPhase", new THREE.BufferAttribute(built.phases, 1));
+
+ disastersShaderMat = buildShaderMaterial();
+ disastersPoints = new THREE.Points(geometry, disastersShaderMat);
+ disastersPoints.name = "disaster-events-points";
+ disastersPoints.renderOrder = DISASTER_RENDER_ORDER;
+ disastersPoints.frustumCulled = false;
+ group.add(disastersPoints);
+ return built.count;
+}
+
+export async function loadDisasters(_scene, earth) {
+ initDisastersLayer(earth);
+ const resp = await fetch(PATHS.disastersSnapshotApi, { cache: "no-store", credentials: "same-origin" });
+ if (!resp.ok) {
+ throw new Error(`HTTP ${resp.status}`);
+ }
+ const payload = await resp.json();
+ disasterPayloadMeta = payload;
+ const totalCount = renderDisasterItems(payload?.items || [], earth);
+ return { totalCount, payload };
+}
+
+export function toggleDisasters(visible, earth) {
+ disastersVisible = Boolean(visible);
+ if (earth) initDisastersLayer(earth);
+ if (disastersGroup) {
+ disastersGroup.visible = disastersVisible;
+ }
+}
+
+export function updateDisastersFrame(elapsedSec) {
+ if (disastersVisible && disastersShaderMat?.uniforms?.uTime) {
+ disastersShaderMat.uniforms.uTime.value = Number(elapsedSec || 0);
+ }
+}
+
+export function clearDisastersData(earth) {
+ disasterRecords = [];
+ disasterPayloadMeta = null;
+ disposeMesh();
+ if (disastersGroup) {
+ earth?.remove?.(disastersGroup);
+ disastersGroup = null;
+ }
+}
+
+export function getDisastersCount() {
+ return disasterRecords.length;
+}
+
+export function getDisasterTypeLabel(typeKey) {
+ return TYPE_LABELS[String(typeKey || "other").toLowerCase()] || TYPE_LABELS.other;
+}
+
+export function findNearestDisaster(lat, lon, maxAngleDeg = 1.8) {
+ if (!disastersVisible || !disasterRecords.length) return null;
+ const targetLat = Number(lat);
+ const targetLon = Number(lon);
+ if (!Number.isFinite(targetLat) || !Number.isFinite(targetLon)) return null;
+
+ let best = null;
+ let bestDist = Infinity;
+ for (const item of disasterRecords) {
+ const dLat = Math.abs(Number(item.lat) - targetLat);
+ let dLon = Math.abs(Number(item.lon) - targetLon);
+ if (dLon > 180) dLon = 360 - dLon;
+ const dist = Math.hypot(dLat, dLon);
+ if (dist <= maxAngleDeg && dist < bestDist) {
+ bestDist = dist;
+ best = item;
+ }
+ }
+ return best;
+}
+
+export function getDisastersLegendItems() {
+ if (!disastersVisible) return [];
+ const counts = disasterPayloadMeta?.by_type || {};
+ return [
+ { label: `地震 (${Number(counts.earthquake || 0)})`, color: "#fa4545" },
+ { label: `林火簇 (${Number(counts.wildfire || 0)})`, color: "#ff9e24" },
+ { label: `气旋/洪水 (${Number(counts.cyclone || 0) + Number(counts.flood || 0)})`, color: "#38bdf8" },
+ { label: `火山/其他 (${Number(counts.volcano || 0) + Number(counts.drought || 0) + Number(counts.other || 0)})`, color: "#f25294" },
+ ];
+}
diff --git a/frontend/public/earth/js/disasters.test.js b/frontend/public/earth/js/disasters.test.js
new file mode 100644
index 00000000..f07b6917
--- /dev/null
+++ b/frontend/public/earth/js/disasters.test.js
@@ -0,0 +1,24 @@
+import { describe, expect, test } from "bun:test";
+import { buildDisasterPointAttributes, findNearestDisaster, toggleDisasters } from "./disasters.js";
+
+describe("disasters layer math and picking", () => {
+ test("buildDisasterPointAttributes packs type and severity float channels", () => {
+ const built = buildDisasterPointAttributes([
+ { lat: 23.85, lon: 121.55, event_type: "earthquake", severity: "high" },
+ { lat: 34.12, lon: 118.14, event_type: "wildfire", severity: "medium", cluster_count: 5 },
+ { lat: null, lon: 10 },
+ ]);
+
+ expect(built.count).toBe(2);
+ expect(built.positions.length).toBe(6);
+ expect(built.types[0]).toBe(0);
+ expect(built.severities[0]).toBe(2);
+ expect(built.types[1]).toBe(1);
+ expect(built.severities[1]).toBe(1);
+ });
+
+ test("findNearestDisaster skips when hidden", () => {
+ toggleDisasters(false, null);
+ expect(findNearestDisaster(23.85, 121.55)).toBeNull();
+ });
+});
diff --git a/frontend/public/earth/js/earth-interactables.js b/frontend/public/earth/js/earth-interactables.js
index 3d13682e..85effa7b 100644
--- a/frontend/public/earth/js/earth-interactables.js
+++ b/frontend/public/earth/js/earth-interactables.js
@@ -50,6 +50,12 @@ function drawInteractableIcon(context, { marker, color = "#7dd3fc" }) {
context.moveTo(-14, -16); context.lineTo(14, -16);
context.moveTo(-14, 0); context.lineTo(14, 0);
context.moveTo(-14, 16); context.lineTo(6, 16);
+ } else if (kind === "port") {
+ context.arc(0, -18, 8, 0, Math.PI * 2);
+ context.moveTo(0, -10); context.lineTo(0, 26);
+ context.moveTo(-16, -2); context.lineTo(16, -2);
+ context.moveTo(-22, 14);
+ context.quadraticCurveTo(0, 32, 22, 14);
} else if (kind === "alert") {
context.moveTo(0, -34); context.lineTo(34, 28); context.lineTo(-34, 28); context.closePath();
context.moveTo(0, -13); context.lineTo(0, 6);
@@ -75,6 +81,7 @@ const earthInteractableLayer = createInteractableLayer({
note: "#facc15",
alert: "#fb7185",
place: "#86efac",
+ port: "#38bdf8",
},
opacity: {
normal: 0.9,
@@ -115,6 +122,29 @@ export async function loadEarthInteractables(earth, { silent = false } = {}) {
const items = (payload.features || [])
.map(featureToInteractableItem)
.filter(Boolean);
+ try {
+ const mcResp = await fetch("/api/v1/vessels/maritime-context", { cache: "no-store" });
+ if (mcResp.ok) {
+ const mc = await mcResp.json();
+ const existingIds = new Set(items.map((it) => it.id));
+ for (const port of mc.ports || []) {
+ if (!port?.id || existingIds.has(port.id)) continue;
+ items.push({
+ id: String(port.id),
+ label: `${port.name} (${port.port_type})`,
+ kind: "port",
+ latitude: Number(port.lat),
+ longitude: Number(port.lon),
+ description: `${port.country || "-"} · ${port.port_type || "-"} · 吞吐排名 ${port.throughput_rank ?? "-"}`,
+ source: port.source_citation || "Lloyd's List / NGA WPI",
+ status: port.port_type || "port",
+ revision: 1,
+ });
+ }
+ }
+ } catch {
+ // Strategic ports enrichment is best-effort.
+ }
interactableRevisions.clear();
items.forEach((item) => interactableRevisions.set(item.id, Number(item.revision || 0)));
earthInteractableLayer.setData(items);
diff --git a/frontend/public/earth/js/earth-texture-image.js b/frontend/public/earth/js/earth-texture-image.js
index a47817fc..14673294 100644
--- a/frontend/public/earth/js/earth-texture-image.js
+++ b/frontend/public/earth/js/earth-texture-image.js
@@ -1,11 +1,43 @@
import { EARTH_MAP_SOURCES } from "./earth-map-sources.js";
+import { putCachedAssetBlob, readCachedAssetBlob } from "./asset-swr-cache.js";
+
+function inferTextureCacheTarget(url, options = {}) {
+ if (options?.cacheBucket && options?.cacheKey) {
+ return { bucket: options.cacheBucket, key: options.cacheKey };
+ }
+ const normalized = String(url || "");
+ if (normalized.startsWith("/api/v1/earth/tiles/")) {
+ return { bucket: "tiles", key: normalized };
+ }
+ if (normalized.startsWith("/api/v1/earth/clouds/") && !normalized.startsWith("/api/v1/earth/clouds/meta")) {
+ return { bucket: "clouds", key: options?.cacheKey || normalized };
+ }
+ return null;
+}
// Keep the original 8K pixels; decode off the render path and share the result.
-async function decodeEarthImage(url, { signal } = {}) {
+async function decodeEarthImage(url, options = {}) {
+ const { signal } = options;
if (typeof createImageBitmap === "function") {
- const response = await fetch(url, { priority: "high", signal });
- if (!response.ok) throw new Error("地表底图加载失败,请重试");
- const blob = await response.blob();
+ const cacheTarget = inferTextureCacheTarget(url, options);
+ let blob = null;
+ if (cacheTarget && !options?.bypassCache) {
+ blob = await readCachedAssetBlob(cacheTarget.bucket, cacheTarget.key);
+ }
+ if (signal?.aborted) {
+ throw new DOMException("Aborted", "AbortError");
+ }
+ if (!blob) {
+ const response = await fetch(url, { priority: "high", signal });
+ if (!response.ok) throw new Error("地表底图加载失败,请重试");
+ blob = await response.blob();
+ if (cacheTarget && blob?.size > 0) {
+ void putCachedAssetBlob(cacheTarget.bucket, cacheTarget.key, blob, {
+ url,
+ fingerprint: options?.cacheFingerprint || url,
+ });
+ }
+ }
if (signal?.aborted) {
throw new DOMException("Aborted", "AbortError");
}
@@ -31,9 +63,9 @@ async function decodeEarthImage(url, { signal } = {}) {
export function createEarthTextureImageLoader(decode = decodeEarthImage) {
let preload = null;
return {
- preload(url) {
- if (preload?.url === url) return preload.promise;
- const entry = { url, promise: decode(url) };
+ preload(url, options) {
+ if (preload?.url === url && !options?.cacheBucket) return preload.promise;
+ const entry = { url, promise: decode(url, options) };
const previous = preload;
preload = entry;
previous?.promise.then(image => image.close?.(), () => {});
@@ -43,7 +75,7 @@ export function createEarthTextureImageLoader(decode = decodeEarthImage) {
load(url, options) {
const entry = preload;
preload = null;
- if (entry?.url === url && !options?.signal) return entry.promise;
+ if (entry?.url === url && !options?.signal && !options?.cacheBucket) return entry.promise;
entry?.promise.then(image => image.close?.(), () => {});
return decode(url, options);
},
diff --git a/frontend/public/earth/js/earth.js b/frontend/public/earth/js/earth.js
index e0877ab6..51409395 100644
--- a/frontend/public/earth/js/earth.js
+++ b/frontend/public/earth/js/earth.js
@@ -40,6 +40,8 @@ let _cloudShadow = null;
let _basemapTileLayer = null;
let _cloudTileLayer = null;
let _basemapChannel = null;
+let _basemapTileTemplate = "/api/v1/earth/tiles/earth_imagery_sentinel2/{z}/{x}/{y}.webp";
+let _basemapMaxZoom = 7;
let _cloudBaseOpacity = CLOUD_LAYER_CONFIG.opacity ?? 0.38;
export let terrain = null;
let showGridLines = false;
@@ -652,6 +654,10 @@ export async function loadBasemapMeta() {
const meta = await response.json();
const maxZoom = Number(meta?.max_zoom || 7);
const lodAlt = Number(meta?.lod_switch_altitude || 1.85);
+ if (meta?.tile_url_template) {
+ _basemapTileTemplate = String(meta.tile_url_template);
+ }
+ _basemapMaxZoom = maxZoom;
_basemapTileLayer?.setTemplate(meta?.tile_url_template || null, {
maxZoom,
lodSwitchAltitude: lodAlt,
@@ -691,6 +697,13 @@ export function disposeEarthTileLayers() {
}
}
+export function getBasemapConfigSnapshot() {
+ return {
+ tileUrlTemplate: _basemapTileTemplate,
+ maxZoom: _basemapMaxZoom,
+ };
+}
+
export function getEarthTextureVisible() {
return _textureVisible;
}
diff --git a/frontend/public/earth/js/fusion-overlays.js b/frontend/public/earth/js/fusion-overlays.js
new file mode 100644
index 00000000..073b00c8
--- /dev/null
+++ b/frontend/public/earth/js/fusion-overlays.js
@@ -0,0 +1,183 @@
+import * as THREE from "three";
+
+import { CONFIG } from "./constants.js";
+import {
+ createDashedRibbonMaterial,
+ createSurfaceRibbonGeometry,
+ createSurfaceRibbonMaterial,
+} from "./surface-ribbon.js";
+import { latLonToVector3 } from "./utils.js";
+
+const CORRELATION_RENDER_ORDER = 0.971;
+const IMPACT_RENDER_ORDER = 0.972;
+const HEX_ALTITUDE_OFFSET = 0.19;
+const ARC_PEAK_OFFSET = 1.65;
+
+export function buildCorrelationHexPolylines(cells = [], radius = CONFIG.earthRadius + HEX_ALTITUDE_OFFSET) {
+ const polylines = [];
+ for (const cell of Array.isArray(cells) ? cells : []) {
+ const boundary = Array.isArray(cell?.boundary) ? cell.boundary : [];
+ if (boundary.length < 3) continue;
+ const pts = boundary
+ .filter((pt) => Array.isArray(pt) && pt.length >= 2)
+ .map((pt) => latLonToVector3(Number(pt[0]), Number(pt[1]), radius));
+ if (pts.length < 3) continue;
+ pts.push(pts[0].clone());
+ polylines.push(pts);
+ }
+ return polylines;
+}
+
+export function buildDependencyImpactArcPolylines(
+ arcs = [],
+ baseRadius = CONFIG.earthRadius + 0.22,
+ segments = 24,
+) {
+ const polylines = [];
+ for (const arc of Array.isArray(arcs) ? arcs : []) {
+ const fLat = Number(arc?.from_lat);
+ const fLon = Number(arc?.from_lon);
+ const tLat = Number(arc?.to_lat);
+ const tLon = Number(arc?.to_lon);
+ if (!Number.isFinite(fLat) || !Number.isFinite(fLon) || !Number.isFinite(tLat) || !Number.isFinite(tLon)) {
+ continue;
+ }
+ const start = latLonToVector3(fLat, fLon, baseRadius).normalize();
+ const end = latLonToVector3(tLat, tLon, baseRadius).normalize();
+ const pts = [];
+ for (let i = 0; i <= segments; i += 1) {
+ const t = i / segments;
+ const vec = start.clone().lerp(end, t).normalize();
+ const lift = Math.sin(t * Math.PI) * ARC_PEAK_OFFSET;
+ pts.push(vec.multiplyScalar(baseRadius + lift));
+ }
+ polylines.push(pts);
+ }
+ return polylines;
+}
+
+export function createFusionOverlaysManager({ getEarth } = {}) {
+ let visible = false;
+ let candidateCells = [];
+ let dependencyArcs = [];
+ let rootGroup = null;
+ let correlationMesh = null;
+ let dependencyMesh = null;
+
+ const ensureGroup = () => {
+ const earth = getEarth?.();
+ if (!earth) return null;
+ if (!rootGroup) {
+ rootGroup = new THREE.Group();
+ rootGroup.name = "fusion_overlays_group";
+ rootGroup.visible = visible;
+ earth.add(rootGroup);
+ } else if (rootGroup.parent !== earth) {
+ earth.add(rootGroup);
+ }
+ return rootGroup;
+ };
+
+ const clearMeshes = () => {
+ if (correlationMesh) {
+ correlationMesh.geometry?.dispose?.();
+ correlationMesh.material?.dispose?.();
+ correlationMesh.removeFromParent?.();
+ correlationMesh = null;
+ }
+ if (dependencyMesh) {
+ dependencyMesh.geometry?.dispose?.();
+ dependencyMesh.material?.dispose?.();
+ dependencyMesh.removeFromParent?.();
+ dependencyMesh = null;
+ }
+ };
+
+ const rebuild = () => {
+ const group = ensureGroup();
+ clearMeshes();
+ if (!group) return;
+
+ const hexLines = buildCorrelationHexPolylines(candidateCells);
+ if (hexLines.length > 0) {
+ const geo = createSurfaceRibbonGeometry(hexLines);
+ if (geo) {
+ const mat = createDashedRibbonMaterial({
+ color: 0xf59e0b,
+ opacity: 0.9,
+ halfWidthPx: 2.0,
+ dashScale: 10.0,
+ dashRatio: 0.55,
+ });
+ correlationMesh = new THREE.Mesh(geo, mat);
+ correlationMesh.renderOrder = CORRELATION_RENDER_ORDER;
+ correlationMesh.name = "fusion_candidate_correlation_hex_batch";
+ group.add(correlationMesh);
+ }
+ }
+
+ const impactLines = buildDependencyImpactArcPolylines(dependencyArcs);
+ if (impactLines.length > 0) {
+ const geo = createSurfaceRibbonGeometry(impactLines);
+ if (geo) {
+ const mat = createSurfaceRibbonMaterial({
+ color: 0xef4444,
+ opacity: 0.92,
+ halfWidthPx: 2.5,
+ });
+ dependencyMesh = new THREE.Mesh(geo, mat);
+ dependencyMesh.renderOrder = IMPACT_RENDER_ORDER;
+ dependencyMesh.name = "fusion_dependency_impact_arc_batch";
+ group.add(dependencyMesh);
+ }
+ }
+ };
+
+ const setOverlayData = ({ candidate_cells = [], dependency_arcs = [] } = {}) => {
+ candidateCells = Array.isArray(candidate_cells) ? candidate_cells : [];
+ dependencyArcs = Array.isArray(dependency_arcs) ? dependency_arcs : [];
+ rebuild();
+ return {
+ candidateCount: candidateCells.length,
+ dependencyArcCount: dependencyArcs.length,
+ };
+ };
+
+ const loadOverlays = async (fetchImpl = globalThis.fetch) => {
+ const resp = await fetchImpl("/api/v1/incidents/overlay");
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const payload = await resp.json();
+ return setOverlayData(payload || {});
+ };
+
+ const setVisible = (next) => {
+ visible = Boolean(next);
+ if (rootGroup) rootGroup.visible = visible;
+ return visible;
+ };
+
+ const getStats = () => ({
+ visible,
+ candidateCount: candidateCells.length,
+ dependencyArcCount: dependencyArcs.length,
+ hasCorrelationMesh: Boolean(correlationMesh),
+ hasDependencyMesh: Boolean(dependencyMesh),
+ });
+
+ const dispose = () => {
+ clearMeshes();
+ rootGroup?.removeFromParent?.();
+ rootGroup = null;
+ candidateCells = [];
+ dependencyArcs = [];
+ };
+
+ return {
+ setOverlayData,
+ loadOverlays,
+ setVisible,
+ isVisible: () => visible,
+ getStats,
+ dispose,
+ };
+}
diff --git a/frontend/public/earth/js/fusion-overlays.test.js b/frontend/public/earth/js/fusion-overlays.test.js
new file mode 100644
index 00000000..f6c52c88
--- /dev/null
+++ b/frontend/public/earth/js/fusion-overlays.test.js
@@ -0,0 +1,50 @@
+import { describe, expect, test } from "bun:test";
+import * as THREE from "three";
+import {
+ buildCorrelationHexPolylines,
+ buildDependencyImpactArcPolylines,
+ createFusionOverlaysManager,
+} from "./fusion-overlays.js";
+
+describe("fusion-overlays", () => {
+ test("batches candidate correlation hexes and dependency impact arcs separately", () => {
+ const cells = [
+ {
+ incident_id: 1,
+ label: "待核查",
+ boundary: [
+ [1.1, 103.5],
+ [1.2, 103.6],
+ [1.3, 103.5],
+ [1.3, 103.3],
+ [1.2, 103.2],
+ [1.1, 103.3],
+ ],
+ },
+ ];
+ const arcs = [
+ {
+ from_lat: 1.2,
+ from_lon: 103.5,
+ to_lat: 1.35,
+ to_lon: 103.82,
+ kind: "dependency_impact",
+ },
+ ];
+
+ expect(buildCorrelationHexPolylines(cells)).toHaveLength(1);
+ expect(buildDependencyImpactArcPolylines(arcs)).toHaveLength(1);
+
+ const earth = new THREE.Group();
+ const mgr = createFusionOverlaysManager({ getEarth: () => earth });
+ mgr.setOverlayData({ candidate_cells: cells, dependency_arcs: arcs });
+ const stats = mgr.getStats();
+ expect(stats.hasCorrelationMesh).toBe(true);
+ expect(stats.hasDependencyMesh).toBe(true);
+ expect(stats.candidateCount).toBe(1);
+ expect(stats.dependencyArcCount).toBe(1);
+
+ mgr.dispose();
+ expect(earth.children).toHaveLength(0);
+ });
+});
diff --git a/frontend/public/earth/js/geo-labels.js b/frontend/public/earth/js/geo-labels.js
index af30aeb9..7dc0be1b 100644
--- a/frontend/public/earth/js/geo-labels.js
+++ b/frontend/public/earth/js/geo-labels.js
@@ -301,6 +301,8 @@ export function createGeoLabels() {
}
return locale;
},
+ getPlaces: () => places,
+ getLocale: () => locale,
getStats() {
const tierCounts = { 1: 0, 2: 0, 3: 0 };
const labels = active
@@ -532,3 +534,11 @@ export function clearGeoLabels() {
export function getGeoLabelStats() {
return _controller.getStats();
}
+
+export function getLoadedGeoLabelPlaces() {
+ return _controller.getPlaces();
+}
+
+export function getGeoLabelLocale() {
+ return _controller.getLocale();
+}
diff --git a/frontend/public/earth/js/geofence-editor.js b/frontend/public/earth/js/geofence-editor.js
new file mode 100644
index 00000000..1a0141a4
--- /dev/null
+++ b/frontend/public/earth/js/geofence-editor.js
@@ -0,0 +1,318 @@
+import * as THREE from "three";
+
+import { CONFIG } from "./constants.js";
+import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js";
+import { latLonToVector3 } from "./utils.js";
+
+const GEOFENCE_RENDER_ORDER = 0.969;
+const GEOFENCE_SURFACE_OFFSET = 0.14;
+
+export function isEditableRole(role) {
+ const normalized = String(role || "").trim().toLowerCase();
+ return normalized === "admin" || normalized === "super_admin";
+}
+
+export function extractRingsFromGeofence(gf) {
+ const geom = gf?.geometry || {};
+ const gtype = String(geom.type || "");
+ const coords = Array.isArray(geom.coordinates) ? geom.coordinates : [];
+ if (gtype === "Polygon" && coords.length > 0 && Array.isArray(coords[0])) {
+ return [coords[0]];
+ }
+ if (gtype === "MultiPolygon") {
+ return coords.filter((poly) => Array.isArray(poly) && Array.isArray(poly[0])).map((poly) => poly[0]);
+ }
+ return [];
+}
+
+export function buildClosedPolygonGeoJson(vertices = []) {
+ const valid = (Array.isArray(vertices) ? vertices : [])
+ .filter((v) => v && Number.isFinite(Number(v.lat)) && Number.isFinite(Number(v.lon)))
+ .map((v) => [Number(Number(v.lon).toFixed(5)), Number(Number(v.lat).toFixed(5))]);
+ if (valid.length < 3) {
+ throw new Error("At least 3 vertices are required to close a geofence polygon");
+ }
+ const first = valid[0];
+ const last = valid[valid.length - 1];
+ if (first[0] !== last[0] || first[1] !== last[1]) {
+ valid.push([first[0], first[1]]);
+ }
+ return {
+ type: "Polygon",
+ coordinates: [valid],
+ };
+}
+
+export function buildGeofenceBatchBuffers(geofences = [], radius = CONFIG.earthRadius + GEOFENCE_SURFACE_OFFSET) {
+ const fillPositions = [];
+ const fillColors = [];
+ const linePositions = [];
+ const lineColors = [];
+
+ for (const gf of Array.isArray(geofences) ? geofences : []) {
+ if (gf?.enabled === false) continue;
+ const isPreset = gf?.kind === "preset";
+ const fillColor = isPreset ? [0.22, 0.74, 0.97] : [0.98, 0.75, 0.14];
+ const lineColor = isPreset ? [0.38, 0.85, 1.0] : [1.0, 0.84, 0.32];
+
+ for (const ring of extractRingsFromGeofence(gf)) {
+ const pts = ring
+ .filter((pt) => Array.isArray(pt) && pt.length >= 2 && Number.isFinite(Number(pt[0])) && Number.isFinite(Number(pt[1])))
+ .map((pt) => latLonToVector3(Number(pt[1]), Number(pt[0]), radius));
+ if (pts.length < 3) continue;
+
+ const openPts =
+ pts[0].distanceToSquared(pts[pts.length - 1]) < 1e-6 && pts.length > 3
+ ? pts.slice(0, -1)
+ : pts;
+
+ for (let i = 0; i < openPts.length; i += 1) {
+ const a = openPts[i];
+ const b = openPts[(i + 1) % openPts.length];
+ linePositions.push(a.x, a.y, a.z, b.x, b.y, b.z);
+ lineColors.push(...lineColor, ...lineColor);
+ }
+
+ if (openPts.length >= 3) {
+ const centroid = new THREE.Vector3();
+ for (const p of openPts) centroid.add(p);
+ centroid.divideScalar(openPts.length).normalize().multiplyScalar(radius);
+
+ for (let i = 0; i < openPts.length; i += 1) {
+ const a = openPts[i];
+ const b = openPts[(i + 1) % openPts.length];
+ fillPositions.push(
+ centroid.x, centroid.y, centroid.z,
+ a.x, a.y, a.z,
+ b.x, b.y, b.z,
+ );
+ fillColors.push(...fillColor, ...fillColor, ...fillColor);
+ }
+ }
+ }
+ }
+
+ return {
+ fillPositions: new Float32Array(fillPositions),
+ fillColors: new Float32Array(fillColors),
+ linePositions: new Float32Array(linePositions),
+ lineColors: new Float32Array(lineColors),
+ };
+}
+
+export function createGeofenceLayerManager({ getEarth } = {}) {
+ let visible = false;
+ let geofences = [];
+ let drawingActive = false;
+ let draftVertices = [];
+ let rootGroup = null;
+ let fillMesh = null;
+ let outlineSegments = null;
+ let draftLine = null;
+
+ const ensureGroup = () => {
+ const earth = getEarth?.();
+ if (!earth) return null;
+ if (!rootGroup) {
+ rootGroup = new THREE.Group();
+ rootGroup.name = "geofences_batch_group";
+ rootGroup.visible = visible;
+ earth.add(rootGroup);
+ } else if (rootGroup.parent !== earth) {
+ earth.add(rootGroup);
+ }
+ return rootGroup;
+ };
+
+ const disposeStaticMeshes = () => {
+ if (fillMesh) {
+ fillMesh.geometry?.dispose?.();
+ fillMesh.material?.dispose?.();
+ fillMesh.removeFromParent?.();
+ fillMesh = null;
+ }
+ if (outlineSegments) {
+ outlineSegments.geometry?.dispose?.();
+ outlineSegments.material?.dispose?.();
+ outlineSegments.removeFromParent?.();
+ outlineSegments = null;
+ }
+ };
+
+ const disposeDraftMesh = () => {
+ if (draftLine) {
+ draftLine.geometry?.dispose?.();
+ draftLine.material?.dispose?.();
+ draftLine.removeFromParent?.();
+ draftLine = null;
+ }
+ };
+
+ const rebuildMeshes = () => {
+ const group = ensureGroup();
+ disposeStaticMeshes();
+ if (!group || !geofences.length) return;
+
+ const buffers = buildGeofenceBatchBuffers(geofences);
+ if (buffers.fillPositions.length > 0) {
+ const fGeo = new THREE.BufferGeometry();
+ fGeo.setAttribute("position", new THREE.BufferAttribute(buffers.fillPositions, 3));
+ fGeo.setAttribute("color", new THREE.BufferAttribute(buffers.fillColors, 3));
+ const fMat = new THREE.MeshBasicMaterial({
+ vertexColors: true,
+ transparent: true,
+ opacity: 0.16,
+ side: THREE.DoubleSide,
+ depthWrite: false,
+ });
+ fillMesh = new THREE.Mesh(fGeo, fMat);
+ fillMesh.renderOrder = GEOFENCE_RENDER_ORDER;
+ fillMesh.name = "geofences_fill_batch";
+ group.add(fillMesh);
+ }
+ if (buffers.linePositions.length > 0) {
+ const lGeo = new THREE.BufferGeometry();
+ lGeo.setAttribute("position", new THREE.BufferAttribute(buffers.linePositions, 3));
+ lGeo.setAttribute("color", new THREE.BufferAttribute(buffers.lineColors, 3));
+ const lMat = new THREE.LineBasicMaterial({
+ vertexColors: true,
+ transparent: true,
+ opacity: 0.78,
+ depthWrite: false,
+ });
+ outlineSegments = new THREE.LineSegments(lGeo, lMat);
+ outlineSegments.renderOrder = GEOFENCE_RENDER_ORDER;
+ outlineSegments.name = "geofences_outline_batch";
+ group.add(outlineSegments);
+ }
+ };
+
+ const rebuildDraftMesh = () => {
+ const group = ensureGroup();
+ disposeDraftMesh();
+ if (!group || !drawingActive || draftVertices.length === 0) return;
+
+ const r = CONFIG.earthRadius + GEOFENCE_SURFACE_OFFSET + 0.04;
+ const pts = draftVertices.map((v) => latLonToVector3(v.lat, v.lon, r));
+ if (pts.length >= 3) pts.push(pts[0].clone());
+ const pos = new Float32Array(pts.length * 3);
+ pts.forEach((p, idx) => {
+ pos[idx * 3] = p.x;
+ pos[idx * 3 + 1] = p.y;
+ pos[idx * 3 + 2] = p.z;
+ });
+ const dGeo = new THREE.BufferGeometry();
+ dGeo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
+ const dMat = new THREE.LineBasicMaterial({
+ color: 0xfbbf24,
+ transparent: true,
+ opacity: 0.95,
+ depthWrite: false,
+ });
+ draftLine = new THREE.Line(dGeo, dMat);
+ draftLine.renderOrder = GEOFENCE_RENDER_ORDER + 0.001;
+ group.add(draftLine);
+ };
+
+ const setGeofences = (items = []) => {
+ geofences = Array.isArray(items) ? items : [];
+ rebuildMeshes();
+ return geofences.length;
+ };
+
+ const loadGeofences = async (fetchImpl = globalThis.fetch) => {
+ const resp = await fetchImpl("/api/v1/geofences?enabled_only=true&ensure_presets=true");
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const payload = await resp.json();
+ const count = setGeofences(payload?.items || []);
+ return { count, items: geofences };
+ };
+
+ const setVisible = (nextVisible) => {
+ visible = Boolean(nextVisible);
+ if (rootGroup) rootGroup.visible = visible;
+ return visible;
+ };
+
+ const isVisible = () => visible;
+ const getGeofences = () => geofences;
+ const getEditable = () => isEditableRole(readStoredAdminAuthState()?.user?.role);
+
+ const startDrawing = () => {
+ if (!getEditable()) {
+ throw new Error("Only admin or super_admin can draw geofences");
+ }
+ drawingActive = true;
+ draftVertices = [];
+ setVisible(true);
+ rebuildDraftMesh();
+ return true;
+ };
+
+ const cancelDrawing = () => {
+ drawingActive = false;
+ draftVertices = [];
+ disposeDraftMesh();
+ };
+
+ const addVertex = (lat, lon) => {
+ if (!drawingActive) return 0;
+ draftVertices.push({ lat: Number(lat), lon: Number(lon) });
+ rebuildDraftMesh();
+ return draftVertices.length;
+ };
+
+ const finishPolygon = async (name, rules = {}, { fetchImpl = globalThis.fetch } = {}) => {
+ const cleanName = String(name || "").trim();
+ if (!cleanName) throw new Error("Geofence name is required");
+ const geometry = buildClosedPolygonGeoJson(draftVertices);
+ const resp = await fetchAdminWriteJson(
+ "/api/v1/geofences",
+ { name: cleanName, kind: "custom", geometry, rules, enabled: true },
+ { fetchImpl },
+ );
+ if (!resp.ok) {
+ const txt = await resp.text();
+ throw new Error(txt || `HTTP ${resp.status}`);
+ }
+ const created = await resp.json();
+ cancelDrawing();
+ setGeofences([created, ...geofences]);
+ setVisible(true);
+ return created;
+ };
+
+ const getStats = () => ({
+ visible,
+ count: geofences.length,
+ drawingActive,
+ draftVertexCount: draftVertices.length,
+ editable: getEditable(),
+ hasFillMesh: Boolean(fillMesh),
+ hasOutlineMesh: Boolean(outlineSegments),
+ });
+
+ const dispose = () => {
+ cancelDrawing();
+ disposeStaticMeshes();
+ rootGroup?.removeFromParent?.();
+ rootGroup = null;
+ geofences = [];
+ };
+
+ return {
+ setGeofences,
+ loadGeofences,
+ setVisible,
+ isVisible,
+ getGeofences,
+ getEditable,
+ isDrawing: () => drawingActive,
+ startDrawing,
+ cancelDrawing,
+ addVertex,
+ finishPolygon,
+ getStats,
+ dispose,
+ };
+}
diff --git a/frontend/public/earth/js/geofence-editor.test.js b/frontend/public/earth/js/geofence-editor.test.js
new file mode 100644
index 00000000..18bc0092
--- /dev/null
+++ b/frontend/public/earth/js/geofence-editor.test.js
@@ -0,0 +1,52 @@
+import { describe, expect, test } from "bun:test";
+import * as THREE from "three";
+import {
+ buildClosedPolygonGeoJson,
+ buildGeofenceBatchBuffers,
+ createGeofenceLayerManager,
+ isEditableRole,
+} from "./geofence-editor.js";
+
+describe("geofence-editor", () => {
+ test("validates role gating for admin vs viewer", () => {
+ expect(isEditableRole("admin")).toBe(true);
+ expect(isEditableRole("super_admin")).toBe(true);
+ expect(isEditableRole("viewer")).toBe(false);
+ expect(isEditableRole("")).toBe(false);
+ });
+
+ test("closes drawn polygon ring and batches multiple geofences into one fill + outline", () => {
+ const poly = buildClosedPolygonGeoJson([
+ { lat: 1.1, lon: 103.5 },
+ { lat: 1.5, lon: 103.5 },
+ { lat: 1.5, lon: 104.0 },
+ ]);
+ expect(poly.type).toBe("Polygon");
+ expect(poly.coordinates[0]).toHaveLength(4);
+ expect(poly.coordinates[0][0]).toEqual(poly.coordinates[0][3]);
+
+ const batch = buildGeofenceBatchBuffers([
+ { id: 1, kind: "preset", enabled: true, geometry: poly },
+ {
+ id: 2,
+ kind: "custom",
+ enabled: true,
+ geometry: {
+ type: "Polygon",
+ coordinates: [[[2.0, 100.0], [2.4, 100.0], [2.4, 100.5], [2.0, 100.5], [2.0, 100.0]]],
+ },
+ },
+ ]);
+ expect(batch.fillPositions.length).toBe(3 * 9 + 4 * 9);
+ expect(batch.linePositions.length).toBe(3 * 6 + 4 * 6);
+
+ const earth = new THREE.Group();
+ const mgr = createGeofenceLayerManager({ getEarth: () => earth });
+ mgr.setGeofences([{ id: 1, kind: "preset", enabled: true, geometry: poly }]);
+ expect(mgr.getStats().hasFillMesh).toBe(true);
+ expect(mgr.getStats().hasOutlineMesh).toBe(true);
+ mgr.dispose();
+ expect(mgr.getStats().hasFillMesh).toBe(false);
+ expect(earth.children).toHaveLength(0);
+ });
+});
diff --git a/frontend/public/earth/js/gps-jamming-math.js b/frontend/public/earth/js/gps-jamming-math.js
new file mode 100644
index 00000000..913a7992
--- /dev/null
+++ b/frontend/public/earth/js/gps-jamming-math.js
@@ -0,0 +1,102 @@
+// gps-jamming-math.js - Pure H3 polygon triangulation for GPS/GNSS jamming layer
+
+// Raise slightly above EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET (0.48) to clear H3 res-4 chord sagitta (~0.009)
+export const GPS_JAMMING_RADIUS_OFFSET = 0.515;
+
+export const GPS_JAMMING_COLORS = Object.freeze({
+ high: [0.94, 0.24, 0.24, 0.76],
+ medium: [0.98, 0.58, 0.05, 0.58],
+ low: [0.95, 0.80, 0.08, 0.40],
+});
+
+const GPS_JAMMING_LEVEL_OFFSET = Object.freeze({
+ high: 0.525,
+ medium: 0.515,
+ low: 0.505,
+});
+
+function latLonToXYZ(lat, lon, radius) {
+ const phi = (90 - lat) * (Math.PI / 180);
+ const theta = (lon + 180) * (Math.PI / 180);
+ const sinPhi = Math.sin(phi);
+ return [
+ -(radius * sinPhi * Math.cos(theta)),
+ radius * Math.cos(phi),
+ radius * sinPhi * Math.sin(theta),
+ ];
+}
+
+function wrapLonNear(lon, refLon) {
+ let wrapped = lon;
+ while (wrapped - refLon > 180) wrapped -= 360;
+ while (wrapped - refLon < -180) wrapped += 360;
+ return wrapped;
+}
+
+export function buildGpsJammingGeometryBuffers(cells, { earthRadius = 100 } = {}) {
+ const list = Array.isArray(cells) ? cells : [];
+ const radius = earthRadius + GPS_JAMMING_RADIUS_OFFSET;
+ let totalTriangles = 0;
+ const normalizedCells = [];
+
+ for (let i = 0; i < list.length; i += 1) {
+ const cell = list[i];
+ const boundary = Array.isArray(cell?.boundary) ? cell.boundary : [];
+ const lat = Number(cell?.lat);
+ const lon = Number(cell?.lon);
+ if (boundary.length < 3 || !Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ totalTriangles += boundary.length;
+ normalizedCells.push({
+ ...cell,
+ lat,
+ lon,
+ boundary: boundary.map(([bLat, bLon]) => [Number(bLat), wrapLonNear(Number(bLon), lon)]),
+ });
+ }
+
+ const positions = new Float32Array(totalTriangles * 9);
+ const colors = new Float32Array(totalTriangles * 12);
+ let posOffset = 0;
+ let colOffset = 0;
+
+ for (let c = 0; c < normalizedCells.length; c += 1) {
+ const cell = normalizedCells[c];
+ const levelKey = String(cell.level || "low").toLowerCase();
+ const rgba = GPS_JAMMING_COLORS[levelKey] || GPS_JAMMING_COLORS.low;
+ const cellRadius = earthRadius + (GPS_JAMMING_LEVEL_OFFSET[levelKey] ?? GPS_JAMMING_RADIUS_OFFSET);
+ const center = latLonToXYZ(cell.lat, cell.lon, cellRadius);
+ const ring = cell.boundary;
+ const ringLen = ring.length;
+
+ for (let k = 0; k < ringLen; k += 1) {
+ const p1 = ring[k];
+ const p2 = ring[(k + 1) % ringLen];
+ const v1 = latLonToXYZ(p1[0], p1[1], cellRadius);
+ const v2 = latLonToXYZ(p2[0], p2[1], cellRadius);
+
+ positions[posOffset++] = center[0];
+ positions[posOffset++] = center[1];
+ positions[posOffset++] = center[2];
+ positions[posOffset++] = v1[0];
+ positions[posOffset++] = v1[1];
+ positions[posOffset++] = v1[2];
+ positions[posOffset++] = v2[0];
+ positions[posOffset++] = v2[1];
+ positions[posOffset++] = v2[2];
+
+ for (let v = 0; v < 3; v += 1) {
+ colors[colOffset++] = rgba[0];
+ colors[colOffset++] = rgba[1];
+ colors[colOffset++] = rgba[2];
+ colors[colOffset++] = rgba[3];
+ }
+ }
+ }
+
+ return {
+ vertexCount: totalTriangles * 3,
+ positions,
+ colors,
+ cellsMeta: normalizedCells,
+ };
+}
diff --git a/frontend/public/earth/js/gps-jamming-worker.js b/frontend/public/earth/js/gps-jamming-worker.js
new file mode 100644
index 00000000..e85c83c4
--- /dev/null
+++ b/frontend/public/earth/js/gps-jamming-worker.js
@@ -0,0 +1,27 @@
+// gps-jamming-worker.js - Web Worker for H3 hexagon fan triangulation
+import { buildGpsJammingGeometryBuffers } from "./gps-jamming-math.js";
+
+self.addEventListener("message", (event) => {
+ const { id, type, cells, earthRadius } = event.data || {};
+ if (type !== "triangulate") return;
+ try {
+ const result = buildGpsJammingGeometryBuffers(cells, { earthRadius });
+ self.postMessage(
+ {
+ id,
+ ok: true,
+ vertexCount: result.vertexCount,
+ positions: result.positions,
+ colors: result.colors,
+ cellsMeta: result.cellsMeta,
+ },
+ [result.positions.buffer, result.colors.buffer],
+ );
+ } catch (error) {
+ self.postMessage({
+ id,
+ ok: false,
+ error: error?.message || String(error),
+ });
+ }
+});
diff --git a/frontend/public/earth/js/gps-jamming.js b/frontend/public/earth/js/gps-jamming.js
new file mode 100644
index 00000000..a0a65eee
--- /dev/null
+++ b/frontend/public/earth/js/gps-jamming.js
@@ -0,0 +1,241 @@
+// gps-jamming.js - Single-mesh H3 GNSS/GPS interference overlay (R+0.515, renderOrder 0.968)
+import * as THREE from "three";
+import { CONFIG, PATHS } from "./constants.js";
+import { buildGpsJammingGeometryBuffers } from "./gps-jamming-math.js";
+
+const GPS_JAMMING_RENDER_ORDER = 0.968;
+
+const GPS_JAMMING_VERT = `
+ uniform float uEarthRadius;
+ varying vec4 vColor;
+ void main() {
+ float offset = length(position) - uEarthRadius;
+ if (offset > 0.520) {
+ vColor = vec4(0.94, 0.24, 0.24, 0.76);
+ } else if (offset > 0.510) {
+ vColor = vec4(0.98, 0.58, 0.05, 0.58);
+ } else {
+ vColor = vec4(0.95, 0.80, 0.08, 0.40);
+ }
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+ }
+`;
+
+const GPS_JAMMING_FRAG = `
+ varying vec4 vColor;
+ void main() {
+ gl_FragColor = vColor;
+ }
+`;
+
+let showGpsJamming = false;
+let jammingGroup = null;
+let jammingMesh = null;
+let jammingMaterial = null;
+let workerInstance = null;
+let workerRequestId = 0;
+let loadGeneration = 0;
+let cellsMeta = [];
+let latestSnapshotMeta = {
+ date: null,
+ stats: { total: 0, high: 0, medium: 0, low: 0 },
+};
+let earthRef = null;
+
+function getOrCreateWorker() {
+ if (typeof Worker === "undefined") return null;
+ if (!workerInstance) {
+ workerInstance = new Worker(new URL("./gps-jamming-worker.js", import.meta.url), {
+ type: "module",
+ });
+ }
+ return workerInstance;
+}
+
+function terminateWorker() {
+ if (workerInstance) {
+ workerInstance.terminate();
+ workerInstance = null;
+ }
+}
+
+async function triangulateInWorkerOrMain(cells) {
+ const worker = getOrCreateWorker();
+ if (!worker) {
+ return buildGpsJammingGeometryBuffers(cells, { earthRadius: CONFIG.earthRadius });
+ }
+ const reqId = ++workerRequestId;
+ return new Promise((resolve, reject) => {
+ const onMessage = (event) => {
+ const msg = event.data;
+ if (!msg || msg.id !== reqId) return;
+ worker.removeEventListener("message", onMessage);
+ worker.removeEventListener("error", onError);
+ if (msg.ok) resolve(msg);
+ else reject(new Error(msg.error || "GPS jamming worker failed"));
+ };
+ const onError = (err) => {
+ worker.removeEventListener("message", onMessage);
+ worker.removeEventListener("error", onError);
+ reject(err);
+ };
+ worker.addEventListener("message", onMessage);
+ worker.addEventListener("error", onError);
+ worker.postMessage({
+ id: reqId,
+ type: "triangulate",
+ cells,
+ earthRadius: CONFIG.earthRadius,
+ });
+ });
+}
+
+function applyTriangulatedMesh(buffers, earth) {
+ if (!showGpsJamming || !earth) return;
+ cellsMeta = Array.isArray(buffers.cellsMeta) ? buffers.cellsMeta : [];
+
+ if (!jammingGroup) {
+ jammingGroup = new THREE.Object3D();
+ jammingGroup.name = "gps-jamming-layer-group";
+ earth.add(jammingGroup);
+ }
+
+ const geom = new THREE.BufferGeometry();
+ geom.setAttribute("position", new THREE.BufferAttribute(buffers.positions, 3));
+ geom.setDrawRange(0, buffers.vertexCount);
+ geom.computeBoundingSphere();
+
+ if (!jammingMaterial) {
+ jammingMaterial = new THREE.ShaderMaterial({
+ uniforms: {
+ uEarthRadius: { value: Number(CONFIG.earthRadius) || 100.0 },
+ },
+ vertexShader: GPS_JAMMING_VERT,
+ fragmentShader: GPS_JAMMING_FRAG,
+ transparent: true,
+ depthTest: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ polygonOffset: true,
+ polygonOffsetFactor: -2,
+ polygonOffsetUnits: -2,
+ });
+ }
+
+ if (!jammingMesh) {
+ jammingMesh = new THREE.Mesh(geom, jammingMaterial);
+ jammingMesh.renderOrder = GPS_JAMMING_RENDER_ORDER;
+ jammingMesh.frustumCulled = false;
+ jammingMesh.raycast = () => {};
+ jammingGroup.add(jammingMesh);
+ } else {
+ const prevGeom = jammingMesh.geometry;
+ jammingMesh.geometry = geom;
+ prevGeom?.dispose?.();
+ }
+ jammingGroup.visible = showGpsJamming && buffers.vertexCount > 0;
+}
+
+export function getShowGpsJamming() {
+ return showGpsJamming;
+}
+
+export function getGpsJammingCount() {
+ return cellsMeta.length;
+}
+
+export function getGpsJammingSnapshotMeta() {
+ return latestSnapshotMeta;
+}
+
+export function clearGpsJammingData(earth = earthRef) {
+ loadGeneration += 1;
+ terminateWorker();
+ if (jammingMesh) {
+ jammingMesh.geometry?.dispose?.();
+ jammingMesh.parent?.remove(jammingMesh);
+ jammingMesh = null;
+ }
+ if (jammingMaterial) {
+ jammingMaterial.dispose?.();
+ jammingMaterial = null;
+ }
+ if (jammingGroup) {
+ jammingGroup.parent?.remove(jammingGroup);
+ jammingGroup = null;
+ }
+ if (earth && jammingGroup?.parent === earth) {
+ earth.remove(jammingGroup);
+ }
+ cellsMeta = [];
+}
+
+export function toggleGpsJamming(show, earth = earthRef) {
+ showGpsJamming = Boolean(show);
+ if (earth) earthRef = earth;
+ if (!showGpsJamming) {
+ clearGpsJammingData(earthRef);
+ return;
+ }
+ if (jammingGroup) jammingGroup.visible = true;
+}
+
+export async function loadGpsJamming(_scene, earth) {
+ if (earth) earthRef = earth;
+ if (!showGpsJamming || !earthRef) return { totalCount: 0 };
+ const gen = ++loadGeneration;
+ const resp = await fetch(PATHS.gpsJammingSnapshotApi, { cache: "no-store" });
+ if (!resp.ok) throw new Error(`GPS jamming HTTP ${resp.status}`);
+ const payload = await resp.json();
+ if (gen !== loadGeneration || !showGpsJamming) return { totalCount: 0 };
+
+ latestSnapshotMeta = {
+ date: payload?.date || null,
+ stats: payload?.stats || { total: 0, high: 0, medium: 0, low: 0 },
+ };
+ const cells = Array.isArray(payload?.cells) ? payload.cells : [];
+ const buffers = await triangulateInWorkerOrMain(cells);
+ if (gen !== loadGeneration || !showGpsJamming) return { totalCount: 0 };
+
+ applyTriangulatedMesh(buffers, earthRef);
+ return {
+ totalCount: cellsMeta.length,
+ date: latestSnapshotMeta.date,
+ stats: latestSnapshotMeta.stats,
+ };
+}
+
+function pointInRing(lat, lon, ring) {
+ let inside = false;
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
+ const yi = ring[i][0];
+ const xi = ring[i][1];
+ const yj = ring[j][0];
+ const xj = ring[j][1];
+ const intersect = (yi > lat) !== (yj > lat) && lon < ((xj - xi) * (lat - yi)) / ((yj - yi) || 1e-9) + xi;
+ if (intersect) inside = !inside;
+ }
+ return inside;
+}
+
+export function findGpsJammingCellAtLatLon(lat, lon) {
+ if (!showGpsJamming || !cellsMeta.length || !Number.isFinite(lat) || !Number.isFinite(lon)) {
+ return null;
+ }
+ for (let i = 0; i < cellsMeta.length; i += 1) {
+ const cell = cellsMeta[i];
+ if (Math.abs(cell.lat - lat) > 2.2 || Math.abs(cell.lon - lon) > 3.2) continue;
+ if (Array.isArray(cell.boundary) && pointInRing(lat, lon, cell.boundary)) {
+ return cell;
+ }
+ }
+ return null;
+}
+
+export function getGpsJammingLegendItems() {
+ return [
+ { key: "high", label: "强干扰 (>10%)", color: "#ef4444", shape: "dot" },
+ { key: "medium", label: "中干扰 (2%-10%)", color: "#f59e0b", shape: "dot" },
+ { key: "low", label: "低干扰 (<2%)", color: "#eab308", shape: "dot" },
+ ];
+}
diff --git a/frontend/public/earth/js/hud-focus-stack.js b/frontend/public/earth/js/hud-focus-stack.js
index b72cf5c3..bc0977ec 100644
--- a/frontend/public/earth/js/hud-focus-stack.js
+++ b/frontend/public/earth/js/hud-focus-stack.js
@@ -27,6 +27,7 @@ const DYNAMIC_CARD_SELECTOR = [
".news-region-card",
"#info-panel",
"#news-hud-panel",
+ "#source-freshness-popover",
"#situational-copilot",
".compute-picker",
"#media-panel",
diff --git a/frontend/public/earth/js/i18n.js b/frontend/public/earth/js/i18n.js
index 44cfad7c..50000fb6 100644
--- a/frontend/public/earth/js/i18n.js
+++ b/frontend/public/earth/js/i18n.js
@@ -36,6 +36,18 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: "正在加载船只数据...",
en: "Loading vessel data...",
},
+ "loading.aircraftData": {
+ zh: "正在加载航空器 ADS-B 数据...",
+ en: "Loading aircraft ADS-B data...",
+ },
+ "loading.gpsJammingData": {
+ zh: "正在加载 GPS 干扰数据...",
+ en: "Loading GPS jamming data...",
+ },
+ "loading.disastersData": {
+ zh: "正在加载自然灾害数据...",
+ en: "Loading natural disaster data...",
+ },
"loading.satelliteData": {
zh: "正在加载卫星数据...",
en: "Loading satellite data...",
@@ -68,6 +80,26 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: "正在加载船只...",
en: "Loading vessels...",
},
+ "startup.aircraft": {
+ zh: "正在加载航空器...",
+ en: "Loading aircraft...",
+ },
+ "startup.gpsJamming": {
+ zh: "正在加载 GPS 干扰热区...",
+ en: "Loading GPS interference cells...",
+ },
+ "startup.disasters": {
+ zh: "正在加载自然灾害态势...",
+ en: "Loading natural disaster telemetry...",
+ },
+ "startup.geofences": {
+ zh: "正在加载电子围栏...",
+ en: "Loading geofences...",
+ },
+ "startup.fusionOverlays": {
+ zh: "正在加载多域关联与影响链...",
+ en: "Loading fusion correlations & dependency arcs...",
+ },
"startup.bgp": {
zh: "正在加载BGP态势...",
en: "Loading BGP situation...",
@@ -188,6 +220,26 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: ({ detail }) => `高精国界不可用:${detail}`,
en: ({ detail }) => `High-precision boundaries unavailable: ${detail}`,
},
+ "status.viewMode2d": {
+ zh: "已切换至 2D 平面地图",
+ en: "Switched to 2D flat map view",
+ },
+ "status.viewMode3d": {
+ zh: "已返回 3D 地球视图",
+ en: "Returned to 3D globe view",
+ },
+ "status.replayEntered": {
+ zh: "4D 时空回放已启用",
+ en: "4D Replay active",
+ },
+ "status.replayExited": {
+ zh: "已恢复实时态势",
+ en: "Returned to Live",
+ },
+ "status.viewMode2dFailed": {
+ zh: "2D 平面地图加载失败,已保留 3D 地球视图",
+ en: "2D flat map failed to load; keeping 3D globe view",
+ },
"status.cameraModeDetected": {
zh: ({ count, mode }) => `检测到 ${count} 个物理摄像头:${mode === "dual" ? "双摄 3D" : "单摄 2D"}`,
en: ({ count, mode }) => `${count} physical cameras detected: ${mode === "dual" ? "Dual 3D" : "Single 2D"}`,
@@ -326,6 +378,10 @@ const EARTH_MESSAGE_TEMPLATES = {
zh: "动捕识别动作已更新",
en: "Motion gestures updated",
},
+ "status.cacheCleared": {
+ zh: "本地资源缓存已清理",
+ en: "Local asset cache cleared",
+ },
"status.settingsReset": {
zh: "设置已重置",
en: "Settings reset",
@@ -527,6 +583,46 @@ const EARTH_MESSAGE_TEMPLATES = {
};
const EXACT_TRANSLATIONS = {
+ "查看各域数据源健康与情报盲区": "Inspect domain source health and intelligence blind spots",
+ "数据源健康 · 检测中": "Source health · Checking",
+ "数据源健康与盲区": "Source Health & Blind Spots",
+ "非最新域不可描述为无事件": "Non-fresh domains must not be reported as event-free",
+ "立即刷新": "Refresh now",
+ "自然灾害": "Natural Disasters",
+ "地震、林火热点与灾难预警": "Earthquakes, wildfire clusters & disaster alerts",
+ "切换自然灾害显示": "Toggle natural disasters layer",
+ "隐藏自然灾害": "Hide natural disasters",
+ "显示自然灾害": "Show natural disasters",
+ "自然灾害加载中...": "Loading natural disasters...",
+ "自然灾害详情": "Natural Disaster Details",
+ "事件标题": "Event Title",
+ "灾害类型": "Disaster Type",
+ "严重程度": "Severity",
+ "震级 / 强度": "Magnitude / Intensity",
+ "火点簇规模": "Hotspot Cluster Count",
+ "最高亮温": "Max Brightness Temp",
+ "地震": "Earthquake",
+ "林火热点簇": "Wildfire Cluster",
+ "热带气旋/风暴": "Cyclone / Storm",
+ "洪涝灾害": "Flood",
+ "火山活动": "Volcano",
+ "干旱": "Drought",
+ "其他自然异常": "Other Hazard",
+ "NGA 海缆告警": "NGA Cable Advisory",
+ "告警出处": "Advisory Source",
+ "无活跃 NGA 海缆通告": "No active NGA cable advisory",
+ "军舰/特种角色": "Naval / Special Role",
+ "海缆工程船": "Cable Repair Ship",
+ "所在咽喉要道": "Maritime Chokepoint",
+ "海上咽喉要道": "Maritime Chokepoints",
+ "战区": "Theater",
+ "战区预设": "Theater Presets",
+ "按重点战区态势筛选。": "Filter news by regional theater.",
+ "俄乌": "Russia-Ukraine",
+ "中东": "Middle East",
+ "印太": "Indo-Pacific",
+ "未分级": "Unrated",
+ "国家背景": "State-Affiliated",
"城市地名标注": "City labels",
"放大地球时逐级显示首都、主要城市与省会名称": "Reveal capitals, major cities, and regional capitals progressively on zoom",
"放大地球时逐级显示首都与主要城市": "Reveal capitals and major cities on zoom",
@@ -1656,6 +1752,102 @@ const EXACT_TRANSLATIONS = {
"加入多物件对比分析": "Add to joint comparison",
"未定位集群": "Unlocated Cluster",
"跨国部署提醒:实证位置与源登记国不同,请核对后采用": "Cross-country deployment notice: verified location differs from registered country; review manually before applying",
+ "本地资源缓存": "Local Asset Cache",
+ "清理缓存": "Clear Cache",
+ "正在清理…": "Clearing…",
+ "当前占用:计算中…": "Used: Calculating…",
+ "当前占用:0 B": "Used: 0 B",
+ "2D 平面地图": "2D Flat Map",
+ "切换 2D 平面视图": "Switch to 2D flat view",
+ "返回 3D 地球视图": "Return to 3D globe view",
+ "已放大至极限 · 切换 2D 平面视图继续放大": "Max 3D zoom reached · Switch to 2D view to zoom further",
+ "关闭提示": "Dismiss prompt",
+ "工作流空间态势卡片": "Workflow Spatial Comparison Cards",
+ "关联目标样本": "Entity Samples",
+ "暂无关联样本": "No linked samples",
+ "时序走廊": "Corridor Timeline",
+ "双边对比比例尺": "Bilateral Duel Scale",
+ "结构构成": "Composition",
+ "电子围栏": "Geofences",
+ "海缆走廊与咽喉监测区": "Cable corridor & chokepoint watchzones",
+ "切换电子围栏显示": "Toggle geofences display",
+ "显示电子围栏": "Show geofences",
+ "隐藏电子围栏": "Hide geofences",
+ "电子围栏加载中...": "Loading geofences...",
+ "态势事件与围栏处置": "Incidents & Geofences",
+ "打开态势事件与围栏处置": "Open incidents & geofences drawer",
+ "态势事件与围栏": "Incidents & Geofences",
+ "绘制电子围栏": "Draw Geofence",
+ "输入围栏名称": "Geofence name",
+ "保存围栏": "Save Polygon",
+ "取消": "Cancel",
+ "规则告警": "Rule Alert",
+ "待核查": "Pending Verification",
+ "依赖影响": "Dependency Impact",
+ "驳回": "Dismiss",
+ "解决": "Resolve",
+ "提交驳回": "Submit Dismiss",
+ "必填驳回理由": "Required dismissal reason",
+ "当前暂无活跃态势事件": "No active situational incidents",
+ "请在地球表面依次点击至少 3 个顶点": "Click at least 3 vertices on the globe",
+ "电子围栏已保存": "Geofence saved",
+ "事件状态已更新": "Incident updated",
+ "事件已驳回": "Incident dismissed",
+ "驳回必须填写理由": "Dismissal requires a reason",
+ "预置围栏(海缆/咽喉)": "Preset (Cables / Chokepoints)",
+ "自定义多边形围栏": "Custom Polygon Geofence",
+ "关联与影响链": "Correlations & Impact Chains",
+ "H3 待核查关联与海缆影响链": "H3 candidate correlations & cable impact chains",
+ "切换关联与影响链显示": "Toggle correlations & impact chains",
+ "显示关联与影响链": "Show correlations & impact chains",
+ "隐藏关联与影响链": "Hide correlations & impact chains",
+ "关联与影响链加载中...": "Loading correlations & impact chains...",
+ "待核查关联(虚线六边形 · 待核查)": "Candidate Correlation (Dashed Hex · Pending)",
+ "依赖影响链(实线弧 · 有独立证据)": "Dependency Impact Chain (Solid Arc · Corroborated)",
+ "4D 时空回放": "4D Replay",
+ "四维时空回放轴": "4D Spatiotemporal Replay",
+ "打开四维时空回放": "Open 4D Replay Timeline",
+ "实时态": "LIVE",
+ "回放态": "REPLAY",
+ "进入回放": "Enter Replay",
+ "返回实时": "Return Live",
+ "播放": "Play",
+ "暂停": "Pause",
+ "倍速": "Speed",
+ "时间滑块": "Time Scrubber",
+ "全历史": "All",
+ "实体关系图谱": "Ontology Graph",
+ "打开实体关系图谱": "Open Ontology Graph",
+ "关系图谱": "Ontology Graph",
+ "调查卷宗工作台": "Investigation Cases",
+ "调查卷宗": "Investigation Cases",
+ "打开调查卷宗工作台": "Open Investigation Cases",
+ "加入卷宗": "Add to Case",
+ "动作审批中心": "Action Approvals",
+ "动作审批": "Actions",
+ "动作与审批": "Actions",
+ "打开动作审批中心": "Open Action Approvals",
+ "新建卷宗标题(如:亚太海缆异常研判)": "New case title",
+ "创建卷宗": "New Case",
+ "固化不可变版本": "Freeze Version",
+ "导出 Markdown": "Export MD",
+ "打印 / PDF 报告": "Print / PDF",
+ "外发告警通知 (需审批)": "Notify Webhook (Approval)",
+ "加入重点关注": "Add to Watchlist",
+ "发起动作": "Submit Action",
+ "批准执行": "Approve",
+ "4D 时空回放已启用": "4D Replay active",
+ "已恢复实时态势": "Returned to Live",
+ "航空器": "Aircraft",
+ "军机与民航 ADS-B": "Military & Civil ADS-B",
+ "全球军机与民航 ADS-B": "Global Military & Civil ADS-B",
+ "GPS 干扰": "GPS Jamming",
+ "GNSS 干扰监测热区": "GNSS interference zones",
+ "GNSS 信号干扰热区": "GNSS signal interference zones",
+ "已启用 0 个图层": "0 layers enabled",
+ "切换航空器显示": "Toggle aircraft display",
+ "切换 GPS 干扰显示": "Toggle GPS jamming display",
+ "切换 BGP 观测显示": "Toggle BGP observation display",
};
const PATTERN_TRANSLATIONS = [
@@ -1763,6 +1955,8 @@ const PATTERN_TRANSLATIONS = [
[/^(\d+) 分钟前$/, "$1m ago"],
[/^新闻源请求失败: (\d+)$/, "News request failed: $1"],
[/^来源 (.+)$/, "Source $1"],
+ [/^当前占用:(.+)((\d+) 项)$/, "Used: $1 ($2 items)"],
+ [/^当前占用:(.+)$/, "Used: $1"],
[/^更新 (.+)$/, "Updated $1"],
[/^置信 (.+)$/, "Confidence $1"],
[/^已复制(.+):(.+)$/, (match, locale) => `Copied ${translateText(match[1], locale)}: ${match[2]}`],
diff --git a/frontend/public/earth/js/incidents-hud.js b/frontend/public/earth/js/incidents-hud.js
new file mode 100644
index 00000000..4af03a81
--- /dev/null
+++ b/frontend/public/earth/js/incidents-hud.js
@@ -0,0 +1,269 @@
+import { getEarthLocale, translateText } from "./i18n.js";
+import { createHUDPanel } from "./hud-panels.js";
+import { sharedHudFocusStack } from "./hud-focus-stack.js";
+import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js";
+import { isEditableRole } from "./geofence-editor.js";
+
+const t = (zh, en) => (getEarthLocale() === "en-US" ? en : zh);
+
+function escapeHtml(text) {
+ return String(text ?? "")
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll('"', """);
+}
+
+function assessmentBadge(kind) {
+ if (kind === "dependency_impact") {
+ return { cls: "is-impact", label: t("依赖影响", "Dependency Impact") };
+ }
+ if (kind === "candidate_correlation") {
+ return { cls: "is-candidate", label: t("待核查", "Pending Verification") };
+ }
+ return { cls: "is-rule", label: t("规则告警", "Rule Alert") };
+}
+
+export function initIncidentsHud({
+ rootParent = typeof document !== "undefined" ? document.body : null,
+ geofenceManager = null,
+ onSelectIncident = null,
+ onIncidentsChanged = null,
+ onStatus = null,
+} = {}) {
+ const panelEl = document.createElement("aside");
+ panelEl.id = "incidents-triage-hud";
+ panelEl.className = "hud-panel incidents-hud-panel hud-panel-draggable";
+ panelEl.hidden = true;
+ panelEl.setAttribute("role", "dialog");
+ panelEl.setAttribute("aria-modal", "false");
+ panelEl.setAttribute("aria-label", t("态势事件与围栏处置", "Incidents & Geofences"));
+
+ panelEl.innerHTML = `
+
+
+ notifications_active
+
${escapeHtml(t("态势事件与围栏处置", "Incidents & Geofences"))}
+
+
+
+
+
+
+
+
+ `;
+
+ rootParent?.append?.(panelEl);
+ const hudPanel = createHUDPanel({
+ panel: panelEl,
+ header: ".hud-panel__header",
+ body: "#incidents-hud-list",
+ });
+ sharedHudFocusStack.register(panelEl, { focus: false });
+
+ const listEl = panelEl.querySelector("#incidents-hud-list");
+ const drawBtn = panelEl.querySelector("#geofence-draw-toggle");
+ const drawControls = panelEl.querySelector("#geofence-draw-controls");
+ const drawNameInput = panelEl.querySelector("#geofence-draw-name");
+ const drawSaveBtn = panelEl.querySelector("#geofence-draw-save");
+ const drawCancelBtn = panelEl.querySelector("#geofence-draw-cancel");
+ const drawStatus = panelEl.querySelector("#geofence-draw-status");
+
+ let items = [];
+ let dismissingId = null;
+
+ const syncRoleUi = () => {
+ const editable = isEditableRole(readStoredAdminAuthState()?.user?.role);
+ if (drawBtn) {
+ drawBtn.hidden = !editable;
+ }
+ };
+
+ const renderList = () => {
+ syncRoleUi();
+ const editable = isEditableRole(readStoredAdminAuthState()?.user?.role);
+ if (!listEl) return;
+ if (!items.length) {
+ listEl.innerHTML = `${escapeHtml(t("当前暂无活跃态势事件", "No active situational incidents"))}
`;
+ return;
+ }
+ listEl.innerHTML = items
+ .map((item) => {
+ const badge = assessmentBadge(item.assessment_kind);
+ const objs = Array.isArray(item.object_ids) ? item.object_ids.slice(0, 4) : [];
+ const isDismissing = dismissingId === item.id;
+ return `
+
+ ${escapeHtml(badge.label)}
+ ${escapeHtml(translateText(item.status || "open"))}
+
+ ${escapeHtml(item.title || item.incident_type)}
+ ${objs.length ? `${objs.map((o) => ``).join("")}
` : ""}
+ ${item.resolution_note ? `${escapeHtml(item.resolution_note)}
` : ""}
+ ${
+ editable
+ ? `
+
+
+
+
`
+ : ""
+ }
+ ${
+ editable && isDismissing
+ ? `
+
+
+
`
+ : ""
+ }
+ `;
+ })
+ .join("");
+ };
+
+ const refresh = async (fetchImpl = globalThis.fetch) => {
+ const resp = await fetchImpl("/api/v1/incidents?limit=60");
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const data = await resp.json();
+ items = Array.isArray(data?.items) ? data.items : [];
+ renderList();
+ return items;
+ };
+
+ const transition = async (id, action, reason = "") => {
+ const body = reason ? { resolution_note: reason } : {};
+ const resp = await fetchAdminWriteJson(`/api/v1/incidents/${id}/${action}`, body);
+ if (!resp.ok) {
+ const errTxt = await resp.text();
+ throw new Error(errTxt || `HTTP ${resp.status}`);
+ }
+ const updated = await resp.json();
+ dismissingId = null;
+ items = items.map((it) => (it.id === updated.id ? updated : it));
+ renderList();
+ await onIncidentsChanged?.(updated);
+ return updated;
+ };
+
+ panelEl.querySelector("#incidents-close-btn")?.addEventListener("click", () => {
+ panelEl.hidden = true;
+ });
+ panelEl.querySelector("#incidents-refresh-btn")?.addEventListener("click", () => {
+ void refresh().catch((err) => onStatus?.(err?.message || String(err), "error"));
+ });
+
+ drawBtn?.addEventListener("click", () => {
+ try {
+ geofenceManager?.startDrawing?.();
+ if (drawControls) drawControls.hidden = false;
+ if (drawStatus) drawStatus.textContent = t("请在地球表面依次点击至少 3 个顶点", "Click at least 3 vertices on the globe");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ });
+
+ drawCancelBtn?.addEventListener("click", () => {
+ geofenceManager?.cancelDrawing?.();
+ if (drawControls) drawControls.hidden = true;
+ if (drawStatus) drawStatus.textContent = "";
+ });
+
+ drawSaveBtn?.addEventListener("click", async () => {
+ try {
+ const name = String(drawNameInput?.value || "").trim() || `Custom Fence ${new Date().toISOString().slice(11, 16)}`;
+ await geofenceManager?.finishPolygon?.(name);
+ if (drawNameInput) drawNameInput.value = "";
+ if (drawControls) drawControls.hidden = true;
+ if (drawStatus) drawStatus.textContent = t("电子围栏已保存", "Geofence saved");
+ await onIncidentsChanged?.();
+ } catch (err) {
+ if (drawStatus) drawStatus.textContent = err?.message || String(err);
+ }
+ });
+
+ listEl?.addEventListener("click", async (event) => {
+ const target = event?.target;
+ if (!(target instanceof HTMLElement)) return;
+
+ const objBtn = target.closest("[data-object-id]");
+ if (objBtn instanceof HTMLElement) {
+ const oid = objBtn.dataset.objectId || "";
+ const found = items.find((i) => Array.isArray(i.object_ids) && i.object_ids.includes(oid));
+ onSelectIncident?.(found || null, oid);
+ return;
+ }
+
+ const actBtn = target.closest("[data-incident-action]");
+ if (!(actBtn instanceof HTMLElement)) return;
+ const action = actBtn.dataset.incidentAction;
+ const id = Number(actBtn.dataset.incidentId);
+ if (!Number.isFinite(id)) return;
+
+ if (action === "toggle-dismiss") {
+ dismissingId = dismissingId === id ? null : id;
+ renderList();
+ return;
+ }
+ if (action === "acknowledge" || action === "resolve") {
+ try {
+ await transition(id, action);
+ onStatus?.(t("事件状态已更新", "Incident updated"), "info");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ return;
+ }
+ if (action === "confirm-dismiss") {
+ const reasonInput = panelEl.querySelector(`[data-dismiss-reason-for="${id}"]`);
+ const reason = String(reasonInput?.value || "").trim();
+ if (!reason) {
+ onStatus?.(t("驳回必须填写理由", "Dismissal requires a reason"), "error");
+ return;
+ }
+ try {
+ await transition(id, "dismiss", reason);
+ onStatus?.(t("事件已驳回", "Incident dismissed"), "info");
+ } catch (err) {
+ onStatus?.(err?.message || String(err), "error");
+ }
+ }
+ });
+
+ const open = async () => {
+ panelEl.hidden = false;
+ sharedHudFocusStack.focus(panelEl);
+ await refresh().catch((err) => onStatus?.(err?.message || String(err), "error"));
+ };
+
+ const close = () => {
+ panelEl.hidden = true;
+ };
+
+ return {
+ open,
+ close,
+ refresh,
+ setVertexFeedback: (count) => {
+ if (drawStatus) drawStatus.textContent = t(`已拾取 ${count} 个顶点`, `${count} vertices picked`);
+ },
+ getItems: () => items,
+ destroy: () => {
+ hudPanel?.destroy?.();
+ panelEl.remove();
+ },
+ };
+}
diff --git a/frontend/public/earth/js/info-card.js b/frontend/public/earth/js/info-card.js
index 4d9a62d0..3ad7d4d2 100644
--- a/frontend/public/earth/js/info-card.js
+++ b/frontend/public/earth/js/info-card.js
@@ -450,6 +450,26 @@ function getMobileDetailIdentity(type, config, data) {
if (data?.status && data.status !== '-') {
metrics.push({ label: infoText('航行状态'), value: translateInfoCardValue(String(data.status)) });
}
+ } else if (type === 'aircraft') {
+ title = data?.callsign && data.callsign !== '-' ? `${data.callsign} (${data?.icao24 || ''})` : (data?.icao24 || infoText('航空器'));
+ categoryLabel = translateInfoCardValue(data?.category || 'aircraft');
+ subtitle = [data?.aircraft_type, data?.operator, data?.registration].filter((v) => v && v !== '-').join(' · ') || `ICAO24 ${data?.icao24 || '-'}`;
+ if (data?.is_emergency) {
+ statusBadge = `${infoText('紧急')} ${data?.emergency_code || '7700'}`;
+ statusBadgeType = 'critical';
+ } else if (data?.is_military) {
+ statusBadge = infoText('军机');
+ statusBadgeType = 'warning';
+ }
+ if (data?.altitude_m != null && data.altitude_m !== '-') {
+ metrics.push({ label: infoText('高度'), value: `${Math.round(Number(data.altitude_m))} m` });
+ }
+ if (data?.speed != null && data.speed !== '-') {
+ metrics.push({ label: infoText('地速'), value: `${Math.round(Number(data.speed))} km/h` });
+ }
+ if (data?.track != null && data.track !== '-') {
+ metrics.push({ label: infoText('航向'), value: `${Math.round(Number(data.track))}°` });
+ }
} else if (type === 'bgp') {
title = translateInfoCardValue(data?.anomaly_type) || infoText('BGP 路由事件');
categoryLabel = infoText('BGP 路由事件');
@@ -767,6 +787,16 @@ export function buildWorkbenchTarget(config, data) {
? `请结合近 60 分钟 AIS 遥测数据,分析船舶「${targetName}」的航行状态与海运态势。`
: '请结合 AIS 遥测数据,分析当前活跃海运船舶构型与在航态势。'),
};
+ case 'aircraft':
+ return {
+ domain: 'aircraft',
+ entityId: data.icao24 || data.callsign || null,
+ label: '在工作台分析空域',
+ icon: 'forum',
+ question: isEn
+ ? `Analyze the flight posture, altitude/track behavior, and regional airspace / GNSS context for aircraft "${targetName}".`
+ : `请结合 ADS-B 遥测数据与当前 GPS 干扰态势,分析航空器「${targetName}」的飞行动态与空域态势。`,
+ };
case 'supercomputer':
case 'gpu_cluster':
case 'data_center':
@@ -1767,6 +1797,7 @@ function getMobilePopupTitle(type, data) {
case 'cloud_center':
case 'edge_node': return data.name || infoText(COMPUTE_SITE_TYPES[type].label);
case 'vessel': return data.name || infoText('船只');
+ case 'aircraft': return data.callsign || data.icao24 || infoText('航空器');
case 'earth_interactable': return data.label || data.name || infoText('交互点');
default: return infoText('详情');
}
@@ -1787,6 +1818,7 @@ function getMobilePopupSubtitle(type, data) {
case 'cloud_center':
case 'edge_node': return localizeCountryName(data.country) || infoText(COMPUTE_SITE_TYPES[type].label);
case 'vessel': return data.vessel_type || infoText('AIS 船只');
+ case 'aircraft': return `${data.aircraft_type || data.category || 'ADS-B'} · ${data.icao24 || ''}`;
case 'earth_interactable': return infoText(data.kind || data.description || '数据点');
default: return '';
}
@@ -2017,7 +2049,9 @@ const CARD_CONFIG = {
{ key: 'status', label: '状态' },
{ key: 'length', label: '长度' },
{ key: 'owner', label: '所有者' },
- { key: 'rfs', label: '投入使用' }
+ { key: 'rfs', label: '投入使用' },
+ { key: 'advisory_summary', label: 'NGA 海缆告警' },
+ { key: 'advisory_source', label: '告警出处' }
]
},
landing_point: {
@@ -2183,7 +2217,49 @@ const CARD_CONFIG = {
{ key: 'flag', label: '旗帜' },
{ key: 'mmsi', label: 'MMSI' },
{ key: 'imo', label: 'IMO' },
- { key: 'length', label: '船长', unit: 'm' }
+ { key: 'length', label: '船长', unit: 'm' },
+ { key: 'military_role', label: '军舰/特种角色' },
+ { key: 'is_cable_ship', label: '海缆工程船' },
+ { key: 'chokepoint_name', label: '所在咽喉要道' }
+ ]
+ },
+ aircraft: {
+ icon: '✈',
+ title: '航空器详情',
+ className: 'aircraft',
+ fields: [
+ { key: 'callsign', label: '呼号' },
+ { key: 'icao24', label: 'ICAO24' },
+ { key: 'registration', label: '注册号' },
+ { key: 'aircraft_type', label: '机型' },
+ { key: 'operator', label: '运营方' },
+ { key: 'altitude_m', label: '高度', unit: 'm' },
+ { key: 'speed', label: '地速', unit: 'km/h' },
+ { key: 'track', label: '航向', unit: '°' },
+ { key: 'vertical_rate', label: '升降率', unit: 'm/s' },
+ { key: 'squawk', label: '应答机码' },
+ { key: 'source', label: '出处' },
+ { key: 'observed_at', label: '观测时间' },
+ { key: 'ingested_at', label: '入库时间' },
+ { key: 'freshness', label: '新鲜度' },
+ { key: 'attribution', label: '数据署名' }
+ ]
+ },
+ disaster: {
+ icon: '🌋',
+ title: '自然灾害详情',
+ className: 'disaster',
+ fields: [
+ { key: 'title', label: '事件标题' },
+ { key: 'event_type', label: '灾害类型' },
+ { key: 'severity', label: '严重程度' },
+ { key: 'magnitude', label: '震级 / 强度' },
+ { key: 'cluster_count', label: '火点簇规模' },
+ { key: 'max_brightness_k', label: '最高亮温', unit: 'K' },
+ { key: 'source', label: '出处' },
+ { key: 'observed_at', label: '观测时间' },
+ { key: 'ingested_at', label: '入库时间' },
+ { key: 'freshness', label: '新鲜度' }
]
},
earth_interactable: {
@@ -2324,6 +2400,15 @@ function mountCard() {
🛰️
${escapeInfoCardHtml(infoText('详情'))}