1581 lines
55 KiB
JavaScript
1581 lines
55 KiB
JavaScript
import { globeZoomForDistance } from "./globe-navigation.js";
|
|
import { createClusterPresentation } from "./cluster-presentation.js";
|
|
import { isSurfaceAnchorVisible, SURFACE_ANCHOR_OCCLUSION_GLSL } from "./surface-marker-occlusion.js";
|
|
import { drawMarkerBadge } from "./marker-badges.js";
|
|
import * as THREE from "three";
|
|
|
|
import { CONFIG } from "./constants.js";
|
|
import { getSurfaceMarkerCameraScale, latLonToVector3 } from "./utils.js";
|
|
|
|
// Focused markers must win across interactable layers, not only within their
|
|
// own point batch. The shared value keeps a selected icon visible when it
|
|
// overlaps another surface icon.
|
|
const INTERACTABLE_FOCUS_RENDER_ORDER = 100;
|
|
|
|
const assetImageCache = new Map();
|
|
const projectedTextureUrls = new WeakMap();
|
|
const assetImageLoadPromises = new Map();
|
|
const surfaceAvoidanceBuckets = new Map();
|
|
const interactableLayerControllers = new Map();
|
|
const DEFAULT_AVOIDANCE_PRECISION = 4;
|
|
const POINT_BUCKET_MIN_CAPACITY = 32;
|
|
const CLUSTER_MIN_COUNT = 2;
|
|
const CLUSTER_MAX_MARKERS_PER_DOT = 14;
|
|
const CLUSTER_DISTANCE = 15;
|
|
const CLUSTER_EXPANSION_HYSTERESIS = 0.08;
|
|
const CLUSTER_DISABLE_ABOVE_ZOOM = 2.5;
|
|
let clusterPresentation = null;
|
|
export function updateInteractableClusters(camera, selectedMarker = null) { updateClusterPresentation(camera, selectedMarker); }
|
|
export function resolveInteractableMarker(marker) {
|
|
return interactableLayerControllers.get(marker?.userData?.icon_layer_id)?.resolveMarker(marker) || marker;
|
|
}
|
|
export function clearInteractableClusters() { clusterPresentation?.destroy(); clusterPresentation = null; }
|
|
|
|
|
|
// Named overlap profiles. Layers that should be recognized as sharing a place
|
|
// must reference the SAME profile. The profile records overlap metadata only;
|
|
// it never moves the marker away from its real geographic anchor.
|
|
//
|
|
// city — ~1.1km grid (precision 2). Use for site/observatory/POI markers
|
|
// that often share a city-center coordinate from geocoding.
|
|
// precise — ~11m grid (precision 4). Use for markers with building-level
|
|
// coordinates (default; preserves prior behavior).
|
|
//
|
|
// Layers that need a fully custom cluster identity (e.g. a city ID string)
|
|
// can pass `getKey: (item, position) => "..."` instead of using a profile.
|
|
// Overlap tracking is opt-in: dynamic high-density layers such as vessels should
|
|
// leave it disabled so their per-frame metadata work stays minimal.
|
|
export const SURFACE_AVOIDANCE_PROFILES = Object.freeze({
|
|
city: Object.freeze({ precision: 2 }),
|
|
precise: Object.freeze({
|
|
precision: DEFAULT_AVOIDANCE_PRECISION,
|
|
}),
|
|
});
|
|
const parsedColors = new Map();
|
|
function colorToRgbArray(colorValue, fallback = "#ffffff") {
|
|
const value = colorValue || fallback;
|
|
// CSS strings/numbers are immutable; caller-owned Color objects may change.
|
|
const cacheable = typeof value === "string" || typeof value === "number";
|
|
if (cacheable && parsedColors.has(value)) return parsedColors.get(value);
|
|
const color = new THREE.Color(value);
|
|
const rgb = [color.r, color.g, color.b];
|
|
if (cacheable) {
|
|
if (parsedColors.size >= 256) parsedColors.delete(parsedColors.keys().next().value);
|
|
parsedColors.set(value, rgb);
|
|
}
|
|
return rgb;
|
|
}
|
|
|
|
function normalizeAvoidanceConfig(avoidance) {
|
|
if (avoidance === false || avoidance === null || avoidance === undefined) {
|
|
return {
|
|
enabled: false,
|
|
precision: DEFAULT_AVOIDANCE_PRECISION,
|
|
};
|
|
}
|
|
|
|
const customConfig =
|
|
avoidance === true || typeof avoidance !== "object" ? {} : avoidance;
|
|
const config = {
|
|
enabled: true,
|
|
precision: DEFAULT_AVOIDANCE_PRECISION,
|
|
...customConfig,
|
|
};
|
|
config.enabled = config.enabled !== false;
|
|
return config;
|
|
}
|
|
|
|
function normalizeClusterConfig(cluster, avoidanceConfig) {
|
|
const customConfig = typeof cluster === "object" && cluster ? cluster : {};
|
|
return {
|
|
enabled: cluster !== false && cluster !== null &&
|
|
(customConfig.enabled ?? avoidanceConfig.enabled),
|
|
minCount: Math.max(2, Math.round(Number(customConfig.minCount ?? CLUSTER_MIN_COUNT))),
|
|
maxMarkersPerDot: Math.max(2, Math.round(Number(customConfig.maxMarkersPerDot ?? CLUSTER_MAX_MARKERS_PER_DOT))),
|
|
distance: Math.max(0, Number(customConfig.distance ?? CLUSTER_DISTANCE)),
|
|
expansionHysteresis: Math.max(0, Number(customConfig.expansionHysteresis ?? CLUSTER_EXPANSION_HYSTERESIS)),
|
|
disableAboveZoom: Number(customConfig.disableAboveZoom ?? CLUSTER_DISABLE_ABOVE_ZOOM),
|
|
};
|
|
}
|
|
|
|
function getSphericalBucketKey(latIndex, lonIndex) {
|
|
return `${latIndex}:${lonIndex}`;
|
|
}
|
|
|
|
function normalizeSphericalLongitudeIndex(lonIndex, lonBucketCount) {
|
|
if (!Number.isFinite(lonBucketCount) || lonBucketCount <= 0) return lonIndex;
|
|
return ((lonIndex % lonBucketCount) + lonBucketCount) % lonBucketCount;
|
|
}
|
|
|
|
function getNeighboringSphericalBucketKeys(latIndex, lonIndex, lonBucketCount) {
|
|
const keys = [];
|
|
for (let latOffset = -1; latOffset <= 1; latOffset += 1) {
|
|
for (let lonOffset = -1; lonOffset <= 1; lonOffset += 1) {
|
|
keys.push(
|
|
getSphericalBucketKey(
|
|
latIndex + latOffset,
|
|
normalizeSphericalLongitudeIndex(lonIndex + lonOffset, lonBucketCount),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
return keys;
|
|
}
|
|
|
|
function getEntrySphericalCoordinates(entry) {
|
|
const direction = entry.direction;
|
|
const lat = Math.asin(Math.max(-1, Math.min(1, direction.y)));
|
|
const lon = Math.atan2(direction.z, direction.x);
|
|
return { lat, lon };
|
|
}
|
|
|
|
function hashStableIds(entries) {
|
|
let hash = 2166136261;
|
|
entries.forEach((entry) => {
|
|
const value = entry.stableId;
|
|
for (let index = 0; index < value.length; index += 1) {
|
|
hash ^= value.charCodeAt(index);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
});
|
|
return (hash >>> 0).toString(36);
|
|
}
|
|
|
|
function getClusterRecordId(entries) {
|
|
const sortedEntries = [...entries].sort((a, b) => a.stableId.localeCompare(b.stableId));
|
|
const anchorId = sortedEntries[0]?.stableId || "unknown";
|
|
return `cluster:${anchorId}:${sortedEntries.length}:${hashStableIds(sortedEntries)}`;
|
|
}
|
|
|
|
function disposeGroupChildren(group) {
|
|
for (let index = group.children.length - 1; index >= 0; index -= 1) {
|
|
const child = group.children[index];
|
|
child.material?.dispose?.();
|
|
child.geometry?.dispose?.();
|
|
group.remove(child);
|
|
}
|
|
}
|
|
|
|
function normalizePosition(position, radius) {
|
|
if (position instanceof THREE.Vector3) {
|
|
return position.clone();
|
|
}
|
|
const lat = Number(position?.latitude ?? position?.lat);
|
|
const lon = Number(position?.longitude ?? position?.lon);
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
|
return latLonToVector3(lat, lon, radius);
|
|
}
|
|
|
|
function createCanvas(width, height) {
|
|
if (typeof OffscreenCanvas !== "undefined") {
|
|
return new OffscreenCanvas(width, height);
|
|
}
|
|
const canvas = document.createElement("canvas");
|
|
canvas.width = width;
|
|
canvas.height = height;
|
|
return canvas;
|
|
}
|
|
|
|
function getAvoidanceKey(item, position, basePosition, config) {
|
|
if (typeof config?.getKey === "function") {
|
|
const key = config.getKey(item, position, basePosition);
|
|
if (key) return String(key);
|
|
}
|
|
|
|
const precision = Number.isFinite(config?.precision)
|
|
? config.precision
|
|
: DEFAULT_AVOIDANCE_PRECISION;
|
|
|
|
if (position instanceof THREE.Vector3) {
|
|
return [
|
|
"vec",
|
|
basePosition.x.toFixed(precision),
|
|
basePosition.y.toFixed(precision),
|
|
basePosition.z.toFixed(precision),
|
|
].join(":");
|
|
}
|
|
|
|
const lat = Number(position?.latitude ?? position?.lat);
|
|
const lon = Number(position?.longitude ?? position?.lon);
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
|
return ["geo", lat.toFixed(precision), lon.toFixed(precision)].join(":");
|
|
}
|
|
|
|
function notifyAvoidancePositionChanged(layerIds) {
|
|
layerIds.forEach((layerId) => {
|
|
interactableLayerControllers.get(layerId)?.refreshPositions?.();
|
|
});
|
|
}
|
|
|
|
function recomputeAvoidanceBucket(key) {
|
|
const entries = surfaceAvoidanceBuckets.get(key);
|
|
if (!entries || entries.length === 0) return;
|
|
|
|
const affectedLayerIds = new Set(entries.map((entry) => entry.layerId));
|
|
const crossLayer = affectedLayerIds.size > 1;
|
|
if (entries.length === 1) {
|
|
const entry = entries[0];
|
|
entry.marker.position.copy(entry.marker.userData.icon_base_position);
|
|
entry.marker.userData.icon_static_avoidance_position = null;
|
|
entry.marker.userData.icon_avoidance_index = 0;
|
|
entry.marker.userData.icon_avoidance_count = 1;
|
|
entry.marker.userData.icon_avoidance_layer_count = 1;
|
|
entry.marker.userData.icon_avoidance_cross_layer = false;
|
|
notifyAvoidancePositionChanged(affectedLayerIds);
|
|
return;
|
|
}
|
|
|
|
const count = entries.length;
|
|
entries.forEach((entry, index) => {
|
|
entry.marker.position.copy(entry.marker.userData.icon_base_position);
|
|
entry.marker.userData.icon_static_avoidance_position = null;
|
|
entry.marker.userData.icon_avoidance_index = index;
|
|
entry.marker.userData.icon_avoidance_count = count;
|
|
entry.marker.userData.icon_avoidance_layer_count = affectedLayerIds.size;
|
|
entry.marker.userData.icon_avoidance_cross_layer = crossLayer;
|
|
});
|
|
|
|
notifyAvoidancePositionChanged(affectedLayerIds);
|
|
}
|
|
|
|
function unregisterLayerAvoidance(layerId) {
|
|
const affectedKeys = new Set();
|
|
surfaceAvoidanceBuckets.forEach((entries, key) => {
|
|
const nextEntries = entries.filter((entry) => entry.layerId !== layerId);
|
|
if (nextEntries.length !== entries.length) {
|
|
affectedKeys.add(key);
|
|
}
|
|
if (nextEntries.length === 0) {
|
|
surfaceAvoidanceBuckets.delete(key);
|
|
} else {
|
|
surfaceAvoidanceBuckets.set(key, nextEntries);
|
|
}
|
|
});
|
|
affectedKeys.forEach((key) => recomputeAvoidanceBucket(key));
|
|
}
|
|
|
|
function registerLayerAvoidance(layerId, markers, avoidanceConfig) {
|
|
if (avoidanceConfig.enabled === false) return;
|
|
|
|
const affectedKeys = new Set();
|
|
markers.forEach((marker) => {
|
|
const key = marker.userData?.icon_avoidance_key;
|
|
if (!key) return;
|
|
if (!surfaceAvoidanceBuckets.has(key)) {
|
|
surfaceAvoidanceBuckets.set(key, []);
|
|
}
|
|
surfaceAvoidanceBuckets.get(key).push({
|
|
layerId,
|
|
marker,
|
|
});
|
|
affectedKeys.add(key);
|
|
});
|
|
|
|
affectedKeys.forEach((key) => recomputeAvoidanceBucket(key));
|
|
}
|
|
|
|
function getMarkerStaticAvoidancePosition(marker) {
|
|
return (
|
|
marker?.userData?.icon_base_position ||
|
|
marker?.position
|
|
);
|
|
}
|
|
|
|
function getAngularDistance(entryA, entryB) {
|
|
const dot = entryA.direction.dot(entryB.direction);
|
|
return Math.acos(Math.min(1, Math.max(-1, dot)));
|
|
}
|
|
|
|
function splitLargeClusterGroup(groupEntries) {
|
|
const maxMarkersPerDot = groupEntries.reduce(
|
|
(maxCount, entry) => Math.min(maxCount, entry.maxMarkersPerDot || CLUSTER_MAX_MARKERS_PER_DOT),
|
|
Number.POSITIVE_INFINITY,
|
|
);
|
|
const safeMaxMarkersPerDot = Number.isFinite(maxMarkersPerDot)
|
|
? maxMarkersPerDot
|
|
: CLUSTER_MAX_MARKERS_PER_DOT;
|
|
if (groupEntries.length <= safeMaxMarkersPerDot) return [groupEntries];
|
|
|
|
const sortedEntries = [...groupEntries].sort(compareEntriesByStableGeography);
|
|
const chunks = [];
|
|
for (let index = 0; index < sortedEntries.length; index += safeMaxMarkersPerDot) {
|
|
chunks.push(sortedEntries.slice(index, index + safeMaxMarkersPerDot));
|
|
}
|
|
return chunks;
|
|
}
|
|
|
|
function computeSphericalClusterRecords(entries, config) {
|
|
if (!entries.length || config.distance <= 0) return [];
|
|
|
|
const radius =
|
|
entries.find((entry) => Number.isFinite(entry.radiusWorld))?.radiusWorld ||
|
|
CONFIG.earthRadius;
|
|
const angularThreshold = Math.max(0.00001, config.distance / Math.max(1, radius));
|
|
const lonBucketCount = Math.max(1, Math.ceil((Math.PI * 2) / angularThreshold));
|
|
const buckets = new Map();
|
|
const entryState = entries.map((entry) => {
|
|
const { lat, lon } = getEntrySphericalCoordinates(entry);
|
|
const latIndex = Math.floor(lat / angularThreshold);
|
|
const lonIndex = normalizeSphericalLongitudeIndex(
|
|
Math.floor(lon / angularThreshold),
|
|
lonBucketCount,
|
|
);
|
|
const state = {
|
|
...entry,
|
|
latIndex,
|
|
lonIndex,
|
|
};
|
|
const key = getSphericalBucketKey(latIndex, lonIndex);
|
|
if (!buckets.has(key)) buckets.set(key, []);
|
|
buckets.get(key).push(state);
|
|
return state;
|
|
});
|
|
|
|
const unvisited = new Set(entryState);
|
|
const groups = [];
|
|
entryState
|
|
.slice()
|
|
.sort((a, b) => a.stableId.localeCompare(b.stableId))
|
|
.forEach((seed) => {
|
|
if (!unvisited.has(seed)) return;
|
|
const groupEntries = [seed];
|
|
unvisited.delete(seed);
|
|
const neighborKeys = getNeighboringSphericalBucketKeys(
|
|
seed.latIndex,
|
|
seed.lonIndex,
|
|
lonBucketCount,
|
|
);
|
|
const candidates = neighborKeys
|
|
.flatMap((key) => buckets.get(key) || [])
|
|
.filter((candidate) => unvisited.has(candidate))
|
|
.sort((a, b) => getAngularDistance(seed, a) - getAngularDistance(seed, b) || a.stableId.localeCompare(b.stableId));
|
|
|
|
candidates.forEach((candidate) => {
|
|
if (!unvisited.has(candidate)) return;
|
|
if (getAngularDistance(seed, candidate) > angularThreshold) return;
|
|
const overlapsGroup = groupEntries.some(
|
|
(entry) => getAngularDistance(candidate, entry) <= angularThreshold,
|
|
);
|
|
if (!overlapsGroup) return;
|
|
groupEntries.push(candidate);
|
|
unvisited.delete(candidate);
|
|
});
|
|
|
|
if (groupEntries.length >= config.minCount) {
|
|
groups.push(groupEntries.sort((a, b) => a.stableId.localeCompare(b.stableId)));
|
|
return;
|
|
}
|
|
|
|
groupEntries.forEach((entry) => unvisited.add(entry));
|
|
});
|
|
|
|
return groups
|
|
.flatMap(splitLargeClusterGroup)
|
|
.map(createClusterRecord)
|
|
.filter(Boolean);
|
|
}
|
|
|
|
function compareEntriesByStableGeography(a, b) {
|
|
const lonA = Math.atan2(a.direction.z, a.direction.x);
|
|
const lonB = Math.atan2(b.direction.z, b.direction.x);
|
|
if (Math.abs(lonA - lonB) > 1e-6) return lonA - lonB;
|
|
const latA = Math.asin(Math.max(-1, Math.min(1, a.direction.y)));
|
|
const latB = Math.asin(Math.max(-1, Math.min(1, b.direction.y)));
|
|
if (Math.abs(latA - latB) > 1e-6) return latA - latB;
|
|
return a.stableId.localeCompare(b.stableId);
|
|
}
|
|
|
|
function createClusterRecord(groupEntries) {
|
|
const sortedEntries = [...groupEntries].sort((a, b) => a.stableId.localeCompare(b.stableId));
|
|
const anchorEntry = sortedEntries[0];
|
|
const clusterPosition = new THREE.Vector3();
|
|
let positionCount = 0;
|
|
sortedEntries.forEach((entry) => {
|
|
const position = getMarkerStaticAvoidancePosition(entry.marker);
|
|
if (!(position instanceof THREE.Vector3)) return;
|
|
clusterPosition.add(position);
|
|
positionCount += 1;
|
|
});
|
|
if (positionCount === 0) return null;
|
|
const fallbackPosition = getMarkerStaticAvoidancePosition(anchorEntry?.marker);
|
|
const altitudeRadius =
|
|
fallbackPosition instanceof THREE.Vector3
|
|
? fallbackPosition.length()
|
|
: CONFIG.earthRadius;
|
|
clusterPosition.normalize().multiplyScalar(altitudeRadius);
|
|
|
|
const clusterId = getClusterRecordId(sortedEntries);
|
|
return {
|
|
clusterId,
|
|
markers: sortedEntries.map((entry) => entry.marker),
|
|
owner: anchorEntry.controller,
|
|
position: clusterPosition,
|
|
};
|
|
}
|
|
|
|
function updateClusterPresentation(camera, selectedMarker) {
|
|
if (!camera) return;
|
|
const controllersToRebuild = new Set();
|
|
interactableLayerControllers.forEach((controller) => {
|
|
controller.beginClusterUpdate?.();
|
|
});
|
|
const records = [...interactableLayerControllers.values()]
|
|
.flatMap(controller => controller.collectClusterRecords(camera));
|
|
records.forEach((record) => {
|
|
record.owner.addOwnedCluster?.(record);
|
|
record.markers.forEach((marker) => {
|
|
const owner = interactableLayerControllers.get(marker.userData?.icon_layer_id);
|
|
owner?.markMarkerClustered?.(marker, record);
|
|
});
|
|
});
|
|
|
|
interactableLayerControllers.forEach((controller) => {
|
|
if (controller.commitClusterUpdate?.()) {
|
|
controllersToRebuild.add(controller);
|
|
}
|
|
});
|
|
if (!clusterPresentation) clusterPresentation = createClusterPresentation({
|
|
getOwner: marker => interactableLayerControllers.get(marker.userData?.icon_layer_id),
|
|
onHiddenChange: owner => owner?.rebuildPointLayers(),
|
|
});
|
|
const stackCandidates = [...interactableLayerControllers.values()]
|
|
.flatMap(controller => controller.getPresentationMarkers());
|
|
clusterPresentation.update(records, camera,
|
|
globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ), stackCandidates, selectedMarker);
|
|
controllersToRebuild.forEach((controller) => controller.rebuildPointLayers?.(camera));
|
|
}
|
|
|
|
function loadAssetImage(source) {
|
|
if (!source) return Promise.resolve(null);
|
|
if (assetImageCache.has(source)) {
|
|
return Promise.resolve(assetImageCache.get(source));
|
|
}
|
|
if (assetImageLoadPromises.has(source)) {
|
|
return assetImageLoadPromises.get(source);
|
|
}
|
|
|
|
const loadPromise = new Promise((resolve, reject) => {
|
|
const image = new Image();
|
|
image.onload = () => {
|
|
assetImageCache.set(source, image);
|
|
assetImageLoadPromises.delete(source);
|
|
resolve(image);
|
|
};
|
|
image.onerror = () => {
|
|
assetImageLoadPromises.delete(source);
|
|
reject(new Error(`Failed to load interactable icon asset: ${source}`));
|
|
};
|
|
image.src = source;
|
|
});
|
|
|
|
assetImageLoadPromises.set(source, loadPromise);
|
|
return loadPromise;
|
|
}
|
|
|
|
export function createInteractableLayer(options = {}) {
|
|
const {
|
|
id,
|
|
objectType = id,
|
|
renderOrder = 4,
|
|
altitudeOffset = 0.2,
|
|
pointSize = 32,
|
|
sizeMode = "fixed",
|
|
sizeScale = {},
|
|
atlasCellSize = 128,
|
|
material = {},
|
|
colors = {},
|
|
opacity = {},
|
|
stateScale = {},
|
|
pulse = {},
|
|
avoidance = false,
|
|
cluster = undefined,
|
|
icon,
|
|
surfaceAnchorOcclusion = false,
|
|
getPosition,
|
|
getKind = (item) => item?.type || "default",
|
|
getRotationBin = () => 0,
|
|
getBucketKey = (marker) => String(getRotationBin(marker)),
|
|
getItemId = (item) => item?.id ?? item?.source_id ?? item?.entity_key,
|
|
getPointSizeMultiplier = () => 1,
|
|
getPointOpacity = null,
|
|
getUserData = (item) => item,
|
|
isItemVisible = () => true,
|
|
dynamicVisuals = false,
|
|
} = options;
|
|
|
|
if (!id) {
|
|
throw new Error("createInteractableLayer requires an id");
|
|
}
|
|
if (!icon?.draw && !icon?.source && !icon?.getSource) {
|
|
throw new Error(`Interactable layer ${id} requires icon.draw, icon.source, or icon.getSource`);
|
|
}
|
|
|
|
const group = new THREE.Group();
|
|
group.name = `interactable-layer:${id}`;
|
|
group.renderOrder = renderOrder;
|
|
group.userData = { type: "interactable_layer", id };
|
|
|
|
const markers = [];
|
|
const pointObjects = [];
|
|
const markerById = new Map();
|
|
let currentMarkers = new WeakSet();
|
|
const pointSlots = new WeakMap();
|
|
const textureCache = new Map();
|
|
let pointsGroup = null;
|
|
let hoverOverlay = null;
|
|
let lockedOverlay = null;
|
|
let visible = false;
|
|
let lastVisualStateKey = "";
|
|
let lastClusterSignature = "";
|
|
let pendingClusterSignature = "";
|
|
let clusterUpdateActive = false;
|
|
let visualStateVersion = 0;
|
|
let clusterTopologyRevision = 0;
|
|
let lastStableClusterKey = "";
|
|
let stableClusterRecords = [];
|
|
let detailClusterMode = false;
|
|
const ownedClusterRecords = [];
|
|
const scratchDirection = new THREE.Vector3();
|
|
const scratchCameraLocal = new THREE.Vector3();
|
|
const scratchCameraPositionLocal = new THREE.Vector3();
|
|
const scratchWorldPosition = new THREE.Vector3();
|
|
const scratchScreenPosition = new THREE.Vector3();
|
|
const viewportSize = new THREE.Vector2(1, 1);
|
|
|
|
const baseOpacity = opacity.normal ?? 0.88;
|
|
const dimmedOpacity = opacity.dimmed ?? 0.26;
|
|
const hoverOpacity = opacity.hover ?? 0.98;
|
|
const lockedOpacity = opacity.locked ?? 1;
|
|
const hoverScale = stateScale.hover ?? 1;
|
|
const lockedScale = stateScale.locked ?? 1;
|
|
const dimmedScale = stateScale.dimmed ?? 1;
|
|
// Rounded badges enable this implicitly, while other icon styles can opt
|
|
// into the same whole-billboard surface behavior without changing artwork.
|
|
const usesSurfaceAnchorOcclusion = Boolean(surfaceAnchorOcclusion || icon.badge);
|
|
const depthTest = usesSurfaceAnchorOcclusion ? false : material.depthTest ?? true;
|
|
const depthWrite = material.depthWrite ?? false;
|
|
const alphaTest = material.alphaTest ?? 0.01;
|
|
const usesDistanceScaling = sizeMode !== "fixed";
|
|
const iconAnchor = new THREE.Vector2(
|
|
Number(icon.anchor?.x ?? icon.anchor?.[0] ?? 0.5),
|
|
Number(icon.anchor?.y ?? icon.anchor?.[1] ?? 0.5),
|
|
);
|
|
const usesIconAnchor =
|
|
Math.abs(iconAnchor.x - 0.5) > 0.001 ||
|
|
Math.abs(iconAnchor.y - 0.5) > 0.001;
|
|
const avoidanceConfig = normalizeAvoidanceConfig(avoidance);
|
|
const clusterConfig = normalizeClusterConfig(cluster, avoidanceConfig);
|
|
|
|
function invalidateVisualState() {
|
|
visualStateVersion += 1;
|
|
lastVisualStateKey = "";
|
|
}
|
|
|
|
function invalidateClusterTopology() {
|
|
clusterTopologyRevision += 1;
|
|
lastStableClusterKey = "";
|
|
lastClusterSignature = "";
|
|
}
|
|
|
|
function refreshViewportSize() {
|
|
const pixelRatio = window.devicePixelRatio || 1;
|
|
viewportSize.set(
|
|
(window.innerWidth || 1) * pixelRatio,
|
|
(window.innerHeight || 1) * pixelRatio,
|
|
);
|
|
}
|
|
|
|
function applyIconAnchor(material) {
|
|
if (!usesIconAnchor && !usesSurfaceAnchorOcclusion) return material;
|
|
|
|
material.defines = {
|
|
...(material.defines || {}),
|
|
...(usesIconAnchor ? { USE_INTERACTABLE_ICON_ANCHOR: "" } : {}),
|
|
...(usesSurfaceAnchorOcclusion ? { USE_SURFACE_ANCHOR_OCCLUSION: "" } : {}),
|
|
};
|
|
material.onBeforeCompile = (shader) => {
|
|
shader.uniforms.interactableIconAnchor = { value: iconAnchor };
|
|
shader.uniforms.interactableViewportSize = { value: viewportSize };
|
|
shader.vertexShader = shader.vertexShader
|
|
.replace(
|
|
"#include <common>",
|
|
[
|
|
"#include <common>",
|
|
"uniform vec2 interactableIconAnchor;",
|
|
"uniform vec2 interactableViewportSize;",
|
|
usesSurfaceAnchorOcclusion ? SURFACE_ANCHOR_OCCLUSION_GLSL : "",
|
|
].join("\n"),
|
|
)
|
|
.replace(
|
|
"#include <project_vertex>",
|
|
[
|
|
"#include <project_vertex>",
|
|
"#ifdef USE_INTERACTABLE_ICON_ANCHOR",
|
|
" vec2 interactableAnchorOffset = vec2((0.5 - interactableIconAnchor.x) * size, (interactableIconAnchor.y - 0.5) * size);",
|
|
" gl_Position.xy += (interactableAnchorOffset / interactableViewportSize) * 2.0 * gl_Position.w;",
|
|
"#endif",
|
|
"#ifdef USE_SURFACE_ANCHOR_OCCLUSION",
|
|
" vec3 globeCenterView = modelViewMatrix[3].xyz;",
|
|
` float globeRadius = ${CONFIG.earthRadius.toFixed(6)} * length(modelViewMatrix[0].xyz);`,
|
|
" if (surfaceAnchorOccluded(-globeCenterView, mvPosition.xyz - globeCenterView, globeRadius)) {",
|
|
" gl_Position = vec4(0.0, 0.0, 2.0, 1.0);",
|
|
" }",
|
|
"#endif",
|
|
].join("\n"),
|
|
);
|
|
};
|
|
material.customProgramCacheKey = () =>
|
|
`interactable-icon-anchor:${iconAnchor.x.toFixed(3)}:${iconAnchor.y.toFixed(3)}:${usesSurfaceAnchorOcclusion}`;
|
|
return material;
|
|
}
|
|
|
|
function getMarkerColor(marker) {
|
|
const kind = marker?.userData?.icon_kind || getKind(marker?.userData);
|
|
return colors.byKind?.[kind] || colors[kind] || colors.normal || "#ffffff";
|
|
}
|
|
|
|
function getIconSource(drawOptions) {
|
|
const stateSource = icon.stateSources?.[drawOptions.state];
|
|
if (stateSource) return stateSource;
|
|
if (typeof icon.getSource === "function") {
|
|
return icon.getSource(drawOptions);
|
|
}
|
|
return icon.source;
|
|
}
|
|
|
|
function drawAssetIcon(context, source, drawOptions) {
|
|
const image = assetImageCache.get(source);
|
|
if (!image) {
|
|
icon.fallbackDraw?.(context, drawOptions);
|
|
return;
|
|
}
|
|
|
|
if (drawOptions.glow) {
|
|
context.shadowColor = drawOptions.color || "#ffffff";
|
|
context.shadowBlur = icon.glowBlur ?? 14;
|
|
}
|
|
|
|
const fitSize =
|
|
typeof icon.fitSize === "function"
|
|
? icon.fitSize(drawOptions)
|
|
: icon.fitSize;
|
|
const fitWidth =
|
|
typeof fitSize === "number"
|
|
? fitSize
|
|
: Number(fitSize?.width ?? atlasCellSize);
|
|
const fitHeight =
|
|
typeof fitSize === "number"
|
|
? fitSize
|
|
: Number(fitSize?.height ?? atlasCellSize);
|
|
const maxWidth = Number.isFinite(fitWidth) ? fitWidth : atlasCellSize;
|
|
const maxHeight = Number.isFinite(fitHeight) ? fitHeight : atlasCellSize;
|
|
const sourceWidth = image.naturalWidth || image.width || atlasCellSize;
|
|
const sourceHeight = image.naturalHeight || image.height || atlasCellSize;
|
|
const scale = Math.min(maxWidth / sourceWidth, maxHeight / sourceHeight);
|
|
const drawWidth = sourceWidth * scale;
|
|
const drawHeight = sourceHeight * scale;
|
|
const drawX = (atlasCellSize - drawWidth) / 2;
|
|
const drawY = (atlasCellSize - drawHeight) / 2;
|
|
|
|
if ((icon.colorable !== false || icon.badge) && drawOptions.color) {
|
|
const tintCanvas = createCanvas(atlasCellSize, atlasCellSize);
|
|
const tintContext = tintCanvas.getContext("2d");
|
|
tintContext.clearRect(0, 0, atlasCellSize, atlasCellSize);
|
|
tintContext.drawImage(image, drawX, drawY, drawWidth, drawHeight);
|
|
tintContext.globalCompositeOperation = "source-in";
|
|
tintContext.fillStyle = drawOptions.color;
|
|
tintContext.fillRect(0, 0, atlasCellSize, atlasCellSize);
|
|
context.drawImage(tintCanvas, 0, 0);
|
|
return;
|
|
}
|
|
|
|
context.drawImage(image, drawX, drawY, drawWidth, drawHeight);
|
|
}
|
|
|
|
function drawIconTexture(textureKey, drawOptions) {
|
|
if (textureCache.has(textureKey)) return textureCache.get(textureKey);
|
|
|
|
const canvas = document.createElement("canvas");
|
|
canvas.width = atlasCellSize;
|
|
canvas.height = atlasCellSize;
|
|
const context = canvas.getContext("2d");
|
|
context.clearRect(0, 0, canvas.width, canvas.height);
|
|
context.save();
|
|
const resolvedDrawOptions = {
|
|
atlasCellSize,
|
|
...drawOptions,
|
|
};
|
|
const badgeOptions = typeof icon.badge === "function" ? icon.badge(resolvedDrawOptions) : icon.badge;
|
|
if (badgeOptions) {
|
|
const palette = drawMarkerBadge(context, { ...resolvedDrawOptions, ...badgeOptions });
|
|
resolvedDrawOptions.color = palette.ink;
|
|
resolvedDrawOptions.glow = false;
|
|
context.translate(canvas.width / 2, canvas.height / 2);
|
|
context.scale(0.6, 0.6);
|
|
if (icon.coordinates === "canvas") context.translate(-canvas.width / 2, -canvas.height / 2);
|
|
} else if (icon.coordinates !== "canvas") {
|
|
context.translate(canvas.width / 2, canvas.height / 2);
|
|
}
|
|
if (icon.draw) {
|
|
icon.draw(context, resolvedDrawOptions);
|
|
} else {
|
|
drawAssetIcon(context, getIconSource(resolvedDrawOptions), resolvedDrawOptions);
|
|
}
|
|
context.restore();
|
|
context.save();
|
|
if (icon.coordinates !== "canvas") context.translate(canvas.width / 2, canvas.height / 2);
|
|
icon.afterDraw?.(context, { atlasCellSize, ...drawOptions });
|
|
context.restore();
|
|
|
|
const texture = new THREE.CanvasTexture(canvas);
|
|
texture.generateMipmaps = false;
|
|
texture.minFilter = THREE.LinearFilter;
|
|
texture.magFilter = THREE.LinearFilter;
|
|
texture.needsUpdate = true;
|
|
textureCache.set(textureKey, texture);
|
|
return texture;
|
|
}
|
|
|
|
function createPointTexture(bucketKey, bucketMarkers) {
|
|
const sampleMarker = bucketMarkers[0];
|
|
const rotationBin = getRotationBin(sampleMarker);
|
|
return drawIconTexture(`point:${bucketKey}`, {
|
|
marker: sampleMarker,
|
|
bucketKey,
|
|
rotationBin,
|
|
glow: false,
|
|
color: "#ffffff",
|
|
state: "normal",
|
|
});
|
|
}
|
|
|
|
function createOverlayTexture(marker, state) {
|
|
const kind = marker?.userData?.icon_kind || "default";
|
|
const rotationBin = getRotationBin(marker);
|
|
const color = getMarkerColor(marker);
|
|
const textureKey = [
|
|
"overlay",
|
|
state,
|
|
kind,
|
|
getBucketKey(marker),
|
|
rotationBin,
|
|
color,
|
|
].join(":");
|
|
return drawIconTexture(textureKey, {
|
|
marker,
|
|
bucketKey: getBucketKey(marker),
|
|
rotationBin,
|
|
glow: true,
|
|
color,
|
|
state,
|
|
});
|
|
}
|
|
|
|
function getCameraScale(camera) {
|
|
if (!usesDistanceScaling || !camera) return 1;
|
|
return getSurfaceMarkerCameraScale(camera, {
|
|
altitudeOffset,
|
|
referenceFov: sizeScale.referenceFov ?? 75,
|
|
min: sizeScale.min ?? 0.12,
|
|
max: sizeScale.max ?? 3,
|
|
});
|
|
}
|
|
|
|
function getCameraZoom(camera) {
|
|
if (!camera?.position?.z) return CONFIG.defaultViewZoom;
|
|
return globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ);
|
|
}
|
|
|
|
function itemKey(item) {
|
|
const value = getItemId(item);
|
|
if (typeof value !== "string" && typeof value !== "number") return null;
|
|
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
const key = String(value).trim();
|
|
return key && key !== "-" ? key : null;
|
|
}
|
|
|
|
function indexMarker(marker) {
|
|
currentMarkers.add(marker);
|
|
const key = itemKey(marker.userData);
|
|
marker.userData.icon_item_id = key;
|
|
if (key === null) return;
|
|
// An ambiguous key cannot identify a replacement after a data refresh.
|
|
if (markerById.has(key)) {
|
|
const previous = markerById.get(key);
|
|
if (previous) previous.userData.icon_item_id = null;
|
|
marker.userData.icon_item_id = null;
|
|
markerById.set(key, null);
|
|
} else markerById.set(key, marker);
|
|
}
|
|
|
|
function getMarkerStableId(marker, fallbackIndex = 0) {
|
|
const itemId = itemKey(marker?.userData || {});
|
|
if (itemId !== undefined && itemId !== null && String(itemId).trim() !== "") {
|
|
return String(itemId);
|
|
}
|
|
return `${id}:${fallbackIndex}`;
|
|
}
|
|
|
|
function beginClusterUpdate() {
|
|
if (!clusterConfig.enabled) return;
|
|
clusterUpdateActive = true;
|
|
ownedClusterRecords.length = 0;
|
|
markers.forEach((marker) => {
|
|
marker.userData.icon_cluster_hidden = false;
|
|
marker.userData.icon_cluster_count = 1;
|
|
marker.userData.icon_cluster_id = null;
|
|
});
|
|
}
|
|
|
|
function collectClusterRecords(camera) {
|
|
if (!visible || !clusterConfig.enabled || !camera || markers.length === 0) return [];
|
|
const zoom = getCameraZoom(camera);
|
|
if (zoom > clusterConfig.disableAboveZoom) detailClusterMode = true;
|
|
else if (zoom < clusterConfig.disableAboveZoom * (1 - clusterConfig.expansionHysteresis)) detailClusterMode = false;
|
|
|
|
// Geographic membership is cached across camera motion and zoom; only
|
|
// data/filter changes invalidate it. The presentation owns the one tween.
|
|
const stableKey = `${id}:${clusterTopologyRevision}`;
|
|
if (stableKey !== lastStableClusterKey) {
|
|
const entries = markers.flatMap((marker, index) => {
|
|
if (!isItemVisible(marker.userData)) return [];
|
|
const position = getMarkerStaticAvoidancePosition(marker);
|
|
if (!(position instanceof THREE.Vector3)) return [];
|
|
return [{
|
|
marker,
|
|
stableId: `${id}:${getMarkerStableId(marker, index)}`,
|
|
controller,
|
|
direction: position.clone().normalize(),
|
|
radiusWorld: position.length(),
|
|
maxMarkersPerDot: clusterConfig.maxMarkersPerDot,
|
|
}];
|
|
}).sort((a, b) => a.stableId.localeCompare(b.stableId));
|
|
stableClusterRecords = computeSphericalClusterRecords(entries, clusterConfig);
|
|
lastStableClusterKey = stableKey;
|
|
}
|
|
return stableClusterRecords.map(record => ({ ...record, expanded: detailClusterMode }));
|
|
}
|
|
|
|
function addOwnedCluster(record) {
|
|
ownedClusterRecords.push(record);
|
|
}
|
|
|
|
function markMarkerClustered(marker, record) {
|
|
if (!marker || marker.userData?.icon_layer_id !== id) return;
|
|
marker.userData.icon_cluster_hidden = true;
|
|
marker.userData.icon_cluster_count = record.markers.length;
|
|
marker.userData.icon_cluster_id = record.clusterId;
|
|
}
|
|
|
|
function getClusterSignature() {
|
|
return ownedClusterRecords
|
|
.map((record) =>
|
|
record.clusterId,
|
|
)
|
|
.join("|");
|
|
}
|
|
|
|
function commitClusterUpdate() {
|
|
if (!clusterUpdateActive) return false;
|
|
clusterUpdateActive = false;
|
|
pendingClusterSignature = getClusterSignature();
|
|
if (pendingClusterSignature === lastClusterSignature) return false;
|
|
lastClusterSignature = pendingClusterSignature;
|
|
return true;
|
|
}
|
|
|
|
function disposePointsGroup() {
|
|
if (pointsGroup?.parent) {
|
|
pointsGroup.parent.remove(pointsGroup);
|
|
}
|
|
pointObjects.forEach((points) => {
|
|
points.userData?.markers?.forEach(marker => pointSlots.delete(marker));
|
|
points.geometry?.dispose?.();
|
|
points.material?.dispose?.();
|
|
});
|
|
pointsGroup = null;
|
|
pointObjects.length = 0;
|
|
}
|
|
|
|
function rebuildPointLayers(camera = null) {
|
|
disposePointsGroup();
|
|
buildPoints(camera);
|
|
if (pointsGroup) pointsGroup.visible = visible;
|
|
invalidateVisualState();
|
|
}
|
|
|
|
function updatePointColors(points) {
|
|
const bucketMarkers = points.userData?.markers || [];
|
|
const colorAttribute = points.geometry?.getAttribute("color");
|
|
if (!colorAttribute?.array) return;
|
|
let firstChanged = -1;
|
|
let lastChanged = -1;
|
|
bucketMarkers.forEach((marker, index) => {
|
|
const pointColor =
|
|
icon.colorable !== false
|
|
? getMarkerColor(marker)
|
|
: "#ffffff";
|
|
const [r, g, b] = colorToRgbArray(pointColor);
|
|
if (colorAttribute.getX(index) !== Math.fround(r)
|
|
|| colorAttribute.getY(index) !== Math.fround(g)
|
|
|| colorAttribute.getZ(index) !== Math.fround(b)) {
|
|
colorAttribute.setXYZ(index, r, g, b);
|
|
if (firstChanged < 0) firstChanged = index;
|
|
lastChanged = index;
|
|
}
|
|
});
|
|
if (firstChanged >= 0) markAttributeRange(colorAttribute, firstChanged * 3, (lastChanged - firstChanged + 1) * 3);
|
|
}
|
|
|
|
function addPointBucket(bucketKey, bucketMarkers) {
|
|
const count = bucketMarkers.length;
|
|
const positions = new Float32Array(count * 3);
|
|
const colorValues = new Float32Array(count * 3);
|
|
|
|
bucketMarkers.forEach((marker, index) => {
|
|
positions[index * 3] = marker.position.x;
|
|
positions[index * 3 + 1] = marker.position.y;
|
|
positions[index * 3 + 2] = marker.position.z;
|
|
const pointColor =
|
|
icon.colorable === false ? "#ffffff" : getMarkerColor(marker);
|
|
const [r, g, b] = colorToRgbArray(pointColor);
|
|
colorValues[index * 3] = r;
|
|
colorValues[index * 3 + 1] = g;
|
|
colorValues[index * 3 + 2] = b;
|
|
});
|
|
|
|
const geometry = new THREE.BufferGeometry();
|
|
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));
|
|
geometry.setAttribute("color", new THREE.BufferAttribute(colorValues, 3).setUsage(THREE.DynamicDrawUsage));
|
|
geometry.computeBoundingSphere();
|
|
|
|
const material = applyIconAnchor(
|
|
new THREE.PointsMaterial({
|
|
map: createPointTexture(bucketKey, bucketMarkers),
|
|
size:
|
|
pointSize *
|
|
getPointSizeMultiplier(bucketMarkers[0]),
|
|
sizeAttenuation: false,
|
|
vertexColors: true,
|
|
transparent: true,
|
|
opacity: getPointOpacity?.(bucketMarkers[0]) ?? baseOpacity,
|
|
depthWrite,
|
|
depthTest,
|
|
alphaTest,
|
|
}),
|
|
);
|
|
|
|
const points = new THREE.Points(geometry, material);
|
|
points.renderOrder = renderOrder;
|
|
points.frustumCulled = false;
|
|
points.userData = {
|
|
type: `${id}_points`,
|
|
id,
|
|
bucketKey,
|
|
markers: bucketMarkers,
|
|
pointSizeMultiplier: getPointSizeMultiplier(bucketMarkers[0]),
|
|
};
|
|
pointObjects.push(points);
|
|
pointsGroup.add(points);
|
|
bucketMarkers.forEach((marker, index) => pointSlots.set(marker, { points, index }));
|
|
return points;
|
|
}
|
|
|
|
function buildPoints(camera = null) {
|
|
refreshViewportSize();
|
|
pointsGroup = new THREE.Group();
|
|
pointsGroup.visible = visible;
|
|
pointsGroup.renderOrder = renderOrder;
|
|
pointsGroup.userData = { type: `${id}_points`, id };
|
|
pointObjects.length = 0;
|
|
|
|
const buckets = new Map();
|
|
markers
|
|
.filter((marker) => !marker.userData?.icon_cluster_hidden && !marker.userData?.icon_presentation_hidden && isItemVisible(marker.userData))
|
|
.forEach((marker) => {
|
|
const key = getBucketKey(marker);
|
|
if (!buckets.has(key)) {
|
|
buckets.set(key, []);
|
|
}
|
|
buckets.get(key).push(marker);
|
|
});
|
|
|
|
buckets.forEach((bucketMarkers, bucketKey) => {
|
|
addPointBucket(bucketKey, bucketMarkers);
|
|
});
|
|
|
|
group.add(pointsGroup);
|
|
}
|
|
|
|
function ensureOverlay(kind) {
|
|
const existing = kind === "locked" ? lockedOverlay : hoverOverlay;
|
|
if (existing) return existing;
|
|
refreshViewportSize();
|
|
|
|
const geometry = new THREE.BufferGeometry();
|
|
geometry.setAttribute(
|
|
"position",
|
|
new THREE.BufferAttribute(new Float32Array(3), 3),
|
|
);
|
|
const material = applyIconAnchor(
|
|
new THREE.PointsMaterial({
|
|
size: pointSize,
|
|
sizeAttenuation: false,
|
|
transparent: true,
|
|
depthWrite,
|
|
depthTest,
|
|
opacity: 1,
|
|
alphaTest,
|
|
}),
|
|
);
|
|
const overlay = new THREE.Points(geometry, material);
|
|
overlay.renderOrder = kind === "locked"
|
|
? Math.max(renderOrder + 0.2, INTERACTABLE_FOCUS_RENDER_ORDER)
|
|
: Math.max(renderOrder + 0.1, INTERACTABLE_FOCUS_RENDER_ORDER - 0.1);
|
|
overlay.frustumCulled = false;
|
|
overlay.visible = false;
|
|
overlay.userData = { type: `${id}_${kind}_overlay`, id };
|
|
group.add(overlay);
|
|
|
|
if (kind === "locked") {
|
|
lockedOverlay = overlay;
|
|
} else {
|
|
hoverOverlay = overlay;
|
|
}
|
|
return overlay;
|
|
}
|
|
|
|
function updateOverlay(overlay, marker, state, nextOpacity, sizeMultiplier = 1) {
|
|
if (!overlay) return;
|
|
if (!marker || marker.userData.icon_cluster_hidden || marker.userData.icon_presentation_hidden || !isItemVisible(marker.userData)) {
|
|
overlay.visible = false;
|
|
return;
|
|
}
|
|
|
|
const texture = createOverlayTexture(marker, state);
|
|
if (overlay.material.map !== texture) {
|
|
overlay.material.map = texture;
|
|
overlay.material.needsUpdate = true;
|
|
}
|
|
overlay.material.opacity = nextOpacity;
|
|
overlay.material.size =
|
|
pointSize *
|
|
getPointSizeMultiplier(marker) *
|
|
sizeMultiplier;
|
|
const positionAttribute = overlay.geometry.getAttribute("position");
|
|
positionAttribute.setXYZ(0, marker.position.x, marker.position.y, marker.position.z);
|
|
positionAttribute.needsUpdate = true;
|
|
overlay.visible = visible;
|
|
}
|
|
|
|
function clearRenderObjects() {
|
|
disposePointsGroup();
|
|
hoverOverlay?.geometry?.dispose?.();
|
|
hoverOverlay?.material?.dispose?.();
|
|
hoverOverlay?.parent?.remove?.(hoverOverlay);
|
|
lockedOverlay?.geometry?.dispose?.();
|
|
lockedOverlay?.material?.dispose?.();
|
|
lockedOverlay?.parent?.remove?.(lockedOverlay);
|
|
hoverOverlay = null;
|
|
lockedOverlay = null;
|
|
}
|
|
|
|
function refreshPositions() {
|
|
pointObjects.forEach((points) => {
|
|
const bucketMarkers = points.userData?.markers || [];
|
|
const positionAttribute = points.geometry?.getAttribute("position");
|
|
if (!positionAttribute) return;
|
|
bucketMarkers.forEach((marker, index) => {
|
|
positionAttribute.setXYZ(
|
|
index,
|
|
marker.position.x,
|
|
marker.position.y,
|
|
marker.position.z,
|
|
);
|
|
});
|
|
positionAttribute.needsUpdate = true;
|
|
points.geometry.computeBoundingSphere();
|
|
});
|
|
invalidateVisualState();
|
|
}
|
|
|
|
function refreshVisuals() {
|
|
invalidateVisualState();
|
|
invalidateClusterTopology();
|
|
if (!pointsGroup) return;
|
|
rebuildPointLayers();
|
|
group.visible = visible;
|
|
}
|
|
|
|
function setData(items = []) {
|
|
invalidateVisualState();
|
|
invalidateClusterTopology();
|
|
unregisterLayerAvoidance(id);
|
|
markers.length = 0;
|
|
markerById.clear();
|
|
currentMarkers = new WeakSet();
|
|
clearRenderObjects();
|
|
disposeGroupChildren(group);
|
|
|
|
const radius = CONFIG.earthRadius + altitudeOffset;
|
|
items.forEach((item) => {
|
|
const rawPosition = getPosition(item);
|
|
const position = normalizePosition(rawPosition, radius);
|
|
if (!position) return;
|
|
const kind = getKind(item);
|
|
const avoidanceKey = avoidanceConfig.enabled
|
|
? getAvoidanceKey(item, rawPosition, position, avoidanceConfig)
|
|
: null;
|
|
const marker = new THREE.Object3D();
|
|
marker.position.copy(position);
|
|
marker.userData = {
|
|
...getUserData(item),
|
|
type: objectType,
|
|
icon_layer_id: id,
|
|
icon_kind: kind,
|
|
icon_base_position: position.clone(),
|
|
icon_presentation_hidden: false,
|
|
icon_presentation_screen: null,
|
|
icon_avoidance_key: avoidanceKey,
|
|
state: "normal",
|
|
};
|
|
marker.userData.legend_filtered = !isItemVisible(marker.userData);
|
|
markers.push(marker);
|
|
indexMarker(marker);
|
|
});
|
|
|
|
registerLayerAvoidance(id, markers, avoidanceConfig);
|
|
buildPoints();
|
|
group.visible = visible;
|
|
}
|
|
|
|
function rebuildFromMarkerData(items) {
|
|
const wasVisible = visible;
|
|
setData(items);
|
|
group.visible = wasVisible;
|
|
}
|
|
|
|
function markAttributeRange(attribute, offset, count) {
|
|
const range = attribute.updateRange;
|
|
const start = range.count < 0 ? offset : Math.min(offset, range.offset);
|
|
const end = range.count < 0 ? offset + count : Math.max(offset + count, range.offset + range.count);
|
|
range.offset = start;
|
|
range.count = end - start;
|
|
attribute.needsUpdate = true;
|
|
}
|
|
|
|
function syncPointBucket(bucketKey, bucketMarkers) {
|
|
bucketMarkers = bucketMarkers.filter(marker => isItemVisible(marker.userData));
|
|
let points = pointObjects.find((entry) => entry.userData.bucketKey === bucketKey);
|
|
if (!points) {
|
|
if (bucketMarkers.length) addPointBucket(bucketKey, bucketMarkers);
|
|
return;
|
|
}
|
|
const currentCapacity = points.geometry.attributes.position.count;
|
|
if (currentCapacity < bucketMarkers.length) {
|
|
const capacity = Math.max(bucketMarkers.length, currentCapacity * 2, POINT_BUCKET_MIN_CAPACITY);
|
|
points.geometry.dispose();
|
|
points.geometry = new THREE.BufferGeometry();
|
|
for (const name of ["position", "color"]) {
|
|
points.geometry.setAttribute(name, new THREE.BufferAttribute(new Float32Array(capacity * 3), 3)
|
|
.setUsage(THREE.DynamicDrawUsage));
|
|
}
|
|
}
|
|
points.userData.markers = bucketMarkers;
|
|
points.geometry.setDrawRange(0, bucketMarkers.length);
|
|
const positions = points.geometry.attributes.position;
|
|
bucketMarkers.forEach((marker, index) => {
|
|
positions.setXYZ(index, marker.position.x, marker.position.y, marker.position.z);
|
|
pointSlots.set(marker, { points, index });
|
|
});
|
|
if (bucketMarkers.length) markAttributeRange(positions, 0, bucketMarkers.length * 3);
|
|
updatePointColors(points);
|
|
}
|
|
|
|
function updateItems(items, { replace = false } = {}) {
|
|
if (clusterConfig.enabled || avoidanceConfig.enabled) {
|
|
throw new Error(`Incremental updates require an unclustered layer: ${id}`);
|
|
}
|
|
if (!pointsGroup) {
|
|
setData(items);
|
|
return;
|
|
}
|
|
const affectedBuckets = new Set();
|
|
const updatedMarkers = [];
|
|
const incomingIds = new Set();
|
|
const radius = CONFIG.earthRadius + altitudeOffset;
|
|
for (const item of items) {
|
|
const itemId = itemKey(item);
|
|
if (!itemId) continue;
|
|
const position = normalizePosition(getPosition(item), radius);
|
|
if (!position) continue;
|
|
incomingIds.add(itemId);
|
|
if (markerById.has(itemId) && markerById.get(itemId) === null) continue;
|
|
let marker = markerById.get(itemId);
|
|
const previousBucket = marker ? getBucketKey(marker) : null;
|
|
const previousVisible = marker ? isItemVisible(marker.userData) : false;
|
|
if (!marker) {
|
|
marker = new THREE.Object3D();
|
|
markers.push(marker);
|
|
currentMarkers.add(marker);
|
|
markerById.set(itemId, marker);
|
|
}
|
|
marker.position.copy(position);
|
|
marker.userData = {
|
|
...marker.userData,
|
|
...getUserData(item),
|
|
type: objectType,
|
|
icon_layer_id: id,
|
|
icon_kind: getKind(item),
|
|
icon_item_id: itemId,
|
|
icon_base_position: position,
|
|
state: marker.userData.state || "normal",
|
|
};
|
|
const nextBucket = getBucketKey(marker);
|
|
marker.userData.legend_filtered = !isItemVisible(marker.userData);
|
|
if (previousBucket !== nextBucket || previousVisible !== !marker.userData.legend_filtered) {
|
|
if (previousBucket !== null) affectedBuckets.add(previousBucket);
|
|
affectedBuckets.add(nextBucket);
|
|
}
|
|
updatedMarkers.push(marker);
|
|
}
|
|
if (replace) {
|
|
let writeIndex = 0;
|
|
for (const marker of markers) {
|
|
const itemId = itemKey(marker.userData);
|
|
if (incomingIds.has(itemId)) markers[writeIndex++] = marker;
|
|
else {
|
|
affectedBuckets.add(getBucketKey(marker));
|
|
markerById.delete(itemId);
|
|
currentMarkers.delete(marker);
|
|
}
|
|
}
|
|
markers.length = writeIndex;
|
|
}
|
|
if (affectedBuckets.size) {
|
|
const buckets = new Map(Array.from(affectedBuckets, (key) => [key, []]));
|
|
markers.forEach((marker) => buckets.get(getBucketKey(marker))?.push(marker));
|
|
buckets.forEach((bucketMarkers, key) => syncPointBucket(key, bucketMarkers));
|
|
}
|
|
updatedMarkers.forEach((marker) => {
|
|
if (!isItemVisible(marker.userData)) return;
|
|
if (affectedBuckets.has(getBucketKey(marker))) return;
|
|
const slot = pointSlots.get(marker);
|
|
if (!slot) return;
|
|
const positions = slot.points.geometry.attributes.position;
|
|
if (positions.getX(slot.index) !== Math.fround(marker.position.x)
|
|
|| positions.getY(slot.index) !== Math.fround(marker.position.y)
|
|
|| positions.getZ(slot.index) !== Math.fround(marker.position.z)) {
|
|
positions.setXYZ(slot.index, marker.position.x, marker.position.y, marker.position.z);
|
|
markAttributeRange(positions, slot.index * 3, 3);
|
|
}
|
|
});
|
|
invalidateVisualState();
|
|
}
|
|
|
|
function upsertItem(item) {
|
|
const itemId = getItemId(item);
|
|
if (itemId === undefined || itemId === null || String(itemId).trim() === "") {
|
|
return false;
|
|
}
|
|
let replaced = false;
|
|
const nextItems = markers.map((marker) => {
|
|
const markerItem = marker.userData || {};
|
|
if (itemKey(markerItem) !== String(itemId).trim()) return { ...markerItem };
|
|
replaced = true;
|
|
return { ...markerItem, ...item };
|
|
});
|
|
if (!replaced) {
|
|
nextItems.push(item);
|
|
}
|
|
rebuildFromMarkerData(nextItems);
|
|
return true;
|
|
}
|
|
|
|
function removeItem(itemId) {
|
|
if (itemId === undefined || itemId === null || String(itemId).trim() === "") {
|
|
return false;
|
|
}
|
|
const nextItems = markers
|
|
.map((marker) => ({ ...(marker.userData || {}) }))
|
|
.filter((item) => itemKey(item) !== String(itemId).trim());
|
|
if (nextItems.length === markers.length) return false;
|
|
rebuildFromMarkerData(nextItems);
|
|
return true;
|
|
}
|
|
|
|
async function preloadAssets(items = []) {
|
|
if (icon.draw && !icon.source && !icon.getSource && !icon.stateSources) {
|
|
return;
|
|
}
|
|
|
|
const sources = new Set();
|
|
const states = ["normal", "hover", "locked"];
|
|
items.forEach((item) => {
|
|
const kind = getKind(item);
|
|
const marker = {
|
|
userData: {
|
|
...getUserData(item),
|
|
type: objectType,
|
|
icon_layer_id: id,
|
|
icon_kind: kind,
|
|
state: "normal",
|
|
},
|
|
};
|
|
states.forEach((state) => {
|
|
const source = getIconSource({
|
|
marker,
|
|
item,
|
|
state,
|
|
color:
|
|
colors.byKind?.[kind] ||
|
|
colors[kind] ||
|
|
colors.normal ||
|
|
"#ffffff",
|
|
});
|
|
if (source) sources.add(source);
|
|
});
|
|
});
|
|
|
|
await Promise.all(Array.from(sources).map((source) => loadAssetImage(source)));
|
|
}
|
|
|
|
function clearData(parent) {
|
|
invalidateVisualState();
|
|
invalidateClusterTopology();
|
|
unregisterLayerAvoidance(id);
|
|
markers.length = 0;
|
|
markerById.clear();
|
|
currentMarkers = new WeakSet();
|
|
clearRenderObjects();
|
|
disposeGroupChildren(group);
|
|
if (parent && group.parent === parent) {
|
|
parent.remove(group);
|
|
}
|
|
}
|
|
|
|
function attach(parent) {
|
|
if (parent && !group.parent) {
|
|
parent.add(group);
|
|
}
|
|
group.visible = visible;
|
|
}
|
|
|
|
function setVisible(nextVisible) {
|
|
visible = Boolean(nextVisible);
|
|
invalidateVisualState();
|
|
invalidateClusterTopology();
|
|
group.visible = visible;
|
|
if (pointsGroup) {
|
|
pointsGroup.visible = visible;
|
|
}
|
|
}
|
|
|
|
function setMarkerState(marker, state = "normal") {
|
|
if (!marker || marker.userData?.type !== objectType) return;
|
|
if (marker.userData.state === state) return;
|
|
marker.userData.state = state;
|
|
invalidateVisualState();
|
|
}
|
|
|
|
function updateVisualState(focusType, focusObject, camera) {
|
|
refreshViewportSize();
|
|
const hasFocus = focusType === objectType && focusObject;
|
|
if (!visible || markers.length === 0 || !pointsGroup) {
|
|
if (lastVisualStateKey !== "hidden") {
|
|
if (pointsGroup) pointsGroup.visible = false;
|
|
if (hoverOverlay) hoverOverlay.visible = false;
|
|
if (lockedOverlay) lockedOverlay.visible = false;
|
|
lastVisualStateKey = "hidden";
|
|
}
|
|
return;
|
|
}
|
|
|
|
pointsGroup.visible = true;
|
|
const lockedKey = hasFocus
|
|
? focusObject?.userData?.mmsi || focusObject?.uuid || "locked"
|
|
: "none";
|
|
const stateKey = [
|
|
"visible",
|
|
focusType || "none",
|
|
lockedKey,
|
|
visualStateVersion,
|
|
].join(":");
|
|
|
|
const cameraScale = getCameraScale(camera);
|
|
const scaleKey = usesDistanceScaling ? cameraScale.toFixed(3) : "fixed";
|
|
const nextStateKey = `${stateKey}:${scaleKey}`;
|
|
|
|
const batchChanged = nextStateKey !== lastVisualStateKey || dynamicVisuals;
|
|
if (!batchChanged && !(pulse.enabled && hasFocus)) return;
|
|
lastVisualStateKey = nextStateKey;
|
|
|
|
// Pulsing changes only the selected overlay. Static batches still refresh
|
|
// for selection, data, filter, camera-scale or explicit visual changes.
|
|
if (batchChanged) pointObjects.forEach((points) => {
|
|
const sampleMarker = points.userData?.markers?.[0];
|
|
const nextTexture = createPointTexture(points.userData?.bucketKey, points.userData?.markers || []);
|
|
if (points.material.map !== nextTexture) {
|
|
points.material.map = nextTexture;
|
|
points.material.needsUpdate = true;
|
|
}
|
|
updatePointColors(points);
|
|
points.visible = visible && points.userData.markers.length > 0;
|
|
points.material.opacity =
|
|
getPointOpacity?.(sampleMarker) ??
|
|
(hasFocus ? dimmedOpacity : baseOpacity);
|
|
points.material.size =
|
|
pointSize *
|
|
getPointSizeMultiplier(sampleMarker) *
|
|
cameraScale *
|
|
(hasFocus ? dimmedScale : 1);
|
|
});
|
|
const hoverMarker = markers.find(
|
|
(marker) => marker.userData?.state === "hover" && marker !== focusObject,
|
|
);
|
|
updateOverlay(
|
|
ensureOverlay("hover"),
|
|
hoverMarker,
|
|
"hover",
|
|
hoverOpacity,
|
|
hoverScale * cameraScale,
|
|
);
|
|
const lockedPulse =
|
|
pulse.enabled && hasFocus
|
|
? 1 + (pulse.amplitude ?? 0) * Math.sin(Date.now() * (pulse.speed ?? 0) + (focusObject?.userData?.pulseOffset ?? 0))
|
|
: 1;
|
|
updateOverlay(
|
|
ensureOverlay("locked"),
|
|
hasFocus ? focusObject : null,
|
|
"locked",
|
|
lockedOpacity,
|
|
lockedScale * lockedPulse * cameraScale,
|
|
);
|
|
}
|
|
|
|
function getPointerIntersections({
|
|
earth,
|
|
camera,
|
|
pointer,
|
|
radiusPx = 20,
|
|
width = window.innerWidth,
|
|
height = window.innerHeight,
|
|
frontFacingDotThreshold = 0,
|
|
} = {}) {
|
|
if (!visible || !earth || !camera || !pointer) return [];
|
|
|
|
scratchCameraPositionLocal.copy(camera.position);
|
|
earth.worldToLocal(scratchCameraPositionLocal);
|
|
scratchCameraLocal.copy(scratchCameraPositionLocal).normalize();
|
|
|
|
const pointerX = ((pointer.x + 1) / 2) * width;
|
|
const pointerY = ((1 - pointer.y) / 2) * height;
|
|
const radiusSq = radiusPx * radiusPx;
|
|
const intersections = [];
|
|
const cameraScale = getCameraScale(camera);
|
|
const visualPointSize = pointSize;
|
|
|
|
markers.forEach((marker) => {
|
|
if (marker.userData?.icon_cluster_hidden || marker.userData?.icon_presentation_hidden || !isItemVisible(marker.userData)) return;
|
|
scratchDirection.copy(marker.position).normalize();
|
|
if (usesSurfaceAnchorOcclusion
|
|
? !isSurfaceAnchorVisible(marker.position, scratchCameraPositionLocal, CONFIG.earthRadius)
|
|
: scratchCameraLocal.dot(scratchDirection) <= frontFacingDotThreshold) return;
|
|
|
|
scratchWorldPosition.copy(marker.position);
|
|
earth.localToWorld(scratchWorldPosition);
|
|
scratchScreenPosition.copy(scratchWorldPosition).project(camera);
|
|
if (scratchScreenPosition.z < -1 || scratchScreenPosition.z > 1) {
|
|
return;
|
|
}
|
|
|
|
const screenX = (scratchScreenPosition.x * 0.5 + 0.5) * width;
|
|
const screenY = (-scratchScreenPosition.y * 0.5 + 0.5) * height;
|
|
const pointSizeMultiplier = getPointSizeMultiplier(marker) * cameraScale;
|
|
const visualCenterX =
|
|
screenX + (0.5 - iconAnchor.x) * visualPointSize * pointSizeMultiplier;
|
|
const visualCenterY =
|
|
screenY + (0.5 - iconAnchor.y) * visualPointSize * pointSizeMultiplier;
|
|
const deltaX = visualCenterX - pointerX;
|
|
const deltaY = visualCenterY - pointerY;
|
|
const distancePxSq = deltaX * deltaX + deltaY * deltaY;
|
|
const markerRadiusPx = Math.max(
|
|
radiusPx,
|
|
visualPointSize * pointSizeMultiplier * 0.5,
|
|
);
|
|
if (distancePxSq > Math.max(radiusSq, markerRadiusPx * markerRadiusPx)) return;
|
|
|
|
intersections.push({
|
|
object: marker,
|
|
point: scratchWorldPosition.clone(),
|
|
distance: camera.position.distanceTo(scratchWorldPosition),
|
|
distancePxSq,
|
|
});
|
|
});
|
|
|
|
return intersections.sort((a, b) => a.distancePxSq - b.distancePxSq);
|
|
}
|
|
|
|
function refreshFilter() {
|
|
markers.forEach(marker => { marker.userData.legend_filtered = !isItemVisible(marker.userData); });
|
|
beginClusterUpdate();
|
|
invalidateClusterTopology();
|
|
lastClusterSignature = "";
|
|
rebuildPointLayers();
|
|
if (hoverOverlay) hoverOverlay.visible = false;
|
|
if (lockedOverlay) lockedOverlay.visible = false;
|
|
}
|
|
|
|
function getMarkerImage(marker) {
|
|
const color = icon.colorable === false ? "#ffffff" : getMarkerColor(marker);
|
|
const image = drawIconTexture(`projected:${getBucketKey(marker)}:${color}`, {
|
|
marker, color, rotationBin:getRotationBin(marker), glow:false, state:"normal",
|
|
}).image;
|
|
if (!projectedTextureUrls.has(image)) projectedTextureUrls.set(image, image.toDataURL());
|
|
return projectedTextureUrls.get(image);
|
|
}
|
|
|
|
const controller = {
|
|
group,
|
|
isMarkerVisible: marker => visible && markers.includes(marker) && isItemVisible(marker.userData),
|
|
getMarkerColor,
|
|
getMarkerSize: (marker, camera) => pointSize * getPointSizeMultiplier(marker) * getCameraScale(camera),
|
|
getMarkerImage,
|
|
resolveMarker: marker => currentMarkers.has(marker) ? marker
|
|
: marker?.userData?.icon_item_id === null ? null : markerById.get(itemKey(marker?.userData)),
|
|
getPresentationMarkers: () => visible && clusterConfig.enabled
|
|
? markers.filter(marker => isItemVisible(marker.userData)) : [],
|
|
refreshPositions,
|
|
refreshVisuals,
|
|
beginClusterUpdate,
|
|
collectClusterRecords,
|
|
addOwnedCluster,
|
|
markMarkerClustered,
|
|
commitClusterUpdate,
|
|
rebuildPointLayers,
|
|
};
|
|
interactableLayerControllers.set(id, controller);
|
|
|
|
return {
|
|
group,
|
|
markers,
|
|
getMarkers: () => markers,
|
|
getMarkerImage,
|
|
getCount: () => markers.length,
|
|
refreshFilter,
|
|
isVisible: () => visible,
|
|
setData,
|
|
updateItems,
|
|
upsertItem,
|
|
removeItem,
|
|
preloadAssets,
|
|
clearData,
|
|
attach,
|
|
setVisible,
|
|
setMarkerState,
|
|
updateVisualState,
|
|
getPointerIntersections,
|
|
refreshVisuals,
|
|
};
|
|
}
|