feat: render the black hole and sky with a WebGL2 ray tracer
Replace the SVG core and backdrop with one shader that traces each pixel through Schwarzschild spacetime. The shadow, the arch of the far side of the disk, the second image and the Einstein ring come from the physics rather than artwork. The disk is a thin disk seen from a low angle, about five times the shadow's radius, with Doppler beaming and a filtered, cloud-like texture. - Sky: a procedural galaxy baked once into a cubemap. Point sources are small, few and brightness-capped so they never rival the orbit markers, which now carry a dark backing disc and outline. - Quality: tiers from high to still, a startup calibration cached per canvas size, an fps cap, and an idle sleep. A locked realistic map draws nothing. - Integration: the canvas follows the galaxy frame through Big Screen, draws in Motion's post-render step, takes the disk clock and capture absorption from the galaxy loop, and falls back to the SVG core without WebGL2. - Radar view: a toolbar toggle switches to a radar look that spreads outward from the hole as a wave, with a sweep on its own clock. The choice is remembered per browser; reduced motion switches at once and holds the sweep. - Tests for the geodesics, quality governor, look spring and layout, plus a standalone preview page (web/blackhole-proto.html) for tuning the look. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
39
web/blackhole-proto.html
Normal file
39
web/blackhole-proto.html
Normal file
@@ -0,0 +1,39 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Black hole prototype</title>
|
||||
<style>
|
||||
html, body { margin: 0; height: 100%; background: #0a0c10; color: #d9dad6; font: 12px/1.4 ui-monospace, monospace; overflow: hidden; }
|
||||
canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; }
|
||||
canvas:active { cursor: grabbing; }
|
||||
#panel { position: fixed; top: 12px; left: 12px; width: 250px; max-height: calc(100% - 24px); overflow: auto; padding: 10px 12px; background: #111418e6; border: 1px solid #2b3138; border-radius: 8px; backdrop-filter: blur(10px); }
|
||||
#panel.hidden { display: none; }
|
||||
#panel h1 { margin: 0 0 6px; font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; }
|
||||
#panel label { display: grid; grid-template-columns: 78px 1fr 38px; gap: 6px; align-items: center; margin: 4px 0; }
|
||||
#panel input[type=range] { width: 100%; }
|
||||
#panel .row { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
|
||||
#panel button { font: inherit; color: inherit; background: #191d22; border: 1px solid #393e45; border-radius: 5px; padding: 4px 8px; cursor: pointer; }
|
||||
#panel pre { margin: 8px 0 0; white-space: pre-wrap; color: #9298a0; }
|
||||
.tag { position: fixed; pointer-events: none; font: 500 10px/1 ui-monospace, monospace; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; opacity: 0; white-space: nowrap; }
|
||||
.tag::before { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-right: 6px; }
|
||||
.tag.left { transform: translateX(-100%); }
|
||||
.tag.left::before { display: none; }
|
||||
.tag.left::after { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-left: 6px; }
|
||||
.tag.mint { color: #8bcbb3; }
|
||||
.tag.mint::before { display: none; }
|
||||
#modes { display: flex; gap: 6px; margin: 4px 0 8px; }
|
||||
#modes button.on { border-color: #e8b57e; color: #ffe2c9; }
|
||||
#fail { position: fixed; inset: 0; display: none; place-items: center; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="stage"></canvas>
|
||||
<div id="fail">WebGL2 is not available in this browser.</div>
|
||||
<div class="tag" id="tagShadow">Shadow · 3√3 M</div>
|
||||
<div class="tag" id="tagDisk">Accretion disk · 6–26 M</div>
|
||||
<div id="panel"><h1>Black hole</h1><div id="modes"></div></div>
|
||||
<script type="module" src="/src/proto/blackhole-proto.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
29
web/scripts/blackhole-layout.test.mjs
Normal file
29
web/scripts/blackhole-layout.test.mjs
Normal file
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { layoutFor } from "../src/lib/blackhole/layout.ts";
|
||||
import { SCENE_WIDTH } from "../src/lib/galaxyLayout.ts";
|
||||
import { CRITICAL_IMPACT } from "../src/lib/blackhole/geodesic.ts";
|
||||
|
||||
const panel = { left: 100, top: 50, width: 800, height: 600 };
|
||||
|
||||
test("the hole sits at the centre of the galaxy frame, relative to the panel", () => {
|
||||
const frame = { left: 100 + 70, top: 50 + 60, width: 660, height: 480 };
|
||||
const { centerX, centerY } = layoutFor(frame, panel);
|
||||
assert.ok(Math.abs(centerX - (70 + 330) / 800) < 1e-9);
|
||||
assert.ok(Math.abs(centerY - (60 + 240) / 600) < 1e-9);
|
||||
});
|
||||
|
||||
test("the shadow has a fixed radius in scene units and scales with the frame", () => {
|
||||
const atNative = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH, height: 480 }, panel);
|
||||
assert.ok(Math.abs(atNative.pxPerM * CRITICAL_IMPACT - 34) < 1e-9);
|
||||
const doubled = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH * 2, height: 960 }, panel);
|
||||
assert.ok(Math.abs(doubled.pxPerM - atNative.pxPerM * 2) < 1e-9);
|
||||
});
|
||||
|
||||
test("a frame moving under a transition moves the hole with it", () => {
|
||||
const before = layoutFor({ left: 200, top: 100, width: 600, height: 436 }, panel);
|
||||
const after = layoutFor({ left: 240, top: 140, width: 600, height: 436 }, panel);
|
||||
assert.ok(Math.abs(after.centerX - before.centerX - 40 / 800) < 1e-9);
|
||||
assert.ok(Math.abs(after.centerY - before.centerY - 40 / 600) < 1e-9);
|
||||
assert.equal(after.pxPerM, before.pxPerM);
|
||||
});
|
||||
40
web/scripts/geodesic.test.mjs
Normal file
40
web/scripts/geodesic.test.mjs
Normal file
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { CRITICAL_IMPACT, HORIZON, deflection, traceImpact, traceRay } from "../src/lib/blackhole/geodesic.ts";
|
||||
|
||||
test("a ray inside the critical impact parameter is captured and one outside escapes", () => {
|
||||
assert.equal(traceImpact(CRITICAL_IMPACT * 0.94).outcome, "captured");
|
||||
assert.equal(traceImpact(CRITICAL_IMPACT * 1.06).outcome, "escaped");
|
||||
});
|
||||
|
||||
test("the shadow edge sits at the analytic 3√3 within the step error", () => {
|
||||
let captured = 0;
|
||||
let escaped = 10;
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const mid = (captured + escaped) / 2;
|
||||
const { outcome } = traceImpact(mid, 48, { maxSteps: 900 });
|
||||
if (outcome === "escaped") escaped = mid;
|
||||
else captured = mid;
|
||||
}
|
||||
assert.ok(Math.abs(escaped - CRITICAL_IMPACT) / CRITICAL_IMPACT < 0.03, `edge at ${escaped}`);
|
||||
});
|
||||
|
||||
test("weak-field deflection follows 4M/b plus the second-order term", () => {
|
||||
const b = 20;
|
||||
const expected = 4 / b + (15 * Math.PI) / 4 / (b * b);
|
||||
const angle = deflection(traceImpact(b, 400, { maxSteps: 600 }));
|
||||
assert.ok(Math.abs(angle - expected) / expected < 0.1, `${angle} vs ${expected}`);
|
||||
});
|
||||
|
||||
test("a ray that falls radially is captured at the horizon", () => {
|
||||
const trace = traceRay([0, 0, 30], [0, 0, -1]);
|
||||
assert.equal(trace.outcome, "captured");
|
||||
assert.ok(trace.minRadius < HORIZON);
|
||||
});
|
||||
|
||||
test("a ray in the disk plane never crosses it and a skewed ray crosses it once", () => {
|
||||
assert.equal(traceImpact(9).crossings.length, 0);
|
||||
const skew = traceRay([9, 14, 40], [0, -0.3, -0.95]);
|
||||
assert.equal(skew.crossings.length, 1);
|
||||
assert.equal(skew.crossings[0].point[1], 0);
|
||||
});
|
||||
108
web/scripts/look.test.mjs
Normal file
108
web/scripts/look.test.mjs
Normal file
@@ -0,0 +1,108 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createLook, jumpLook, requestLook, stepLook, styleAt, waveParams, WAVE_FEATHER } from "../src/lib/blackhole/look.ts";
|
||||
import { farthestCornerM } from "../src/lib/blackhole/layout.ts";
|
||||
|
||||
const run = (look, seconds, fps = 60) => {
|
||||
const progress = [];
|
||||
for (let i = 0; i < seconds * fps; i++) {
|
||||
stepLook(look, 1 / fps);
|
||||
progress.push(look.progress);
|
||||
}
|
||||
return progress;
|
||||
};
|
||||
|
||||
test("the wave expands from the hole, never overshoots, and settles on the new look", () => {
|
||||
const look = createLook(0);
|
||||
requestLook(look, 1);
|
||||
assert.equal(look.running, true);
|
||||
assert.equal(look.progress, 0);
|
||||
const progress = run(look, 3);
|
||||
for (let i = 1; i < progress.length; i++) {
|
||||
assert.ok(progress[i] >= progress[i - 1] - 1e-12, "progress never goes backwards");
|
||||
assert.ok(progress[i] <= 1, "progress never overshoots");
|
||||
}
|
||||
assert.equal(look.running, false);
|
||||
assert.equal(look.from, 1);
|
||||
assert.equal(look.to, 1);
|
||||
const finishedAt = progress.findIndex((value) => value === 1);
|
||||
assert.ok(finishedAt > 20 && finishedAt < 150, `settled after ${finishedAt} frames`);
|
||||
});
|
||||
|
||||
test("a request made mid-wave waits for the wave to finish instead of reversing it", () => {
|
||||
const look = createLook(0);
|
||||
requestLook(look, 1);
|
||||
run(look, 0.3);
|
||||
const before = look.progress;
|
||||
requestLook(look, 0);
|
||||
assert.equal(look.queued, 0);
|
||||
assert.equal(look.to, 1, "the running wave keeps its target");
|
||||
assert.ok(look.progress >= before);
|
||||
run(look, 4);
|
||||
assert.equal(look.running, false);
|
||||
assert.equal(look.to, 0, "the queued look ran afterwards");
|
||||
});
|
||||
|
||||
test("asking for the look that is already showing does nothing, and the queue follows the latest request", () => {
|
||||
const look = createLook(1);
|
||||
requestLook(look, 1);
|
||||
assert.equal(look.running, false);
|
||||
requestLook(look, 0);
|
||||
assert.equal(look.running, true);
|
||||
requestLook(look, 1);
|
||||
assert.equal(look.queued, 1, "asking for the old look mid-wave queues it");
|
||||
requestLook(look, 0);
|
||||
assert.equal(look.queued, undefined, "asking for the running target again cancels the queue");
|
||||
assert.equal(look.to, 0);
|
||||
});
|
||||
|
||||
test("pixels inside the front show the new look and pixels outside keep the old one", () => {
|
||||
const look = createLook(0);
|
||||
requestLook(look, 1);
|
||||
run(look, 0.4);
|
||||
const wave = waveParams(look, 50);
|
||||
assert.equal(styleAt(wave, 0), 1);
|
||||
assert.equal(styleAt(wave, wave.waveRadius + 1), 0);
|
||||
const middle = styleAt(wave, wave.waveRadius - WAVE_FEATHER / 2);
|
||||
assert.ok(middle > 0 && middle < 1, "the front is soft");
|
||||
});
|
||||
|
||||
test("the front covers the whole picture by the time the wave finishes, and fades as it goes", () => {
|
||||
const look = createLook(0);
|
||||
requestLook(look, 1);
|
||||
const fronts = [];
|
||||
const radii = [];
|
||||
for (let i = 0; i < 240 && look.running; i++) {
|
||||
stepLook(look, 1 / 60);
|
||||
const wave = waveParams(look, 50);
|
||||
fronts.push(wave.waveFront);
|
||||
radii.push(wave.waveRadius);
|
||||
}
|
||||
for (let i = 1; i < fronts.length; i++) {
|
||||
assert.ok(fronts[i] <= fronts[i - 1] + 1e-12);
|
||||
assert.ok(radii[i] >= radii[i - 1] - 1e-12);
|
||||
}
|
||||
const settled = waveParams(look, 50);
|
||||
assert.equal(settled.waveFront, 0);
|
||||
assert.equal(settled.styleFrom, 1);
|
||||
assert.equal(styleAt(settled, 49), 1);
|
||||
});
|
||||
|
||||
test("the wave has to travel as far as the farthest corner", () => {
|
||||
const radius = farthestCornerM({ x: 300, y: 200 }, { width: 800, height: 600 }, 10);
|
||||
assert.ok(Math.abs(radius - Math.hypot(500, 400) / 10) < 1e-9);
|
||||
});
|
||||
|
||||
test("jumping to a look drops any wave and any queued request", () => {
|
||||
const look = createLook(0);
|
||||
requestLook(look, 1);
|
||||
run(look, 0.2);
|
||||
requestLook(look, 0);
|
||||
jumpLook(look, 1);
|
||||
assert.equal(look.running, false);
|
||||
assert.equal(look.from, 1);
|
||||
assert.equal(look.to, 1);
|
||||
assert.equal(look.queued, undefined);
|
||||
assert.equal(waveParams(look, 50).waveFront, 0);
|
||||
assert.equal(styleAt(waveParams(look, 50), 40), 1);
|
||||
});
|
||||
41
web/scripts/quality.test.mjs
Normal file
41
web/scripts/quality.test.mjs
Normal file
@@ -0,0 +1,41 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { FRAME_BUDGET_MS, FREEZE_BUDGET_MS, QUALITY_TIERS, chooseTier, initialTier } from "../src/lib/blackhole/quality.ts";
|
||||
|
||||
const samples = (ms, count = 30) => Array.from({ length: count }, () => ms);
|
||||
|
||||
test("the governor steps down one tier when the median render time exceeds the budget", () => {
|
||||
assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS + 4), sinceChangeMs: 5000 }), 1);
|
||||
assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS - 4), sinceChangeMs: 5000 }), 0);
|
||||
});
|
||||
|
||||
test("the governor ignores a lone spike, too few samples and a tier that has not settled", () => {
|
||||
const spiky = [...samples(4, 29), 90];
|
||||
assert.equal(chooseTier({ tier: 1, samples: spiky, sinceChangeMs: 5000 }), 1);
|
||||
assert.equal(chooseTier({ tier: 1, samples: samples(40, 5), sinceChangeMs: 5000 }), 1);
|
||||
assert.equal(chooseTier({ tier: 1, samples: samples(40), sinceChangeMs: 200 }), 1);
|
||||
});
|
||||
|
||||
test("the governor stops at the lowest tier and never steps back up", () => {
|
||||
const last = QUALITY_TIERS.length - 1;
|
||||
assert.equal(chooseTier({ tier: last, samples: samples(80), sinceChangeMs: 5000 }), last);
|
||||
assert.equal(chooseTier({ tier: 2, samples: samples(0.5), sinceChangeMs: 5000 }), 2);
|
||||
});
|
||||
|
||||
test("motion only freezes when the lowest animated tier is clearly failing", () => {
|
||||
const minimal = QUALITY_TIERS.findIndex(({ name }) => name === "minimal");
|
||||
assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS - 4), sinceChangeMs: 5000 }), minimal);
|
||||
assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS + 4), sinceChangeMs: 5000 }), minimal + 1);
|
||||
assert.equal(QUALITY_TIERS[minimal + 1].maxFps, 0);
|
||||
});
|
||||
|
||||
test("tiers get strictly cheaper and software rendering starts at the bottom", () => {
|
||||
for (let i = 1; i < QUALITY_TIERS.length; i++) {
|
||||
assert.ok(QUALITY_TIERS[i].scale <= QUALITY_TIERS[i - 1].scale);
|
||||
assert.ok(QUALITY_TIERS[i].steps <= QUALITY_TIERS[i - 1].steps);
|
||||
assert.ok(QUALITY_TIERS[i].maxFps <= QUALITY_TIERS[i - 1].maxFps);
|
||||
}
|
||||
assert.equal(initialTier({ software: true, pixels: 1e6 }), QUALITY_TIERS.length - 1);
|
||||
assert.equal(initialTier({ software: false, cores: 8, memoryGb: 16, pixels: 2e6 }), 0);
|
||||
assert.equal(initialTier({ software: false, cores: 4, pixels: 2e6 }), 1);
|
||||
});
|
||||
@@ -31,6 +31,17 @@ const panelTitles: Record<HUDMode, string> = {
|
||||
snapshot: "Snapshot detail",
|
||||
};
|
||||
|
||||
const LOOK_KEY = "tessera.look";
|
||||
|
||||
/** The look is a per-viewer preference. Storage can be blocked or empty, so every access is guarded. */
|
||||
function readRadar() {
|
||||
try {
|
||||
return window.localStorage.getItem(LOOK_KEY) === "radar";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function priority(orbit: Orbit) {
|
||||
if (orbit.last_status === "failed") return 0;
|
||||
return orbitStatus(orbit.last_status).busy ? 1 : 2;
|
||||
@@ -44,6 +55,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
||||
const [logoutError, setLogoutError] = useState(false);
|
||||
const workspaceScroll = useRef<number>(undefined);
|
||||
const [bigScreen, setBigScreen] = useState(false);
|
||||
const [radar, setRadar] = useState(readRadar);
|
||||
const [mode, setMode] = useState<HUDMode>("scene");
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const searchTrigger = useRef<HTMLButtonElement>(null);
|
||||
@@ -109,6 +121,15 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
||||
if (!bigScreen) workspaceScroll.current = window.scrollY;
|
||||
setBigScreen(!bigScreen);
|
||||
}
|
||||
function toggleRadar() {
|
||||
const next = !radar;
|
||||
setRadar(next);
|
||||
try {
|
||||
window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic");
|
||||
} catch {
|
||||
// The look still changes for this visit; it just will not be remembered.
|
||||
}
|
||||
}
|
||||
|
||||
const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 });
|
||||
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 });
|
||||
@@ -256,6 +277,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
||||
orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)}
|
||||
flowing={play && !reducedMotion} reducedMotion={reducedMotion} captureEffect={captureEffect} captureGlow={captureGlow} captureReady={captureReady}
|
||||
bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
|
||||
radar={radar} onToggleRadar={toggleRadar}
|
||||
onToggleFlow={() => setPlay((value) => !value)}
|
||||
onSelectOrbit={(id) => {
|
||||
selectOrbit(id);
|
||||
|
||||
65
web/src/components/scene/BlackholeBackdrop.tsx
Normal file
65
web/src/components/scene/BlackholeBackdrop.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import { createBlackholeController, type BlackholeController, type CoreSignal } from "../../lib/blackhole/controller";
|
||||
|
||||
/**
|
||||
* The black hole and the sky behind it, drawn by one WebGL2 shader. It sits under the whole scene panel and follows
|
||||
* the galaxy frame, which springs between the workspace and Big Screen.
|
||||
*/
|
||||
export function BlackholeBackdrop({ signal, bigScreen, radar, reducedMotion, onUnavailable }: {
|
||||
signal: CoreSignal;
|
||||
bigScreen: boolean;
|
||||
radar: boolean;
|
||||
reducedMotion: boolean;
|
||||
onUnavailable: () => void;
|
||||
}) {
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const controller = useRef<BlackholeController>(undefined);
|
||||
const unavailable = useRef(onUnavailable);
|
||||
unavailable.current = onUnavailable;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = canvas.current;
|
||||
const panel = element?.closest<HTMLElement>(".vault-scene");
|
||||
const created = element && panel && createBlackholeController({
|
||||
canvas: element,
|
||||
panel,
|
||||
frame: () => panel.querySelector<HTMLElement>(".galaxy-frame"),
|
||||
signal,
|
||||
onLost: () => unavailable.current(),
|
||||
});
|
||||
if (!created) {
|
||||
unavailable.current();
|
||||
return;
|
||||
}
|
||||
controller.current = created;
|
||||
signal.wake = created.wake;
|
||||
return () => {
|
||||
signal.wake = undefined;
|
||||
controller.current = undefined;
|
||||
created.dispose();
|
||||
};
|
||||
}, [signal]);
|
||||
|
||||
// The radar look arrives as a wave from the hole. The look the page loads with is applied at once, with no wave.
|
||||
const styled = useRef<BlackholeController>(undefined);
|
||||
useLayoutEffect(() => {
|
||||
controller.current?.setReducedMotion(reducedMotion);
|
||||
}, [reducedMotion]);
|
||||
useLayoutEffect(() => {
|
||||
// A new controller (first mount, or a StrictMode remount) takes the current look at once; later changes animate.
|
||||
const fresh = styled.current !== controller.current;
|
||||
styled.current = controller.current;
|
||||
controller.current?.setLook(radar ? 1 : 0, fresh);
|
||||
}, [radar]);
|
||||
|
||||
// The frame moves under a spring when the mode changes, so keep drawing until it settles.
|
||||
useLayoutEffect(() => {
|
||||
controller.current?.track(2200);
|
||||
}, [bigScreen]);
|
||||
|
||||
return (
|
||||
<div className="space-backdrop" aria-hidden="true">
|
||||
<canvas ref={canvas} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
|
||||
import { useScreenTransition } from "../../hooks/useScreenTransition";
|
||||
import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion";
|
||||
import { VaultCore } from "./VaultCore";
|
||||
import type { CoreSignal } from "../../lib/blackhole/controller";
|
||||
|
||||
export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string };
|
||||
|
||||
@@ -23,6 +24,8 @@ type Props = {
|
||||
bigScreen: boolean;
|
||||
captureEffect?: CaptureEffect;
|
||||
captureGlow: MotionValue<number>;
|
||||
signal: CoreSignal;
|
||||
svgCore: boolean;
|
||||
captureReady: boolean;
|
||||
onSelectOrbit: (id: string) => void;
|
||||
onSelectSnapshot: (id: string) => void;
|
||||
@@ -37,7 +40,7 @@ const ACCRETION_SECONDS = 6.4;
|
||||
const TRAIL_WIDTHS = [0.8, 1.4, 2.3];
|
||||
|
||||
export function BlackholeGalaxy({
|
||||
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, captureReady, onSelectOrbit, onSelectSnapshot,
|
||||
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, onSelectOrbit, onSelectSnapshot,
|
||||
}: Props) {
|
||||
const frame = useRef<HTMLDivElement>(null);
|
||||
const bodyNodes = useRef(new Map<SVGGElement, { id: string; index: number }>());
|
||||
@@ -52,6 +55,7 @@ export function BlackholeGalaxy({
|
||||
const diskTime = useRef(0);
|
||||
const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy);
|
||||
const trailId = useId();
|
||||
const knockoutId = useId();
|
||||
const trail = useRef<SVGPathElement>(null);
|
||||
const trailSegments = useRef<(SVGUseElement | null)[]>([]);
|
||||
const head = useRef<SVGCircleElement>(null);
|
||||
@@ -213,6 +217,11 @@ export function BlackholeGalaxy({
|
||||
const phase = (diskTime.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
|
||||
core.current?.style.setProperty("--accretion-offset", String(-100 * phase));
|
||||
}
|
||||
if (signal.time !== diskTime.current || signal.absorption !== absorption) {
|
||||
signal.time = diskTime.current;
|
||||
signal.absorption = absorption;
|
||||
signal.wake?.();
|
||||
}
|
||||
const coreStyle = core.current?.style;
|
||||
if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) {
|
||||
coreStyle.setProperty("--capture-absorption", String(absorption));
|
||||
@@ -270,6 +279,7 @@ export function BlackholeGalaxy({
|
||||
data-orbit-marker={orbit.id}
|
||||
className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`}
|
||||
>
|
||||
<circle className="orbit-knockout" r={selected ? 16 : 11} fill={`url(#${knockoutId})`} />
|
||||
<motion.circle className="orbit-halo" r={selected ? 16 : 10}
|
||||
variants={{ idle: { opacity: 0.08 }, hover: { opacity: 0.3 } }} />
|
||||
{status.tone === "red" && <path className="orbit-alert" d="M0 -8 8 0 0 8 -8 0Z" />}
|
||||
@@ -283,12 +293,19 @@ export function BlackholeGalaxy({
|
||||
return (
|
||||
<motion.div ref={frame} className="galaxy-frame" data-flowing={flowing} style={revealVariables}>
|
||||
<svg viewBox={`${-HALF_WIDTH} ${-HALF_HEIGHT} ${SCENE_WIDTH} ${SCENE_HEIGHT}`} aria-hidden="true">
|
||||
<defs>
|
||||
<radialGradient id={knockoutId}>
|
||||
<stop offset="0" stopColor="#0a0c10" stopOpacity=".78" />
|
||||
<stop offset=".55" stopColor="#0a0c10" stopOpacity=".62" />
|
||||
<stop offset="1" stopColor="#0a0c10" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<g className="orbit-tracks" pointerEvents="none">
|
||||
{orbitRadii.map((radius) => (
|
||||
<ellipse key={radius} rx={radius} ry={radius * ORBIT_TILT} className={selectedSlot?.radius === radius ? "is-selected" : ""} />
|
||||
))}
|
||||
</g>
|
||||
<VaultCore ref={core} />
|
||||
{svgCore ? <VaultCore ref={core} /> : <g ref={core} data-vault-core />}
|
||||
<g className="orbit-layer">{renderOrbits}</g>
|
||||
{selectedPosition && <motion.circle className="orbit-selection" cx={selectionX} cy={selectionY} r="13" />}
|
||||
<g className="lock-details" pointerEvents={moving ? "none" : undefined}>
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { BlackholeGalaxy, type CaptureEffect } from "./BlackholeGalaxy";
|
||||
import { useCallback, useState } from "react";
|
||||
import { BlackholeBackdrop } from "./BlackholeBackdrop";
|
||||
import { SpaceBackdrop } from "./SpaceBackdrop";
|
||||
import type { CoreSignal } from "../../lib/blackhole/controller";
|
||||
import { motion, type MotionValue } from "motion/react";
|
||||
import type { Orbit, Snapshot } from "../../api";
|
||||
|
||||
export function VaultScene({
|
||||
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, captureEffect, captureGlow, captureReady,
|
||||
bigScreen, onToggleBigScreen, onToggleFlow, onSelectOrbit, onSelectSnapshot,
|
||||
bigScreen, radar, onToggleBigScreen, onToggleRadar, onToggleFlow, onSelectOrbit, onSelectSnapshot,
|
||||
}: {
|
||||
orbits: Orbit[];
|
||||
selectedOrbitId?: string;
|
||||
@@ -16,16 +19,23 @@ export function VaultScene({
|
||||
captureGlow: MotionValue<number>;
|
||||
captureReady: boolean;
|
||||
bigScreen: boolean;
|
||||
radar: boolean;
|
||||
onToggleBigScreen: () => void;
|
||||
onToggleRadar: () => void;
|
||||
onToggleFlow: () => void;
|
||||
onSelectOrbit: (id: string) => void;
|
||||
onSelectSnapshot: (id: string) => void;
|
||||
}) {
|
||||
// The galaxy loop publishes the disk clock and capture absorption here; the WebGL backdrop reads them.
|
||||
const [signal] = useState<CoreSignal>(() => ({ time: 0, absorption: 0 }));
|
||||
const [svgCore, setSvgCore] = useState(false);
|
||||
const showSvgCore = useCallback(() => setSvgCore(true), []);
|
||||
const selected = orbits.find(({ id }) => id === selectedOrbitId);
|
||||
const screenLabel = bigScreen ? "Exit big screen" : "Big screen";
|
||||
const radarLabel = radar ? "Realistic view" : "Radar view";
|
||||
return (
|
||||
<section className="vault-scene" aria-label="Orbital map">
|
||||
<SpaceBackdrop />
|
||||
{svgCore ? <SpaceBackdrop /> : <BlackholeBackdrop signal={signal} bigScreen={bigScreen} radar={radar} reducedMotion={reducedMotion} onUnavailable={showSvgCore} />}
|
||||
<div className="scene-toolbar">
|
||||
<div>
|
||||
<p className="instrument-label">Vault map</p>
|
||||
@@ -48,6 +58,24 @@ export function VaultScene({
|
||||
</svg>
|
||||
{reducedMotion ? "Reduced motion" : flowing ? "Pause motion" : "Resume motion"}
|
||||
</button>
|
||||
{!svgCore && (
|
||||
<button
|
||||
className="console-control scene-screen-control scene-look-control"
|
||||
onClick={onToggleRadar}
|
||||
aria-pressed={radar}
|
||||
aria-label={radarLabel}
|
||||
title={radarLabel}
|
||||
type="button"
|
||||
>
|
||||
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none"
|
||||
stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="8" cy="8" r="6" />
|
||||
<circle cx="8" cy="8" r="2.6" opacity=".55" />
|
||||
<path d="M8 8 12.2 3.8" />
|
||||
</svg>
|
||||
<span>{radarLabel}</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="console-control scene-screen-control"
|
||||
onClick={onToggleBigScreen}
|
||||
@@ -74,6 +102,8 @@ export function VaultScene({
|
||||
bigScreen={bigScreen}
|
||||
captureEffect={captureEffect}
|
||||
captureGlow={captureGlow}
|
||||
signal={signal}
|
||||
svgCore={svgCore}
|
||||
captureReady={captureReady}
|
||||
onSelectOrbit={onSelectOrbit}
|
||||
onSelectSnapshot={onSelectSnapshot}
|
||||
|
||||
@@ -313,6 +313,7 @@ button:disabled { cursor: default; }
|
||||
}
|
||||
.vault-scene > :not(.space-backdrop) { position: relative; }
|
||||
.space-backdrop { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
|
||||
.space-backdrop canvas { display: block; width: 100%; height: 100%; }
|
||||
.space-backdrop::after {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@@ -337,13 +338,15 @@ button:disabled { cursor: default; }
|
||||
.legend-snapshot { border: 1px solid #dfe4ef; transform: rotate(45deg); }
|
||||
.galaxy-frame { width: 100%; max-width: calc((var(--workspace-height) - 120px) * 1.375); aspect-ratio: 11 / 8; align-self: center; justify-self: center; }
|
||||
.galaxy-frame > svg { display: block; width: 100%; height: 100%; overflow: hidden; }
|
||||
.orbit-tracks { fill: none; stroke: #949eaa; stroke-width: .75; opacity: .28; }
|
||||
.orbit-tracks { fill: none; stroke: #949eaa; stroke-width: .75; opacity: .36; }
|
||||
.orbit-tracks .is-selected { stroke: #eebf92; stroke-dasharray: 3 4; stroke-width: 1.6; }
|
||||
.orbit-marker { color: #c3c9d0; }
|
||||
.orbit-marker--red { color: var(--color-orbit-red); }
|
||||
.orbit-marker--amber { color: var(--color-orbit-amber); }
|
||||
.orbit-marker--green { color: var(--color-orbit-green); }
|
||||
.orbit-light, .orbit-halo { fill: currentColor; pointer-events: none; }
|
||||
.orbit-light { stroke: #0a0c10; stroke-width: 1.4; }
|
||||
.orbit-knockout { pointer-events: none; }
|
||||
.orbit-halo { opacity: .08; }
|
||||
.orbit-alert, .orbit-selection, .orbit-busy { fill: none; stroke: currentColor; stroke-width: 1.15; pointer-events: none; }
|
||||
.orbit-selection { stroke: #f8eadc; stroke-width: 1; }
|
||||
|
||||
235
web/src/lib/blackhole/controller.ts
Normal file
235
web/src/lib/blackhole/controller.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { cancelFrame, frame as frameLoop } from "motion/react";
|
||||
import { farthestCornerM, layoutFor } from "./layout";
|
||||
import { createLook, jumpLook, requestLook, stepLook, waveParams, type Look } from "./look";
|
||||
import { CALIBRATION_SAMPLES, QUALITY_TIERS, chooseTier, initialTier } from "./quality";
|
||||
import { createBlackholeRenderer, defaultParams, type BlackholeParams } from "./renderer";
|
||||
|
||||
/** What the scene tells the renderer each frame. The galaxy loop writes it and calls `wake`. */
|
||||
export type CoreSignal = { time: number; absorption: number; wake?: () => void };
|
||||
|
||||
export type BlackholeController = {
|
||||
/** Ask for a redraw. Cheap to call every frame: draws are coalesced and capped by the quality tier. */
|
||||
wake: () => void;
|
||||
/** Keep drawing for a while at full rate, while the frame is moving under a transition. */
|
||||
track: (ms: number) => void;
|
||||
/** Switch between the realistic look and the radar look. The radar look spreads outward from the hole as a wave. */
|
||||
setLook: (look: Look, instant?: boolean) => void;
|
||||
/** Reduced motion switches looks at once and holds the radar sweep still, evenly lit. */
|
||||
setReducedMotion: (reduced: boolean) => void;
|
||||
dispose: () => void;
|
||||
};
|
||||
|
||||
type Options = {
|
||||
canvas: HTMLCanvasElement;
|
||||
panel: HTMLElement;
|
||||
frame: () => HTMLElement | null;
|
||||
signal: CoreSignal;
|
||||
onLost: () => void;
|
||||
};
|
||||
|
||||
export function createBlackholeController({ canvas, panel, frame, signal, onLost }: Options): BlackholeController | undefined {
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const nav = navigator as Navigator & { deviceMemory?: number };
|
||||
const areaPx = () => panel.clientWidth * panel.clientHeight * dpr * dpr;
|
||||
const startTier = (software: boolean) => initialTier({
|
||||
software,
|
||||
cores: navigator.hardwareConcurrency,
|
||||
memoryGb: nav.deviceMemory,
|
||||
pixels: areaPx(),
|
||||
});
|
||||
let tier = startTier(false);
|
||||
|
||||
let renderer: ReturnType<typeof createBlackholeRenderer>;
|
||||
try {
|
||||
renderer = createBlackholeRenderer(canvas, { skySize: QUALITY_TIERS[tier].skySize });
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!renderer) return undefined;
|
||||
const gpu = renderer;
|
||||
const software = gpu.info.software;
|
||||
if (software) tier = QUALITY_TIERS.length - 1;
|
||||
/** Calibrated results by canvas area, so toggling Big Screen back and forth does not re-time the GPU each time. */
|
||||
const calibrations: { area: number; tier: number }[] = [];
|
||||
|
||||
const params: BlackholeParams = { ...defaultParams };
|
||||
let queued = false;
|
||||
let lastDraw = 0;
|
||||
let trackUntil = 0;
|
||||
let forced = true;
|
||||
let frozenTime = signal.time;
|
||||
let calibrateTimer = 0;
|
||||
let disposed = false;
|
||||
// The look has its own clock: the radar sweep keeps turning on a locked map, because it is an instrument, not scenery.
|
||||
const look = createLook(0);
|
||||
let reduced = false;
|
||||
let sweepClock = 0;
|
||||
let sweepAmount = 0;
|
||||
let lastTick = 0;
|
||||
|
||||
const resize = () => {
|
||||
if (!panel.clientWidth || !panel.clientHeight) return;
|
||||
gpu.resize(panel.clientWidth, panel.clientHeight, dpr, QUALITY_TIERS[tier].scale);
|
||||
};
|
||||
|
||||
const applyTier = (next: number) => {
|
||||
tier = next;
|
||||
const preset = QUALITY_TIERS[tier];
|
||||
params.steps = preset.steps;
|
||||
params.stepScale = preset.stepScale;
|
||||
params.bloomPasses = preset.bloomPasses;
|
||||
frozenTime = signal.time;
|
||||
resize();
|
||||
};
|
||||
|
||||
const layout = () => {
|
||||
const target = frame();
|
||||
if (!target) return false;
|
||||
const box = target.getBoundingClientRect();
|
||||
const area = panel.getBoundingClientRect();
|
||||
if (!box.width || !area.width || !area.height) return false;
|
||||
Object.assign(params, layoutFor(box, area));
|
||||
return true;
|
||||
};
|
||||
|
||||
// Draw in Motion's post-render step: by then the frame's springing transform for this tick is applied, so the hole
|
||||
// can never lag the orbit markers that ride on it.
|
||||
const tick = ({ timestamp }: { timestamp: number }) => {
|
||||
queued = false;
|
||||
draw(timestamp);
|
||||
};
|
||||
const schedule = () => {
|
||||
if (queued || disposed || document.hidden) return;
|
||||
queued = true;
|
||||
frameLoop.postRender(tick);
|
||||
};
|
||||
|
||||
function draw(now: number) {
|
||||
const preset = QUALITY_TIERS[tier];
|
||||
const tracking = now < trackUntil;
|
||||
const waving = look.running;
|
||||
const radar = look.to === 1 || look.from === 1;
|
||||
const motion = !reduced && preset.maxFps > 0;
|
||||
const sweepTarget = radar && motion ? 1 : 0;
|
||||
// The still tier freezes ambient motion, but a capture still plays out at a low rate.
|
||||
const cap = preset.maxFps > 0 ? preset.maxFps : signal.absorption > 0 ? 15 : 0;
|
||||
const free = tracking || waving;
|
||||
if (!free && !forced && cap === 0 && Math.abs(sweepTarget - sweepAmount) < 0.004) return;
|
||||
if (!free && !forced && now - lastDraw < 1000 / cap - 2) {
|
||||
schedule();
|
||||
return;
|
||||
}
|
||||
if (!layout()) return;
|
||||
|
||||
const dt = lastTick ? Math.min(0.1, (now - lastTick) / 1000) : 0;
|
||||
lastTick = now;
|
||||
stepLook(look, dt);
|
||||
if (sweepTarget > 0) sweepClock += dt;
|
||||
sweepAmount += (sweepTarget - sweepAmount) * Math.min(1, dt * 7);
|
||||
if (Math.abs(sweepTarget - sweepAmount) < 0.004) sweepAmount = sweepTarget;
|
||||
|
||||
const width = panel.clientWidth;
|
||||
const height = panel.clientHeight;
|
||||
const maxRadius = farthestCornerM({ x: params.centerX * width, y: params.centerY * height }, { width, height }, params.pxPerM);
|
||||
Object.assign(params, waveParams(look, maxRadius), { styleKind: 1, sweep: sweepClock * 0.8, sweepAmount });
|
||||
|
||||
const time = preset.maxFps > 0 ? signal.time : frozenTime;
|
||||
params.sway = 0.06 * Math.sin(time * 0.05);
|
||||
params.absorb = signal.absorption;
|
||||
gpu.render(time, params);
|
||||
lastDraw = now;
|
||||
forced = false;
|
||||
if (tracking || look.running || sweepTarget > 0 || sweepAmount !== sweepTarget) schedule();
|
||||
}
|
||||
|
||||
const wake = (force = false) => {
|
||||
if (force) forced = true;
|
||||
schedule();
|
||||
};
|
||||
|
||||
/** Time a few synchronised frames and step the quality down until the frame budget holds. */
|
||||
const calibrate = () => {
|
||||
if (disposed || document.hidden || !layout()) return;
|
||||
const area = areaPx();
|
||||
const cached = calibrations.find((entry) => Math.abs(entry.area / area - 1) < 0.25);
|
||||
if (cached) {
|
||||
if (cached.tier !== tier) applyTier(cached.tier);
|
||||
wake(true);
|
||||
return;
|
||||
}
|
||||
// Software rendering and the lowest tier have nothing left to learn, so do not stall the page timing them.
|
||||
tier = software ? QUALITY_TIERS.length - 1 : startTier(false);
|
||||
applyTier(tier);
|
||||
for (let attempt = 0; attempt < QUALITY_TIERS.length && tier < QUALITY_TIERS.length - 1; attempt++) {
|
||||
const samples: number[] = [];
|
||||
for (let i = 0; i < CALIBRATION_SAMPLES; i++) {
|
||||
const start = performance.now();
|
||||
gpu.render(0, params);
|
||||
gpu.finish();
|
||||
samples.push(performance.now() - start);
|
||||
}
|
||||
const next = chooseTier({ tier, samples, sinceChangeMs: Infinity });
|
||||
if (next === tier) break;
|
||||
applyTier(next);
|
||||
}
|
||||
calibrations.push({ area, tier });
|
||||
wake(true);
|
||||
};
|
||||
|
||||
const scheduleCalibration = () => {
|
||||
window.clearTimeout(calibrateTimer);
|
||||
calibrateTimer = window.setTimeout(calibrate, 700);
|
||||
};
|
||||
const observer = new ResizeObserver(() => {
|
||||
resize();
|
||||
wake(true);
|
||||
scheduleCalibration();
|
||||
});
|
||||
// A page loaded or resized while hidden draws nothing, and a locked map has no other reason to wake: catch up.
|
||||
const visibility = () => {
|
||||
if (document.hidden) return;
|
||||
resize();
|
||||
wake(true);
|
||||
scheduleCalibration();
|
||||
};
|
||||
const lost = (event: Event) => {
|
||||
event.preventDefault();
|
||||
onLost();
|
||||
};
|
||||
|
||||
applyTier(tier);
|
||||
observer.observe(panel);
|
||||
canvas.addEventListener("webglcontextlost", lost);
|
||||
document.addEventListener("visibilitychange", visibility);
|
||||
calibrateTimer = window.setTimeout(calibrate, 350);
|
||||
wake(true);
|
||||
|
||||
return {
|
||||
wake: () => wake(false),
|
||||
track: (ms) => {
|
||||
trackUntil = performance.now() + ms;
|
||||
wake(true);
|
||||
},
|
||||
setLook: (target, instant = false) => {
|
||||
if (instant || reduced) jumpLook(look, target);
|
||||
else requestLook(look, target);
|
||||
lastTick = 0;
|
||||
wake(true);
|
||||
},
|
||||
setReducedMotion: (value) => {
|
||||
reduced = value;
|
||||
if (reduced && look.running) jumpLook(look, look.queued ?? look.to);
|
||||
lastTick = 0;
|
||||
wake(true);
|
||||
},
|
||||
dispose: () => {
|
||||
disposed = true;
|
||||
cancelFrame(tick);
|
||||
window.clearTimeout(calibrateTimer);
|
||||
observer.disconnect();
|
||||
canvas.removeEventListener("webglcontextlost", lost);
|
||||
document.removeEventListener("visibilitychange", visibility);
|
||||
gpu.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
99
web/src/lib/blackhole/geodesic.ts
Normal file
99
web/src/lib/blackhole/geodesic.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Null geodesics in Schwarzschild spacetime, in units G = c = M = 1.
|
||||
//
|
||||
// The TypeScript tracer below is the reference for the GLSL tracer in `shaders.ts`: both use the same
|
||||
// constants and the same step rule, so the unit tests exercise the algorithm the shader runs.
|
||||
//
|
||||
// Light follows d²x/dt² = -3 h² x / r⁵ in flat 3D coordinates, with h = |x × v| conserved. This
|
||||
// reproduces the photon sphere at r = 3 and the critical impact parameter b = 3√3.
|
||||
|
||||
export const HORIZON = 2;
|
||||
export const PHOTON_SPHERE = 3;
|
||||
export const ISCO = 6;
|
||||
export const CRITICAL_IMPACT = 3 * Math.sqrt(3);
|
||||
|
||||
/** Camera plane distance. Rays are parallel (orthographic) and start this far from the hole. */
|
||||
export const START_RADIUS = 48;
|
||||
/** A ray that is farther than this and moving outward has escaped. */
|
||||
export const ESCAPE_RADIUS = 56;
|
||||
export const STEP_SCALE = 0.05;
|
||||
export const MAX_DT = 1.6;
|
||||
export const MAX_STEPS = 220;
|
||||
|
||||
export const GLSL_CONSTANTS = `
|
||||
const float HORIZON = ${HORIZON.toFixed(1)};
|
||||
const float START_RADIUS = ${START_RADIUS.toFixed(1)};
|
||||
const float ESCAPE_RADIUS = ${ESCAPE_RADIUS.toFixed(1)};
|
||||
const float MAX_DT = ${MAX_DT};
|
||||
const int MAX_STEPS = ${MAX_STEPS};
|
||||
`;
|
||||
|
||||
export type Vec3 = [number, number, number];
|
||||
|
||||
export type Crossing = { radius: number; point: Vec3; direction: Vec3 };
|
||||
|
||||
export type Trace = {
|
||||
outcome: "captured" | "escaped" | "unresolved";
|
||||
/** Unit direction the ray leaves with, when it escaped. */
|
||||
exit: Vec3;
|
||||
minRadius: number;
|
||||
steps: number;
|
||||
/** Crossings of the y = 0 plane (the disk plane), in the order the traced ray meets them. */
|
||||
crossings: Crossing[];
|
||||
};
|
||||
|
||||
export type TraceOptions = { maxSteps?: number; escapeRadius?: number };
|
||||
|
||||
const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const length = (a: Vec3) => Math.sqrt(dot(a, a));
|
||||
const cross = (a: Vec3, b: Vec3): Vec3 => [
|
||||
a[1] * b[2] - a[2] * b[1],
|
||||
a[2] * b[0] - a[0] * b[2],
|
||||
a[0] * b[1] - a[1] * b[0],
|
||||
];
|
||||
|
||||
export function traceRay(position: Vec3, direction: Vec3, options: TraceOptions = {}): Trace {
|
||||
const maxSteps = options.maxSteps ?? MAX_STEPS;
|
||||
const escapeRadius = options.escapeRadius ?? ESCAPE_RADIUS;
|
||||
let pos: Vec3 = [...position];
|
||||
const vel: Vec3 = [...direction];
|
||||
const h = cross(pos, vel);
|
||||
const h2 = dot(h, h);
|
||||
const crossings: Crossing[] = [];
|
||||
let minRadius = Infinity;
|
||||
|
||||
for (let step = 0; step < maxSteps; step++) {
|
||||
const r = length(pos);
|
||||
minRadius = Math.min(minRadius, r);
|
||||
if (r < HORIZON) return { outcome: "captured", exit: [0, 0, 0], minRadius, steps: step, crossings };
|
||||
if (r > escapeRadius && dot(pos, vel) > 0) {
|
||||
const speed = length(vel);
|
||||
return { outcome: "escaped", exit: [vel[0] / speed, vel[1] / speed, vel[2] / speed], minRadius, steps: step, crossings };
|
||||
}
|
||||
|
||||
const dt = Math.min(MAX_DT, STEP_SCALE * r);
|
||||
const pull = (-3 * h2) / (r * r * r * r * r);
|
||||
vel[0] += pull * pos[0] * dt;
|
||||
vel[1] += pull * pos[1] * dt;
|
||||
vel[2] += pull * pos[2] * dt;
|
||||
const next: Vec3 = [pos[0] + vel[0] * dt, pos[1] + vel[1] * dt, pos[2] + vel[2] * dt];
|
||||
|
||||
if (pos[1] * next[1] < 0) {
|
||||
const t = pos[1] / (pos[1] - next[1]);
|
||||
const point: Vec3 = [pos[0] + (next[0] - pos[0]) * t, 0, pos[2] + (next[2] - pos[2]) * t];
|
||||
const speed = length(vel);
|
||||
crossings.push({ radius: length(point), point, direction: [vel[0] / speed, vel[1] / speed, vel[2] / speed] });
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return { outcome: "unresolved", exit: [0, 0, 0], minRadius, steps: maxSteps, crossings };
|
||||
}
|
||||
|
||||
/** Trace a ray that arrives parallel to -z with impact parameter `b`, offset along +x. */
|
||||
export function traceImpact(b: number, startRadius = START_RADIUS, options: TraceOptions = {}): Trace {
|
||||
return traceRay([b, 0, startRadius], [0, 0, -1], { escapeRadius: startRadius * 1.15, ...options });
|
||||
}
|
||||
|
||||
/** Angle a ray is bent through, in radians, measured against its incoming direction. */
|
||||
export function deflection(trace: Trace): number {
|
||||
return Math.acos(Math.max(-1, Math.min(1, -trace.exit[2])));
|
||||
}
|
||||
28
web/src/lib/blackhole/layout.ts
Normal file
28
web/src/lib/blackhole/layout.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { SCENE_WIDTH } from "../galaxyLayout.ts";
|
||||
import { CRITICAL_IMPACT } from "./geodesic.ts";
|
||||
|
||||
export type Box = { left: number; top: number; width: number; height: number };
|
||||
|
||||
/**
|
||||
* The shadow's radius in scene units. The disk reaches about five times that, so at 34 it ends near the first orbit
|
||||
* ring (128) instead of covering the orbits, while staying in proportion to the shadow.
|
||||
*/
|
||||
const SHADOW_SCENE_RADIUS = 34;
|
||||
const PX_PER_M_SCENE = SHADOW_SCENE_RADIUS / CRITICAL_IMPACT;
|
||||
|
||||
/** Where the hole sits in the panel, and how big a gravitational radius is, for the current frame. */
|
||||
export function layoutFor(frame: Box, panel: Box) {
|
||||
return {
|
||||
centerX: (frame.left + frame.width / 2 - panel.left) / panel.width,
|
||||
centerY: (frame.top + frame.height / 2 - panel.top) / panel.height,
|
||||
pxPerM: (PX_PER_M_SCENE * frame.width) / SCENE_WIDTH,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** Distance from the hole to the farthest corner of the canvas, in gravitational radii: how far a wave must travel. */
|
||||
export function farthestCornerM(center: { x: number; y: number }, size: { width: number; height: number }, pxPerM: number) {
|
||||
const dx = Math.max(center.x, size.width - center.x);
|
||||
const dy = Math.max(center.y, size.height - center.y);
|
||||
return Math.hypot(dx, dy) / pxPerM;
|
||||
}
|
||||
111
web/src/lib/blackhole/look.ts
Normal file
111
web/src/lib/blackhole/look.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
// The radar look arrives as a wave that spreads outward from the hole, rather than a fade over the whole picture.
|
||||
// This module holds the wave's spring and turns it into shader parameters. It has no DOM or GL, so it is testable.
|
||||
|
||||
/** 0 is the realistic look, 1 is the radar look. */
|
||||
export type Look = 0 | 1;
|
||||
|
||||
export type LookTransition = {
|
||||
/** Look outside the front. */
|
||||
from: Look;
|
||||
/** Look inside the front, and the look the scene settles on. */
|
||||
to: Look;
|
||||
/** 0 when the front is at the hole, 1 when it has left the picture. */
|
||||
progress: number;
|
||||
velocity: number;
|
||||
running: boolean;
|
||||
/** A request made mid-wave. It starts when the wave ends, so a wave never reverses and pops. */
|
||||
queued?: Look;
|
||||
};
|
||||
|
||||
/** Close to critically damped: the front accelerates away from the hole and settles without overshoot. */
|
||||
export const WAVE_STIFFNESS = 70;
|
||||
export const WAVE_DAMPING = 17;
|
||||
/** Softness of the front, in gravitational radii. */
|
||||
export const WAVE_FEATHER = 3;
|
||||
|
||||
const SETTLED_PROGRESS = 0.999;
|
||||
const SETTLED_SPEED = 0.01;
|
||||
const SUBSTEP = 0.008;
|
||||
|
||||
export function createLook(initial: Look = 0): LookTransition {
|
||||
return { from: initial, to: initial, progress: 1, velocity: 0, running: false };
|
||||
}
|
||||
|
||||
export function requestLook(transition: LookTransition, target: Look) {
|
||||
if (transition.running) {
|
||||
transition.queued = target === transition.to ? undefined : target;
|
||||
return;
|
||||
}
|
||||
if (target === transition.to) return;
|
||||
transition.from = transition.to;
|
||||
transition.to = target;
|
||||
transition.progress = 0;
|
||||
transition.velocity = 0;
|
||||
transition.running = true;
|
||||
}
|
||||
|
||||
/** Switch look at once, with no wave: for reduced motion and for the look the page loads with. */
|
||||
export function jumpLook(transition: LookTransition, target: Look) {
|
||||
transition.from = target;
|
||||
transition.to = target;
|
||||
transition.progress = 1;
|
||||
transition.velocity = 0;
|
||||
transition.running = false;
|
||||
transition.queued = undefined;
|
||||
}
|
||||
|
||||
/** Advance the wave by `dt` seconds. Returns whether it is still running. */
|
||||
export function stepLook(transition: LookTransition, dt: number): boolean {
|
||||
if (!transition.running) return false;
|
||||
const steps = Math.max(1, Math.ceil(dt / SUBSTEP));
|
||||
const h = dt / steps;
|
||||
for (let i = 0; i < steps; i++) {
|
||||
transition.velocity += (WAVE_STIFFNESS * (1 - transition.progress) - WAVE_DAMPING * transition.velocity) * h;
|
||||
transition.progress = Math.min(1, transition.progress + transition.velocity * h);
|
||||
}
|
||||
if (transition.progress >= SETTLED_PROGRESS && Math.abs(transition.velocity) < SETTLED_SPEED) {
|
||||
transition.progress = 1;
|
||||
transition.velocity = 0;
|
||||
transition.running = false;
|
||||
transition.from = transition.to;
|
||||
const next = transition.queued;
|
||||
transition.queued = undefined;
|
||||
if (next !== undefined) requestLook(transition, next);
|
||||
}
|
||||
return transition.running;
|
||||
}
|
||||
|
||||
export type WaveParams = {
|
||||
styleFrom: number;
|
||||
styleTo: number;
|
||||
waveRadius: number;
|
||||
waveFeather: number;
|
||||
waveFront: number;
|
||||
};
|
||||
|
||||
/** Shader parameters for the current wave. `maxRadius` is the distance from the hole to the farthest corner, in M. */
|
||||
export function waveParams(transition: LookTransition, maxRadius: number): WaveParams {
|
||||
if (!transition.running) {
|
||||
return { styleFrom: transition.to, styleTo: transition.to, waveRadius: 1e4, waveFeather: WAVE_FEATHER, waveFront: 0 };
|
||||
}
|
||||
const { progress } = transition;
|
||||
return {
|
||||
styleFrom: transition.from,
|
||||
styleTo: transition.to,
|
||||
waveRadius: progress * (maxRadius + WAVE_FEATHER),
|
||||
waveFeather: WAVE_FEATHER,
|
||||
// The leading edge is brightest as it leaves the hole and fades out as it reaches the edge of the picture.
|
||||
waveFront: 1 - progress ** 3,
|
||||
};
|
||||
}
|
||||
|
||||
const smoothstep = (edge0: number, edge1: number, x: number) => {
|
||||
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
|
||||
return t * t * (3 - 2 * t);
|
||||
};
|
||||
|
||||
/** The look at a given distance from the hole: the same maths the shader uses, for labels and overlays. */
|
||||
export function styleAt(wave: WaveParams, radius: number): number {
|
||||
const inside = 1 - smoothstep(wave.waveRadius - wave.waveFeather, wave.waveRadius, radius);
|
||||
return wave.styleFrom + (wave.styleTo - wave.styleFrom) * inside;
|
||||
}
|
||||
62
web/src/lib/blackhole/quality.ts
Normal file
62
web/src/lib/blackhole/quality.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
export type QualityTier = {
|
||||
name: "high" | "medium" | "low" | "minimal" | "still";
|
||||
/** Scene render scale relative to the canvas. The composite upsamples, so lensing stays smooth. */
|
||||
scale: number;
|
||||
/** Ray-march step budget. A ray that runs out while heading outward samples the sky; the rest stay dark. */
|
||||
steps: number;
|
||||
/** Larger steps trade accuracy near the hole for speed. */
|
||||
stepScale: number;
|
||||
/** Quarter-resolution bloom passes: 4 is the full glow, 2 a tighter one, 0 none. */
|
||||
bloomPasses: 0 | 2 | 4;
|
||||
/** Edge length of each baked sky cubemap face. */
|
||||
skySize: number;
|
||||
/** Ambient frame-rate cap. The slow disk drift does not need more. Zero freezes ambient motion. */
|
||||
maxFps: number;
|
||||
};
|
||||
|
||||
export const QUALITY_TIERS: readonly QualityTier[] = [
|
||||
{ name: "high", scale: 1, steps: 200, stepScale: 0.05, bloomPasses: 4, skySize: 768, maxFps: 30 },
|
||||
{ name: "medium", scale: 0.75, steps: 170, stepScale: 0.06, bloomPasses: 4, skySize: 768, maxFps: 30 },
|
||||
{ name: "low", scale: 0.5, steps: 130, stepScale: 0.075, bloomPasses: 2, skySize: 512, maxFps: 24 },
|
||||
{ name: "minimal", scale: 0.4, steps: 100, stepScale: 0.09, bloomPasses: 0, skySize: 512, maxFps: 20 },
|
||||
{ name: "still", scale: 0.4, steps: 100, stepScale: 0.09, bloomPasses: 0, skySize: 512, maxFps: 0 },
|
||||
];
|
||||
|
||||
export type GovernorInput = {
|
||||
tier: number;
|
||||
/** Recent render times in ms: time spent drawing, not the gap between frames. */
|
||||
samples: number[];
|
||||
/** How long the current tier has been active. */
|
||||
sinceChangeMs: number;
|
||||
};
|
||||
|
||||
/** Frame budget in ms. A tier that cannot hold this leaves too little room for the rest of the page. */
|
||||
export const FRAME_BUDGET_MS = 12;
|
||||
/** Freezing motion is a last resort, so the step into it needs a clearly failing frame time. */
|
||||
export const FREEZE_BUDGET_MS = 24;
|
||||
/** Enough synchronised frames to take a median without stalling the page for long. */
|
||||
export const CALIBRATION_SAMPLES = 10;
|
||||
const MIN_SAMPLES = CALIBRATION_SAMPLES;
|
||||
const SETTLE_MS = 1500;
|
||||
|
||||
/**
|
||||
* Pick the next quality tier. It only ever steps down: stepping back up would oscillate, because a
|
||||
* cheaper tier always looks fast.
|
||||
*/
|
||||
export function chooseTier({ tier, samples, sinceChangeMs }: GovernorInput): number {
|
||||
const last = QUALITY_TIERS.length - 1;
|
||||
if (tier >= last || sinceChangeMs < SETTLE_MS || samples.length < MIN_SAMPLES) return tier;
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const median = sorted[Math.floor(sorted.length / 2)];
|
||||
const budget = tier + 1 === last ? FREEZE_BUDGET_MS : FRAME_BUDGET_MS;
|
||||
return median > budget ? tier + 1 : tier;
|
||||
}
|
||||
|
||||
/** Start one tier lower when the device cannot be expected to cope: small screens and weak hardware hints. */
|
||||
export function initialTier(hints: { software: boolean; cores?: number; memoryGb?: number; pixels: number }): number {
|
||||
if (hints.software) return QUALITY_TIERS.length - 1;
|
||||
let tier = 0;
|
||||
if ((hints.cores ?? 8) <= 4 || (hints.memoryGb ?? 8) <= 4) tier = 1;
|
||||
if (hints.pixels > 3840 * 2160 * 0.9) tier = Math.max(tier, 1);
|
||||
return tier;
|
||||
}
|
||||
312
web/src/lib/blackhole/renderer.ts
Normal file
312
web/src/lib/blackhole/renderer.ts
Normal file
@@ -0,0 +1,312 @@
|
||||
import { CRITICAL_IMPACT, ISCO } from "./geodesic";
|
||||
import { blurShader, compositeShader, sceneShader, skyBakeShader, vertexShader } from "./shaders";
|
||||
|
||||
/** Elevation the baked sky is composed for. The camera can move independently, so dragging it gives real parallax. */
|
||||
export const SKY_ELEVATION = (12 * Math.PI) / 180;
|
||||
|
||||
export type BlackholeParams = {
|
||||
/** Camera elevation above the disk plane, radians. */
|
||||
elevation: number;
|
||||
diskIn: number;
|
||||
diskOut: number;
|
||||
diskGain: number;
|
||||
doppler: number;
|
||||
bloom: number;
|
||||
exposure: number;
|
||||
steps: number;
|
||||
/** Disk images past this many plane crossings are dropped: they form a hairline ring on the shadow edge. */
|
||||
maxCrossings: number;
|
||||
/** Disk light from rays that passed closer than this to the hole (in M) is faded out. */
|
||||
rimCut: number;
|
||||
stepScale: number;
|
||||
/** Quarter-resolution bloom passes: 0, 2 or 4. */
|
||||
bloomPasses: number;
|
||||
/** Sky brightness multiplier. */
|
||||
sky: number;
|
||||
/** Look outside the wave front: 0 realistic, 1 stylized. */
|
||||
styleFrom: number;
|
||||
/** Look inside the wave front. */
|
||||
styleTo: number;
|
||||
/** Wave front, in gravitational radii from the hole. */
|
||||
waveRadius: number;
|
||||
waveFeather: number;
|
||||
/** 0 .. 1 brightness of the wave's leading edge. */
|
||||
waveFront: number;
|
||||
/** Stylized look: 1 schematic, 2 toon. */
|
||||
styleKind: number;
|
||||
/** Radar sweep angle, radians. */
|
||||
sweep: number;
|
||||
/** 0 evenly lit .. 1 full phosphor persistence. */
|
||||
sweepAmount: number;
|
||||
/** Capture absorption, 0..1: brightens the disk. */
|
||||
absorb: number;
|
||||
sway: number;
|
||||
showShadow: boolean;
|
||||
/** CSS pixels per gravitational radius. */
|
||||
pxPerM: number;
|
||||
/** Hole centre as a fraction of the canvas, y down. */
|
||||
centerX: number;
|
||||
centerY: number;
|
||||
};
|
||||
|
||||
export const defaultParams: BlackholeParams = {
|
||||
elevation: (8 * Math.PI) / 180,
|
||||
diskIn: ISCO,
|
||||
diskOut: 26,
|
||||
diskGain: 2.1,
|
||||
doppler: 0.75,
|
||||
bloom: 0.4,
|
||||
exposure: 1,
|
||||
steps: 200,
|
||||
maxCrossings: 2,
|
||||
rimCut: 0,
|
||||
stepScale: 0.05,
|
||||
bloomPasses: 4,
|
||||
sky: 0.55,
|
||||
styleFrom: 0,
|
||||
styleTo: 0,
|
||||
waveRadius: 1e4,
|
||||
waveFeather: 3,
|
||||
waveFront: 0,
|
||||
styleKind: 1,
|
||||
sweep: 0,
|
||||
sweepAmount: 1,
|
||||
absorb: 0,
|
||||
sway: 0,
|
||||
showShadow: false,
|
||||
pxPerM: 9.4,
|
||||
centerX: 0.5,
|
||||
centerY: 0.5,
|
||||
};
|
||||
|
||||
type Target = { texture: WebGLTexture; framebuffer: WebGLFramebuffer; width: number; height: number };
|
||||
|
||||
export type BlackholeRenderer = {
|
||||
info: { renderer: string; vendor: string; hdr: boolean; software: boolean; skySize: number; skyBakeMs: number };
|
||||
resize: (cssWidth: number, cssHeight: number, dpr: number, scale: number) => void;
|
||||
render: (time: number, params: BlackholeParams) => void;
|
||||
/** Block until the GPU has finished the last frame, for timing. */
|
||||
finish: () => void;
|
||||
dispose: () => void;
|
||||
};
|
||||
|
||||
export function createBlackholeRenderer(canvas: HTMLCanvasElement, options: { skySize?: number } = {}): BlackholeRenderer | undefined {
|
||||
const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, powerPreference: "high-performance" });
|
||||
if (!gl) return undefined;
|
||||
|
||||
const hdr = !!(gl.getExtension("EXT_color_buffer_float") || gl.getExtension("EXT_color_buffer_half_float"));
|
||||
const debug = gl.getExtension("WEBGL_debug_renderer_info");
|
||||
const renderer = debug ? String(gl.getParameter(debug.UNMASKED_RENDERER_WEBGL)) : "unknown";
|
||||
const vendor = debug ? String(gl.getParameter(debug.UNMASKED_VENDOR_WEBGL)) : "unknown";
|
||||
const software = /swiftshader|llvmpipe|software/i.test(renderer);
|
||||
|
||||
const compile = (type: number, source: string) => {
|
||||
const shader = gl.createShader(type)!;
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader) ?? "shader failed");
|
||||
return shader;
|
||||
};
|
||||
const program = (fragment: string) => {
|
||||
const handle = gl.createProgram()!;
|
||||
gl.attachShader(handle, compile(gl.VERTEX_SHADER, vertexShader));
|
||||
gl.attachShader(handle, compile(gl.FRAGMENT_SHADER, fragment));
|
||||
gl.bindAttribLocation(handle, 0, "aPosition");
|
||||
gl.linkProgram(handle);
|
||||
if (!gl.getProgramParameter(handle, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(handle) ?? "link failed");
|
||||
const uniforms = new Map<string, WebGLUniformLocation | null>();
|
||||
return { handle, uniform: (name: string) => {
|
||||
if (!uniforms.has(name)) uniforms.set(name, gl.getUniformLocation(handle, name));
|
||||
return uniforms.get(name)!;
|
||||
} };
|
||||
};
|
||||
|
||||
const scene = program(sceneShader);
|
||||
const skyBake = program(skyBakeShader);
|
||||
const blur = program(blurShader);
|
||||
const composite = program(compositeShader);
|
||||
|
||||
const quad = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(0);
|
||||
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
// The sky never changes, so render it once into a small cubemap instead of recomputing the noise per pixel.
|
||||
const skySize = options.skySize ?? 768;
|
||||
const skyMap = gl.createTexture()!;
|
||||
const bakeStart = performance.now();
|
||||
{
|
||||
gl.bindTexture(gl.TEXTURE_CUBE_MAP, skyMap);
|
||||
for (let face = 0; face < 6; face++) {
|
||||
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.RGBA8, skySize, skySize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
}
|
||||
const framebuffer = gl.createFramebuffer()!;
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
||||
gl.useProgram(skyBake.handle);
|
||||
gl.uniform1f(skyBake.uniform("uSkyElevation"), SKY_ELEVATION);
|
||||
gl.viewport(0, 0, skySize, skySize);
|
||||
for (let face = 0; face < 6; face++) {
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, skyMap, 0);
|
||||
gl.uniform1i(skyBake.uniform("uFace"), face);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
gl.deleteFramebuffer(framebuffer);
|
||||
gl.bindTexture(gl.TEXTURE_CUBE_MAP, skyMap);
|
||||
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
|
||||
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
|
||||
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
|
||||
}
|
||||
const skyBakeMs = performance.now() - bakeStart;
|
||||
|
||||
const makeTarget = (width: number, height: number): Target => {
|
||||
const texture = gl.createTexture()!;
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
if (hdr) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, width, height, 0, gl.RGBA, gl.HALF_FLOAT, null);
|
||||
else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
const framebuffer = gl.createFramebuffer()!;
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
|
||||
return { texture, framebuffer, width, height };
|
||||
};
|
||||
const freeTarget = (target?: Target) => {
|
||||
if (!target) return;
|
||||
gl.deleteTexture(target.texture);
|
||||
gl.deleteFramebuffer(target.framebuffer);
|
||||
};
|
||||
|
||||
let sceneTarget: Target | undefined;
|
||||
let bloomA: Target | undefined;
|
||||
let bloomB: Target | undefined;
|
||||
let dpr = 1;
|
||||
let cssWidth = 1;
|
||||
let cssHeight = 1;
|
||||
|
||||
const draw = (target: Target | undefined, width: number, height: number) => {
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, target?.framebuffer ?? null);
|
||||
gl.viewport(0, 0, width, height);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
};
|
||||
const bind = (unit: number, target: Target) => {
|
||||
gl.activeTexture(gl.TEXTURE0 + unit);
|
||||
gl.bindTexture(gl.TEXTURE_2D, target.texture);
|
||||
};
|
||||
|
||||
return {
|
||||
info: { renderer, vendor, hdr, software, skySize, skyBakeMs },
|
||||
resize(nextCssWidth, nextCssHeight, nextDpr, scale) {
|
||||
cssWidth = nextCssWidth;
|
||||
cssHeight = nextCssHeight;
|
||||
dpr = nextDpr;
|
||||
canvas.width = Math.max(1, Math.round(cssWidth * dpr));
|
||||
canvas.height = Math.max(1, Math.round(cssHeight * dpr));
|
||||
freeTarget(sceneTarget);
|
||||
freeTarget(bloomA);
|
||||
freeTarget(bloomB);
|
||||
sceneTarget = makeTarget(Math.max(1, Math.round(canvas.width * scale)), Math.max(1, Math.round(canvas.height * scale)));
|
||||
const bloomWidth = Math.max(1, Math.round(sceneTarget.width / 4));
|
||||
const bloomHeight = Math.max(1, Math.round(sceneTarget.height / 4));
|
||||
bloomA = makeTarget(bloomWidth, bloomHeight);
|
||||
bloomB = makeTarget(bloomWidth, bloomHeight);
|
||||
},
|
||||
render(time, params) {
|
||||
if (!sceneTarget || !bloomA || !bloomB) return;
|
||||
const pxPerM = params.pxPerM * dpr;
|
||||
const centerX = params.centerX * canvas.width;
|
||||
const centerY = (1 - params.centerY) * canvas.height;
|
||||
const scale = sceneTarget.width / canvas.width;
|
||||
|
||||
gl.useProgram(scene.handle);
|
||||
gl.activeTexture(gl.TEXTURE2);
|
||||
gl.bindTexture(gl.TEXTURE_CUBE_MAP, skyMap);
|
||||
gl.uniform1i(scene.uniform("uSkyMap"), 2);
|
||||
gl.uniform1f(scene.uniform("uSky"), params.sky);
|
||||
gl.uniform1f(scene.uniform("uStyleFrom"), params.styleFrom);
|
||||
gl.uniform1f(scene.uniform("uStyleTo"), params.styleTo);
|
||||
gl.uniform1f(scene.uniform("uWaveRadius"), params.waveRadius);
|
||||
gl.uniform1f(scene.uniform("uWaveFeather"), params.waveFeather);
|
||||
gl.uniform1i(scene.uniform("uKind"), params.styleKind);
|
||||
gl.uniform1f(scene.uniform("uSweep"), params.sweep);
|
||||
gl.uniform1f(scene.uniform("uSweepAmount"), params.sweepAmount);
|
||||
gl.uniform1f(scene.uniform("uStepScale"), params.stepScale);
|
||||
gl.uniform2f(scene.uniform("uCenter"), centerX * scale, centerY * scale);
|
||||
gl.uniform1f(scene.uniform("uPxPerM"), pxPerM * scale);
|
||||
gl.uniform1f(scene.uniform("uElevation"), params.elevation);
|
||||
gl.uniform1f(scene.uniform("uTime"), time);
|
||||
gl.uniform1f(scene.uniform("uSway"), params.sway);
|
||||
gl.uniform1f(scene.uniform("uDiskIn"), params.diskIn);
|
||||
gl.uniform1f(scene.uniform("uDiskOut"), params.diskOut);
|
||||
gl.uniform1f(scene.uniform("uDiskGain"), params.diskGain);
|
||||
gl.uniform1f(scene.uniform("uDoppler"), params.doppler);
|
||||
gl.uniform1f(scene.uniform("uAbsorb"), params.absorb);
|
||||
gl.uniform1i(scene.uniform("uSteps"), Math.round(params.steps));
|
||||
gl.uniform1f(scene.uniform("uRimCut"), params.rimCut);
|
||||
gl.uniform1i(scene.uniform("uMaxCrossings"), Math.round(params.maxCrossings));
|
||||
draw(sceneTarget, sceneTarget.width, sceneTarget.height);
|
||||
|
||||
const bloomOn = params.bloomPasses > 0 && params.bloom > 0;
|
||||
gl.useProgram(blur.handle);
|
||||
gl.uniform1i(blur.uniform("uSource"), 0);
|
||||
const pass = (source: Target, destination: Target, horizontal: boolean, threshold: number, stride: number) => {
|
||||
bind(0, source);
|
||||
gl.uniform2f(blur.uniform("uStep"), horizontal ? stride / source.width : 0, horizontal ? 0 : stride / source.height);
|
||||
gl.uniform1f(blur.uniform("uThreshold"), threshold);
|
||||
draw(destination, destination.width, destination.height);
|
||||
};
|
||||
if (bloomOn) {
|
||||
pass(sceneTarget, bloomA, true, 0.45, 2.2);
|
||||
pass(bloomA, bloomB, false, 0, 1.4);
|
||||
if (params.bloomPasses >= 4) {
|
||||
pass(bloomB, bloomA, true, 0, 2.4);
|
||||
pass(bloomA, bloomB, false, 0, 2.4);
|
||||
}
|
||||
}
|
||||
|
||||
gl.useProgram(composite.handle);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
bind(0, sceneTarget);
|
||||
bind(1, bloomB);
|
||||
gl.uniform1i(composite.uniform("uScene"), 0);
|
||||
gl.uniform1i(composite.uniform("uBloom"), 1);
|
||||
gl.uniform1f(composite.uniform("uBloomAmount"), bloomOn ? params.bloom : 0);
|
||||
gl.uniform1f(composite.uniform("uStyleFrom"), params.styleFrom);
|
||||
gl.uniform1f(composite.uniform("uStyleTo"), params.styleTo);
|
||||
gl.uniform1f(composite.uniform("uWaveRadius"), params.waveRadius);
|
||||
gl.uniform1f(composite.uniform("uWaveFeather"), params.waveFeather);
|
||||
gl.uniform1f(composite.uniform("uWaveFront"), params.waveFront);
|
||||
gl.uniform1i(composite.uniform("uKind"), params.styleKind);
|
||||
gl.uniform1f(composite.uniform("uSweep"), params.sweep);
|
||||
gl.uniform1f(composite.uniform("uSweepAmount"), params.sweepAmount);
|
||||
gl.uniform1f(composite.uniform("uPxPerM"), pxPerM);
|
||||
gl.uniform1f(composite.uniform("uExposure"), params.exposure);
|
||||
gl.uniform2f(composite.uniform("uCanvas"), canvas.width, canvas.height);
|
||||
gl.uniform2f(composite.uniform("uCenter"), centerX, centerY);
|
||||
gl.uniform1f(composite.uniform("uShadowRadius"), CRITICAL_IMPACT * pxPerM);
|
||||
gl.uniform1f(composite.uniform("uShowShadow"), params.showShadow ? 1 : 0);
|
||||
draw(undefined, canvas.width, canvas.height);
|
||||
},
|
||||
finish() {
|
||||
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
|
||||
},
|
||||
dispose() {
|
||||
freeTarget(sceneTarget);
|
||||
freeTarget(bloomA);
|
||||
freeTarget(bloomB);
|
||||
gl.deleteTexture(skyMap);
|
||||
gl.deleteProgram(skyBake.handle);
|
||||
gl.deleteProgram(scene.handle);
|
||||
gl.deleteProgram(blur.handle);
|
||||
gl.deleteProgram(composite.handle);
|
||||
gl.deleteBuffer(quad);
|
||||
},
|
||||
};
|
||||
}
|
||||
536
web/src/lib/blackhole/shaders.ts
Normal file
536
web/src/lib/blackhole/shaders.ts
Normal file
@@ -0,0 +1,536 @@
|
||||
import { GLSL_CONSTANTS } from "./geodesic";
|
||||
|
||||
export const vertexShader = `#version 300 es
|
||||
in vec2 aPosition;
|
||||
out vec2 vUv;
|
||||
void main() {
|
||||
vUv = aPosition * 0.5 + 0.5;
|
||||
gl_Position = vec4(aPosition, 0.0, 1.0);
|
||||
}`;
|
||||
|
||||
const noiseLibrary = `
|
||||
float hash31(vec3 p) {
|
||||
p = fract(p * vec3(.1031, .1030, .0973));
|
||||
p += dot(p, p.yxz + 33.33);
|
||||
return fract((p.x + p.y) * p.z);
|
||||
}
|
||||
vec3 hash33(vec3 p) {
|
||||
p = fract(p * vec3(.1031, .1030, .0973));
|
||||
p += dot(p, p.yxz + 33.33);
|
||||
return fract((p.xxy + p.yxx) * p.zyx);
|
||||
}
|
||||
float vnoise(vec3 p) {
|
||||
vec3 i = floor(p), f = fract(p);
|
||||
f = f * f * (3.0 - 2.0 * f);
|
||||
float a = hash31(i), b = hash31(i + vec3(1, 0, 0)), c = hash31(i + vec3(0, 1, 0)), d = hash31(i + vec3(1, 1, 0));
|
||||
float e = hash31(i + vec3(0, 0, 1)), g = hash31(i + vec3(1, 0, 1)), h = hash31(i + vec3(0, 1, 1)), k = hash31(i + vec3(1, 1, 1));
|
||||
return mix(mix(mix(a, b, f.x), mix(c, d, f.x), f.y), mix(mix(e, g, f.x), mix(h, k, f.x), f.y), f.z);
|
||||
}
|
||||
float fbm(vec3 p) {
|
||||
float s = 0.0, a = 0.5;
|
||||
for (int i = 0; i < 4; i++) { s += a * vnoise(p); p = p * 2.03 + 11.7; a *= 0.5; }
|
||||
return s;
|
||||
}
|
||||
|
||||
`;
|
||||
|
||||
const skyLibrary = `
|
||||
float fbm3(vec3 p) {
|
||||
float s = 0.0, a = 0.5;
|
||||
for (int i = 0; i < 3; i++) { s += a * vnoise(p); p = p * 2.07 + 5.3; a *= 0.5; }
|
||||
return s;
|
||||
}
|
||||
|
||||
const float POINT_CAP = 0.42;
|
||||
|
||||
vec3 starLayer(vec3 d, float scale, float density, float footprint, float halo) {
|
||||
vec3 p = d * scale;
|
||||
vec3 cell = floor(p);
|
||||
float pick = hash31(cell);
|
||||
if (pick > density) return vec3(0.0);
|
||||
vec3 offset = hash33(cell + 7.1) * 0.6 + 0.2;
|
||||
float dist = length(fract(p) - offset);
|
||||
float size = 0.022 + 0.04 * hash31(cell + 3.3);
|
||||
float blur = min(max(size, footprint * scale), 0.15);
|
||||
float energy = min(1.0, (size * size) / (blur * blur));
|
||||
float glow = exp(-(dist * dist) / (blur * blur)) * energy;
|
||||
vec3 inCell = fract(p);
|
||||
float border = min(min(min(inCell.x, 1.0 - inCell.x), min(inCell.y, 1.0 - inCell.y)), min(inCell.z, 1.0 - inCell.z));
|
||||
float wide = halo * exp(-(dist * dist) / (blur * blur * 7.0)) * energy * smoothstep(0.0, 0.2, border);
|
||||
float tone = hash31(cell + 5.7);
|
||||
vec3 tint = mix(vec3(1.0, 0.78, 0.52), vec3(0.80, 0.86, 1.0), tone * tone * 0.7);
|
||||
return tint * (glow + wide) * (0.3 + 0.9 * hash31(cell + 9.2));
|
||||
}
|
||||
|
||||
// Distant galaxies: tilted elliptical smudges with a bright nucleus, one per rare cell.
|
||||
vec3 galaxyLayer(vec3 d, float scale, float density, float footprint) {
|
||||
vec3 p = d * scale;
|
||||
vec3 cell = floor(p);
|
||||
if (hash31(cell + 21.3) > density) return vec3(0.0);
|
||||
vec3 centre = hash33(cell + 2.2) * 0.3 + 0.35;
|
||||
vec3 diff = fract(p) - centre;
|
||||
diff -= d * dot(diff, d);
|
||||
vec3 t1 = normalize(cross(d, vec3(0.0, 1.0, 0.013)));
|
||||
vec3 t2 = cross(d, t1);
|
||||
vec3 seed = hash33(cell + 8.8);
|
||||
float angle = seed.x * 3.14159;
|
||||
vec2 uv = vec2(dot(diff, t1), dot(diff, t2));
|
||||
uv = vec2(cos(angle) * uv.x + sin(angle) * uv.y, -sin(angle) * uv.x + cos(angle) * uv.y);
|
||||
float major = 0.06 + 0.05 * seed.y;
|
||||
float minor = major * (0.25 + 0.5 * seed.z);
|
||||
float fp = footprint * scale;
|
||||
float vx = major * major + fp * fp;
|
||||
float vy = minor * minor + fp * fp;
|
||||
float energy = (major * minor) / sqrt(vx * vy);
|
||||
float r2 = uv.x * uv.x / vx + uv.y * uv.y / vy;
|
||||
float body = exp(-r2 * 1.6) * 0.8 + exp(-r2 * 9.0) * 1.3;
|
||||
vec3 tint = mix(vec3(1.0, 0.78, 0.55), vec3(0.72, 0.8, 1.0), hash31(cell + 6.6));
|
||||
vec3 inCell = fract(p);
|
||||
float border = min(min(min(inCell.x, 1.0 - inCell.x), min(inCell.y, 1.0 - inCell.y)), min(inCell.z, 1.0 - inCell.z));
|
||||
return tint * body * energy * 0.9 * smoothstep(0.0, 0.22, border);
|
||||
}
|
||||
|
||||
vec3 skyColor(vec3 d, float elevation, float footprint) {
|
||||
// The galactic plane passes through the reference line of sight; the bulge sits to one side of the hole.
|
||||
vec3 view = vec3(0.0, -sin(elevation), -cos(elevation));
|
||||
vec3 plane = normalize(vec3(0.42, cos(elevation), -sin(elevation)));
|
||||
vec3 along = cross(plane, view);
|
||||
vec3 coreDir = view * cos(0.5) + along * sin(0.5);
|
||||
vec3 coreSide = cross(plane, coreDir);
|
||||
float lat = dot(d, plane);
|
||||
float lon = atan(dot(d, coreSide), dot(d, coreDir));
|
||||
|
||||
// The plane fades with longitude, so the sky behind the camera (which the hole bends into its ring) stays dark.
|
||||
float envelope = exp(-lon * lon / 1.2);
|
||||
float disk = exp(-lat * lat / 0.010) * envelope;
|
||||
float haze = exp(-lat * lat / 0.16) * envelope;
|
||||
float bulge = exp(-lon * lon / 0.075 - lat * lat / 0.020);
|
||||
float arm = 0.45 + 0.75 * exp(-lon * lon / 0.9);
|
||||
|
||||
vec3 color = vec3(0.0);
|
||||
float stellarMask = disk + haze * 0.3 + bulge;
|
||||
if (stellarMask > 0.01) {
|
||||
float grain = 0.45 + 1.1 * fbm3(d * 11.0 + 2.0);
|
||||
vec3 lane = vec3(cos(lon) * 5.5, sin(lon) * 5.5, lat * 21.0);
|
||||
float dustLane = smoothstep(0.44, 0.7, fbm3(lane + 4.1)) * exp(-lat * lat / 0.022);
|
||||
float absorb = 1.0 - 0.82 * dustLane;
|
||||
vec3 cool = vec3(0.42, 0.40, 0.60);
|
||||
vec3 warm = vec3(1.0, 0.68, 0.40);
|
||||
vec3 diffuse = mix(cool, warm, clamp(0.5 + bulge * 1.0 + exp(-lon * lon / 0.5) * 0.2, 0.0, 1.0));
|
||||
color += diffuse * (disk * arm * 0.26 + haze * 0.04 + bulge * 0.8) * grain * absorb * 0.30;
|
||||
}
|
||||
|
||||
vec3 nebulaA = normalize(view - along * 0.6 + plane * 0.20);
|
||||
vec3 nebulaB = normalize(view + along * 0.95 - plane * 0.24);
|
||||
float na = exp(-(1.0 - dot(d, nebulaA)) * 34.0);
|
||||
float nb = exp(-(1.0 - dot(d, nebulaB)) * 46.0);
|
||||
if (na + nb > 0.01) {
|
||||
float filament = 1.0 - abs(2.0 * fbm3(d * 8.0 + 9.0) - 1.0);
|
||||
float body = 0.35 + 0.9 * fbm3(d * 5.0 + 1.0);
|
||||
color += vec3(0.90, 0.40, 0.18) * na * body * (0.10 + 1.7 * filament * filament) * 0.10;
|
||||
color += vec3(0.52, 0.55, 0.92) * nb * body * (0.08 + 1.6 * filament * filament) * 0.085;
|
||||
}
|
||||
|
||||
float boost = 1.0 + 2.6 * disk + 2.0 * bulge;
|
||||
// Point sources must never rival an orbit marker on top of them: few bright ones, small, and a hard brightness cap.
|
||||
vec3 points = starLayer(d, 42.0, 0.09 * boost, footprint, 0.0) * 0.5;
|
||||
points += starLayer(d, 95.0, 0.12 * boost, footprint, 0.0) * 0.65;
|
||||
points += starLayer(d, 210.0, 0.17 * boost, footprint, 0.0) * 0.85;
|
||||
points += starLayer(d, 17.0, 0.012 * boost, footprint, 0.08) * 0.6;
|
||||
points += galaxyLayer(d, 22.0, 0.012, footprint) * 0.14;
|
||||
float peak = max(points.r, max(points.g, points.b));
|
||||
points *= min(1.0, POINT_CAP / max(peak, 1e-4));
|
||||
return color + points;
|
||||
}
|
||||
|
||||
`;
|
||||
|
||||
export const skyBakeShader = `#version 300 es
|
||||
precision highp float;
|
||||
uniform int uFace;
|
||||
uniform float uSkyElevation;
|
||||
in vec2 vUv;
|
||||
out vec4 outColor;
|
||||
${noiseLibrary}
|
||||
${skyLibrary}
|
||||
void main() {
|
||||
vec2 q = vUv * 2.0 - 1.0;
|
||||
vec3 d;
|
||||
if (uFace == 0) d = vec3(1.0, -q.y, -q.x);
|
||||
else if (uFace == 1) d = vec3(-1.0, -q.y, q.x);
|
||||
else if (uFace == 2) d = vec3(q.x, 1.0, q.y);
|
||||
else if (uFace == 3) d = vec3(q.x, -1.0, -q.y);
|
||||
else if (uFace == 4) d = vec3(q.x, -q.y, 1.0);
|
||||
else d = vec3(-q.x, -q.y, -1.0);
|
||||
d = normalize(d);
|
||||
float footprint = max(fwidth(d.x), max(fwidth(d.y), fwidth(d.z)));
|
||||
vec3 c = skyColor(d, uSkyElevation, footprint);
|
||||
// Compress to 8 bits: c/(1+c), then gamma, so the dark gradients keep their precision.
|
||||
vec3 x = c / (1.0 + c);
|
||||
float noise = fract(sin(dot(gl_FragCoord.xy + vec2(float(uFace) * 17.0), vec2(12.9898, 78.233))) * 43758.5453);
|
||||
outColor = vec4(pow(x, vec3(1.0 / 2.2)) + (noise - 0.5) / 255.0, 1.0);
|
||||
}`;
|
||||
|
||||
export const sceneShader = `#version 300 es
|
||||
precision highp float;
|
||||
${GLSL_CONSTANTS}
|
||||
uniform samplerCube uSkyMap;
|
||||
uniform vec2 uCenter; // hole centre in target pixels, y up
|
||||
uniform float uPxPerM; // target pixels per gravitational radius
|
||||
uniform float uElevation; // camera elevation above the disk plane, radians
|
||||
uniform float uTime; // disk clock, seconds
|
||||
uniform float uSway; // sky yaw, radians
|
||||
uniform float uSky; // sky brightness
|
||||
uniform float uStyleFrom; // look outside the wave: 0 realistic, 1 stylized
|
||||
uniform float uStyleTo; // look inside the wave
|
||||
uniform float uWaveRadius; // wave front, in gravitational radii from the hole
|
||||
uniform float uWaveFeather;
|
||||
uniform int uKind; // stylized look: 1 schematic, 2 toon
|
||||
uniform float uSweep; // radar sweep angle, radians
|
||||
uniform float uSweepAmount;// 0 evenly lit .. 1 full phosphor persistence
|
||||
uniform float uStepScale;
|
||||
uniform float uDiskIn;
|
||||
uniform float uDiskOut;
|
||||
uniform float uDiskGain;
|
||||
uniform float uDoppler;
|
||||
uniform float uAbsorb;
|
||||
uniform int uSteps;
|
||||
uniform float uRimCut; // disk light from rays that skimmed closer than this to the hole is faded out
|
||||
uniform int uMaxCrossings; // disk images beyond this many plane crossings are the hairline rings hugging the shadow
|
||||
const float SKY_SCALE = 38.0;
|
||||
out vec4 outColor;
|
||||
|
||||
${noiseLibrary}
|
||||
// Disk colour ramp: ember red -> orange -> yellow -> pale cream, with a faint cool core at the very top.
|
||||
vec3 heat(float t) {
|
||||
vec3 c = mix(vec3(0.0), vec3(0.30, 0.035, 0.012), smoothstep(0.0, 0.16, t));
|
||||
c = mix(c, vec3(0.80, 0.15, 0.03), smoothstep(0.12, 0.38, t));
|
||||
c = mix(c, vec3(1.0, 0.42, 0.07), smoothstep(0.30, 0.62, t));
|
||||
c = mix(c, vec3(1.0, 0.72, 0.24), smoothstep(0.55, 0.90, t));
|
||||
c = mix(c, vec3(1.0, 0.92, 0.66), smoothstep(0.85, 1.30, t));
|
||||
c = mix(c, vec3(0.90, 0.95, 1.0), smoothstep(1.6, 2.6, t));
|
||||
return c;
|
||||
}
|
||||
|
||||
float gGlow = 1.0; // radar phosphor persistence at this pixel, set once per pixel in main
|
||||
float gStyle = 0.0; // 0 realistic .. 1 stylized at this pixel, set once per pixel in main
|
||||
|
||||
// The stylized look spreads outward from the hole as a wave: pixels the front has passed show the new look.
|
||||
float styleAt(float radius) {
|
||||
float inside = 1.0 - smoothstep(uWaveRadius - uWaveFeather, uWaveRadius, radius);
|
||||
return mix(uStyleFrom, uStyleTo, inside);
|
||||
}
|
||||
|
||||
vec3 rotateSky(vec3 d) {
|
||||
float cy = cos(uSway), sy = sin(uSway);
|
||||
return vec3(cy * d.x + sy * d.z, d.y, -sy * d.x + cy * d.z);
|
||||
}
|
||||
|
||||
vec3 skyTexel(vec3 d, float bias) {
|
||||
vec3 x = pow(texture(uSkyMap, d, bias).rgb, vec3(2.2));
|
||||
return x / max(vec3(1.0) - x, vec3(0.001));
|
||||
}
|
||||
|
||||
// Distance in pixels to the nearest integer of c, as an anti-aliased line of the given half-width.
|
||||
float lineAA(float c, float halfWidth) {
|
||||
float w = min(fwidth(c), 0.5);
|
||||
float a = abs(fract(c - 0.5) - 0.5) / max(w, 1e-4);
|
||||
return 1.0 - smoothstep(halfWidth, halfWidth + 1.0, a);
|
||||
}
|
||||
|
||||
// Schematic sky: the celestial coordinate grid, bent by the same rays that bend the light.
|
||||
vec3 schematicSky(vec3 d, vec3 right, vec3 up, vec3 camera, float impact) {
|
||||
vec3 q = vec3(dot(d, right), dot(d, up), dot(d, -camera));
|
||||
float lat = asin(clamp(q.y, -1.0, 1.0));
|
||||
float lon = atan(q.x, q.z);
|
||||
float step10 = 0.17453293;
|
||||
float minor = max(lineAA(lat / step10, 0.5), lineAA(lon / step10, 0.5));
|
||||
float major = max(lineAA(lat / (3.0 * step10), 0.8), lineAA(lon / (3.0 * step10), 0.8));
|
||||
// Close to the hole the grid wraps many times and buries the disk, so it fades out entirely there.
|
||||
float calm = smoothstep(20.0, 34.0, impact);
|
||||
vec3 faint = vec3(0.008, 0.024, 0.020);
|
||||
vec3 bright = vec3(0.022, 0.060, 0.048);
|
||||
return (faint * minor + bright * major) * calm * gGlow;
|
||||
}
|
||||
|
||||
// Toon sky: chunky star dots and two styled tones for the galactic band.
|
||||
vec3 toonSky(vec3 d) {
|
||||
vec3 soft = skyTexel(d, 5.0);
|
||||
float glow = dot(soft, vec3(0.3, 0.5, 0.2));
|
||||
float tone = floor(clamp(glow * 20.0, 0.0, 2.99));
|
||||
vec3 styled = tone < 0.5 ? vec3(0.0) : tone < 1.5 ? vec3(0.055, 0.05, 0.085) : vec3(0.16, 0.10, 0.085);
|
||||
vec3 spark = skyTexel(d, 2.0);
|
||||
float local = dot(spark - soft, vec3(0.3, 0.5, 0.2));
|
||||
float w = max(fwidth(local), 0.015);
|
||||
float star = smoothstep(0.09 - w, 0.09 + w, local);
|
||||
return styled + vec3(0.95, 0.86, 0.72) * star * 0.9;
|
||||
}
|
||||
|
||||
float diskMask(float r) {
|
||||
return smoothstep(uDiskIn, uDiskIn + 0.3, r) * (1.0 - smoothstep(uDiskOut - 0.3, uDiskOut, r));
|
||||
}
|
||||
|
||||
// Fractal noise that drops the octaves too fine for the pixels to resolve. Unresolved detail collapses to the
|
||||
// noise's mean, so it melts into a smooth glow instead of aliasing into moire. The footprint is the size of a pixel
|
||||
// on the disk, in gravitational radii; radialFreq is the first octave's frequency across the flow, in cycles/M.
|
||||
float fbmLod(vec3 p, float radialFreq, float footprint) {
|
||||
float sum = 0.0, amp = 0.5, freq = radialFreq;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float resolved = smoothstep(2.5, 6.0, 1.0 / (footprint * freq));
|
||||
sum += amp * mix(0.5, vnoise(p), resolved);
|
||||
p = p * 2.03 + 11.7;
|
||||
amp *= 0.5;
|
||||
freq *= 2.03;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
vec3 diskLight(vec3 hit, vec3 dir) {
|
||||
float r = length(hit);
|
||||
vec3 toward = -normalize(dir);
|
||||
vec3 spin = vec3(hit.z, 0.0, -hit.x) / r;
|
||||
float beta = inversesqrt(r - 2.0);
|
||||
float g = sqrt(max(1.0 - 3.0 / r, 0.0)) / (1.0 - beta * dot(spin, toward));
|
||||
g = mix(1.0, g, uDoppler);
|
||||
|
||||
float inner = uDiskIn / r;
|
||||
float temperature = pow(inner, 0.75) * (0.55 + 0.45 * smoothstep(0.0, 0.5, 1.0 - inner));
|
||||
float observed = temperature * g;
|
||||
|
||||
vec3 real = vec3(0.0);
|
||||
if (gStyle < 1.0) {
|
||||
float edge = smoothstep(uDiskIn, uDiskIn + 0.5, r) * (1.0 - smoothstep(uDiskOut * 0.45, uDiskOut, r));
|
||||
// Differential rotation: the inner gas laps the outer gas, so the clouds shear as they flow.
|
||||
float angle = atan(hit.z, hit.x) + uTime * 1.1 * pow(6.0 / r, 1.2);
|
||||
// How big a pixel is on the disk. Light bent a long way round the hole is squeezed onto fewer pixels.
|
||||
float bend = acos(clamp(dot(normalize(dir), -vec3(0.0, sin(uElevation), cos(uElevation))), -1.0, 1.0));
|
||||
float footprint = (1.0 / uPxPerM) * (1.0 + 2.5 * smoothstep(0.25, 1.1, bend));
|
||||
// Soft clouds of light stretched along the flow, not neat grooves.
|
||||
vec3 q = vec3(cos(angle), sin(angle), 0.0) * vec3(2.3, 2.3, 1.0) + vec3(0.0, 0.0, r * 2.4);
|
||||
vec3 hair = vec3(cos(angle * 1.7), sin(angle * 1.7), 0.0) * vec3(4.6, 4.6, 1.0) + vec3(0.0, 0.0, r * 6.0);
|
||||
float filaments = fbmLod(q, 2.4, footprint) * 0.8 + fbmLod(hair + 7.0, 6.0, footprint) * 0.3;
|
||||
float turbulence = 0.3 + 1.1 * smoothstep(0.1, 0.95, filaments) + 0.4 * fbmLod(q * 0.45 + 3.0, 1.1, footprint);
|
||||
float ringBands = 1.0;
|
||||
float lum = pow(max(observed, 0.0), 2.7) * uDiskGain * turbulence * ringBands * edge;
|
||||
real = heat(observed * 0.72) * lum * (1.0 + 1.7 * uAbsorb);
|
||||
}
|
||||
|
||||
vec3 styled = vec3(0.0);
|
||||
if (gStyle > 0.0) {
|
||||
// Contour bands of the same observed brightness: the Doppler asymmetry shows as uneven band widths.
|
||||
float levels = uKind == 1 ? 5.0 : 4.0;
|
||||
// Radar bands are equal steps in log brightness, so the long dim outer disk still shows contours.
|
||||
float x = uKind == 1
|
||||
? clamp((log(max(observed, 0.02)) + 1.9) / 2.4, 0.0, 0.999)
|
||||
: clamp((observed - 0.38) / 0.85, 0.0, 0.999);
|
||||
float tone = (floor(x * levels) + 0.5) / levels;
|
||||
float edgeDistance = abs(fract(x * levels + 0.5) - 0.5);
|
||||
float seam = 1.0 - smoothstep(uKind == 1 ? 0.012 : 0.03, uKind == 1 ? 0.05 : 0.09, edgeDistance);
|
||||
// The long dim outer disk stays faint; only the bright inner contours carry weight.
|
||||
vec3 fill = heat(0.1 + tone * 0.95) * (0.03 + 0.55 * tone * tone * tone);
|
||||
if (uKind == 2) {
|
||||
float band = floor(x * levels);
|
||||
fill = band < 0.5 ? vec3(0.27, 0.075, 0.04) : band < 1.5 ? vec3(0.60, 0.22, 0.09) : band < 2.5 ? vec3(0.92, 0.52, 0.21) : vec3(1.0, 0.82, 0.55);
|
||||
}
|
||||
vec3 ink = uKind == 1 ? vec3(0.02, 0.03, 0.05) : vec3(0.035, 0.02, 0.025);
|
||||
styled = mix(fill, ink, seam * (uKind == 1 ? 0.3 : 0.9)) * diskMask(r) * (uKind == 1 ? gGlow : 1.0);
|
||||
}
|
||||
return mix(real, styled, gStyle);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 p = (gl_FragCoord.xy - uCenter) / uPxPerM;
|
||||
vec3 camera = vec3(0.0, sin(uElevation), cos(uElevation));
|
||||
vec3 right = vec3(1.0, 0.0, 0.0);
|
||||
vec3 up = vec3(0.0, cos(uElevation), -sin(uElevation));
|
||||
|
||||
vec3 pos = camera * START_RADIUS + right * p.x + up * p.y;
|
||||
vec3 vel = -camera;
|
||||
vec3 h = cross(pos, vel);
|
||||
float h2 = dot(h, h);
|
||||
|
||||
// Radar persistence: a pixel is brightest just after the sweep passes and fades as it comes round again.
|
||||
float sweepAge = mod(uSweep - atan(p.y, p.x), 6.2831853);
|
||||
gGlow = mix(1.0, 0.45 + 0.55 * exp(-sweepAge * 0.9), uSweepAmount);
|
||||
|
||||
vec3 color = vec3(0.0);
|
||||
float transmittance = 1.0;
|
||||
bool captured = false;
|
||||
bool escaped = false;
|
||||
int crossings = 0;
|
||||
float closest = 1e9;
|
||||
|
||||
// Far from the hole a ray neither reaches the disk nor bends much: use the weak-field deflection there and
|
||||
// cross-fade into the traced result so no seam shows.
|
||||
float b = length(p);
|
||||
gStyle = styleAt(b);
|
||||
float far = smoothstep(uDiskOut + 3.0, uDiskOut + 7.0, b);
|
||||
vec3 weakField = normalize(-camera - (right * p.x + up * p.y) / max(b, 0.001) * (4.0 / max(b, 1.0) + 11.8 / max(b * b, 1.0)));
|
||||
int limit = far >= 1.0 ? 0 : uSteps;
|
||||
if (far >= 1.0) { escaped = true; vel = weakField; }
|
||||
|
||||
for (int i = 0; i < MAX_STEPS; i++) {
|
||||
if (i >= limit) break;
|
||||
float r = length(pos);
|
||||
closest = min(closest, r);
|
||||
if (r < HORIZON) { captured = true; break; }
|
||||
if (r > ESCAPE_RADIUS && dot(pos, vel) > 0.0) { escaped = true; break; }
|
||||
|
||||
float dt = min(MAX_DT, uStepScale * r);
|
||||
float r2 = r * r;
|
||||
vel += (-3.0 * h2 / (r2 * r2 * r)) * pos * dt;
|
||||
vec3 next = pos + vel * dt;
|
||||
|
||||
if (pos.y * next.y < 0.0) {
|
||||
float t = pos.y / (pos.y - next.y);
|
||||
vec3 hit = mix(pos, next, t);
|
||||
float hr = length(hit);
|
||||
if (hr > uDiskIn && hr < uDiskOut && crossings < uMaxCrossings) {
|
||||
crossings++;
|
||||
// In the radar view, light that has been bent a long way round the hole is drawn quietly, so the unbent disk
|
||||
// stays the subject and the shadow does not sit inside a glowing hoop.
|
||||
float bend = acos(clamp(dot(normalize(vel), -camera), -1.0, 1.0));
|
||||
float echo = uKind == 1 ? mix(1.0, mix(1.0, 0.14, smoothstep(0.18, 0.85, bend)), gStyle) : 1.0;
|
||||
// Rays that skim the photon sphere crowd a hair-thin band of pixels against the shadow edge: they paint a
|
||||
// one-pixel ring, so their disk light is faded out.
|
||||
float rim = smoothstep(uRimCut - 0.9, uRimCut, closest);
|
||||
color += transmittance * diskLight(hit, vel) * echo * rim;
|
||||
// The real disk is optically thick, so the near side hides what lies behind it; the radar look keeps it see-through.
|
||||
// Outer gas is thin, so opacity falls away with radius: the glowing inner disk hides what is behind it, the rim does not.
|
||||
float thickness = 1.0 - smoothstep(uDiskOut * 0.28, uDiskOut * 0.85, hr);
|
||||
transmittance *= 1.0 - mix(0.92 * thickness, 0.18, gStyle) * diskMask(hr);
|
||||
}
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
|
||||
// A ray that ran out of steps while already heading outward has nearly finished bending: let it see the sky.
|
||||
if (!captured && !escaped && dot(pos, vel) > 0.0) escaped = true;
|
||||
|
||||
if (escaped) {
|
||||
// Rays are parallel, so add the perspective offset of this pixel to the lensed exit direction. The sky then
|
||||
// spans a wide field of view and bends exactly as much as the ray did.
|
||||
vec3 lensed = normalize(mix(normalize(vel), weakField, far));
|
||||
vec3 sky = rotateSky(normalize(lensed + (right * p.x + up * p.y) / SKY_SCALE));
|
||||
vec3 real = gStyle < 1.0 ? skyTexel(sky, 0.0) * uSky : vec3(0.0);
|
||||
vec3 styled = vec3(0.0);
|
||||
if (gStyle > 0.0) styled = uKind == 1 ? schematicSky(sky, right, up, camera, b) : toonSky(sky);
|
||||
color += transmittance * mix(real, styled, gStyle);
|
||||
}
|
||||
|
||||
// Outline where the disk's silhouette meets what is behind it.
|
||||
if (gStyle > 0.0) {
|
||||
float outline = smoothstep(0.010, 0.026, fwidth(1.0 - transmittance));
|
||||
vec3 ink = uKind == 1 ? vec3(0.95, 0.66, 0.40) : vec3(0.03, 0.02, 0.03);
|
||||
float strength = uKind == 1 ? 0.3 : 1.0;
|
||||
color = mix(color, ink, outline * strength * gStyle * (uKind == 1 ? gGlow : 1.0));
|
||||
}
|
||||
|
||||
outColor = vec4(color, 1.0);
|
||||
}`;
|
||||
|
||||
export const blurShader = `#version 300 es
|
||||
precision highp float;
|
||||
uniform sampler2D uSource;
|
||||
uniform vec2 uStep; // source texel step along the blur direction
|
||||
uniform float uThreshold;
|
||||
in vec2 vUv;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
float weights[5] = float[5](0.2270270, 0.1945946, 0.1216216, 0.0540541, 0.0162162);
|
||||
vec3 sum = vec3(0.0);
|
||||
for (int i = -4; i <= 4; i++) {
|
||||
vec3 c = texture(uSource, vUv + uStep * float(i)).rgb;
|
||||
sum += max(c - uThreshold, 0.0) * weights[abs(i)];
|
||||
}
|
||||
outColor = vec4(sum, 1.0);
|
||||
}`;
|
||||
|
||||
export const compositeShader = `#version 300 es
|
||||
precision highp float;
|
||||
uniform sampler2D uScene;
|
||||
uniform sampler2D uBloom;
|
||||
uniform float uBloomAmount;
|
||||
uniform float uExposure;
|
||||
uniform vec2 uCanvas;
|
||||
uniform vec2 uCenter; // canvas pixels, y up
|
||||
uniform float uShadowRadius;
|
||||
uniform float uShowShadow;
|
||||
uniform float uStyleFrom;
|
||||
uniform float uStyleTo;
|
||||
uniform float uWaveRadius;
|
||||
uniform float uWaveFeather;
|
||||
uniform float uWaveFront; // 0 .. 1 brightness of the wave's leading edge
|
||||
uniform int uKind;
|
||||
uniform float uSweep;
|
||||
uniform float uSweepAmount;
|
||||
uniform float uPxPerM; // canvas pixels per gravitational radius
|
||||
in vec2 vUv;
|
||||
out vec4 outColor;
|
||||
|
||||
vec3 aces(vec3 x) {
|
||||
return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
float radiusM = length(gl_FragCoord.xy - uCenter) / uPxPerM;
|
||||
float styleHere = mix(uStyleFrom, uStyleTo, 1.0 - smoothstep(uWaveRadius - uWaveFeather, uWaveRadius, radiusM));
|
||||
vec3 hdr = texture(uScene, vUv).rgb + texture(uBloom, vUv).rgb * uBloomAmount * (1.0 - styleHere);
|
||||
vec3 color = mix(aces(hdr * uExposure), clamp(hdr * uExposure, 0.0, 1.0), styleHere);
|
||||
color = pow(color, vec3(1.0 / 2.2));
|
||||
color = max(color, vec3(0.039, 0.047, 0.063));
|
||||
float noise = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453);
|
||||
color += (noise - 0.5) / 255.0;
|
||||
if (styleHere > 0.0) {
|
||||
// The shadow is a perfect circle of radius 3√3 M, so draw its edge analytically.
|
||||
float width = uKind == 1 ? 0.9 : 2.6;
|
||||
float ring = abs(length(gl_FragCoord.xy - uCenter) - uShadowRadius);
|
||||
float line = 1.0 - smoothstep(width - 0.7, width + 0.7, ring);
|
||||
vec3 ink = uKind == 1 ? vec3(0.95, 0.66, 0.40) : vec3(1.0, 0.80, 0.52);
|
||||
color = mix(color, ink, line * (uKind == 1 ? 0.26 : 1.0) * styleHere);
|
||||
}
|
||||
if (styleHere > 0.0 && uKind == 1) {
|
||||
// Radar reticle: range rings every 6 M, a bearing scale at 30 M, just outside the disk, a crosshair and the sweep head.
|
||||
vec2 q = gl_FragCoord.xy - uCenter;
|
||||
float radiusPx = length(q);
|
||||
float R = radiusM;
|
||||
float bearing = atan(q.y, q.x);
|
||||
vec3 mint = vec3(0.55, 0.80, 0.70);
|
||||
|
||||
float index = R / 6.0;
|
||||
float ringPx = abs(fract(index - 0.5) - 0.5) / max(fwidth(index), 1e-4);
|
||||
float ringLine = 1.0 - smoothstep(0.4, 1.4, ringPx);
|
||||
float major = mod(floor(index + 0.5), 3.0) < 0.5 ? 1.0 : 0.0;
|
||||
float reach = 1.0 - smoothstep(32.0, 46.0, R);
|
||||
float rings = ringLine * (0.07 + 0.09 * major) * reach * step(0.5, index);
|
||||
|
||||
float tickIndex = bearing / 0.0872665;
|
||||
float tickPx = abs(fract(tickIndex - 0.5) - 0.5) * 0.0872665 * radiusPx;
|
||||
float tickLine = 1.0 - smoothstep(0.4, 1.4, tickPx);
|
||||
float longTick = mod(floor(tickIndex + 0.5), 6.0) < 0.5 ? 1.0 : 0.0;
|
||||
float onScale = abs(R - 30.0) < (longTick > 0.5 ? 1.6 : 0.8) ? 1.0 : 0.0;
|
||||
float ticks = tickLine * onScale * 0.34;
|
||||
float scaleRing = (1.0 - smoothstep(0.4, 1.4, abs(R - 30.0) * uPxPerM)) * 0.2;
|
||||
|
||||
float crosshair = (1.0 - smoothstep(0.4, 1.3, min(abs(q.x), abs(q.y)))) * 0.07 * (1.0 - smoothstep(29.0, 31.0, R));
|
||||
|
||||
float age = mod(uSweep - bearing, 6.2831853);
|
||||
float headPx = min(age, 6.2831853 - age) * radiusPx;
|
||||
float head = (1.0 - smoothstep(0.5, 1.8, headPx)) * 0.5 * (1.0 - smoothstep(29.5, 30.5, R));
|
||||
float fan = exp(-age * 2.4) * 0.045 * (1.0 - smoothstep(29.5, 30.5, R));
|
||||
|
||||
float inkAmount = clamp(rings + ticks + scaleRing + crosshair + (head + fan) * uSweepAmount, 0.0, 1.0);
|
||||
color = mix(color, mint, inkAmount * styleHere);
|
||||
}
|
||||
// Leading edge of the wave: mint when the radar look is arriving, amber when the realistic look returns.
|
||||
float span = max(uWaveFeather, 0.001);
|
||||
float edge = exp(-pow((radiusM - uWaveRadius + 0.25 * span) / (span * 0.14), 2.0)) * uWaveFront;
|
||||
float trail = smoothstep(uWaveRadius - span * 3.2, uWaveRadius - 0.2 * span, radiusM) * (1.0 - smoothstep(uWaveRadius - 0.2 * span, uWaveRadius, radiusM)) * uWaveFront;
|
||||
vec3 waveColor = mix(vec3(1.0, 0.72, 0.42), vec3(0.55, 0.80, 0.70), uStyleTo);
|
||||
color = mix(color, waveColor, clamp(edge * 0.8 + trail * 0.12, 0.0, 1.0));
|
||||
if (uShowShadow > 0.5) {
|
||||
float ring = abs(length(gl_FragCoord.xy - uCenter) - uShadowRadius);
|
||||
color = mix(color, vec3(0.2, 1.0, 0.5), (1.0 - smoothstep(0.0, 1.5, ring)) * 0.9);
|
||||
}
|
||||
outColor = vec4(color, 1.0);
|
||||
}`;
|
||||
268
web/src/proto/blackhole-proto.ts
Normal file
268
web/src/proto/blackhole-proto.ts
Normal file
@@ -0,0 +1,268 @@
|
||||
import { createBlackholeRenderer, defaultParams, type BlackholeParams } from "../lib/blackhole/renderer";
|
||||
import { farthestCornerM } from "../lib/blackhole/layout";
|
||||
import { createLook, requestLook, stepLook, styleAt, waveParams } from "../lib/blackhole/look";
|
||||
import { QUALITY_TIERS, chooseTier, initialTier } from "../lib/blackhole/quality";
|
||||
|
||||
const canvas = document.querySelector<HTMLCanvasElement>("#stage")!;
|
||||
const panel = document.querySelector<HTMLDivElement>("#panel")!;
|
||||
const probe = document.createElement("canvas").getContext("webgl2");
|
||||
const probeInfo = probe?.getExtension("WEBGL_debug_renderer_info");
|
||||
const software = /swiftshader|llvmpipe|software/i.test(String(probeInfo ? probe!.getParameter(probeInfo.UNMASKED_RENDERER_WEBGL) : ""));
|
||||
const nav = navigator as Navigator & { deviceMemory?: number };
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
let tier = initialTier({
|
||||
software, cores: navigator.hardwareConcurrency, memoryGb: nav.deviceMemory,
|
||||
pixels: window.innerWidth * window.innerHeight * dpr * dpr,
|
||||
});
|
||||
|
||||
const renderer = createBlackholeRenderer(canvas, { skySize: QUALITY_TIERS[tier].skySize });
|
||||
if (!renderer) {
|
||||
document.querySelector<HTMLElement>("#fail")!.style.display = "grid";
|
||||
throw new Error("WebGL2 unavailable");
|
||||
}
|
||||
|
||||
// ?throttle=N draws the scene N times per frame, standing in for a GPU N times slower.
|
||||
const throttle = Math.max(1, Math.round(Number(new URLSearchParams(location.search).get("throttle")) || 1));
|
||||
if (throttle > 1) {
|
||||
const draw = renderer.render;
|
||||
renderer.render = (time, drawParams) => { for (let i = 0; i < throttle; i++) draw(time, drawParams); };
|
||||
}
|
||||
|
||||
const params: BlackholeParams = { ...defaultParams };
|
||||
const state = { frozenWave: false, scale: 1, speed: 1, paused: false, swayAmount: 1, maxFps: 30, auto: true, tierName: "" };
|
||||
let diskClock = 0;
|
||||
let last = performance.now();
|
||||
let lastRender = 0;
|
||||
let drawMs = 0;
|
||||
let dirty = true;
|
||||
let raf = 0;
|
||||
let sweeping = false;
|
||||
|
||||
const readout = document.createElement("pre");
|
||||
|
||||
// The radar look arrives as a wave spreading outward from the hole (see lib/blackhole/look.ts).
|
||||
const look = createLook(0);
|
||||
let wave = waveParams(look, 0);
|
||||
const modeBar = document.querySelector<HTMLDivElement>("#modes")!;
|
||||
for (const [name, value] of [["realistic", 0], ["radar", 1]] as const) {
|
||||
const element = document.createElement("button");
|
||||
element.textContent = name;
|
||||
element.dataset.mode = name;
|
||||
element.addEventListener("click", () => setMode(value));
|
||||
modeBar.append(element);
|
||||
}
|
||||
function setMode(value: 0 | 1) {
|
||||
requestLook(look, value);
|
||||
for (const element of modeBar.children) element.classList.toggle("on", (element as HTMLElement).dataset.mode === (value ? "radar" : "realistic"));
|
||||
wake();
|
||||
}
|
||||
function applyWave() {
|
||||
const center = { x: params.centerX * window.innerWidth, y: params.centerY * window.innerHeight };
|
||||
const maxRadius = farthestCornerM(center, { width: window.innerWidth, height: window.innerHeight }, params.pxPerM);
|
||||
wave = waveParams(look, maxRadius);
|
||||
Object.assign(params, wave, { styleKind: 1 });
|
||||
}
|
||||
const tagShadow = document.querySelector<HTMLElement>("#tagShadow")!;
|
||||
const tagDisk = document.querySelector<HTMLElement>("#tagDisk")!;
|
||||
const ringTags = [6, 12, 18, 24, 30].map((range) => {
|
||||
const element = document.createElement("div");
|
||||
element.className = "tag mint";
|
||||
element.textContent = `${range} M`;
|
||||
document.body.append(element);
|
||||
return { range, element };
|
||||
});
|
||||
// Labels appear as the wave front passes them, using the same maths as the shader.
|
||||
function placeTags() {
|
||||
const cx = params.centerX * window.innerWidth, cy = params.centerY * window.innerHeight;
|
||||
const at = (radius: number) => styleAt(wave, radius);
|
||||
// A small legend in the corner, revealed as the wave front reaches it.
|
||||
const legend = at(params.diskOut + 2);
|
||||
tagShadow.style.opacity = String(legend);
|
||||
tagShadow.style.left = "24px";
|
||||
tagShadow.style.top = `${window.innerHeight - 54}px`;
|
||||
tagDisk.style.opacity = String(legend);
|
||||
tagDisk.style.left = "24px";
|
||||
tagDisk.style.top = `${window.innerHeight - 34}px`;
|
||||
for (const { range, element } of ringTags) {
|
||||
const angle = (62 * Math.PI) / 180;
|
||||
element.style.opacity = String(at(range) * 0.75);
|
||||
element.style.left = `${cx + range * params.pxPerM * Math.cos(angle) + 4}px`;
|
||||
element.style.top = `${cy - range * params.pxPerM * Math.sin(angle) - 12}px`;
|
||||
}
|
||||
}
|
||||
const sliders: Record<string, HTMLInputElement> = {};
|
||||
|
||||
function wake() {
|
||||
dirty = true;
|
||||
if (!raf) raf = requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
function slider(label: string, get: () => number, set: (value: number) => void, min: number, max: number, step: number, apply?: () => void) {
|
||||
const row = document.createElement("label");
|
||||
const input = document.createElement("input");
|
||||
const value = document.createElement("span");
|
||||
input.type = "range";
|
||||
Object.assign(input, { min, max, step, value: get() });
|
||||
const show = () => { value.textContent = Number(input.value).toFixed(step < 0.1 ? 2 : 1); };
|
||||
input.addEventListener("input", () => { set(Number(input.value)); show(); apply?.(); wake(); });
|
||||
show();
|
||||
row.append(label, input, value);
|
||||
panel.append(row);
|
||||
sliders[label] = input;
|
||||
}
|
||||
|
||||
function resize() {
|
||||
renderer!.resize(window.innerWidth, window.innerHeight, dpr, state.scale);
|
||||
wake();
|
||||
}
|
||||
|
||||
function applyTier(next: number) {
|
||||
tier = next;
|
||||
const preset = QUALITY_TIERS[tier];
|
||||
state.scale = preset.scale;
|
||||
state.maxFps = preset.maxFps;
|
||||
state.tierName = preset.name;
|
||||
state.paused = preset.maxFps === 0;
|
||||
params.steps = preset.steps;
|
||||
params.stepScale = preset.stepScale;
|
||||
params.bloomPasses = preset.bloomPasses;
|
||||
resize();
|
||||
}
|
||||
|
||||
/** Time a handful of synchronised frames and step the quality down until the budget holds. */
|
||||
function calibrate() {
|
||||
if (!state.auto) return;
|
||||
for (let attempt = 0; attempt < QUALITY_TIERS.length; attempt++) {
|
||||
const samples: number[] = [];
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const start = performance.now();
|
||||
renderer!.render(i * 0.016, params);
|
||||
renderer!.finish();
|
||||
samples.push(performance.now() - start);
|
||||
}
|
||||
const next = chooseTier({ tier, samples, sinceChangeMs: Infinity });
|
||||
if (next === tier) return;
|
||||
applyTier(next);
|
||||
}
|
||||
}
|
||||
|
||||
const physical = (key: keyof BlackholeParams) => () => params[key] as number;
|
||||
const assign = (key: keyof BlackholeParams) => (value: number) => { (params as Record<string, unknown>)[key] = value; };
|
||||
|
||||
slider("elevation °", () => params.elevation * 180 / Math.PI, (v) => { params.elevation = v * Math.PI / 180; }, 5, 88, 0.5);
|
||||
slider("scale M→px", physical("pxPerM"), assign("pxPerM"), 4, 40, 0.1);
|
||||
slider("sky", physical("sky"), assign("sky"), 0, 1.5, 0.05);
|
||||
slider("disk gain", physical("diskGain"), assign("diskGain"), 0.2, 4, 0.05);
|
||||
slider("doppler", physical("doppler"), assign("doppler"), 0, 1, 0.05);
|
||||
slider("bloom", physical("bloom"), assign("bloom"), 0, 3, 0.05);
|
||||
slider("exposure", physical("exposure"), assign("exposure"), 0.3, 3, 0.05);
|
||||
slider("absorb", physical("absorb"), assign("absorb"), 0, 1, 0.05);
|
||||
slider("disk speed", () => state.speed, (v) => { state.speed = v; }, 0, 4, 0.05);
|
||||
slider("sway", () => state.swayAmount, (v) => { state.swayAmount = v; }, 0, 4, 0.05);
|
||||
|
||||
const row = document.createElement("div");
|
||||
row.className = "row";
|
||||
const button = (label: string, action: () => void) => {
|
||||
const element = document.createElement("button");
|
||||
element.textContent = label;
|
||||
element.addEventListener("click", () => { action(); wake(); });
|
||||
row.append(element);
|
||||
return element;
|
||||
};
|
||||
const select = document.createElement("select");
|
||||
for (const option of ["auto", ...QUALITY_TIERS.map(({ name }) => name)]) select.append(new Option(option, option));
|
||||
select.addEventListener("change", () => {
|
||||
state.auto = select.value === "auto";
|
||||
if (state.auto) { applyTier(initialTier({ software, cores: navigator.hardwareConcurrency, memoryGb: nav.deviceMemory, pixels: window.innerWidth * window.innerHeight * dpr * dpr })); calibrate(); }
|
||||
else applyTier(QUALITY_TIERS.findIndex(({ name }) => name === select.value));
|
||||
});
|
||||
row.append(select);
|
||||
button("pause", () => { state.paused = !state.paused; });
|
||||
button("shadow ring", () => { params.showShadow = !params.showShadow; });
|
||||
button("hide panel", () => panel.classList.add("hidden"));
|
||||
panel.append(row, readout);
|
||||
window.addEventListener("keydown", (event) => { if (event.key === "h") panel.classList.toggle("hidden"); });
|
||||
|
||||
let dragY: number | undefined;
|
||||
canvas.addEventListener("pointerdown", (event) => { dragY = event.clientY; canvas.setPointerCapture(event.pointerId); });
|
||||
canvas.addEventListener("pointermove", (event) => {
|
||||
if (dragY === undefined) return;
|
||||
params.elevation = Math.max(0.09, Math.min(1.53, params.elevation + (event.clientY - dragY) * 0.004));
|
||||
dragY = event.clientY;
|
||||
sliders["elevation °"].value = String(params.elevation * 180 / Math.PI);
|
||||
wake();
|
||||
});
|
||||
canvas.addEventListener("pointerup", () => { dragY = undefined; });
|
||||
|
||||
let settle = 0;
|
||||
window.addEventListener("resize", () => {
|
||||
resize();
|
||||
clearTimeout(settle);
|
||||
settle = window.setTimeout(calibrate, 400);
|
||||
});
|
||||
|
||||
function frame(now: number) {
|
||||
raf = 0;
|
||||
if (!dirty && state.paused && !look.running && !sweeping) return;
|
||||
if (!look.running && !sweeping && state.maxFps > 0 && now - lastRender < 1000 / state.maxFps - 2 && !dirty) { raf = requestAnimationFrame(frame); return; }
|
||||
const delta = Math.min(0.1, (now - last) / 1000);
|
||||
last = now;
|
||||
lastRender = now;
|
||||
if (!state.frozenWave) {
|
||||
stepLook(look, delta);
|
||||
applyWave();
|
||||
}
|
||||
params.sweep = diskClock * 0.8;
|
||||
// Persistence fades in and out instead of popping when motion pauses.
|
||||
const sweepTarget = state.paused ? 0 : 1;
|
||||
params.sweepAmount += (sweepTarget - params.sweepAmount) * Math.min(1, delta * 7);
|
||||
sweeping = Math.abs(sweepTarget - params.sweepAmount) > 0.004;
|
||||
if (!sweeping) params.sweepAmount = sweepTarget;
|
||||
placeTags();
|
||||
if (!state.paused) diskClock += delta * state.speed;
|
||||
params.sway = 0.06 * state.swayAmount * Math.sin(diskClock * 0.05);
|
||||
const start = performance.now();
|
||||
renderer!.render(diskClock, params);
|
||||
drawMs += (performance.now() - start - drawMs) * 0.1;
|
||||
dirty = false;
|
||||
const { info } = renderer!;
|
||||
readout.textContent = `${info.renderer}${info.software ? " (SOFTWARE: timings not representative)" : ""}\n` +
|
||||
`tier: ${state.tierName}${state.auto ? " (auto)" : ""} cap ${state.maxFps} fps${throttle > 1 ? ` THROTTLE ×${throttle}` : ""}\n` +
|
||||
`canvas ${canvas.width}×${canvas.height} scene ×${state.scale}\n` +
|
||||
`sky ${info.skySize}² cubemap, baked in ${info.skyBakeMs.toFixed(0)} ms\n` +
|
||||
`cpu submit ${drawMs.toFixed(2)} ms${state.paused ? "\nIDLE: not rendering" : ""}`;
|
||||
if (!state.paused || look.running || sweeping) raf = requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
async function benchmark(scales = [0.5, 0.75, 1], frames = 60) {
|
||||
const saved = state.scale;
|
||||
const results: Record<string, number> = {};
|
||||
for (const scale of scales) {
|
||||
state.scale = scale;
|
||||
renderer!.resize(window.innerWidth, window.innerHeight, dpr, scale);
|
||||
renderer!.render(0, params);
|
||||
renderer!.finish();
|
||||
const start = performance.now();
|
||||
for (let i = 0; i < frames; i++) { renderer!.render(i * 0.016, params); renderer!.finish(); }
|
||||
results[String(scale)] = Number(((performance.now() - start) / frames).toFixed(2));
|
||||
}
|
||||
state.scale = saved;
|
||||
renderer!.resize(window.innerWidth, window.innerHeight, dpr, saved);
|
||||
return { renderer: renderer!.info.renderer, software: renderer!.info.software, canvas: [canvas.width, canvas.height], msPerFrame: results };
|
||||
}
|
||||
|
||||
// Debug: hold the wave at a given progress so a still can be inspected. Pass null to release it.
|
||||
function previewWave(progress: number | null, to: 0 | 1 = 1) {
|
||||
if (progress === null) { state.frozenWave = false; Object.assign(look, createLook(to)); wake(); return; }
|
||||
state.frozenWave = true;
|
||||
Object.assign(look, { from: (1 - to) as 0 | 1, to, progress, velocity: 0, running: true, queued: undefined });
|
||||
applyWave();
|
||||
placeTags();
|
||||
renderer!.render(diskClock, params);
|
||||
}
|
||||
|
||||
Object.assign(window, { __bh: { params, state, benchmark, renderer, wake, applyTier, throttle, setMode, look, previewWave, tier: () => tier } });
|
||||
modeBar.children[0].classList.add("on");
|
||||
applyTier(tier);
|
||||
calibrate();
|
||||
wake();
|
||||
Reference in New Issue
Block a user