Phase 2c: eclipse/overpass calculators + live-map camera polish
CI / Lint, typecheck, test, build (pull_request) Failing after 9s

Calculators (apps/live-map/src/calculators/):
- eclipse.ts: findEclipseWindows(bodies, opts) — coarse scan with
  threshold-crossing detection, bisection to refine start/end,
  ternary search to find peak. Handles eclipse already in progress
  at scan-start. Uses sun = parentId===null body.
- overpass.ts: findOverpasses(opts) — coarse scan for local distance
  minima, ternary refinement. Targets: vessel, body, ground station
  (lat/lon/alt → heliocentric).

UI:
- panels/CalculatorsPanel.tsx: collapsible bottom-center panel with
  two tabs. Eclipse form: observer, eclipser, from UT → 3 windows.
  Overpass form: observer vessel, target kind+id, max dist → 5 passes.
- timeFormat.ts: shared KSP-time formatters.

Live-map camera polish (apps/live-map/src/scene/):
- camera.ts: CameraController — log-scale distance (z→exp(z)*1e8 m,
  range -3..12), spherical orbit around target, smooth lerp to
  selected body/vessel. Mouse wheel zooms, drag rotates, click
  raycasts for track toggle. Pointer-move-distance gate to
  distinguish click from drag.
- glow.ts: additive shader-based atmospheric halo (rim-falloff
  fragment shader, BackSide) attached as child of body mesh.
- layout.ts: bodyPositionAt now returns true heliocentric (walks
  parent chain); previous version returned parent-relative for
  non-root children which broke the eclipse calculator.

Bug fix:
- packages/orbital-math/src/occultation.ts: sign of projection check
  was inverted. `proj <= 0` correctly returns 0 (occluder behind
  observer), `proj > 0` triggers eclipse computation.

Tests: 28 live-map tests (10 scene + 12 calculator + 6 camera),
45 total across the workspace, all passing.
This commit is contained in:
Mavis
2026-06-02 19:46:00 +00:00
parent 9e76ec9328
commit 07cc5321d1
13 changed files with 1533 additions and 86 deletions
+60 -60
View File
@@ -1,9 +1,10 @@
/**
* Scene — the 3D Three.js rendering of the universe.
*
* Re-renders when the bodies, vessels, or focus settings change.
* The animation loop runs the orbit propagation and positions the
* meshes for the current `ut`.
* - Builds body meshes, orbit lines, vessel markers
* - Adds atmospheric glow on planets
* - Uses CameraController for log-scale distance, mouse zoom,
* drag-to-rotate, click-to-track via raycasting
*/
import { useEffect, useRef } from 'react';
import * as THREE from 'three';
@@ -11,16 +12,17 @@ import { sampleOrbit } from '@kerbal-rt/orbital-math';
import type { UniverseSnapshot } from '@kerbal-rt/shared-types';
import { bodyColor, vesselColor } from './color.js';
import { bodyPositionAt, vesselPositionAt } from './layout.js';
import { CameraController } from './camera.js';
import { createGlow } from './glow.js';
export interface SceneProps {
snapshot: UniverseSnapshot;
ut: number;
/** Which body or vessel the camera should follow. null = free. */
followId: string | null;
/** Toggle visibility of orbit lines by category. */
showPlanetOrbits: boolean;
showMoonOrbits: boolean;
showVesselOrbits: boolean;
onSelect: (id: string | null) => void;
}
interface SceneRefs {
@@ -30,7 +32,7 @@ interface SceneRefs {
bodyMeshes: Map<string, THREE.Mesh>;
vesselMeshes: Map<string, THREE.Mesh>;
orbitLines: Map<string, THREE.Line>;
mount: HTMLDivElement;
controller: CameraController;
raf: number;
}
@@ -41,15 +43,20 @@ const ORBIT_OPACITY: Record<string, number> = {
};
export function Scene(props: SceneProps) {
const { snapshot, ut, followId, showPlanetOrbits, showMoonOrbits, showVesselOrbits } = props;
const { snapshot, ut, followId, showPlanetOrbits, showMoonOrbits, showVesselOrbits, onSelect } =
props;
const mountRef = useRef<HTMLDivElement>(null);
const refsRef = useRef<SceneRefs | null>(null);
// Latest-snapshot / ut / followId refs so the camera controller
// always sees the current values without needing to be recreated.
const stateRef = useRef({ snapshot, ut, followId, onSelect });
stateRef.current = { snapshot, ut, followId, onSelect };
// One-time scene setup
useEffect(() => {
const mount = mountRef.current;
if (!mount) return;
const refs = createScene(mount);
const refs = createScene(mount, stateRef);
refsRef.current = refs;
const onResize = () => {
@@ -66,6 +73,7 @@ export function Scene(props: SceneProps) {
return () => {
window.removeEventListener('resize', onResize);
cancelAnimationFrame(refs.raf);
refs.controller.dispose();
refs.renderer.dispose();
if (mount.contains(refs.renderer.domElement)) {
mount.removeChild(refs.renderer.domElement);
@@ -73,15 +81,14 @@ export function Scene(props: SceneProps) {
};
}, []);
// Rebuild the body / vessel meshes whenever the snapshot's set of
// bodies or vessels changes (not on every snapshot — they're stable).
// Rebuild meshes when bodies/vessels set changes
useEffect(() => {
const refs = refsRef.current;
if (!refs) return;
rebuildMeshes(refs, snapshot);
}, [snapshot.bodies, snapshot.vessels, snapshot]);
// Toggle orbit line visibility
// Toggle orbit visibility
useEffect(() => {
const refs = refsRef.current;
if (!refs) return;
@@ -90,48 +97,44 @@ export function Scene(props: SceneProps) {
const isMoon = snapshot.bodies.find((b) => b.id === id && b.kind === 'moon');
if (isPlanet) line.visible = showPlanetOrbits;
else if (isMoon) line.visible = showMoonOrbits;
else line.visible = showVesselOrbits; // vessel
else line.visible = showVesselOrbits;
}
}, [showPlanetOrbits, showMoonOrbits, showVesselOrbits, snapshot.bodies]);
// Per-frame: propagate, position meshes, follow camera
// Per-frame
useEffect(() => {
const refs = refsRef.current;
if (!refs) return;
let lastUt = Number.NEGATIVE_INFINITY;
const render = () => {
// Re-propagate positions whenever ut changes
if (ut !== lastUt) {
lastUt = ut;
positionMeshes(refs, snapshot, ut);
}
// Camera follow
if (followId) {
const followPos = getFollowPosition(snapshot, followId, ut);
if (followPos) {
refs.camera.position.lerp(
new THREE.Vector3(followPos.x, followPos.y, followPos.z).multiplyScalar(1.05),
0.05,
);
// Also add a small offset for context
const target = new THREE.Vector3(followPos.x, followPos.y, followPos.z);
refs.camera.lookAt(target);
}
const cur = stateRef.current;
if (cur.ut !== lastUt) {
lastUt = cur.ut;
positionMeshes(refs, cur.snapshot, cur.ut);
}
refs.controller.update();
refs.renderer.render(refs.scene, refs.camera);
refs.raf = requestAnimationFrame(render);
};
refs.raf = requestAnimationFrame(render);
return () => cancelAnimationFrame(refs.raf);
}, [snapshot, ut, followId]);
}, []);
return <div ref={mountRef} style={{ width: '100%', height: '100%' }} />;
return <div ref={mountRef} style={{ width: '100%', height: '100%', cursor: 'grab' }} />;
}
// ─── Three.js setup helpers ────────────────────────────────────────────────
function createScene(mount: HTMLDivElement): SceneRefs {
function createScene(
mount: HTMLDivElement,
stateRef: React.MutableRefObject<{
snapshot: UniverseSnapshot;
ut: number;
followId: string | null;
onSelect: (id: string | null) => void;
}>,
): SceneRefs {
const width = mount.clientWidth;
const height = mount.clientHeight;
@@ -148,17 +151,16 @@ function createScene(mount: HTMLDivElement): SceneRefs {
mount.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0x404040, 0.4));
const sunLight = new THREE.PointLight(0xffffff, 2, 0, 0);
scene.add(sunLight);
scene.add(new THREE.PointLight(0xffffff, 2, 0, 0));
const onResize = () => {
const w = mount.clientWidth;
const h = mount.clientHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
};
window.addEventListener('resize', onResize);
const controller = new CameraController({
camera,
domElement: mount,
getSnapshot: () => stateRef.current.snapshot,
getUt: () => stateRef.current.ut,
getFollowId: () => stateRef.current.followId,
onSelect: (id) => stateRef.current.onSelect(id),
});
return {
scene,
@@ -167,17 +169,20 @@ function createScene(mount: HTMLDivElement): SceneRefs {
bodyMeshes: new Map(),
vesselMeshes: new Map(),
orbitLines: new Map(),
mount,
controller,
raf: 0,
};
}
function rebuildMeshes(refs: SceneRefs, snap: UniverseSnapshot): void {
// Remove existing meshes / lines
for (const mesh of refs.bodyMeshes.values()) {
refs.scene.remove(mesh);
mesh.geometry.dispose();
(mesh.material as THREE.Material).dispose();
if (Array.isArray(mesh.material)) {
mesh.material.forEach((m) => m.dispose());
} else {
(mesh.material as THREE.Material).dispose();
}
}
for (const mesh of refs.vesselMeshes.values()) {
refs.scene.remove(mesh);
@@ -198,13 +203,13 @@ function rebuildMeshes(refs: SceneRefs, snap: UniverseSnapshot): void {
const geo = new THREE.SphereGeometry(Math.max(body.radius, 1e8), 32, 16);
const mat = new THREE.MeshBasicMaterial({ color: bodyColor(body.id) });
const mesh = new THREE.Mesh(geo, mat);
mesh.userData = { id: body.id };
refs.scene.add(mesh);
refs.bodyMeshes.set(body.id, mesh);
continue;
}
if (body.parentId === null) continue;
// Body sphere
const displayRadius = Math.max(body.radius, 1e6);
const geo = new THREE.SphereGeometry(displayRadius, 32, 16);
const mat = new THREE.MeshPhongMaterial({
@@ -212,9 +217,16 @@ function rebuildMeshes(refs: SceneRefs, snap: UniverseSnapshot): void {
emissive: 0x111111,
});
const mesh = new THREE.Mesh(geo, mat);
mesh.userData = { id: body.id };
refs.scene.add(mesh);
refs.bodyMeshes.set(body.id, mesh);
// Atmospheric glow for planets/moons (skip very small bodies)
if (body.kind === 'planet' || (body.kind === 'moon' && body.radius > 100_000)) {
const glow = createGlow(body.radius, bodyColor(body.id), 0.35, 1.35);
mesh.add(glow); // attach as child so it follows position
}
// Orbit line
const points = sampleOrbit(body.orbit, body.gravitationalParameter, 256);
const positions = new Float32Array(points.length * 3);
@@ -239,10 +251,10 @@ function rebuildMeshes(refs: SceneRefs, snap: UniverseSnapshot): void {
const geo = new THREE.SphereGeometry(2e5, 12, 8);
const mat = new THREE.MeshBasicMaterial({ color: vesselColor(vessel.owner) });
const mesh = new THREE.Mesh(geo, mat);
mesh.userData = { id: vessel.id };
refs.scene.add(mesh);
refs.vesselMeshes.set(vessel.id, mesh);
// Vessel orbit (relative to its reference body)
if (vessel.referenceBodyId) {
const ref = snap.bodies.find((b) => b.id === vessel.referenceBodyId);
if (ref) {
@@ -281,15 +293,3 @@ function positionMeshes(refs: SceneRefs, snap: UniverseSnapshot, ut: number): vo
if (mesh) mesh.position.set(pos.x, pos.y, pos.z);
}
}
function getFollowPosition(
snap: UniverseSnapshot,
id: string,
ut: number,
): { x: number; y: number; z: number } | null {
const vessel = snap.vessels.find((v) => v.id === id);
if (vessel) return vesselPositionAt(snap.bodies, vessel, ut);
const body = snap.bodies.find((b) => b.id === id);
if (body) return bodyPositionAt(snap.bodies, id, ut);
return null;
}