Compare commits

...
Author SHA1 Message Date
Antigravity AI 704bd45c75 feat(osm-search): implement OSM Search plugin with Bellingcat-style proximity [Minor]
- implement @worldwideview/wwv-plugin-osm-search package [Minor]
- add Next.js proxy route for Overpass API with mirror fallback [Patch]
- implement real-time bounding box selection with dynamic updates [Patch]
- implement advanced proximity intersection mode using 'around' queries [Minor]
- fix core rendering issues (visibility, depth-test, eyeOffset) [Patch]
- refactor viewer initialization for instant plugin loading [Patch]
- align Cesium/Resium versions and fix JSDOM localStorage tests [Patch]
2026-04-15 16:53:31 +12:00
Antigravity AI 77138a93b0 feat(osm): register osm search plugin 2026-04-15 12:13:40 +12:00
Antigravity AI 36076ffd4d feat(osm): implement sidebar and search query builder 2026-04-15 12:06:11 +12:00
Antigravity AI ea9a73a853 feat(api): overpass dumb proxy 2026-04-15 12:02:27 +12:00
Antigravity AI 15be2a333c feat(osm): implement locking b-box overlay 2026-04-15 12:00:18 +12:00
Antigravity AI 1a6d234560 feat(osm): setup plugin shell and state 2026-04-15 12:00:04 +12:00
24 changed files with 960 additions and 89 deletions

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ const nextConfig: NextConfig = {
"@worldwideview/wwv-plugin-international-sanctions",
"@worldwideview/wwv-plugin-sdk",
"@worldwideview/wwv-plugin-wildfire",
"@worldwideview/wwv-plugin-osm-search",
"resium",
"react-player",
"satellite.js"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "1.8.1",
"version": "1.8.2",
"private": true,
"scripts": {
"setup": "node scripts/setup.mjs",
@@ -0,0 +1,19 @@
{
"name": "@worldwideview/wwv-plugin-osm-search",
"version": "1.1.0",
"description": "OSM Search Plugin for WorldWideView",
"main": "src/index.ts",
"type": "module",
"dependencies": {
"@worldwideview/wwv-plugin-sdk": "workspace:*",
"cesium": "^1.139.0",
"lucide-react": "^0.576.0",
"react": "19.2.3",
"resium": "1.19.4",
"zustand": "^5.0.11"
},
"devDependencies": {
"@types/react": "^19.0.2",
"typescript": "^5.4.5"
}
}
@@ -0,0 +1,83 @@
import React, { useEffect, useMemo } from "react";
import { Color, Cartesian3, Rectangle, PolygonHierarchy, ClassificationType, ArcType } from "cesium";
import { Entity, PolygonGraphics, PolylineGraphics, CustomDataSource } from "resium";
import { useOsmStore } from "../store";
export function OSMBboxOverlay({ viewer, enabled }: { viewer: any; enabled: boolean }) {
const { bboxLocked, showBbox, lockedBbox, currentBbox, setCurrentBbox } = useOsmStore();
useEffect(() => {
if (!viewer || !enabled) return;
const updateBbox = () => {
if (bboxLocked) return;
const rect = viewer.camera.computeViewRectangle(viewer.scene.globe.ellipsoid);
if (rect) {
const marginLat = (rect.north - rect.south) * 0.15;
const marginLon = (rect.east - rect.west) * 0.15;
setCurrentBbox(new Rectangle(
rect.west + marginLon, rect.south + marginLat,
rect.east - marginLon, rect.north - marginLat
));
}
};
// Use 'changed' for continuous updates during movement
viewer.camera.changed.addEventListener(updateBbox);
viewer.camera.moveEnd.addEventListener(updateBbox);
// Initial attempt
updateBbox();
// Temporary interval for 2 seconds to force updates while the globe/camera settles
const initInterval = setInterval(updateBbox, 100);
const timeout = setTimeout(() => clearInterval(initInterval), 2000);
return () => {
clearInterval(initInterval);
clearTimeout(timeout);
if (viewer && !viewer.isDestroyed()) {
viewer.camera.changed.removeEventListener(updateBbox);
viewer.camera.moveEnd.removeEventListener(updateBbox);
}
};
}, [viewer, enabled, bboxLocked, setCurrentBbox]);
const activeBbox = bboxLocked ? lockedBbox : currentBbox;
const positions = useMemo(() => {
if (!activeBbox) return [];
return Cartesian3.fromRadiansArray([
activeBbox.west, activeBbox.south,
activeBbox.east, activeBbox.south,
activeBbox.east, activeBbox.north,
activeBbox.west, activeBbox.north,
activeBbox.west, activeBbox.south,
]);
}, [activeBbox]);
// Don't render if layer is disabled OR if user has hidden the box
if (!enabled || !activeBbox || !showBbox) return null;
return (
<CustomDataSource name="OSMSearchBBox">
<Entity>
<PolygonGraphics
hierarchy={new PolygonHierarchy(positions)}
fill={true}
material={Color.RED.withAlpha(0.25)}
classificationType={ClassificationType.BOTH}
arcType={ArcType.GEODESIC}
height={0}
/>
<PolylineGraphics
positions={positions}
width={3}
material={Color.RED}
clampToGround={true}
arcType={ArcType.GEODESIC}
/>
</Entity>
</CustomDataSource>
);
}
@@ -0,0 +1,285 @@
import React, { useState } from "react";
import { Math as CesiumMath } from "cesium";
import { Eye, EyeOff } from "lucide-react";
import { useOsmStore } from "../store";
const COMMON_TAGS = [
"amenity=hospital", "amenity=school", "amenity=police", "amenity=fire_station",
"shop=supermarket", "highway=bus_stop", "building=house", "tourism=hotel",
"man_made=tower", "industrial=factory"
];
interface OSMSidebarProps {
plugin?: any; // OSMSearchPlugin
}
export function OSMSidebar({ plugin }: OSMSidebarProps) {
const { bboxLocked, showBbox, setShowBbox, setBboxLocked, currentBbox, setLockedBbox, lockedBbox } = useOsmStore();
const [mode, setMode] = useState<"bellingcat" | "turbo">("bellingcat");
const [rawQuery, setRawQuery] = useState("[out:json];\nnode[amenity=cafe]({{bbox}});\nout center;");
const [searchText, setSearchText] = useState("");
const [activeTags, setActiveTags] = useState<string[]>([]);
const [distance, setDistance] = useState(500);
const [isScanning, setIsScanning] = useState(false);
const toggleLock = () => {
if (!bboxLocked) {
setLockedBbox(currentBbox);
setBboxLocked(true);
} else {
setBboxLocked(false);
setLockedBbox(null);
}
};
const handleScan = async () => {
if (!bboxLocked) {
setLockedBbox(currentBbox);
setBboxLocked(true);
}
const bboxParams = lockedBbox || currentBbox;
if (!bboxParams) {
alert("Please wait for map viewport to initialize");
return;
}
// Overpass bbox order: south, west, north, east (in degrees)
const s = CesiumMath.toDegrees(bboxParams.south).toFixed(6);
const w = CesiumMath.toDegrees(bboxParams.west).toFixed(6);
const n = CesiumMath.toDegrees(bboxParams.north).toFixed(6);
const e = CesiumMath.toDegrees(bboxParams.east).toFixed(6);
const bboxString = `${s},${w},${n},${e}`;
let ql = "";
if (mode === "turbo") {
ql = rawQuery.replace(/{{bbox}}/g, bboxString);
} else {
// Bellingcat-style proximity search
if (activeTags.length === 1) {
const [key, val] = activeTags[0].split("=");
ql = `[out:json][timeout:25];
nwr["${key}"="${val}"](${bboxString});
out center;`;
} else if (activeTags.length > 1) {
// Chain search: Find A, then find B near A, then find C near B...
// Using .t0, .t1, .t2 as set names
ql = `[out:json][timeout:25];\n`;
activeTags.forEach((tag, idx) => {
const [key, val] = tag.split("=");
if (idx === 0) {
ql += `nwr["${key}"="${val}"](${bboxString})->.t0;\n`;
} else {
ql += `nwr["${key}"="${val}"](around.t${idx - 1}:${distance})->.t${idx};\n`;
}
});
// Final output: the last set in the chain
ql += `.t${activeTags.length - 1} out center;`;
}
}
setIsScanning(true);
try {
const res = await fetch("/api/plugins/osm-search", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: ql })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || "Search failed");
if (plugin?.pushResults && plugin?.mapOverpassToEntities) {
const entities = plugin.mapOverpassToEntities(data.data || []);
plugin.pushResults(entities);
} else {
console.warn("Plugin bridge not available in OSMSidebar", data.data);
}
} catch (err) {
console.error(err);
alert("Search failed: " + (err as Error).message);
} finally {
setIsScanning(false);
}
};
const renderedTags = searchText
? COMMON_TAGS.filter(t => t.toLowerCase().includes(searchText.toLowerCase()))
: COMMON_TAGS;
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<div style={{ background: "rgba(255,255,255,0.05)", padding: "10px", borderRadius: "6px", border: "1px solid rgba(255,255,255,0.1)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
<span style={{ fontSize: "12px", color: "var(--text-secondary)" }}>Viewport Bounding Box</span>
<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<button
onClick={() => setShowBbox(!showBbox)}
title={showBbox ? "Hide Box" : "Show Box"}
style={{
background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer",
display: "flex", alignItems: "center", padding: "2px"
}}
>
{showBbox ? <Eye size={14} /> : <EyeOff size={14} />}
</button>
<span style={{
fontSize: "10px",
padding: "2px 6px",
borderRadius: "10px",
background: bboxLocked ? "#ef444422" : "#22c55e22",
color: bboxLocked ? "#ef4444" : "#22c55e",
border: `1px solid ${bboxLocked ? "#ef444444" : "#22c55e44"}`
}}>
{bboxLocked ? "LOCKED" : "FOLLOWING"}
</span>
</div>
</div>
<button
onClick={toggleLock}
style={{
width: "100%",
padding: "6px",
background: "var(--bg-secondary)",
border: "1px solid var(--border-subtle)",
borderRadius: "4px",
color: "var(--text-primary)",
fontSize: "12px",
cursor: "pointer"
}}
>
{bboxLocked ? "Unlock Viewport" : "Lock Selection Box"}
</button>
</div>
<div style={{ display: "flex", gap: "4px", background: "rgba(0,0,0,0.2)", padding: "2px", borderRadius: "6px" }}>
<button
style={{
flex: 1,
padding: "6px",
border: "none",
borderRadius: "4px",
fontSize: "12px",
backgroundColor: mode === "bellingcat" ? "var(--bg-tertiary)" : "transparent",
color: mode === "bellingcat" ? "var(--text-primary)" : "var(--text-muted)",
cursor: "pointer"
}}
onClick={() => setMode("bellingcat")}
>
Quick Presets
</button>
<button
style={{
flex: 1,
padding: "6px",
border: "none",
borderRadius: "4px",
fontSize: "12px",
backgroundColor: mode === "turbo" ? "var(--bg-tertiary)" : "transparent",
color: mode === "turbo" ? "var(--text-primary)" : "var(--text-muted)",
cursor: "pointer"
}}
onClick={() => setMode("turbo")}
>
Overpass QL
</button>
</div>
{mode === "bellingcat" && (
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
{activeTags.length > 1 && (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", background: "rgba(0,0,0,0.2)", padding: "8px", borderRadius: "4px" }}>
<label style={{ fontSize: "11px", color: "var(--text-muted)" }}>Intersection Radius: <strong>{distance}m</strong></label>
<input
type="range" min="50" max="2000" step="50"
value={distance} onChange={e => setDistance(Number(e.target.value))}
style={{ width: "100px", accentColor: "var(--accent-blue)" }}
/>
</div>
)}
<input
style={{
width: "100%",
padding: "8px",
backgroundColor: "rgba(0,0,0,0.3)",
color: "#fff",
border: "1px solid var(--border-subtle)",
borderRadius: "4px",
fontSize: "13px"
}}
placeholder="Filter tags (e.g. amenity=...)"
value={searchText}
onChange={e => setSearchText(e.target.value)}
/>
<div style={{ display: "flex", flexWrap: "wrap", gap: "6px", maxHeight: "150px", overflowY: "auto", padding: "4px" }}>
{renderedTags.map(tag => {
const isActive = activeTags.includes(tag);
return (
<button
key={tag}
style={{
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
color: isActive ? "#fff" : "var(--text-secondary)",
padding: "4px 10px",
borderRadius: "14px",
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
fontSize: "11px",
cursor: "pointer",
transition: "all 0.2s"
}}
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
>
{tag.replace("=", ": ")}
</button>
);
})}
</div>
</div>
)}
{mode === "turbo" && (
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
<label style={{ fontSize: "11px", color: "var(--text-muted)" }}>Raw Overpass Query</label>
<textarea
style={{
backgroundColor: "rgba(0,0,0,0.3)",
color: "#fff",
border: "1px solid var(--border-subtle)",
padding: "8px",
width: "100%",
borderRadius: "4px",
fontSize: "12px",
fontFamily: "monospace",
resize: "vertical"
}}
value={rawQuery}
onChange={e => setRawQuery(e.target.value)}
rows={6}
/>
<span style={{ fontSize: "10px", color: "var(--text-muted)" }}>Use {'{{bbox}}'} as placeholder</span>
</div>
)}
<button
onClick={handleScan}
disabled={isScanning || (mode === "bellingcat" && activeTags.length === 0)}
style={{
padding: "10px",
background: isScanning ? "var(--bg-tertiary)" : "var(--accent-blue)",
color: "white",
marginTop: "4px",
border: "none",
borderRadius: "4px",
fontWeight: 600,
cursor: isScanning ? "not-allowed" : "pointer",
opacity: (mode === "bellingcat" && activeTags.length === 0) ? 0.5 : 1
}}
>
{isScanning ? "SCANNING OVERPASS..." : `SCAN AREA (${mode === "turbo" ? "TURBO" : activeTags.length + " TAGS"})`}
</button>
</div>
);
}
@@ -0,0 +1,87 @@
import { Search } from "lucide-react";
import type { PluginManifest, WorldPlugin, PluginContext, TimeRange, GeoEntity, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
import { OSMBboxOverlay } from "./components/OSMBboxOverlay";
import { OSMSidebar } from "./components/OSMSidebar";
import { manifest } from "./manifest";
export class OSMSearchPlugin implements WorldPlugin {
id = manifest.id;
name = manifest.name;
description = manifest.description!;
icon = Search;
category = manifest.category as any;
version = manifest.version;
private ctx!: PluginContext;
async initialize(ctx: PluginContext) {
this.ctx = ctx;
}
destroy() {}
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> { return []; }
getPollingInterval() { return 999999999; }
getLayerConfig(): LayerConfig {
return { color: "#ff0000", clusterEnabled: true, clusterDistance: 50 };
}
renderEntity(entity: GeoEntity): CesiumEntityOptions {
return {
type: "point",
color: "#ff0000",
size: 8,
// Ensure points are always visible and don't sink into terrain
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
}
/** Configures how the camera and UI behaves when an OSM entity is selected */
getSelectionBehavior(entity: GeoEntity) {
return {
// Default "go-to" distance in meters.
// 500m provides a good "street-level" view for OSM features.
preferredZoomDistance: 500,
showTrail: false
};
}
getSidebarComponent() { return OSMSidebar; }
getGlobeComponent() { return OSMBboxOverlay; }
/** Public bridge for the sidebar component to push search results into the main map state */
pushResults(entities: GeoEntity[]) {
if (this.ctx) {
this.ctx.onDataUpdate(entities);
}
}
/** Maps Overpass API elements to WorldWideView GeoEntities */
mapOverpassToEntities(elements: any[]): GeoEntity[] {
return elements
.filter(el => (el.lat && el.lon) || el.center)
.map(el => {
const lat = el.lat || el.center?.lat;
const lon = el.lon || el.center?.lon;
const name = el.tags?.name || el.tags?.amenity || el.tags?.shop || el.tags?.highway || `OSM ${el.type} ${el.id}`;
return {
id: `osm-${el.type}-${el.id}`,
pluginId: this.id,
latitude: lat,
longitude: lon,
timestamp: new Date(),
label: name,
properties: {
osm_id: el.id,
osm_type: el.type,
...el.tags
}
};
});
}
}
export { manifest };
@@ -0,0 +1,13 @@
import type { PluginManifest } from "@worldwideview/wwv-plugin-sdk";
export const manifest: PluginManifest = {
id: "osm-search",
name: "OSM Search",
version: "1.0.0",
description: "Configurable Overpass API search. Includes Bellingcat-style proximity search and Overpass Turbo raw QL.",
type: "data-layer",
format: "bundle",
trust: "built-in",
capabilities: ["data:own", "ui:sidebar", "globe:overlay"],
category: "custom"
};
@@ -0,0 +1,24 @@
import { create } from "zustand";
import { Rectangle } from "cesium";
interface OsmPluginState {
bboxLocked: boolean;
showBbox: boolean;
currentBbox: Rectangle | null;
lockedBbox: Rectangle | null;
setBboxLocked: (locked: boolean) => void;
setShowBbox: (show: boolean) => void;
setCurrentBbox: (rect: Rectangle | null) => void;
setLockedBbox: (rect: Rectangle | null) => void;
}
export const useOsmStore = create<OsmPluginState>((set) => ({
bboxLocked: false,
showBbox: true,
currentBbox: null,
lockedBbox: null,
setBboxLocked: (locked) => set({ bboxLocked: locked }),
setShowBbox: (show) => set({ showBbox: show }),
setCurrentBbox: (rect) => set({ currentBbox: rect }),
setLockedBbox: (rect) => set({ lockedBbox: rect }),
}));
@@ -0,0 +1,29 @@
import { describe, it, expect } from "vitest";
import { OSMSearchPlugin } from "../src/index";
describe("OSMSearchPlugin", () => {
it("should instantiate with correct id", () => {
const plugin = new OSMSearchPlugin();
expect(plugin.id).toBe("osm-search");
expect(plugin.category).toBe("custom");
});
it("should map overpass elements to geo entities", () => {
const plugin = new OSMSearchPlugin();
const elements = [
{
type: "node",
id: 123,
lat: 45.0,
lon: 90.0,
tags: { name: "Test Node", amenity: "cafe" }
}
];
const entities = plugin.mapOverpassToEntities(elements);
expect(entities.length).toBe(1);
expect(entities[0].id).toBe("osm-node-123");
expect(entities[0].latitude).toBe(45.0);
expect(entities[0].label).toBe("Test Node");
expect(entities[0].properties.amenity).toBe("cafe");
});
});
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist/",
"rootDir": "src/",
"jsx": "react-jsx"
},
"include": ["src/**/*"]
}
+41 -2
View File
@@ -130,7 +130,7 @@ importers:
version: 8.20.0
zustand:
specifier: ^5.0.11
version: 5.0.12(@types/[email protected])([email protected])
version: 5.0.12(@types/[email protected])([email protected])([email protected]([email protected]))
devDependencies:
'@testing-library/dom':
specifier: ^10.4.1
@@ -515,6 +515,34 @@ importers:
specifier: workspace:*
version: link:../wwv-plugin-sdk
packages/wwv-plugin-osm-search:
dependencies:
'@worldwideview/wwv-plugin-sdk':
specifier: workspace:*
version: link:../wwv-plugin-sdk
cesium:
specifier: ^1.139.0
version: 1.139.1
lucide-react:
specifier: ^0.576.0
version: 0.576.0([email protected])
react:
specifier: 19.2.3
version: 19.2.3
resium:
specifier: 1.19.4
version: 1.19.4([email protected])([email protected]([email protected]))([email protected])
zustand:
specifier: ^5.0.11
version: 5.0.12(@types/[email protected])([email protected])([email protected]([email protected]))
devDependencies:
'@types/react':
specifier: ^19.0.2
version: 19.2.14
typescript:
specifier: ^5.4.5
version: 5.9.3
packages/wwv-plugin-satellite:
dependencies:
'@worldwideview/wwv-plugin-sdk':
@@ -3747,6 +3775,11 @@ packages:
[email protected]:
resolution: {integrity: sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==}
[email protected]:
resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
[email protected]:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -6998,6 +7031,11 @@ snapshots:
[email protected]: {}
[email protected]([email protected]):
dependencies:
react: 19.2.3
optional: true
[email protected]: {}
[email protected]: {}
@@ -7168,7 +7206,8 @@ snapshots:
[email protected]: {}
[email protected](@types/[email protected])([email protected]):
[email protected](@types/[email protected])([email protected])([email protected]([email protected])):
optionalDependencies:
'@types/react': 19.2.14
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
+72
View File
@@ -0,0 +1,72 @@
import { NextResponse } from "next/server";
const OVERPASS_MIRRORS = [
"https://overpass-api.de/api/interpreter",
"https://lz4.overpass-api.de/api/interpreter",
"https://overpass.kumi.systems/api/interpreter"
];
async function tryMirror(url: string, query: string, timeout: number) {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `data=${encodeURIComponent(query)}`,
signal: AbortSignal.timeout(timeout)
});
return res;
}
export async function POST(req: Request) {
try {
const body = await req.json();
const { query } = body;
if (!query) {
return NextResponse.json({ error: "Missing query" }, { status: 400 });
}
console.log(`[OSMSearchProxy] Querying Overpass API mirrors... (length: ${query.length})`);
let lastError = null;
for (const mirror of OVERPASS_MIRRORS) {
try {
console.log(`[OSMSearchProxy] Trying mirror: ${mirror}`);
const res = await tryMirror(mirror, query, 25000); // 25s per mirror
if (res.ok) {
const data = await res.json();
if (data.elements) {
return NextResponse.json({ data: data.elements });
}
if (data.remark) {
console.warn(`[OSMSearchProxy] ${mirror} returned remark: ${data.remark}`);
// If it's a specific query error (remark), don't bother retrying mirrors
return NextResponse.json({ error: data.remark }, { status: 400 });
}
} else {
const text = await res.text();
console.warn(`[OSMSearchProxy] Mirror ${mirror} failed: ${res.status} ${res.statusText}`);
lastError = { status: res.status, statusText: res.statusText, details: text };
// If it's a 4xx error (except 429), it's probably a bad query, so don't retry
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
break;
}
}
} catch (err: any) {
console.warn(`[OSMSearchProxy] Mirror ${mirror} threw error:`, err.message);
lastError = { status: 500, statusText: "Internal Error", details: err.message };
}
}
return NextResponse.json(
{
error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load.",
lastError
},
{ status: lastError?.status || 504 }
);
} catch (e: any) {
console.error(`[OSMSearchProxy] Internal error:`, e);
return NextResponse.json({ error: e.message }, { status: 500 });
}
}
+2
View File
@@ -27,6 +27,7 @@ import { CivilUnrestPlugin } from "@worldwideview/wwv-plugin-civil-unrest";
import { SurveillanceSatellitesPlugin } from "@worldwideview/wwv-plugin-surveillance-satellites";
import { CyberAttacksPlugin } from "@worldwideview/wwv-plugin-cyber-attacks";
import { InternationalSanctionsPlugin } from "@worldwideview/wwv-plugin-international-sanctions";
import { OSMSearchPlugin } from "@worldwideview/wwv-plugin-osm-search";
import { useStore } from "@/core/state/store";
import { dataBus } from "@/core/data/DataBus";
import { PanelToggleArrows } from "@/components/layout/PanelToggleArrows";
@@ -97,6 +98,7 @@ export function AppShell() {
new SurveillanceSatellitesPlugin(),
new CyberAttacksPlugin(),
new InternationalSanctionsPlugin(),
new OSMSearchPlugin(),
];
for (const plugin of builtIns) {
+187 -28
View File
@@ -1,11 +1,162 @@
import { useStore } from "@/core/state/store";
import { pluginManager } from "@/core/plugins/PluginManager";
import { PluginIcon } from "@/components/common/PluginIcon";
import { Eye, MapPin, Lock, Unlock, Star, ExternalLink, Maximize2 } from "lucide-react";
import { Eye, MapPin, Lock, Unlock, Star, ExternalLink, Maximize2, Filter, RotateCcw } from "lucide-react";
import { dataBus } from "@/core/data/DataBus";
import { sectionHeaderStyle } from "./sharedStyles";
import { TimestampProperty } from "../properties/TimestampProperty";
import { DynamicPropertiesRender } from "../properties/DynamicPropertiesRender";
import { useRef, useEffect } from "react";
function LegendItem({
label,
color,
pluginId,
colorOverrides,
updatePluginSettings,
isFilterable = false,
isActive = true,
toggleFilter = () => {},
isDefault = false,
customLayerColor = null
}: {
label: string,
color: string,
pluginId: string,
colorOverrides?: Record<string, string>,
updatePluginSettings: (id: string, s: any) => void,
isFilterable?: boolean,
isActive?: boolean,
toggleFilter?: () => void,
isDefault?: boolean,
customLayerColor?: string | null
}) {
const inputRef = useRef<HTMLInputElement>(null);
const displayColor = isDefault
? (customLayerColor || color)
: (colorOverrides?.[color] || color);
const hasOverride = isDefault
? !!customLayerColor
: !!colorOverrides?.[color];
const actualColorForInput = displayColor.startsWith("#") ? displayColor : "#3b82f6";
return (
<div
style={{
display: "flex",
alignItems: "center",
gap: "var(--space-md)",
background: "rgba(255,255,255,0.03)",
padding: "var(--space-sm) var(--space-md)",
borderRadius: "var(--radius-md)",
cursor: "pointer",
opacity: isActive ? 1 : 0.4,
transition: "all var(--duration-fast)",
border: "1px solid rgba(255,255,255,0.05)",
position: "relative",
overflow: "hidden"
}}
onClick={() => inputRef.current?.click()}
onMouseEnter={(e) => {
e.currentTarget.style.background = "rgba(255,255,255,0.06)";
e.currentTarget.style.borderColor = "rgba(255,255,255,0.1)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "rgba(255,255,255,0.03)";
e.currentTarget.style.borderColor = "rgba(255,255,255,0.05)";
}}
>
<input
ref={inputRef}
type="color"
value={actualColorForInput}
onChange={(e) => {
if (isDefault) {
updatePluginSettings(pluginId, { customLayerColor: e.target.value });
} else if (colorOverrides) {
updatePluginSettings(pluginId, {
colorOverrides: { ...colorOverrides, [color]: e.target.value }
});
}
}}
style={{ position: "absolute", opacity: 0, width: 0, height: 0, pointerEvents: "none" }}
/>
<div style={{
position: "absolute",
top: 0,
left: 0,
width: "3px",
height: "100%",
background: displayColor,
boxShadow: `0 0 10px ${displayColor}88`
}} />
<div style={{
width: 16,
height: 16,
borderRadius: "var(--radius-sm)",
backgroundColor: displayColor,
border: "1px solid rgba(255,255,255,0.2)",
boxShadow: `0 0 8px ${displayColor}44`,
flexShrink: 0
}} />
<div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "1px" }}>
<span style={{ fontSize: 13, fontWeight: 500, color: "var(--text-primary)" }}>{label}</span>
<span style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--text-muted)", letterSpacing: "0.02em" }}>{displayColor.toUpperCase()}</span>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-xs)" }}>
{isFilterable && (
<button
onClick={(e) => { e.stopPropagation(); toggleFilter(); }}
title={isActive ? "Disable filter" : "Enable filter"}
style={{
background: isActive ? "rgba(0, 255, 255, 0.1)" : "transparent",
border: "none",
color: isActive ? "var(--accent-cyan)" : "var(--text-muted)",
padding: "6px",
borderRadius: "var(--radius-sm)",
display: "flex",
cursor: "pointer"
}}
>
<Filter size={14} />
</button>
)}
{hasOverride && (
<button
onClick={(e) => {
e.stopPropagation();
if (isDefault) {
updatePluginSettings(pluginId, { customLayerColor: null });
} else if (colorOverrides) {
const newOverrides = { ...colorOverrides };
delete newOverrides[color];
updatePluginSettings(pluginId, { colorOverrides: newOverrides });
}
}}
title="Reset to default"
style={{
background: "transparent",
border: "none",
color: "var(--text-muted)",
padding: "6px",
borderRadius: "var(--radius-sm)",
display: "flex",
cursor: "pointer"
}}
>
<RotateCcw size={14} />
</button>
)}
</div>
</div>
);
}
export function IntelTab() {
const selectedEntity = useStore((s) => s.selectedEntity);
@@ -17,15 +168,20 @@ export function IntelTab() {
const highlightLayerId = useStore((s) => s.highlightLayerId);
const filters = useStore((s) => s.filters);
const setFilter = useStore((s) => s.setFilter);
const addFloatingStream = useStore((s) => s.addFloatingStream);
const updatePluginSettings = useStore((s) => s.updatePluginSettings);
const pluginSettings = useStore((s) => s.dataConfig.pluginSettings);
if (!selectedEntity) {
if (highlightLayerId) {
const layerPlugin = pluginManager.getPlugin(highlightLayerId);
if (layerPlugin) {
const layerConfig = layerPlugin.plugin.getLayerConfig();
const SidebarComp = layerPlugin.plugin.getSidebarComponent?.();
const defaultColor = layerConfig?.color || "var(--accent-cyan)";
const legend = layerPlugin.plugin.getLegend?.();
const pluginId = layerPlugin.plugin.id;
const settings = pluginSettings[pluginId] || {};
const colorOverrides = settings.colorOverrides || {};
return (
<div style={{ padding: "var(--space-md)" }}>
@@ -38,13 +194,20 @@ export function IntelTab() {
<div style={{ color: "var(--text-secondary)", fontSize: 13, marginBottom: "var(--space-lg)", lineHeight: 1.5 }}>
{layerPlugin.plugin.description}
</div>
{SidebarComp && (
<div style={{ marginBottom: "var(--space-lg)", paddingBottom: "var(--space-lg)", borderBottom: "1px solid var(--border-subtle)" }}>
<SidebarComp plugin={layerPlugin.plugin} />
</div>
)}
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-sm)" }}>
<span style={{ fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.05em" }}>
{legend && legend.length > 1 ? "Data Point Colors" : "Data Point Color"}
</span>
{legend && legend.length > 0 ? (
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-sm)" }}>
{legend.map((item, idx) => {
const isFilterable = Boolean(item.filterId && item.filterValue);
const currentFilter = isFilterable ? filters[layerPlugin.plugin.id]?.[item.filterId!] : undefined;
@@ -57,7 +220,6 @@ export function IntelTab() {
const toggleFilter = () => {
if (!isFilterable) return;
const pluginId = layerPlugin.plugin.id;
const filterId = item.filterId!;
const filterVal = item.filterValue!;
@@ -79,34 +241,29 @@ export function IntelTab() {
};
return (
<div
key={idx}
style={{
display: "flex",
alignItems: "center",
gap: "var(--space-sm)",
background: "rgba(255,255,255,0.03)",
padding: "var(--space-sm)",
borderRadius: "var(--radius-sm)",
cursor: isFilterable ? "pointer" : "default",
opacity: isActive ? 1 : 0.4,
transition: "opacity var(--duration-fast)"
}}
onClick={toggleFilter}
title={isFilterable ? "Click to filter by this category" : ""}
>
<span style={{ width: 14, height: 14, borderRadius: "50%", backgroundColor: item.color, display: "inline-block", border: "1px solid rgba(255,255,255,0.2)", boxShadow: "0 0 6px rgba(0,0,0,0.5)", flexShrink: 0 }} />
<span style={{ fontSize: 13, color: "var(--text-primary)" }}>{item.label}</span>
<span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--text-muted)", marginLeft: "auto" }}>{item.color}</span>
</div>
<LegendItem
key={idx}
label={item.label}
color={item.color}
pluginId={pluginId}
colorOverrides={colorOverrides}
updatePluginSettings={updatePluginSettings}
isFilterable={isFilterable}
isActive={isActive}
toggleFilter={toggleFilter}
/>
);
})}
</div>
) : (
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-sm)", background: "rgba(255,255,255,0.03)", padding: "var(--space-sm)", borderRadius: "var(--radius-sm)" }}>
<span style={{ width: 14, height: 14, borderRadius: "50%", backgroundColor: defaultColor, display: "inline-block", border: "1px solid rgba(255,255,255,0.2)", boxShadow: "0 0 6px rgba(0,0,0,0.5)" }} />
<span style={{ fontSize: 13, fontFamily: "var(--font-mono)", color: "var(--text-primary)" }}>{defaultColor}</span>
</div>
<LegendItem
label="Default Layer Color"
color={defaultColor}
pluginId={pluginId}
updatePluginSettings={updatePluginSettings}
isDefault={true}
customLayerColor={settings.customLayerColor}
/>
)}
</div>
</div>
@@ -215,10 +372,12 @@ export function IntelTab() {
title="Go to entity"
onClick={() => {
console.log("[Intel] Go To button clicked", selectedEntity.latitude, selectedEntity.longitude);
const behavior = managed?.plugin.getSelectionBehavior?.(selectedEntity);
dataBus.emit("cameraGoTo", {
lat: selectedEntity.latitude,
lon: selectedEntity.longitude,
alt: selectedEntity.altitude || 0,
distance: behavior?.preferredZoomDistance
});
}}
>
+1 -1
View File
@@ -224,7 +224,7 @@ function processEntity(
return;
}
if (!item.options.disableManualHorizonCulling) {
if (!item.options.disableManualHorizonCulling || primitive.disableDepthTestDistance === Number.POSITIVE_INFINITY) {
// Mathematical horizon culling (extremely fast, precise for sphere)
item._occluded = Cartesian3.dot(posRef, camPos) <= R2;
if (item._occluded) {
+27 -7
View File
@@ -61,6 +61,7 @@ export default function GlobeView() {
shadowsEnabled, enableLighting,
}), [showFps, resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting]);
const filters = useStore((s) => s.filters);
const pluginSettings = useStore((s) => s.dataConfig.pluginSettings);
const lockedEntityId = useStore((s) => s.lockedEntityId);
const setCameraPosition = useStore((s) => s.setCameraPosition);
const setFps = useStore((s) => s.setFps);
@@ -71,18 +72,34 @@ export default function GlobeView() {
const visibleEntities = useMemo(() => {
const result: Array<{ entity: GeoEntity; options: CesiumEntityOptions }> = [];
pluginManager.getAllPlugins().forEach((managed) => {
if (!layers[managed.plugin.id]?.enabled) return;
const pluginId = managed.plugin.id;
if (!layers[pluginId]?.enabled) return;
if (managed.plugin.getLayerConfig().disableDefaultRendering) return;
const entities = entitiesByPlugin[managed.plugin.id];
const entities = entitiesByPlugin[pluginId];
if (!Array.isArray(entities)) return;
const settings = pluginSettings[pluginId];
const colorOverrides = settings?.colorOverrides;
const customLayerColor = settings?.customLayerColor;
const defs = managed.plugin.getFilterDefinitions?.() || [];
const active = filters[managed.plugin.id] || {};
const active = filters[pluginId] || {};
applyFilters(entities, defs, active).forEach((entity) => {
result.push({ entity, options: getCachedRenderOptions(managed.plugin, entity) });
const originalOptions = getCachedRenderOptions(managed.plugin, entity);
// Apply color overrides
let options = originalOptions;
if (colorOverrides && colorOverrides[originalOptions.color]) {
options = { ...originalOptions, color: colorOverrides[originalOptions.color] };
} else if (customLayerColor) {
options = { ...originalOptions, color: customLayerColor };
}
result.push({ entity, options });
});
});
return result;
}, [layers, entitiesByPlugin, filters]);
}, [layers, entitiesByPlugin, filters, pluginSettings]);
const { isGoogle3D } = useImageryManager(viewerRef.current, viewerReady);
useBorders(viewerRef.current, showLabels, isGoogle3D);
@@ -201,14 +218,17 @@ export default function GlobeView() {
}, [lockedEntityId, viewerReady]);
const PluginGlobeComponents = useMemo(() => {
return pluginManager.getAllPlugins()
const components = pluginManager.getAllPlugins()
.filter(managed => managed.plugin.getGlobeComponent)
.map(managed => {
const Comp = managed.plugin.getGlobeComponent!();
const enabled = layers[managed.plugin.id]?.enabled ?? false;
console.log(`[GlobeView] Rendering plugin globe component: ${managed.plugin.id}, enabled: ${enabled}`);
return <Comp key={managed.plugin.id} viewer={viewerRef.current} enabled={enabled} />;
});
}, [layers]);
console.log(`[GlobeView] Recomputing PluginGlobeComponents. Count: ${components.length}`);
return components;
}, [layers, viewerReady]);
return (
<Viewer
+28 -40
View File
@@ -13,21 +13,43 @@ export function useViewerInitialization(sceneSettings: any) {
const handleViewerReady = useCallback(async (viewer: CesiumViewer) => {
viewerRef.current = viewer;
// CesiumJS may initialize a default imagery layer even with Resium's
// baseLayer={false}. Strip it so useImageryManager is the sole controller.
// 1. Core Viewer Settings (Sync)
viewer.imageryLayers.removeAll();
viewer.scene.requestRenderMode = true;
viewer.scene.maximumRenderTimeChange = 0.5;
// viewer.scene.orderIndependentTranslucency is read-only in newer Cesium versions and no longer configurable
viewer.scene.debugShowFramesPerSecond = sceneSettings.showFps;
viewer.resolutionScale = sceneSettings.resolutionScale;
viewer.scene.postProcessStages.fxaa.enabled = sceneSettings.antiAliasing === "fxaa";
viewer.scene.msaaSamples = sceneSettings.antiAliasing === "none" || sceneSettings.antiAliasing === "fxaa" ? 1 : parseInt(sceneSettings.antiAliasing.replace("msaa", "").replace("x", ""), 10) || 1;
viewer.scene.globe.depthTestAgainstTerrain = true;
// Configure Screen Space Camera
const sscc = viewer.scene.screenSpaceCameraController;
sscc.tiltEventTypes = [
CameraEventType.MIDDLE_DRAG,
CameraEventType.RIGHT_DRAG,
CameraEventType.PINCH,
{ eventType: CameraEventType.LEFT_DRAG, modifier: KeyboardEventModifier.CTRL },
{ eventType: CameraEventType.RIGHT_DRAG, modifier: KeyboardEventModifier.CTRL }
];
sscc.zoomEventTypes = [CameraEventType.WHEEL, CameraEventType.PINCH];
if ("ontouchstart" in window || navigator.maxTouchPoints > 0) {
(sscc as any)._zoomFactor = 15;
(sscc as any)._translateFactor = 2;
(sscc as any)._tiltFactor = 50;
}
// Initialize collections so renderers can start immediately
initPrimitiveCollections(viewer);
// Initial Camera Position (Sync)
viewer.camera.setView({ destination: Cartesian3.fromDegrees(0, 20, 10000000) });
// Signal ready NOW so UI and Overlays (OSM Box) appear instantly
setViewerReady(true);
// 2. Heavy/Async Data Loading (Background)
let globeFired = false;
const fireGlobeReady = () => {
if (globeFired) return;
@@ -37,6 +59,7 @@ export function useViewerInitialization(sceneSettings: any) {
}
dataBus.emit("globeReady", {} as Record<string, never>);
};
const globalTimeout = setTimeout(() => {
console.warn("[GlobeView] Global tile-init timeout (15s) — forcing globe ready.");
fireGlobeReady();
@@ -58,20 +81,16 @@ export function useViewerInitialization(sceneSettings: any) {
});
if (viewer.isDestroyed()) {
console.warn("[GlobeView] Viewer destroyed during tileset init — aborting.");
clearTimeout(globalTimeout);
return;
}
tileset.maximumScreenSpaceError = sceneSettings.maxScreenSpaceError;
// Increase the local cache of downloaded tiles from the default 512MB to 2048MB.
// This massively mitigates duplicate tile API requests hitting Google when users
// pan around the map in local areas.
(tileset as any).maximumMemoryUsage = 2048;
viewer.scene.primitives.add(tileset);
const removeListener = tileset.initialTilesLoaded.addEventListener(() => {
console.log("[GlobeView] Initial tiles loaded — syncing state and firing ready.");
console.log("[GlobeView] Initial tiles loaded — syncing state.");
useStore.getState().updateMapConfig({ baseLayerId: "google-3d" });
clearTimeout(globalTimeout);
fireGlobeReady();
@@ -80,13 +99,10 @@ export function useViewerInitialization(sceneSettings: any) {
googleLoaded = true;
} catch (err: any) {
console.error("[GlobeView] Failed to initialize Google 3D Tiles:", err);
useStore.getState().showErrorToast("Google 3D Tiles failed to load: " + (err.message || "Invalid Key or 403 Forbidden"));
// We fall through to local map fallback below.
}
}
if (!googleLoaded) {
console.log("[GlobeView] Google 3D Tiles inactive/unauthorized. Falling back to default flat imagery.");
if (useStore.getState().mapConfig.baseLayerId === "google-3d") {
useStore.getState().updateMapConfig({ fallbackLayerId: "bing-aerial" });
}
@@ -95,36 +111,8 @@ export function useViewerInitialization(sceneSettings: any) {
}
} catch (err) {
console.error("[GlobeView] Unexpected error during early globe init:", err);
if (useStore.getState().mapConfig.baseLayerId === "google-3d") {
useStore.getState().updateMapConfig({ fallbackLayerId: "bing-aerial" });
}
clearTimeout(globalTimeout);
fireGlobeReady();
}
if (viewer.isDestroyed()) return;
initPrimitiveCollections(viewer);
const sscc = viewer.scene.screenSpaceCameraController;
sscc.tiltEventTypes = [
CameraEventType.MIDDLE_DRAG,
CameraEventType.RIGHT_DRAG,
CameraEventType.PINCH,
{ eventType: CameraEventType.LEFT_DRAG, modifier: KeyboardEventModifier.CTRL },
{ eventType: CameraEventType.RIGHT_DRAG, modifier: KeyboardEventModifier.CTRL }
];
sscc.zoomEventTypes = [
CameraEventType.WHEEL,
CameraEventType.PINCH
];
if ("ontouchstart" in window || navigator.maxTouchPoints > 0) {
(sscc as any)._zoomFactor = 15;
(sscc as any)._translateFactor = 2;
(sscc as any)._tiltFactor = 50;
}
setViewerReady(true);
}, [sceneSettings]);
return { viewerRef, viewerReady, handleViewerReady };
+8 -1
View File
@@ -27,6 +27,13 @@ export function getBaseSize(): number {
/** Padding ratio — the icon fills (1 - 2*INSET) of the canvas. */
const ICON_INSET = 0.12;
/**
* Background circle size ratio (relative to canvas radius).
* Adjust this to scale the black half-transparent backdrop.
* 1.0 = fills canvas, 0.8 = 80% of canvas radius.
*/
const BG_RADIUS_RATIO = 1.0;
/** Default backdrop behind the icon for terrain contrast. */
const DEFAULT_BG = "rgba(15, 23, 42, 0.55)";
@@ -74,7 +81,7 @@ export function getHiResIcon(srcUrl: string, bgColor = DEFAULT_BG): Promise<stri
// Subtle circle backdrop for terrain contrast
const cx = pxSize / 2;
ctx.beginPath();
ctx.arc(cx, cx, cx, 0, Math.PI * 2);
ctx.arc(cx, cx, cx * BG_RADIUS_RATIO, 0, Math.PI * 2);
ctx.fillStyle = bgColor;
ctx.fill();
+21 -3
View File
@@ -63,6 +63,15 @@ export function updateExistingItem(
item.baseColor = color;
item.baseOutlineColor = getCachedColor(options.outlineColor) || Color.BLACK;
const isGroundBased = (entity.altitude || 0) < 100;
const disableDepthTestDistance = isGroundBased
? Number.POSITIVE_INFINITY
: options.disableDepthTestDistance;
if (item.primitive.disableDepthTestDistance !== disableDepthTestDistance) {
item.primitive.disableDepthTestDistance = disableDepthTestDistance;
}
const billboardColor = (options as any)._isAutoSVG ? Color.WHITE : color;
if (!Color.equals(item.primitive.color, billboardColor)) item.primitive.color = billboardColor;
@@ -115,6 +124,14 @@ export function createNewItem(
const baseSize = getBaseSize();
const billboardColor = (options as any)._isAutoSVG ? Color.WHITE : color;
// Performance optimization: Ground-based entities (altitude < 100m) should disable
// Cesium's heavy depth testing and instead use our efficient manual horizon culling.
// Air-based entities keep depth testing enabled for realistic occlusion against mountains.
const isGroundBased = (entity.altitude || 0) < 100;
const disableDepthTestDistance = isGroundBased
? Number.POSITIVE_INFINITY
: options.disableDepthTestDistance;
const addedPrimitive = options.iconUrl
? billboards.add({
position: newPosition, image: resolvedIcon,
@@ -123,17 +140,18 @@ export function createNewItem(
verticalOrigin: VerticalOrigin.CENTER, horizontalOrigin: HorizontalOrigin.CENTER,
rotation: options.rotation ? -CesiumMath.toRadians(options.rotation) : 0,
color: billboardColor, scaleByDistance: new NearFarScalar(1e6, 1.0, 2e7, 0.5), id: clickId,
eyeOffset: new Cartesian3(0, 0, options.depthBias ?? -10000), // Small depth bias for far-range terrain
// eyeOffset: new Cartesian3(0, 0, options.depthBias ?? -10000), // Small depth bias for far-range terrain
// WARNING: Do NOT use heightReference: HeightReference.CLAMP_TO_GROUND here.
// It causes severe lag/performance drops with thousands of dynamic entities.
disableDepthTestDistance: options.disableDepthTestDistance, distanceDisplayCondition: ddc,
disableDepthTestDistance, distanceDisplayCondition: ddc,
})
: points.add({
position: newPosition, pixelSize: options.size || defaultPointSize(), color, outlineColor,
outlineWidth: options.outlineWidth || 1, show: false,
scaleByDistance: new NearFarScalar(1e6, 1.0, 2e7, 0.5), id: clickId,
disableDepthTestDistance: options.disableDepthTestDistance, distanceDisplayCondition: ddc,
disableDepthTestDistance, distanceDisplayCondition: ddc,
});
existingMap.set(entity.id, {
primitive: addedPrimitive, labelPrimitive: undefined, entity, posRef: newPosition,
options, baseColor: color, baseOutlineColor: outlineColor, lastHighlightState: 'normal'
+15 -3
View File
@@ -19,6 +19,12 @@ const hubScaleByDistance = new NearFarScalar(2.0e6, 1.0, 1.5e7, 0.5);
/** Duration of expand/collapse animation in ms. */
const ANIM_DURATION_MS = 220;
/**
* Radius of the cluster hub background circle.
* Adjust this to scale the black half-transparent badge.
*/
const HUB_BG_RADIUS = 14;
/** Reusable scratch Cartesian2 to avoid allocation. */
const scratchOffset = new Cartesian2();
@@ -37,7 +43,7 @@ function getClusterIcon(count: number, hexColor: string): string {
const textStr = count > 99 ? '99+' : count.toString();
const fillValue = "rgba(15, 23, 42, 0.95)";
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}">
<circle cx="${center}" cy="${center}" r="16" fill="${fillValue}" stroke="${hexColor}" stroke-width="2.5"/>
<circle cx="${center}" cy="${center}" r="${HUB_BG_RADIUS}" fill="${fillValue}" stroke="${hexColor}" stroke-width="2.5"/>
<text x="${center}" y="${center + 1}" font-family="Inter, sans-serif" font-size="14px" font-weight="bold" fill="#ffffff" text-anchor="middle" dominant-baseline="middle">${textStr}</text>
</svg>`;
@@ -157,8 +163,14 @@ function tickSingle(stack: EntityStack, now: number, billboards: BillboardCollec
function manageDedicatedHub(stack: EntityStack, billboards: BillboardCollection) {
let bb = hubBillboards.get(stack.id);
const count = stack.children.length;
// Caching CSS color string per stack rather than generating it every frame
const cssColor = (stack.hubItem as any)._cachedCssColor ?? ((stack.hubItem as any)._cachedCssColor = stack.hubItem.baseColor?.toCssColorString() ?? "#ffffff");
// Check if the hubItem's baseColor has changed since we last cached it
const currentBaseColor = stack.hubItem.baseColor?.toCssColorString() ?? "#ffffff";
if ((stack.hubItem as any)._cachedCssColor !== currentBaseColor) {
(stack.hubItem as any)._cachedCssColor = currentBaseColor;
}
const cssColor = (stack.hubItem as any)._cachedCssColor;
const expectedImage = getClusterIcon(count, cssColor);
const anyExpanded = isAnyStackExpanded();
+2 -2
View File
@@ -62,7 +62,7 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
maxScreenSpaceError: 32, // Increase from 16 to 32 to significantly reduce 3D tile network requests and costs
shadowsEnabled: false,
enableLighting: false,
baseLayerId: typeof window !== "undefined" ? (localStorage.getItem("wwv_map_layer") || "google-3d") : "google-3d",
baseLayerId: (typeof window !== "undefined" && window.localStorage && typeof window.localStorage.getItem === "function") ? (localStorage.getItem("wwv_map_layer") || "google-3d") : "google-3d",
fallbackLayerId: null,
sceneMode: 3,
},
@@ -72,7 +72,7 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
})),
updateMapConfig: (config) =>
set((state) => {
if (config.baseLayerId && typeof window !== "undefined") {
if (config.baseLayerId && typeof window !== "undefined" && window.localStorage && typeof window.localStorage.setItem === "function") {
localStorage.setItem("wwv_map_layer", config.baseLayerId);
}
return { mapConfig: { ...state.mapConfig, ...config } };
+1
View File
@@ -10,4 +10,5 @@ export const BUILT_IN_PLUGIN_IDS = [
"wildfire",
"camera",
"borders",
"osm-search",
] as const;
+3
View File
@@ -64,6 +64,9 @@
],
"@worldwideview/wwv-plugin-undersea-cables": [
"./packages/wwv-plugin-undersea-cables/src"
],
"@worldwideview/wwv-plugin-osm-search": [
"./packages/wwv-plugin-osm-search/src"
]
}
},
+1 -1
View File
@@ -10,6 +10,6 @@ export default defineConfig({
alias: {
'@': path.resolve(__dirname, './src'),
},
include: ['src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}'],
include: ['src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}', 'packages/**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
});