import * as THREE from "three"; import {CalloutConnector} from "./callout-connector.js"; import {createCalloutSettleGate, layoutObstaclesSignature, updateCalloutFloat} from "./callout-rest.js"; import {centralReadingExclusion, legalDockRect} from "./callout-dock-layout.js"; import {CONFIG} from "./constants.js"; import {projectedSphereRadius, smoothHighlightAnchor} from "./highlight-anchor.js"; import {bindHUDDrag} from "./hud-drag.js"; import {sharedHudFocusStack} from "./hud-focus-stack.js"; import {advanceCalloutReveal} from "./callout-reveal.js"; import {createRegionConnectorPath} from "./callout-region-path.js"; import {CALLOUT_LIMITS_STORAGE_KEY, getCalloutLimits} from "./callout-limits.js"; import {sharedCalloutStageArbitrator} from "./callout-stage-arbitrator.js"; const STORAGE_KEY = "planet.compute.card-positions.v1"; const EDGE = 12; const clamp = (value,min,max) => Math.max(min,Math.min(Math.max(min,max),value)); export function renderSpatialCalloutConnector(state, { animate = false, globe = null } = {}) { const point = state?.sourcePoint || state?.point; const rect = state && { x: state.displayX ?? state.x + (state.floatX || 0), y: state.displayY ?? state.y + (state.floatY || 0), width: state.width, height: state.height }; if (!point || !state.connector) return false; // Strict leash: only automatically stretching peripheral capsules have an auto-stretching cutoff. // When a card is manually dragged/placed by the user (state.userPlaced || state.dragging), // or is a spotlight stage card, NEVER cut or hide the connector! const isManual = Boolean(state.userPlaced || state.dragging); if (!isManual && !state.isSpotlight) { const cardCenterX = rect.x + rect.width / 2; const cardCenterY = rect.y + rect.height / 2; const distToAnchor = Math.hypot(point.x - cardCenterX, point.y - cardCenterY); const maxAllowedDist = (state.width || 220) + 140; if (distToAnchor > maxAllowedDist) { state.connector.hide(); return false; } } if (state.connector.isAnimating?.()) return true; const rearChanged = state.lastConnectorFront !== point.front; const sameRect = state.lastConnectorRect && ["x", "y", "width", "height"].every( key => Math.abs(rect[key] - state.lastConnectorRect[key]) < 0.5, ); const positionSettled = Math.hypot(state.x - state.targetX, state.y - state.targetY) < 0.5; if (state.connector.isVisible?.() === true && state.lastConnector && !rearChanged && sameRect && !state.dragging && positionSettled && Math.hypot(point.x - state.lastConnector.x, point.y - state.lastConnector.y) < 1) { return true; } const path = createRegionConnectorPath(point, rect, { globe }); const rendered = path ? state.connector.render(path, { animate }) : false; if (!rendered) state.connector.hide(); const connectorElement = state.connector.connectorEl; if (connectorElement) { const rear = !point.front; connectorElement.classList.toggle("is-rear", rear); connectorElement.classList.toggle("is-spotlight-connector", Boolean(state.isSpotlight)); connectorElement.dataset.anchorDepth = rear ? "rear" : "front"; connectorElement.dataset.calloutKey = state.key; } state.lastConnector = { x: point.x, y: point.y }; state.lastConnectorFront = point.front; state.lastConnectorRect = rect; return rendered; } /** * Computes a 3D orbital hover target for a non-spotlight capsule card. * Strictly bounded short tether (34-44px) locks to the geographic anchor on Earth, * moves in 120fps lockstep with the globe in 3D space, and avoids collisions. */ export function calculateOrbitalTarget(state, globe, viewport, occupiedRects = []) { const point = state.point || state.sourcePoint; const isHoverExpanded = Boolean(state.hoverExpanded); const w = isHoverExpanded ? Math.max(state.width || 340, 320) : (state.width || 220); const h = isHoverExpanded ? Math.max(state.height || 340, 260) : (state.height || 42); const vpWidth = viewport?.width || (typeof innerWidth !== "undefined" ? innerWidth : 1920); const vpHeight = viewport?.height || (typeof innerHeight !== "undefined" ? innerHeight : 1080); if (!point || !globe) { return { x: clamp(state.x || 100, 16, vpWidth - w - 16), y: clamp(state.y || 100, 64, vpHeight - h - 76), width: w, height: h, }; } // Backside horizon limb silhouette projection: // If point is on the backside, anchor emerges from the limb silhouette of the globe // without penetrating the front surface. let anchorX = point.x; let anchorY = point.y; if (!point.front && globe && Number.isFinite(globe.radius)) { const dx = point.x - globe.x; const dy = point.y - globe.y; const dist = Math.hypot(dx, dy) || 1; anchorX = globe.x + (dx / dist) * globe.radius; anchorY = globe.y + (dy / dist) * globe.radius; } // Vector from globe center to geographic anchor on screen const dy = anchorY - globe.y; const dist = Math.hypot(anchorX - globe.x, dy) || 1; const uy = dy / dist; // Short tether distance (bounded stem: strictly 36px) const stemDistance = 36; // Bounds clamping to safe UI zones (avoid top header and bottom toolbar) const minX = 16; const maxX = Math.max(minX, vpWidth - w - 16); const minY = 64; const maxY = Math.max(minY, vpHeight - h - 76); // Baseline capsule geometry (收缩态胶囊的基准位置): const capsuleW = 220; const capsuleH = 42; // Deterministic docking flank: // Dock to the right of anchor by default; if near or exceeding right screen edge, dock to left. // Include 40px hysteresis if previous position exists to avoid rapid flipping near screen edge. const prevFlank = (state.x != null && state.displayFlank) ? state.displayFlank : null; const canFitRight = prevFlank === "left" ? (anchorX + stemDistance + capsuleW <= vpWidth - 50) : (anchorX + stemDistance + capsuleW <= vpWidth - 16); let capsuleX; if (canFitRight) { capsuleX = anchorX + stemDistance; state.displayFlank = "right"; } else { capsuleX = anchorX - stemDistance - capsuleW; state.displayFlank = "left"; } let capsuleY = anchorY + stemDistance * uy * 0.3 - capsuleH / 2; capsuleX = clamp(capsuleX, minX, Math.max(minX, vpWidth - capsuleW - 16)); capsuleY = clamp(capsuleY, minY, Math.max(minY, vpHeight - capsuleH - 76)); let x = capsuleX; let y = capsuleY; if (isHoverExpanded) { const bottomLimit = vpHeight - 76; const spaceBelow = bottomLimit - (capsuleY + capsuleH); const spaceAbove = capsuleY - minY; // Prefer downward expansion (natural reading flow, keeps header under cursor); // only expand upwards if downward would overflow AND upward has more room: const isExpandUp = (spaceBelow < (h - capsuleH)) && (spaceAbove > spaceBelow); state.element?.classList?.toggle?.("hud-panel--expand-up", isExpandUp); state.element?.classList?.toggle?.("hud-panel--expand-down", !isExpandUp); // Continuous geometry to prevent hover flicker: // When expanding up, align the bottom of the card with the bottom of the capsule, // so the pointer that entered the capsule remains securely inside the expanded card! if (isExpandUp) { y = capsuleY + capsuleH - h; } else { // When expanding down, keep card's top anchored directly to capsule's top y = capsuleY; } // Keep horizontal alignment with the capsule so the pointer stays inside if (capsuleX + w > vpWidth - 16) { x = Math.max(minX, vpWidth - w - 16); } else { x = capsuleX; } } else { state.element?.classList?.remove?.("hud-panel--expand-up", "hud-panel--expand-down"); x = capsuleX; y = capsuleY; } // Viewport margin protection: softly clamp if reaching near the viewport edge x = clamp(x, minX, maxX); y = clamp(y, minY, maxY); // Sibling compact capsules collision avoidance only (Level 2 vs Level 2): // Big cards (Level 1) are never collided with here; they naturally cover capsules. const isFront = Boolean(point.front); let adjustedY = y; let adjustedX = x; if (!isHoverExpanded) { const siblingCapsules = occupiedRects.filter(r => r.isCapsule); for (const r of siblingCapsules) { if ((r.isFront == null || r.isFront === isFront) && Math.abs(adjustedX - r.x) < (capsuleW - 20) && Math.abs(adjustedY - r.y) < (capsuleH + 6)) { const shouldBeLower = (state.key && r.key) ? (state.key > r.key) : (anchorY >= r.y); if (shouldBeLower) { adjustedY = r.y + capsuleH + 6; } else { adjustedY = r.y - capsuleH - 6; } adjustedY = clamp(adjustedY, minY, maxY); } } } const target = { x: Math.round(adjustedX), y: Math.round(adjustedY), width: w, height: h, isFront, isCapsule: true, key: state.key, }; // A hover-expanded card is a transient floating preview (z-index: 60); // register only its base capsule footprint so neighboring cards stay stably anchored! const obstacleRect = isHoverExpanded ? { x: Math.round(capsuleX), y: Math.round(capsuleY), width: capsuleW, height: capsuleH, isFront, isCapsule: true, key: state.key, } : target; occupiedRects.push(obstacleRect); return target; } export function createCalloutController({root,getSpatialContext,getAnchorCandidates,project,stageArbitrator=sharedCalloutStageArbitrator}) { const lastSpotlightSwitchTimes = new Map(); const cards=new Map(), byElement=new WeakMap(); stageArbitrator?.clearByOwner?.("spatial"); let lastArbitratorRevision = -1; let saved={}; try {saved=JSON.parse(localStorage.getItem(STORAGE_KEY)||"{}");} catch { /* Optional preferences. */ } if(!saved || typeof saved!=="object" || Array.isArray(saved)) saved={}; let dirty=true, revision=0, mobile=false, lastViewport="", lastObstacleAt=-Infinity; let obstacles=[], urgent=false; let permanentSpotlightKeys=new Set(), lastGlobe=null, lastCardHoverExitAt=-Infinity; let limits=getCalloutLimits(); if(typeof window !== "undefined") { window.addEventListener("earth:callout-limits-change", (e) => { if(e.detail) { limits = e.detail; urgent = true; invalidate(); } }); } const settle=createCalloutSettleGate(); const reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)"); const invalidate=()=>{dirty=true;revision++;}; const persist=()=>{try {localStorage.setItem(STORAGE_KEY,JSON.stringify(saved));} catch { /* Optional preferences. */ }}; function savePosition(state) { saved[state.key]={x:state.targetX,y:state.targetY,viewportWidth:innerWidth,viewportHeight:innerHeight, width:state.element.style.width,height:state.element.style.height}; persist(); } function measure(state) { state.width=state.element.offsetWidth;state.height=state.element.offsetHeight; if (state.element.classList.contains("is-spotlight") && state.height > 60) { state.expandedWidth = state.width; state.expandedHeight = state.height; } state.header=state.element.querySelector("header"); } function writePosition(state,viewport) { const ratio=window.devicePixelRatio || 1; let x=state.x+(state.isSpotlight ? (state.floatX||0) : 0); let y=state.y+(state.isSpotlight ? (state.floatY||0) : 0); if(state.userPlaced && !state.dragging && state.isSpotlight && !legalDockRect({x,y,width:state.width,height:state.height}, [centralReadingExclusion(viewport)],viewport,0)) {x=state.x;y=state.y;} x=Math.round(x*ratio)/ratio;y=Math.round(y*ratio)/ratio; if(x!==state.displayX) state.element.style.left=`${x}px`; if(y!==state.displayY) state.element.style.top=`${y}px`; state.displayX=x;state.displayY=y; } const resizeObserver=new ResizeObserver(entries=>{ const scale=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--hud-scale"))||1; for(const entry of entries) { const state=byElement.get(entry.target);if(!state) continue; for(const axis of ["width","height"]) { const value=entry.target.style[axis]; if(/^[0-9.]+px$/.test(value)) entry.target.style[axis]=`calc(${parseFloat(value)/scale}px * var(--hud-scale))`; } const width=entry.target.offsetWidth,height=entry.target.offsetHeight; if(width===state.width && height===state.height) continue; state.width=width;state.height=height; if(!state.morphing) { invalidate(); } } }); function attach(item) { const stored=saved[item.key]; if(stored?.width) item.element.style.width=stored.width; if(stored?.height) item.element.style.height=stored.height; const state={...item,x:NaN,y:NaN,targetX:NaN,targetY:NaN,userPlaced:false,hoverExpanded:false, revealPhase:"pending",connector:new CalloutConnector({container:root,className:"callout-connector compute-connector"})}; // Historical stored coordinates are only soft layout hints; never treat newly attached/surfaced cards as user-placed! if(Number.isFinite(stored?.x) && Number.isFinite(stored?.y) && state.isSpotlight) { state.preference={x:stored.x*innerWidth/(stored.viewportWidth||innerWidth), y:stored.y*innerHeight/(stored.viewportHeight||innerHeight)}; } measure(state); let leaveTimer = null; const listeners=[ ["pointerenter",()=>{ if (leaveTimer) { clearTimeout(leaveTimer); leaveTimer = null; } state.hovering=true; if (!state.isSpotlight && !state.hoverExpanded) { state.hoverExpanded=true; state.hoverJustTriggered=true; state.element.classList.add("is-hover-expanded"); measure(state); urgent=true; invalidate(); } }], ["pointerleave",()=>{ state.hovering=false; if (leaveTimer) clearTimeout(leaveTimer); leaveTimer = setTimeout(() => { lastCardHoverExitAt = performance.now(); if (!state.hovering && state.hoverExpanded) { state.hoverExpanded=false; state.hoverJustExited=true; state.element.classList.remove("is-hover-expanded"); measure(state); urgent=true; invalidate(); } }, 140); }], ["focusin",event=>{state.focused=Boolean(event.target.matches(":focus-visible, input, textarea, select, [contenteditable=true]"));}], ["focusout",event=>{if(!item.element.contains(event.relatedTarget)) state.focused=false;}], ]; listeners.forEach(([event,handler])=>item.element.addEventListener(event,handler)); item.element.addEventListener("click",click,true); sharedHudFocusStack.register(item.element); const stopDrag=bindHUDDrag(item.element,{ enabled:()=>!mobile && Number.isFinite(state.x), readPosition:()=>({left:state.displayX??state.x,top:state.displayY??state.y}), onStart:()=>{ if (leaveTimer) clearTimeout(leaveTimer); sharedHudFocusStack.focus(item.element,{source:"user"}); state.motion=null;state.settlingDrop=false;state.dragging=true;state.floatX=state.floatY=0; state.vx=0;state.vy=0; state.lastUserDragAt=performance.now(); }, onMove:({left,top})=>{ state.x=state.targetX=clamp(left,EDGE,innerWidth-state.width-EDGE); state.y=state.targetY=clamp(top,EDGE,innerHeight-state.height-EDGE); state.preference={x:state.x,y:state.y}; state.userPlaced=true; state.userPinned=true; state.dragSyncedHemisphere=null; state.vx=0;state.vy=0; state.lastUserDragAt=performance.now(); item.element.dataset.dragged="true"; item.element.dataset.userPlaced="true"; writePosition(state,{width:innerWidth,height:innerHeight}); }, onEnd:moved=>{ state.dragging=false; if(moved) { state.userPlaced=true; state.userPinned=true; state.targetX=state.x; state.targetY=state.y; state.preference={x:state.x,y:state.y}; state.motion=null; state.settlingDrop=false; state.vx=0;state.vy=0; state.lastUserDragAt=performance.now(); const globeCenterX = lastGlobe ? lastGlobe.x : innerWidth * 0.5; const cardCenterX = state.x + (state.width || 320) * 0.5; const pt = state.point?.front ? state.point : (state.sourcePoint || state.point); const cardIsRight = cardCenterX >= globeCenterX; const anchorIsRight = pt ? (pt.x >= globeCenterX) : cardIsRight; state.dragSyncedHemisphere = (cardIsRight === anchorIsRight); item.element.dataset.dragged="false"; item.element.dataset.userPlaced="true"; savePosition(state); state.ignoreClickUntil=performance.now()+200; urgent=true; invalidate(); } }, }); state.cleanup=()=>{ if (leaveTimer) clearTimeout(leaveTimer); stopDrag(); item.element.classList.remove("is-callout-front"); item.element.removeEventListener("click",click,true); listeners.forEach(([event,handler])=>item.element.removeEventListener(event,handler)); }; return state; } function set(items) { const keys=new Set(items.map(item=>item.key)); for(const [key,state] of cards) if(!keys.has(key)) { permanentSpotlightKeys.delete(key); state.cleanup();state.connector.hide();state.connector.connectorEl?.remove(); resizeObserver.unobserve(state.element);byElement.delete(state.element);cards.delete(key);invalidate(); } for(const item of items) { const existing=cards.get(item.key); if(existing) { existing.anchor=item.anchor;existing.anchorCodes=item.anchorCodes;existing.anchorCandidates=item.anchorCandidates; existing.defaultSpotlight=Boolean(item.defaultSpotlight); existing.preferredSide=item.preferredSide||null; existing.bilateralPeerKey=item.bilateralPeerKey||null; if(existing.defaultSpotlight && !existing.collapsedByUser) { permanentSpotlightKeys.add(item.key); } if(existing.header!==item.element.querySelector("header")) {measure(existing);invalidate();} } else { const state=attach(item); state.defaultSpotlight=Boolean(item.defaultSpotlight); state.preferredSide=item.preferredSide||null; state.bilateralPeerKey=item.bilateralPeerKey||null; state.collapsedByUser=false; if(state.defaultSpotlight) { permanentSpotlightKeys.add(item.key); } cards.set(item.key,state);byElement.set(item.element,state);resizeObserver.observe(item.element); item.element.style.visibility="hidden";item.element.dataset.calloutPhase="pending";invalidate(); } } } function measureObstacles(now) { if(now-lastObstacleAt<500) return;lastObstacleAt=now; const owned=new Set([...cards.values()].map(state=>state.element)); // Exclude #info-panel and #earth-mobile-popup so sibling callouts never read animated DOM rects: const next=[...document.querySelectorAll(".hud-panel, #desktop-news-ticker, #legend, #control-toolbar, #toolbar-hub, .hud-panel-brand")] .filter(el=>!owned.has(el) && !el.matches(".compute-picker,.compute-evidence,#info-panel,#earth-mobile-popup") && !el.hidden && !el.classList.contains("hud-panel-hidden") && getComputedStyle(el).visibility!=="hidden" && getComputedStyle(el).opacity!=="0" && el.getClientRects().length) .map(el=>{const r=el.getBoundingClientRect();return {x:r.x - 8,y:r.y - 8,width:r.width + 16,height:r.height + 16};}); if(layoutObstaclesSignature(next)!==layoutObstaclesSignature(obstacles)) {obstacles=next;invalidate();} } function computeSafeStageBounds(viewport) { const leftHudEdge = obstacles .filter(o => o.x < 140 && o.y > 60 && o.y < viewport.height * 0.75) .reduce((max, o) => Math.max(max, o.x + o.width), 0); const minX = Math.max(leftHudEdge + 16, 24); const maxX = viewport.width - 24; const topHudEdge = obstacles .filter(o => o.y < 80 && o.x < viewport.width * 0.35) .reduce((max, o) => Math.max(max, o.y + o.height), 0); const minY = Math.max(topHudEdge + 12, 68); const bottomToolbar = obstacles.find(o => o.y > viewport.height * 0.75 && (o.x + o.width > viewport.width * 0.35 && o.x < viewport.width * 0.65)); const maxY = bottomToolbar ? (bottomToolbar.y - 14) : (viewport.height - 110); return { minX, maxX, minY, maxY }; } function syncAndArbitrateStage(viewport, globe) { const safeBounds = computeSafeStageBounds(viewport); const activeStageKeys = new Set(); const g = globe || lastGlobe || { x: viewport.width * 0.5, y: viewport.height * 0.5, radius: Math.min(viewport.width, viewport.height) * 0.4 }; for (const key of permanentSpotlightKeys) { const sc = cards.get(key); if (!sc || sc.hoverExpanded) continue; // Always use true geographic projection `sc.point` (projected to limb if rear), // NEVER `sc.sourcePoint` (which depends on cardPoint = state.x/state.y and would create a feedback loop)! let pt = sc.point || sc.sourcePoint; if (!pt && !sc.userPinned) continue; if (pt && pt.front === false && Number.isFinite(g.radius)) { const dx = pt.x - g.x; const dy = pt.y - g.y; const dist = Math.hypot(dx, dy) || 1; pt = { x: g.x + (dx / dist) * g.radius, y: g.y + (dy / dist) * g.radius, front: false }; } activeStageKeys.add(key); const isCompute = sc.element.classList.contains("compute-card"); const expW = sc.expandedWidth || sc.width || (isCompute ? 300 : 340); const expH = sc.expandedHeight || (sc.height > 60 ? sc.height : (isCompute ? 320 : 360)); const isPinned = Boolean(sc.userPinned && Number.isFinite(sc.targetX) && Number.isFinite(sc.targetY)); stageArbitrator.setCard(key, { owner: "spatial", kind: isCompute ? "compute" : "news", anchor: pt || { x: g.x, y: g.y, front: true }, size: { width: expW, height: expH }, isPrimary: true, preferredSide: sc.preferredSide || null, bilateralPeerKey: sc.bilateralPeerKey || null, userPinned: isPinned, pinnedRect: isPinned ? { x: sc.targetX, y: sc.targetY, width: expW, height: expH } : null, overlapDepth: 32, }); } stageArbitrator.clearByOwner("spatial", activeStageKeys); const arbitration = stageArbitrator.arbitrate({ viewport, globe: g, safeBounds }); return { arbitration, safeBounds, globe: g }; } function preparePlan(viewport) { const { arbitration, safeBounds, globe } = syncAndArbitrateStage(viewport, lastGlobe); lastArbitratorRevision = arbitration.revision; const occupiedForOrbit = []; for (const [key, state] of cards) { const effectiveSpotlight = permanentSpotlightKeys.has(key); if (state.isSpotlight !== effectiveSpotlight) { state.isSpotlight = effectiveSpotlight; state.element.classList.toggle("is-spotlight", effectiveSpotlight); measure(state); } if (state.isSpotlight && !state.hoverExpanded) { if (state.userPinned && Number.isFinite(state.targetX)) { continue; } const target = stageArbitrator.computeTarget(key, { viewport, globe, safeBounds }); if (target) { state.targetX = target.x; state.targetY = target.y; state.stageSide = target.stageSide; state.corridor = target.corridor; if (!Number.isFinite(state.x) || state.revealPhase !== "visible") { state.x = target.x; state.y = target.y; state.vx = 0; state.vy = 0; } if (state.revealPhase === "visible") state.element.style.visibility = ""; } } else { if (state.userPinned && Number.isFinite(state.targetX)) { // Keep user-pinned position } else { state.userPlaced = false; state.motion = null; const orbitalTarget = calculateOrbitalTarget(state, globe, viewport, occupiedForOrbit); state.targetX = orbitalTarget.x; state.targetY = orbitalTarget.y; if (!Number.isFinite(state.x) || state.revealPhase !== "visible") { state.x = orbitalTarget.x; state.y = orbitalTarget.y; state.vx = 0; state.vy = 0; } if (state.revealPhase === "visible") state.element.style.visibility = ""; } } } dirty = false; urgent = false; } function update(deltaMs,now) { if(!cards.size || root.hidden) return; mobile=document.documentElement.classList.contains("layout-mode-mobile"); if(mobile) {for(const state of cards.values()) {state.connector.hide();state.element.style.visibility="";}return;} const viewport={width:innerWidth,height:innerHeight}; const viewportKey=`${innerWidth}:${innerHeight}`; if(viewportKey!==lastViewport) { const hadPrevViewport = Boolean(lastViewport); lastViewport=viewportKey; for(const state of cards.values()) { measure(state); if (hadPrevViewport && !state.userPinned) { if (Number.isFinite(state.x)) state.x = clamp(state.x, EDGE, Math.max(EDGE, innerWidth - state.width - EDGE)); if (Number.isFinite(state.y)) state.y = clamp(state.y, EDGE, Math.max(EDGE, innerHeight - state.height - EDGE)); } } urgent=true; invalidate(); } measureObstacles(now); const context=getSpatialContext?.();if(!context?.earth || !context?.camera) return; context.camera.updateMatrixWorld(); const center=new THREE.Vector3().setFromMatrixPosition(context.earth.matrixWorld); const distance=context.camera.position.distanceTo(center); const rim=center.clone().add(new THREE.Vector3().setFromMatrixColumn(context.camera.matrixWorld,0).multiplyScalar(CONFIG.earthRadius)).project(context.camera); center.project(context.camera); const globe={x:(center.x+1)*innerWidth/2,y:(1-center.y)*innerHeight/2, radius:projectedSphereRadius(Math.abs(rim.x-center.x)*innerWidth/2,distance,CONFIG.earthRadius)}; lastGlobe=globe; const busy=context.isDragging || context.activeTouchPoints>0 || context.hasActiveGlobeInertia || [...cards.values()].some(state=>state.dragging) || Boolean(document.querySelector(".hud-panel.is-dragging,.hud-panel.is-resizing")); // Only true external HUD obstacles (like satellite detail card) count as obstacles; // sibling cards in this controller never block each other's anchors, eliminating hover jitter! const sources=[...obstacles]; for(const state of cards.values()) { state.point=project(state.anchor,context.earth,context.camera,innerWidth,innerHeight); if(!state.point) {state.connector.hide();continue;} if (state.isSpotlight) { const alternate=state.highlightAnchorState?.candidateKey!=null || !state.point.front || state.point.visibility<0.34; const candidates=alternate?(state.anchorCandidates||getAnchorCandidates?.(state.anchorCodes)||[]):[]; const projectedCandidates = candidates.map(anchor=>project(anchor,context.earth,context.camera,innerWidth,innerHeight)).filter(Boolean); const result=smoothHighlightAnchor({...state.highlightAnchorState,cardPoint:Number.isFinite(state.x)? {x:state.x+state.width/2,y:state.y+state.height/2}:null},{preferred:state.point, candidates:projectedCandidates, globe,obstacles:projectedCandidates.length ? sources : [],viewport,deltaMs}); const rawVis = result.rawVisibility ?? state.point?.visibility; state.highlightAnchorState=result.state; state.sourcePoint=result.source ? {...result.source, ...(Number.isFinite(rawVis) ? {visibility: rawVis, rawVisibility: rawVis} : {})} : state.point; state.element.classList.toggle("is-rear",!state.sourcePoint.front); } else { state.sourcePoint=state.point; state.element.classList.toggle("is-rear",!state.point.front); } if (state.userPinned && !state.dragging) { if (state.hovering) { state.lastUserDragAt = now; } const pt = state.point?.front ? state.point : (state.sourcePoint || state.point); const rawVis = Number.isFinite(state.point?.visibility) ? state.point.visibility : (Number.isFinite(pt?.rawVisibility) ? pt.rawVisibility : (Number.isFinite(pt?.visibility) ? pt.visibility : null)); // Absolute user drag priority: never unpin or snap back unless anchor is in extreme deep occlusion (> 130 deg, real visibility < -0.65) const isDeepRear = Boolean(pt && pt.front === false && rawVis !== null && rawVis < -0.65); if (isDeepRear) { state.userPinned = false; state.userPlaced = false; state.dragSyncedHemisphere = false; state.vx = 0; state.vy = 0; state.element.dataset.dragged = "false"; state.element.dataset.userPlaced = "false"; urgent = true; invalidate(); } } } // Auto-focus the region closest to the center of view when Earth rotates: // If user is currently hovering or inspecting ANY card, completely FREEZE auto-switching // so the stage spotlight card never jerks, shifts, or flaps under the user's cursor! const isAnyCardHovered = [...cards.values()].some(s => s.hovering || s.hoverExpanded); const inHoverCooldown = (now - lastCardHoverExitAt) < 2500; const hasExplicitStoredLimit = (scopeType) => { try { const raw = typeof localStorage !== "undefined" ? localStorage.getItem(CALLOUT_LIMITS_STORAGE_KEY) : null; if (!raw) return false; const parsed = JSON.parse(raw); return parsed != null && typeof parsed === "object" && parsed[scopeType] != null; } catch { return false; } }; for (const type of ["compute", "news"]) { if (isAnyCardHovered || inHoverCooldown) continue; if (type === "compute" && [...cards.values()].some(s => s.element.classList.contains("compute-card") && s.collapsedByUser)) { continue; } const defaultSpotlights = [...cards.entries()].filter(([, s]) => ( (s.element.classList.contains("compute-card") ? "compute" : "news") === type && Boolean(s.defaultSpotlight) && !s.collapsedByUser )); const candidates = [...cards.entries()].filter(([, s]) => (s.element.classList.contains("compute-card") ? "compute" : "news") === type && s.point && (s.point.front || (Boolean(s.defaultSpotlight) && !s.collapsedByUser)) ); if (candidates.length === 0) continue; let currentKey = [...permanentSpotlightKeys].find(k => { const s = cards.get(k); return s && (s.element.classList.contains("compute-card") ? "compute" : "news") === type; }); const radius = globe.radius || 400; // Find candidate closest to globe center let bestKey = null; let bestDist = Infinity; for (const [k, s] of candidates) { const p = s.point; const centerDist = p.front ? Math.hypot(p.x - globe.x, p.y - globe.y) : Infinity; if (centerDist < bestDist || !bestKey) { bestDist = centerDist; bestKey = k; } } if (!currentKey) { if (bestKey) { permanentSpotlightKeys.add(bestKey); lastSpotlightSwitchTimes.set(type, now); } } else if (bestKey && bestKey !== currentKey && defaultSpotlights.length === 0) { const currentCard = cards.get(currentKey); const curPoint = currentCard?.point; const curDist = curPoint?.front ? Math.hypot(curPoint.x - globe.x, curPoint.y - globe.y) : Infinity; const isCurrentRecentlyDragged = Boolean( currentCard?.dragging || currentCard?.userPinned ); // Auto-switch criteria with Dwell Protection: // 1. Current card has rotated to rear side (!front) -> switch immediately // 2. Otherwise enforce 1500ms dwell cooldown and significant distance margin (at least 45px closer) const lastSwitchAt = lastSpotlightSwitchTimes.get(type) || 0; const dwellElapsed = now - lastSwitchAt; const isCurrentRear = !curPoint?.front; const hasDwellExpired = dwellElapsed >= 1500; const isCurrentDrifting = hasDwellExpired && curDist > radius * 0.35 && bestDist < curDist - 45; const isCandidateCentral = hasDwellExpired && bestDist < radius * 0.35 && bestDist < curDist - 50; const hasHoveredCard = [...cards.values()].some(s => s.hovering || s.hoverExpanded); if (!hasHoveredCard && !isCurrentRecentlyDragged && (isCurrentRear || isCurrentDrifting || isCandidateCentral)) { lastSpotlightSwitchTimes.set(type, now); permanentSpotlightKeys.delete(currentKey); if (currentCard && !currentCard.hoverExpanded) { currentCard.isSpotlight = false; currentCard.element.classList.remove("is-spotlight"); } permanentSpotlightKeys.add(bestKey); const bestCard = cards.get(bestKey); if (bestCard && !bestCard.userPinned) { bestCard.userPlaced = false; bestCard.element.dataset.dragged = "false"; bestCard.element.dataset.userPlaced = "false"; } urgent = true; invalidate(); } } const primaryKey = permanentSpotlightKeys.has(currentKey) ? currentKey : bestKey; const baseLimit = Math.max(1, Math.floor(Number(limits[type]) || 1)); const limit = (type === "compute" && defaultSpotlights.length > 0 && !hasExplicitStoredLimit("compute")) ? Math.max(baseLimit, innerWidth >= 1100 ? defaultSpotlights.length : 1) : baseLimit; const eligible = [...cards.entries()].filter(([, state]) => ( (state.element.classList.contains("compute-card") ? "compute" : "news") === type && state.point && (state.point.front || state.dragging || state.userPinned || (Boolean(state.defaultSpotlight) && !state.collapsedByUser)) )); const ranked = eligible.sort(([aKey, a], [bKey, b]) => ( Number(Boolean(b.dragging || b.userPinned)) - Number(Boolean(a.dragging || a.userPinned)) || Number(Boolean(b.defaultSpotlight && !b.collapsedByUser)) - Number(Boolean(a.defaultSpotlight && !a.collapsedByUser)) || Number(bKey === primaryKey) - Number(aKey === primaryKey) || Math.hypot(a.point.x - globe.x, a.point.y - globe.y) - Math.hypot(b.point.x - globe.x, b.point.y - globe.y) )); const selectedKeys = new Set(ranked.slice(0, limit).map(([key]) => key)); let selectionChanged = false; for (const key of permanentSpotlightKeys) { const state = cards.get(key); if (!state || ((state.element.classList.contains("compute-card") ? "compute" : "news") === type && !selectedKeys.has(key))) { permanentSpotlightKeys.delete(key); selectionChanged = true; } } for (const key of selectedKeys) { if (!permanentSpotlightKeys.has(key)) { permanentSpotlightKeys.add(key); selectionChanged = true; const promotedState = cards.get(key); if (promotedState?.element && !context.isDragging) { sharedHudFocusStack.focus(promotedState.element, { source: "system", kind: "ambient_tick", }); } } } if (selectionChanged) { urgent = true; invalidate(); } } // Single-source stage arbitration across Selection, News, and Compute cards: const { arbitration, safeBounds } = syncAndArbitrateStage(viewport, globe); if (arbitration.revision !== lastArbitratorRevision) { lastArbitratorRevision = arbitration.revision; urgent = true; invalidate(); } let spotlightChanged = false; for (const [key, state] of cards) { const isSpotlight = permanentSpotlightKeys.has(key); if (state.isSpotlight !== isSpotlight) { state.isSpotlight = isSpotlight; state.element.classList.toggle("is-spotlight", isSpotlight); state.morphing = true; setTimeout(() => { state.morphing = false; measure(state); urgent = true; invalidate(); }, 380); spotlightChanged = true; } } if (spotlightChanged) { for (const state of cards.values()) measure(state); urgent = true; invalidate(); } const settled=settle(now,busy,String(revision)); if(dirty && (!busy || urgent) && (settled||urgent)) preparePlan(viewport); // Update non-spotlight (or hover-expanded) 3D orbital positions in real-time (120fps lockstep) const occupiedForCapsules = []; // Sibling capsules stacking only for (const state of cards.values()) { if (state.isSpotlight && !state.hoverExpanded) { const pt = state.sourcePoint || state.point; const rawVis = Number.isFinite(pt?.rawVisibility) ? pt.rawVisibility : (Number.isFinite(pt?.visibility) ? pt.visibility : (pt?.front ? 1 : -1)); const isRearAnchor = Boolean(pt && !(pt.front && rawVis > 0.04)); state.element.classList.remove("is-backside", "is-occluded"); state.element.classList.toggle("is-rear", isRearAnchor); state.element.style.zIndex = sharedHudFocusStack.getCardZIndex(state.element, { isSpotlight: true, isHoverExpanded: false, isFront: !isRearAnchor, }); state.element.style.opacity = "1"; state.element.style.setProperty("--spatial-scale", "1"); state.element.style.transform = ""; if (state.connector?.connectorEl) { state.connector.connectorEl.style.opacity = "1"; } continue; } if (!state.userPinned) { state.userPlaced = false; state.motion = null; } const point = state.point; if (!point) continue; // Small cards NEVER disappear when behind big cards; big cards naturally layer on top if (state.hoverExpanded) { const rawVis = Number.isFinite(point?.rawVisibility) ? point.rawVisibility : (Number.isFinite(point?.visibility) ? point.visibility : (point?.front ? 1 : -1)); const isRearAnchor = !(point.front && rawVis > 0.04); state.element.classList.remove("is-backside", "is-occluded"); state.element.classList.toggle("is-rear", isRearAnchor); state.element.style.zIndex = sharedHudFocusStack.getCardZIndex(state.element, { isSpotlight: state.isSpotlight, isHoverExpanded: true, isFront: !isRearAnchor, }); state.element.style.opacity = "1"; state.element.style.setProperty("--spatial-scale", "1"); state.element.style.transform = "scale(1)"; if (state.connector?.connectorEl) { state.connector.connectorEl.style.opacity = "1"; } state.element.style.pointerEvents = "auto"; state.element.style.visibility = ""; } else { state.element.classList.remove("is-occluded"); const vis = point.visibility ?? (point.front ? 1 : -1); const isFront = point.front && vis > 0.04; // Smooth continuous gradual dimming and depth scaling: // Front (vis >= 0.12): alpha = 1.0, scale = 1.0 // Transitioning to backside (-0.50 <= vis < 0.12): smoothly dim to 0.42 and shrink to 0.75 // Deep backside (vis < -0.50): alpha = 0.42, scale = 0.75 const t = Math.max(0, Math.min(1, (vis - (-0.50)) / (0.12 - (-0.50)))); const ease = t * t * (3 - 2 * t); const alpha = 0.42 + 0.58 * ease; const scale = 0.75 + 0.25 * ease; if (!isFront) { state.element.classList.add("is-backside", "is-rear"); state.element.style.zIndex = "8"; } else { state.element.classList.remove("is-backside", "is-rear"); state.element.style.zIndex = "30"; } state.element.style.opacity = alpha.toFixed(3); state.element.style.setProperty("--spatial-scale", scale.toFixed(3)); state.element.style.transform = `scale(${scale.toFixed(3)})`; if (state.connector?.connectorEl) { state.connector.connectorEl.style.opacity = (alpha * 0.75).toFixed(3); } state.element.style.pointerEvents = "auto"; state.element.style.visibility = ""; } // Continuous smooth spring tracking with Earth rotation: // Non-spotlight cards act like a silky flag tethered to the Earth's geographic anchor if (!state.dragging && !state.userPinned) { const orbital = calculateOrbitalTarget(state, globe, viewport, occupiedForCapsules); state.targetX = orbital.x; state.targetY = orbital.y; if (state.hoverJustTriggered) { state.hoverJustTriggered = false; state.x = orbital.x; state.y = orbital.y; state.vx = 0; state.vy = 0; } else if (state.hoverJustExited) { state.hoverJustExited = false; state.x = orbital.x; state.y = orbital.y; state.vx = 0; state.vy = 0; } else if (Number.isFinite(state.x) && state.revealPhase === "visible") { const dt = Math.max(0.5, Math.min(2.5, deltaMs / 16.6)); const dx = orbital.x - state.x; const dy = orbital.y - state.y; const dist = Math.hypot(dx, dy); if (dist > 45) { const maxSpeed = 8.5; const desiredSpeed = Math.min(maxSpeed, dist * 0.045); const step = Math.min(dist, desiredSpeed * dt); state.x += (dx / dist) * step; state.y += (dy / dist) * step; } else if (dist <= 1.5) { state.x = orbital.x; state.y = orbital.y; state.vx = 0; state.vy = 0; } else { const followRate = Math.min(0.24, 0.14 * dt); state.x += dx * followRate; state.y += dy * followRate; } } else { state.x = orbital.x; state.y = orbital.y; state.vx = 0; state.vy = 0; } } } for (const state of cards.values()) { if (!Number.isFinite(state.x)) continue; // Continuous Fluid Balloon Follow for Spotlight Cards (轻柔气球空气阻尼漂浮): // Hover does NOT pause card translation; only active dragging by user takes over! if (state.isSpotlight && !state.hoverExpanded && !state.dragging) { // Dynamic continuous tracking strictly constrained within the arbitrated stage slot & corridor: const pt = state.sourcePoint || state.point; if (pt && !state.userPinned && lastGlobe) { const constrained = stageArbitrator.computeTarget(state.key, { viewport, globe: lastGlobe, safeBounds, }); if (constrained) { state.targetX = constrained.x; state.targetY = constrained.y; state.stageSide = constrained.stageSide; state.corridor = constrained.corridor; } } if (Number.isFinite(state.targetX) && Number.isFinite(state.targetY)) { if (state.revealPhase !== "visible") { state.x = state.targetX; state.y = state.targetY; state.vx = 0; state.vy = 0; } else { const dx = state.targetX - state.x; const dy = state.targetY - state.y; const dist = Math.hypot(dx, dy); if (dist > 0.5) { const dt = Math.max(0.5, Math.min(2.5, deltaMs / 16.6)); const maxSpeed = 8.0; const desiredSpeed = Math.min(maxSpeed, dist * 0.032); const desiredVx = (dx / dist) * desiredSpeed; const desiredVy = (dy / dist) * desiredSpeed; const inertiaBlend = Math.min(1, 0.12 * dt); state.vx = (state.vx || 0) + (desiredVx - (state.vx || 0)) * inertiaBlend; state.vy = (state.vy || 0) + (desiredVy - (state.vy || 0)) * inertiaBlend; const stepX = state.vx * dt; const stepY = state.vy * dt; if (Math.hypot(stepX, stepY) >= dist) { state.x = state.targetX; state.y = state.targetY; state.vx = 0; state.vy = 0; } else { state.x += stepX; state.y += stepY; } } else { state.x = state.targetX; state.y = state.targetY; state.vx = 0; state.vy = 0; } } } updateCalloutFloat(state, now, deltaMs, true); } writePosition(state, viewport); { const rendered = renderSpatialCalloutConnector(state, { animate: state.revealPhase === "pending" && !reducedMotion.matches, globe }); const wasVisible = state.revealPhase === "visible"; state.revealPhase = advanceCalloutReveal(state, { now, rendered, animating: state.connector.isAnimating(), reducedMotion: reducedMotion.matches }); if (state.revealPhase === "visible" && !wasVisible) { state.element.style.visibility = ""; if (!reducedMotion.matches) state.element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 180, easing: "ease" }); } } if (state.element.dataset.calloutPhase !== state.revealPhase) state.element.dataset.calloutPhase = state.revealPhase; } } const click=event=>{ const element=event.target.closest(".compute-card,.news-region-card"); const state=byElement.get(element); if(!state || state.ignoreClickUntil>performance.now()) return; if(event.target.closest('[data-action="card-collapse"]')) { state.collapsedByUser = true; state.isSpotlight = false; state.hoverExpanded = false; state.element.classList.remove("is-spotlight", "is-hover-expanded"); permanentSpotlightKeys.delete(state.key); urgent = true; invalidate(); return; } if(event.target.closest('button, a, [role="tab"], input, select, textarea, summary')) return; if(state.key && !permanentSpotlightKeys.has(state.key)) { const type = state.element.classList.contains("compute-card") ? "compute" : "news"; const maxSpotlightsForType = type === "compute" && innerWidth >= 1100 ? 2 : 1; const existingForType = [...permanentSpotlightKeys].filter(k => { const s = cards.get(k); return s && (s.element.classList.contains("compute-card") ? "compute" : "news") === type; }); while (existingForType.length >= maxSpotlightsForType) { const evictKey = existingForType.shift(); const s = cards.get(evictKey); permanentSpotlightKeys.delete(evictKey); if (s) { s.isSpotlight = false; s.hoverExpanded = false; s.element.classList.remove("is-spotlight", "is-hover-expanded"); } } state.collapsedByUser = false; permanentSpotlightKeys.add(state.key); state.isSpotlight = true; state.hoverExpanded = false; state.element.classList.add("is-spotlight"); state.element.classList.remove("is-hover-expanded"); state.morphing = true; setTimeout(() => { state.morphing = false; measure(state); urgent = true; invalidate(); }, 380); urgent = true; invalidate(); } }; function setSpotlightKeys(nextKeys, scopeType = "compute") { const allowed = new Set(Array.isArray(nextKeys) ? nextKeys : []); for (const [k, s] of cards.entries()) { const isCompute = s.element.classList.contains("compute-card"); if ((scopeType === "compute" && !isCompute) || (scopeType === "news" && isCompute)) continue; if (allowed.has(k)) { s.collapsedByUser = false; permanentSpotlightKeys.add(k); s.isSpotlight = true; s.hoverExpanded = false; s.element.classList.add("is-spotlight"); s.element.classList.remove("is-hover-expanded"); } else { permanentSpotlightKeys.delete(k); s.isSpotlight = false; s.hoverExpanded = false; s.element.classList.remove("is-spotlight", "is-hover-expanded"); } measure(s); } urgent = true; invalidate(); } return {set,setSpotlightKeys,update,invalidate,destroy(){set([]);resizeObserver.disconnect();}}; }