Init Main project

This commit is contained in:
tyuXX 2026-11-15 12:57:24 +03:00
commit 9e581ae67f
220 changed files with 253987 additions and 0 deletions

170
src/client/api.ts Normal file
View file

@ -0,0 +1,170 @@
// Client HTTP API wrapper, token/settings localStorage helpers -> (this fails half the time but oh well), and SSE stream connection.
import type {
LockedDesignItemInfo,
RocketDesign,
SavedRocketBlueprint,
} from "../shared/types.js";
export interface ClientSettings {
quality: "low" | "medium" | "high";
sound: boolean;
notifications: boolean;
dynamicTheme: boolean;
colorMode: "dark" | "light";
reducedEffects: boolean;
}
const TOKEN_KEY = "spacegaem_proto_token";
const SETTINGS_KEY = "spacegaem_proto_settings";
export function getToken(): string | null {
return localStorage.getItem(TOKEN_KEY);
}
export function setToken(t: string | null): void {
if (t) localStorage.setItem(TOKEN_KEY, t);
else localStorage.removeItem(TOKEN_KEY);
}
export function getSettings(): ClientSettings {
try {
const raw = JSON.parse(
localStorage.getItem(SETTINGS_KEY) ?? "{}",
) as Partial<ClientSettings>;
return {
quality: raw.quality ?? "high",
sound: raw.sound ?? true,
notifications: raw.notifications ?? true,
dynamicTheme: raw.dynamicTheme ?? true,
colorMode: raw.colorMode === "light" ? "light" : "dark",
reducedEffects: raw.reducedEffects ?? false,
};
} catch {
return {
quality: "high",
sound: true,
notifications: true,
dynamicTheme: true,
colorMode: "dark",
reducedEffects: false,
};
}
}
export function saveSettings(s: ClientSettings): void {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
document.body.dataset.dynamicTheme = s.dynamicTheme ? "on" : "off";
document.documentElement.dataset.colorMode = s.colorMode;
document.documentElement.classList.toggle(
"reduced-effects",
!!s.reducedEffects,
);
}
async function request<T = any>(
method: string,
url: string,
body?: unknown,
auth = true,
): Promise<T> {
const headers: Record<string, string> = {};
if (body !== undefined) headers["Content-Type"] = "application/json";
const token = getToken();
if (auth && token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let data: any = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = { error: text };
}
if (!res.ok) {
throw new Error(data?.error ?? `HTTP ${res.status}`);
}
return data as T;
}
export const api = {
get: <T = any>(url: string, auth = true) =>
request<T>("GET", url, undefined, auth),
post: <T = any>(url: string, body: unknown, auth = true) =>
request<T>("POST", url, body, auth),
delete: <T = any>(url: string, auth = true) =>
request<T>("DELETE", url, undefined, auth),
getMlStatus: () => request<any>("GET", "/api/ml-status", undefined, false),
toggleMlBridge: (enabled?: boolean) =>
request<any>("POST", "/api/ml-toggle", { enabled }, true),
getDesigns: () =>
request<{
ok: boolean;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>("GET", "/api/agency/designs", undefined, true),
saveDesignBlueprint: (payload: {
id?: string;
name: string;
design: RocketDesign;
notes?: string;
isPublic?: boolean;
targetHint?: string;
}) =>
request<{
ok: boolean;
blueprint: SavedRocketBlueprint;
shareCode: string;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>("POST", "/api/agency/designs", payload, true),
deleteDesignBlueprint: (id: string) =>
request<{
ok: boolean;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>(
"DELETE",
`/api/agency/designs/${encodeURIComponent(id)}`,
undefined,
true,
),
importDesignBlueprint: (payload: {
codeOrJson: string;
name?: string;
saveToHangar?: boolean;
}) =>
request<{
ok: boolean;
design: RocketDesign;
shareCode: string;
lockedItems: LockedDesignItemInfo[];
summary: {
totalDv: number;
totalCost: number;
stageCount: number;
designTier: string;
};
blueprint?: SavedRocketBlueprint;
myDesigns?: SavedRocketBlueprint[];
}>("POST", "/api/agency/designs/import", payload, true),
};
export interface LiveEvent {
type: string;
data?: Record<string, any>;
at?: number;
}
export function connectEvents(onEvent: (ev: LiveEvent) => void): EventSource {
const es = new EventSource("/api/events");
es.onmessage = (msg) => {
try {
const parsed = JSON.parse(msg.data) as LiveEvent;
onEvent(parsed);
} catch {}
};
return es;
}

140
src/client/app.ts Normal file
View file

@ -0,0 +1,140 @@
// Literally everything (pls help me my autocorrect is trying to insult me how does this even work)
import { getSettings, saveSettings } from "./api.js";
import { navigate, registerScreenRenderers } from "./router.js";
import {
loadCatalogs,
refreshMe,
refreshWorld,
startEvents,
} from "./session.js";
import {
applyThemeFromState,
type DebriefScreenParams,
type LaunchScreenParams,
state,
} from "./state.js";
import {
getColorMode,
isReducedEffects,
toggleColorMode,
toggleReducedEffects,
} from "./theme.js";
import {
clear,
h,
initNotificationDrawer,
initTooltipController,
toast,
} from "./ui.js";
import { renderAuth } from "./screens/auth.js";
import { renderContracts } from "./screens/contracts.js";
import { renderDashboard } from "./screens/dashboard.js";
import { renderDebrief } from "./screens/debrief.js";
import { renderLaunchSequence } from "./screens/launchSequence.js";
import { renderMainMenu } from "./screens/mainMenu.js";
import { renderMissionConfig } from "./screens/missionConfig.js";
import { renderOnboarding } from "./screens/onboarding.js";
import { renderRocketBuilder } from "./screens/rocketBuilder.js";
import { renderWorldMap } from "./screens/worldMap.js";
registerScreenRenderers({
mainMenu: (el) => renderMainMenu(el),
auth: (el) => renderAuth(el),
onboarding: (el) => renderOnboarding(el),
dashboard: (el) => renderDashboard(el),
builder: (el) => renderRocketBuilder(el),
config: (el) => renderMissionConfig(el),
launch: (el, p) => renderLaunchSequence(el, p as LaunchScreenParams),
debrief: (el, p) => renderDebrief(el, p as DebriefScreenParams),
contracts: (el) => renderContracts(el),
worldMap: (el) => renderWorldMap(el),
});
function renderComfortToolbar(): void {
const root = document.getElementById("comfort-controls-root");
if (!root) return;
clear(root);
const mode = getColorMode();
const reduced = isReducedEffects();
root.appendChild(
h(
"div",
{ class: "comfort-pill-bar" },
h(
"button",
{
class: `comfort-btn ${mode === "light" ? "active" : ""}`,
title: "Toggle Daylight Light Mode / Dark Mode",
onClick: () => {
toggleColorMode();
renderComfortToolbar();
},
},
mode === "light" ? "SUN LIGHT" : "DARK",
),
h(
"button",
{
class: `comfort-btn ${reduced ? "active" : ""}`,
title:
"Toggle Eye-Saver (Reduced Effects: disables glows, scanlines & shake)",
onClick: () => {
toggleReducedEffects();
applyThemeFromState();
renderComfortToolbar();
},
},
reduced ? "EYE-SAVER ON" : "EYE-SAVER",
),
),
);
}
async function waitForStylesAndLoad(): Promise<void> {
const pendingLinks = Array.from(
document.querySelectorAll('link[rel="stylesheet"]'),
) as HTMLLinkElement[];
const cssPromises = pendingLinks
.filter((link) => !link.sheet)
.map(
(link) =>
new Promise<void>((resolve) => {
link.addEventListener("load", () => resolve(), { once: true });
link.addEventListener("error", () => resolve(), { once: true });
}),
);
const loadPromise =
document.readyState === "complete"
? Promise.resolve()
: new Promise<void>((resolve) => {
window.addEventListener("load", () => resolve(), { once: true });
});
await Promise.race([
Promise.all([loadPromise, ...cssPromises]).then(() => undefined),
new Promise<void>((resolve) => window.setTimeout(resolve, 1500)),
]);
}
async function boot(): Promise<void> {
saveSettings(getSettings());
applyThemeFromState();
renderComfortToolbar();
window.addEventListener("sgywftp:theme-changed", renderComfortToolbar);
initNotificationDrawer();
initTooltipController();
const readyPromise = waitForStylesAndLoad();
try {
await loadCatalogs();
} catch (err) {
toast(`Failed to load mission catalogs: ${(err as Error).message}`, "err");
}
await refreshMe();
if (state.agency) {
await refreshWorld();
startEvents();
}
await readyPromise;
navigate("mainMenu");
}
void boot();

389
src/client/glossary.ts Normal file
View file

@ -0,0 +1,389 @@
// Terminologic glossary, cus I forget what this shit means every 2 seconds pls don't ask me this, I not know rockeet siençe
export interface GlossaryEntry {
title: string;
summary: string;
formula?: string;
category:
| "Propulsion"
| "Structures & Aero"
| "Flight & Orbit"
| "Avionics & Bus"
| "Program & Compliance";
}
const TERMINOLOGY_GLOSSARY_RAW = {
dv: {
title: "Delta-v (Δv)",
summary:
"Total velocity-change capability of the launch vehicle across all stages. Includes gravity, drag, and steering losses during ascent.",
formula:
"Δv = Isp · g0 · ln(m_wet / m_dry) (two-phase when jettisoning drop tanks)",
category: "Propulsion",
},
dv_margin: {
title: "Delta-v Margin",
summary:
"Difference between your rocket Δv and the mission target requirement. Positive margin provides reserve for wind shear, throttling, and guidance dispersion.",
formula: "Margin = Vehicle Δv − Required Δv",
category: "Propulsion",
},
req_dv: {
title: "Required Delta-v",
summary:
"Minimum velocity budget needed to enter the target orbit, including inclination plane cost, Earth ascent losses (~1,400–1,800 m/s), and transfer burns.",
category: "Propulsion",
},
twr: {
title: "Thrust-to-Weight Ratio (TWR)",
summary:
"Total engine thrust divided by vehicle Earth weight at liftoff. Must exceed 1.02 to lift off the pad; 1.30–1.70 minimizes gravity losses without excessive Max-Q.",
formula: "TWR = Thrust / (Wet Mass × 9.81 m/s²)",
category: "Propulsion",
},
stage_twr: {
title: "Stage Ignition TWR",
summary:
"Thrust-to-weight ratio at the moment this stage ignites in flight. Upper stages should maintain ≥ 0.50 so the vehicle climbs past apoapsis before falling back.",
category: "Propulsion",
},
isp: {
title: "Specific Impulse (Isp)",
summary:
"Propellant fuel efficiency measured in seconds (higher means more thrust per kg burned per second). Vacuum Isp is higher than sea-level Isp due to zero atmospheric backpressure.",
formula: "ve = Isp · g0 (effective exhaust velocity)",
category: "Propulsion",
},
nozzle_ratio: {
title: "Nozzle Expansion Ratio",
summary:
"Bell exit-area scaling factor. Smaller bells (0.85–1.0×) resist sea-level flow separation near liftoff; wider bells (1.15–1.4×) boost vacuum Isp on upper stages.",
category: "Propulsion",
},
gimbal: {
title: "Gimbal Deflection Range",
summary:
"Maximum nozzle pivot angle (± degrees) for Thrust Vector Control (TVC). Enables steering during the pitch-over turn and counters aerodynamic instability or wind shear.",
category: "Propulsion",
},
propellant_chemistry: {
title: "Propellant Chemistry",
summary:
"Kerolox (RP-1/LOX) is dense with high thrust; Hydrolox (LH2/LOX) offers top Isp but needs bulky insulated tanks; Methalox balances density & efficiency; Hypergolic is storable; Solid cannot throttle.",
category: "Propulsion",
},
crossfeed: {
title: "Propellant Crossfeed",
summary:
"Plumbing manifold that draws fuel and oxidizer from external drop tanks first while keeping the core tank full, allowing empty external casings to drop early mid-burn.",
category: "Propulsion",
},
drop_tanks: {
title: "Disposable Drop Tanks",
summary:
"Aerodynamic external tanks mounted radially onto a liquid stage (e.g., 1× Shuttle-style belly tank or 2×–6× side pods). Drained first via crossfeed and jettisoned empty mid-burn to raise Δv.",
category: "Propulsion",
},
fill_ratio: {
title: "Tank Fill Ratio",
summary:
"Percentage of propellant volume loaded before launch (Expert mode). Offloading propellant lowers liftoff weight and raises TWR at the cost of reduced total Δv.",
category: "Propulsion",
},
engine_count: {
title: "Engine Cluster Count",
summary:
"Number of identical engines mounted on this stage thrust structure. Multiplies stage thrust and mass flow proportionally while keeping the same propellant tank.",
category: "Propulsion",
},
wet_dry_mass: {
title: "Wet vs Dry Mass",
summary:
"Wet mass is fueled liftoff mass (structure + engines + payload + propellant). Dry mass is structural mass remaining at burnout. Rocket Δv grows with the ratio of Wet to Dry mass.",
category: "Structures & Aero",
},
cg_cp: {
title: "CG vs CP (Center of Gravity / Pressure)",
summary:
"CG is the mass balance point; CP is where aerodynamic lift acts. Keeping CG ahead of (above) CP makes the rocket naturally arrow-stable in flight.",
category: "Structures & Aero",
},
stability_calibers: {
title: "Static Stability Margin (Calibers)",
summary:
"Distance from Center of Pressure up to Center of Gravity divided by hull diameter. Positive calibers passively stabilize ascent; deeply negative values risk tumbling under Max-Q.",
formula: "Margin = (CG_y − CP_y) / Max Diameter",
category: "Structures & Aero",
},
fineness: {
title: "Fineness Ratio (L / D)",
summary:
"Ratio of overall rocket height to maximum fuselage diameter. Tall slender rockets (> 20.5 L/D) cut frontal drag but endure sharper structural bending during Max-Q.",
formula: "L/D = Total Height / Max Diameter",
category: "Structures & Aero",
},
buckling: {
title: "Axial Buckling Ratio",
summary:
"Ratio of peak compressive/bending launch load to the airframe shell limit. Must remain below 1.00; thicken walls or upgrade hull materials/structures if exceeded.",
formula: "Buckling = Peak Axial + Wind Load / Shell Yield Capacity",
category: "Structures & Aero",
},
max_q: {
title: "Max-Q (Maximum Dynamic Pressure)",
summary:
"Peak aerodynamic pressure q = ½ ρ v² experienced in the dense lower atmosphere near Mach 1. Over-speeding or soft walls above stage Max-Q limit cause structural breakup.",
formula: "q = ½ · ρ(alt) · v²",
category: "Structures & Aero",
},
wall_factor: {
title: "Wall Thickness Multiplier",
summary:
"Scales airframe skin gauge above/below baseline. Thicker walls raise buckling and Max-Q structural limits while adding dry mass.",
category: "Structures & Aero",
},
airframe_material: {
title: "Hull Material",
summary:
"Alloys and composites trade mass density against yield strength and heat tolerance: Al-Li and Carbon Composite shave dry weight; Stainless Steel resists high thermal loads.",
category: "Structures & Aero",
},
interstage: {
title: "Interstage Adapter",
summary:
"Structural shroud/truss bridging two stage diameters and enclosing upper-stage engine bells with pneumatic or pyrotechnic separation latches.",
category: "Structures & Aero",
},
grid_fins: {
title: "Aerodynamic Fins / Grid Fins",
summary:
"Tail-mounted fins generating restoring drag force aft of the Center of Gravity, pulling CP downward to stabilize top-heavy or wide-fairing rockets.",
category: "Structures & Aero",
},
heatshield: {
title: "TPS Heatshield Blanket",
summary:
"Thermal Protection System ablative or tile cladding that raises stage survival temperature against high-speed atmospheric friction and reentry plasma.",
category: "Structures & Aero",
},
fairing: {
title: "Payload Fairing",
summary:
"Clamshell nose shroud shielding satellites from supersonic airflow, wind shear, and debris. Automatically jettisoned once outside dense atmosphere (~80–120 km).",
category: "Structures & Aero",
},
las: {
title: "Launch Abort System (LAS)",
summary:
"High-thrust solid escape tower mounted atop crew capsules to yank astronauts clear of pad fires or mid-ascent booster failures.",
category: "Structures & Aero",
},
apoapsis: {
title: "Apoapsis (Ap)",
summary:
"Highest altitude point along an orbital ellipse. Reaching target apoapsis allows coasting upward before a final circularization burn raises periapsis.",
category: "Flight & Orbit",
},
periapsis: {
title: "Periapsis (Pe)",
summary:
"Lowest altitude point along an orbit. Must stay above Earth dense atmosphere (≥ 90 km) for a stable non-decaying parking orbit.",
category: "Flight & Orbit",
},
inclination: {
title: "Orbital Inclination (i)",
summary:
"Angle between the orbital plane and Earth equator (0° equatorial, 28.5° KSC, 97.5° polar Sun-synchronous). Higher inclination loses surface rotational launch assist.",
category: "Flight & Orbit",
},
mach: {
title: "Mach Number",
summary:
"Airspeed divided by the local speed of sound at current altitude temperature. Transonic shock waves and drag peak sharply between Mach 0.85 and 1.25.",
category: "Flight & Orbit",
},
g_load: {
title: "Axial Acceleration (G-Load)",
summary:
"Total acceleration felt by vehicle structure and crew in multiples of Earth gravity (9.81 m/s²). Crewed capsules enforce strict G-limits as propellant empties.",
category: "Flight & Orbit",
},
heat_flux: {
title: "Aerodynamic Heat Flux",
summary:
"Stagnation heating power (W/cm²) transferred from compressed supersonic air onto the nosecone, drop tanks, and exposed structures.",
category: "Flight & Orbit",
},
flight_path_angle: {
title: "Pitch & Gravity Turn",
summary:
"Vehicle nose angle relative to the local horizon (90° straight up, 0° horizontal). A crisp pitch-over kick lets gravity bend velocity efficiently toward orbit.",
category: "Flight & Orbit",
},
meco_seco: {
title: "MECO / SECO",
summary:
"Main Engine Cutoff (first-stage shutdown and separation) and Second/Sustainer Engine Cutoff (upper stage shutdown once target orbit corridor is met).",
category: "Flight & Orbit",
},
burnout_metrics: {
title: "Burnout Velocity & Downrange",
summary:
"Speed and great-circle distance traveled east/azimuth from the launch pad when orbital insertion or fuel exhaustion occurs.",
category: "Flight & Orbit",
},
dv_remaining: {
title: "Remaining Δv Reserve",
summary:
"Unspent velocity-change impulse remaining after parking orbit insertion, used for circularization or trans-lunar / planetary injection burns.",
category: "Flight & Orbit",
},
park_orbit_quality: {
title: "Orbit Insertion Grade",
summary:
"Precision rating (A+ to Failed) comparing achieved Apoapsis, Periapsis, and Inclination corridor accuracy against mission tolerances.",
category: "Flight & Orbit",
},
max_q_throttle: {
title: "Max-Q Throttle Limit",
summary:
"Automated engine throttle-down near Max-Q (~Mach 0.9–1.5) to prevent aerodynamic dynamic pressure from exceeding airframe yield stress.",
category: "Flight & Orbit",
},
fairing_sep_alt: {
title: "Fairing Separation Altitude",
summary:
"Altitude (km) at which the protective payload shroud jettisons. Jettisoning too low risks aero/micrometeoroid payload damage; too high hauls unnecessary mass.",
category: "Flight & Orbit",
},
turn_end_alt: {
title: "Gravity Turn End Altitude",
summary:
"Altitude at which guidance finishes flattening toward horizontal (0°). Too low burns in thick air; too high wastes propellant fighting gravity.",
category: "Flight & Orbit",
},
flight_computer: {
title: "Flight Computer (GNC)",
summary:
"Guidance, Navigation & Control avionics processing attitude loops, crossfeed valve sequencing, telemetry encoding, and fault voting.",
category: "Avionics & Bus",
},
rad_hardening: {
title: "Radiation Hardening (RAD)",
summary:
"Chip-level shielding & Triple Modular Redundancy resisting cosmic rays and solar proton storms that trigger Single-Event Upsets (SEUs).",
category: "Avionics & Bus",
},
cpu_load: {
title: "Peak CPU Load",
summary:
"Flight computer processor utilization across multi-engine throttling, drop-tank crossfeed logic, comms, and hazard avoidance. Exceeding 92–100% risks guidance freeze.",
category: "Avionics & Bus",
},
seu: {
title: "Single-Event Upsets (SEUs)",
summary:
"Transient bit-flips caused by ionizing radiation during solar storms or high-altitude belts. Unshielded avionics suffer cumulative resets if SEUs spike.",
category: "Avionics & Bus",
},
reliability_risk: {
title: "Hardware Defect Risk",
summary:
"Estimated per-flight component malfunction chance derived from part maturity, thermal/Max-Q margins, and manufacturing quality control.",
category: "Avionics & Bus",
},
maturity: {
title: "Design Maturity",
summary:
"Flight qualification tier (Concept → Prototype → Flight-Proven). Test flights and successful missions lower hardware failure probability and insurance costs.",
category: "Avionics & Bus",
},
spacecraft_bus: {
title: "Spacecraft Bus & Power",
summary:
"Payload support subsystems: solar arrays or RTGs, batteries, Reaction Control System (RCS), and thermal radiators needed to keep the mission alive in space.",
category: "Avionics & Bus",
},
power_margin: {
title: "Electrical Power Margin",
summary:
"Generated solar/RTG wattage minus continuous bus, heater, and comms transmitter consumption. Negative balance causes battery depletion and brownouts.",
category: "Avionics & Bus",
},
comms_link: {
title: "Comms Signal Health",
summary:
"RF/Optical telemetry link quality balancing antenna dish gain, transmitter band (S/X/Ka/Optical), Earth tracking network tier, and distance attenuation.",
category: "Avionics & Bus",
},
telemetry_freq: {
title: "Tracking Station & Link Band",
summary:
"Ground antenna handover across range stations (Regional vs Global Deep Space Network) and carrier frequency carrying live guidance and health frames.",
category: "Avionics & Bus",
},
crew_eclss: {
title: "Crew Capacity & ECLSS",
summary:
"Astronaut seats aboard the flight and Environmental Control & Life Support System rating governing oxygen regeneration, CO2 scrubbing, and emergency reserve.",
category: "Program & Compliance",
},
safety_compliance: {
title: "Engineering & Safety Compliance",
summary:
"Pre-launch Range Safety rules (PROP, STR, FLT, SAF, AVN, BUS). Blocking failures halt launch; advisory warnings may require design fixes or a paid Waiver.",
category: "Program & Compliance",
},
waivers: {
title: "Flight Safety Waiver",
summary:
"Regulatory exception allowing launch despite an advisory compliance flag for an added fee and increased in-flight risk. Critical safety rules cannot be waived.",
category: "Program & Compliance",
},
rd_tech: {
title: "R&D Tech Tree",
summary:
"Agency research investments unlocking advanced engines, high-capacity external drop tanks, low-mass alloys, and deep-space avionics.",
category: "Program & Compliance",
},
difficulty: {
title: "Simulation Difficulty",
summary:
"Controls engineering realism: Casual grants forgiving margins; Standard balances physics & finance; Expert enables tank fill ratios, severe wind shear, and radiation SEUs.",
category: "Program & Compliance",
},
design_tier: {
title: "Builder Architecture Mode",
summary:
"Guided mode uses structured per-stage slots + drop-tank symmetry controls; Pro Freeform enables direct 3D axis placement, arbitrary radial pods, and custom part stacking.",
category: "Program & Compliance",
},
contract_tier: {
title: "Contract Tier & Payout",
summary:
"Mission difficulty bracket (T1–T5) setting payload mass, orbital destination, deadline window, completion payout, and penalty upon loss or cancellation.",
category: "Program & Compliance",
},
space_weather: {
title: "Space Weather & Range Hazards",
summary:
"Forecast solar wind, proton storms (raising SEU risk), upper atmospheric wind shear (spiking Max-Q loads), and micrometeoroid flux affecting launch timing.",
category: "Program & Compliance",
},
launch_cost: {
title: "Total Mission Cost",
summary:
"Total expenditure debited upon launch: stages, engines, core & disposable tanks, avionics, payload integration, range fees, and any active waivers.",
category: "Program & Compliance",
},
ground_network: {
title: "Ground Tracking Network",
summary:
"Earth dish infrastructure tier (Regional vs Global DSN) needed to maintain command uplink downrange and across deep-space distances.",
category: "Program & Compliance",
},
} as const satisfies Record<string, GlossaryEntry>;
export type GlossaryKey = keyof typeof TERMINOLOGY_GLOSSARY_RAW;
export const TERMINOLOGY_GLOSSARY: Record<GlossaryKey, GlossaryEntry> =
TERMINOLOGY_GLOSSARY_RAW;

57
src/client/router.ts Normal file
View file

@ -0,0 +1,57 @@
// (Tech support with -4 hours of sleep and 6th mug of coffee) Uhm, sir, have you tried turning it off and on again?
// Oh.
// Oh...
import { type ScreenName, setCurrentScreen } from "./state.js";
import { clear, hideTooltip } from "./ui.js";
export type ScreenRenderer = (
appEl: HTMLElement,
params: Record<string, any>,
) => (() => void) | void;
const appEl = document.getElementById("app") as HTMLElement;
let activeCleanup: (() => void) | null = null;
let screenRenderers: Partial<Record<ScreenName, ScreenRenderer>> = {};
const RIGHT_SIDEBAR_OFFSET_PX: Partial<Record<ScreenName, number>> = {
dashboard: 370,
builder: 440,
config: 440,
worldMap: 340,
};
export function registerScreenRenderers(
renderers: Partial<Record<ScreenName, ScreenRenderer>>,
): void {
screenRenderers = renderers;
}
export function navigate(
screen: ScreenName,
params: Record<string, any> = {},
): void {
if (activeCleanup) {
try {
activeCleanup();
} catch (err) {
console.warn("Cleanup error:", err);
}
activeCleanup = null;
}
setCurrentScreen(screen);
const sidebarOffset = RIGHT_SIDEBAR_OFFSET_PX[screen] ?? 0;
document.documentElement.style.setProperty(
"--right-sidebar-offset",
`${sidebarOffset}px`,
);
document.documentElement.classList.toggle(
"has-right-sidebar",
sidebarOffset > 0,
);
clear(appEl);
hideTooltip();
const cleanup = screenRenderers[screen]?.(appEl, params);
if (typeof cleanup === "function") {
activeCleanup = cleanup;
}
}

192
src/client/screens/auth.ts Normal file
View file

@ -0,0 +1,192 @@
// Login, registration, and difficulty selector screen.
import { api, setToken } from "../api.js";
import { navigate } from "../router.js";
import { refreshMe, refreshWorld, startEvents } from "../session.js";
import { state } from "../state.js";
import { DIFFICULTY_PROFILES } from "../../shared/physics.js";
import type { AgencyState, CanonicalDifficulty } from "../../shared/types.js";
import { h, toast } from "../ui.js";
export function renderAuth(root: HTMLElement): void {
let mode: "login" | "register" = "register";
let difficulty: CanonicalDifficulty = "enthusiast";
const nameInput = h("input", {
class: "input",
placeholder: "e.g. Aether Aerospace",
autocomplete: "organization",
});
const pwdInput = h("input", {
class: "input",
type: "password",
placeholder: "Account passphrase (min 4 chars)",
autocomplete: "current-password",
});
const errEl = h("div", { class: "auth-error" });
const tabLogin = h(
"button",
{ class: "btn sm ghost" },
"Existing Agency Login",
);
const tabRegister = h(
"button",
{ class: "btn sm primary" },
"Register New Agency",
);
const diffKeys: CanonicalDifficulty[] = [
"sandbox",
"explorer",
"enthusiast",
"engineer",
"director",
];
const diffButtons = {} as Record<CanonicalDifficulty, HTMLButtonElement>;
for (const k of diffKeys) {
const prof = DIFFICULTY_PROFILES[k];
diffButtons[k] = h(
"button",
{
class: `btn diff-card ${k === difficulty ? "selected" : ""}`,
type: "button",
style: k === "sandbox" ? { gridColumn: "1 / -1" } : undefined,
},
h(
"div",
{ class: "dc-head" },
h("span", {}, prof.label),
h("span", { class: "accent" }, prof.audience),
),
h("div", { class: "dc-sub" }, prof.tagline),
h(
"div",
{ class: "dc-meta" },
k === "sandbox"
? "Unlimited ($10B) • All Missions & R&D • Zero Penalties"
: `$${Math.round(prof.startingFunds / 1e6)}M Start • ±${prof.orbitTolPct}% Orbit • ${prof.maxBailouts} Bailout${prof.maxBailouts === 1 ? "" : "s"}`,
),
);
}
const diffGroup = h(
"div",
{ class: "field" },
h("span", {}, "Program Difficulty & Experience Tier"),
h("div", { class: "diff-picker" }, ...diffKeys.map((k) => diffButtons[k])),
);
const submitBtn = h(
"button",
{ class: "btn primary", type: "submit" },
"Establish Agency",
);
function syncMode() {
tabLogin.className = `btn sm ${mode === "login" ? "primary" : "ghost"}`;
tabRegister.className = `btn sm ${mode === "register" ? "primary" : "ghost"}`;
diffGroup.style.display = mode === "register" ? "flex" : "none";
submitBtn.textContent =
mode === "register" ? "Establish Agency" : "Authenticate & Enter";
errEl.textContent = "";
}
tabLogin.addEventListener("click", () => {
mode = "login";
syncMode();
});
tabRegister.addEventListener("click", () => {
mode = "register";
syncMode();
});
diffKeys.forEach((d) => {
diffButtons[d].addEventListener("click", () => {
difficulty = d;
diffKeys.forEach((k) => {
diffButtons[k].classList.toggle("selected", k === d);
});
});
});
const form = h(
"form",
{
class: "col",
onSubmit: async (ev: Event) => {
ev.preventDefault();
errEl.textContent = "";
const name = nameInput.value.trim();
const password = pwdInput.value;
if (name.length < 2) {
errEl.textContent = "Agency name must be at least 2 characters.";
return;
}
if (password.length < 4) {
errEl.textContent = "Password must be at least 4 characters.";
return;
}
submitBtn.disabled = true;
try {
const endpoint =
mode === "register" ? "/api/auth/register" : "/api/auth/login";
const payload =
mode === "register"
? { name, password, difficulty }
: { name, password };
const res = await api.post<{ token: string; agency: AgencyState }>(
endpoint,
payload,
false,
);
setToken(res.token);
state.agency = res.agency;
state.account = { name: res.agency.name };
await refreshMe();
await refreshWorld();
startEvents();
toast(
mode === "register"
? `Welcome aboard, ${res.agency.name}.`
: `Authenticated as ${res.agency.name}.`,
"ok",
);
if (!res.agency.sponsorId) navigate("onboarding");
else navigate("dashboard");
} catch (err) {
errEl.textContent = (err as Error).message;
submitBtn.disabled = false;
}
},
},
h("label", { class: "field" }, "Agency Name", nameInput),
h("label", { class: "field" }, "Passphrase", pwdInput),
diffGroup,
errEl,
h(
"div",
{ class: "row spread", style: { marginTop: "6px" } },
h(
"button",
{
class: "btn ghost sm",
type: "button",
onClick: () => navigate("mainMenu"),
},
"Back",
),
submitBtn,
),
);
const card = h(
"div",
{ class: "panel auth-card col" },
h(
"div",
{ class: "row", style: { marginBottom: "4px" } },
tabRegister,
tabLogin,
),
h("h2", {}, "Agency Credentials"),
h(
"p",
{ class: "sub" },
"Register a new launch provider (agency name is public on the leaderboard) or log into an existing agency.",
),
form,
);
syncMode();
root.appendChild(h("div", { class: "screen screen-center" }, card));
setTimeout(() => nameInput.focus(), 40);
}

View file

@ -0,0 +1,546 @@
// Hangar blueprints save/load/import and SGYW1 share code modal
import { api } from "../../api.js";
import { state } from "../../state.js";
import {
buildRocket,
decodeRocketShareCode,
encodeRocketShareCode,
normalizeDesign,
} from "../../../shared/physics.js";
import type {
LockedDesignItemInfo,
RocketDesign,
SavedRocketBlueprint,
} from "../../../shared/types.js";
import { clear, fmtMoney, fmtNum, h, modal, toast } from "../../ui.js";
import { curAgency, priceOfPart, type BuilderContext } from "./context.js";
import { recordHistory } from "./history.js";
export async function openBlueprintsModal(ctx: BuilderContext): Promise<void> {
const { contract } = ctx;
let myDesigns: SavedRocketBlueprint[] = [
...(curAgency(ctx).savedDesigns ?? []),
];
let communityDesigns: SavedRocketBlueprint[] = [];
const rootWrap = h("div", {
style: {
display: "flex",
flexDirection: "column",
gap: "12px",
maxHeight: "72vh",
overflowY: "auto",
},
});
const m = modal("Vehicle Hangar: Save, Load & Share Blueprints", rootWrap, [
{ label: "Close", kind: "ghost" },
]);
m.el.style.maxWidth = "780px";
m.el.style.width = "94vw";
const loadDesignIntoBuilder = (
raw: RocketDesign,
label: string,
locked: LockedDesignItemInfo[] = [],
) => {
ctx.design = normalizeDesign(
structuredClone(raw),
state.parts,
state.materials,
);
ctx.activeStageIdx = 0;
if (ctx.design.designTier === "pro") {
ctx.selectedProUid = ctx.design.proParts?.[0]?.uid ?? null;
}
recordHistory(ctx, `Load blueprint: ${label}`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
m.close();
if (locked.length > 0) {
toast(
`Loaded "${label}" with ${locked.length} locked R&D item(s). Check Diagnostics panel to unlock or swap.`,
"warn",
);
} else {
toast(`Loaded blueprint "${label}".`, "ok");
}
};
const copyText = async (txt: string, okMsg: string) => {
try {
await navigator.clipboard.writeText(txt);
toast(okMsg, "ok");
} catch {
const tmp = h("textarea", {
value: txt,
style: { position: "fixed", left: "-9999px" },
}) as HTMLTextAreaElement;
document.body.appendChild(tmp);
tmp.select();
document.execCommand("copy");
tmp.remove();
toast(okMsg, "ok");
}
};
const renderModalBody = (
importPreview?: {
design: RocketDesign;
shareCode: string;
lockedItems: LockedDesignItemInfo[];
summary: {
totalDv: number;
totalCost: number;
stageCount: number;
designTier: string;
};
} | null,
) => {
clear(rootWrap);
const saveNameInput = h("input", {
class: "input",
value: ctx.design.name || "Custom Launcher",
placeholder: "Blueprint name",
}) as HTMLInputElement;
const saveNotesInput = h("input", {
class: "input",
placeholder: "Mission / notes (optional)",
}) as HTMLInputElement;
const publishChk = h("input", { type: "checkbox" }) as HTMLInputElement;
const shareCodeStr = encodeRocketShareCode(ctx.design);
const shareCodeBox = h("input", {
class: "input mono",
readonly: true,
value: shareCodeStr,
style: { fontSize: "10px" },
}) as HTMLInputElement;
rootWrap.appendChild(
h(
"div",
{ class: "panel", style: { padding: "10px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "11px" } },
"SAVE & EXPORT CURRENT VEHICLE",
),
h(
"div",
{
class: "row",
style: { gap: "8px", marginTop: "8px", flexWrap: "wrap" },
},
h("label", { class: "field grow" }, "Name", saveNameInput),
h("label", { class: "field grow" }, "Notes", saveNotesInput),
),
h(
"div",
{
class: "row spread",
style: { marginTop: "8px", flexWrap: "wrap", gap: "8px" },
},
h(
"label",
{ class: "row", style: { fontSize: "11px", gap: "6px" } },
publishChk,
h("span", {}, "Publish to Community Hangar"),
),
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"button",
{
class: "btn xs primary",
onClick: async () => {
try {
const res = await api.saveDesignBlueprint({
name:
saveNameInput.value.trim() ||
ctx.design.name ||
"Unnamed Rocket",
design: ctx.design,
notes: saveNotesInput.value.trim() || undefined,
isPublic: publishChk.checked,
targetHint: contract?.targetName,
});
myDesigns = res.myDesigns;
communityDesigns = res.communityDesigns;
if (state.agency) state.agency.savedDesigns = res.myDesigns;
toast(`Saved "${res.blueprint.name}" to Hangar!`, "ok");
renderModalBody(importPreview);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Save to Hangar",
),
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
const payload = JSON.stringify(
{
name: saveNameInput.value.trim() || ctx.design.name,
design: ctx.design,
},
null,
2,
);
const blob = new Blob([payload], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${(ctx.design.name || "rocket").replace(/[^a-z0-9_-]+/gi, "_").toLowerCase()}.rocket.json`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
toast("Downloaded .rocket.json file.", "info");
},
},
"Download .rocket.json",
),
),
),
h(
"div",
{ class: "row", style: { marginTop: "8px", gap: "6px" } },
shareCodeBox,
h(
"button",
{
class: "btn xs selected",
onClick: () =>
void copyText(
shareCodeStr,
"Copied SGYW1 share code to clipboard!",
),
},
"Copy Share Code",
),
),
),
);
const importTextArea = h("textarea", {
class: "input mono",
rows: 2,
placeholder: "Paste SGYW1:... share code or RocketDesign JSON here",
style: { fontSize: "10px", width: "100%" },
}) as HTMLTextAreaElement;
const saveImportedChk = h("input", {
type: "checkbox",
checked: true,
}) as HTMLInputElement;
const fileInput = h("input", {
type: "file",
accept: ".json,.rocket.json,application/json",
style: { fontSize: "11px" },
}) as HTMLInputElement;
fileInput.addEventListener("change", async () => {
const f = fileInput.files?.[0];
if (!f) return;
importTextArea.value = await f.text();
toast(`Loaded JSON from ${f.name}. Click Import & Preview.`, "info");
});
const previewBox = importPreview
? h(
"div",
{
class: "panel",
style: {
padding: "8px 10px",
marginTop: "8px",
borderColor:
importPreview.lockedItems.length > 0
? "var(--amber)"
: "var(--green)",
},
},
h(
"div",
{ class: "row spread", style: { gap: "8px", flexWrap: "wrap" } },
h(
"div",
{},
h(
"strong",
{ style: { fontSize: "11px" } },
`${importPreview.design.name} (${importPreview.summary.designTier.toUpperCase()})`,
),
h(
"div",
{ class: "dim mono", style: { fontSize: "10px" } },
`Δv ${fmtNum(importPreview.summary.totalDv)} m/s • Cost ${fmtMoney(importPreview.summary.totalCost)} • ${importPreview.summary.stageCount} stage(s)`,
),
importPreview.lockedItems.length > 0
? h(
"div",
{
class: "amber",
style: { fontSize: "10px", marginTop: "3px" },
},
`Warning: ${importPreview.lockedItems.length} locked part(s): ${importPreview.lockedItems.map((l) => `${l.partOrMatName} (${l.techName})`).join(", ")}`,
)
: h(
"div",
{
class: "green",
style: { fontSize: "10px", marginTop: "3px" },
},
"All R&D technologies unlocked for your agency.",
),
),
h(
"button",
{
class: "btn xs primary",
onClick: () =>
loadDesignIntoBuilder(
importPreview.design,
importPreview.design.name || "Imported Rocket",
importPreview.lockedItems,
),
},
"Load Imported Rocket",
),
),
)
: null;
rootWrap.appendChild(
h(
"div",
{ class: "panel", style: { padding: "10px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "11px" } },
"IMPORT SHARE CODE OR JSON",
),
h("div", { style: { marginTop: "6px" } }, importTextArea),
h(
"div",
{
class: "row spread",
style: { marginTop: "6px", flexWrap: "wrap", gap: "8px" },
},
h(
"div",
{ class: "row", style: { gap: "8px", flexWrap: "wrap" } },
fileInput,
h(
"label",
{ class: "row", style: { fontSize: "11px", gap: "4px" } },
saveImportedChk,
h("span", {}, "Also save copy to My Hangar"),
),
),
h(
"button",
{
class: "btn xs primary",
onClick: async () => {
const codeOrJson = importTextArea.value.trim();
if (!codeOrJson) {
toast(
"Paste a share code or choose a JSON file first.",
"warn",
);
return;
}
try {
const res = await api.importDesignBlueprint({
codeOrJson,
saveToHangar: saveImportedChk.checked,
});
if (res.myDesigns) {
myDesigns = res.myDesigns;
if (state.agency) state.agency.savedDesigns = res.myDesigns;
}
renderModalBody({
design: res.design,
shareCode: res.shareCode,
lockedItems: res.lockedItems,
summary: res.summary,
});
} catch (err) {
try {
const localDecoded = decodeRocketShareCode(
codeOrJson,
state.parts,
state.materials,
);
const asm = buildRocket(
localDecoded,
state.parts,
state.materials,
{
priceOf: (p, m) => priceOfPart(ctx, p, m),
difficulty: curAgency(ctx).difficulty,
unlockedTechs: curAgency(ctx).unlockedTechs ?? [],
},
);
renderModalBody({
design: localDecoded,
shareCode: encodeRocketShareCode(localDecoded),
lockedItems: [],
summary: {
totalDv: Math.round(asm.totalDv),
totalCost: Math.round(asm.totalCost),
stageCount: localDecoded.stages.length,
designTier: localDecoded.designTier ?? "basic",
},
});
} catch {
toast((err as Error).message, "err");
}
}
},
},
"Import & Preview",
),
),
previewBox,
),
);
const renderBpSection = (
title: string,
items: SavedRocketBlueprint[],
canDelete: boolean,
) => {
return h(
"div",
{ class: "panel", style: { padding: "10px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "11px" } },
`${title} (${items.length})`,
),
items.length === 0
? h(
"div",
{ class: "dim", style: { fontSize: "11px", marginTop: "6px" } },
"No blueprints stored here yet.",
)
: h(
"div",
{
style: {
display: "flex",
flexDirection: "column",
gap: "6px",
marginTop: "8px",
},
},
...items.map((bp) =>
h(
"div",
{
class: "panel row spread",
style: {
padding: "8px 10px",
gap: "8px",
flexWrap: "wrap",
},
},
h(
"div",
{ style: { minWidth: "220px" } },
h(
"div",
{ style: { fontSize: "12px", fontWeight: "600" } },
`${bp.name} `,
h(
"span",
{ class: "badge info", style: { fontSize: "9px" } },
(bp.designTier ?? "basic").toUpperCase(),
),
bp.isPublic
? h(
"span",
{
class: "badge ok",
style: { fontSize: "9px", marginLeft: "4px" },
},
"PUBLIC",
)
: null,
),
h(
"div",
{ class: "dim mono", style: { fontSize: "10px" } },
`By ${bp.authorAgency} • ${bp.stageCount ?? bp.design.stages.length} stg • Δv ${fmtNum(bp.totalDv ?? 0)} m/s • ${fmtMoney(bp.totalCost ?? 0)}`,
),
bp.notes
? h(
"div",
{ class: "dim", style: { fontSize: "10px" } },
bp.notes,
)
: null,
),
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"button",
{
class: "btn xs primary",
onClick: () =>
loadDesignIntoBuilder(bp.design, bp.name),
},
"Load",
),
h(
"button",
{
class: "btn xs ghost",
onClick: () =>
void copyText(
encodeRocketShareCode(bp.design),
`Copied code for "${bp.name}"!`,
),
},
"Copy Code",
),
canDelete
? h(
"button",
{
class: "btn xs danger",
onClick: async () => {
try {
const res = await api.deleteDesignBlueprint(
bp.id,
);
myDesigns = res.myDesigns;
communityDesigns = res.communityDesigns;
if (state.agency)
state.agency.savedDesigns = res.myDesigns;
toast(`Deleted "${bp.name}".`, "info");
renderModalBody(importPreview);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Delete",
)
: null,
),
),
),
),
);
};
rootWrap.appendChild(renderBpSection("MY AGENCY HANGAR", myDesigns, true));
rootWrap.appendChild(
renderBpSection("SERVER COMMUNITY BLUEPRINTS", communityDesigns, false),
);
};
renderModalBody(null);
try {
const res = await api.getDesigns();
myDesigns = res.myDesigns;
communityDesigns = res.communityDesigns;
renderModalBody(null);
} catch {}
}

View file

@ -0,0 +1,131 @@
// Shared mutable state, context interface, and part pricing/lock helpers for Rocket Builder
// Read the room. Get it? Context? Cus read the room is basically like get the context? No? Ok... I'll see myself out.
import * as THREE from "three";
import { state } from "../../state.js";
import type { RocketMeshHandle } from "../../three/rocketMesh.js";
import type { ManagedView } from "../../three/sceneManager.js";
import {
buildRocket,
getRequiredTechNode,
isPartUnlocked,
validateDesign,
} from "../../../shared/physics.js";
import type {
AgencyState,
CoachDiagnostic,
ContractOffer,
ContractValueEstimate,
DesignReliabilityReport,
MaterialSpec,
MaturityLevel,
MissionTemplate,
Part,
RocketDesign,
Sponsor,
} from "../../../shared/types.js";
export const MATURITY_ORDER: MaturityLevel[] = [
"concept",
"pdr",
"cdr",
"flight-ready",
];
export const MAX_HISTORY_ENTRIES = 50;
export interface HistoryEntry {
snapshot: RocketDesign;
label: string;
at: number;
coalesceKey?: string;
}
export type BuilderTab = "stages" | "payload" | "compliance" | "value";
export interface BuilderDragState {
uid: string;
startHitY: number;
startYBottom: number;
startHitX: number;
startHitZ: number;
startRadial: number;
startGroupPosY: number;
}
export interface BuilderContext {
agency: AgencyState;
contract: ContractOffer | MissionTemplate | null;
sponsor: Sponsor | undefined;
design: RocketDesign;
history: HistoryEntry[];
historyIndex: number;
lastRecordedJson: string;
suppressHistory: boolean;
activeTab: BuilderTab;
activeStageIdx: number;
fairingCutaway: boolean;
showCenters: boolean;
selectedProUid: string | null;
priceMultipliers: Record<string, number>;
viewportEl: HTMLElement;
sidebarEl: HTMLElement;
bodyEl: HTMLElement;
tierBar: HTMLElement;
summaryBar: HTMLElement;
coopBar: HTMLElement;
tabsBar: HTMLElement;
footerBar: HTMLElement;
hudStatsRow: HTMLElement;
undoBtn: HTMLButtonElement;
redoBtn: HTMLButtonElement;
historyBtn: HTMLButtonElement;
proDragHint: HTMLElement;
cgCpBtn: HTMLButtonElement;
view: ManagedView;
dragPlane: THREE.Mesh;
currentMesh: RocketMeshHandle | null;
buildToken: number;
rebuildTimer: ReturnType<typeof setTimeout> | null;
isDragging3D: boolean;
dragState: BuilderDragState | null;
latestValidation: ReturnType<typeof validateDesign> | null;
latestAssembly: ReturnType<typeof buildRocket> | null;
latestReliability: DesignReliabilityReport | null;
latestValueEstimate: ContractValueEstimate | null;
latestCoach: CoachDiagnostic[];
refreshEngineering: (refitCamera?: boolean, immediate?: boolean) => void;
renderSidebarBody: () => void;
renderAll: () => void;
renderTierAndTabs: () => void;
renderSummaryAndCoopBars: () => void;
scheduleRebuild3D: (
asm: ReturnType<typeof buildRocket>,
refitCamera?: boolean,
immediate?: boolean,
) => void;
renderHudOverlay: () => void;
}
export function curAgency(ctx: BuilderContext): AgencyState {
return state.agency ?? ctx.agency;
}
export function partLockTag(ctx: BuilderContext, id: string): string {
const ag = curAgency(ctx);
if (isPartUnlocked(id, ag)) return "";
const node = getRequiredTechNode(id);
return node
? ` [LOCKED: ${node.name} ($${(node.cost / 1e6).toFixed(1)}M)]`
: " [LOCKED]";
}
export function priceOfPart(
ctx: BuilderContext,
part: Part,
material?: MaterialSpec,
): number {
const pm = ctx.priceMultipliers[part.id] ?? 1;
const mm = material
? (ctx.priceMultipliers[`mat:${material.id}`] ?? 1) * material.costFactor
: 1;
return Math.round(part.cost * pm * mm);
}

View file

@ -0,0 +1,526 @@
// Hardware diagnostics panel, one-click quick fixes, and advice
import { api } from "../../api.js";
import { state } from "../../state.js";
import {
createStarterStage,
getDifficultyProfile,
isPartUnlocked,
} from "../../../shared/physics.js";
import type {
AgencyState,
LockedDesignItemInfo,
RocketDesign,
StageDiagnosticItem,
} from "../../../shared/types.js";
import { fmtMoney, h, term, toast } from "../../ui.js";
import { curAgency, type BuilderContext } from "./context.js";
import { recordHistory } from "./history.js";
export function renderDiagnosticsSection(ctx: BuilderContext): void {
const { bodyEl } = ctx;
if (!ctx.latestValidation) return;
const runDiagnosticFix = async (diag: StageDiagnosticItem) => {
const ag = curAgency(ctx);
if (diag.actionKind === "unlock-tech" && diag.techId) {
try {
const res = await api.post<{ agency: AgencyState }>(
"/api/agency/unlock-tech",
{
techId: diag.techId,
},
);
state.agency = res.agency;
toast(`Researched tech for ${diag.title}!`, "ok");
ctx.refreshEngineering(false, true);
ctx.renderAll();
} catch (err) {
toast((err as Error).message, "err");
}
return;
}
if (
diag.actionKind === "swap-part" &&
diag.targetPartOrMatId &&
diag.fallbackId
) {
let changed = false;
const swapInStage = (st: RocketDesign["stages"][number]) => {
if (st.engineId === diag.targetPartOrMatId) {
st.engineId = diag.fallbackId!;
changed = true;
}
if (st.tankId === diag.targetPartOrMatId) {
st.tankId = diag.fallbackId!;
changed = true;
}
if (st.dropTankId === diag.targetPartOrMatId) {
st.dropTankId = diag.fallbackId!;
changed = true;
}
if (st.structureId === diag.targetPartOrMatId) {
st.structureId = diag.fallbackId!;
changed = true;
}
if (st.materialId === diag.targetPartOrMatId) {
st.materialId = diag.fallbackId!;
changed = true;
}
if (st.interstageId === diag.targetPartOrMatId) {
st.interstageId = diag.fallbackId!;
changed = true;
}
};
if (diag.stageIndex != null && ctx.design.stages[diag.stageIndex]) {
swapInStage(ctx.design.stages[diag.stageIndex]);
} else {
ctx.design.stages.forEach(swapInStage);
}
if (ctx.design.fairingId === diag.targetPartOrMatId) {
ctx.design.fairingId = diag.fallbackId;
changed = true;
}
if (ctx.design.computerId === diag.targetPartOrMatId) {
ctx.design.computerId = diag.fallbackId;
changed = true;
}
if (ctx.design.payloadPartId === diag.targetPartOrMatId) {
ctx.design.payloadPartId = diag.fallbackId;
changed = true;
}
for (const pp of ctx.design.proParts ?? []) {
if (pp.partId === diag.targetPartOrMatId) {
pp.partId = diag.fallbackId;
changed = true;
}
if (pp.materialId === diag.targetPartOrMatId) {
pp.materialId = diag.fallbackId;
changed = true;
}
}
if (changed) {
recordHistory(ctx, `Swap locked component -> ${diag.fallbackId}`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
toast("Swapped to unlocked fallback component.", "ok");
}
return;
}
if (diag.actionKind === "auto-pair-tank") {
const sIdx = diag.stageIndex ?? ctx.activeStageIdx;
const st = ctx.design.stages[sIdx];
if (!st) return;
const eng = state.parts.find((p) => p.id === st.engineId);
const tanks = state.parts.filter(
(p) => p.kind === "tank" && !p.isDropTank,
);
const compat =
tanks.find(
(t) =>
t.propellantType === eng?.propellantType &&
isPartUnlocked(t.id, ag),
) ?? tanks.find((t) => t.propellantType === eng?.propellantType);
if (compat) {
st.tankId = compat.id;
ctx.activeStageIdx = sIdx;
ctx.activeTab = "stages";
recordHistory(ctx, `Auto-pair tank on Stage ${sIdx + 1}`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
toast(`Paired ${compat.name} to Stage ${sIdx + 1}.`, "ok");
}
return;
}
if (diag.actionKind === "enable-fins") {
const sIdx = diag.stageIndex ?? 0;
if (ctx.design.stages[sIdx]) {
ctx.design.stages[sIdx].hasFins = true;
ctx.activeStageIdx = sIdx;
ctx.activeTab = "stages";
recordHistory(ctx, `Enable Stage ${sIdx + 1} fins`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
toast(`Enabled aerodynamic fins on Stage ${sIdx + 1}.`, "ok");
}
return;
}
if (diag.actionKind === "add-stage") {
if (ctx.design.stages.length < 4) {
ctx.design.stages.push(createStarterStage("upper"));
ctx.activeStageIdx = ctx.design.stages.length - 1;
ctx.activeTab = "stages";
recordHistory(ctx, "Add upper stage (quick-fix)");
ctx.refreshEngineering(true, true);
ctx.renderAll();
toast(`Added Stage ${ctx.design.stages.length} for extra Δv.`, "ok");
}
return;
}
if (diag.actionKind === "select-computer") {
const computers = state.parts
.filter((p) => p.kind === "computer" && isPartUnlocked(p.id, ag))
.sort(
(a, b) =>
(b.computeCapacityIps ?? 100) - (a.computeCapacityIps ?? 100),
);
const best = computers[0];
if (best && best.id !== ctx.design.computerId) {
ctx.design.computerId = best.id;
if (ctx.design.designTier === "pro" && ctx.design.proParts) {
const ex = ctx.design.proParts.find((p) => p.role === "computer");
if (ex) {
ex.partId = best.id;
ex.diameter = best.diameter;
ex.length = best.length;
} else {
ctx.design.proParts.push({
uid: `pro-comp-${Date.now()}`,
role: "computer",
partId: best.id,
stageIndex: Math.max(0, ctx.design.stages.length - 1),
yBottom: Math.max(
0.5,
(ctx.latestAssembly?.fairingY ?? 20) - 0.6,
),
radialOffset: 0,
radialAngleDeg: 0,
symmetry: 1,
diameter: best.diameter,
length: best.length,
});
}
}
recordHistory(ctx, `Select flight computer ${best.name}`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
toast(`Installed ${best.name}.`, "ok");
} else {
ctx.activeTab = "payload";
ctx.renderAll();
toast("Opened Fairing, Payload & Avionics tab.", "info");
}
return;
}
if (diag.actionKind === "waive-rule" && diag.ruleId) {
const waived = new Set(ctx.design.waivedRuleIds ?? []);
if (!waived.has(diag.ruleId)) {
waived.add(diag.ruleId);
ctx.design.waivedRuleIds = Array.from(waived);
recordHistory(ctx, `Grant compliance waiver ${diag.code}`);
ctx.refreshEngineering(false, true);
ctx.renderAll();
toast(`Waived ${diag.code} (${diag.title}).`, "warn");
}
return;
}
if (diag.actionKind === "jump-stage") {
if (diag.stageIndex != null && ctx.design.stages[diag.stageIndex]) {
ctx.activeStageIdx = diag.stageIndex;
ctx.activeTab = "stages";
} else if (
diag.locationLabel.includes("Fairing") ||
diag.locationLabel.includes("Avionics")
) {
ctx.activeTab = "payload";
} else {
ctx.activeTab = "compliance";
}
ctx.renderAll();
}
};
const lockedItemsList = ctx.latestValidation.lockedItems ?? [];
const diagItems = ctx.latestValidation.stageDiagnostics ?? [];
if (diagItems.length > 0 || lockedItemsList.length > 0) {
const ag = curAgency(ctx);
const lockByPartStage = new Map<string, LockedDesignItemInfo>();
for (const li of lockedItemsList) {
lockByPartStage.set(`${li.partOrMatId}:${li.stageIndex ?? -1}`, li);
}
const errCount = diagItems.filter((d) => d.severity === "error").length;
const warnCount = diagItems.filter((d) => d.severity === "warn").length;
bodyEl.appendChild(
h(
"div",
{
class: "panel",
style: {
padding: "10px",
marginBottom: "8px",
borderColor: errCount > 0 ? "var(--red)" : "var(--amber)",
},
},
h(
"div",
{ class: "row spread" },
h(
"strong",
{
class: `${errCount > 0 ? "red" : "amber"} mono`,
style: { fontSize: "11px" },
},
`STAGE & HARDWARE DIAGNOSTICS (${errCount} ERR • ${warnCount} WARN)`,
),
h(
"span",
{ class: "dim mono", style: { fontSize: "10px" } },
`${lockedItemsList.length} locked R&D`,
),
),
...diagItems.slice(0, 12).map((diag) => {
const lockMeta = diag.targetPartOrMatId
? lockByPartStage.get(
`${diag.targetPartOrMatId}:${diag.stageIndex ?? -1}`,
)
: undefined;
const repMet = lockMeta
? (ag.reputation ?? 0) >= lockMeta.techMinReputation
: true;
const canAfford = lockMeta ? ag.treasury >= lockMeta.techCost : true;
return h(
"div",
{
class: "panel",
style: {
padding: "6px 8px",
marginTop: "6px",
borderColor:
diag.severity === "error"
? "rgba(239,68,68,0.45)"
: "rgba(245,158,11,0.45)",
},
},
h(
"div",
{ class: "row spread", style: { gap: "6px", flexWrap: "wrap" } },
h(
"div",
{ class: "row", style: { gap: "6px", flexWrap: "wrap" } },
h(
"span",
{
class: `badge ${diag.severity === "error" ? "err" : "warn"}`,
style: { fontSize: "9px" },
},
diag.locationLabel,
),
h(
"span",
{ class: "mono dim", style: { fontSize: "10px" } },
diag.code,
),
h("strong", { style: { fontSize: "11px" } }, diag.title),
),
diag.stageIndex != null &&
ctx.design.stages[diag.stageIndex] &&
ctx.design.designTier !== "pro" &&
diag.actionKind !== "jump-stage"
? h(
"button",
{
class: "btn xs ghost",
onClick: () => {
ctx.activeStageIdx = diag.stageIndex!;
ctx.activeTab = "stages";
ctx.renderAll();
},
},
`Go Stage ${diag.stageIndex + 1}`,
)
: null,
),
h(
"div",
{ class: "dim", style: { fontSize: "11px", marginTop: "3px" } },
diag.detail,
),
h(
"div",
{
class: "row",
style: { gap: "6px", marginTop: "5px", flexWrap: "wrap" },
},
diag.actionKind
? h(
"button",
{
class: `btn xs ${diag.actionKind === "waive-rule" ? "ghost" : "primary"}`,
disabled:
diag.actionKind === "unlock-tech" &&
(!repMet || !canAfford),
title:
diag.actionKind === "unlock-tech" && !repMet
? `Requires ${lockMeta?.techMinReputation} Reputation`
: diag.actionKind === "unlock-tech" && !canAfford
? "Insufficient treasury"
: undefined,
onClick: () => void runDiagnosticFix(diag),
},
diag.actionLabel ?? "Fix",
)
: null,
lockMeta?.fallbackUnlockedId
? h(
"button",
{
class: "btn xs selected",
onClick: () =>
void runDiagnosticFix({
...diag,
actionKind: "swap-part",
fallbackId: lockMeta.fallbackUnlockedId,
}),
},
`Swap → ${lockMeta.fallbackUnlockedName ?? lockMeta.fallbackUnlockedId}`,
)
: null,
),
);
}),
diagItems.length > 12
? h(
"div",
{ class: "dim", style: { fontSize: "10px", marginTop: "6px" } },
`+ ${diagItems.length - 12} more items in NASA CML / TRL tab.`,
)
: null,
),
);
}
if (ctx.latestReliability) {
const sfFee = Math.max(
450_000,
Math.round((ctx.latestAssembly?.totalCost ?? 0) * 0.04),
);
bodyEl.appendChild(
h(
"div",
{ class: "panel", style: { padding: "8px 10px", marginBottom: "8px" } },
h(
"div",
{ class: "row spread" },
h(
"span",
{ class: "mono", style: { fontSize: "10px" } },
term("REL:", "reliability_risk"),
` ${ctx.latestReliability.reliabilityPct.toFixed(1)}% • Defect Risk ${ctx.latestReliability.anomalyRiskPct.toFixed(1)}%${ctx.latestReliability.staticFired ? " (STATIC FIRED)" : ""}`,
),
h(
"button",
{
class: `btn xs ${ctx.latestReliability.staticFired ? "ghost" : "primary"}`,
disabled: ctx.latestReliability.staticFired,
onClick: async () => {
try {
const res = await api.post<{
fee: number;
agency: AgencyState;
}>("/api/agency/static-fire", {
design: ctx.design,
});
state.agency = res.agency;
toast(
`Static fire verified (-${fmtMoney(res.fee)}). Defect risk reduced by 8%.`,
"ok",
);
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
} catch (err) {
toast((err as Error).message, "err");
}
},
},
ctx.latestReliability.staticFired
? "Static Fired OK"
: `Static Fire (${fmtMoney(sfFee)})`,
),
),
),
);
}
if (ctx.latestCoach.length > 0) {
const prof = getDifficultyProfile(curAgency(ctx).difficulty);
const headerTitle =
prof.coachMode === "explorer"
? "EXPLORER MISSION COACH"
: prof.coachMode === "encyclopedia"
? "AEROSPACE ENCYCLOPEDIA"
: "FLIGHT DIRECTOR TELEMETRY";
bodyEl.appendChild(
h(
"div",
{
class: "panel",
style: {
padding: "8px 10px",
marginBottom: "8px",
borderColor: "var(--sim-accent-dim)",
},
},
h(
"div",
{
class: "mono accent",
style: { fontSize: "10px", fontWeight: "700", marginBottom: "4px" },
},
headerTitle,
),
...ctx.latestCoach
.slice(0, 2)
.map((c) =>
h(
"div",
{
style: {
fontSize: "11px",
marginTop: "4px",
paddingTop: "4px",
borderTop: "1px solid var(--border)",
},
},
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"span",
{
class: `badge ${c.severity === "critical" ? "err" : c.severity === "warn" ? "warn" : "info"}`,
},
c.conceptTag ?? c.code,
),
h("strong", {}, c.title),
),
h(
"div",
{
class: "dim",
style: { lineHeight: "1.35", marginTop: "2px" },
},
c.explanation,
),
c.formula
? h(
"div",
{
class: "mono accent",
style: { fontSize: "10px", marginTop: "2px" },
},
c.formula,
)
: null,
h(
"div",
{
class: "mono",
style: {
fontSize: "10px",
color: "var(--green)",
marginTop: "2px",
},
},
`Tip: ${c.actionHint}`,
),
),
),
),
);
}
}

View file

@ -0,0 +1,337 @@
// Rocket Builder tier selector, tabs, evaluation pipeline, summary vicodins, and co-op thingies
import { api } from "../../api.js";
import { state } from "../../state.js";
import {
buildRocket,
computeDesignReliability,
convertStagesToProParts,
createDefaultTeamStations,
estimateContractValue,
generateCoachDiagnostics,
TEAM_STATION_DEFS,
validateDesign,
} from "../../../shared/physics.js";
import type {
AgencyState,
DesignTier,
MaterialSpec,
Part,
TeamStationId,
} from "../../../shared/types.js";
import { clear, fmtMoney, h, term, toast } from "../../ui.js";
import { curAgency, priceOfPart, type BuilderContext } from "./context.js";
export function renderTierAndTabs(ctx: BuilderContext): void {
clear(ctx.tierBar);
ctx.tierBar.appendChild(
h(
"span",
{ class: "mono dim", style: { fontSize: "10px", marginRight: "auto" } },
term("FIDELITY TIER", "design_tier"),
),
);
(["casual", "standard", "expert", "pro"] as DesignTier[]).forEach((t) => {
ctx.tierBar.appendChild(
h(
"button",
{
class: `btn xs ${ctx.design.designTier === t ? "selected" : "ghost"}`,
onClick: () => {
ctx.design.designTier = t;
if (t === "pro") {
if (!ctx.design.proParts || ctx.design.proParts.length === 0) {
ctx.design.proParts = convertStagesToProParts(
ctx.design,
state.parts,
);
}
if (!ctx.selectedProUid && ctx.design.proParts.length > 0) {
ctx.selectedProUid = ctx.design.proParts[0].uid;
}
if (ctx.activeTab === "stages") ctx.showCenters = true;
}
ctx.proDragHint.style.display =
t === "pro" ? "inline-flex" : "none";
ctx.cgCpBtn.textContent = ctx.showCenters
? "CG / CP: ON"
: "CG / CP: OFF";
ctx.cgCpBtn.classList.toggle("selected", ctx.showCenters);
ctx.cgCpBtn.classList.toggle("ghost", !ctx.showCenters);
ctx.refreshEngineering(false, true);
ctx.renderAll();
},
},
t === "pro" ? "PRO" : t.toUpperCase(),
),
);
});
clear(ctx.tabsBar);
const tabs: Array<{ id: typeof ctx.activeTab; label: string }> = [
{
id: "stages",
label:
ctx.design.designTier === "pro"
? `Pro Assembly (${ctx.design.proParts?.length ?? 0})`
: `Stages (${ctx.design.stages.length})`,
},
{
id: "payload",
label:
ctx.design.designTier === "pro"
? "Aero & Payload"
: "Fairing & Payload",
},
{ id: "compliance", label: "NASA CML / TRL" },
{ id: "value", label: "Contract & Value" },
];
for (const tb of tabs) {
ctx.tabsBar.appendChild(
h(
"button",
{
class: ctx.activeTab === tb.id ? "active" : "",
onClick: () => {
ctx.activeTab = tb.id;
ctx.renderAll();
},
},
tb.label,
),
);
}
}
export function evaluateNow(ctx: BuilderContext): void {
const priceOf = (part: Part, material?: MaterialSpec) =>
priceOfPart(ctx, part, material);
if (ctx.design.designTier === "pro" && ctx.design.proParts) {
const fPart = ctx.design.proParts.find((p) => p.role === "fairing");
const pPart = ctx.design.proParts.find((p) => p.role === "payload");
const lPart = ctx.design.proParts.find((p) => p.role === "las");
const cPart = ctx.design.proParts.find((p) => p.role === "computer");
ctx.design.fairingId = fPart ? fPart.partId : "";
ctx.design.payloadPartId = pPart ? pPart.partId : null;
ctx.design.hasLaunchAbort = !!lPart;
if (cPart) ctx.design.computerId = cPart.partId;
}
const effectiveMission = ctx.contract
? {
...ctx.contract,
payloadMass:
ctx.contract.payloadMass +
(ctx.contract.crewed && ctx.agency?.crewConfig
? ctx.agency.crewConfig.crewSize *
(85 + 15 * ctx.agency.crewConfig.lifeSupport) +
500 * ctx.agency.crewConfig.lifeSupport
: 0),
}
: null;
ctx.latestAssembly = buildRocket(ctx.design, state.parts, state.materials, {
priceOf,
mission: effectiveMission,
difficulty: curAgency(ctx).difficulty,
weather: state.world?.weather ?? "nominal",
unlockedTechs: curAgency(ctx).unlockedTechs ?? [],
});
ctx.latestValidation = validateDesign(
ctx.design,
state.parts,
state.materials,
{
mission: effectiveMission,
simTime: state.world?.simTime ?? 0,
weather: state.world?.weather ?? "nominal",
activeHazards: state.world?.activeHazards ?? [],
unlockedTechs: curAgency(ctx).unlockedTechs ?? [],
difficulty: curAgency(ctx).difficulty,
waiverCostMult: ctx.sponsor?.waiverCostMult ?? 1.0,
crewedSeats: curAgency(ctx).crewConfig?.crewSize ?? 0,
eclssLevel: curAgency(ctx).crewConfig?.lifeSupport ?? 0,
priceOf,
},
);
ctx.latestReliability = computeDesignReliability(
ctx.design,
ctx.latestAssembly,
curAgency(ctx),
);
ctx.latestValueEstimate = estimateContractValue(
ctx.design,
ctx.latestAssembly,
ctx.latestValidation,
{
mission: effectiveMission,
difficulty: curAgency(ctx).difficulty,
sponsorReputationMult: ctx.sponsor?.reputationMult ?? 1.0,
staticFired: false,
launchInsured: !!curAgency(ctx).launchInsured,
anomalyRiskPct: ctx.latestReliability.anomalyRiskPct,
},
);
ctx.latestCoach = generateCoachDiagnostics(
ctx.design,
ctx.latestAssembly,
ctx.latestValidation,
effectiveMission,
curAgency(ctx).difficulty,
);
}
export function renderSummaryAndCoopBars(ctx: BuilderContext): void {
clear(ctx.summaryBar);
const val = ctx.latestValueEstimate;
const bus = ctx.latestAssembly?.spacecraftBus;
const reqSig = ctx.contract?.minSignalHealthPct ?? 60;
const reqPwr = ctx.contract?.minPowerMarginPct ?? 10;
const sigCls = bus
? bus.signalHealthPct >= reqSig
? "green"
: bus.signalHealthPct >= reqSig - 10
? "amber"
: "red"
: "dim";
const pwrCls = bus
? bus.powerMarginPct >= reqPwr
? "green"
: bus.powerMarginPct >= 0
? "amber"
: "red"
: "dim";
const gradeCls =
bus?.efficiencyGrade === "S" || bus?.efficiencyGrade === "A"
? "green"
: bus?.efficiencyGrade === "B"
? "accent"
: bus?.efficiencyGrade === "C"
? "amber"
: "red";
const profitCls = val
? val.projectedNetProfitNominal >= 0
? "green"
: "red"
: "dim";
ctx.summaryBar.append(
h(
"div",
{ class: "spread", style: { gap: "8px" } },
h(
"span",
{
class: "mono",
style: {
fontSize: "10px",
fontWeight: "700",
color: ctx.contract ? "var(--brand-blue)" : "var(--text-dim)",
},
},
ctx.contract
? `${ctx.contract.name} • ${ctx.contract.targetName}${ctx.contract.isConvoluted ? " [CONVOLUTED]" : ""}`
: "Sandbox / Free-Flight Test Stand (No Active Contract)",
),
h(
"button",
{
class: `btn xs ${ctx.activeTab === "value" ? "selected" : "ghost"}`,
onClick: () => {
ctx.activeTab = "value";
ctx.renderAll();
},
},
"Value Chart →",
),
),
h(
"div",
{ class: "summary-pills" },
ctx.contract && val
? h("span", {}, `Budget: ${fmtMoney(ctx.contract.budget)}`)
: null,
val
? h(
"span",
{ class: profitCls },
`Net EV: ${fmtMoney(val.projectedNetProfitNominal)}`,
)
: null,
bus
? h(
"span",
{ class: gradeCls },
`Eff ${bus.efficiencyGrade} (${bus.efficiencyScore})`,
)
: null,
bus ? h("span", { class: sigCls }, `Sig ${bus.signalHealthPct}%`) : null,
bus
? h(
"span",
{ class: pwrCls },
`Pwr ${bus.powerMarginPct >= 0 ? "+" : ""}${bus.powerMarginPct}%`,
)
: null,
bus
? h("span", { class: "dim" }, `${fmtMoney(bus.costPerKgPayload)}/kg`)
: null,
),
);
clear(ctx.coopBar);
const ag = curAgency(ctx);
const stations = ag.teamStations ?? createDefaultTeamStations();
const readyCount = TEAM_STATION_DEFS.filter(
(d) => stations[d.id]?.ready,
).length;
ctx.coopBar.appendChild(
h(
"span",
{ class: "mono dim", style: { fontSize: "9px", marginRight: "4px" } },
`CO-OP (${readyCount}/4)`,
),
);
for (const def of TEAM_STATION_DEFS) {
const st = stations[def.id] ?? {
stationId: def.id as TeamStationId,
title: def.title,
operatorName: "Unassigned",
ready: false,
updatedAt: 0,
};
const cls = st.ready
? "ready"
: st.operatorName !== "Unassigned"
? "occupied"
: "";
const shortOp =
st.operatorName === "Unassigned" ? "OPEN" : st.operatorName.slice(0, 10);
ctx.coopBar.appendChild(
h(
"button",
{
class: `station-pill ${cls}`,
title: `${def.title}: ${def.scope} (Click to claim / toggle Ready)`,
onClick: async () => {
try {
const opName = state.account?.name || ag.name;
const nextReady = st.operatorName === opName ? !st.ready : false;
const res = await api.post<{
teamStations: AgencyState["teamStations"];
agency: AgencyState;
}>("/api/agency/station", {
stationId: def.id,
operatorName: opName,
ready: nextReady,
});
if (state.agency) state.agency.teamStations = res.teamStations;
renderSummaryAndCoopBars(ctx);
toast(
`${def.title}: ${opName} (${nextReady ? "READY" : "ACTIVE"})`,
"info",
);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
`${def.id.toUpperCase()}: ${shortOp} ${st.ready ? "✓" : "○"}`,
),
);
}
}

View file

@ -0,0 +1,169 @@
// Undo/redo timeline history and restore modal for Rocket Builder
// Everything needs an undo button
import { state } from "../../state.js";
import { normalizeDesign } from "../../../shared/physics.js";
import { h, modal, toast } from "../../ui.js";
import { MAX_HISTORY_ENTRIES, type BuilderContext } from "./context.js";
export function updateHistoryButtons(ctx: BuilderContext): void {
ctx.undoBtn.disabled = ctx.historyIndex <= 0;
ctx.redoBtn.disabled = ctx.historyIndex >= ctx.history.length - 1;
ctx.historyBtn.textContent = `History (${ctx.historyIndex + 1}/${ctx.history.length})`;
}
export function recordHistory(
ctx: BuilderContext,
label: string,
coalesceKey?: string,
): void {
if (ctx.suppressHistory) return;
const serialized = JSON.stringify(ctx.design);
if (serialized === ctx.lastRecordedJson) return;
const now = Date.now();
const snap = structuredClone(ctx.design);
if (ctx.historyIndex < ctx.history.length - 1) {
ctx.history = ctx.history.slice(0, ctx.historyIndex + 1);
}
const top = ctx.history[ctx.historyIndex];
if (coalesceKey && top?.coalesceKey === coalesceKey && now - top.at < 950) {
top.snapshot = snap;
top.at = now;
if (label && label !== "Adjust vehicle parameters") top.label = label;
} else {
ctx.history.push({ snapshot: snap, label, at: now, coalesceKey });
if (ctx.history.length > MAX_HISTORY_ENTRIES) {
ctx.history.shift();
}
ctx.historyIndex = ctx.history.length - 1;
}
ctx.lastRecordedJson = serialized;
updateHistoryButtons(ctx);
}
export function applyHistoryIndex(ctx: BuilderContext, idx: number): void {
if (idx < 0 || idx >= ctx.history.length) return;
ctx.suppressHistory = true;
try {
ctx.historyIndex = idx;
ctx.design = normalizeDesign(
structuredClone(ctx.history[idx].snapshot),
state.parts,
state.materials,
);
if (ctx.activeStageIdx >= ctx.design.stages.length) {
ctx.activeStageIdx = Math.max(0, ctx.design.stages.length - 1);
}
ctx.lastRecordedJson = JSON.stringify(ctx.design);
ctx.renderAll();
} finally {
ctx.suppressHistory = false;
updateHistoryButtons(ctx);
}
}
export function undoEdit(ctx: BuilderContext): void {
if (ctx.historyIndex <= 0) return;
const label = ctx.history[ctx.historyIndex]?.label ?? "edit";
applyHistoryIndex(ctx, ctx.historyIndex - 1);
toast(`Undid: ${label}`, "info");
}
export function redoEdit(ctx: BuilderContext): void {
if (ctx.historyIndex >= ctx.history.length - 1) return;
applyHistoryIndex(ctx, ctx.historyIndex + 1);
toast(`Redid: ${ctx.history[ctx.historyIndex]?.label ?? "edit"}`, "info");
}
export function openHistoryModal(ctx: BuilderContext): void {
const listWrap = h("div", {
style: {
maxHeight: "55vh",
overflowY: "auto",
display: "flex",
flexDirection: "column",
gap: "6px",
},
});
const entriesDesc = ctx.history
.map((entry, idx) => ({ entry, idx }))
.reverse();
for (const { entry, idx } of entriesDesc) {
const isCurrent = idx === ctx.historyIndex;
const isFuture = idx > ctx.historyIndex;
listWrap.appendChild(
h(
"div",
{
class: "panel row spread",
style: {
padding: "8px 10px",
borderColor: isCurrent ? "var(--brand-blue)" : "var(--border)",
opacity: isFuture ? "0.62" : "1",
gap: "8px",
},
},
h(
"div",
{},
h(
"div",
{
class: "mono",
style: {
fontSize: "11px",
fontWeight: isCurrent ? "700" : "500",
},
},
`#${idx + 1} ${entry.label}${isCurrent ? " (Current)" : isFuture ? " (Undone)" : ""}`,
),
h(
"div",
{ class: "dim", style: { fontSize: "10px" } },
`${new Date(entry.at).toLocaleTimeString()} • ${entry.snapshot.stages.length} stage(s) • Tier: ${entry.snapshot.designTier ?? "basic"}`,
),
),
h(
"button",
{
class: `btn xs ${isCurrent ? "selected" : "primary"}`,
disabled: isCurrent,
onClick: () => {
applyHistoryIndex(ctx, idx);
m.close();
toast(
`Restored ctx.history step #${idx + 1}: ${entry.label}`,
"info",
);
},
},
isCurrent ? "Active" : "Restore",
),
),
);
}
const m = modal(
"Editor History Timeline",
h(
"div",
{},
h(
"p",
{ class: "dim", style: { fontSize: "12px", marginBottom: "10px" } },
"Click any checkpoint to jump cleanly across your edits (up to 50 recent checkpoints). Keyboard shortcuts: Ctrl+Z / Ctrl+Y.",
),
listWrap,
),
[
{
label: "Undo",
kind: "ghost",
onClick: () => {
undoEdit(ctx);
m.close();
},
},
{ label: "Close", kind: "primary" },
],
);
m.el.style.maxWidth = "560px";
}

View file

@ -0,0 +1,733 @@
// Rocket Builder Avionics, Aero profile, Fairing, Payload, and Spacecraft Bus tab
import { state } from "../../state.js";
import {
createDefaultSpacecraftConfig,
GROUND_NETWORK_SPECS,
SCIENCE_INSTRUMENTS,
SPACECRAFT_COMMS_SYSTEMS,
SPACECRAFT_POWER_SYSTEMS,
} from "../../../shared/physics.js";
import type { GroundNetworkTier } from "../../../shared/types.js";
import { fmtMoney, fmtNum, h, term } from "../../ui.js";
import { partLockTag, type BuilderContext } from "./context.js";
export function renderPayloadTab(ctx: BuilderContext): void {
const { bodyEl, contract } = ctx;
const lockTag = (id: string) => partLockTag(ctx, id);
const fairings = state.parts.filter((p) => p.kind === "fairing");
const payloads = state.parts.filter((p) => p.kind === "payload");
const computers = state.parts.filter((p) => p.kind === "computer");
const aero = ctx.latestAssembly!.aero;
const compPart = ctx.latestAssembly?.computerPart;
const baseLoad = Math.round(ctx.latestAssembly?.computeLoadBasePct ?? 0);
const peakLoad = Math.round(ctx.latestAssembly?.peakComputeLoadEstPct ?? 0);
const diagTier = ctx.latestAssembly?.effectiveDiagnosticTier ?? 1;
const compSel = h(
"select",
{
class: "input",
onChange: () => {
ctx.design.computerId = compSel.value;
if (ctx.design.designTier === "pro" && ctx.design.proParts) {
const idx = ctx.design.proParts.findIndex(
(p) => p.role === "computer",
);
const part = state.parts.find((p) => p.id === compSel.value);
if (part) {
if (idx >= 0) {
ctx.design.proParts[idx].partId = part.id;
} else {
ctx.design.proParts.push({
uid: `pro-comp-${Date.now()}`,
role: "computer",
partId: part.id,
stageIndex: Math.max(0, ctx.design.stages.length - 1),
yBottom: Math.max(
0.5,
(ctx.latestAssembly?.fairingY ?? 20) - 0.6,
),
radialOffset: 0,
radialAngleDeg: 0,
symmetry: 1,
diameter: part.diameter,
length: part.length,
});
}
}
}
ctx.refreshEngineering(true, true);
ctx.renderSidebarBody();
},
},
h(
"option",
{ value: "", selected: !ctx.design.computerId },
"— None Attached (Fails AVN-01 Compliance) —",
),
...computers.map((c) =>
h(
"option",
{ value: c.id, selected: c.id === ctx.design.computerId },
`${c.name} (${c.computeCapacityIps ?? 100} MIPS • Rad-Hard L${c.radHardeningLevel ?? 1} • Scrub ${Math.round((c.faultScrubRate ?? 0) * 100)}%)${lockTag(c.id)}`,
),
),
);
const computerCard = h(
"div",
{
class: "stage-card active",
style: {
marginBottom: "10px",
borderColor:
!compPart || peakLoad > 125
? "var(--red)"
: peakLoad > 95
? "var(--amber)"
: "var(--brand-blue)",
},
},
h(
"div",
{ class: "spread" },
h("h3", {}, term("Flight Computer & Avionics Core", "flight_computer")),
h(
"span",
{
class: `badge ${peakLoad > 125 ? "err" : peakLoad > 95 ? "warn" : "ok"}`,
},
`DIAG TIER ${diagTier}`,
),
),
h(
"div",
{ class: "slot-group" },
h("label", { class: "field" }, "Flight Computer Hardware", compSel),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Compute Load (Nominal / Max-Q Peak)", "cpu_load"),
),
h(
"span",
{
class: `v ${peakLoad > 125 ? "red" : peakLoad > 95 ? "amber" : "green"}`,
},
`${baseLoad}% / ${peakLoad}%`,
),
),
compPart
? h(
"div",
{ class: "col", style: { gap: "2px", fontSize: "11px" } },
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Radiation Hardening & Scrubbing", "rad_hardening"),
),
h(
"span",
{ class: "v" },
`L${compPart.radHardeningLevel ?? 1} (${Math.round((compPart.faultScrubRate ?? 0) * 100)}% EDAC scrub)`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Avionics Power / Thermal Cap"),
h(
"span",
{ class: "v" },
`${compPart.powerDrawKw ?? 0.5} kW • ${compPart.maxTempK ?? 400} K`,
),
),
)
: h(
"p",
{ class: "red mono", style: { fontSize: "11px" } },
"CRITICAL: Vehicle has no Flight Computer! Select avionics above to enable GNC & pass AVN-01.",
),
);
bodyEl.appendChild(computerCard);
const activeHazards = state.world?.activeHazards ?? [];
if (activeHazards.length > 0) {
bodyEl.appendChild(
h(
"div",
{
class: "panel",
style: {
padding: "10px",
marginBottom: "10px",
borderColor: "var(--amber)",
},
},
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h(
"h3",
{},
term("Active Pre-Launch Hazard Advisory", "space_weather"),
),
h("span", { class: "badge warn" }, `${activeHazards.length} ACTIVE`),
),
...activeHazards.map((hz) =>
h(
"div",
{ style: { fontSize: "11px", marginTop: "4px" } },
h(
"div",
{ class: "amber mono", style: { fontWeight: "700" } },
`${hz.title} (${hz.altMinKm}–${hz.altMaxKm} km)`,
),
h("div", { class: "dim" }, hz.countermeasureHint),
),
),
),
);
}
const aeroCard = h(
"div",
{ class: "stage-card active", style: { marginBottom: "10px" } },
h("h3", {}, term("Shape-Based Aerodynamic Profile", "fineness")),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Projected Frontal Area"),
h("span", { class: "v" }, `${aero.frontalAreaM2.toFixed(2)} m²`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Base Zero-Lift Cd"),
h(
"span",
{ class: `v ${aero.baseCd <= 0.42 ? "green" : "amber"}` },
aero.baseCd.toFixed(3),
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Step / Frustum Penalty"),
h("span", { class: "v" }, `+${aero.stepPenaltyCd.toFixed(3)} Cd`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Radial Interference Drag"),
h("span", { class: "v" }, `+${aero.radialInterferenceCd.toFixed(3)} Cd`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Nose Fineness / Shroud", "fairing")),
h(
"span",
{ class: `v ${aero.hasExposedBluntNose ? "red" : "green"}` },
aero.hasExposedBluntNose
? "EXPOSED BLUNT NOSE (+0.44 Cd)"
: `${aero.noseFinenessRatio.toFixed(2)} L/D Fairing`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Fin Restoring Moment", "grid_fins")),
h("span", { class: "v" }, `${fmtNum(aero.finRestoringMoment)} N·m/rad`),
),
);
bodyEl.appendChild(aeroCard);
if (ctx.design.designTier === "pro") {
const massInput = h("input", {
type: "number",
class: "input",
min: 0,
max: 150000,
step: 100,
value: ctx.design.payloadMass,
onInput: () => {
ctx.design.payloadMass = Math.max(0, Number(massInput.value) || 0);
ctx.refreshEngineering(false, false);
},
});
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active" },
h("h3", {}, "Pro Payload & Mission Mass"),
h(
"div",
{ class: "dim", style: { fontSize: "11px", marginBottom: "6px" } },
"In Pro mode, mount or reposition Fairings, Payloads, and LAS Towers inside the Pro Assembly tab.",
),
h("label", { class: "field" }, "Payload Mass Override (kg)", massInput),
contract
? h(
"div",
{ class: "mono dim", style: { fontSize: "10px" } },
`Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`,
)
: null,
),
);
renderSpacecraftBusSection(ctx);
return;
}
const fairingSel = h(
"select",
{
class: "input",
onChange: () => {
ctx.design.fairingId = fairingSel.value;
ctx.refreshEngineering(true, true);
ctx.renderSidebarBody();
},
},
...fairings.map((f) =>
h(
"option",
{ value: f.id, selected: f.id === ctx.design.fairingId },
`${f.name} (Max Payload Ø ${f.maxPayloadDiameter ?? f.diameter}m, Max-Q ${(f.maxQ ?? 55000) / 1000} kPa)${lockTag(f.id)}`,
),
),
);
const payloadSel = h(
"select",
{
class: "input",
onChange: () => {
ctx.design.payloadPartId = payloadSel.value;
const p = payloads.find((x) => x.id === payloadSel.value);
if (p) ctx.design.payloadMass = p.dryMass;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...payloads.map((p) =>
h(
"option",
{ value: p.id, selected: p.id === ctx.design.payloadPartId },
`${p.name} (${fmtNum(p.dryMass)} kg${p.crewedCapable ? ", CREWED" : ""})`,
),
),
);
const lasChk = h("input", {
type: "checkbox",
checked: !!ctx.design.hasLaunchAbort,
onChange: () => {
ctx.design.hasLaunchAbort = lasChk.checked;
ctx.refreshEngineering(true, true);
ctx.renderSidebarBody();
},
});
const contractMassInput = h("input", {
type: "number",
class: "input",
min: 0,
max: 150000,
step: 100,
value: ctx.design.payloadMass,
onInput: () => {
ctx.design.payloadMass = Math.max(
0,
Number(contractMassInput.value) || 0,
);
ctx.refreshEngineering(false, false);
},
});
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active" },
h("h3", {}, "Fairing & NASA Spacecraft Integration"),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
term("Payload Fairing Shroud", "fairing"),
fairingSel,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
"NASA 3D Spacecraft / Capsule",
payloadSel,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
"Payload Bus Mass (kg)",
contractMassInput,
),
contract
? h(
"div",
{ class: "mono dim", style: { fontSize: "10px" } },
`Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`,
)
: null,
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "row", style: { cursor: "pointer", fontSize: "12px" } },
lasChk,
term(
"Mount Launch Abort Escape Tower (+1,400 kg, mandatory for crewed missions)",
"las",
),
),
),
),
);
renderSpacecraftBusSection(ctx);
}
export function renderSpacecraftBusSection(ctx: BuilderContext): void {
const { bodyEl, contract } = ctx;
if (!ctx.design.spacecraftConfig) {
ctx.design.spacecraftConfig = createDefaultSpacecraftConfig(contract);
}
const sc = ctx.design.spacecraftConfig;
const bus = ctx.latestAssembly?.spacecraftBus;
if (!bus) return;
const pwrSel = h(
"select",
{
class: "input",
onChange: () => {
sc.powerSystemId = pwrSel.value;
ctx.refreshEngineering(false, false);
ctx.renderSidebarBody();
},
},
...SPACECRAFT_POWER_SYSTEMS.map((p) =>
h(
"option",
{ value: p.id, selected: p.id === sc.powerSystemId },
`${p.name} (${p.powerWattsAt1AU}W @1AU • ${p.massKg}kg • ${fmtMoney(p.cost)})`,
),
),
);
const commSel = h(
"select",
{
class: "input",
onChange: () => {
sc.commsSystemId = commSel.value;
ctx.refreshEngineering(false, false);
ctx.renderSidebarBody();
},
},
...SPACECRAFT_COMMS_SYSTEMS.map((c) =>
h(
"option",
{ value: c.id, selected: c.id === sc.commsSystemId },
`${c.name} (${c.baseDataRateMbps} Mbps • ${c.powerDrawWatts}W • ${fmtMoney(c.cost)})`,
),
),
);
const netSel = h(
"select",
{
class: "input",
onChange: () => {
sc.groundNetworkTier = netSel.value as GroundNetworkTier;
ctx.refreshEngineering(false, false);
ctx.renderSidebarBody();
},
},
...Object.values(GROUND_NETWORK_SPECS).map((n) =>
h(
"option",
{
value: n.id,
selected: n.id === (sc.groundNetworkTier ?? "regional"),
},
`${n.name} (${n.coveragePct}% cov • +${fmtMoney(n.cost)})`,
),
),
);
const lifeInput = h("input", {
type: "number",
class: "input",
min: 1,
max: 15,
step: 1,
value: sc.missionLifetimeYears,
onInput: () => {
sc.missionLifetimeYears = Math.max(
1,
Math.min(15, Math.round(Number(lifeInput.value) || 3)),
);
ctx.refreshEngineering(false, false);
},
});
const pwrMarginOk = bus.powerMarginPct >= (contract?.minPowerMarginPct ?? 10);
const sigOk = bus.signalHealthPct >= (contract?.minSignalHealthPct ?? 60);
const dataOk = bus.dataMarginMbps >= 0;
const instList = h(
"div",
{ class: "col", style: { gap: "6px" } },
...SCIENCE_INSTRUMENTS.map((inst) => {
const checked = sc.instrumentIds.includes(inst.id);
const disabled = !checked && sc.instrumentIds.length >= 4;
const chk = h("input", {
type: "checkbox",
checked,
disabled,
onChange: () => {
if (chk.checked) {
if (
!sc.instrumentIds.includes(inst.id) &&
sc.instrumentIds.length < 4
) {
sc.instrumentIds = [...sc.instrumentIds, inst.id];
}
} else {
sc.instrumentIds = sc.instrumentIds.filter((id) => id !== inst.id);
}
ctx.refreshEngineering(false, false);
ctx.renderSidebarBody();
},
});
return h(
"label",
{
class: "rule-item " + (checked ? "pass" : ""),
style: { cursor: disabled ? "not-allowed" : "pointer" },
},
h(
"div",
{ class: "spread", style: { gap: "8px" } },
h(
"span",
{ class: "row", style: { gap: "6px" } },
chk,
h("strong", {}, inst.name),
),
h(
"span",
{ class: "mono green", style: { fontSize: "10px" } },
`+${inst.scienceBonusPct}% Sci • +${inst.researchPointsBonus} RP`,
),
),
h(
"div",
{ class: "mono dim", style: { fontSize: "10px" } },
`${inst.massKg} kg • ${inst.powerDrawWatts}W • ${inst.dataRateMbps} Mbps • ${fmtMoney(inst.cost)}`,
),
);
}),
);
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active", style: { marginTop: "10px" } },
h(
"div",
{ class: "spread" },
h(
"h3",
{},
term("Spacecraft Bus, Ground Control & Science", "spacecraft_bus"),
),
h(
"span",
{ class: `badge ${sigOk && pwrMarginOk ? "ok" : "warn"}` },
`Eff Grade ${bus.efficiencyGrade}`,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
term("Power Generation Subsystem", "power_margin"),
pwrSel,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
term("Onboard Comms Transponder", "comms_link"),
commSel,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
term("Ground Control Antenna Network", "ground_network"),
netSel,
),
),
h(
"div",
{ class: "slot-group" },
h(
"label",
{ class: "field" },
"Planned Mission Lifetime (Years)",
lifeInput,
),
),
h(
"div",
{ class: "slot-title", style: { marginTop: "4px" } },
`Power Budget Breakdown (Solar Flux ${Math.round(bus.solarFluxFactor * 100)}%)`,
),
h(
"div",
{ class: "bus-power-grid" },
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "EOL Supply"),
h("span", { class: "v accent" }, `${bus.endOfLifePowerWatts} W`),
),
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "Total Load"),
h("span", { class: "v" }, `${bus.requiredPowerWatts} W`),
),
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "Avionics & ADCS"),
h("span", { class: "v" }, `${bus.avionicsPowerWatts} W`),
),
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "Comms RF/Laser"),
h("span", { class: "v" }, `${bus.commsPowerWatts} W`),
),
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "Science Suite"),
h("span", { class: "v" }, `${bus.instrumentsPowerWatts} W`),
),
h(
"div",
{ class: "bus-power-cell" },
h("span", { class: "k" }, "Thermal + ECLSS"),
h(
"span",
{ class: "v" },
`${bus.thermalEclipsePowerWatts + bus.eclssPowerWatts} W`,
),
),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term(
`Power Margin (Req >= ${contract?.minPowerMarginPct ?? 10}%)`,
"power_margin",
),
),
h(
"span",
{
class: `v ${pwrMarginOk ? "green" : bus.powerMarginPct >= 0 ? "amber" : "red"}`,
},
`${bus.powerMarginWatts >= 0 ? "+" : ""}${bus.powerMarginWatts} W (${bus.powerMarginPct >= 0 ? "+" : ""}${bus.powerMarginPct}%)`,
),
),
h(
"div",
{ class: "slot-title", style: { marginTop: "4px" } },
term("Ground Control Telemetry & Link Health", "comms_link"),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
`Link Health (Req >= ${contract?.minSignalHealthPct ?? 60}%)`,
),
h(
"span",
{ class: `v ${sigOk ? "green" : "red"}` },
`${bus.signalHealthPct}% (${bus.linkStatus})`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "RF/Optical Link Margin"),
h(
"span",
{
class: `v ${bus.linkMarginDb >= 3 ? "green" : bus.linkMarginDb >= 0 ? "amber" : "red"}`,
},
`${bus.linkMarginDb >= 0 ? "+" : ""}${bus.linkMarginDb.toFixed(1)} dB`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Ground Station Coverage"),
h("span", { class: "v" }, `${bus.groundStationCoveragePct}%`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Downlink vs Data Load"),
h(
"span",
{ class: `v ${dataOk ? "green" : "red"}` },
`${bus.downlinkCapacityMbps.toFixed(1)} / ${bus.requiredDataRateMbps.toFixed(1)} Mbps`,
),
),
h(
"div",
{ class: "spread", style: { marginTop: "6px" } },
h(
"div",
{ class: "slot-title" },
`Science Instruments (${sc.instrumentIds.length}/4)`,
),
h(
"span",
{ class: "mono dim", style: { fontSize: "10px" } },
`Req Min: ${contract?.requiredInstrumentsMin ?? 0}`,
),
),
instList,
),
);
}

View file

@ -0,0 +1,513 @@
// Rocket Builder Pro tier free-form part mixer and per-part inspector
import { state } from "../../state.js";
import { convertStagesToProParts } from "../../../shared/physics.js";
import type { Part, ProPlacedPart } from "../../../shared/types.js";
import { h, term, toast } from "../../ui.js";
import { partLockTag, type BuilderContext } from "./context.js";
export function addProPartFromPalette(
ctx: BuilderContext,
part: Part,
radial = false,
asDropTank = false,
): void {
if (!ctx.design.proParts)
ctx.design.proParts = convertStagesToProParts(ctx.design, state.parts);
const list = ctx.design.proParts;
const selected = list.find((p) => p.uid === ctx.selectedProUid);
const topY = list.reduce((m, p) => Math.max(m, p.yBottom + p.length), 0);
const stageIndex = selected
? selected.stageIndex
: Math.max(0, (ctx.latestAssembly?.stages.length ?? 1) - 1);
const uid = `pro-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const markDropTank =
part.kind === "tank" && (asDropTank || !!part.isDropTank);
let radialOffset = 0;
let symmetry: 1 | 2 | 3 | 4 | 6 | 8 = part.kind === "fins" ? 4 : 1;
let yBottom = Number(topY.toFixed(2));
if (radial || markDropTank) {
const coreR = selected ? selected.diameter / 2 : 1.85;
radialOffset = Number(
(coreR + part.diameter * 0.5 + (markDropTank ? 0.18 : 0)).toFixed(2),
);
symmetry =
part.kind === "fins" ? 4 : part.id === "drop-tank-hydro-et" ? 1 : 2;
yBottom = selected ? selected.yBottom : 0;
}
const item: ProPlacedPart = {
uid,
role: part.kind,
partId: part.id,
stageIndex,
yBottom,
radialOffset,
radialAngleDeg: 0,
symmetry,
diameter: part.diameter,
length:
part.kind === "heatshield"
? Number((part.length * 0.5).toFixed(2))
: part.length,
propellantFill: part.kind === "tank" ? 1.0 : undefined,
isDropTank: markDropTank || undefined,
materialId:
part.kind === "tank" ||
part.kind === "structure" ||
part.kind === "interstage"
? (state.materials[0]?.id ?? "al-7075")
: undefined,
};
list.push(item);
ctx.selectedProUid = uid;
ctx.refreshEngineering(false, true);
ctx.renderTierAndTabs();
ctx.renderSidebarBody();
toast(
`Mounted ${part.name}${markDropTank ? ` as ${symmetry}× external drop tank(s)` : radial ? " radially (2×)" : " on stack"}.`,
"info",
);
}
export function renderProTab(ctx: BuilderContext): void {
const { bodyEl } = ctx;
const lockTag = (id: string) => partLockTag(ctx, id);
if (!ctx.design.proParts)
ctx.design.proParts = convertStagesToProParts(ctx.design, state.parts);
const partsList = ctx.design.proParts;
const paletteSel = h(
"select",
{ class: "input" },
...state.parts.map((p) =>
h(
"option",
{ value: p.id },
`[${p.kind.toUpperCase()}] ${p.name} (${p.diameter}m × ${p.length}m)${lockTag(p.id)}`,
),
),
);
const paletteCard = h(
"div",
{ class: "stage-card active" },
h(
"div",
{ class: "spread" },
h("h3", {}, "Free Part Mixer"),
h("span", { class: "badge info" }, `${partsList.length} parts`),
),
h(
"div",
{ class: "mono dim", style: { fontSize: "10px", marginBottom: "6px" } },
"Drag pieces directly in 3D or mount centerline / radial strap-ons below. Shape & radial interference determine drag Cd and CG/CP.",
),
paletteSel,
h(
"div",
{ class: "row", style: { marginTop: "6px" } },
h(
"button",
{
class: "btn xs primary grow",
onClick: () => {
const p = state.parts.find((x) => x.id === paletteSel.value);
if (p) addProPartFromPalette(ctx, p, false);
},
},
"+ Mount on Stack Top",
),
h(
"button",
{
class: "btn xs grow",
onClick: () => {
const p = state.parts.find((x) => x.id === paletteSel.value);
if (p) addProPartFromPalette(ctx, p, true);
},
},
"+ Mount Radially (2×)",
),
h(
"button",
{
class: "btn xs grow",
onClick: () => {
const p = state.parts.find((x) => x.id === paletteSel.value);
if (!p) return;
if (p.kind !== "tank") {
toast(
"Select a propellant Tank or Drop Tank in the palette to attach as crossfeed.",
"warn",
);
return;
}
addProPartFromPalette(ctx, p, true, true);
},
},
"+ Drop Tank",
),
),
);
bodyEl.appendChild(paletteCard);
const sorted = [...partsList].sort(
(a, b) =>
b.yBottom + b.length - (a.yBottom + a.length) ||
a.radialOffset - b.radialOffset,
);
const listBox = h("div", {
class: "col",
style: {
maxHeight: "175px",
overflowY: "auto",
gap: "4px",
marginBottom: "8px",
},
});
for (const pp of sorted) {
const pSpec = state.parts.find((x) => x.id === pp.partId);
const isSel = pp.uid === ctx.selectedProUid;
listBox.appendChild(
h(
"button",
{
class: `btn xs ${isSel ? "selected" : "ghost"}`,
style: { justifyContent: "space-between", textAlign: "left" },
onClick: () => {
ctx.selectedProUid = pp.uid;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
h("span", {}, `S${pp.stageIndex + 1} • ${pSpec?.name ?? pp.partId}`),
h(
"span",
{ class: "mono dim", style: { fontSize: "10px" } },
`Y=${pp.yBottom.toFixed(1)} R=${pp.radialOffset.toFixed(1)} (${pp.symmetry}×)`,
),
),
);
}
bodyEl.appendChild(
h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "slot-title" },
"Mounted Parts Hierarchy (Top → Bottom)",
),
listBox,
),
);
const sel =
partsList.find((x) => x.uid === ctx.selectedProUid) ?? partsList[0];
if (!sel) return;
ctx.selectedProUid = sel.uid;
const sameRoleParts = state.parts.filter((x) => x.kind === sel.role);
const roleModelSel = h(
"select",
{
class: "input",
onChange: () => {
sel.partId = roleModelSel.value;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...sameRoleParts.map((p) =>
h(
"option",
{ value: p.id, selected: p.id === sel.partId },
`${p.name} (${p.propellantType ?? p.kind})${lockTag(p.id)}`,
),
),
);
const stageSel = h(
"select",
{
class: "input",
onChange: () => {
sel.stageIndex = Number(stageSel.value);
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...[0, 1, 2, 3].map((i) =>
h(
"option",
{ value: String(i), selected: sel.stageIndex === i },
`Stage ${i + 1}`,
),
),
);
const yLabel = h("span", {}, `Vertical Y (${sel.yBottom.toFixed(1)} m)`);
const ySlider = h("input", {
type: "range",
class: "slider",
min: 0,
max: 85,
step: 0.1,
value: sel.yBottom,
onInput: () => {
sel.yBottom = Number(ySlider.value);
yLabel.textContent = `Vertical Y (${sel.yBottom.toFixed(1)} m)`;
ctx.refreshEngineering(false, false);
},
});
const rLabel = h(
"span",
{},
`Radial Offset R (${sel.radialOffset.toFixed(2)} m)`,
);
const rSlider = h("input", {
type: "range",
class: "slider",
min: 0,
max: 8.5,
step: 0.05,
value: sel.radialOffset,
onInput: () => {
sel.radialOffset = Number(rSlider.value);
rLabel.textContent = `Radial Offset R (${sel.radialOffset.toFixed(2)} m)`;
ctx.refreshEngineering(false, false);
},
});
const angLabel = h(
"span",
{},
`Radial Angle (${Math.round(sel.radialAngleDeg)}°)`,
);
const angSlider = h("input", {
type: "range",
class: "slider",
min: 0,
max: 355,
step: 5,
value: sel.radialAngleDeg,
onInput: () => {
sel.radialAngleDeg = Number(angSlider.value);
angLabel.textContent = `Radial Angle (${Math.round(sel.radialAngleDeg)}°)`;
ctx.refreshEngineering(false, false);
},
});
const dLabel = h("span", {}, `Diameter (${sel.diameter.toFixed(1)} m)`);
const dSlider = h("input", {
type: "range",
class: "slider",
min: 0.6,
max: 11.5,
step: 0.1,
value: sel.diameter,
onInput: () => {
sel.diameter = Number(dSlider.value);
dLabel.textContent = `Diameter (${sel.diameter.toFixed(1)} m)`;
ctx.refreshEngineering(false, false);
},
});
const lLabel = h("span", {}, `Length (${sel.length.toFixed(1)} m)`);
const lSlider = h("input", {
type: "range",
class: "slider",
min: 0.4,
max: 48.0,
step: 0.2,
value: sel.length,
onInput: () => {
sel.length = Number(lSlider.value);
lLabel.textContent = `Length (${sel.length.toFixed(1)} m)`;
ctx.refreshEngineering(false, false);
},
});
const symRow = h(
"div",
{ class: "row", style: { gap: "4px", flexWrap: "wrap" } },
...([1, 2, 3, 4, 6, 8] as const).map((sym) =>
h(
"button",
{
class: `btn xs ${sel.symmetry === sym ? "selected" : "ghost"}`,
onClick: () => {
sel.symmetry = sym;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
`${sym}×`,
),
),
);
const extraControls: Array<HTMLElement | null> = [];
if (sel.role === "tank") {
const fValEl = h(
"span",
{ class: "mono dim" },
`(${Math.round((sel.propellantFill ?? 1) * 100)}%)`,
);
const fLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("Propellant Fill", "fill_ratio"),
fValEl,
);
const fSlider = h("input", {
type: "range",
class: "slider",
min: 0.2,
max: 1.0,
step: 0.05,
value: sel.propellantFill ?? 1.0,
onInput: () => {
sel.propellantFill = Number(fSlider.value);
fValEl.textContent = `(${Math.round((sel.propellantFill ?? 1) * 100)}%)`;
ctx.refreshEngineering(false, false);
},
});
extraControls.push(h("label", { class: "field" }, fLabel, fSlider));
const dropChk = h("input", {
type: "checkbox",
checked: !!sel.isDropTank,
onChange: () => {
sel.isDropTank = dropChk.checked || undefined;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
});
extraControls.push(
h(
"label",
{
class: "row",
style: { cursor: "pointer", fontSize: "11px", marginTop: "4px" },
},
dropChk,
term("External Drop Tank (Crossfeed Jettison)", "crossfeed"),
),
);
}
if (
sel.role === "tank" ||
sel.role === "structure" ||
sel.role === "interstage"
) {
const mSel = h(
"select",
{
class: "input",
onChange: () => {
sel.materialId = mSel.value;
ctx.refreshEngineering(false, true);
},
},
...state.materials.map((m) =>
h(
"option",
{ value: m.id, selected: m.id === sel.materialId },
`${m.name} (${m.yieldStrengthMPa} MPa)${lockTag(m.id)}`,
),
),
);
extraControls.push(
h(
"label",
{ class: "field" },
term("Structural Material", "airframe_material"),
mSel,
),
);
}
const inspector = h(
"div",
{ class: "stage-card active" },
h(
"div",
{ class: "spread" },
h("h3", {}, `Inspector // ${sel.role.toUpperCase()}`),
h(
"div",
{ class: "row" },
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
const clone: ProPlacedPart = {
...structuredClone(sel),
uid: `pro-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,
yBottom: Number((sel.yBottom + sel.length).toFixed(2)),
};
partsList.push(clone);
ctx.selectedProUid = clone.uid;
ctx.refreshEngineering(false, true);
ctx.renderTierAndTabs();
ctx.renderSidebarBody();
},
},
"Duplicate",
),
partsList.length > 1
? h(
"button",
{
class: "btn xs danger",
onClick: () => {
const i = partsList.findIndex((x) => x.uid === sel.uid);
if (i >= 0) partsList.splice(i, 1);
ctx.selectedProUid = partsList[0]?.uid ?? null;
ctx.refreshEngineering(false, true);
ctx.renderTierAndTabs();
ctx.renderSidebarBody();
},
},
"Delete",
)
: null,
),
),
h("label", { class: "field" }, "Component Model", roleModelSel),
h("label", { class: "field" }, "Stage Assignment", stageSel),
h("label", { class: "field" }, yLabel, ySlider),
h("label", { class: "field" }, rLabel, rSlider),
h("label", { class: "field" }, angLabel, angSlider),
h("div", { class: "field" }, h("span", {}, "Radial Symmetry"), symRow),
h("label", { class: "field" }, dLabel, dSlider),
h("label", { class: "field" }, lLabel, lSlider),
...extraControls,
h(
"div",
{ class: "row", style: { marginTop: "6px" } },
h(
"button",
{
class: "btn xs ghost grow",
onClick: () => {
sel.radialOffset = 0;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
"Snap Centerline (R=0)",
),
h(
"button",
{
class: "btn xs ghost grow",
onClick: () => {
const below = partsList
.filter(
(x) =>
x.uid !== sel.uid &&
Math.abs(x.radialOffset - sel.radialOffset) < 1.2 &&
x.yBottom + x.length <= sel.yBottom + sel.length + 0.5,
)
.sort((a, b) => b.yBottom + b.length - (a.yBottom + a.length))[0];
sel.yBottom = below
? Number((below.yBottom + below.length).toFixed(2))
: 0;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
"Snap Down Flush",
),
),
);
bodyEl.appendChild(inspector);
}

View file

@ -0,0 +1,490 @@
// Rocket Builder stage Slot 1 (engine cluster) and Slot 2 (tanks & crossfeed drops) UI
import { state } from "../../state.js";
import { isPartUnlocked } from "../../../shared/physics.js";
import type { AgencyState, Part, RocketDesign } from "../../../shared/types.js";
import { h, term } from "../../ui.js";
import { partLockTag, type BuilderContext } from "./context.js";
import { recordHistory } from "./history.js";
export interface StagePropulsionOpts {
ctx: BuilderContext;
idx: number;
getSt: () => RocketDesign["stages"][number];
ag: AgencyState;
engines: Part[];
tanks: Part[];
dropTanks: Part[];
isStandardOrExpert: boolean;
isExpert: boolean;
updateStageSummaryText: () => void;
propMetrics: HTMLElement;
dropMetricsLine: HTMLElement;
structMetrics: HTMLElement;
}
export function buildStagePropulsionAndTankCards(opts: StagePropulsionOpts): {
slot1Card: HTMLElement;
slot2Card: HTMLElement;
} {
const {
ctx,
idx,
getSt,
ag,
engines,
tanks,
dropTanks,
isStandardOrExpert,
isExpert,
updateStageSummaryText,
propMetrics,
dropMetricsLine,
structMetrics,
} = opts;
const st = getSt();
const lockTag = (id: string) => partLockTag(ctx, id);
const engPart = state.parts.find((p) => p.id === st.engineId);
const tankPart = state.parts.find((p) => p.id === st.tankId);
const chemMismatch = engPart?.propellantType !== tankPart?.propellantType;
const isSolidStage = engPart?.propellantType === "solid";
const dropCount = isSolidStage ? 0 : (st.dropTankCount ?? 0);
const dropPart =
dropCount > 0 && st.dropTankId
? dropTanks.find((d) => d.id === st.dropTankId)
: undefined;
const dropChemMismatch =
!isSolidStage &&
dropCount > 0 &&
(!dropPart || dropPart.propellantType !== engPart?.propellantType);
const countValEl = h("span", { class: "mono dim" }, `(${st.engineCount})`);
const nozzleValEl = h(
"span",
{ class: "mono dim" },
`(${(st.nozzleRatio ?? 1).toFixed(2)}×)`,
);
const gimbalValEl = h(
"span",
{ class: "mono dim" },
`(${(st.gimbalDeg ?? 4).toFixed(1)}°)`,
);
const diamValEl = h(
"span",
{ class: "mono dim" },
`(${st.diameter.toFixed(1)} m)`,
);
const lenValEl = h(
"span",
{ class: "mono dim" },
`(${st.length.toFixed(1)} m)`,
);
const fillValEl = h(
"span",
{ class: "mono dim" },
`(${Math.round(st.fillRatio * 100)}%)`,
);
const countLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("Cluster Count", "engine_count"),
countValEl,
);
const nozzleLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("Nozzle Expansion", "nozzle_ratio"),
nozzleValEl,
);
const gimbalLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("TVC Gimbal Range", "gimbal"),
gimbalValEl,
);
const diamLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
"Diameter",
diamValEl,
);
const lenLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
"Tank Length",
lenValEl,
);
const fillLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("Propellant Fill", "fill_ratio"),
fillValEl,
);
const engSel = h(
"select",
{
class: "input",
onChange: () => {
const cur = getSt();
cur.engineId = engSel.value;
const newEng = state.parts.find((p) => p.id === cur.engineId);
if (newEng?.propellantType === "solid") {
cur.dropTankCount = 0;
cur.dropTankId = undefined;
}
if (ctx.design.designTier === "casual" && newEng?.propellantType) {
const matchTank = tanks.find(
(t) => t.propellantType === newEng.propellantType,
);
if (matchTank) cur.tankId = matchTank.id;
if ((cur.dropTankCount ?? 0) > 0) {
const matchDrop = dropTanks.find(
(d) => d.propellantType === newEng.propellantType,
);
if (matchDrop) cur.dropTankId = matchDrop.id;
}
}
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...engines.map((e) =>
h(
"option",
{ value: e.id, selected: e.id === st.engineId },
`${e.name} [${e.propellantType ?? "n/a"}] (${Math.round((e.thrust ?? 0) / 1000)} kN, Isp ${e.ispVac ?? e.isp}s)${lockTag(e.id)}`,
),
),
);
const engCountInput = h("input", {
type: "range",
class: "slider",
min: 1,
max: 9,
step: 1,
value: st.engineCount,
onInput: () => {
const cur = getSt();
cur.engineCount = Number(engCountInput.value);
countValEl.textContent = `(${cur.engineCount})`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const nozzleSlider = h("input", {
type: "range",
class: "slider",
min: 0.7,
max: 1.45,
step: 0.05,
value: st.nozzleRatio ?? 1.0,
onInput: () => {
const cur = getSt();
cur.nozzleRatio = Number(nozzleSlider.value);
nozzleValEl.textContent = `(${(cur.nozzleRatio ?? 1).toFixed(2)}×)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const gimbalSlider = h("input", {
type: "range",
class: "slider",
min: 1,
max: 10,
step: 0.5,
value: st.gimbalDeg ?? 4,
onInput: () => {
const cur = getSt();
cur.gimbalDeg = Number(gimbalSlider.value);
gimbalValEl.textContent = `(${(cur.gimbalDeg ?? 4).toFixed(1)}°)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const tankSel = h(
"select",
{
class: "input",
onChange: () => {
const cur = getSt();
cur.tankId = tankSel.value;
const chosen = state.parts.find((p) => p.id === cur.tankId);
if (chosen) {
cur.diameter = chosen.diameter;
cur.length = chosen.length;
}
ctx.refreshEngineering(true, true);
ctx.renderSidebarBody();
},
},
...tanks.map((t) =>
h(
"option",
{ value: t.id, selected: t.id === st.tankId },
`${t.name} [${t.propellantType}] (${t.diameter}m × ${t.length}m)${lockTag(t.id)}`,
),
),
);
const diamSlider = h("input", {
type: "range",
class: "slider",
min: 1.8,
max: 9.0,
step: 0.1,
value: st.diameter,
onInput: () => {
const cur = getSt();
cur.diameter = Number(diamSlider.value);
diamValEl.textContent = `(${cur.diameter.toFixed(1)} m)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const lenSlider = h("input", {
type: "range",
class: "slider",
min: 3.0,
max: 48.0,
step: 0.5,
value: st.length,
onInput: () => {
const cur = getSt();
cur.length = Number(lenSlider.value);
lenValEl.textContent = `(${cur.length.toFixed(1)} m)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const fillSlider = h("input", {
type: "range",
class: "slider",
min: 0.3,
max: 1.0,
step: 0.05,
value: st.fillRatio,
onInput: () => {
const cur = getSt();
cur.fillRatio = Number(fillSlider.value);
fillValEl.textContent = `(${Math.round(cur.fillRatio * 100)}%)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const sortedDropTanks = [...dropTanks].sort((a, b) => {
const aMatch = a.propellantType === engPart?.propellantType ? 0 : 1;
const bMatch = b.propellantType === engPart?.propellantType ? 0 : 1;
return aMatch - bMatch;
});
const dropTankSel = h(
"select",
{
class: "input",
onChange: () => {
const cur = getSt();
cur.dropTankId = dropTankSel.value || undefined;
recordHistory(ctx, `Select Stage ${idx + 1} drop tank`);
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...sortedDropTanks.map((d) =>
h(
"option",
{ value: d.id, selected: d.id === st.dropTankId },
`${d.name} [${d.propellantType}] (+${Math.round((d.propellantMass ?? 0) / 1000)}t prop / ${(d.dryMass / 1000).toFixed(1)}t dry)${lockTag(d.id)}`,
),
),
);
const dropTankQtyRow = h(
"div",
{ class: "row", style: { gap: "4px", flexWrap: "wrap" } },
...([0, 1, 2, 4, 6] as const).map((qty) =>
h(
"button",
{
type: "button",
class: `btn xs ${dropCount === qty ? "selected" : "ghost"}`,
disabled: isSolidStage,
onClick: () => {
const cur = getSt();
if (qty === 0) {
cur.dropTankCount = 0;
cur.dropTankId = undefined;
} else {
cur.dropTankCount = qty;
if (!cur.dropTankId) {
const chem = engPart?.propellantType;
const picked =
(qty === 1
? dropTanks.find(
(d) =>
d.id === "drop-tank-hydro-et" &&
d.propellantType === chem &&
isPartUnlocked(d.id, ag),
)
: undefined) ??
dropTanks.find(
(d) =>
d.propellantType === chem && isPartUnlocked(d.id, ag),
) ??
dropTanks.find((d) => d.propellantType === chem) ??
dropTanks[0];
if (picked) cur.dropTankId = picked.id;
}
}
recordHistory(ctx, `Stage ${idx + 1} drop tanks -> ${qty}×`);
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
qty === 0 ? "None" : qty === 1 ? "1× Belly ET" : `${qty}×`,
),
),
);
const slot1Card = h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "slot-title" },
term("Slot 1 // Engine Cluster", "propellant_chemistry"),
),
h("label", { class: "field" }, "Engine Model", engSel),
isStandardOrExpert
? h("label", { class: "field" }, countLabel, engCountInput)
: null,
isExpert ? h("label", { class: "field" }, nozzleLabel, nozzleSlider) : null,
isExpert ? h("label", { class: "field" }, gimbalLabel, gimbalSlider) : null,
propMetrics,
);
const slot2Card = h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "slot-title" },
term("Slot 2 // Propellant Tank", "wet_dry_mass"),
),
h("label", { class: "field" }, "Tank Core", tankSel),
chemMismatch
? h(
"div",
{
class: "row spread",
style: {
background: "rgba(248,113,113,0.12)",
padding: "6px 8px",
border: "1px solid var(--red)",
},
},
h(
"span",
{ class: "red mono", style: { fontSize: "10px" } },
`Chemistry mismatch (${engPart?.propellantType} vs ${tankPart?.propellantType})`,
),
h(
"button",
{
class: "btn xs primary",
onClick: () => {
const match = tanks.find(
(t) => t.propellantType === engPart?.propellantType,
);
if (match) {
getSt().tankId = match.id;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
}
},
},
"Auto-Pair Tank",
),
)
: null,
isStandardOrExpert
? h("label", { class: "field" }, diamLabel, diamSlider)
: null,
isStandardOrExpert
? h("label", { class: "field" }, lenLabel, lenSlider)
: null,
isExpert ? h("label", { class: "field" }, fillLabel, fillSlider) : null,
h(
"div",
{
style: {
marginTop: "6px",
paddingTop: "6px",
borderTop: "1px dashed var(--border)",
},
},
h(
"div",
{ class: "field", style: { marginBottom: "4px" } },
term("Disposable Drop Tanks (Crossfeed)", "drop_tanks"),
dropTankQtyRow,
),
isSolidStage
? h(
"div",
{ class: "mono amber", style: { fontSize: "10px" } },
"Solid SRB stages burn cast grain — external liquid drop tanks disabled.",
)
: dropCount > 0
? h(
"div",
{ class: "col", style: { gap: "4px", marginTop: "4px" } },
h(
"label",
{ class: "field" },
term("Drop Tank Model", "crossfeed"),
dropTankSel,
),
dropChemMismatch
? h(
"div",
{
class: "row spread",
style: {
background: "rgba(248,113,113,0.12)",
padding: "5px 8px",
border: "1px solid var(--red)",
},
},
h(
"span",
{ class: "red mono", style: { fontSize: "10px" } },
`Drop chemistry mismatch (${engPart?.propellantType} vs ${dropPart?.propellantType ?? "none"})`,
),
h(
"button",
{
type: "button",
class: "btn xs primary",
onClick: () => {
const match =
dropTanks.find(
(d) =>
d.propellantType === engPart?.propellantType &&
isPartUnlocked(d.id, ag),
) ??
dropTanks.find(
(d) =>
d.propellantType === engPart?.propellantType,
);
if (match) {
getSt().dropTankId = match.id;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
}
},
},
"Auto-Pair Drop",
),
)
: null,
dropMetricsLine,
)
: null,
),
structMetrics,
);
return { slot1Card, slot2Card };
}

View file

@ -0,0 +1,315 @@
// Rocket Builder Stages tab: stage stack selector and airframe/thermal controls
import { state } from "../../state.js";
import { createStarterStage } from "../../../shared/physics.js";
import { fmtMoney, fmtNum, h, term } from "../../ui.js";
import { curAgency, partLockTag, type BuilderContext } from "./context.js";
import { recordHistory } from "./history.js";
import { buildStagePropulsionAndTankCards } from "./stagePropulsionControls.js";
export function renderStagesTab(ctx: BuilderContext): void {
const { bodyEl } = ctx;
const ag = curAgency(ctx);
const lockTag = (id: string) => partLockTag(ctx, id);
const engines = state.parts.filter((p) => p.kind === "engine");
const tanks = state.parts.filter((p) => p.kind === "tank" && !p.isDropTank);
const dropTanks = state.parts.filter(
(p) => p.kind === "tank" && !!p.isDropTank,
);
const structures = state.parts.filter((p) => p.kind === "structure");
const interstages = state.parts.filter((p) => p.kind === "interstage");
const isStandardOrExpert = ctx.design.designTier !== "casual";
const isExpert = ctx.design.designTier === "expert";
const diags = ctx.latestValidation?.stageDiagnostics ?? [];
const stageTabs = h(
"div",
{ class: "row", style: { flexWrap: "wrap", gap: "4px" } },
...ctx.design.stages.map((_st, idx) => {
const sErrs = diags.filter(
(d) => d.stageIndex === idx && d.severity === "error",
).length;
const sWarns = diags.filter(
(d) => d.stageIndex === idx && d.severity === "warn",
).length;
return h(
"button",
{
class: `btn xs ${ctx.activeStageIdx === idx ? "selected" : "ghost"}`,
style:
sErrs > 0
? { borderColor: "var(--red)" }
: sWarns > 0
? { borderColor: "var(--amber)" }
: undefined,
onClick: () => {
ctx.activeStageIdx = idx;
ctx.renderSidebarBody();
},
},
idx === 0 ? "Stage 1 (Core)" : `Stage ${idx + 1}`,
sErrs > 0
? h(
"span",
{
class: "badge err",
style: {
marginLeft: "4px",
fontSize: "9px",
padding: "1px 4px",
},
},
`!${sErrs}`,
)
: null,
sWarns > 0
? h(
"span",
{
class: "badge warn",
style: {
marginLeft: "3px",
fontSize: "9px",
padding: "1px 4px",
},
},
`▲${sWarns}`,
)
: null,
);
}),
ctx.design.stages.length < 4
? h(
"button",
{
class: "btn xs primary",
onClick: () => {
ctx.design.stages.push(createStarterStage("upper"));
ctx.activeStageIdx = ctx.design.stages.length - 1;
recordHistory(ctx, `Add Stage ${ctx.design.stages.length}`);
ctx.refreshEngineering(true, true);
ctx.renderAll();
},
},
"+ Add Stage",
)
: null,
);
bodyEl.appendChild(stageTabs);
const idx = Math.min(ctx.activeStageIdx, ctx.design.stages.length - 1);
ctx.activeStageIdx = idx;
const getSt = () => ctx.design.stages[idx];
const st = getSt();
const propMetrics = h("div", {
class: "mono dim",
style: { fontSize: "10px" },
});
const dropMetricsLine = h("div", {
class: "mono accent",
style: { fontSize: "10px" },
});
const wallValEl = h(
"span",
{ class: "mono dim" },
`(${st.wallThicknessFactor.toFixed(2)}×)`,
);
const wallLabel = h(
"span",
{ class: "row", style: { gap: "4px" } },
term("Wall Thickness", "wall_factor"),
wallValEl,
);
const structSel = h(
"select",
{
class: "input",
onChange: () => {
getSt().structureId = structSel.value;
ctx.refreshEngineering(false, true);
updateStageSummaryText();
},
},
...structures.map((s) =>
h(
"option",
{ value: s.id, selected: s.id === st.structureId },
`${s.name} (Max-Q ${(s.maxQ ?? 45000) / 1000} kPa)${lockTag(s.id)}`,
),
),
);
const matSel = h(
"select",
{
class: "input",
onChange: () => {
getSt().materialId = matSel.value;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
...state.materials.map((m) =>
h(
"option",
{ value: m.id, selected: m.id === st.materialId },
`${m.name} (${m.yieldStrengthMPa} MPa, ${m.maxTempK}K)${lockTag(m.id)}`,
),
),
);
const wallSlider = h("input", {
type: "range",
class: "slider",
min: 0.65,
max: 1.6,
step: 0.05,
value: st.wallThicknessFactor,
onInput: () => {
const cur = getSt();
cur.wallThicknessFactor = Number(wallSlider.value);
wallValEl.textContent = `(${cur.wallThicknessFactor.toFixed(2)}×)`;
ctx.refreshEngineering(false, false);
updateStageSummaryText();
},
});
const interSel = h(
"select",
{
class: "input",
onChange: () => {
getSt().interstageId = interSel.value;
ctx.refreshEngineering(false, true);
updateStageSummaryText();
},
},
...interstages.map((i) =>
h("option", { value: i.id, selected: i.id === st.interstageId }, i.name),
),
);
const finsChk = h("input", {
type: "checkbox",
checked: !!st.hasFins,
onChange: () => {
getSt().hasFins = finsChk.checked;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
});
const hsChk = h("input", {
type: "checkbox",
checked: !!st.hasHeatshield,
onChange: () => {
getSt().hasHeatshield = hsChk.checked;
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
});
const structMetrics = h("div", {
class: "mono dim",
style: { fontSize: "10px" },
});
const stageMassLine = h("div", {
class: "mono dim",
style: { fontSize: "10px" },
});
function updateStageSummaryText() {
if (!ctx.latestAssembly) return;
const cur = getSt();
const sNow = ctx.latestAssembly.stages[idx];
if (!sNow || !cur) return;
propMetrics.textContent = `Engines: ${cur.engineCount}× | TWR ${sNow.twrAtIgnition.toFixed(2)} | Stage Δv ${fmtNum(sNow.dv)} m/s | Nozzle ${(cur.nozzleRatio ?? 1).toFixed(2)}× | Gimbal ${(cur.gimbalDeg ?? 4).toFixed(1)}°`;
structMetrics.textContent = `Dim: ${cur.diameter.toFixed(1)}m × ${cur.length.toFixed(1)}m | Fill ${Math.round(cur.fillRatio * 100)}% | Stress ${sNow.axialStressMPa.toFixed(1)} / ${sNow.yieldLimitMPa.toFixed(1)} MPa`;
const dropPropKg = sNow.dropTankPropellantMass ?? 0;
const dropDryKg = sNow.dropTankDryMass ?? 0;
dropMetricsLine.textContent =
dropPropKg > 0 || dropDryKg > 0
? `Crossfeed burns ${(dropPropKg / 1000).toFixed(1)}t external prop first -> jettisons ${(dropDryKg / 1000).toFixed(1)}t casings mid-burn`
: "";
stageMassLine.textContent = `Stage Mass: ${(sNow.dryMass / 1000).toFixed(1)}t dry + ${(sNow.propellantMass / 1000).toFixed(1)}t prop${dropPropKg > 0 ? ` (incl. ${(dropPropKg / 1000).toFixed(1)}t drop)` : ""} • ${fmtMoney(sNow.stageCost)}`;
}
updateStageSummaryText();
const { slot1Card, slot2Card } = buildStagePropulsionAndTankCards({
ctx,
idx,
getSt,
ag,
engines,
tanks,
dropTanks,
isStandardOrExpert,
isExpert,
updateStageSummaryText,
propMetrics,
dropMetricsLine,
structMetrics,
});
const card = h(
"div",
{ class: "stage-card active" },
h(
"div",
{ class: "spread" },
h(
"h3",
{},
`Stage ${idx + 1} (${idx === 0 ? "Booster Core" : idx === ctx.design.stages.length - 1 ? "Upper Stage" : "Sustainer"})`,
),
ctx.design.stages.length > 1
? h(
"button",
{
class: "btn xs danger",
onClick: () => {
ctx.design.stages.splice(idx, 1);
ctx.activeStageIdx = Math.max(0, idx - 1);
ctx.refreshEngineering(true, true);
ctx.renderAll();
},
},
"Remove Stage",
)
: null,
),
slot1Card,
slot2Card,
h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "slot-title" },
term("Slot 3 // Structure, Alloy & Thermal", "buckling"),
),
h("label", { class: "field" }, "Airframe Frame", structSel),
h(
"label",
{ class: "field" },
term("Structural Material", "airframe_material"),
matSel,
),
isExpert ? h("label", { class: "field" }, wallLabel, wallSlider) : null,
idx < ctx.design.stages.length - 1 && isStandardOrExpert
? h(
"label",
{ class: "field" },
term("Interstage Adapter", "interstage"),
interSel,
)
: null,
h(
"div",
{ class: "row", style: { gap: "16px", marginTop: "4px" } },
h(
"label",
{ class: "row", style: { cursor: "pointer", fontSize: "11px" } },
finsChk,
term("Aero Grid Fins", "grid_fins"),
),
h(
"label",
{ class: "row", style: { cursor: "pointer", fontSize: "11px" } },
hsChk,
term("Thermal TPS Shield", "heatshield"),
),
),
stageMassLine,
),
);
bodyEl.appendChild(card);
}

View file

@ -0,0 +1,657 @@
// Contract ROI value analysis, NASA CML/TRL compliance gates, and builder action footer
// Is this just so I can say I added this? Yes. Yes it is.
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { refreshMe } from "../../session.js";
import { state } from "../../state.js";
import { simulateAscent } from "../../../shared/ascent_sim.js";
import type {
MaturityLevel,
RocketDesign,
SimResult,
} from "../../../shared/types.js";
import { clear, fmtMoney, fmtNum, h, modal, term, toast } from "../../ui.js";
import { curAgency, MATURITY_ORDER, type BuilderContext } from "./context.js";
export function renderContractValueTab(ctx: BuilderContext): void {
const { bodyEl, contract } = ctx;
const v = ctx.latestValueEstimate;
const bus = ctx.latestAssembly?.spacecraftBus;
if (!v || !bus || !ctx.latestAssembly || !ctx.latestValidation) return;
const maxScale = Math.max(1, v.grossProjectedRevenue, v.totalProjectedCost);
const pct = (n: number) => `${Math.max(0, (n / maxScale) * 100).toFixed(1)}%`;
const baseRev = v.advancePayout + v.completionPayoutNominal;
const opsBusCost =
v.fairingAndAbortCost + v.instrumentsCost + v.insuranceCost;
const penaltyCost = v.waiverPenaltyCost + v.staticFireCost;
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active" },
h(
"div",
{ class: "spread" },
h(
"h3",
{},
v.hasContract
? `Contract Value & ROI: ${v.contractTitle}`
: "Free-Flight Value Estimate",
),
h(
"span",
{
class: `badge ${v.efficiencyGrade === "S" || v.efficiencyGrade === "A" ? "ok" : v.efficiencyGrade === "B" ? "info" : "warn"}`,
},
`GRADE ${v.efficiencyGrade}`,
),
),
h(
"div",
{ class: "value-chart" },
h(
"div",
{},
h(
"div",
{
class: "spread mono",
style: { fontSize: "10px", marginBottom: "4px" },
},
h("span", { class: "dim" }, "Projected Gross Revenue Stack"),
h("span", { class: "green" }, fmtMoney(v.grossProjectedRevenue)),
),
h(
"div",
{ class: "value-bar-track" },
baseRev > 0
? h("div", {
class: "value-seg base",
style: { width: pct(baseRev) },
title: `Base + Completion: ${fmtMoney(baseRev)}`,
})
: null,
v.estimatedScienceBonus > 0
? h("div", {
class: "value-seg science",
style: { width: pct(v.estimatedScienceBonus) },
title: `Science Bonus: ${fmtMoney(v.estimatedScienceBonus)}`,
})
: null,
v.estimatedEfficiencyBonus > 0
? h("div", {
class: "value-seg eff",
style: { width: pct(v.estimatedEfficiencyBonus) },
title: `Efficiency Bonus: ${fmtMoney(v.estimatedEfficiencyBonus)}`,
})
: null,
v.estimatedReusabilitySavings > 0
? h("div", {
class: "value-seg bonus",
style: { width: pct(v.estimatedReusabilitySavings) },
title: `Booster Recovery: ${fmtMoney(v.estimatedReusabilitySavings)}`,
})
: null,
),
),
h(
"div",
{},
h(
"div",
{
class: "spread mono",
style: { fontSize: "10px", marginBottom: "4px" },
},
h("span", { class: "dim" }, "Projected Total Expenditure Stack"),
h("span", { class: "amber" }, fmtMoney(v.totalProjectedCost)),
),
h(
"div",
{ class: "value-bar-track" },
v.stagesHardwareCost > 0
? h("div", {
class: "value-seg hw",
style: { width: pct(v.stagesHardwareCost) },
title: `Stages Hardware: ${fmtMoney(v.stagesHardwareCost)}`,
})
: null,
opsBusCost > 0
? h("div", {
class: "value-seg bus",
style: { width: pct(opsBusCost) },
title: `Fairing, Bus & Insurance: ${fmtMoney(opsBusCost)}`,
})
: null,
penaltyCost > 0
? h("div", {
class: "value-seg ops",
style: { width: pct(penaltyCost) },
title: `Waivers & Static Fire: ${fmtMoney(penaltyCost)}`,
})
: null,
),
),
h(
"div",
{
class: "mono dim",
style: {
fontSize: "9px",
display: "flex",
flexWrap: "wrap",
gap: "8px",
},
},
h("span", {}, `Blue: Base ${fmtMoney(baseRev)}`),
h(
"span",
{ class: "green" },
`Green: Sci ${fmtMoney(v.estimatedScienceBonus)}`,
),
h(
"span",
{ style: { color: "var(--violet)" } },
`Violet: Eff ${fmtMoney(v.estimatedEfficiencyBonus)}`,
),
h(
"span",
{ class: "amber" },
`Amber: Reuse ${fmtMoney(v.estimatedReusabilitySavings)}`,
),
),
),
h(
"div",
{ class: "stat-grid" },
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Nominal Net Profit", "contract_tier")),
h(
"div",
{ class: `v ${v.projectedNetProfitNominal >= 0 ? "good" : "bad"}` },
fmtMoney(v.projectedNetProfitNominal),
),
),
h(
"div",
{ class: "stat-box" },
h(
"div",
{ class: "k" },
term("Risk-Adjusted EV", "reliability_risk"),
),
h(
"div",
{
class: `v ${v.expectedValueRiskAdjusted >= 0 ? "good" : "warn"}`,
},
fmtMoney(v.expectedValueRiskAdjusted),
),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, "Projected ROI"),
h(
"div",
{
class: `v ${v.projectedRoiPct >= 20 ? "good" : v.projectedRoiPct >= 0 ? "warn" : "bad"}`,
},
`${v.projectedRoiPct.toFixed(1)}%`,
),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, "Partial Orbit Profit"),
h(
"div",
{ class: `v ${v.projectedNetProfitPartial >= 0 ? "good" : "bad"}` },
fmtMoney(v.projectedNetProfitPartial),
),
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Contract Budget / 35% Advance"),
h(
"span",
{ class: "v" },
`${fmtMoney(v.contractBudget)} • ${fmtMoney(v.advancePayout)}`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Payload Cost Specific Index"),
h(
"span",
{ class: "v" },
`${fmtMoney(bus.costPerKgPayload)}/kg payload`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Projected Rep & Research Gain"),
h(
"span",
{ class: "v green" },
`+${v.estimatedRepGain} RP rep • +${v.estimatedResearchPoints} R&D pts`,
),
),
),
);
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active" },
h("h3", {}, "Efficiency, Telemetry & Ground Ratings"),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
`Composite Efficiency (Min ${contract?.minEfficiencyScore ?? 45})`,
),
h(
"span",
{
class: `v ${bus.efficiencyScore >= (contract?.minEfficiencyScore ?? 45) ? "green" : "red"}`,
},
`Grade ${bus.efficiencyGrade} • ${bus.efficiencyScore}/100`,
),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Propulsive / Mass Fraction Eff", "wet_dry_mass"),
),
h("span", { class: "v" }, `${bus.propulsiveEfficiencyPct}%`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Launch Cost Efficiency"),
h("span", { class: "v" }, `${bus.costEfficiencyPct}%`),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Spacecraft Bus & Power Eff", "spacecraft_bus"),
),
h("span", { class: "v" }, `${bus.busEfficiencyPct}%`),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Ground Comms Signal Health", "comms_link"),
),
h(
"span",
{
class: `v ${bus.signalHealthPct >= (contract?.minSignalHealthPct ?? 60) ? "green" : "red"}`,
},
`${bus.signalHealthPct}% (${bus.linkMarginDb >= 0 ? "+" : ""}${bus.linkMarginDb.toFixed(1)} dB)`,
),
),
h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("End-of-Life Power Margin", "power_margin"),
),
h(
"span",
{
class: `v ${bus.powerMarginPct >= (contract?.minPowerMarginPct ?? 10) ? "green" : "red"}`,
},
`${bus.powerMarginPct >= 0 ? "+" : ""}${bus.powerMarginPct}%`,
),
),
),
);
if (contract?.multiLegWaypoints?.length || v.bonusObjectives.length) {
bodyEl.appendChild(
h(
"div",
{ class: "stage-card active" },
h("h3", {}, "Mission Architecture & Bonus Checklist"),
contract?.multiLegWaypoints?.length
? h(
"div",
{
class: "mono dim",
style: { fontSize: "10px", marginBottom: "6px" },
},
`Multi-Leg Sequence: ${contract.multiLegWaypoints.join(" -> ")}`,
)
: null,
...v.bonusObjectives.map((b) =>
h(
"div",
{ class: `rule-item ${b.met ? "pass" : "fail"}` },
h(
"div",
{ class: "spread" },
h("strong", {}, b.text),
h(
"span",
{ class: `badge ${b.met ? "ok" : "warn"}` },
b.met ? "MET" : "PENDING",
),
),
h(
"span",
{ class: "dim mono", style: { fontSize: "10px" } },
b.detail,
),
),
),
),
);
}
}
export function renderComplianceTab(ctx: BuilderContext): void {
const { bodyEl } = ctx;
if (!ctx.latestValidation) return;
const comp = ctx.latestValidation.compliance;
const waivedSet = new Set(ctx.design.waivedRuleIds ?? []);
const curIdx = MATURITY_ORDER.indexOf(ctx.design.maturity);
const maxIdx = MATURITY_ORDER.indexOf(comp.maxAllowedMaturity);
const nextMaturity = curIdx < 3 ? MATURITY_ORDER[curIdx + 1] : null;
const canAdvance =
nextMaturity && MATURITY_ORDER.indexOf(nextMaturity) <= maxIdx;
const maturityPanel = h(
"div",
{ class: "stage-card active" },
h(
"div",
{ class: "spread" },
h("h3", {}, term("NASA CML / TRL Maturity Gate", "maturity")),
h(
"span",
{
class: `badge ${ctx.design.maturity === "flight-ready" ? "ok" : "info"}`,
},
ctx.design.maturity.toUpperCase(),
),
),
h(
"div",
{ class: "row", style: { gap: "4px" } },
...MATURITY_ORDER.map((m, i) =>
h(
"div",
{
class: `badge ${i <= curIdx ? "ok" : i <= maxIdx ? "info" : "err"}`,
style: { flex: "1", justifyContent: "center", padding: "5px 4px" },
},
m.toUpperCase(),
),
),
),
h(
"div",
{ class: "mono dim", style: { fontSize: "10px" } },
`Passed ${comp.passedCount}/${comp.totalRules} rules • Max Allowed: ${comp.maxAllowedMaturity.toUpperCase()} • Anomaly Risk: +${comp.anomalyRiskPct.toFixed(1)}% • Waivers: ${fmtMoney(comp.waiverCostTotal)}`,
),
nextMaturity
? h(
"button",
{
class: `btn sm ${canAdvance ? "primary" : "ghost"}`,
disabled: !canAdvance,
onClick: async () => {
try {
const saved = await api.post<{ design: RocketDesign }>(
"/api/agency/rocket",
{ design: ctx.design },
);
ctx.design = saved.design;
const res = await api.post<{ maturity: MaturityLevel }>(
"/api/agency/maturity",
{
maturity: nextMaturity,
},
);
ctx.design.maturity = res.maturity;
await refreshMe();
ctx.refreshEngineering(false, true);
ctx.renderAll();
toast(`Advanced to ${res.maturity.toUpperCase()}!`, "ok");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
canAdvance
? `Advance Gate → ${nextMaturity.toUpperCase()}`
: `Resolve Mandatory Blockers for ${nextMaturity.toUpperCase()}`,
)
: h(
"span",
{ class: "green mono", style: { fontSize: "11px" } },
"Vehicle certified FLIGHT-READY for pad integration.",
),
);
bodyEl.appendChild(maturityPanel);
const sortedRules = [...comp.rules].sort((a, b) => {
const rank = (r: typeof a) =>
!r.passed && !r.waived ? 0 : !r.passed && r.waived ? 1 : 2;
return rank(a) - rank(b);
});
for (const r of sortedRules) {
const cls = r.passed ? "pass" : r.waived ? "waived" : "fail";
const item = h(
"div",
{ class: `rule-item ${cls}` },
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "mono", style: { fontWeight: "700" } },
`${r.code} • ${r.title}`,
),
h(
"span",
{ class: `badge ${r.passed ? "ok" : r.waived ? "warn" : "err"}` },
r.passed ? "PASS" : r.waived ? "WAIVED" : r.severity.toUpperCase(),
),
),
h("div", { class: "dim", style: { fontSize: "11px" } }, r.detail),
!r.passed && r.severity === "waiverable"
? h(
"div",
{ class: "row spread", style: { marginTop: "4px" } },
h(
"span",
{ class: "amber mono", style: { fontSize: "10px" } },
term(
`Fee ${fmtMoney(r.waiverCost)} • Risk +${r.riskPenaltyPct}%`,
"waivers",
),
),
h(
"button",
{
class: `btn xs ${waivedSet.has(r.id) ? "warn" : "ghost"}`,
onClick: () => {
if (waivedSet.has(r.id)) waivedSet.delete(r.id);
else waivedSet.add(r.id);
ctx.design.waivedRuleIds = [...waivedSet];
ctx.design.maturity = "concept";
ctx.refreshEngineering(false, true);
ctx.renderSidebarBody();
},
},
waivedSet.has(r.id) ? "Revoke Waiver" : "Grant Waiver",
),
)
: null,
);
bodyEl.appendChild(item);
}
}
export function renderFooter(ctx: BuilderContext): void {
const { footerBar, contract } = ctx;
clear(footerBar);
footerBar.append(
h(
"button",
{
class: "btn sm ghost",
onClick: async () => {
try {
const saved = await api.post<{ design: RocketDesign }>(
"/api/agency/rocket",
{ design: ctx.design },
);
ctx.design = saved.design;
await refreshMe();
ctx.renderAll();
toast("Design saved to hangar.", "ok");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Save Design",
),
h(
"button",
{
class: "btn sm",
onClick: async () => {
try {
await api.post("/api/agency/rocket", { design: ctx.design });
const sim = await api.post<SimResult>("/api/simulate", {
design: ctx.design,
previewOnly: false,
});
await refreshMe();
modal(
sim.success
? "Test Flight Nominal (Sub-Contract)"
: "Test Flight Anomaly Detected",
h(
"div",
{ class: "col" },
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Burnout Ap / Pe"),
h(
"span",
{ class: "v" },
`${fmtNum(sim.apoapsis / 1000)} × ${fmtNum(sim.periapsis / 1000)} km`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Peak Max-Q"),
h(
"span",
{ class: "v" },
`${(sim.maxQ / 1000).toFixed(1)} kPa`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Peak Load / Heat"),
h(
"span",
{ class: "v" },
`${sim.peakGLoad.toFixed(1)} G • ${sim.peakHeatFluxWcm2.toFixed(0)} W/cm²`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Test Range Fee"),
h("span", { class: "v amber" }, fmtMoney(sim.testFee ?? 0)),
),
!sim.success
? h(
"p",
{ class: "red mono", style: { fontSize: "11px" } },
sim.failureDetail,
)
: h(
"p",
{ class: "green mono", style: { fontSize: "11px" } },
"Ascent trajectory achieved stable orbit insertion.",
),
),
[
{ label: "Close", kind: "ghost" },
{
label: "Watch 3D Replay",
kind: "primary",
onClick: () => {
navigate("launch", { testResult: sim });
},
},
],
);
} catch (err) {
const localSim = simulateAscent(
ctx.design,
state.parts,
state.materials,
{
mission: contract,
difficulty: curAgency(ctx).difficulty,
rollAnomalies: false,
sampleEvery: 1.0,
},
);
toast((err as Error).message, "err");
console.warn("Local test estimate:", localSim.failureDetail);
}
},
},
"Test Flight",
),
h(
"button",
{
class: "btn sm primary grow",
onClick: async () => {
try {
const saved = await api.post<{ design: RocketDesign }>(
"/api/agency/rocket",
{ design: ctx.design },
);
ctx.design = saved.design;
await refreshMe();
navigate("config");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Save & Param Config →",
),
);
}

View file

@ -0,0 +1,296 @@
// 3D rocket viewport mesh rebuilds, bottom telemetry HUD, and Pro KSP-style (Saw this in reddit) 3D drag controller
import * as THREE from "three";
import { buildRocketMesh, disposeRocketMesh } from "../../three/rocketMesh.js";
import { buildRocket } from "../../../shared/physics.js";
import type { GlossaryKey } from "../../glossary.js";
import { clear, fmtMoney, fmtNum, h, term } from "../../ui.js";
import type { BuilderContext } from "./context.js";
export async function rebuild3D(
ctx: BuilderContext,
asm: ReturnType<typeof buildRocket>,
refitCamera = false,
): Promise<void> {
const myToken = ++ctx.buildToken;
const built = await buildRocketMesh(asm, {
realModels: true,
fairingCutaway: ctx.fairingCutaway,
selectedUid: ctx.design.designTier === "pro" ? ctx.selectedProUid : null,
showCenters: ctx.showCenters,
});
if (myToken !== ctx.buildToken) {
disposeRocketMesh(built);
return;
}
if (ctx.currentMesh) {
ctx.view.scene.remove(ctx.currentMesh.group);
disposeRocketMesh(ctx.currentMesh);
}
ctx.currentMesh = built;
ctx.view.scene.add(built.group);
if (refitCamera || ctx.view.controls.target.y === 10) {
const midY = Math.max(4, asm.height * 0.48);
const dist = Math.max(16, asm.height * 1.18);
ctx.view.controls.target.set(0, midY, 0);
ctx.view.camera.position.set(dist * 0.72, midY + dist * 0.18, dist * 0.9);
}
}
export function scheduleRebuild3D(
ctx: BuilderContext,
asm: ReturnType<typeof buildRocket>,
refitCamera = false,
immediate = false,
): void {
if (ctx.rebuildTimer) {
clearTimeout(ctx.rebuildTimer);
ctx.rebuildTimer = null;
}
if (immediate) {
void rebuild3D(ctx, asm, refitCamera);
} else {
ctx.rebuildTimer = setTimeout(() => {
ctx.rebuildTimer = null;
if (ctx.latestAssembly)
void rebuild3D(ctx, ctx.latestAssembly, refitCamera);
}, 45);
}
}
export function renderHudOverlay(ctx: BuilderContext): void {
if (!ctx.latestAssembly || !ctx.latestValidation) return;
const v = ctx.latestValidation;
const a = ctx.latestAssembly;
clear(ctx.hudStatsRow);
const pills: Array<{
k: string;
tip: GlossaryKey;
val: string;
cls?: string;
}> = [
{
k: "Total Δv",
tip: "dv",
val: `${fmtNum(v.totalDv)} / ${fmtNum(v.effectiveRequiredDv)} m/s`,
cls: v.dvMargin >= 0 ? "green" : "red",
},
{
k: "Liftoff TWR",
tip: "twr",
val: a.liftoffTwr.toFixed(2),
cls:
a.liftoffTwr >= 1.2 ? "green" : a.liftoffTwr >= 1.05 ? "amber" : "red",
},
{
k: "Est Max-Q",
tip: "max_q",
val: `${(a.estimatedMaxQPa / 1000).toFixed(1)} kPa`,
},
{
k: "Aero Shape",
tip: "fineness",
val: `Cd ${a.aero.baseCd.toFixed(2)} • ${a.aero.frontalAreaM2.toFixed(1)}m²`,
cls: a.aero.hasExposedBluntNose
? "amber"
: a.aero.baseCd <= 0.42
? "green"
: "amber",
},
{
k: "Stability",
tip: "stability_calibers",
val: `${a.stabilityMarginCalibers.toFixed(2)} cal`,
cls:
a.stabilityMarginCalibers >= 0.4
? "green"
: a.stabilityMarginCalibers >= 0
? "amber"
: "red",
},
{ k: "Build Cost", tip: "launch_cost", val: fmtMoney(v.totalMissionCost) },
{
k: "Reliability",
tip: "reliability_risk",
val: ctx.latestReliability
? `${ctx.latestReliability.reliabilityPct.toFixed(0)}%${ctx.latestReliability.staticFired ? " [SF]" : ""}`
: "—",
cls:
ctx.latestReliability && ctx.latestReliability.reliabilityPct >= 90
? "green"
: ctx.latestReliability && ctx.latestReliability.reliabilityPct >= 80
? "amber"
: "red",
},
{
k: "Flight CPU",
tip: "cpu_load",
val: `${Math.round(a.peakComputeLoadEstPct ?? 0)}% peak`,
cls:
(a.peakComputeLoadEstPct ?? 0) > 125
? "bad"
: (a.peakComputeLoadEstPct ?? 0) > 95
? "warn"
: "good",
},
{
k: "Compliance",
tip: "safety_compliance",
val: `${v.compliance.passedCount}/${v.compliance.totalRules}`,
cls: v.compliance.activeFailures.length ? "red" : "green",
},
];
for (const p of pills) {
ctx.hudStatsRow.appendChild(
h(
"div",
{
class: "stat-box",
style: { minWidth: "108px", padding: "7px 10px" },
},
h("div", { class: "k" }, term(p.k, p.tip)),
h(
"div",
{ class: `v ${p.cls ?? ""}`, style: { fontSize: "12px" } },
p.val,
),
),
);
}
}
export function resolveProUid(obj: THREE.Object3D | null): string | null {
let cur = obj;
while (cur) {
if (typeof cur.userData?.proPartUid === "string")
return cur.userData.proPartUid;
cur = cur.parent;
}
return null;
}
export function attachProDragHandlers(ctx: BuilderContext): () => void {
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
function updateNdc(ev: PointerEvent): void {
const rect = ctx.view.renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((ev.clientX - rect.left) / Math.max(1, rect.width)) * 2 - 1;
pointerNdc.y =
-((ev.clientY - rect.top) / Math.max(1, rect.height)) * 2 + 1;
}
const onPointerDown = (ev: PointerEvent) => {
if (
ctx.design.designTier !== "pro" ||
ev.button !== 0 ||
ev.altKey ||
!ctx.currentMesh ||
!ctx.design.proParts
)
return;
updateNdc(ev);
raycaster.setFromCamera(pointerNdc, ctx.view.camera);
const hits = raycaster.intersectObjects(
[...ctx.currentMesh.proPartGroups.values()],
true,
);
if (!hits.length) return;
const uid = resolveProUid(hits[0].object);
if (!uid) return;
const part = ctx.design.proParts.find((p) => p.uid === uid);
if (!part) return;
ctx.selectedProUid = uid;
ctx.dragPlane.visible = true;
ctx.dragPlane.position.copy(hits[0].point);
ctx.dragPlane.lookAt(ctx.view.camera.position);
ctx.dragPlane.updateMatrixWorld(true);
ctx.view.controls.enabled = false;
ctx.isDragging3D = true;
ctx.dragState = {
uid,
startHitY: hits[0].point.y,
startYBottom: part.yBottom,
startHitX: hits[0].point.x,
startHitZ: hits[0].point.z,
startRadial: part.radialOffset,
startGroupPosY: ctx.currentMesh.proPartGroups.get(uid)?.position.y ?? 0,
};
if (ctx.activeTab === "stages") ctx.renderSidebarBody();
ctx.refreshEngineering(false, true);
};
const onPointerMove = (ev: PointerEvent) => {
if (!ctx.isDragging3D || !ctx.dragState || !ctx.design.proParts) return;
const part = ctx.design.proParts.find((p) => p.uid === ctx.dragState!.uid);
if (!part) return;
updateNdc(ev);
raycaster.setFromCamera(pointerNdc, ctx.view.camera);
const hits = raycaster.intersectObjects([ctx.dragPlane], false);
if (!hits.length) return;
const pt = hits[0].point;
let newY = Math.max(
0,
ctx.dragState.startYBottom + (pt.y - ctx.dragState.startHitY),
);
if (newY < 0.5) {
newY = 0;
} else {
for (const other of ctx.design.proParts) {
if (other.uid === part.uid) continue;
const otherTop = other.yBottom + other.length;
if (Math.abs(newY - otherTop) < 0.65) {
newY = otherTop;
break;
}
}
}
part.yBottom = Number(newY.toFixed(2));
const horizDelta = Math.hypot(
pt.x - ctx.dragState.startHitX,
pt.z - ctx.dragState.startHitZ,
);
if (horizDelta > 0.4 || ctx.dragState.startRadial > 0.15) {
const horizDist = Math.hypot(pt.x, pt.z);
if (horizDist < 0.75) {
part.radialOffset = 0;
} else {
part.radialOffset = Number(
Math.max(0.5, Math.min(8.5, horizDist)).toFixed(2),
);
part.radialAngleDeg = Math.round(
((Math.atan2(pt.z, pt.x) * 180) / Math.PI + 360) % 360,
);
}
}
const g = ctx.currentMesh?.proPartGroups.get(part.uid);
if (g)
g.position.y =
ctx.dragState.startGroupPosY +
(part.yBottom - ctx.dragState.startYBottom);
ctx.refreshEngineering(false, false);
};
const onPointerUp = () => {
if (!ctx.isDragging3D) return;
ctx.isDragging3D = false;
ctx.dragState = null;
ctx.dragPlane.visible = false;
ctx.view.controls.enabled = true;
ctx.refreshEngineering(false, true);
if (ctx.activeTab === "stages") ctx.renderSidebarBody();
};
ctx.view.renderer.domElement.addEventListener(
"pointerdown",
onPointerDown,
true,
);
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerup", onPointerUp);
window.addEventListener("pointercancel", onPointerUp);
return () => {
ctx.view.renderer.domElement.removeEventListener(
"pointerdown",
onPointerDown,
true,
);
window.removeEventListener("pointermove", onPointerMove);
window.removeEventListener("pointerup", onPointerUp);
window.removeEventListener("pointercancel", onPointerUp);
};
}

View file

@ -0,0 +1,79 @@
// Contracts market, leaderboard, and exchange screen
import { api } from "../api.js";
import { navigate } from "../router.js";
import { state } from "../state.js";
import type { ContractOffer } from "../../shared/types.js";
import { h, toast } from "../ui.js";
import {
openCustomMissionModal,
type LeaderboardRow,
type PriceRow,
} from "./contracts/customModal.js";
import { renderMarketPanel } from "./contracts/marketPanel.js";
import {
renderOffersPanel,
type OffersPanelState,
} from "./contracts/offersPanel.js";
export function renderContracts(root: HTMLElement): () => void {
const agency = state.agency;
if (!agency) {
navigate("auth");
return () => {};
}
const offersCol = h("div", { class: "col" });
const boardCol = h("div", { class: "col" });
const marketState: { rightTab: "leaderboard" | "market" } = {
rightTab: "leaderboard",
};
const offersState: OffersPanelState = {
offers: [],
offerFilter: "all",
contractorFilter: "all",
};
async function refreshAll(): Promise<void> {
try {
const [offers, leaderboard, prices] = await Promise.all([
api.get<ContractOffer[]>("/api/contracts", true),
api.get<LeaderboardRow[]>("/api/leaderboard", false),
api.get<PriceRow[]>("/api/prices", false),
]);
state.contracts = offers;
offersState.offers = offers;
renderOffersPanel(offersCol, offersState, openCustomMissionModal);
renderMarketPanel(boardCol, leaderboard, prices, marketState);
} catch (err) {
toast((err as Error).message, "err");
}
}
const header = h(
"div",
{ class: "spread" },
h(
"div",
{ class: "row" },
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("dashboard") },
"← Dashboard",
),
h("h2", {}, "Contracts, Leaderboard & Commodity Exchange"),
),
h(
"button",
{ class: "btn xs", onClick: () => void refreshAll() },
"Refresh Feed",
),
);
root.appendChild(
h(
"div",
{ class: "screen list-page" },
header,
h("div", { class: "cols" }, offersCol, boardCol),
),
);
void refreshAll();
const timer = window.setInterval(() => void refreshAll(), 8000);
return () => window.clearInterval(timer);
}

View file

@ -0,0 +1,462 @@
// Custom contract authoring modal
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { refreshMe } from "../../session.js";
import { state } from "../../state.js";
import type {
ContractOffer,
GroundNetworkTier,
} from "../../../shared/types.js";
import { fmtMoney, fmtNum, h, modal, term, toast } from "../../ui.js";
import type { GlossaryKey } from "../../glossary.js";
export interface LeaderboardRow {
name: string;
isAI: boolean;
aiType?: "standard" | "ml";
mlStats?: { episodes: number; avgReward: number; backend: string } | null;
difficulty?: string;
difficultyLabel?: string;
aiSkill?: number | null;
bankrupt: boolean;
sponsorId: string | null;
treasury: number;
reputation: number;
missionsCompleted: number;
missionsFailed: number;
earnedTotal: number;
score: number;
}
export interface PriceRow {
id: string;
kind: string;
name: string;
baseCost: number;
price: number;
changePct: number;
}
const CUSTOM_PRESETS: Record<
string,
{
label: string;
apKm: number;
peKm: number;
incDeg: number;
payloadId: string;
payloadMass: number;
net: GroundNetworkTier;
}
> = {
vleo: {
label: "VLEO Earth Recon",
apKm: 280,
peKm: 240,
incDeg: 51.6,
payloadId: "payload-cubesat-2u",
payloadMass: 650,
net: "regional",
},
leo: {
label: "LEO Constellation",
apKm: 450,
peKm: 420,
incDeg: 51.6,
payloadId: "payload-hubble",
payloadMass: 4200,
net: "regional",
},
sso: {
label: "Sun-Synchronous Polar",
apKm: 720,
peKm: 700,
incDeg: 98.2,
payloadId: "payload-landsat8",
payloadMass: 2900,
net: "regional",
},
geo: {
label: "GEO / Molniya Relay",
apKm: 35786,
peKm: 500,
incDeg: 28.5,
payloadId: "payload-tdrs",
payloadMass: 3600,
net: "global-dsn",
},
l1: {
label: "Sun-Earth L1/L2 Halo",
apKm: 1500000,
peKm: 220,
incDeg: 28.5,
payloadId: "payload-jwst",
payloadMass: 6200,
net: "global-dsn",
},
lunar: {
label: "Lunar Polar Orbit",
apKm: 384400,
peKm: 120,
incDeg: 88.0,
payloadId: "payload-lro",
payloadMass: 2200,
net: "global-dsn",
},
"moon-landing": {
label: "Lunar Surface South Pole",
apKm: 384400,
peKm: 100,
incDeg: 89.2,
payloadId: "payload-apollo-lm",
payloadMass: 15100,
net: "global-dsn",
},
mars: {
label: "Mars Aerocapture Transfer",
apKm: 55000000,
peKm: 200,
incDeg: 28.5,
payloadId: "payload-perseverance",
payloadMass: 4100,
net: "global-dsn",
},
asteroid: {
label: "Deep-Space Asteroid Rendezvous",
apKm: 32000000,
peKm: 200,
incDeg: 28.5,
payloadId: "payload-osiris",
payloadMass: 2400,
net: "global-dsn",
},
jupiter: {
label: "Jovian Radiation Torus",
apKm: 628000000,
peKm: 300,
incDeg: 28.5,
payloadId: "payload-juno",
payloadMass: 4200,
net: "optical-deep-space",
},
solar: {
label: "Inner Heliosphere / Venus Pass",
apKm: 140000000,
peKm: 250,
incDeg: 42.0,
payloadId: "payload-parker",
payloadMass: 1400,
net: "global-dsn",
},
};
export function openCustomMissionModal(): void {
const payloads = state.parts.filter((p) => p.kind === "payload");
const nameEl = h("input", {
class: "input",
type: "text",
value: "Custom Multi-Regime Mission",
}) as HTMLInputElement;
const targetEl = h(
"select",
{ class: "input" },
...Object.entries(CUSTOM_PRESETS).map(([k, v]) =>
h("option", { value: k, selected: k === "geo" }, v.label),
),
) as HTMLSelectElement;
const peEl = h("input", {
class: "input",
type: "number",
value: 500,
min: 120,
max: 50000,
}) as HTMLInputElement;
const apEl = h("input", {
class: "input",
type: "number",
value: 35786,
min: 180,
max: 900000000,
}) as HTMLInputElement;
const incEl = h("input", {
class: "input",
type: "number",
value: 28.5,
step: "0.1",
min: 0,
max: 110,
}) as HTMLInputElement;
const payloadEl = h(
"select",
{ class: "input" },
...payloads.map((p) =>
h(
"option",
{ value: p.id, selected: p.id === "payload-tdrs" },
`${p.name} (${fmtNum(p.dryMass)} kg)`,
),
),
) as HTMLSelectElement;
const massEl = h("input", {
class: "input",
type: "number",
value: 3600,
min: 250,
max: 200000,
}) as HTMLInputElement;
const netEl = h(
"select",
{ class: "input" },
h("option", { value: "regional" }, "Regional Coastal Tracking"),
h(
"option",
{ value: "global-dsn", selected: true },
"Global DSN + TDRS Relay",
),
h("option", { value: "optical-deep-space" }, "Deep-Space Optical Laser"),
) as HTMLSelectElement;
const sigEl = h("input", {
class: "input",
type: "number",
value: 76,
min: 45,
max: 95,
}) as HTMLInputElement;
const pwrEl = h("input", {
class: "input",
type: "number",
value: 20,
min: 0,
max: 50,
}) as HTMLInputElement;
const effEl = h("input", {
class: "input",
type: "number",
value: 64,
min: 35,
max: 85,
}) as HTMLInputElement;
const instEl = h("input", {
class: "input",
type: "number",
value: 2,
min: 0,
max: 4,
}) as HTMLInputElement;
const ecEl = h("input", {
class: "input",
type: "number",
value: 0.28,
step: "0.02",
min: 0.05,
max: 0.45,
}) as HTMLInputElement;
const radEl = h(
"select",
{ class: "input" },
h("option", { value: "low" }, "Low"),
h("option", { value: "moderate", selected: true }, "Moderate"),
h("option", { value: "extreme" }, "Extreme"),
) as HTMLSelectElement;
const budgetEl = h("input", {
class: "input",
type: "number",
value: "",
placeholder: "Auto ($M)",
min: 10,
max: 3000,
}) as HTMLInputElement;
const crewEl = h("input", { type: "checkbox" }) as HTMLInputElement;
const reuseEl = h("input", { type: "checkbox" }) as HTMLInputElement;
const convEl = h("input", {
type: "checkbox",
checked: true,
}) as HTMLInputElement;
targetEl.addEventListener("change", () => {
const p = CUSTOM_PRESETS[targetEl.value];
if (!p) return;
peEl.value = String(p.peKm);
apEl.value = String(p.apKm);
incEl.value = String(p.incDeg);
payloadEl.value = p.payloadId;
massEl.value = String(p.payloadMass);
netEl.value = p.net;
radEl.value =
targetEl.value === "jupiter" || targetEl.value === "solar"
? "extreme"
: convEl.checked
? "moderate"
: "low";
});
payloadEl.addEventListener("change", () => {
const part = payloads.find((p) => p.id === payloadEl.value);
if (part) {
massEl.value = String(Math.max(Number(massEl.value) || 0, part.dryMass));
crewEl.checked = [
"payload-esas-crew",
"payload-apollo-lm",
"payload-gateway",
].includes(part.id);
}
});
const field = (label: string, control: HTMLElement, tipKey?: GlossaryKey) =>
h(
"label",
{
style: {
display: "flex",
flexDirection: "column",
gap: "4px",
fontSize: "11px",
},
},
h("span", { class: "dim" }, tipKey ? term(label, tipKey) : label),
control,
);
const form = h(
"div",
{
class: "col",
style: { gap: "10px", maxHeight: "70vh", overflowY: "auto" },
},
h(
"p",
{ class: "dim", style: { fontSize: "11px", margin: "0" } },
"Author a bespoke multi-constraint contract with custom orbital geometry, comms link thresholds, power margin, efficiency floor, and scientific instrumentation.",
),
field("Mission Title", nameEl),
h(
"div",
{
style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" },
},
field("Orbital Regime", targetEl, "contract_tier"),
field("Recommended Payload", payloadEl),
),
h(
"div",
{
style: {
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: "8px",
},
},
field("Periapsis (km)", peEl, "periapsis"),
field("Apoapsis (km)", apEl, "apoapsis"),
field("Inclination (deg)", incEl, "inclination"),
),
h(
"div",
{
style: {
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: "8px",
},
},
field("Payload Mass (kg)", massEl),
field("Ground Network", netEl, "ground_network"),
field("Budget Override ($M)", budgetEl),
),
h(
"div",
{
style: {
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: "8px",
},
},
field("Min Signal Health (%)", sigEl, "comms_link"),
field("Min Power Margin (%)", pwrEl, "power_margin"),
field("Min Efficiency (0-100)", effEl, "spacecraft_bus"),
),
h(
"div",
{
style: {
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: "8px",
},
},
field("Min Instruments (0-4)", instEl),
field("Eclipse Fraction", ecEl),
field("Radiation Hazard", radEl, "rad_hardening"),
),
h(
"div",
{
class: "row",
style: { gap: "14px", flexWrap: "wrap", paddingTop: "4px" },
},
h(
"label",
{ class: "row", style: { gap: "6px", fontSize: "11px" } },
convEl,
"Convoluted Multi-Constraint",
),
h(
"label",
{ class: "row", style: { gap: "6px", fontSize: "11px" } },
crewEl,
"Crewed Mission",
),
h(
"label",
{ class: "row", style: { gap: "6px", fontSize: "11px" } },
reuseEl,
"Reusable Booster",
),
),
);
modal("Custom Mission Architect", form, [
{ label: "Cancel", kind: "ghost" },
{
label: "Sign Custom Contract (+35% Advance)",
kind: "primary",
onClick: async () => {
try {
const rawBudget = Number(budgetEl.value);
const res = await api.post<{
contract: ContractOffer;
advance: number;
}>("/api/contracts/custom", {
name: nameEl.value.trim() || undefined,
target: targetEl.value,
periapsisKm: Number(peEl.value),
apoapsisKm: Number(apEl.value),
inclinationDeg: Number(incEl.value),
recommendedPayloadId: payloadEl.value,
payloadMass: Number(massEl.value),
requiredGroundNetwork: netEl.value as GroundNetworkTier,
minSignalHealthPct: Number(sigEl.value),
minPowerMarginPct: Number(pwrEl.value),
minEfficiencyScore: Number(effEl.value),
requiredInstrumentsMin: Number(instEl.value),
eclipseFraction: Number(ecEl.value),
radiationHazard: radEl.value as "low" | "moderate" | "extreme",
crewed: crewEl.checked,
isReusable: reuseEl.checked,
isConvoluted: convEl.checked,
budget:
Number.isFinite(rawBudget) && rawBudget > 0
? Math.round(rawBudget * 1e6)
: undefined,
});
toast(
`Custom contract signed: ${res.contract.name} (+${fmtMoney(res.advance)})`,
"ok",
);
await refreshMe();
navigate("dashboard");
return true;
} catch (err) {
toast((err as Error).message, "err");
return false;
}
},
},
]);
}

View file

@ -0,0 +1,176 @@
// Global agency standings leaderboard and price ticker panel
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import { clear, fmtMoney, h } from "../../ui.js";
import type { LeaderboardRow, PriceRow } from "./customModal.js";
export function renderMarketPanel(
boardCol: HTMLElement,
leaderboard: LeaderboardRow[],
prices: PriceRow[],
uiState: { rightTab: "leaderboard" | "market" },
): void {
const agency = state.agency;
clear(boardCol);
const tabs = h(
"div",
{ class: "row" },
h(
"button",
{
class: `btn sm ${uiState.rightTab === "leaderboard" ? "selected" : "ghost"}`,
onClick: () => {
uiState.rightTab = "leaderboard";
renderMarketPanel(boardCol, leaderboard, prices, uiState);
},
},
"Global Standings",
),
h(
"button",
{
class: `btn sm ${uiState.rightTab === "market" ? "selected" : "ghost"}`,
onClick: () => {
uiState.rightTab = "market";
renderMarketPanel(boardCol, leaderboard, prices, uiState);
},
},
"Parts & Alloy Market",
),
);
boardCol.appendChild(tabs);
if (uiState.rightTab === "leaderboard") {
const flightByAgency = new Map(
(state.world?.activeFlights ?? []).map((f) => [f.agencyName, f]),
);
for (let i = 0; i < leaderboard.length; i++) {
const row = leaderboard[i];
const live = flightByAgency.get(row.name);
const isMe = row.name === agency!.name;
boardCol.appendChild(
h(
"div",
{
class: "panel",
style: {
padding: "10px 12px",
borderColor: isMe
? "var(--brand-blue)"
: row.bankrupt
? "var(--red)"
: "var(--border)",
},
},
h(
"div",
{ class: "spread" },
h(
"div",
{ class: "row" },
h(
"span",
{ class: "mono accent", style: { fontWeight: "800" } },
`#${i + 1}`,
),
h("strong", { class: "mono" }, row.name),
row.isAI
? row.aiType === "ml"
? h(
"span",
{
class: "badge ok",
title: row.mlStats
? `ML Policy (${row.mlStats.backend}) • ${row.mlStats.episodes} episodes • avg reward ${row.mlStats.avgReward}`
: "ML-Supported AI Policy",
},
"ML-AI",
)
: h("span", { class: "badge info" }, "AI")
: h("span", { class: "badge ok" }, "PLAYER"),
row.difficultyLabel || row.difficulty
? h(
"span",
{
class: `badge ${row.difficulty === "director" ? "err" : row.difficulty === "engineer" ? "warn" : ""}`,
},
row.difficultyLabel ?? row.difficulty?.toUpperCase(),
)
: null,
row.isAI && row.aiSkill != null
? h(
"span",
{ class: "badge" },
`SKILL ${row.aiSkill.toFixed(2)}`,
)
: null,
row.bankrupt
? h("span", { class: "badge err" }, "BANKRUPT")
: null,
),
h(
"span",
{ class: "mono accent", style: { fontWeight: "700" } },
`${row.score} PTS`,
),
),
h(
"div",
{
class: "row spread dim mono",
style: { fontSize: "11px", marginTop: "6px" },
},
h(
"span",
{},
`Treasury: ${fmtMoney(row.treasury)} • Rep: ${row.reputation.toFixed(1)}`,
),
h(
"span",
{},
`${row.missionsCompleted} OK / ${row.missionsFailed} FAIL`,
),
),
live
? h(
"div",
{ class: "row spread", style: { marginTop: "6px" } },
h(
"span",
{ class: "accent mono", style: { fontSize: "10px" } },
`LIVE FLIGHT → ${live.target.toUpperCase()} (${Math.round(live.progress * 100)}%)`,
),
h(
"button",
{
class: "btn xs primary",
onClick: () => navigate("launch", { spectateId: live.id }),
},
"Spectate",
),
)
: null,
),
);
}
} else {
const sorted = [...prices].sort(
(a, b) => Math.abs(b.changePct) - Math.abs(a.changePct),
);
for (const p of sorted) {
boardCol.appendChild(
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, `${p.name} [${p.kind}]`),
h(
"span",
{
class: `v ${p.changePct > 2 ? "red" : p.changePct < -2 ? "green" : ""}`,
},
`${p.kind === "material" ? `${p.price}%` : fmtMoney(p.price)} (${p.changePct >= 0 ? "+" : ""}${p.changePct}%)`,
),
),
);
}
}
}

View file

@ -0,0 +1,397 @@
// Contract market offers filter bar and selectable contract cards
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { refreshMe } from "../../session.js";
import { currentContract, state } from "../../state.js";
import type { ContractOffer } from "../../../shared/types.js";
import {
clear,
fmtDuration,
fmtMoney,
fmtNum,
h,
term,
toast,
} from "../../ui.js";
export interface OffersPanelState {
offers: ContractOffer[];
offerFilter: "all" | "standard" | "advanced" | "convoluted";
contractorFilter: string;
}
export function renderOffersPanel(
offersCol: HTMLElement,
panelState: OffersPanelState,
onOpenCustomModal: () => void,
): void {
const agency = state.agency;
const offers = panelState.offers;
clear(offersCol);
const active = currentContract();
const hasInFlight = (agency!.activeMissions ?? []).some((m) => !m.settled);
const canSignNew =
!active && !hasInFlight && !agency!.bankrupt && !agency!.terminatedReason;
offersCol.appendChild(
h(
"div",
{ class: "spread", style: { gap: "8px", flexWrap: "wrap" } },
h(
"h3",
{ class: "accent", style: { margin: "0" } },
"Contract Market & Mission Architect",
),
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"button",
{
class: "btn sm warn",
disabled: !canSignNew,
onClick: async () => {
try {
const res = await api.post<{
contract: ContractOffer;
advance: number;
}>("/api/contracts/custom", {
proceduralConvoluted: true,
});
toast(
`Convoluted contract generated: ${res.contract.name} (+${fmtMoney(res.advance)})`,
"ok",
);
await refreshMe();
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"⚡ Generate Convoluted Mission",
),
h(
"button",
{
class: "btn sm primary",
disabled: !canSignNew,
onClick: () => onOpenCustomModal(),
},
"+ Custom Mission Architect",
),
),
),
);
const byContractor = new Map<
string,
{ id: string; name: string; color: string; count: number; isHome: boolean }
>();
const tplOfferCount = new Map<string, number>();
for (const c of offers) {
const tid = c.templateId ?? c.id;
tplOfferCount.set(tid, (tplOfferCount.get(tid) ?? 0) + 1);
const cid = c.contractorId ?? "nasa";
const entry = byContractor.get(cid);
if (entry) {
entry.count++;
} else {
byContractor.set(cid, {
id: cid,
name: c.contractorName ?? cid.toUpperCase(),
color: c.contractorColor ?? "#38bdf8",
count: 1,
isHome: !!c.isHomeSponsor,
});
}
}
const contractorBar = h(
"div",
{ class: "row", style: { gap: "6px", flexWrap: "wrap", marginTop: "4px" } },
h(
"button",
{
class: `btn xs ${panelState.contractorFilter === "all" ? "selected" : "ghost"}`,
onClick: () => {
panelState.contractorFilter = "all";
renderOffersPanel(offersCol, panelState, onOpenCustomModal);
},
},
`All Contractors (${offers.length})`,
),
h(
"button",
{
class: `btn xs ${panelState.contractorFilter === "home" ? "selected" : "ghost"}`,
onClick: () => {
panelState.contractorFilter = "home";
renderOffersPanel(offersCol, panelState, onOpenCustomModal);
},
},
"Home Sponsor (+8% / +15% Rep)",
),
...Array.from(byContractor.values()).map((sp) =>
h(
"button",
{
class: `btn xs ${panelState.contractorFilter === sp.id ? "selected" : "ghost"}`,
style: {
borderColor:
panelState.contractorFilter === sp.id ? sp.color : undefined,
},
onClick: () => {
panelState.contractorFilter = sp.id;
renderOffersPanel(offersCol, panelState, onOpenCustomModal);
},
},
`${sp.isHome ? "* " : ""}${sp.name} (${sp.count})`,
),
),
);
offersCol.appendChild(contractorBar);
const stdCount = offers.filter(
(c) => !c.advanced && !c.isConvoluted && !c.isCustom,
).length;
const advCount = offers.filter((c) => c.advanced && !c.isConvoluted).length;
const convCount = offers.filter((c) => c.isConvoluted || c.isCustom).length;
const filterDef: Array<{
id: OffersPanelState["offerFilter"];
label: string;
}> = [
{ id: "all", label: `All Types (${offers.length})` },
{ id: "standard", label: `Standard (${stdCount})` },
{ id: "advanced", label: `Advanced (${advCount})` },
{ id: "convoluted", label: `Convoluted & Custom (${convCount})` },
];
offersCol.appendChild(
h(
"div",
{
class: "row",
style: { gap: "6px", flexWrap: "wrap", marginTop: "4px" },
},
...filterDef.map((f) =>
h(
"button",
{
class: `btn xs ${panelState.offerFilter === f.id ? "selected" : "ghost"}`,
onClick: () => {
panelState.offerFilter = f.id;
renderOffersPanel(offersCol, panelState, onOpenCustomModal);
},
},
f.label,
),
),
),
);
if (active) {
offersCol.appendChild(
h(
"div",
{
class: "panel",
style: { padding: "12px", borderColor: "var(--brand-blue)" },
},
h(
"div",
{ class: "spread" },
h("strong", { class: "mono" }, `Active: ${active.name}`),
h(
"span",
{ class: "badge ok" },
"contractorName" in active && active.contractorName
? `${active.contractorName} • ${active.targetName}`
: active.targetName,
),
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", marginTop: "4px" } },
"Complete or launch your current contract before accepting or generating a new one.",
),
),
);
}
const filtered = offers.filter((c) => {
if (panelState.contractorFilter === "home" && !c.isHomeSponsor)
return false;
if (
panelState.contractorFilter !== "all" &&
panelState.contractorFilter !== "home" &&
c.contractorId !== panelState.contractorFilter
)
return false;
if (panelState.offerFilter === "standard")
return !c.advanced && !c.isConvoluted && !c.isCustom;
if (panelState.offerFilter === "advanced")
return !!c.advanced && !c.isConvoluted;
if (panelState.offerFilter === "convoluted")
return !!c.isConvoluted || !!c.isCustom;
return true;
});
const grid = h("div", { class: "card-grid" });
for (const c of filtered) {
const acceptId = c.offerId ?? c.id;
const dupCount = tplOfferCount.get(c.templateId ?? c.id) ?? 1;
const btn = h(
"button",
{
class: `btn sm ${c.isActive ? "selected" : "primary"}`,
disabled: !canSignNew,
onClick: async () => {
try {
const res = await api.post<{ advance: number }>(
`/api/contracts/${encodeURIComponent(acceptId)}/accept`,
{},
);
toast(
`Contract signed with ${c.contractorName ?? "sponsor"}! Advance grant +${fmtMoney(res.advance)}.`,
"ok",
);
await refreshMe();
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
c.isActive ? "Active Contract" : "Accept (+35% Advance)",
);
grid.appendChild(
h(
"div",
{ class: `card ${c.isActive ? "selected" : ""}` },
h(
"div",
{ class: "spread", style: { gap: "6px", flexWrap: "wrap" } },
h("h3", {}, c.name),
h(
"div",
{ class: "row", style: { gap: "4px" } },
c.contractorName
? h(
"span",
{
class: "badge",
style: {
borderColor: c.contractorColor ?? "var(--brand-blue)",
color: c.contractorColor ?? "var(--brand-blue)",
},
},
c.contractorName,
)
: null,
c.isHomeSponsor
? h(
"span",
{ class: "badge ok" },
`LOYALTY +${c.loyaltyBonusPct ?? 8}%`,
)
: null,
dupCount > 1
? h("span", { class: "badge" }, `${dupCount} BIDDERS`)
: null,
c.isCustom ? h("span", { class: "badge info" }, "CUSTOM") : null,
c.isConvoluted
? h("span", { class: "badge err" }, "CONVOLUTED")
: c.advanced
? h("span", { class: "badge warn" }, "ADVANCED")
: null,
h(
"span",
{ class: "badge info" },
`Tier ${c.tier} • ${c.targetName}`,
),
),
),
h("p", { class: "sub" }, c.description),
h(
"div",
{ class: "meta" },
h("span", { class: "green" }, `Budget ${fmtMoney(c.budget)}`),
h("span", {}, term(`Base Δv ${fmtNum(c.requiredDv)} m/s`, "req_dv")),
c.windowPenaltyDv > 0
? h("span", { class: "amber" }, `Window +${c.windowPenaltyDv} m/s`)
: h("span", { class: "green" }, "Window Optimal"),
h("span", {}, `Payload ${fmtNum(c.payloadMass)} kg`),
c.crewed ? h("span", { class: "amber" }, "CREWED") : null,
c.isReusable ? h("span", { class: "accent" }, "REUSABLE") : null,
h(
"span",
{ class: "dim" },
term(
`Net: ${c.requiredGroundNetwork ?? "regional"}`,
"ground_network",
),
),
h(
"span",
{ class: "dim" },
term(`Signal ≥${c.minSignalHealthPct ?? 60}%`, "comms_link"),
),
h(
"span",
{ class: "dim" },
term(`Power ≥+${c.minPowerMarginPct ?? 10}%`, "power_margin"),
),
h("span", { class: "dim" }, `Eff ≥${c.minEfficiencyScore ?? 45}`),
c.radiationHazard && c.radiationHazard !== "low"
? h(
"span",
{ class: c.radiationHazard === "extreme" ? "red" : "amber" },
term(
`Rad: ${c.radiationHazard.toUpperCase()}`,
"rad_hardening",
),
)
: null,
c.eclipseFraction
? h(
"span",
{ class: "dim" },
`Eclipse ${Math.round(c.eclipseFraction * 100)}%`,
)
: null,
(c.requiredInstrumentsMin ?? 0) > 0
? h(
"span",
{ class: "accent" },
`${c.requiredInstrumentsMin}+ Instruments`,
)
: null,
(c.bonusObjectives?.length ?? 0) > 0
? h(
"span",
{ class: "green" },
`+${c.bonusObjectives!.length} Bonus Goals`,
)
: null,
),
c.multiLegWaypoints?.length
? h(
"div",
{
class: "dim mono",
style: { fontSize: "10px", marginTop: "6px" },
},
`Legs: ${c.multiLegWaypoints.join(" -> ")}`,
)
: null,
h(
"div",
{ class: "row spread", style: { marginTop: "10px" } },
h(
"span",
{ class: "faint mono", style: { fontSize: "10px" } },
term(
`Orbit ${c.targetOrbit.periapsisKm}×${c.targetOrbit.apoapsisKm} km (${fmtDuration(c.launchWindowPeriodSec)} cycle)`,
"apoapsis",
),
),
btn,
),
),
);
}
offersCol.appendChild(grid);
}

View file

@ -0,0 +1,289 @@
// Number fluxuation simulator 3000
import * as THREE from "three";
import { navigate } from "../router.js";
import { refreshMe, refreshWorld } from "../session.js";
import { currentContract, state } from "../state.js";
import { encodeModelPath, loadFittedModel } from "../three/modelLoader.js";
import { buildLaunchComplex, buildRocketMesh } from "../three/rocketMesh.js";
import { createView } from "../three/sceneManager.js";
import {
buildRocket,
getDifficultyProfile,
isPartUnlocked,
validateDesign,
} from "../../shared/physics.js";
import { h } from "../ui.js";
import {
createFlightsPanel,
createHazardPanel,
createLastSettlementCard,
} from "./dashboard/flightsPanel.js";
import {
createAlertBanners,
createNavGrid,
createTelemetryAndContractCards,
type DashboardSidebarDeps,
} from "./dashboard/sidebarCards.js";
import { openTechLabModal } from "./dashboard/techLabModal.js";
export function renderDashboard(root: HTMLElement): () => void {
const agency = state.agency;
if (!agency) {
navigate("auth");
return () => {};
}
const contract = currentContract();
const hasRocket = !!agency.rocketDesign?.stages?.length;
const viewportEl = h("div", { class: "dash-viewport" });
const sidebarEl = h("div", { class: "dash-sidebar" });
const view = createView(viewportEl, { fov: 44, far: 15000 });
view.addStars(2600, 5000);
view.scene.fog = new THREE.FogExp2(0x0b0e14, 0.0028);
const apron = new THREE.Mesh(
new THREE.CircleGeometry(140, 48),
new THREE.MeshStandardMaterial({
color: 0x151b26,
roughness: 0.9,
metalness: 0.1,
}),
);
apron.rotation.x = -Math.PI / 2;
apron.position.y = -0.15;
view.scene.add(apron);
let padSubject: THREE.Group | null = null;
let disposed = false;
async function populatePad() {
let rocketH = 26;
const padWeather = state.world?.weather ?? "nominal";
if (hasRocket && agency?.rocketDesign) {
try {
const asm = buildRocket(
agency.rocketDesign,
state.parts,
state.materials,
{
mission: contract,
difficulty: agency.difficulty,
weather: padWeather,
},
);
rocketH = asm.height;
} catch {
rocketH = 26;
}
}
try {
const complex = await buildLaunchComplex(hasRocket ? rocketH : 18);
if (disposed) return;
view.scene.add(complex);
} catch {}
if (hasRocket && agency?.rocketDesign) {
const asm = buildRocket(
agency.rocketDesign,
state.parts,
state.materials,
{
mission: contract,
difficulty: agency.difficulty,
weather: padWeather,
},
);
const built = await buildRocketMesh(asm, {
realModels: true,
fairingCutaway: false,
});
if (disposed) return;
padSubject = built.group;
view.scene.add(padSubject);
view.camera.position.set(
asm.height * 0.95,
asm.height * 0.6,
asm.height * 1.15,
);
view.controls.target.set(0, asm.height * 0.45, 0);
} else {
try {
const cat = await loadFittedModel(
encodeModelPath("cat_3d_model_free.glb"),
{
height: 8.5,
anchorBottom: true,
},
);
if (disposed) return;
padSubject = cat;
view.scene.add(padSubject);
view.camera.position.set(16, 10, 20);
view.controls.target.set(0, 4, 0);
} catch (err) {
console.warn("Cat placeholder failed:", err);
}
}
}
view.controls.autoRotate = true;
view.controls.autoRotateSpeed = 0.35;
void populatePad();
const weather = state.world?.weather ?? "nominal";
const weatherClass =
weather === "nominal"
? "ok"
: weather === "solar-wind"
? "info"
: weather === "radiation-storm"
? "err"
: "warn";
const headerBar = h(
"div",
{ class: "dash-header" },
h(
"div",
{ class: "row" },
h("h1", {}, agency.name),
h(
"span",
{ class: "badge info" },
agency.sponsorId?.toUpperCase() ?? "INDEP",
),
h(
"span",
{ class: `badge ${weatherClass}` },
`WX: ${weather.toUpperCase()}`,
),
),
h(
"div",
{ class: "row" },
h(
"span",
{ class: "mono dim", style: { fontSize: "11px" } },
state.world?.simDate ?? "Synchronizing ephemeris...",
),
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("mainMenu") },
"Main Menu",
),
),
);
viewportEl.appendChild(headerBar);
const padStatusCard = h(
"div",
{ class: "panel", style: { padding: "10px 14px" } },
hasRocket
? h(
"div",
{ class: "mono", style: { fontSize: "11px" } },
`Pad Vehicle: ${agency.rocketDesign!.name} (${agency.rocketDesign!.stages.length} stage${agency.rocketDesign!.stages.length > 1 ? "s" : ""}) • Maturity: `,
h(
"span",
{ class: "accent" },
agency.rocketDesign!.maturity.toUpperCase(),
),
)
: h(
"div",
{ class: "mono dim", style: { fontSize: "11px" } },
"Pad Status: Empty Launch Mount — Pad Mascot Holding Pad (cat_3d_model_free.glb). Open Rocket Builder to design a vehicle.",
),
);
viewportEl.appendChild(
h("div", { class: "dash-overlay-bottom" }, padStatusCard),
);
const profile = getDifficultyProfile(agency.difficulty);
const nowSim = state.world?.simTime ?? 0;
const bailoutsUsed = agency.bailoutsTaken ?? 0;
const bailoutsRem = Math.max(0, profile.maxBailouts - bailoutsUsed);
const unlockedSet = new Set(agency.unlockedTechs ?? ["starter"]);
const padDamagedRem = Math.max(
0,
Math.ceil((agency.padDamagedUntilSimTime ?? 0) - nowSim),
);
const groundedRem = Math.max(
0,
Math.ceil((agency.groundedUntilSimTime ?? 0) - nowSim),
);
let validationSummary: ReturnType<typeof validateDesign> | null = null;
let hasLockedDesignParts = false;
if (hasRocket && agency.rocketDesign) {
try {
validationSummary = validateDesign(
agency.rocketDesign,
state.parts,
state.materials,
{
mission: contract,
simTime: state.world?.simTime ?? 0,
weather,
activeHazards: state.world?.activeHazards ?? [],
unlockedTechs: agency.unlockedTechs ?? [],
difficulty: agency.difficulty,
crewedSeats: agency.crewConfig?.crewSize ?? 0,
eclssLevel: agency.crewConfig?.lifeSupport ?? 0,
},
);
hasLockedDesignParts =
agency.rocketDesign.stages.some(
(st) =>
!isPartUnlocked(st.engineId, agency) ||
!isPartUnlocked(st.tankId, agency) ||
!isPartUnlocked(st.structureId, agency) ||
!isPartUnlocked(st.materialId, agency) ||
(!!st.interstageId && !isPartUnlocked(st.interstageId, agency)) ||
(!!st.dropTankId &&
(st.dropTankCount ?? 0) > 0 &&
!isPartUnlocked(st.dropTankId, agency)),
) ||
!isPartUnlocked(agency.rocketDesign.fairingId, agency) ||
(!!agency.rocketDesign.computerId &&
!isPartUnlocked(agency.rocketDesign.computerId, agency)) ||
(agency.rocketDesign.proParts ?? []).some(
(pp) =>
!isPartUnlocked(pp.partId, agency) ||
(!!pp.materialId && !isPartUnlocked(pp.materialId, agency)),
);
} catch {
validationSummary = null;
}
}
const flights = createFlightsPanel();
const deps: DashboardSidebarDeps = {
agency,
contract,
weather,
profile,
unlockedSet,
bailoutsRem,
padDamagedRem,
groundedRem,
validationSummary,
hasLockedDesignParts,
onOpenTechLab: () => openTechLabModal(unlockedSet),
};
const { terminatedBanner, standdownBanner, bailoutBanner } =
createAlertBanners(deps);
const { agencyStatsPanel, contractPanel } =
createTelemetryAndContractCards(deps);
const hazardPanel = createHazardPanel();
const lastSettlementCard = createLastSettlementCard(agency);
const navGrid = createNavGrid(deps);
if (terminatedBanner) sidebarEl.appendChild(terminatedBanner);
if (standdownBanner) sidebarEl.appendChild(standdownBanner);
if (bailoutBanner) sidebarEl.appendChild(bailoutBanner);
sidebarEl.append(agencyStatsPanel, contractPanel);
if (hazardPanel) sidebarEl.appendChild(hazardPanel);
if (lastSettlementCard) sidebarEl.appendChild(lastSettlementCard);
sidebarEl.append(flights.panel, navGrid);
root.appendChild(
h("div", { class: "screen dash-root" }, viewportEl, sidebarEl),
);
const poll = window.setInterval(async () => {
await refreshWorld();
flights.renderFlights();
}, 5000);
void refreshMe();
return () => {
disposed = true;
window.clearInterval(poll);
view.dispose();
};
}

View file

@ -0,0 +1,204 @@
// Live world flights monitor
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import type { AgencyState } from "../../../shared/types.js";
import { clear, fmtMoney, h } from "../../ui.js";
export function createFlightsPanel(): {
panel: HTMLElement;
renderFlights: () => void;
} {
const flightsListEl = h("div", { class: "col", style: { gap: "8px" } });
const activeFlightsPanel = h(
"div",
{ class: "panel", style: { padding: "14px" } },
h(
"div",
{ class: "spread", style: { marginBottom: "8px" } },
h("h3", {}, "Active Flights (Live)"),
h("span", { class: "badge info" }, "WORLD"),
),
flightsListEl,
);
function renderFlights(): void {
clear(flightsListEl);
const flights = state.world?.activeFlights ?? [];
if (!flights.length) {
flightsListEl.appendChild(
h(
"p",
{ class: "dim mono", style: { fontSize: "11px" } },
"No vehicles currently in flight.",
),
);
return;
}
for (const f of flights) {
const pct = Math.min(100, Math.round(f.progress * 100));
flightsListEl.appendChild(
h(
"div",
{
class: "row spread",
style: {
padding: "6px 8px",
background: "var(--bg-deep)",
border: "1px solid var(--border)",
fontSize: "11px",
},
},
h(
"div",
{ class: "col", style: { gap: "2px" } },
h(
"span",
{ class: "mono" },
f.isAI
? `${f.agencyName} [${f.aiType === "ml" ? "ML-AI" : "AI"} • ${(f.difficulty ?? "engineer").toUpperCase()}${f.aiSkill != null ? ` • ${f.aiSkill.toFixed(2)}` : ""}]`
: f.agencyName,
),
h(
"span",
{ class: "dim mono", style: { fontSize: "10px" } },
`${f.target.toUpperCase()} • ${pct}%`,
),
),
h(
"button",
{
class: "btn xs primary",
onClick: () => navigate("launch", { spectateId: f.id }),
},
"Spectate",
),
),
);
}
}
renderFlights();
return { panel: activeFlightsPanel, renderFlights };
}
export function createLastSettlementCard(
agency: AgencyState,
): HTMLElement | null {
return agency.lastSettlement
? h(
"div",
{
class: "panel",
style: {
padding: "12px",
borderColor: agency.lastSettlement.success
? "rgba(52, 211, 153, 0.45)"
: "rgba(248, 113, 113, 0.45)",
},
},
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "11px" } },
`Last Flight: ${agency.lastSettlement.missionName}`,
),
h(
"span",
{ class: `badge ${agency.lastSettlement.success ? "ok" : "err"}` },
agency.lastSettlement.orbitGrade.toUpperCase(),
),
),
h(
"p",
{
class: "dim",
style: { fontSize: "11px", lineHeight: "1.4", marginBottom: "6px" },
},
agency.lastSettlement.summary,
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Settlement Cash"),
h(
"span",
{
class: `v ${agency.lastSettlement.netCashChange >= 0 ? "green" : "red"}`,
},
`${agency.lastSettlement.netCashChange >= 0 ? "+" : "-"}${fmtMoney(Math.abs(agency.lastSettlement.netCashChange))}`,
),
),
)
: null;
}
export function createHazardPanel(): HTMLElement | null {
const activeHazards = state.world?.activeHazards ?? [];
const upcomingHazards = state.world?.upcomingHazards ?? [];
const hazardPanel =
activeHazards.length || upcomingHazards.length
? h(
"div",
{
class: "panel",
style: {
padding: "12px",
borderColor: activeHazards.some((hz) => hz.severity === "extreme")
? "var(--red)"
: activeHazards.length
? "var(--amber)"
: "var(--border)",
},
},
h(
"div",
{ class: "spread", style: { marginBottom: "6px" } },
h("h3", {}, "Launch Environment Forecast"),
h(
"span",
{ class: `badge ${activeHazards.length ? "warn" : "ok"}` },
activeHazards.length
? `${activeHazards.length} ACTIVE`
: "NOMINAL",
),
),
...activeHazards.map((hz) =>
h(
"div",
{ class: "rule-item waived", style: { marginBottom: "6px" } },
h(
"div",
{ class: "spread" },
h("strong", { class: "amber" }, hz.title),
h(
"span",
{ class: "badge warn" },
`${hz.altMinKm}–${hz.altMaxKm} km`,
),
),
h(
"div",
{ class: "dim", style: { fontSize: "11px" } },
hz.description,
),
h(
"div",
{ class: "accent mono", style: { fontSize: "10px" } },
`Mitigation: ${hz.countermeasureHint}`,
),
),
),
upcomingHazards.length
? h(
"div",
{
class: "dim mono",
style: { fontSize: "10px", marginTop: "4px" },
},
`Forecast next window: ${upcomingHazards.map((u) => u.title).join(", ")}`,
)
: null,
)
: null;
return hazardPanel;
}

View file

@ -0,0 +1,514 @@
// Dashboard status banners, active contract, and launch controls
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import {
getDifficultyProfile,
TECH_TREE,
validateDesign,
} from "../../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
MissionTemplate,
} from "../../../shared/types.js";
import { fmtMoney, fmtNum, h, modal, term, toast } from "../../ui.js";
export interface DashboardSidebarDeps {
agency: AgencyState;
contract: ContractOffer | MissionTemplate | null;
weather: string;
profile: ReturnType<typeof getDifficultyProfile>;
unlockedSet: Set<string>;
bailoutsRem: number;
padDamagedRem: number;
groundedRem: number;
validationSummary: ReturnType<typeof validateDesign> | null;
hasLockedDesignParts: boolean;
onOpenTechLab: () => void;
}
export function createAlertBanners(deps: DashboardSidebarDeps): {
terminatedBanner: HTMLElement | null;
standdownBanner: HTMLElement | null;
bailoutBanner: HTMLElement | null;
} {
const { agency, profile, bailoutsRem, padDamagedRem, groundedRem } = deps;
const terminatedBanner = agency.terminatedReason
? h(
"div",
{
class: "panel",
style: { padding: "12px", borderColor: "var(--red)" },
},
h(
"div",
{ class: "col", style: { gap: "8px" } },
h("h3", { class: "red" }, "AGENCY LICENSE REVOKED"),
h(
"p",
{ class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } },
agency.terminatedReason,
),
h(
"button",
{
class: "btn sm danger",
onClick: async () => {
const res = await api.post<{ agency: AgencyState }>(
"/api/agency/reset",
{},
);
state.agency = res.agency;
navigate("onboarding");
},
},
"Reset Agency & Start New Program",
),
),
)
: null;
const standdownBanner =
!agency.terminatedReason && (padDamagedRem > 0 || groundedRem > 0)
? h(
"div",
{
class: "panel",
style: { padding: "12px", borderColor: "var(--amber)" },
},
h(
"div",
{ class: "col", style: { gap: "8px" } },
h("h3", { class: "amber" }, "OPERATIONAL STAND-DOWN ACTIVE"),
groundedRem > 0
? h(
"p",
{ class: "dim mono", style: { fontSize: "11px" } },
`Safety Board Grounding: ${groundedRem}s sim remaining`,
)
: null,
padDamagedRem > 0
? h(
"p",
{ class: "dim mono", style: { fontSize: "11px" } },
`Pad Blast Repair: ${padDamagedRem}s sim remaining`,
)
: null,
h(
"button",
{
class: "btn sm warn",
onClick: async () => {
try {
const res = await api.post<{
fee: number;
agency: AgencyState;
}>("/api/agency/clear-standdown", {});
state.agency = res.agency;
toast(
`Expedited clearance approved (-${fmtMoney(res.fee)}).`,
"ok",
);
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
`Expedite Clearance (${fmtMoney((padDamagedRem > 0 ? 4_000_000 : 0) + (groundedRem > 0 ? 6_000_000 : 0))})`,
),
),
)
: null;
const bailoutBanner =
!agency.terminatedReason &&
(agency.bankrupt || agency.treasury < 25_000_000)
? h(
"div",
{
class: "panel",
style: { padding: "12px", borderColor: "var(--red)" },
},
h(
"div",
{ class: "col", style: { gap: "8px" } },
h(
"h3",
{ class: "red" },
agency.bankrupt ? "AGENCY INSOLVENT" : "LOW TREASURY WARNING",
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } },
bailoutsRem > 0
? `${agency.bankrupt ? "Launch operations suspended until capital is restored." : "Funds below $25M."} Emergency bailouts remaining: ${bailoutsRem}/${profile.maxBailouts}.`
: `No sponsor bailouts remaining on ${profile.label} difficulty. Reset Agency to start a new campaign.`,
),
h(
"div",
{ class: "row" },
h(
"button",
{
class: "btn sm warn grow",
disabled: bailoutsRem <= 0,
onClick: async () => {
try {
const res = await api.post<{
grant: number;
agency: AgencyState;
}>("/api/agency/bailout", {});
state.agency = res.agency;
toast(
`Sponsor restructuring grant approved (+${fmtMoney(res.grant)}).`,
"ok",
);
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
bailoutsRem > 0
? `Grant (${bailoutsRem} left)`
: "No Bailouts Left",
),
h(
"button",
{
class: "btn sm danger",
onClick: () => {
modal(
"Reset Agency Program?",
h(
"p",
{ class: "dim" },
"This clears treasury, contracts, and rocket design back to Step 1 onboarding.",
),
[
{ label: "Cancel", kind: "ghost" },
{
label: "Confirm Reset",
kind: "danger",
onClick: async () => {
const res = await api.post<{ agency: AgencyState }>(
"/api/agency/reset",
{},
);
state.agency = res.agency;
navigate("onboarding");
},
},
],
);
},
},
"Reset",
),
),
),
)
: null;
return { terminatedBanner, standdownBanner, bailoutBanner };
}
export function createTelemetryAndContractCards(deps: DashboardSidebarDeps): {
agencyStatsPanel: HTMLElement;
contractPanel: HTMLElement;
} {
const {
agency,
contract,
profile,
unlockedSet,
bailoutsRem,
validationSummary,
hasLockedDesignParts,
onOpenTechLab,
} = deps;
const agencyStatsPanel = h(
"div",
{ class: "panel", style: { padding: "14px" } },
h(
"div",
{ class: "spread", style: { marginBottom: "8px" } },
h("h3", {}, "Agency Telemetry"),
h("span", { class: "badge info" }, term(profile.label, "difficulty")),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Treasury"),
h(
"span",
{ class: `v ${agency.treasury < 25e6 ? "red" : "green"}` },
fmtMoney(agency.treasury),
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Reputation"),
h("span", { class: "v accent" }, `${agency.reputation.toFixed(1)} RP`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Record"),
h(
"span",
{ class: "v" },
`${agency.missionsCompleted} OK / ${agency.missionsFailed} FAIL`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Bailouts / Losses", "crew_eclss")),
h(
"span",
{ class: `v ${(agency.casualtiesTotal ?? 0) > 0 ? "red" : ""}` },
`${bailoutsRem}/${profile.maxBailouts} Bailouts • ${agency.casualtiesTotal ?? 0} Crew Lost`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Insurance / R&D", "rd_tech")),
h(
"span",
{ class: "v" },
`${agency.launchInsured || profile.id === "explorer" || profile.id === "sandbox" ? "INSURED" : "UNINSURED"} • ${unlockedSet.size}/${TECH_TREE.length}`,
),
),
h(
"button",
{
class: "btn sm primary",
style: { marginTop: "10px", width: "100%" },
onClick: () => onOpenTechLab(),
},
`R&D Tech Lab (${unlockedSet.size}/${TECH_TREE.length} Unlocked)`,
),
);
const contractPanel = h(
"div",
{ class: "panel", style: { padding: "14px" } },
h(
"div",
{ class: "spread", style: { marginBottom: "6px" } },
h("h3", {}, "Active Contract"),
contract
? h("span", { class: "badge info" }, contract.targetName)
: h("span", { class: "badge warn" }, "NONE"),
),
contract
? h(
"div",
{ class: "col", style: { gap: "6px" } },
h(
"div",
{ class: "mono", style: { fontSize: "12px", fontWeight: "700" } },
contract.name,
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } },
contract.description,
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Payout Budget", "contract_tier")),
h("span", { class: "v green" }, fmtMoney(contract.budget)),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Required Δv", "req_dv")),
h(
"span",
{ class: "v" },
`${fmtNum(validationSummary?.effectiveRequiredDv ?? contract.requiredDv)} m/s`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Payload"),
h("span", { class: "v" }, `${fmtNum(contract.payloadMass)} kg`),
),
validationSummary
? h(
"div",
{ class: "stat-row" },
h(
"span",
{ class: "k" },
term("Launch Readiness", "safety_compliance"),
),
h(
"span",
{
class: `v ${validationSummary.valid && !hasLockedDesignParts && (agency.rocketDesign?.maturity === "flight-ready" || profile.id === "sandbox") ? "green" : "amber"}`,
},
hasLockedDesignParts
? "LOCKED R&D PARTS"
: validationSummary.valid
? agency.rocketDesign?.maturity === "flight-ready" ||
profile.id === "sandbox"
? "FLIGHT-READY"
: `MATURITY: ${agency.rocketDesign?.maturity.toUpperCase()}`
: `${validationSummary.errors.length} BLOCKERS`,
),
)
: null,
)
: h(
"div",
{ class: "col", style: { gap: "8px" } },
h(
"p",
{ class: "dim", style: { fontSize: "11px" } },
"No active contract assigned. Browse the Contract Market to bid on a mission.",
),
h(
"button",
{ class: "btn sm primary", onClick: () => navigate("contracts") },
"Open Contract Market",
),
),
);
return { agencyStatsPanel, contractPanel };
}
export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement {
const {
agency,
contract,
profile,
padDamagedRem,
groundedRem,
validationSummary,
hasLockedDesignParts,
onOpenTechLab,
} = deps;
const hasActiveOwnFlight = (agency.activeMissions ?? []).some(
(m) => !m.settled,
);
const canLaunch =
!agency.terminatedReason &&
!agency.bankrupt &&
padDamagedRem <= 0 &&
groundedRem <= 0 &&
!hasActiveOwnFlight &&
!hasLockedDesignParts &&
!!contract &&
!!agency.rocketDesign &&
!!validationSummary?.valid &&
(agency.rocketDesign.maturity === "flight-ready" ||
profile.id === "sandbox") &&
agency.treasury >= (validationSummary?.totalMissionCost ?? 0);
const launchBtnLabel = hasActiveOwnFlight
? "Mission In Flight — Spectate"
: padDamagedRem > 0 || groundedRem > 0
? "Launch Stand-Down Active"
: canLaunch
? `Launch Mission (${fmtMoney(validationSummary!.totalMissionCost)})`
: "Launch Mission (Needs Flight-Ready Vehicle)";
const navGrid = h(
"div",
{ class: "dash-nav" },
h(
"button",
{ class: "btn", onClick: () => navigate("builder") },
"Rocket Builder",
),
h(
"button",
{ class: "btn", onClick: () => navigate("config") },
"Param Config",
),
h(
"button",
{ class: "btn", onClick: () => navigate("worldMap") },
"World Map",
),
h(
"button",
{ class: "btn", onClick: () => navigate("contracts") },
"Contracts & Rank",
),
h(
"button",
{
class: `btn full-span ${canLaunch || hasActiveOwnFlight ? "primary" : "warn"}`,
onClick: () => {
if (hasActiveOwnFlight) {
const openFlight = (agency.activeMissions ?? []).find(
(m) => !m.settled,
);
if (openFlight) navigate("launch", { spectateId: openFlight.id });
return;
}
if (agency.terminatedReason) {
toast(agency.terminatedReason, "err");
return;
}
if (padDamagedRem > 0 || groundedRem > 0) {
toast(
"Launch stand-down active. Wait for clearance or click Expedite Clearance.",
"warn",
);
return;
}
if (!contract) {
toast("Accept a contract first.", "err");
navigate("contracts");
return;
}
if (!agency.rocketDesign) {
toast("Build and save a rocket design first.", "err");
navigate("builder");
return;
}
if (hasLockedDesignParts) {
toast(
"Rocket uses locked R&D parts. Unlock them in the R&D Tech Lab first.",
"err",
);
onOpenTechLab();
return;
}
if (!validationSummary?.valid) {
toast(
validationSummary?.errors[0] ??
"Resolve engineering blockers in Rocket Builder.",
"err",
);
navigate("builder");
return;
}
if (
profile.id !== "sandbox" &&
agency.rocketDesign.maturity !== "flight-ready"
) {
toast(
"Advance vehicle maturity to FLIGHT-READY in Rocket Builder.",
"warn",
);
navigate("builder");
return;
}
if (agency.treasury < validationSummary.totalMissionCost) {
toast("Insufficient treasury funds for vehicle + waivers.", "err");
return;
}
navigate("launch");
},
},
launchBtnLabel,
),
);
return navGrid;
}

View file

@ -0,0 +1,91 @@
// R&D technology unlock modal dialog
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import { TECH_TREE } from "../../../shared/physics.js";
import type { AgencyState } from "../../../shared/types.js";
import { fmtMoney, h, modal, toast } from "../../ui.js";
export function openTechLabModal(unlockedSet: Set<string>): void {
const agency = state.agency;
const listEl = h("div", {
class: "col",
style: { gap: "8px", maxHeight: "60vh", overflowY: "auto" },
});
for (const node of TECH_TREE) {
const unlocked = unlockedSet.has(node.id);
const repMet = (agency!.reputation ?? 0) >= node.minReputation;
listEl.appendChild(
h(
"div",
{
class: "panel",
style: {
padding: "10px 12px",
borderColor: unlocked
? "rgba(52, 211, 153, 0.45)"
: "var(--border)",
},
},
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "12px" } },
node.name,
),
unlocked
? h("span", { class: "badge ok" }, "UNLOCKED")
: h("span", { class: "badge warn" }, fmtMoney(node.cost)),
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", marginBottom: "6px" } },
node.description,
),
!unlocked
? h(
"div",
{ class: "row spread" },
h(
"span",
{ class: "mono dim", style: { fontSize: "10px" } },
!repMet
? `Requires ${node.minReputation} RP (have ${agency!.reputation.toFixed(1)} RP)`
: `Unlocks ${node.unlocksIds.length} parts/materials`,
),
h(
"button",
{
class: "btn xs primary",
disabled:
!repMet ||
agency!.treasury < node.cost ||
!!agency!.terminatedReason,
onClick: async () => {
try {
const res = await api.post<{ agency: AgencyState }>(
"/api/agency/unlock-tech",
{
techId: node.id,
},
);
state.agency = res.agency;
document.querySelector(".modal-backdrop")?.remove();
toast(`Unlocked R&D Tech: ${node.name}`, "ok");
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
`Research (${fmtMoney(node.cost)})`,
),
)
: null,
),
);
}
modal("R&D Technology Tree", listEl, [{ label: "Close", kind: "ghost" }]);
}

View file

@ -0,0 +1,464 @@
// post-flight mission debriefing, grading, casualty/LAS outcome, financials, and coach diagnostics.
// fancy talk for stage completed
import { navigate } from "../router.js";
import { refreshMe } from "../session.js";
import {
applyThemeFromState,
currentContract,
type DebriefScreenParams,
state,
} from "../state.js";
import {
buildRocket,
generateCoachDiagnostics,
getDifficultyProfile,
validateDesign,
} from "../../shared/physics.js";
import type { CoachDiagnostic } from "../../shared/types.js";
import { fmtDuration, fmtMoney, fmtNum, h, term } from "../ui.js";
export function renderDebrief(
root: HTMLElement,
params: DebriefScreenParams = {},
): void {
const mission = params.mission;
const settlement =
params.settlement ?? mission?.settlement ?? state.agency?.lastSettlement;
const ascent = mission?.ascent ?? params.testResult;
const isTest = !mission && !!params.testResult;
const isSpectating = !!params.isSpectating;
applyThemeFromState(ascent?.success ? "orbit" : "failed");
if (!ascent) {
navigate("dashboard");
return;
}
const orbitGrade =
settlement?.orbitGrade ??
ascent.orbitGrade ??
(ascent.success ? "nominal" : "failed");
const crewOutcome = settlement?.crewOutcome ?? ascent.crewOutcome ?? "none";
let grade: "S" | "A" | "B" | "C" | "F" = "F";
if (ascent.success) {
const dvMargin = mission?.validation?.dvMargin ?? ascent.dvRemaining;
if (orbitGrade === "partial") grade = "C";
else if (dvMargin > 600 && ascent.peakGLoad < 5.5) grade = "S";
else if (dvMargin > 200) grade = "A";
else if (dvMargin >= 0) grade = "B";
else grade = "C";
}
const orbitBadgeText =
orbitGrade === "nominal"
? "NOMINAL ORBIT"
: orbitGrade === "partial"
? "PARTIAL ORBIT (30% PAYOUT)"
: "ORBITAL MISINJECTION";
const orbitBadgeCls =
orbitGrade === "nominal" ? "ok" : orbitGrade === "partial" ? "warn" : "err";
const crewBanner =
crewOutcome === "las_saved"
? h(
"div",
{
class: "panel",
style: { padding: "10px 12px", borderColor: "var(--amber)" },
},
h(
"strong",
{ class: "amber mono" },
"LAUNCH ABORT SYSTEM SAVE — 0 CASUALTIES",
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", marginTop: "4px" } },
"All crew members recovered via escape tower. Vehicle lost; inquiry fine avoided.",
),
)
: crewOutcome === "loss_of_crew"
? h(
"div",
{
class: "panel",
style: { padding: "10px 12px", borderColor: "var(--red)" },
},
h(
"strong",
{ class: "red mono" },
`LOSS OF CREW (LOC) — ${settlement?.casualties ?? 2} FATALITIES`,
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", marginTop: "4px" } },
settlement?.agencyTerminated
? "Catastrophic crew loss revoked your agency operating license."
: "Safety board imposed $18M inquiry penalty, -75% reputation collapse, and a launch stand-down.",
),
)
: crewOutcome === "nominal"
? h("span", { class: "badge ok" }, "CREW SAFE ON ORBIT")
: null;
let diagnostics: CoachDiagnostic[] = [];
const designUsed = mission?.rocketDesign ?? state.agency?.rocketDesign;
if (designUsed) {
try {
const asm = buildRocket(designUsed, state.parts, state.materials);
const val =
mission?.validation ??
validateDesign(designUsed, state.parts, state.materials, {
mission: mission?.contract ?? currentContract(),
simTime: state.world?.simTime ?? 0,
weather: state.world?.weather ?? "nominal",
});
diagnostics = generateCoachDiagnostics(
designUsed,
asm,
val,
mission?.contract ?? currentContract(),
state.agency?.difficulty,
ascent,
).slice(0, 3);
} catch {
diagnostics = [];
}
}
const profile = getDifficultyProfile(state.agency?.difficulty);
const advancePayout =
settlement?.advancePayout ??
(mission?.contract?.budget
? Math.round(mission.contract.budget * 0.35)
: 0);
const netOutcomeAfterLaunch = settlement
? settlement.netCashChange - (mission?.cost ?? 0)
: -(mission?.cost ?? 0);
const totalProgramPnl = advancePayout + netOutcomeAfterLaunch;
const ledgerCard = mission
? h(
"div",
{ class: "panel", style: { padding: "12px", marginTop: "6px" } },
h(
"h3",
{ style: { marginBottom: "6px", fontSize: "12px" } },
"Financial & Reputation Settlement Ledger",
),
advancePayout > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Contract Advance (35% Signed)"),
h("span", { class: "v green" }, `+${fmtMoney(advancePayout)}`),
)
: null,
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Vehicle Launch Expense"),
h("span", { class: "v red" }, `-${fmtMoney(mission.cost)}`),
),
settlement && settlement.grossPayout > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Completion & Efficiency Balance"),
h(
"span",
{ class: "v green" },
`+${fmtMoney(settlement.grossPayout)}`,
),
)
: null,
settlement && (settlement.scienceBonus ?? 0) > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Science & Instrument Bonus"),
h(
"span",
{ class: "v green" },
`+${fmtMoney(settlement.scienceBonus ?? 0)}`,
),
)
: null,
settlement && settlement.reusabilityBonus > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Booster Recovery Bonus"),
h(
"span",
{ class: "v green" },
`+${fmtMoney(settlement.reusabilityBonus)}`,
),
)
: null,
settlement && settlement.insurancePayout > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Insurance Hull Claim (70%)"),
h(
"span",
{ class: "v green" },
`+${fmtMoney(settlement.insurancePayout)}`,
),
)
: null,
settlement && settlement.breachPenalty > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Contract Breach Fine"),
h(
"span",
{ class: "v red" },
`-${fmtMoney(settlement.breachPenalty)}`,
),
)
: null,
settlement && settlement.padRepairCost > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Pad Blast Rebuild Cost"),
h(
"span",
{ class: "v red" },
`-${fmtMoney(settlement.padRepairCost)}`,
),
)
: null,
settlement && settlement.crewInquiryFine > 0
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Crew Safety Board Inquiry Fine"),
h(
"span",
{ class: "v red" },
`-${fmtMoney(settlement.crewInquiryFine)}`,
),
)
: null,
settlement
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Total Contract Program P&L"),
h(
"span",
{ class: `v ${totalProgramPnl >= 0 ? "green" : "red"}` },
`${totalProgramPnl >= 0 ? "+" : "-"}${fmtMoney(Math.abs(totalProgramPnl))}`,
),
)
: null,
ascent.efficiencyGrade
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Efficiency & Ground Signal"),
h(
"span",
{ class: "v accent" },
`Grade ${ascent.efficiencyGrade} (${ascent.efficiencyScore ?? 75}/100) • Min Sig ${ascent.minSignalHealthPct ?? 80}%`,
),
)
: null,
settlement
? h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Reputation / Research Delta"),
h(
"span",
{
class: `v ${settlement.reputationDelta >= 0 ? "green" : "red"}`,
},
`${settlement.reputationDelta >= 0 ? "+" : ""}${settlement.reputationDelta.toFixed(1)} RP`,
),
)
: null,
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Current Treasury"),
h(
"span",
{
class: `v ${(state.agency?.treasury ?? 0) < 25e6 ? "amber" : "green"}`,
},
fmtMoney(state.agency?.treasury ?? 0),
),
),
)
: null;
const coachCard = diagnostics.length
? h(
"div",
{ class: "panel", style: { padding: "12px", marginTop: "4px" } },
h(
"div",
{ class: "spread", style: { marginBottom: "6px" } },
h(
"h3",
{ style: { fontSize: "12px" } },
"Root-Cause Diagnostic Coach",
),
h("span", { class: "badge info" }, profile.coachMode.toUpperCase()),
),
...diagnostics.map((d) =>
h(
"div",
{
style: {
padding: "6px 0",
borderTop: "1px solid var(--border)",
fontSize: "11px",
},
},
h(
"div",
{ class: "row", style: { gap: "6px", marginBottom: "2px" } },
h(
"span",
{
class: `badge ${d.severity === "critical" ? "err" : d.severity === "warn" ? "warn" : "info"}`,
},
d.code,
),
h("strong", {}, d.title),
),
h(
"p",
{ class: "dim", style: { lineHeight: "1.4" } },
d.explanation,
),
h(
"p",
{
class: "accent mono",
style: { fontSize: "10px", marginTop: "2px" },
},
`Action: ${d.actionHint}`,
),
),
),
)
: null;
const card = h(
"div",
{ class: "panel debrief-card col" },
h(
"div",
{ class: "spread" },
h(
"h2",
{},
isTest
? "Test Range Debrief"
: isSpectating
? `Telemetry Debrief — ${mission?.agencyName}`
: "Mission After-Action Report",
),
h("span", { class: `badge ${orbitBadgeCls}` }, orbitBadgeText),
),
crewBanner,
h(
"div",
{ class: "score-ring" },
h("div", { class: `grade ${grade.toLowerCase()}` }, grade),
h(
"div",
{ class: "col", style: { gap: "6px" } },
h("h3", {}, mission?.name ?? "Sub-Contract Test Flight"),
h(
"p",
{
class: ascent.success ? "green mono" : "red mono",
style: { fontSize: "12px", lineHeight: "1.45" },
},
settlement?.summary
? settlement.summary
: ascent.success
? `Vehicle inserted into ${fmtNum(ascent.periapsis / 1000)}×${fmtNum(ascent.apoapsis / 1000)} km orbit at ${ascent.inclinationDeg.toFixed(1)}° inclination.`
: ascent.failureDetail,
),
mission?.trajectory
? h(
"span",
{ class: "badge info" },
`Astrodynamics Propagator: ${mission.trajectory.source.toUpperCase()}`,
)
: null,
),
),
h(
"div",
{ class: "stat-grid" },
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Burnout Velocity", "burnout_metrics")),
h("div", { class: "v" }, `${fmtNum(ascent.burnoutVelocity)} m/s`),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Burnout Altitude", "burnout_metrics")),
h("div", { class: "v" }, `${fmtNum(ascent.burnoutAltitude / 1000)} km`),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Final Orbit Pe×Ap", "periapsis")),
h(
"div",
{ class: "v" },
`${fmtNum(ascent.periapsis / 1000)} × ${fmtNum(ascent.apoapsis / 1000)} km`,
),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Peak Accel / Thermal", "heat_flux")),
h(
"div",
{ class: "v" },
`${ascent.peakGLoad.toFixed(1)} G / ${ascent.peakHeatFluxWcm2.toFixed(0)} W/cm²`,
),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, term("Reserve Δv", "dv_remaining")),
h("div", { class: "v" }, `${fmtNum(ascent.dvRemaining)} m/s`),
),
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, "Flight Duration"),
h("div", { class: "v" }, fmtDuration(ascent.finalTime)),
),
),
ledgerCard,
coachCard,
h(
"div",
{ class: "row", style: { marginTop: "8px" } },
h(
"button",
{ class: "btn primary", onClick: () => navigate("dashboard") },
"Return to Dashboard",
),
h(
"button",
{ class: "btn", onClick: () => navigate("builder") },
"Modify Rocket",
),
h(
"button",
{ class: "btn ghost", onClick: () => navigate("contracts") },
"Contracts & Leaderboard",
),
),
);
root.appendChild(h("div", { class: "screen debrief-root" }, card));
void refreshMe();
}

View file

@ -0,0 +1,408 @@
// Effects so it looks cool and people ignore how broken things probably are
import * as THREE from "three";
import { setPlumeAtmosphere } from "../../three/rocketMesh.js";
import { getColorMode, isReducedEffects } from "../../theme.js";
import type { TelemetrySample } from "../../../shared/types.js";
import type { LaunchContext } from "./context.js";
import { advanceGpuPool, spawnExhaustParticle } from "./particles.js";
const skyLow = new THREE.Color(0x0c1a33);
const skyMid = new THREE.Color(0x091020);
const skySpace = new THREE.Color(0x0b0e14);
const tmpColor = new THREE.Color();
const nozzleWorldPos = new THREE.Vector3();
const exhaustDir = new THREE.Vector3();
export function updateAscentVisuals(
ctx: LaunchContext,
sample: TelemetrySample,
tPos: number,
dt: number,
now: number,
): void {
if (ctx.simClock < 0) {
ctx.bannerEl.textContent = `T-00:0${Math.ceil(Math.abs(ctx.simClock))} // IGNITION SEQUENCE`;
} else {
ctx.bannerEl.textContent = sample.thrusting
? `STAGE ${sample.stage} BURN • MACH ${(sample.mach ?? 0).toFixed(2)} • ALT ${(sample.altitude / 1000).toFixed(1)} KM`
: `COASTING • MACH ${(sample.mach ?? 0).toFixed(2)} • ALT ${(sample.altitude / 1000).toFixed(1)} KM`;
}
const altM = sample.altitude;
const drM = sample.downrange;
const altKm = altM / 1000;
const rM = Math.hypot(altM, drM);
const visR = rM < 400 ? rM * 0.25 : 100 + Math.pow(rM - 400, 0.72) * 0.35;
const isoScale = rM > 1e-3 ? visR / rM : 0.25;
const visAlt = altM * isoScale;
const visDr = drM * isoScale;
const prevPos = ctx.rocketRoot.position.clone();
ctx.rocketRoot.position.set(visDr, visAlt + ctx.cgPivotY, 0);
ctx.rocketRoot.rotation.z = -((90 - sample.pitchDeg) * Math.PI) / 180;
const aoaBuffet =
!isReducedEffects() &&
sample.dynamicPressure > 15000 &&
Math.abs(sample.aoaDeg ?? 0) > 6
? Math.sin(now * 0.045) * 0.025
: 0;
ctx.rocketRoot.rotation.x = aoaBuffet;
ctx.rocketRoot.updateMatrixWorld(true);
ctx.view.camera.position.sub(ctx.prevShake);
ctx.prevShake.set(0, 0, 0);
const delta = ctx.rocketRoot.position.clone().sub(prevPos);
if (ctx.camMode === "track") {
ctx.view.camera.position.add(delta);
ctx.view.controls.target
.copy(ctx.rocketRoot.position)
.add(new THREE.Vector3(0, ctx.rocketHeightVis * 0.1, 0));
} else if (ctx.camMode === "chase") {
const backDir = new THREE.Vector3(0, -1, 0).applyEuler(
ctx.rocketRoot.rotation,
);
const chasePos = ctx.rocketRoot.position
.clone()
.add(backDir.multiplyScalar(Math.max(24, ctx.rocketHeightVis * 0.75)))
.add(new THREE.Vector3(0, 8, Math.max(26, ctx.rocketHeightVis * 0.7)));
ctx.view.camera.position.lerp(chasePos, Math.min(1, dt * 7));
ctx.view.controls.target
.copy(ctx.rocketRoot.position)
.add(new THREE.Vector3(0, ctx.rocketHeightVis * 0.15, 0));
} else if (ctx.camMode === "nose" && ctx.rocketHandle) {
const nosePos = ctx.rocketHandle.noseAnchor.getWorldPosition(
new THREE.Vector3(),
);
ctx.view.camera.position
.copy(nosePos)
.add(new THREE.Vector3(4.5, 4.5, 6.5));
ctx.view.controls.target.copy(ctx.rocketRoot.position);
}
const qShake = Math.max(0, sample.dynamicPressure / 65000 - 0.12) * 0.48;
const gShake = Math.max(0, sample.gLoad - 2.2) * 0.09;
const shakeAmp =
ctx.paused || isReducedEffects()
? 0
: Math.min(0.65, qShake + gShake + (sample.thrusting ? 0.04 : 0));
if (shakeAmp > 0.01) {
ctx.prevShake.set(
(Math.random() - 0.5) * shakeAmp,
(Math.random() - 0.5) * shakeAmp,
(Math.random() - 0.5) * shakeAmp,
);
ctx.view.camera.position.add(ctx.prevShake);
}
const daySkyLow =
getColorMode() === "light" ? new THREE.Color(0xcbdcf0) : skyLow;
if (altKm < 25) {
tmpColor.lerpColors(daySkyLow, skyMid, Math.min(1, altKm / 25));
} else {
tmpColor.lerpColors(skyMid, skySpace, Math.min(1, (altKm - 25) / 55));
}
ctx.view.scene.background = tmpColor;
if (ctx.rocketHandle && sample.stage > ctx.highestStageShown) {
for (let i = ctx.highestStageShown - 1; i < sample.stage - 1; i++) {
if (ctx.rocketHandle.stagePlumes[i]) {
ctx.rocketHandle.stagePlumes[i].visible = false;
}
const dropped = ctx.rocketHandle.stageGroups[i];
if (dropped && dropped.parent === ctx.rocketHandle.group) {
const dropPos = dropped.getWorldPosition(new THREE.Vector3());
const baseWorld = ctx.rocketHandle.group.getWorldPosition(
new THREE.Vector3(),
);
ctx.rocketHandle.group.remove(dropped);
dropped.position.copy(baseWorld);
dropped.rotation.copy(ctx.rocketRoot.rotation);
ctx.view.scene.add(dropped);
ctx.debrisList.push({
obj: dropped,
vx: -4 - Math.random() * 2,
vy: -9,
vz: (Math.random() - 0.5) * 3,
spinX: (Math.random() - 0.5) * 1.4,
spinZ: 0.75,
ttl: 12,
});
for (let k = 0; k < 10; k++) {
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
dropPos.x + (Math.random() - 0.5) * 2,
dropPos.y + (Math.random() - 0.5) * 2,
dropPos.z + (Math.random() - 0.5) * 2,
(Math.random() - 0.5) * 12,
(Math.random() - 0.5) * 12,
(Math.random() - 0.5) * 12,
0xe2e8f0,
1.1,
2.5,
0.8,
0.45,
);
}
}
}
ctx.highestStageShown = sample.stage;
}
if (ctx.rocketHandle && sample.fairingJettisoned && !ctx.fairingSeparated) {
ctx.fairingSeparated = true;
[
{ half: ctx.rocketHandle.fairingLeft, dir: -1 },
{ half: ctx.rocketHandle.fairingRight, dir: 1 },
].forEach(({ half, dir }) => {
if (half && half.parent === ctx.rocketHandle!.group) {
const halfWorld = ctx.rocketHandle!.group.getWorldPosition(
new THREE.Vector3(),
);
ctx.rocketHandle!.group.remove(half);
half.position.copy(halfWorld);
half.rotation.copy(ctx.rocketRoot.rotation);
ctx.view.scene.add(half);
ctx.debrisList.push({
obj: half,
vx: dir * 6,
vy: -2,
vz: dir * 4,
spinX: dir * 1.8,
spinZ: -dir * 1.4,
ttl: 10,
});
}
});
}
if (ctx.rocketHandle && ctx.simResult!.dropTankJettisons?.length) {
for (const ev of ctx.simResult!.dropTankJettisons) {
if (ctx.jettisonedDropStages.has(ev.stageIndex) || tPos < ev.t) continue;
ctx.jettisonedDropStages.add(ev.stageIndex);
const dropMeshes =
ctx.rocketHandle.stageDropTankGroups[ev.stageIndex] ?? [];
for (const tankObj of dropMeshes) {
if (!tankObj.parent) continue;
const tankWorldPos = tankObj.getWorldPosition(new THREE.Vector3());
tankObj.parent.remove(tankObj);
tankObj.position.copy(tankWorldPos);
tankObj.rotation.copy(ctx.rocketRoot.rotation);
ctx.view.scene.add(tankObj);
const rDir = (tankObj.userData.radialDir as
{ x: number; z: number } | undefined) ?? { x: 1, z: 0 };
const peelVec = new THREE.Vector3(
rDir.x * 5.2,
-3.5,
rDir.z * 5.2,
).applyEuler(ctx.rocketRoot.rotation);
ctx.debrisList.push({
obj: tankObj,
vx: peelVec.x,
vy: peelVec.y - 3.5,
vz: peelVec.z,
spinX: rDir.z * 1.4 + (Math.random() - 0.5) * 0.6,
spinZ: -rDir.x * 1.4,
ttl: 11,
});
for (let k = 0; k < 6; k++) {
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
tankWorldPos.x + (Math.random() - 0.5) * 1.2,
tankWorldPos.y + (Math.random() - 0.5) * 1.2,
tankWorldPos.z + (Math.random() - 0.5) * 1.2,
peelVec.x + (Math.random() - 0.5) * 5,
peelVec.y + (Math.random() - 0.5) * 5,
peelVec.z + (Math.random() - 0.5) * 5,
0xe2e8f0,
0.8,
2.0,
0.65,
0.38,
);
}
}
}
}
if (ctx.rocketHandle) {
const activeIdx = Math.max(
0,
Math.min(ctx.rocketHandle.stagePlumes.length - 1, sample.stage - 1),
);
const preIgnition = ctx.simClock > -0.95 && ctx.simClock < 0;
const burning = (sample.thrusting && ctx.simClock >= 0) || preIgnition;
const vacExpand = 1 + Math.min(2.2, altKm / 38);
const throttleScale = preIgnition ? 0.55 : Math.max(0.4, sample.throttle);
const jitter = 0.88 + Math.random() * 0.25;
ctx.rocketHandle.stagePlumes.forEach((plume, idx) => {
const shouldShow =
burning && (preIgnition ? idx === 0 : idx === activeIdx);
plume.visible = shouldShow;
if (shouldShow) {
const effJitter = isReducedEffects() ? 1.0 : jitter;
const yJit = isReducedEffects() ? 1.0 : 0.92 + Math.random() * 0.18;
plume.scale.set(
throttleScale * effJitter * vacExpand,
throttleScale * yJit * (1 + Math.min(1.05, altKm / 55)),
throttleScale * effJitter * vacExpand,
);
setPlumeAtmosphere(plume, altKm, throttleScale);
}
});
if (!ctx.paused && burning) {
const anchorIdx = preIgnition ? 0 : activeIdx;
const anchor = ctx.rocketHandle.stageNozzleAnchors[anchorIdx];
if (anchor) {
anchor.getWorldPosition(nozzleWorldPos);
exhaustDir
.set(0, -1, 0)
.applyEuler(ctx.rocketRoot.rotation)
.normalize();
const red = isReducedEffects();
const spawns = (altM < 250 ? 5 : altKm < 38 ? 3 : 2) * (red ? 0.5 : 1);
const spawnCount = Math.max(1, Math.round(spawns));
for (let s = 0; s < spawnCount; s++) {
if (altM < 250) {
const ang = Math.random() * Math.PI * 2;
const spd = 11 + Math.random() * 19;
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
nozzleWorldPos.x + (Math.random() - 0.5) * 3.2,
Math.max(0.8, nozzleWorldPos.y - 1.2),
nozzleWorldPos.z + (Math.random() - 0.5) * 3.2,
Math.cos(ang) * spd,
1.5 + Math.random() * 4.5,
Math.sin(ang) * spd,
0xf1f5f9,
2.6 + Math.random() * 1.1,
4.2,
2.1,
0.48,
{
endColorHex: 0xcbd5e1,
drag: 1.55,
buoyancy: 3.4,
groundClampY: 1.4,
},
);
if (!red && s % 2 === 0) {
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
nozzleWorldPos.x + (Math.random() - 0.5) * 2.0,
Math.max(0.6, nozzleWorldPos.y - 0.8),
nozzleWorldPos.z + (Math.random() - 0.5) * 2.0,
Math.cos(ang) * (spd * 1.3),
1.2 + Math.random() * 3.0,
Math.sin(ang) * (spd * 1.3),
0xffb74d,
0.75,
0.8,
0.55,
0.78,
{
additive: true,
endColorHex: 0xff5722,
drag: 2.1,
groundClampY: 0.7,
},
);
}
} else if (altKm < 38) {
const pSpeed = 30 + Math.random() * 18;
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
nozzleWorldPos.x +
exhaustDir.x * 2.8 +
(Math.random() - 0.5) * 1.1,
nozzleWorldPos.y +
exhaustDir.y * 2.8 +
(Math.random() - 0.5) * 1.1,
nozzleWorldPos.z + (Math.random() - 0.5) * 1.1,
exhaustDir.x * pSpeed + (Math.random() - 0.5) * 6.5,
exhaustDir.y * pSpeed + (Math.random() - 0.5) * 6.5,
(Math.random() - 0.5) * 6.5,
altKm < 12 ? 0xd6c7b2 : 0xe2e8f0,
1.6 + Math.random() * 0.6,
3.2,
1.75,
0.36,
{ endColorHex: 0xf8fafc, drag: 2.2, buoyancy: 2.0 },
);
if (!red && altKm < 24 && s === 0) {
const sparkSpd = 52 + Math.random() * 26;
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
nozzleWorldPos.x + exhaustDir.x * 1.6,
nozzleWorldPos.y + exhaustDir.y * 1.6,
nozzleWorldPos.z,
exhaustDir.x * sparkSpd + (Math.random() - 0.5) * 7,
exhaustDir.y * sparkSpd + (Math.random() - 0.5) * 7,
(Math.random() - 0.5) * 7,
0xffcc80,
0.55,
0.4,
0.32,
0.85,
{ additive: true, endColorHex: 0xf97316, drag: 1.1 },
);
}
} else {
const pSpeed = 45 + Math.random() * 22;
spawnExhaustParticle(
{ smokePool: ctx.smokePool, sparkPool: ctx.sparkPool },
nozzleWorldPos.x + exhaustDir.x * 3.8,
nozzleWorldPos.y + exhaustDir.y * 3.8,
nozzleWorldPos.z,
exhaustDir.x * pSpeed + (Math.random() - 0.5) * 16,
exhaustDir.y * pSpeed + (Math.random() - 0.5) * 16,
(Math.random() - 0.5) * 16,
0x93c5fd,
2.8,
6.0,
0.75,
0.16,
{ endColorHex: 0xcbd5e1, drag: 0.6 },
);
}
}
}
}
}
if (ctx.machCone && ctx.machConeMat) {
const mach = sample.mach ?? 0;
const showMach = mach >= 0.88 && mach <= 1.32 && altKm < 32;
ctx.machCone.visible = showMach;
if (showMach) {
const strength = Math.max(0, 1 - Math.abs(mach - 1.03) / 0.24);
ctx.machConeMat.uniforms.uOpacity.value =
strength * (isReducedEffects() ? 0.36 : 0.42 + Math.random() * 0.14);
const s = 0.9 + strength * 0.35;
ctx.machCone.scale.set(s, s, s);
}
}
if (ctx.plasmaGlow && ctx.plasmaGlowMat) {
const showPlasma = sample.heatFluxWcm2 > 5;
ctx.plasmaGlow.visible = showPlasma;
if (showPlasma) {
const jit = isReducedEffects() ? 1.0 : 0.88 + Math.random() * 0.2;
ctx.plasmaGlowMat.uniforms.uOpacity.value = Math.min(
0.68,
((sample.heatFluxWcm2 - 5) / 36) * jit,
);
}
}
}
export function stepParticlesAndDebris(ctx: LaunchContext, dt: number): void {
if (!ctx.paused) {
const pStep = dt * Math.min(4, ctx.speed);
const viewH = ctx.view.renderer.domElement.clientHeight || 800;
advanceGpuPool(ctx.smokePool, pStep, viewH);
advanceGpuPool(ctx.sparkPool, pStep, viewH);
}
for (let i = ctx.debrisList.length - 1; i >= 0; i--) {
const d = ctx.debrisList[i];
d.vy -= 9.8 * dt * ctx.speed;
d.obj.position.x += d.vx * dt * ctx.speed;
d.obj.position.y += d.vy * dt * ctx.speed;
d.obj.position.z += d.vz * dt * ctx.speed;
d.obj.rotation.x += d.spinX * dt;
d.obj.rotation.z += d.spinZ * dt;
d.ttl -= dt;
if (d.ttl <= 0) {
ctx.view.scene.remove(d.obj);
ctx.debrisList.splice(i, 1);
}
}
}

View file

@ -0,0 +1,81 @@
// Mutable launch sequence scene, playback, and telemetry HUD state
import * as THREE from "three";
import type { RocketMeshHandle } from "../../three/rocketMesh.js";
import type { ManagedView } from "../../three/sceneManager.js";
import type { buildRocket } from "../../../shared/physics.js";
import type {
ActiveMission,
MissionSettlement,
RocketDesign,
SimResult,
TrajectoryResult,
} from "../../../shared/types.js";
import type { FallingDebris, GpuParticlePool } from "./particles.js";
export type AscentCamMode = "track" | "chase" | "nose";
export interface HudVals {
met: HTMLElement;
alt: HTMLElement;
vel: HTMLElement;
att: HTMLElement;
drag: HTMLElement;
dyn: HTMLElement;
load: HTMLElement;
cpu: HTMLElement;
rad: HTMLElement;
fair: HTMLElement;
gnd: HTMLElement;
sig: HTMLElement;
eff: HTMLElement;
}
export interface LaunchContext {
view: ManagedView;
bannerEl: HTMLElement;
titleLeft: HTMLElement;
controlsTop: HTMLElement;
hudEl: HTMLElement;
eventsEl: HTMLElement;
liveStripCanvas: HTMLCanvasElement;
liveHistory: Array<{ cpu: number; g: number; q: number; rad: number }>;
disposed: boolean;
speed: number;
paused: boolean;
simClock: number;
phase: "ascent" | "orbit" | "done";
activeMission: ActiveMission | null;
settlement: MissionSettlement | undefined;
simResult: SimResult | null;
trajectory: TrajectoryResult | null;
designUsed: RocketDesign | null;
builtAssembly: ReturnType<typeof buildRocket> | null;
isSpectating: boolean;
isTest: boolean;
rocketRoot: THREE.Group;
ascentEnvGroup: THREE.Group | null;
padGroup: THREE.Group | null;
rocketHandle: RocketMeshHandle | null;
machCone: THREE.Mesh | null;
machConeMat: THREE.ShaderMaterial | null;
plasmaGlow: THREE.Mesh | null;
plasmaGlowMat: THREE.ShaderMaterial | null;
rocketHeightVis: number;
cgPivotY: number;
camMode: AscentCamMode;
smokePool: GpuParticlePool | null;
sparkPool: GpuParticlePool | null;
prevShake: THREE.Vector3;
highestStageShown: number;
fairingSeparated: boolean;
jettisonedDropStages: Set<number>;
debrisList: FallingDebris[];
emittedEventIdx: Set<number>;
hudVals: HudVals | null;
orbitGroup: THREE.Group | null;
craftMarker: THREE.Object3D | null;
orbitProgress: number;
lastHudRefresh: number;
onEnterOrbit: () => void;
onRebuildControls: () => void;
}

View file

@ -0,0 +1,227 @@
// Ascent sky, curved Earth horizon, clouds, and supersonic aero shock shaders
// The earth is just a blue ball, source? Trust me bro
import * as THREE from "three";
import { getSettings } from "../../api.js";
import { isReducedEffects } from "../../theme.js";
import type { RocketMeshHandle } from "../../three/rocketMesh.js";
import { getSoftParticleTexture } from "../../three/sceneManager.js";
import { createGpuParticlePool, type GpuParticlePool } from "./particles.js";
export function createAscentEnvironment(): {
env: THREE.Group;
smokePool: GpuParticlePool;
sparkPool: GpuParticlePool;
} {
const env = new THREE.Group();
const earthRadius = 18000;
const earth = new THREE.Mesh(
new THREE.SphereGeometry(earthRadius, 72, 54),
new THREE.MeshStandardMaterial({
color: 0x0e2540,
roughness: 0.88,
metalness: 0.06,
}),
);
earth.position.set(0, -earthRadius - 0.25, 0);
earth.receiveShadow = true;
env.add(earth);
const atmoLimb = new THREE.Mesh(
new THREE.SphereGeometry(earthRadius + 210, 72, 54),
new THREE.ShaderMaterial({
vertexShader: `
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vNormalW = normalize((modelMatrix * vec4(normal, 0.0)).xyz);
vViewDir = normalize(cameraPosition - wp.xyz);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
float d = clamp(-dot(normalize(vNormalW), normalize(vViewDir)), 0.0, 1.0);
float limb = clamp(d * 3.4, 0.0, 1.0) * (1.0 - smoothstep(0.14, 0.62, d));
float scatter = pow(max(0.0001, limb), 1.45);
vec3 col = mix(vec3(0.10, 0.42, 0.92), vec3(0.42, 0.84, 1.0), scatter);
gl_FragColor = vec4(col, clamp(scatter * 0.42, 0.0, 0.55));
}
`,
transparent: true,
side: THREE.BackSide,
blending: THREE.AdditiveBlending,
depthWrite: false,
}),
);
atmoLimb.position.copy(earth.position);
env.add(atmoLimb);
const cloudTex = getSoftParticleTexture();
const cloudMatLow = new THREE.MeshBasicMaterial({
color: 0xe2e8f0,
map: cloudTex,
transparent: true,
opacity: 0.22,
side: THREE.DoubleSide,
depthWrite: false,
});
const cloudMatHigh = new THREE.MeshBasicMaterial({
color: 0xcbd5e1,
map: cloudTex,
transparent: true,
opacity: 0.14,
side: THREE.DoubleSide,
depthWrite: false,
});
const layers = [
{ visY: 175, mat: cloudMatLow, count: 28, rMin: 48, rMax: 120 },
{ visY: 345, mat: cloudMatHigh, count: 22, rMin: 70, rMax: 165 },
];
for (const lay of layers) {
for (let i = 0; i < lay.count; i++) {
const span =
(lay.rMin + ((i * 37) % Math.max(1, lay.rMax - lay.rMin))) * 2.2;
const puff = new THREE.Mesh(
new THREE.PlaneGeometry(span, span * 0.82),
lay.mat,
);
puff.rotation.x = -Math.PI / 2;
puff.rotation.z = (i * 1.17) % Math.PI;
const angle = (i / lay.count) * Math.PI * 2;
const range = 130 + (i % 5) * 410;
puff.position.set(
Math.cos(angle) * range + 120,
lay.visY + ((i % 3) - 1) * 14,
Math.sin(angle) * range,
);
env.add(puff);
}
}
const markerMat = new THREE.MeshBasicMaterial({
color: 0x60a5fa,
transparent: true,
opacity: 0.24,
side: THREE.DoubleSide,
depthWrite: false,
});
for (const drX of [180, 450, 900, 1500, 2300]) {
const m = new THREE.Mesh(new THREE.RingGeometry(8, 12, 24), markerMat);
m.rotation.x = -Math.PI / 2;
m.position.set(drX, 0.2, 0);
env.add(m);
}
const q = getSettings().quality;
const red = isReducedEffects();
const smokeCount = Math.round(
(q === "low" ? 300 : q === "medium" ? 700 : 1200) * (red ? 0.5 : 1),
);
const sparkCount = Math.round(
(q === "low" ? 120 : q === "medium" ? 240 : 400) * (red ? 0.5 : 1),
);
const smokePool = createGpuParticlePool(smokeCount, false, env);
const sparkPool = createGpuParticlePool(sparkCount, true, env);
return { env, smokePool, sparkPool };
}
export function createRocketAeroEffects(
rocketHandle: RocketMeshHandle,
maxDiameter: number,
): {
machCone: THREE.Mesh;
machConeMat: THREE.ShaderMaterial;
plasmaGlow: THREE.Mesh;
plasmaGlowMat: THREE.ShaderMaterial;
} {
const machConeMat = new THREE.ShaderMaterial({
uniforms: {
uOpacity: { value: 0 },
uColor: { value: new THREE.Color(0xe0f2fe) },
},
vertexShader: `
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
vUv = uv;
vec4 wp = modelMatrix * vec4(position, 1.0);
vNormalW = normalize((modelMatrix * vec4(normal, 0.0)).xyz);
vViewDir = normalize(cameraPosition - wp.xyz);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
uniform float uOpacity;
uniform vec3 uColor;
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
float ndv = abs(dot(normalize(vNormalW), normalize(vViewDir)));
float rim = pow(max(0.0001, ndv), 1.35);
float axial = smoothstep(0.0, 0.35, vUv.y) * smoothstep(1.0, 0.72, vUv.y);
float a = uOpacity * rim * axial;
if (a < 0.005) discard;
gl_FragColor = vec4(uColor, a);
}
`,
transparent: true,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
depthWrite: false,
});
const machCone = new THREE.Mesh(
new THREE.ConeGeometry(maxDiameter * 1.9, maxDiameter * 3.0, 32, 1, true),
machConeMat,
);
machCone.position.y = -maxDiameter * 1.15;
machCone.visible = false;
rocketHandle.noseAnchor.add(machCone);
const plasmaGlowMat = new THREE.ShaderMaterial({
uniforms: {
uOpacity: { value: 0 },
uHotColor: { value: new THREE.Color(0xfff1e6).multiplyScalar(1.3) },
uOuterColor: { value: new THREE.Color(0xff5522) },
},
vertexShader: `
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
vUv = uv;
vec4 wp = modelMatrix * vec4(position, 1.0);
vNormalW = normalize((modelMatrix * vec4(normal, 0.0)).xyz);
vViewDir = normalize(cameraPosition - wp.xyz);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
uniform float uOpacity;
uniform vec3 uHotColor;
uniform vec3 uOuterColor;
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
float ndv = abs(dot(normalize(vNormalW), normalize(vViewDir)));
float soft = pow(max(0.0001, ndv), 1.5);
float noseCap = smoothstep(0.28, 0.92, vUv.y);
vec3 col = mix(uOuterColor, uHotColor, pow(max(0.0001, vUv.y), 2.0));
float a = uOpacity * soft * noseCap;
if (a < 0.005) discard;
gl_FragColor = vec4(col, a);
}
`,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
});
const plasmaGlow = new THREE.Mesh(
new THREE.SphereGeometry(maxDiameter * 0.85, 24, 18),
plasmaGlowMat,
);
plasmaGlow.scale.set(1.12, 0.78, 1.12);
plasmaGlow.visible = false;
rocketHandle.noseAnchor.add(plasmaGlow);
return { machCone, machConeMat, plasmaGlow, plasmaGlowMat };
}

View file

@ -0,0 +1,241 @@
// Cool lookin stuff
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import { getColorMode } from "../../theme.js";
import { getUnlockedDiagnosticTier } from "../../../shared/physics.js";
import type { TelemetrySample } from "../../../shared/types.js";
import { clear, fmtNum, h, term } from "../../ui.js";
import type { AscentCamMode, LaunchContext } from "./context.js";
export function pushEventLog(
ctx: LaunchContext,
label: string,
kind: "info" | "warn" | "err" = "info",
): void {
const cls = kind === "err" ? "red" : kind === "warn" ? "amber" : "accent";
ctx.eventsEl.appendChild(
h(
"div",
{ style: { marginBottom: "4px", lineHeight: "1.35" } },
h(
"span",
{ class: cls },
`[T+${Math.max(0, ctx.simClock).toFixed(1)}s] `,
),
h("span", {}, label),
),
);
ctx.eventsEl.scrollTop = ctx.eventsEl.scrollHeight;
}
export function buildControlsBar(ctx: LaunchContext): void {
clear(ctx.controlsTop);
const speedBtns = [
{ label: "||", val: 0 },
{ label: "1×", val: 1 },
{ label: "4×", val: 4 },
{ label: "16×", val: 16 },
];
for (const s of speedBtns) {
ctx.controlsTop.appendChild(
h(
"button",
{
class: `btn xs ${(s.val === 0 && ctx.paused) || (!ctx.paused && ctx.speed === s.val) ? "selected" : "ghost"}`,
onClick: () => {
if (s.val === 0) ctx.paused = !ctx.paused;
else {
ctx.paused = false;
ctx.speed = s.val;
}
buildControlsBar(ctx);
},
},
s.label,
),
);
}
if (ctx.phase === "ascent") {
const camModes: Array<{ id: AscentCamMode; label: string }> = [
{ id: "track", label: "Cam: Track" },
{ id: "chase", label: "Cam: Tight" },
{ id: "nose", label: "Cam: Nose" },
];
for (const cm of camModes) {
ctx.controlsTop.appendChild(
h(
"button",
{
class: `btn xs ${ctx.camMode === cm.id ? "selected" : "ghost"}`,
onClick: () => {
ctx.camMode = cm.id;
if (cm.id === "track") {
ctx.view.camera.position.set(
ctx.rocketRoot.position.x +
Math.max(40, ctx.rocketHeightVis * 1.1),
ctx.rocketRoot.position.y +
Math.max(20, ctx.rocketHeightVis * 0.5),
ctx.rocketRoot.position.z +
Math.max(55, ctx.rocketHeightVis * 1.45),
);
}
buildControlsBar(ctx);
},
},
cm.label,
),
);
}
}
if (ctx.phase === "ascent" && ctx.simResult?.success && ctx.trajectory) {
ctx.controlsTop.appendChild(
h(
"button",
{
class: "btn xs",
onClick: () => ctx.onEnterOrbit(),
},
"Skip to Orbit",
),
);
}
ctx.controlsTop.appendChild(
h(
"button",
{
class: "btn xs primary",
onClick: () =>
navigate("debrief", {
mission: ctx.activeMission ?? undefined,
settlement: ctx.settlement,
testResult: ctx.simResult ?? undefined,
isSpectating: ctx.isSpectating,
}),
},
ctx.phase === "ascent" ? "Proceed to Debrief →" : "Mission Debrief →",
),
);
}
export function updateTelemetryHud(
ctx: LaunchContext,
sample: TelemetrySample,
now: number,
): void {
if (now - ctx.lastHudRefresh <= 90) return;
ctx.lastHudRefresh = now;
const sigPct = sample.signalHealthPct ?? 100;
const sigCls = sigPct >= 75 ? "green" : sigPct >= 55 ? "amber" : "red";
const pwrW = Math.round(
sample.powerBalanceWatts ??
ctx.builtAssembly?.spacecraftBus?.powerMarginWatts ??
0,
);
const effGrade =
ctx.simResult!.efficiencyGrade ??
ctx.builtAssembly?.spacecraftBus?.efficiencyGrade ??
"—";
const effScore =
ctx.simResult!.efficiencyScore ??
ctx.builtAssembly?.spacecraftBus?.efficiencyScore;
const cpuLoad = sample.cpuLoadPct ?? 0;
const compStatus = sample.computerStatus ?? "nominal";
const cpuCls =
compStatus === "failed" || compStatus === "overloaded" || cpuLoad > 125
? "red"
: compStatus === "degraded" || cpuLoad > 95
? "amber"
: "green";
const diagTier = getUnlockedDiagnosticTier(
state.agency?.unlockedTechs,
state.agency?.difficulty,
);
const radFlux = sample.radFluxMsvHr ?? 0.06;
ctx.liveHistory.push({
cpu: cpuLoad,
g: sample.gLoad,
q: sample.dynamicPressure / 1000,
rad: radFlux,
});
if (ctx.liveHistory.length > 90) ctx.liveHistory.shift();
if (!ctx.hudVals) {
clear(ctx.hudEl);
const mkRow = (labelNode: HTMLElement | string, cls = "v") => {
const valSpan = h("span", { class: cls });
const row = h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, labelNode),
valSpan,
);
ctx.hudEl.appendChild(row);
return valSpan;
};
ctx.hudVals = {
met: mkRow("MET", "v accent"),
alt: mkRow(term("Altitude", "apoapsis")),
vel: mkRow(term("Velocity / Mach", "mach")),
att: mkRow(term("Pitch / γ / AoA", "flight_path_angle")),
drag: mkRow(term("Aero Drag / Cd", "fineness")),
dyn: mkRow(term("Dynamic Press", "max_q")),
load: mkRow(term("Load / Heat", "g_load")),
cpu: mkRow(term("Flight CPU", "cpu_load")),
rad: mkRow(term("Rad Flux / SEUs", "seu")),
fair: mkRow(term("Fairing", "fairing")),
gnd: mkRow(term("Ground Station", "telemetry_freq"), "v accent"),
sig: mkRow(term("Signal / Bus", "comms_link")),
eff: mkRow(term("Efficiency", "spacecraft_bus")),
};
if (diagTier >= 2) ctx.hudEl.appendChild(ctx.liveStripCanvas);
}
ctx.hudVals.met.textContent =
ctx.simClock < 0
? `T${ctx.simClock.toFixed(1)}s`
: `T+${ctx.simClock.toFixed(1)}s`;
ctx.hudVals.alt.textContent = `${(sample.altitude / 1000).toFixed(2)} km`;
ctx.hudVals.vel.textContent = `${fmtNum(sample.velocity)} m/s • M ${(sample.mach ?? 0).toFixed(2)}`;
ctx.hudVals.att.textContent = `${sample.pitchDeg.toFixed(1)}° / ${(sample.flightPathDeg ?? sample.pitchDeg).toFixed(1)}° / ${(sample.aoaDeg ?? 0).toFixed(1)}°`;
ctx.hudVals.drag.textContent = `${((sample.dragForceN ?? 0) / 1000).toFixed(1)} kN (Cd ${(sample.cd ?? 0.34).toFixed(2)})`;
ctx.hudVals.dyn.textContent = `${(sample.dynamicPressure / 1000).toFixed(1)} kPa`;
ctx.hudVals.load.textContent = `${sample.gLoad.toFixed(2)} G • ${sample.heatFluxWcm2.toFixed(0)} W/cm²`;
ctx.hudVals.cpu.className = `v ${cpuCls}`;
ctx.hudVals.cpu.textContent = `${Math.round(cpuLoad)}% • ${compStatus.toUpperCase()}`;
ctx.hudVals.rad.className = `v ${(sample.seuCount ?? 0) > 0 ? "amber" : ""}`;
ctx.hudVals.rad.textContent = `${radFlux.toFixed(2)} mSv/h • ${sample.seuCount ?? 0} SEU (T${diagTier})`;
ctx.hudVals.fair.textContent = sample.fairingJettisoned
? "SEPARATED"
: "ATTACHED";
ctx.hudVals.gnd.textContent = sample.groundStation ?? "PAD-39A S-BAND";
ctx.hudVals.sig.className = `v ${sigCls}`;
ctx.hudVals.sig.textContent = `${sigPct.toFixed(0)}% • ${pwrW >= 0 ? "+" : ""}${pwrW} W`;
ctx.hudVals.eff.textContent =
effScore != null ? `Grade ${effGrade} (${effScore})` : `Grade ${effGrade}`;
if (diagTier >= 2) {
const c2d = ctx.liveStripCanvas.getContext("2d");
if (c2d) {
const W = ctx.liveStripCanvas.width;
const H = ctx.liveStripCanvas.height;
c2d.fillStyle = getColorMode() === "light" ? "#f1f5f9" : "#090d14";
c2d.fillRect(0, 0, W, H);
const drawLine = (
col: string,
fn: (pt: (typeof ctx.liveHistory)[number]) => number,
) => {
c2d.strokeStyle = col;
c2d.lineWidth = 1.6;
c2d.beginPath();
ctx.liveHistory.forEach((pt, idx) => {
const x = (idx / Math.max(1, ctx.liveHistory.length - 1)) * W;
const y = H - Math.min(1, Math.max(0, fn(pt))) * (H - 8) - 4;
if (idx === 0) c2d.moveTo(x, y);
else c2d.lineTo(x, y);
});
c2d.stroke();
};
drawLine("#f59e0b", (pt) => pt.cpu / 150);
drawLine("#38bdf8", (pt) => pt.q / 65);
drawLine("#34d399", (pt) => pt.g / 8);
drawLine("#f472b6", (pt) => pt.rad / 5);
}
}
}

View file

@ -0,0 +1,169 @@
// Spin
import * as THREE from "three";
import { applyThemeFromState, currentContract } from "../../state.js";
import { BODY_RADIUS_KM } from "../../../shared/ephemeris.js";
import type { SimResult, TelemetrySample } from "../../../shared/types.js";
import type { LaunchContext } from "./context.js";
import { pushEventLog } from "./hud.js";
import { resetGpuPool } from "./particles.js";
export function sampleTelemetryAt(
simResult: SimResult | null,
t: number,
): TelemetrySample | null {
const arr = simResult?.telemetry ?? [];
if (!arr.length) return null;
if (t <= arr[0].t) return arr[0];
if (t >= arr[arr.length - 1].t) return arr[arr.length - 1];
for (let i = 0; i < arr.length - 1; i++) {
if (t >= arr[i].t && t <= arr[i + 1].t) {
const a = arr[i];
const b = arr[i + 1];
const f = (t - a.t) / Math.max(1e-4, b.t - a.t);
return {
t,
altitude: a.altitude + (b.altitude - a.altitude) * f,
downrange: a.downrange + (b.downrange - a.downrange) * f,
velocity: a.velocity + (b.velocity - a.velocity) * f,
vx: a.vx + (b.vx - a.vx) * f,
vy: a.vy + (b.vy - a.vy) * f,
mass: a.mass + (b.mass - a.mass) * f,
dynamicPressure:
a.dynamicPressure + (b.dynamicPressure - a.dynamicPressure) * f,
gLoad: a.gLoad + (b.gLoad - a.gLoad) * f,
heatFluxWcm2: a.heatFluxWcm2 + (b.heatFluxWcm2 - a.heatFluxWcm2) * f,
throttle: a.throttle + (b.throttle - a.throttle) * f,
stage: a.stage,
thrusting: a.thrusting,
fairingJettisoned: b.fairingJettisoned || a.fairingJettisoned,
pitchDeg: a.pitchDeg + (b.pitchDeg - a.pitchDeg) * f,
mach: (a.mach ?? 0) + ((b.mach ?? 0) - (a.mach ?? 0)) * f,
cd: (a.cd ?? 0.34) + ((b.cd ?? 0.34) - (a.cd ?? 0.34)) * f,
dragForceN:
(a.dragForceN ?? 0) + ((b.dragForceN ?? 0) - (a.dragForceN ?? 0)) * f,
flightPathDeg:
(a.flightPathDeg ?? a.pitchDeg) +
((b.flightPathDeg ?? b.pitchDeg) - (a.flightPathDeg ?? a.pitchDeg)) *
f,
aoaDeg: (a.aoaDeg ?? 0) + ((b.aoaDeg ?? 0) - (a.aoaDeg ?? 0)) * f,
signalHealthPct:
a.signalHealthPct != null && b.signalHealthPct != null
? a.signalHealthPct + (b.signalHealthPct - a.signalHealthPct) * f
: a.signalHealthPct,
powerBalanceWatts:
a.powerBalanceWatts != null && b.powerBalanceWatts != null
? a.powerBalanceWatts +
(b.powerBalanceWatts - a.powerBalanceWatts) * f
: a.powerBalanceWatts,
groundStation: f < 0.5 ? a.groundStation : b.groundStation,
cpuLoadPct:
(a.cpuLoadPct ?? 0) + ((b.cpuLoadPct ?? 0) - (a.cpuLoadPct ?? 0)) * f,
seuCount: b.seuCount ?? a.seuCount,
radFluxMsvHr:
(a.radFluxMsvHr ?? 0.06) +
((b.radFluxMsvHr ?? 0.06) - (a.radFluxMsvHr ?? 0.06)) * f,
computerStatus: f < 0.5 ? a.computerStatus : b.computerStatus,
};
}
}
return arr[arr.length - 1];
}
export function enterOrbitPhase(ctx: LaunchContext): void {
if (ctx.phase === "orbit") return;
ctx.phase = "orbit";
applyThemeFromState("orbit");
ctx.bannerEl.textContent = "ORBITAL INSERTION CONFIRMED // PROPAGATING";
ctx.onRebuildControls();
ctx.view.scene.remove(ctx.rocketRoot);
if (ctx.ascentEnvGroup) ctx.view.scene.remove(ctx.ascentEnvGroup);
if (ctx.padGroup) ctx.view.scene.remove(ctx.padGroup);
resetGpuPool(ctx.smokePool);
resetGpuPool(ctx.sparkPool);
ctx.debrisList.forEach((d) => ctx.view.scene.remove(d.obj));
ctx.debrisList.length = 0;
ctx.jettisonedDropStages.clear();
ctx.hudVals = null;
ctx.view.scene.background = new THREE.Color(0x0b0e14);
ctx.orbitGroup = new THREE.Group();
const target =
ctx.trajectory?.target ??
ctx.activeMission?.target ??
currentContract()?.target ??
"leo";
const bodyId =
target === "lunar" || target === "moon-landing"
? "moon"
: target === "mars"
? "mars"
: target === "jupiter"
? "jupiter"
: target === "solar"
? "sun"
: "earth";
const rKm = BODY_RADIUS_KM[bodyId] ?? 6371;
const pts = ctx.trajectory?.points ?? [];
const maxKm = Math.max(
rKm * 1.6,
...pts.map((p) => Math.hypot(p.x, p.y, p.z)),
);
const visScale = 120 / maxKm;
const bodyVisR = Math.max(8, Math.min(48, rKm * visScale));
const bodyColors: Record<string, number> = {
earth: 0x3b82f6,
moon: 0xcbd5e1,
mars: 0xd96b43,
jupiter: 0xd8b48a,
sun: 0xffd166,
};
const planet = new THREE.Mesh(
new THREE.SphereGeometry(bodyVisR, 36, 36),
bodyId === "sun"
? new THREE.MeshBasicMaterial({ color: bodyColors[bodyId] })
: new THREE.MeshStandardMaterial({
color: bodyColors[bodyId] ?? 0x4f9cf9,
roughness: 0.72,
metalness: 0.08,
}),
);
ctx.orbitGroup.add(planet);
if (pts.length > 1) {
const curvePts = pts.map(
(p) => new THREE.Vector3(p.x * visScale, p.y * visScale, p.z * visScale),
);
const lineGeo = new THREE.BufferGeometry().setFromPoints(curvePts);
const line = new THREE.Line(
lineGeo,
new THREE.LineBasicMaterial({
color: 0x60a5fa,
transparent: true,
opacity: 0.85,
}),
);
ctx.orbitGroup.add(line);
(ctx.orbitGroup as any).userData.curvePts = curvePts;
}
ctx.craftMarker = new THREE.Mesh(
new THREE.SphereGeometry(2.4, 16, 16),
new THREE.MeshBasicMaterial({ color: 0x34d399 }),
);
ctx.orbitGroup.add(ctx.craftMarker);
ctx.view.scene.add(ctx.orbitGroup);
ctx.view.camera.position.set(110, 80, 145);
ctx.view.controls.target.set(0, 0, 0);
pushEventLog(
ctx,
"Entered orbital coast & Astrodynamics propagator ctx.view.",
"info",
);
}
export function updateOrbitMarker(ctx: LaunchContext): void {
if (!ctx.orbitGroup || !ctx.craftMarker) return;
const pts: THREE.Vector3[] | undefined = (ctx.orbitGroup as any).userData
.curvePts;
if (pts?.length) {
const idx = Math.floor(ctx.orbitProgress * (pts.length - 1));
ctx.craftMarker.position.copy(pts[idx]);
}
}

View file

@ -0,0 +1,336 @@
// GPU-accelerated particle pool shaders and exhaust particle simulation
// Me acting like I know what I'm doing when I know shit about shaders
import * as THREE from "three";
import { getSoftParticleTexture } from "../../three/sceneManager.js";
export interface FallingDebris {
obj: THREE.Object3D;
vx: number;
vy: number;
vz: number;
spinX: number;
spinZ: number;
ttl: number;
}
export interface ParticleSlot {
active: boolean;
x: number;
y: number;
z: number;
vx: number;
vy: number;
vz: number;
age: number;
maxAge: number;
baseScale: number;
growRate: number;
baseOpacity: number;
rot: number;
rotSpeed: number;
r0: number;
g0: number;
b0: number;
r1: number;
g1: number;
b1: number;
drag: number;
buoyancy: number;
groundClampY: number | null;
}
export interface GpuParticlePool {
points: THREE.Points;
mat: THREE.ShaderMaterial;
slots: ParticleSlot[];
positions: Float32Array;
sizes: Float32Array;
alphas: Float32Array;
colors: Float32Array;
rots: Float32Array;
attrPos: THREE.BufferAttribute;
attrSize: THREE.BufferAttribute;
attrAlpha: THREE.BufferAttribute;
attrColor: THREE.BufferAttribute;
attrRot: THREE.BufferAttribute;
cursor: number;
}
const tmpStartCol = new THREE.Color();
const tmpEndCol = new THREE.Color();
const PARTICLE_VERT = `
attribute float aSize;
attribute float aAlpha;
attribute vec3 aColor;
attribute float aRot;
uniform float uScale;
varying float vAlpha;
varying vec3 vColor;
varying float vRot;
void main() {
vAlpha = aAlpha;
vColor = aColor;
vRot = aRot;
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
gl_PointSize = max(1.0, aSize * (uScale / max(1.0, -mvPosition.z)));
gl_Position = projectionMatrix * mvPosition;
}
`;
const PARTICLE_FRAG = `
uniform sampler2D uTexture;
varying float vAlpha;
varying vec3 vColor;
varying float vRot;
void main() {
if (vAlpha <= 0.004) discard;
vec2 uv = gl_PointCoord - vec2(0.5);
float c = cos(vRot);
float s = sin(vRot);
vec2 ruv = vec2(uv.x * c - uv.y * s, uv.x * s + uv.y * c) + vec2(0.5);
vec4 tex = texture2D(uTexture, ruv);
float alpha = tex.a * vAlpha;
if (alpha <= 0.004) discard;
gl_FragColor = vec4(vColor * tex.rgb, alpha);
}
`;
export function createGpuParticlePool(
count: number,
additive: boolean,
env: THREE.Group,
): GpuParticlePool {
const positions = new Float32Array(count * 3);
const sizes = new Float32Array(count);
const alphas = new Float32Array(count);
const colors = new Float32Array(count * 3);
const rots = new Float32Array(count);
const geo = new THREE.BufferGeometry();
const attrPos = new THREE.BufferAttribute(positions, 3).setUsage(
THREE.DynamicDrawUsage,
);
const attrSize = new THREE.BufferAttribute(sizes, 1).setUsage(
THREE.DynamicDrawUsage,
);
const attrAlpha = new THREE.BufferAttribute(alphas, 1).setUsage(
THREE.DynamicDrawUsage,
);
const attrColor = new THREE.BufferAttribute(colors, 3).setUsage(
THREE.DynamicDrawUsage,
);
const attrRot = new THREE.BufferAttribute(rots, 1).setUsage(
THREE.DynamicDrawUsage,
);
geo.setAttribute("position", attrPos);
geo.setAttribute("aSize", attrSize);
geo.setAttribute("aAlpha", attrAlpha);
geo.setAttribute("aColor", attrColor);
geo.setAttribute("aRot", attrRot);
const mat = new THREE.ShaderMaterial({
uniforms: {
uTexture: { value: getSoftParticleTexture() },
uScale: { value: 420 },
},
vertexShader: PARTICLE_VERT,
fragmentShader: PARTICLE_FRAG,
transparent: true,
depthWrite: false,
blending: additive ? THREE.AdditiveBlending : THREE.NormalBlending,
});
const points = new THREE.Points(geo, mat);
points.frustumCulled = false;
points.renderOrder = additive ? 3 : 2;
env.add(points);
const slots: ParticleSlot[] = [];
for (let i = 0; i < count; i++) {
slots.push({
active: false,
x: 0,
y: 0,
z: 0,
vx: 0,
vy: 0,
vz: 0,
age: 0,
maxAge: 1,
baseScale: 1,
growRate: 1,
baseOpacity: 0.5,
rot: 0,
rotSpeed: 0,
r0: 1,
g0: 1,
b0: 1,
r1: 1,
g1: 1,
b1: 1,
drag: 1.0,
buoyancy: 0,
groundClampY: null,
});
}
return {
points,
mat,
slots,
positions,
sizes,
alphas,
colors,
rots,
attrPos,
attrSize,
attrAlpha,
attrColor,
attrRot,
cursor: 0,
};
}
export function spawnExhaustParticle(
pools: {
smokePool: GpuParticlePool | null;
sparkPool: GpuParticlePool | null;
},
x: number,
y: number,
z: number,
vx: number,
vy: number,
vz: number,
colorHex: number,
baseScale: number,
growRate: number,
maxAge: number,
baseOpacity: number,
opts?: {
additive?: boolean;
endColorHex?: number;
drag?: number;
buoyancy?: number;
groundClampY?: number | null;
rotSpeed?: number;
},
): void {
const pool = opts?.additive ? pools.sparkPool : pools.smokePool;
if (!pool || !pool.slots.length) return;
const len = pool.slots.length;
let chosenIdx = -1;
for (let k = 0; k < len; k++) {
const probe = (pool.cursor + k) % len;
if (!pool.slots[probe].active) {
chosenIdx = probe;
pool.cursor = (probe + 1) % len;
break;
}
}
if (chosenIdx < 0) {
chosenIdx = pool.cursor;
pool.cursor = (pool.cursor + 1) % len;
}
const slot = pool.slots[chosenIdx];
tmpStartCol.setHex(colorHex);
tmpEndCol.setHex(opts?.endColorHex ?? colorHex);
const hdrGain = opts?.additive ? 1.45 : 1.0;
slot.active = true;
slot.x = x;
slot.y = y;
slot.z = z;
slot.vx = vx;
slot.vy = vy;
slot.vz = vz;
slot.age = 0;
slot.maxAge = maxAge;
slot.baseScale = baseScale * 2.5;
slot.growRate = growRate * 2.5;
slot.baseOpacity = baseOpacity;
slot.rot = Math.random() * Math.PI * 2;
slot.rotSpeed = opts?.rotSpeed ?? (Math.random() - 0.5) * 1.4;
slot.r0 = tmpStartCol.r * hdrGain;
slot.g0 = tmpStartCol.g * hdrGain;
slot.b0 = tmpStartCol.b * hdrGain;
slot.r1 = tmpEndCol.r * hdrGain;
slot.g1 = tmpEndCol.g * hdrGain;
slot.b1 = tmpEndCol.b * hdrGain;
slot.drag = opts?.drag ?? 1.4;
slot.buoyancy = opts?.buoyancy ?? 0;
slot.groundClampY = opts?.groundClampY ?? null;
pool.positions[chosenIdx * 3] = x;
pool.positions[chosenIdx * 3 + 1] = y;
pool.positions[chosenIdx * 3 + 2] = z;
pool.sizes[chosenIdx] = slot.baseScale;
pool.alphas[chosenIdx] = baseOpacity;
pool.colors[chosenIdx * 3] = slot.r0;
pool.colors[chosenIdx * 3 + 1] = slot.g0;
pool.colors[chosenIdx * 3 + 2] = slot.b0;
pool.rots[chosenIdx] = slot.rot;
}
export function advanceGpuPool(
pool: GpuParticlePool | null,
step: number,
viewHeight: number,
) {
if (!pool) return;
pool.mat.uniforms.uScale.value = Math.max(180, viewHeight * 0.56);
const n = pool.slots.length;
for (let i = 0; i < n; i++) {
const s = pool.slots[i];
if (!s.active) {
pool.alphas[i] = 0;
pool.sizes[i] = 0;
continue;
}
s.age += step;
if (s.age >= s.maxAge) {
s.active = false;
pool.alphas[i] = 0;
pool.sizes[i] = 0;
continue;
}
const frac = s.age / s.maxAge;
const damp = Math.exp(-s.drag * step);
s.vx *= damp;
s.vy = s.vy * damp + s.buoyancy * step;
s.vz *= damp;
s.x += s.vx * step;
s.y += s.vy * step;
s.z += s.vz * step;
if (s.groundClampY !== null && s.y < s.groundClampY) {
s.y = s.groundClampY;
const speed = Math.hypot(s.vx, s.vz) + 2.0;
const spread = Math.atan2(s.vz, s.vx) + (Math.random() - 0.5) * 0.35;
s.vx = Math.cos(spread) * speed * 1.15;
s.vz = Math.sin(spread) * speed * 1.15;
s.vy = Math.abs(s.vy) * 0.15 + 0.6;
}
s.rot += s.rotSpeed * step;
pool.positions[i * 3] = s.x;
pool.positions[i * 3 + 1] = s.y;
pool.positions[i * 3 + 2] = s.z;
pool.sizes[i] = Math.max(0.1, s.baseScale + s.growRate * s.age);
const fadeIn = Math.min(1, s.age / Math.max(0.06, s.maxAge * 0.12));
pool.alphas[i] = s.baseOpacity * fadeIn * Math.pow(1 - frac, 1.45);
pool.colors[i * 3] = s.r0 + (s.r1 - s.r0) * frac;
pool.colors[i * 3 + 1] = s.g0 + (s.g1 - s.g0) * frac;
pool.colors[i * 3 + 2] = s.b0 + (s.b1 - s.b0) * frac;
pool.rots[i] = s.rot;
}
pool.attrPos.needsUpdate = true;
pool.attrSize.needsUpdate = true;
pool.attrAlpha.needsUpdate = true;
pool.attrColor.needsUpdate = true;
pool.attrRot.needsUpdate = true;
}
export function resetGpuPool(pool: GpuParticlePool | null) {
if (!pool) return;
for (let i = 0; i < pool.slots.length; i++) {
pool.slots[i].active = false;
pool.alphas[i] = 0;
pool.sizes[i] = 0;
}
pool.attrAlpha.needsUpdate = true;
pool.attrSize.needsUpdate = true;
}

View file

@ -0,0 +1,312 @@
// 3D launch ascent & orbit sequence screen
import * as THREE from "three";
import { api } from "../api.js";
import { navigate } from "../router.js";
import { refreshMe } from "../session.js";
import {
applyThemeFromState,
currentContract,
type LaunchScreenParams,
state,
} from "../state.js";
import { playIgnitionBurst } from "../sound.js";
import {
buildLaunchComplex,
buildRocketMesh,
disposeRocketMesh,
} from "../three/rocketMesh.js";
import { createView } from "../three/sceneManager.js";
import { generateTrajectory } from "../../shared/ephemeris.js";
import { buildRocket, createStarterDesign } from "../../shared/physics.js";
import type {
ActiveMission,
AgencyState,
MissionSettlement,
} from "../../shared/types.js";
import { clear, h, toast } from "../ui.js";
import {
stepParticlesAndDebris,
updateAscentVisuals,
} from "./launch/ascentEffects.js";
import type { LaunchContext } from "./launch/context.js";
import {
createAscentEnvironment,
createRocketAeroEffects,
} from "./launch/environment.js";
import {
buildControlsBar,
pushEventLog,
updateTelemetryHud,
} from "./launch/hud.js";
import {
enterOrbitPhase,
sampleTelemetryAt,
updateOrbitMarker,
} from "./launch/orbitPhase.js";
export function renderLaunchSequence(
root: HTMLElement,
params: LaunchScreenParams = {},
): () => void {
const viewportEl = h("div", { class: "launch-viewport" });
const bannerEl = h(
"div",
{ class: "launch-banner" },
"T-00:02 // TERMINAL COUNT",
);
const titleLeft = h("div", { class: "launch-title-left" });
const controlsTop = h("div", { class: "launch-controls" });
const hudStackEl = h("div", { class: "launch-hud-stack" });
const hudEl = h("div", { class: "launch-hud" });
const eventsEl = h("div", { class: "launch-events" });
hudStackEl.append(eventsEl, hudEl);
viewportEl.append(titleLeft, controlsTop, bannerEl, hudStackEl);
root.appendChild(h("div", { class: "screen launch-root" }, viewportEl));
const view = createView(viewportEl, { fov: 46, far: 120000 });
view.addStars(3200, 30000);
view.camera.position.set(42, 24, 58);
view.controls.target.set(0, 12, 0);
const ctx: LaunchContext = {
view,
bannerEl,
titleLeft,
controlsTop,
hudEl,
eventsEl,
liveStripCanvas: h("canvas", {
class: "canvas-box",
width: 270,
height: 64,
style: { marginTop: "6px" },
}) as HTMLCanvasElement,
liveHistory: [],
disposed: false,
speed: 1,
paused: false,
simClock: -2.2,
phase: "ascent",
activeMission: null,
settlement: undefined,
simResult: null,
trajectory: null,
designUsed: null,
builtAssembly: null,
isSpectating: !!params.spectateId,
isTest: !!params.testResult,
rocketRoot: new THREE.Group(),
ascentEnvGroup: null,
padGroup: null,
rocketHandle: null,
machCone: null,
machConeMat: null,
plasmaGlow: null,
plasmaGlowMat: null,
rocketHeightVis: 45,
cgPivotY: 18,
camMode: "track",
smokePool: null,
sparkPool: null,
prevShake: new THREE.Vector3(),
highestStageShown: 1,
fairingSeparated: false,
jettisonedDropStages: new Set(),
debrisList: [],
emittedEventIdx: new Set(),
hudVals: null,
orbitGroup: null,
craftMarker: null,
orbitProgress: 0,
lastHudRefresh: 0,
onEnterOrbit: () => enterOrbitPhase(ctx),
onRebuildControls: () => buildControlsBar(ctx),
};
async function initLaunch(): Promise<void> {
try {
if (params.spectateId) {
const spec = await api.get<
ActiveMission & { progress: number; simTime: number }
>(`/api/missions/spectate/${encodeURIComponent(params.spectateId)}`);
if (ctx.disposed) return;
ctx.activeMission = spec;
ctx.simResult = spec.ascent;
ctx.trajectory = spec.trajectory;
ctx.designUsed = spec.rocketDesign;
ctx.simClock = 0;
} else if (params.testResult) {
ctx.simResult = params.testResult;
ctx.designUsed =
state.agency?.rocketDesign ?? createStarterDesign(currentContract());
ctx.trajectory = generateTrajectory(
currentContract()?.target ?? "leo",
undefined,
220,
{
altKm: ctx.designUsed.flightParams.targetApoapsisKm,
incDeg: ctx.designUsed.flightParams.targetInclinationDeg,
},
);
} else {
const res = await api.post<{
ok: boolean;
mission: ActiveMission;
settlement?: MissionSettlement;
remainingTreasury: number;
agency?: AgencyState;
}>("/api/mission/launch", {});
if (ctx.disposed) return;
ctx.activeMission = res.mission;
ctx.settlement = res.settlement ?? res.mission.settlement;
ctx.simResult = res.mission.ascent;
ctx.trajectory = res.mission.trajectory;
ctx.designUsed = res.mission.rocketDesign;
if (res.agency) state.agency = res.agency;
else await refreshMe();
}
} catch (err) {
toast((err as Error).message, "err");
navigate("dashboard");
return;
}
if (!ctx.designUsed || !ctx.simResult) {
navigate("dashboard");
return;
}
applyThemeFromState("ascent");
clear(ctx.titleLeft);
ctx.titleLeft.append(
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("dashboard") },
"← Dashboard",
),
h(
"h2",
{},
ctx.isSpectating
? `SPECTATING: ${ctx.activeMission?.agencyName} — ${ctx.activeMission?.name}`
: ctx.isTest
? `TEST FLIGHT: ${ctx.designUsed.name}`
: `FLIGHT DIRECTOR: ${ctx.activeMission?.name}`,
),
);
clear(ctx.eventsEl);
ctx.eventsEl.appendChild(
h(
"h3",
{ class: "accent", style: { marginBottom: "6px" } },
"Flight Events Log",
),
);
const asm = buildRocket(ctx.designUsed, state.parts, state.materials, {
mission: ctx.activeMission?.contract ?? currentContract(),
difficulty: state.agency?.difficulty,
weather: state.world?.weather ?? "nominal",
});
ctx.builtAssembly = asm;
ctx.rocketHeightVis = asm.height;
const envBuilt = createAscentEnvironment();
ctx.ascentEnvGroup = envBuilt.env;
ctx.smokePool = envBuilt.smokePool;
ctx.sparkPool = envBuilt.sparkPool;
ctx.view.scene.add(ctx.ascentEnvGroup);
ctx.padGroup = await buildLaunchComplex(asm.height);
if (ctx.disposed) return;
const apron = new THREE.Mesh(
new THREE.CircleGeometry(220, 48),
new THREE.MeshStandardMaterial({
color: 0x151b26,
roughness: 0.92,
metalness: 0.06,
}),
);
apron.rotation.x = -Math.PI / 2;
apron.position.y = -0.15;
apron.receiveShadow = true;
ctx.padGroup.add(apron);
ctx.view.scene.add(ctx.padGroup);
ctx.rocketHandle = await buildRocketMesh(asm, {
realModels: true,
fairingCutaway: false,
});
if (ctx.disposed) return;
ctx.cgPivotY = Math.max(1, asm.cgY ?? asm.height * 0.42);
ctx.rocketHandle.group.position.y = -ctx.cgPivotY;
ctx.rocketRoot.position.set(0, ctx.cgPivotY, 0);
ctx.rocketRoot.add(ctx.rocketHandle.group);
const aero = createRocketAeroEffects(ctx.rocketHandle, asm.maxDiameter);
ctx.machCone = aero.machCone;
ctx.machConeMat = aero.machConeMat;
ctx.plasmaGlow = aero.plasmaGlow;
ctx.plasmaGlowMat = aero.plasmaGlowMat;
ctx.view.scene.add(ctx.rocketRoot);
ctx.view.camera.position.set(
asm.height * 1.15,
asm.height * 0.6,
asm.height * 1.55,
);
ctx.view.controls.target.set(0, asm.height * 0.45, 0);
buildControlsBar(ctx);
}
let burstPlayed = false;
let raf = 0;
let lastMs = performance.now();
function tick(): void {
if (ctx.disposed) return;
raf = requestAnimationFrame(tick);
const now = performance.now();
const dt = Math.min(0.08, (now - lastMs) / 1000);
lastMs = now;
if (!ctx.simResult) return;
if (!ctx.paused) {
if (ctx.phase === "ascent") {
const prevClock = ctx.simClock;
ctx.simClock += dt * ctx.speed;
if (prevClock < 0 && ctx.simClock >= 0 && !burstPlayed) {
burstPlayed = true;
playIgnitionBurst();
pushEventLog(ctx, "MAIN ENGINE START — LIFTOFF!", "info");
}
} else if (ctx.phase === "orbit") {
ctx.orbitProgress =
(ctx.orbitProgress + dt * 0.08 * Math.max(1, ctx.speed * 0.5)) % 1;
}
}
if (ctx.phase === "ascent") {
const tPos = Math.max(0, ctx.simClock);
const sample = sampleTelemetryAt(ctx.simResult, tPos);
ctx.simResult.events.forEach((ev, idx) => {
if (!ctx.emittedEventIdx.has(idx) && tPos >= ev.t) {
ctx.emittedEventIdx.add(idx);
pushEventLog(ctx, ev.label, ev.kind);
}
});
if (sample) {
updateAscentVisuals(ctx, sample, tPos, dt, now);
updateTelemetryHud(ctx, sample, now);
}
stepParticlesAndDebris(ctx, dt);
if (tPos >= ctx.simResult.finalTime + 1.2) {
if (ctx.simResult.success && ctx.trajectory) {
enterOrbitPhase(ctx);
} else {
ctx.phase = "done";
ctx.paused = true;
applyThemeFromState("failed");
ctx.bannerEl.textContent = `ANOMALY DETECTED // ${ctx.simResult.failureReason?.toUpperCase() ?? "ABORT"}`;
pushEventLog(ctx, ctx.simResult.failureDetail, "err");
buildControlsBar(ctx);
}
}
} else if (ctx.phase === "orbit") {
updateOrbitMarker(ctx);
}
}
void initLaunch();
raf = requestAnimationFrame(tick);
return () => {
ctx.disposed = true;
cancelAnimationFrame(raf);
disposeRocketMesh(ctx.rocketHandle);
ctx.view.dispose();
};
}

View file

@ -0,0 +1,339 @@
// Renders the animated 3D solar system main menu, settings dialog, and quick-join entry.
// Again, self explanatory
import { api, getSettings, saveSettings } from "../api.js";
import { navigate } from "../router.js";
import { refreshMe, refreshWorld, startEvents } from "../session.js";
import { state } from "../state.js";
import { createView } from "../three/sceneManager.js";
import { buildSolarSystem } from "../three/solarSystem.js";
import { h, modal, toast } from "../ui.js";
function openSettingsModal(): void {
const s = { ...getSettings() };
const qualitySel = h(
"select",
{
class: "input",
onChange: () => {
s.quality = qualitySel.value as typeof s.quality;
},
},
h(
"option",
{ value: "low", selected: s.quality === "low" },
"Low (1x DPR, low shadow/antialias)",
),
h(
"option",
{ value: "medium", selected: s.quality === "medium" },
"Medium (1.5x DPR)",
),
h(
"option",
{ value: "high", selected: s.quality === "high" },
"High (Native DPR + antialias)",
),
);
const colorModeSel = h(
"select",
{
class: "input",
onChange: () => {
s.colorMode = colorModeSel.value as "dark" | "light";
},
},
h(
"option",
{ value: "dark", selected: s.colorMode === "dark" },
"Dark Slate (Default Night Ops)",
),
h(
"option",
{ value: "light", selected: s.colorMode === "light" },
"Daylight Clean (Light Mode)",
),
);
const reducedChk = h("input", {
type: "checkbox",
checked: s.reducedEffects,
onChange: () => {
s.reducedEffects = reducedChk.checked;
},
});
const soundChk = h("input", {
type: "checkbox",
checked: s.sound,
onChange: () => {
s.sound = soundChk.checked;
},
});
const notifChk = h("input", {
type: "checkbox",
checked: s.notifications,
onChange: () => {
s.notifications = notifChk.checked;
},
});
const dynChk = h("input", {
type: "checkbox",
checked: s.dynamicTheme,
onChange: () => {
s.dynamicTheme = dynChk.checked;
},
});
const mlRow = h(
"div",
{ class: "slot-group", style: { marginTop: "6px" } },
h(
"div",
{ class: "slot-title" },
"ML AI Subprocess Bridge (Python / ONNX / PyTorch)",
),
);
const mlStatusText = h(
"div",
{ class: "mono dim", style: { fontSize: "11px" } },
"Checking server ML bridge status...",
);
const mlToggleBtn = h(
"button",
{
class: "btn sm ghost",
disabled: !state.agency,
onClick: async () => {
try {
const updated = await api.toggleMlBridge();
renderMlBox(updated);
toast(
`ML AI Bridge ${updated.enabled ? "ENABLED" : "DISABLED"} (${updated.backend})`,
"ok",
);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Toggle ML Bridge",
);
const renderMlBox = (st: any) => {
mlStatusText.textContent = `State: ${st.enabled ? "ON" : "OFF"} | Backend: ${st.backend} | Python: ${st.pythonAvailable ? `v${st.pythonVersion ?? "?"}` : "Absent (TS Fallback)"} | Episodes: ${st.episodes ?? 0}`;
mlToggleBtn.textContent = st.enabled
? "Disable ML Bridge"
: "Enable ML Bridge";
};
mlRow.append(
mlStatusText,
h(
"div",
{ class: "row" },
mlToggleBtn,
!state.agency
? h(
"span",
{ class: "mono faint", style: { fontSize: "10px" } },
"(Sign in to toggle server bridge)",
)
: null,
),
);
void api
.getMlStatus()
.then(renderMlBox)
.catch(() => {
mlStatusText.textContent = "ML bridge status unavailable.";
});
const body = h(
"div",
{ class: "col" },
h("label", { class: "field" }, "3D Graphics Quality", qualitySel),
h("label", { class: "field" }, "Color Theme", colorModeSel),
h(
"label",
{ class: "row", style: { cursor: "pointer" } },
reducedChk,
h(
"span",
{},
"Reduced Effects / Eye-Saver (disables glows, blur, chamfers, scanlines & camera shake)",
),
),
h(
"label",
{ class: "row", style: { cursor: "pointer" } },
soundChk,
h("span", {}, "UI & Ignition Sound Effects"),
),
h(
"label",
{ class: "row", style: { cursor: "pointer" } },
notifChk,
h("span", {}, "Mission & Space Weather Notifications"),
),
h(
"label",
{ class: "row", style: { cursor: "pointer" } },
dynChk,
h(
"span",
{},
"Dynamic Simulation Color Palette (shifts with space weather & target)",
),
),
mlRow,
);
modal("System & Graphics Settings", body, [
{ label: "Cancel", kind: "ghost" },
{
label: "Save Settings",
kind: "primary",
onClick: () => {
saveSettings(s);
window.dispatchEvent(new CustomEvent("sgywftp:theme-changed"));
toast("Settings saved.", "ok");
},
},
]);
}
function proceedAfterJoin(): void {
if (state.agency) {
startEvents();
void refreshWorld();
if (!state.agency.sponsorId) {
navigate("onboarding");
} else {
navigate("dashboard");
}
return;
}
navigate("auth");
}
function handleJoinClick(): void {
if (!state.serverInfo?.serverPasswordRequired) {
proceedAfterJoin();
return;
}
const pwdInput = h("input", {
class: "input",
type: "password",
placeholder: "Enter server access code",
});
const errLine = h("div", { class: "auth-error" });
const body = h(
"div",
{ class: "col" },
h(
"p",
{ class: "dim", style: { fontSize: "12px" } },
"This telemetry instance requires a server access password.",
),
h("label", { class: "field" }, "Server Password", pwdInput),
errLine,
);
const m = modal("Server Access Verification", body, [
{ label: "Cancel", kind: "ghost" },
{
label: "Verify & Join",
kind: "primary",
onClick: async () => {
errLine.textContent = "";
try {
await api.post("/api/join", { password: pwdInput.value }, false);
proceedAfterJoin();
} catch (err) {
errLine.textContent = (err as Error).message;
return false;
}
},
},
]);
pwdInput.addEventListener("keydown", (ev) => {
if (ev.key === "Enter") {
const btn = m.el.querySelector(
".btn.primary",
) as HTMLButtonElement | null;
btn?.click();
}
});
setTimeout(() => pwdInput.focus(), 40);
}
export function renderMainMenu(root: HTMLElement): () => void {
const screen = h("div", { class: "screen" });
const bg = h("div", {
style: { position: "absolute", inset: "0", zIndex: "0" },
});
screen.appendChild(bg);
root.appendChild(screen);
let solar: ReturnType<typeof buildSolarSystem> | null = null;
let simTime = Date.now() / 1000;
const view = createView(bg, {
fov: 46,
far: 30000,
onFrame: (dt) => {
simTime += dt * 48000;
solar?.update(simTime, dt * 0.045);
},
});
view.addStars(3800, 12000);
view.camera.position.set(0, 290, 620);
view.controls.target.set(0, 0, 0);
view.controls.autoRotate = true;
view.controls.autoRotateSpeed = 0.22;
solar = buildSolarSystem(view.scene, { slowSpin: true, showAssets: false });
view.scene.add(solar.group);
const authedLabel = state.agency
? `Resume Agency (${state.agency.name})`
: "Join Mission Control";
const overlay = h(
"div",
{ class: "menu-root" },
h(
"div",
{ class: "menu-brand-pill" },
"GsDistance Project // NASA Space Apps Challenge",
),
h("h1", { class: "menu-title" }, "Space Gaem"),
h("div", { class: "menu-subtitle" }, "You Will Feel The Pain"),
h(
"div",
{ class: "menu-buttons" },
h(
"button",
{ class: "btn primary", onClick: handleJoinClick },
authedLabel,
),
state.agency
? h(
"button",
{
class: "btn ghost",
onClick: async () => {
try {
await api.post("/api/auth/logout", {});
} catch {}
localStorage.removeItem("spacegaem_proto_token");
state.agency = null;
state.account = null;
navigate("auth");
},
},
"Switch Agency",
)
: null,
h("button", { class: "btn", onClick: openSettingsModal }, "Settings"),
),
h(
"div",
{ class: "menu-footer" },
`NASA CML/TRL Compliance Engine • 6-DOF-Lite Ascent Sim • Dynamic Ephemeris (${state.parts.length} parts loaded)`,
),
);
screen.appendChild(overlay);
if (state.agency) void refreshMe();
return () => {
view.dispose();
};
}

View file

@ -0,0 +1,381 @@
// Flight parameter configurator screen with real-time ascent & orbital diagnostics
// Again, self explanatory
import { api } from "../api.js";
import { navigate } from "../router.js";
import { refreshMe } from "../session.js";
import { currentContract, state } from "../state.js";
import { simulateAscent } from "../../shared/ascent_sim.js";
import {
autoTuneFlightParams,
buildRocket,
createDefaultFlightParams,
createStarterDesign,
getDifficultyProfile,
normalizeDesign,
} from "../../shared/physics.js";
import type { CrewConfig, FlightParams } from "../../shared/types.js";
import { h, term, toast } from "../ui.js";
import type { GlossaryKey } from "../glossary.js";
import {
renderDiagPanel,
renderForecastBoxes,
type MissionConfigContext,
} from "./missionConfig/prelaunch.js";
export function renderMissionConfig(root: HTMLElement): void {
const agency = state.agency;
if (!agency) {
navigate("auth");
return;
}
const contract = currentContract();
const workingDesign = normalizeDesign(
agency.rocketDesign
? structuredClone(agency.rocketDesign)
: createStarterDesign(contract, agency.difficulty),
state.parts,
state.materials,
);
const profile = getDifficultyProfile(agency.difficulty);
const fp: FlightParams = {
...createDefaultFlightParams(contract),
...workingDesign.flightParams,
};
workingDesign.flightParams = fp;
const crew: CrewConfig = {
crewSize: agency.crewConfig?.crewSize ?? (contract?.crewed ? 2 : 0),
lifeSupport: agency.crewConfig?.lifeSupport ?? (contract?.crewed ? 2 : 1),
};
const sliderSyncers: Array<() => void> = [];
function recomputePreview(): void {
workingDesign.flightParams = { ...fp };
ctx.cachedGmatTraj = null;
const sim = simulateAscent(workingDesign, state.parts, state.materials, {
weather: state.world?.weather ?? "nominal",
activeHazards: state.world?.activeHazards ?? [],
unlockedTechs: agency?.unlockedTechs ?? [],
mission: contract,
rollAnomalies: false,
sampleEvery: 1.5,
difficulty: agency?.difficulty,
});
ctx.latestSimResult = sim;
renderDiagPanel(ctx);
renderForecastBoxes(ctx, sim);
}
const ctx: MissionConfigContext = {
agency,
contract,
workingDesign,
profile,
fp,
ascentCanvas: h("canvas", {
class: "canvas-box",
width: 760,
height: 280,
}) as HTMLCanvasElement,
telemetryDiagCanvas: h("canvas", {
class: "canvas-box",
width: 760,
height: 280,
}) as HTMLCanvasElement,
orbitCanvas: h("canvas", {
class: "canvas-box",
width: 760,
height: 260,
}) as HTMLCanvasElement,
diagTabsEl: h("div", {
class: "row",
style: { gap: "6px", flexWrap: "wrap" },
}),
diagPanelEl: h("div", { class: "col", style: { gap: "10px" } }),
rootCauseBoxEl: h("div", { class: "panel", style: { padding: "12px" } }),
gmatStatsBoxEl: h("div", { class: "panel", style: { padding: "12px" } }),
simSummaryEl: h("div", { class: "stat-grid" }),
windowBoxEl: h("div", { class: "panel", style: { padding: "12px" } }),
hazardsBoxEl: h("div", { class: "panel", style: { padding: "12px" } }),
prelaunchBoxEl: h("div", { class: "panel", style: { padding: "12px" } }),
diagTab: "ascent",
latestSimResult: null,
cachedGmatTraj: null,
gmatLoading: false,
onRecomputePreview: recomputePreview,
};
function makeSlider<K extends keyof FlightParams>(
label: string,
key: K,
min: number,
max: number,
step: number,
unit: string,
tipKey?: GlossaryKey,
) {
const valEl = h("span", { class: "accent mono" }, `${fp[key]} ${unit}`);
const input = h("input", {
type: "range",
class: "slider",
min,
max,
step,
value: fp[key],
onInput: () => {
fp[key] = Number(input.value);
valEl.textContent = `${fp[key]} ${unit}`;
recomputePreview();
},
});
sliderSyncers.push(() => {
input.value = String(fp[key]);
valEl.textContent = `${fp[key]} ${unit}`;
});
return h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "slot-title" },
tipKey ? term(label, tipKey) : label,
),
valEl,
),
input,
);
}
const crewSizeInput = h("input", {
type: "range",
class: "slider",
min: 0,
max: 6,
step: 1,
value: crew.crewSize,
onInput: () => {
crew.crewSize = Number(crewSizeInput.value);
crewVal.textContent = `${crew.crewSize} crew (+${crew.crewSize * (85 + 15 * crew.lifeSupport) + (crew.crewSize > 0 ? 500 * crew.lifeSupport : 0)} kg)`;
},
});
const eclssInput = h("input", {
type: "range",
class: "slider",
min: 0,
max: 3,
step: 1,
value: crew.lifeSupport,
onInput: () => {
crew.lifeSupport = Number(eclssInput.value);
eclssVal.textContent = `Tier ${crew.lifeSupport}`;
crewVal.textContent = `${crew.crewSize} crew (+${crew.crewSize * (85 + 15 * crew.lifeSupport) + (crew.crewSize > 0 ? 500 * crew.lifeSupport : 0)} kg)`;
},
});
const crewVal = h("span", { class: "mono accent" }, `${crew.crewSize} crew`);
const eclssVal = h(
"span",
{ class: "mono accent" },
`Tier ${crew.lifeSupport}`,
);
async function saveParameters() {
if (!agency?.rocketDesign) {
toast("Save a rocket design in Rocket Builder first.", "warn");
navigate("builder");
return false;
}
await api.post("/api/agency/flight-params", { flightParams: fp });
await api.post("/api/agency/crew", { crew });
await refreshMe();
return true;
}
const mainCol = h(
"div",
{ class: "param-main" },
h(
"div",
{ class: "spread" },
h(
"div",
{ class: "row" },
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("dashboard") },
"← Dashboard",
),
h("h2", {}, "Flight Parameter Configurator"),
),
h(
"span",
{ class: "badge info" },
agency.rocketDesign?.name ?? "Reference Trajectory Preview",
),
),
ctx.diagTabsEl,
ctx.diagPanelEl,
);
const sideCol = h(
"div",
{ class: "param-side" },
ctx.simSummaryEl,
ctx.windowBoxEl,
ctx.hazardsBoxEl,
ctx.prelaunchBoxEl,
h(
"button",
{
class: "btn sm primary",
onClick: () => {
try {
const asm = buildRocket(
workingDesign,
state.parts,
state.materials,
);
const tuned = autoTuneFlightParams(workingDesign, asm, contract);
Object.assign(fp, tuned);
sliderSyncers.forEach((sync) => sync());
recomputePreview();
toast(
"Flight computer auto-tuned guidance profile for current rocket & orbit.",
"ok",
);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Auto-Tune Flight Computer",
),
makeSlider(
"Gravity Turn Start Velocity",
"gravityTurnStartVel",
35,
160,
5,
"m/s",
"flight_path_angle",
),
makeSlider(
"Initial Pitch-Over Kick",
"pitchOverDeg",
3,
18,
0.5,
"°",
"flight_path_angle",
),
makeSlider(
"Gravity Turn Level-Off Alt",
"turnEndAltKm",
65,
130,
1,
"km",
"turn_end_alt",
),
makeSlider(
"Max-Q Throttle Bucket",
"maxQThrottle",
0.5,
1.0,
0.02,
"frac",
"max_q_throttle",
),
makeSlider(
"Fairing Jettison Altitude",
"fairingSepAltKm",
70,
130,
5,
"km",
"fairing_sep_alt",
),
makeSlider(
"Target Apoapsis Altitude",
"targetApoapsisKm",
170,
850,
10,
"km",
"apoapsis",
),
makeSlider(
"Target Inclination",
"targetInclinationDeg",
0,
98,
0.5,
"°",
"inclination",
),
makeSlider(
"Upper Burn Continuous Fraction",
"upperBurnSplit",
0.65,
1.0,
0.05,
"ratio",
"meco_seco",
),
h(
"div",
{ class: "slot-group" },
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "slot-title" },
term("Crew Complement", "crew_eclss"),
),
crewVal,
),
crewSizeInput,
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "slot-title" },
term("ECLSS Life Support", "crew_eclss"),
),
eclssVal,
),
eclssInput,
),
h(
"div",
{ class: "row", style: { marginTop: "auto", paddingTop: "8px" } },
h(
"button",
{
class: "btn sm ghost",
onClick: async () => {
try {
if (await saveParameters())
toast("Flight parameters & ECLSS saved.", "ok");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Save Profile",
),
h(
"button",
{
class: "btn sm primary grow",
onClick: async () => {
try {
if (await saveParameters()) navigate("launch");
} catch (err) {
toast((err as Error).message, "err");
}
},
},
"Save & Proceed to Pad →",
),
),
);
recomputePreview();
root.appendChild(h("div", { class: "screen param-root" }, mainCol, sideCol));
}

View file

@ -0,0 +1,356 @@
// Canvas chart renderers for ascent profile, telemetry channels, and orbital geometry
// I started rendering by making charts first, they're cool
import { generateTrajectory } from "../../../shared/ephemeris.js";
import type {
ContractOffer,
FlightParams,
MissionTemplate,
SimResult,
TrajectoryResult,
} from "../../../shared/types.js";
import { getColorMode } from "../../theme.js";
import { clear, fmtDuration, fmtNum, h } from "../../ui.js";
export function drawAscentChart(
ascentCanvas: HTMLCanvasElement,
sim: SimResult,
): void {
const ctx = ascentCanvas.getContext("2d");
if (!ctx) return;
const light = getColorMode() === "light";
const W = ascentCanvas.width;
const H = ascentCanvas.height;
ctx.fillStyle = light ? "#f8fafc" : "#0b0e14";
ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = light ? "rgba(15, 23, 42, 0.12)" : "rgba(42, 52, 73, 0.55)";
ctx.lineWidth = 1;
for (let i = 1; i < 5; i++) {
const y = (H / 5) * i;
ctx.beginPath();
ctx.moveTo(48, y);
ctx.lineTo(W - 14, y);
ctx.stroke();
}
const pts = sim.telemetry;
if (!pts.length) return;
const maxDr = Math.max(250, ...pts.map((p) => p.downrange / 1000));
const maxAlt = Math.max(220, ...pts.map((p) => p.altitude / 1000));
const padL = 48;
const padR = 16;
const padT = 18;
const padB = 26;
const pw = W - padL - padR;
const ph = H - padT - padB;
const toX = (drKm: number) => padL + (drKm / maxDr) * pw;
const toY = (altKm: number) => padT + ph - (altKm / maxAlt) * ph;
const qPeak = pts.reduce(
(best, p) => (p.dynamicPressure > best.dynamicPressure ? p : best),
pts[0],
);
const qx = toX(qPeak.downrange / 1000);
const qy = toY(qPeak.altitude / 1000);
ctx.strokeStyle = sim.success ? (light ? "#0284c7" : "#60a5fa") : "#ef4444";
ctx.lineWidth = 2.4;
ctx.beginPath();
pts.forEach((p, idx) => {
const x = toX(p.downrange / 1000);
const y = toY(p.altitude / 1000);
if (idx === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
ctx.fillStyle = "#f59e0b";
ctx.beginPath();
ctx.arc(qx, qy, 4.5, 0, Math.PI * 2);
ctx.fill();
ctx.font = "11px monospace";
ctx.fillText(
`Max-Q ${(qPeak.dynamicPressure / 1000).toFixed(1)} kPa`,
Math.min(W - 140, qx + 8),
Math.max(16, qy - 6),
);
ctx.fillStyle = light ? "#475569" : "#94a3b8";
ctx.fillText("0 km", 6, padT + ph);
ctx.fillText(`${Math.round(maxAlt)} km`, 4, padT + 10);
ctx.fillText(`Downrange ${Math.round(maxDr)} km`, W - 150, H - 6);
ctx.fillStyle = sim.success ? (light ? "#059669" : "#34d399") : "#ef4444";
ctx.fillText(
sim.success
? `ORBIT INSERTION ${Math.round(sim.periapsis / 1000)}×${Math.round(sim.apoapsis / 1000)} km`
: sim.failureDetail.slice(0, 56),
padL + 8,
20,
);
}
export function drawMultiTelemetryChart(
telemetryDiagCanvas: HTMLCanvasElement,
rootCauseBoxEl: HTMLElement,
sim: SimResult,
): void {
const ctx = telemetryDiagCanvas.getContext("2d");
if (!ctx) return;
const light = getColorMode() === "light";
const W = telemetryDiagCanvas.width;
const H = telemetryDiagCanvas.height;
ctx.fillStyle = light ? "#f8fafc" : "#0b0e14";
ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = light ? "rgba(15, 23, 42, 0.12)" : "rgba(42, 52, 73, 0.55)";
ctx.lineWidth = 1;
for (let i = 1; i < 4; i++) {
const y = (H / 4) * i;
ctx.beginPath();
ctx.moveTo(42, y);
ctx.lineTo(W - 16, y);
ctx.stroke();
}
const pts = sim.telemetry;
if (!pts.length) return;
const maxT = Math.max(10, pts[pts.length - 1].t);
const maxQ = Math.max(10000, ...pts.map((p) => p.dynamicPressure));
const maxG = Math.max(4, ...pts.map((p) => p.gLoad));
const maxCpu = Math.max(120, ...pts.map((p) => p.cpuLoadPct ?? 0));
const maxRad = Math.max(2, ...pts.map((p) => p.radFluxMsvHr ?? 0));
const padL = 42;
const padT = 26;
const padB = 22;
const pw = W - padL - 16;
const ph = H - padT - padB;
const toX = (t: number) => padL + (t / maxT) * pw;
const plotSeries = (
color: string,
getter: (p: (typeof pts)[number]) => number,
) => {
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
pts.forEach((p, idx) => {
const x = toX(p.t);
const y = padT + ph - Math.min(1, Math.max(0, getter(p))) * ph;
if (idx === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
};
const cpu100Y = padT + ph - (100 / maxCpu) * ph;
ctx.save();
ctx.setLineDash([4, 4]);
ctx.strokeStyle = "rgba(245, 158, 11, 0.6)";
ctx.beginPath();
ctx.moveTo(padL, cpu100Y);
ctx.lineTo(W - 16, cpu100Y);
ctx.stroke();
ctx.restore();
plotSeries("#38bdf8", (p) => p.dynamicPressure / maxQ);
plotSeries("#34d399", (p) => p.gLoad / maxG);
plotSeries("#f59e0b", (p) => (p.cpuLoadPct ?? 0) / maxCpu);
plotSeries("#f472b6", (p) => (p.radFluxMsvHr ?? 0) / maxRad);
ctx.font = "11px monospace";
ctx.fillStyle = "#38bdf8";
ctx.fillText(`Q max ${(maxQ / 1000).toFixed(1)}kPa`, 46, 16);
ctx.fillStyle = "#34d399";
ctx.fillText(`G max ${maxG.toFixed(1)}G`, 178, 16);
ctx.fillStyle = "#f59e0b";
ctx.fillText(`CPU peak ${Math.round(sim.peakCpuLoadPct ?? 0)}%`, 284, 16);
ctx.fillStyle = "#f472b6";
ctx.fillText(
`Rad peak ${maxRad.toFixed(1)} mSv/h (${sim.totalSeuCount ?? 0} SEU)`,
420,
16,
);
ctx.fillStyle = light ? "#475569" : "#94a3b8";
ctx.fillText(`T+0s`, padL, H - 6);
ctx.fillText(`T+${Math.round(maxT)}s`, W - 64, H - 6);
const compFault =
sim.failureReason === "computer_damaged" ||
sim.failureReason === "computer_overload" ||
sim.failureReason === "radiation_seu_lockup" ||
pts.some((p) => p.computerStatus === "failed");
clear(rootCauseBoxEl);
rootCauseBoxEl.append(
h(
"div",
{ class: "spread", style: { marginBottom: "6px" } },
h("h3", {}, "Tier-2 Avionics & Propulsion Root-Cause Analyzer"),
h(
"span",
{ class: `badge ${sim.success ? "ok" : "err"}` },
sim.success ? "NOMINAL ASCENT" : (sim.failureReason ?? "FAULT"),
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Flight Computer Peak Load / SEUs"),
h(
"span",
{
class: `v ${(sim.peakCpuLoadPct ?? 0) > 125 ? "red" : (sim.peakCpuLoadPct ?? 0) > 95 ? "amber" : "green"}`,
},
`${Math.round(sim.peakCpuLoadPct ?? 0)}% • ${sim.totalSeuCount ?? 0} SEUs (${compFault ? "HW/CTRL FAULT" : "NOMINAL"})`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Peak Heat Flux / Dynamic Pressure"),
h(
"span",
{ class: "v" },
`${sim.peakHeatFluxWcm2.toFixed(1)} W/cm² • ${(sim.maxQ / 1000).toFixed(1)} kPa (Stage ${sim.maxQStage})`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Burnout State (Alt / Vel / Downrange)"),
h(
"span",
{ class: "v" },
`${(sim.burnoutAltitude / 1000).toFixed(1)} km • ${fmtNum(sim.burnoutVelocity)} m/s • ${(sim.burnoutDownrange / 1000).toFixed(1)} km`,
),
),
...(sim.success
? []
: [
h(
"p",
{
class: "red mono",
style: { fontSize: "11px", marginTop: "6px" },
},
`Diagnostic Verdict: ${sim.failureDetail}`,
),
]),
);
}
export interface OrbitChartOptions {
orbitCanvas: HTMLCanvasElement;
gmatStatsBoxEl: HTMLElement;
contract: ContractOffer | MissionTemplate | null;
fp: FlightParams;
gmatLoading: boolean;
trajInput?: TrajectoryResult | null;
}
export function drawOrbitChart(opts: OrbitChartOptions): void {
const { orbitCanvas, gmatStatsBoxEl, contract, fp, gmatLoading, trajInput } =
opts;
const ctx = orbitCanvas.getContext("2d");
if (!ctx) return;
const light = getColorMode() === "light";
const W = orbitCanvas.width;
const H = orbitCanvas.height;
ctx.fillStyle = light ? "#f8fafc" : "#0b0e14";
ctx.fillRect(0, 0, W, H);
const traj =
trajInput ??
generateTrajectory(contract?.target ?? "leo", undefined, 220, {
altKm: fp.targetApoapsisKm,
incDeg: fp.targetInclinationDeg,
});
const maxR = Math.max(1, ...traj.points.map((p) => Math.hypot(p.x, p.z)));
const scale = (Math.min(W, H) * 0.4) / maxR;
const cx = W * 0.5;
const cy = H * 0.5;
ctx.fillStyle =
contract?.target === "mars"
? "#d96b43"
: contract?.target === "solar"
? "#ffd166"
: "#3498db";
ctx.beginPath();
ctx.arc(cx, cy, Math.max(8, Math.min(22, 6371 * scale)), 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 2.4;
for (let i = 1; i < traj.points.length; i++) {
const p0 = traj.points[i - 1];
const p1 = traj.points[i];
const x0 = cx + p0.x * scale;
const y0 = cy + p0.z * scale;
const x1 = cx + p1.x * scale;
const y1 = cy + p1.z * scale;
if (p1.inShadow) {
ctx.strokeStyle = "#a855f7";
} else if ((p1.radBeltFlux ?? 0) > 1.0) {
ctx.strokeStyle = "#f59e0b";
} else {
ctx.strokeStyle = light ? "#0284c7" : "#60a5fa";
}
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();
}
const eclipseCount = traj.points.filter((p) => p.inShadow).length;
const eclipsePct = Math.round(
(eclipseCount / Math.max(1, traj.points.length)) * 100,
);
const peakFlux = Math.max(0, ...traj.points.map((p) => p.radBeltFlux ?? 0));
const maxDrift = Math.max(
0,
...traj.points.map((p) => p.perturbationDriftKm ?? 0),
);
const samplePt = traj.points[Math.floor(traj.points.length * 0.25)];
ctx.fillStyle = light ? "#475569" : "#94a3b8";
ctx.font = "11px monospace";
ctx.fillText(
`[${traj.source.toUpperCase()}] Target ${(contract?.target ?? "leo").toUpperCase()} • Inc ${fp.targetInclinationDeg.toFixed(1)}° • Period ${fmtDuration(traj.period)}`,
14,
18,
);
ctx.fillStyle = "#a855f7";
ctx.fillText(`Eclipse Shadow: ${eclipsePct}%`, 14, H - 10);
ctx.fillStyle = "#f59e0b";
ctx.fillText(`Peak Van Allen Flux: ${peakFlux.toFixed(2)}`, 190, H - 10);
ctx.fillStyle = "#34d399";
ctx.fillText(`Perturbation Drift: ${maxDrift.toFixed(1)} km`, 420, H - 10);
clear(gmatStatsBoxEl);
gmatStatsBoxEl.append(
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h("h3", {}, "Tier-3 GMAT Orbital Propagation & Environment"),
h(
"span",
{ class: `badge ${traj.source === "gmat" ? "ok" : "info"}` },
gmatLoading
? "QUERYING GMAT..."
: traj.source === "gmat"
? "GMAT RK89"
: "ANALYTIC + J2",
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Osculating SMA / Ecc"),
h(
"span",
{ class: "v" },
`${fmtNum(samplePt?.smaKm ?? 6371 + fp.targetApoapsisKm)} km • e ${(samplePt?.ecc ?? 0.002).toFixed(4)}`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Eclipse Shadow / Peak Rad Flux"),
h(
"span",
{ class: "v amber" },
`${eclipsePct}% shadow • ${peakFlux.toFixed(2)} rel flux`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "J2 / Drag Perturbation Drift"),
h(
"span",
{ class: "v" },
`${maxDrift.toFixed(2)} km per propagation window`,
),
),
);
}

View file

@ -0,0 +1,544 @@
// Prelaunch QA, diagnostic tabs, weather hazards, and launch window cards
import { api } from "../../api.js";
import { navigate } from "../../router.js";
import { state } from "../../state.js";
import { computeLaunchWindow } from "../../../shared/ephemeris.js";
import {
buildRocket,
computeDesignReliability,
getDifficultyProfile,
getUnlockedDiagnosticTier,
} from "../../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
DesignReliabilityReport,
FlightParams,
MissionTemplate,
RocketDesign,
SimResult,
TrajectoryResult,
} from "../../../shared/types.js";
import type { GlossaryKey } from "../../glossary.js";
import {
clear,
fmtDuration,
fmtMoney,
fmtNum,
h,
term,
toast,
} from "../../ui.js";
import {
drawAscentChart,
drawMultiTelemetryChart,
drawOrbitChart,
} from "./charts.js";
export interface MissionConfigContext {
agency: AgencyState;
contract: ContractOffer | MissionTemplate | null;
workingDesign: RocketDesign;
profile: ReturnType<typeof getDifficultyProfile>;
fp: FlightParams;
ascentCanvas: HTMLCanvasElement;
telemetryDiagCanvas: HTMLCanvasElement;
orbitCanvas: HTMLCanvasElement;
diagTabsEl: HTMLElement;
diagPanelEl: HTMLElement;
rootCauseBoxEl: HTMLElement;
gmatStatsBoxEl: HTMLElement;
simSummaryEl: HTMLElement;
windowBoxEl: HTMLElement;
hazardsBoxEl: HTMLElement;
prelaunchBoxEl: HTMLElement;
diagTab: "ascent" | "telemetry" | "gmat";
latestSimResult: SimResult | null;
cachedGmatTraj: TrajectoryResult | null;
gmatLoading: boolean;
onRecomputePreview: () => void;
}
export function renderPrelaunchBox(
ctx: MissionConfigContext,
sim?: SimResult,
): void {
const { agency, workingDesign, profile, prelaunchBoxEl, onRecomputePreview } =
ctx;
const curAgency = state.agency ?? agency!;
let rel: DesignReliabilityReport | null = null;
let sfFee = 450_000;
let insPrem = 0;
try {
const asm = buildRocket(workingDesign, state.parts, state.materials);
rel = computeDesignReliability(workingDesign, asm, curAgency);
sfFee = Math.max(450_000, Math.round(asm.totalCost * 0.04));
insPrem =
profile.id === "explorer" || profile.id === "sandbox"
? 0
: Math.round(asm.totalCost * 0.08);
} catch {
rel = null;
}
clear(prelaunchBoxEl);
prelaunchBoxEl.append(
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h(
"span",
{ class: "mono", style: { fontSize: "11px", fontWeight: "700" } },
"PRE-LAUNCH QA & COVERAGE",
),
h(
"span",
{
class: `badge ${rel && rel.reliabilityPct >= 90 ? "ok" : rel && rel.reliabilityPct >= 80 ? "info" : "warn"}`,
},
rel ? `${rel.reliabilityPct.toFixed(1)}% REL` : "N/A",
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Orbit Corridor"),
h(
"span",
{ class: "v info" },
`±${profile.orbitTolPct}% Ap / ±${profile.incTolDeg}° Inc`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Static Fire QA"),
h(
"span",
{ class: `v ${rel?.staticFired ? "green" : "amber"}` },
rel?.staticFired
? "VERIFIED (-8% Defect)"
: `UNVERIFIED (${fmtMoney(profile.id === "sandbox" ? 0 : sfFee)})`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Launch Insurance"),
h(
"span",
{
class: `v ${curAgency.launchInsured || profile.id === "explorer" || profile.id === "sandbox" ? "green" : ""}`,
},
profile.id === "sandbox"
? "INCLUDED (Sandbox)"
: profile.id === "explorer"
? "INCLUDED (Explorer)"
: curAgency.launchInsured
? `ACTIVE (+${fmtMoney(insPrem)})`
: `OFF (${fmtMoney(insPrem)})`,
),
),
...(sim
? [
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Predicted Insertion"),
h(
"span",
{
class: `v ${sim.orbitGrade === "nominal" ? "green" : sim.orbitGrade === "partial" ? "amber" : "red"}`,
},
(sim.orbitGrade ?? "failed").toUpperCase(),
),
),
]
: []),
h(
"div",
{ class: "row", style: { marginTop: "8px", gap: "6px" } },
h(
"button",
{
class: `btn xs ${rel?.staticFired ? "ghost" : "primary"} grow`,
disabled: !agency?.rocketDesign || !!rel?.staticFired,
onClick: async () => {
try {
const res = await api.post<{ fee: number; agency: AgencyState }>(
"/api/agency/static-fire",
{
design: workingDesign,
},
);
state.agency = res.agency;
toast(`Static fire completed (-${fmtMoney(res.fee)}).`, "ok");
onRecomputePreview();
} catch (err) {
toast((err as Error).message, "err");
}
},
},
rel?.staticFired
? "Static Fire OK"
: `Static Fire (${fmtMoney(profile.id === "sandbox" ? 0 : sfFee)})`,
),
profile.id !== "explorer" && profile.id !== "sandbox"
? h(
"button",
{
class: `btn xs ${curAgency.launchInsured ? "warn" : "ghost"} grow`,
onClick: async () => {
try {
const res = await api.post<{
launchInsured: boolean;
agency: AgencyState;
}>("/api/agency/insurance", {
enabled: !curAgency.launchInsured,
});
state.agency = res.agency;
toast(
res.launchInsured
? "Launch insurance enabled (8%)."
: "Launch insurance disabled.",
"info",
);
renderPrelaunchBox(ctx, sim);
} catch (err) {
toast((err as Error).message, "err");
}
},
},
curAgency.launchInsured ? "Insurance: ON" : "Insure (8%)",
)
: null,
),
);
}
export function renderDiagPanel(ctx: MissionConfigContext): void {
const {
agency,
contract,
fp,
ascentCanvas,
telemetryDiagCanvas,
orbitCanvas,
diagTabsEl,
diagPanelEl,
rootCauseBoxEl,
gmatStatsBoxEl,
} = ctx;
const diagTier = getUnlockedDiagnosticTier(
agency?.unlockedTechs,
agency?.difficulty,
);
clear(diagTabsEl);
const tabs: Array<{
id: MissionConfigContext["diagTab"];
label: string;
reqTier: number;
}> = [
{ id: "ascent", label: "Ascent Profile (Tier 1)", reqTier: 1 },
{
id: "telemetry",
label: `Telemetry & Root-Cause (Tier 2${diagTier < 2 ? " LOCKED" : ""})`,
reqTier: 2,
},
{
id: "gmat",
label: `GMAT Orbit & Perturbations (Tier 3${diagTier < 3 ? " LOCKED" : ""})`,
reqTier: 3,
},
];
for (const tb of tabs) {
diagTabsEl.appendChild(
h(
"button",
{
class: `btn xs ${ctx.diagTab === tb.id ? "selected" : "ghost"}`,
onClick: () => {
ctx.diagTab = tb.id;
if (
tb.id === "gmat" &&
diagTier >= 3 &&
!ctx.cachedGmatTraj &&
!ctx.gmatLoading
) {
ctx.gmatLoading = true;
void api
.post<TrajectoryResult>("/api/trajectory", {
target: contract?.target ?? "leo",
altKm: fp.targetApoapsisKm,
incDeg: fp.targetInclinationDeg,
})
.then((tr) => {
ctx.cachedGmatTraj = tr;
})
.catch(() => {})
.finally(() => {
ctx.gmatLoading = false;
renderDiagPanel(ctx);
});
}
renderDiagPanel(ctx);
},
},
tb.label,
),
);
}
clear(diagPanelEl);
if (ctx.diagTab === "ascent") {
diagPanelEl.append(
h("h3", { class: "dim" }, "Ascent Guidance & Max-Q Envelope Preview"),
ascentCanvas,
h("h3", { class: "dim" }, "Orbital Injection Geometry Preview"),
orbitCanvas,
);
if (ctx.latestSimResult) drawAscentChart(ascentCanvas, ctx.latestSimResult);
drawOrbitChart({
orbitCanvas,
gmatStatsBoxEl,
contract,
fp,
gmatLoading: ctx.gmatLoading,
trajInput: ctx.cachedGmatTraj,
});
} else if (ctx.diagTab === "telemetry") {
if (diagTier < 2) {
diagPanelEl.appendChild(
h(
"div",
{
class: "panel",
style: { padding: "20px", borderColor: "var(--amber)" },
},
h("h3", {}, "Tier-2 Pre-Flight & Telemetry Suite Locked"),
h(
"p",
{ class: "dim", style: { marginTop: "6px", lineHeight: "1.5" } },
'Unlock "Avionics & Flight Telemetry Suite" ($4.5M) in the Dashboard R&D Tech Lab to inspect multi-channel Q / G-load / CPU load / radiation curves and failure root-cause analysis.',
),
h(
"button",
{
class: "btn sm primary",
style: { marginTop: "10px" },
onClick: () => navigate("dashboard"),
},
"Go to Dashboard Tech Lab",
),
),
);
} else {
diagPanelEl.append(telemetryDiagCanvas, rootCauseBoxEl);
if (ctx.latestSimResult)
drawMultiTelemetryChart(
telemetryDiagCanvas,
rootCauseBoxEl,
ctx.latestSimResult,
);
}
} else {
if (diagTier < 3) {
diagPanelEl.appendChild(
h(
"div",
{
class: "panel",
style: { padding: "20px", borderColor: "var(--amber)" },
},
h("h3", {}, "Tier-3 GMAT Orbital Diagnostics Locked"),
h(
"p",
{ class: "dim", style: { marginTop: "6px", lineHeight: "1.5" } },
'Unlock "GMAT Orbital Diagnostics Suite" ($12.0M) in the Dashboard R&D Tech Lab for GMAT RungeKutta89 perturbation drift, Van Allen radiation flux mapping, and orbital eclipse prediction.',
),
h(
"button",
{
class: "btn sm primary",
style: { marginTop: "10px" },
onClick: () => navigate("dashboard"),
},
"Go to Dashboard Tech Lab",
),
),
);
} else {
diagPanelEl.append(orbitCanvas, gmatStatsBoxEl);
drawOrbitChart({
orbitCanvas,
gmatStatsBoxEl,
contract,
fp,
gmatLoading: ctx.gmatLoading,
trajInput: ctx.cachedGmatTraj,
});
}
}
}
export function renderForecastBoxes(
ctx: MissionConfigContext,
sim: SimResult,
): void {
const { contract, simSummaryEl, windowBoxEl, hazardsBoxEl } = ctx;
clear(simSummaryEl);
const items: Array<{
k: string;
tip?: GlossaryKey;
v: string;
cls?: string;
}> = [
{
k: "Predicted Outcome",
v: sim.success
? sim.orbitGrade === "partial"
? "PARTIAL ORBIT"
: "ORBIT OK"
: (sim.failureReason ?? "FAILED"),
cls: sim.success
? sim.orbitGrade === "partial"
? "warn"
: "good"
: "bad",
},
{
k: "Burnout Ap × Pe",
tip: "apoapsis",
v: `${fmtNum(sim.apoapsis / 1000)} × ${fmtNum(sim.periapsis / 1000)} km`,
},
{
k: "Peak Max-Q / G",
tip: "max_q",
v: `${(sim.maxQ / 1000).toFixed(1)} kPa / ${sim.peakGLoad.toFixed(1)} G`,
},
{
k: "Peak CPU / Reserve Δv",
tip: "cpu_load",
v: `${Math.round(sim.peakCpuLoadPct ?? 0)}% CPU / ${fmtNum(sim.dvRemaining)} m/s`,
cls:
(sim.peakCpuLoadPct ?? 0) > 125
? "bad"
: sim.dvRemaining > 150
? "good"
: "warn",
},
];
for (const it of items) {
simSummaryEl.appendChild(
h(
"div",
{ class: "stat-box" },
h("div", { class: "k" }, it.tip ? term(it.k, it.tip) : it.k),
h("div", { class: `v ${it.cls ?? ""}` }, it.v),
),
);
}
const activeHazards = state.world?.activeHazards ?? [];
const upcomingHazards = state.world?.upcomingHazards ?? [];
clear(hazardsBoxEl);
hazardsBoxEl.append(
h(
"div",
{ class: "spread", style: { marginBottom: "4px" } },
h(
"span",
{ class: "mono", style: { fontSize: "11px", fontWeight: "700" } },
term("PRE-LAUNCH HAZARD FORECAST", "space_weather"),
),
h(
"span",
{ class: `badge ${activeHazards.length ? "warn" : "ok"}` },
activeHazards.length ? `${activeHazards.length} ACTIVE` : "CLEAR",
),
),
...(activeHazards.length
? activeHazards.map((hz) =>
h(
"div",
{ class: "rule-item waived", style: { marginTop: "4px" } },
h(
"div",
{ class: "spread" },
h("strong", { class: "amber" }, hz.title),
h(
"span",
{ class: "badge warn" },
`${hz.altMinKm}–${hz.altMaxKm} km`,
),
),
h(
"div",
{ class: "dim", style: { fontSize: "10px" } },
hz.countermeasureHint,
),
),
)
: [
h(
"div",
{ class: "dim mono", style: { fontSize: "10px" } },
"No severe atmospheric or radiation anomalies active.",
),
]),
...(upcomingHazards.length
? [
h(
"div",
{
class: "faint mono",
style: { fontSize: "10px", marginTop: "4px" },
},
`Next: ${upcomingHazards.map((u) => u.title).join(", ")}`,
),
]
: []),
);
const win = computeLaunchWindow(
contract?.target ?? "leo",
state.world?.simTime ?? 0,
contract?.launchWindowPeriodSec ?? 7200,
);
clear(windowBoxEl);
windowBoxEl.append(
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "mono", style: { fontSize: "11px", fontWeight: "700" } },
"SYNODIC LAUNCH WINDOW",
),
h(
"span",
{
class: `badge ${win.quality === "OPTIMAL" ? "ok" : win.quality === "FAIR" ? "info" : "warn"}`,
},
win.quality,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Phase Penalty"),
h(
"span",
{ class: `v ${win.penaltyDv > 0 ? "amber" : "green"}` },
`+${win.penaltyDv} m/s`,
),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Next Optimal Peak"),
h(
"span",
{ class: "v" },
win.optimalInSec === 0 ? "OPEN NOW" : fmtDuration(win.optimalInSec),
),
),
);
renderPrelaunchBox(ctx, sim);
}

View file

@ -0,0 +1,257 @@
// Sponsor and starter contract selection with live 3D GLTF payload preview.
// Self explanatory
import { api } from "../api.js";
import { navigate } from "../router.js";
import { refreshMe, refreshWorld } from "../session.js";
import { state } from "../state.js";
import { encodeModelPath, loadFittedModel } from "../three/modelLoader.js";
import { createView } from "../three/sceneManager.js";
import {
getDifficultyProfile,
normalizeDifficulty,
} from "../../shared/physics.js";
import type { AgencyState, ContractOffer } from "../../shared/types.js";
import { clear, fmtMoney, fmtNum, h, term, toast } from "../ui.js";
export function renderOnboarding(root: HTMLElement): () => void {
const sponsors = state.sponsors;
const isSandbox = normalizeDifficulty(state.agency?.difficulty) === "sandbox";
const starterMissions = isSandbox
? state.missions
: state.missions.filter((m) => m.tier <= 1);
let selectedSponsorId = sponsors[0]?.id ?? "nasa";
let selectedMissionId = starterMissions[0]?.id ?? state.missions[0]?.id ?? "";
const previewBox = h("div", { class: "onboard-preview-box" });
const view = createView(previewBox, { fov: 42 });
view.camera.position.set(16, 10, 18);
view.controls.target.set(0, 0, 0);
view.controls.autoRotate = true;
view.controls.autoRotateSpeed = 1.1;
let currentPreviewModel: any = null;
const previewCaption = h(
"div",
{ class: "mono dim", style: { fontSize: "11px" } },
"",
);
async function showPayloadPreview(missionId: string) {
const mission = state.missions.find((m) => m.id === missionId);
const payloadPart =
state.parts.find((p) => p.id === mission?.recommendedPayloadId) ??
state.parts.find((p) => p.kind === "payload");
if (currentPreviewModel) {
view.scene.remove(currentPreviewModel);
currentPreviewModel = null;
}
if (payloadPart?.modelFile) {
previewCaption.textContent = `Loading NASA 3D payload: ${payloadPart.name}...`;
try {
const mesh = await loadFittedModel(
encodeModelPath(payloadPart.modelFile),
{
height: 9,
radius: 5.5,
anchorBottom: false,
},
);
view.scene.add(mesh);
currentPreviewModel = mesh;
previewCaption.textContent = `${payloadPart.name} • ${fmtNum(mission?.payloadMass ?? payloadPart.dryMass)} kg`;
} catch (err) {
previewCaption.textContent = `GLB preview unavailable (${(err as Error).message})`;
}
} else {
previewCaption.textContent = mission
? `${mission.targetName} Payload`
: "Payload Preview";
}
}
const sponsorCardsEl = h("div", {
class: "card-grid",
style: { gridTemplateColumns: "repeat(auto-fill, minmax(230px, 1fr))" },
});
const missionCardsEl = h("div", {
class: "card-grid",
style: { gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))" },
});
const summaryBox = h("div", { class: "panel", style: { padding: "14px" } });
const confirmBtn = h(
"button",
{ class: "btn primary", style: { width: "100%" } },
"Sign Contract & Open Hangar",
);
function renderSelections() {
clear(sponsorCardsEl);
for (const sp of sponsors) {
const card = h(
"div",
{
class: `card ${sp.id === selectedSponsorId ? "selected" : ""}`,
onClick: () => {
selectedSponsorId = sp.id;
renderSelections();
},
},
h(
"div",
{ class: "spread" },
h("h3", {}, sp.name),
h("span", { class: "badge info" }, sp.flag),
),
h("p", { class: "sub" }, sp.description),
h(
"div",
{ class: "meta" },
h("span", {}, `Budget ${Math.round(sp.budgetMult * 100)}%`),
h("span", {}, `Waiver ${Math.round(sp.waiverCostMult * 100)}%`),
h("span", {}, `Rep ${Math.round(sp.reputationMult * 100)}%`),
),
);
sponsorCardsEl.appendChild(card);
}
clear(missionCardsEl);
for (const m of starterMissions) {
const card = h(
"div",
{
class: `card ${m.id === selectedMissionId ? "selected" : ""}`,
onClick: () => {
selectedMissionId = m.id;
renderSelections();
void showPayloadPreview(m.id);
},
},
h(
"div",
{ class: "spread" },
h("h3", {}, m.name),
h("span", { class: "badge ok" }, m.targetName),
),
h("p", { class: "sub" }, m.description),
h(
"div",
{ class: "meta" },
h("span", {}, `Budget ${fmtMoney(m.budget)}`),
h("span", {}, term(`Δv ${fmtNum(m.requiredDv)} m/s`, "req_dv")),
h("span", {}, `Payload ${fmtNum(m.payloadMass)} kg`),
),
);
missionCardsEl.appendChild(card);
}
const sp = sponsors.find((s) => s.id === selectedSponsorId);
const ms = state.missions.find((m) => m.id === selectedMissionId);
const profile = getDifficultyProfile(state.agency?.difficulty);
const seedBudget =
sp && ms
? Math.round(profile.startingFunds * sp.budgetMult + ms.budget * 0.35)
: profile.startingFunds;
clear(summaryBox);
summaryBox.appendChild(
h(
"div",
{ class: "col" },
h("h3", {}, "Program Grant Summary"),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Difficulty Tier", "difficulty")),
h("span", { class: "v info" }, profile.label),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Sponsor"),
h("span", { class: "v accent" }, sp?.name ?? "-"),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Initial Contract"),
h("span", { class: "v" }, ms?.name ?? "-"),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Seed + 35% Advance"),
h("span", { class: "v green" }, fmtMoney(seedBudget)),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Target Orbit", "apoapsis")),
h(
"span",
{ class: "v" },
`${ms?.targetOrbit?.periapsisKm ?? 200}×${ms?.targetOrbit?.apoapsisKm ?? 220} km`,
),
),
),
);
}
confirmBtn.addEventListener("click", async () => {
if (!selectedSponsorId || !selectedMissionId) {
toast("Select both a sponsor and an inaugural mission.", "err");
return;
}
confirmBtn.disabled = true;
try {
const res = await api.post<{
agency: AgencyState;
contract: ContractOffer;
}>("/api/agency/onboard", {
sponsorId: selectedSponsorId,
missionId: selectedMissionId,
});
state.agency = res.agency;
await refreshMe();
await refreshWorld();
toast(
`Funded by ${selectedSponsorId.toUpperCase()} — proceed to build your first launch vehicle.`,
"ok",
);
navigate("dashboard");
} catch (err) {
toast((err as Error).message, "err");
confirmBtn.disabled = false;
}
});
renderSelections();
if (selectedMissionId) void showPayloadPreview(selectedMissionId);
const leftCol = h(
"div",
{ class: "onboard-scroll col" },
h(
"div",
{ class: "spread" },
h(
"div",
{ class: "col", style: { gap: "4px" } },
h("h2", {}, "Inaugural Funding & Mission Charter"),
h("p", { class: "dim" }, `Agency: ${state.agency?.name ?? "Unknown"}`),
),
h("span", { class: "badge info" }, "Step 1 of 2"),
),
h("h3", { class: "accent" }, "1. Select Space Sponsor"),
sponsorCardsEl,
h(
"h3",
{ class: "accent", style: { marginTop: "8px" } },
"2. Select Inaugural Tier-1 Contract",
),
missionCardsEl,
);
const rightCol = h(
"div",
{ class: "onboard-preview" },
h("h3", {}, "Recommended Payload Hardware (3D)"),
previewBox,
previewCaption,
summaryBox,
confirmBtn,
);
root.appendChild(
h("div", { class: "screen onboard-layout" }, leftCol, rightCol),
);
return () => {
view.dispose();
};
}

View file

@ -0,0 +1,422 @@
// 3D Rocket Builder and configuration screen
import * as THREE from "three";
import { api } from "../api.js";
import { navigate } from "../router.js";
import { currentContract, state } from "../state.js";
import { disposeRocketMesh } from "../three/rocketMesh.js";
import { createView } from "../three/sceneManager.js";
import {
convertStagesToProParts,
createDefaultSpacecraftConfig,
createStarterDesign,
normalizeDesign,
} from "../../shared/physics.js";
import type { RocketDesign } from "../../shared/types.js";
import { clear, h, term, toast } from "../ui.js";
import { openBlueprintsModal } from "./builder/blueprintsModal.js";
import { curAgency, type BuilderContext } from "./builder/context.js";
import { renderDiagnosticsSection } from "./builder/diagnosticsBar.js";
import {
evaluateNow,
renderSummaryAndCoopBars,
renderTierAndTabs,
} from "./builder/engineeringBar.js";
import {
openHistoryModal,
recordHistory,
redoEdit,
undoEdit,
updateHistoryButtons,
} from "./builder/history.js";
import { renderPayloadTab } from "./builder/payloadTab.js";
import { renderProTab } from "./builder/proTab.js";
import { renderStagesTab } from "./builder/stagesTab.js";
import {
renderComplianceTab,
renderContractValueTab,
renderFooter,
} from "./builder/valueAndComplianceTabs.js";
import {
attachProDragHandlers,
renderHudOverlay,
scheduleRebuild3D,
} from "./builder/viewportAndDrag.js";
export function renderRocketBuilder(root: HTMLElement): () => void {
const agency = state.agency;
if (!agency) {
navigate("auth");
return () => {};
}
const contract = currentContract();
const sponsor = state.sponsors.find((s) => s.id === agency.sponsorId);
const initialDesign: RocketDesign = normalizeDesign(
agency.rocketDesign
? structuredClone(agency.rocketDesign)
: createStarterDesign(contract, agency.difficulty),
state.parts,
state.materials,
);
if (!agency.rocketDesign && contract?.recommendedPayloadId) {
initialDesign.payloadPartId = contract.recommendedPayloadId;
}
if (!initialDesign.spacecraftConfig) {
initialDesign.spacecraftConfig = createDefaultSpacecraftConfig(contract);
}
const viewportEl = h("div", { class: "builder-viewport" });
const sidebarEl = h("div", { class: "builder-sidebar" });
const view = createView(viewportEl, { fov: 42, far: 8000 });
view.addStars(1800, 3500);
view.camera.position.set(18, 16, 26);
view.controls.target.set(0, 10, 0);
const dragPlane = new THREE.Mesh(
new THREE.BoxGeometry(1000, 1000, 0.05),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide,
}),
);
dragPlane.visible = false;
view.scene.add(dragPlane);
const undoBtn = h(
"button",
{
class: "btn xs ghost",
disabled: true,
title: "Undo last edit (Ctrl+Z)",
onClick: () => undoEdit(ctx),
},
"↶ Undo",
) as HTMLButtonElement;
const redoBtn = h(
"button",
{
class: "btn xs ghost",
disabled: true,
title: "Redo edit (Ctrl+Y / Ctrl+Shift+Z)",
onClick: () => redoEdit(ctx),
},
"↷ Redo",
) as HTMLButtonElement;
const historyBtn = h(
"button",
{
class: "btn xs ghost",
title: "Inspect & jump across edit history",
onClick: () => openHistoryModal(ctx),
},
"History (1/1)",
) as HTMLButtonElement;
const blueprintsBtn = h(
"button",
{
class: "btn xs selected",
title: "Save, load, share SGYW1 codes, or import JSON blueprints",
onClick: () => void openBlueprintsModal(ctx),
},
"Blueprints & Share",
);
const cutawayBtn = h(
"button",
{
class: "btn xs selected",
onClick: () => {
ctx.fairingCutaway = !ctx.fairingCutaway;
cutawayBtn.textContent = ctx.fairingCutaway
? "Fairing: X-Ray Cutaway"
: "Fairing: Solid Shell";
cutawayBtn.classList.toggle("selected", ctx.fairingCutaway);
refreshEngineering(false, true);
},
},
"Fairing: X-Ray Cutaway",
);
const cgCpBtn = h(
"button",
{
class: "btn xs ghost",
onClick: () => {
ctx.showCenters = !ctx.showCenters;
cgCpBtn.textContent = ctx.showCenters ? "CG / CP: ON" : "CG / CP: OFF";
cgCpBtn.classList.toggle("selected", ctx.showCenters);
cgCpBtn.classList.toggle("ghost", !ctx.showCenters);
refreshEngineering(false, true);
},
},
"CG / CP: OFF",
) as HTMLButtonElement;
const proDragHint = h(
"span",
{
class: "badge info",
style: {
display: initialDesign.designTier === "pro" ? "inline-flex" : "none",
fontSize: "10px",
},
},
"PRO 3D DRAG: Click/drag parts (Right-drag orbit)",
);
const topLeftOverlay = h(
"div",
{ class: "dash-header" },
h(
"div",
{ class: "row", style: { flexWrap: "wrap", gap: "6px" } },
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("dashboard") },
"← Dashboard",
),
h("h1", {}, "Rocket Builder"),
h(
"span",
{ class: "badge info" },
contract ? contract.targetName : "Free Design",
),
proDragHint,
),
h(
"div",
{ class: "row", style: { flexWrap: "wrap", gap: "6px" } },
undoBtn,
redoBtn,
historyBtn,
blueprintsBtn,
cgCpBtn,
term("", "cg_cp"),
cutawayBtn,
),
);
viewportEl.appendChild(topLeftOverlay);
const hudStatsRow = h("div", { class: "builder-hud-bottom" });
viewportEl.appendChild(hudStatsRow);
const tierBar = h("div", { class: "builder-tier-bar" });
const summaryBar = h("div", { class: "builder-summary-bar" });
const coopBar = h("div", { class: "builder-coop-bar" });
const tabsBar = h("div", { class: "builder-tabs" });
const bodyEl = h("div", { class: "builder-body" });
const footerBar = h("div", {
class: "row",
style: {
padding: "10px 12px",
borderTop: "1px solid var(--border)",
background: "var(--bg-deep)",
},
});
sidebarEl.append(tierBar, summaryBar, coopBar, tabsBar, bodyEl, footerBar);
const ctx: BuilderContext = {
agency,
contract,
sponsor,
design: initialDesign,
history: [
{
snapshot: structuredClone(initialDesign),
label: "Initial design",
at: Date.now(),
},
],
historyIndex: 0,
lastRecordedJson: JSON.stringify(initialDesign),
suppressHistory: false,
activeTab: "stages",
activeStageIdx: 0,
fairingCutaway: true,
showCenters: false,
selectedProUid: initialDesign.proParts?.[0]?.uid ?? null,
priceMultipliers: {},
viewportEl,
sidebarEl,
bodyEl,
tierBar,
summaryBar,
coopBar,
tabsBar,
footerBar,
hudStatsRow,
undoBtn,
redoBtn,
historyBtn,
proDragHint,
cgCpBtn,
view,
dragPlane,
currentMesh: null,
buildToken: 0,
rebuildTimer: null,
isDragging3D: false,
dragState: null,
latestValidation: null,
latestAssembly: null,
latestReliability: null,
latestValueEstimate: null,
latestCoach: [],
refreshEngineering: (refitCamera, immediate) =>
refreshEngineering(refitCamera, immediate),
renderSidebarBody: () => renderSidebarBody(),
renderAll: () => renderAll(),
renderTierAndTabs: () => renderTierAndTabs(ctx),
renderSummaryAndCoopBars: () => renderSummaryAndCoopBars(ctx),
scheduleRebuild3D: (asm, refitCamera, immediate) =>
scheduleRebuild3D(ctx, asm, refitCamera, immediate),
renderHudOverlay: () => renderHudOverlay(ctx),
};
void api
.get<Array<{ id: string; price: number; baseCost: number }>>(
"/api/prices",
false,
)
.then((rows) => {
for (const r of rows) {
if (r.baseCost > 0) ctx.priceMultipliers[r.id] = r.price / r.baseCost;
}
refreshEngineering(false, true);
})
.catch(() => {});
function renderSidebarBody(): void {
clear(ctx.bodyEl);
if (!ctx.latestAssembly || !ctx.latestValidation) return;
const nameInput = h("input", {
class: "input",
value: ctx.design.name,
onInput: () => {
ctx.design.name = nameInput.value.trim() || "Custom Launcher";
},
onChange: () => {
recordHistory(ctx, "Rename vehicle", "rename");
},
}) as HTMLInputElement;
ctx.bodyEl.appendChild(
h(
"div",
{ class: "row", style: { alignItems: "flex-end" } },
h("label", { class: "field grow" }, "Vehicle Designation", nameInput),
h(
"button",
{
class: "btn xs ghost",
title: "Reset to contract-appropriate starter launch vehicle",
onClick: () => {
const keepPro = ctx.design.designTier === "pro";
ctx.design = normalizeDesign(
createStarterDesign(contract, curAgency(ctx).difficulty),
state.parts,
state.materials,
);
if (contract?.recommendedPayloadId)
ctx.design.payloadPartId = contract.recommendedPayloadId;
if (keepPro) {
ctx.design.designTier = "pro";
ctx.design.proParts = convertStagesToProParts(
ctx.design,
state.parts,
);
ctx.selectedProUid = ctx.design.proParts[0]?.uid ?? null;
}
ctx.activeStageIdx = 0;
recordHistory(ctx, "Load starter reference");
refreshEngineering(true, true);
renderAll();
toast(
"Loaded reference architecture for current contract.",
"info",
);
},
},
"Load Reference",
),
),
);
renderDiagnosticsSection(ctx);
if (ctx.activeTab === "stages") {
if (ctx.design.designTier === "pro") renderProTab(ctx);
else renderStagesTab(ctx);
} else if (ctx.activeTab === "payload") {
renderPayloadTab(ctx);
} else if (ctx.activeTab === "value") {
renderContractValueTab(ctx);
} else {
renderComplianceTab(ctx);
}
}
function refreshEngineering(refitCamera = false, immediate = true): void {
if (!ctx.suppressHistory && !ctx.isDragging3D) {
recordHistory(ctx, "Adjust vehicle parameters", "auto-edit");
}
evaluateNow(ctx);
renderHudOverlay(ctx);
renderTierAndTabs(ctx);
renderSummaryAndCoopBars(ctx);
if (ctx.latestAssembly)
scheduleRebuild3D(ctx, ctx.latestAssembly, refitCamera, immediate);
}
function renderAll(): void {
updateHistoryButtons(ctx);
refreshEngineering(false, true);
renderSidebarBody();
renderFooter(ctx);
}
const detachDrag = attachProDragHandlers(ctx);
const onAgencySync = (ev: Event) => {
const detail = (ev as CustomEvent<Record<string, any>>).detail ?? {};
const myAccount = state.account?.name;
if (
detail.rocketDesign &&
detail.sender &&
detail.sender !== myAccount &&
!ctx.isDragging3D
) {
ctx.design = normalizeDesign(
structuredClone(detail.rocketDesign),
state.parts,
state.materials,
);
recordHistory(ctx, `Sync update from ${detail.sender}`);
renderAll();
toast(`Synced rocket update from ${detail.sender}`, "info");
} else {
renderSummaryAndCoopBars(ctx);
}
};
const onKeyDown = (ev: KeyboardEvent) => {
const targetTag = (ev.target as HTMLElement | null)?.tagName;
if (
targetTag === "INPUT" ||
targetTag === "TEXTAREA" ||
targetTag === "SELECT"
)
return;
if ((ev.ctrlKey || ev.metaKey) && !ev.altKey) {
const k = ev.key.toLowerCase();
if (k === "z") {
ev.preventDefault();
if (ev.shiftKey) redoEdit(ctx);
else undoEdit(ctx);
} else if (k === "y") {
ev.preventDefault();
redoEdit(ctx);
}
}
};
window.addEventListener("sgywftp:agency-sync", onAgencySync);
window.addEventListener("keydown", onKeyDown);
renderAll();
root.appendChild(
h("div", { class: "screen builder-root" }, viewportEl, sidebarEl),
);
return () => {
ctx.buildToken++;
if (ctx.rebuildTimer) clearTimeout(ctx.rebuildTimer);
window.removeEventListener("sgywftp:agency-sync", onAgencySync);
window.removeEventListener("keydown", onKeyDown);
detachDrag();
if (ctx.currentMesh) {
ctx.view.scene.remove(ctx.currentMesh.group);
disposeRocketMesh(ctx.currentMesh);
ctx.currentMesh = null;
}
ctx.view.dispose();
};
}

View file

@ -0,0 +1,336 @@
// Renders live 3D solar system explorer, and active global flights table.
import * as THREE from "three";
import { navigate } from "../router.js";
import { refreshWorld } from "../session.js";
import { state } from "../state.js";
import { encodeModelPath, loadFittedModel } from "../three/modelLoader.js";
import { createView } from "../three/sceneManager.js";
import {
buildSolarSystem,
compressedPosition,
type SolarSystemHandle,
} from "../three/solarSystem.js";
import { NASA_ASSETS, PLANETS } from "../../shared/ephemeris.js";
import { clear, fmtDuration, h, term } from "../ui.js";
export function renderWorldMap(root: HTMLElement): () => void {
const viewportEl = h("div", { class: "map-viewport" });
const sidebarEl = h("div", { class: "map-sidebar" });
let simTime = state.world?.simTime ?? Date.now() / 1000;
let focusBodyId: string | null = "earth";
let selectedAssetId: string | null = null;
let speedMult = 1;
let solar: SolarSystemHandle | null = null;
const view = createView(viewportEl, {
fov: 46,
far: 35000,
onFrame: (dt) => {
if (!solar) return;
simTime += dt * 30 * speedMult;
solar.update(simTime);
if (focusBodyId && !selectedAssetId) {
const mesh = solar.planetMeshes.get(focusBodyId);
if (mesh) view.controls.target.lerp(mesh.position, 0.08);
} else if (selectedAssetId) {
const mesh = solar.assetMeshes.get(selectedAssetId);
if (mesh) view.controls.target.lerp(mesh.position, 0.1);
}
},
});
view.addStars(4000, 14000);
view.camera.position.set(220, 260, 420);
const solarSystem = buildSolarSystem(view.scene, { showAssets: true });
solar = solarSystem;
view.scene.add(solarSystem.group);
viewportEl.appendChild(
h(
"div",
{ class: "dash-header" },
h(
"div",
{ class: "row" },
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("dashboard") },
"← Dashboard",
),
h("h1", {}, "Solar System & NASA Asset Tracker"),
h(
"span",
{ class: "badge info" },
`WX: ${(state.world?.weather ?? "nominal").toUpperCase()}`,
),
),
h(
"div",
{ class: "row" },
h(
"button",
{
class: "btn xs",
onClick: () => {
speedMult = 1;
},
},
"30× Sim",
),
h(
"button",
{
class: "btn xs",
onClick: () => {
speedMult = 2500;
},
},
"Orbit Fast",
),
h(
"button",
{
class: "btn xs",
onClick: () => {
focusBodyId = "sun";
selectedAssetId = null;
view.controls.target.set(0, 0, 0);
},
},
"Heliocentric",
),
),
),
);
const assetPreviewBox = h("div", {
class: "onboard-preview-box",
style: { height: "180px", flexShrink: "0" },
});
const assetView = createView(assetPreviewBox, { fov: 40 });
assetView.camera.position.set(12, 8, 14);
assetView.controls.autoRotate = true;
assetView.controls.autoRotateSpeed = 1.2;
let assetModel: THREE.Group | null = null;
const inspectorDetails = h("div", { class: "col", style: { gap: "6px" } });
async function inspectSelection(kind: "body" | "asset", id: string) {
clear(inspectorDetails);
if (assetModel) {
assetView.scene.remove(assetModel);
assetModel = null;
}
if (kind === "body") {
focusBodyId = id;
selectedAssetId = null;
const body = PLANETS.find((p) => p.id === id);
if (body) {
inspectorDetails.append(
h(
"div",
{ class: "spread" },
h("strong", { class: "mono accent" }, body.name),
h("span", { class: "badge info" }, "CELESTIAL BODY"),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Mean Radius"),
h("span", { class: "v" }, `${body.radiusKm.toLocaleString()} km`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Inclination", "inclination")),
h("span", { class: "v" }, `${body.incDeg}°`),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, term("Eccentricity", "apoapsis")),
h("span", { class: "v" }, `${body.ecc}`),
),
);
if (id === "asteroid") {
try {
assetModel = await loadFittedModel(
encodeModelPath("nasa_3d_glb/1999 RQ36 asteroid.glb"),
{ height: 7 },
);
assetView.scene.add(assetModel);
} catch {}
}
}
const pos = compressedPosition(id, simTime);
view.camera.position.set(pos.x + 65, pos.y + 42, pos.z + 85);
} else {
selectedAssetId = id;
focusBodyId = null;
const asset = NASA_ASSETS.find((a) => a.id === id);
if (asset) {
inspectorDetails.append(
h(
"div",
{ class: "spread" },
h("strong", { class: "mono accent" }, asset.name),
h("span", { class: "badge ok" }, asset.category),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Primary Body"),
h("span", { class: "v" }, asset.parentBody.toUpperCase()),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Orbital Period"),
h("span", { class: "v" }, fmtDuration(asset.periodSec)),
),
h(
"div",
{ class: "stat-row" },
h("span", { class: "k" }, "Inclination"),
h("span", { class: "v" }, `${asset.incDeg}°`),
),
);
try {
assetModel = await loadFittedModel(encodeModelPath(asset.modelFile), {
height: 7.5,
radius: 5,
});
assetView.scene.add(assetModel);
} catch (err) {
inspectorDetails.appendChild(
h(
"span",
{ class: "dim mono", style: { fontSize: "10px" } },
(err as Error).message,
),
);
}
}
const m = solarSystem.assetMeshes.get(id);
if (m)
view.camera.position.set(
m.position.x + 28,
m.position.y + 18,
m.position.z + 36,
);
}
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
view.renderer.domElement.addEventListener("click", (ev) => {
const rect = view.renderer.domElement.getBoundingClientRect();
pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, view.camera);
const targets = [
...solarSystem.assetMeshes.values(),
...solarSystem.planetMeshes.values(),
];
const hits = raycaster.intersectObjects(targets, false);
if (hits.length > 0) {
const ud = hits[0].object.userData;
if (ud.kind && ud.id) void inspectSelection(ud.kind, ud.id);
}
});
const flightsSection = h("div", { class: "col", style: { gap: "6px" } });
function renderFlights() {
clear(flightsSection);
const flights = state.world?.activeFlights ?? [];
if (!flights.length) {
flightsSection.appendChild(
h(
"span",
{ class: "dim mono", style: { fontSize: "11px" } },
"No active missions in transit.",
),
);
return;
}
for (const f of flights) {
flightsSection.appendChild(
h(
"div",
{
class: "row spread",
style: {
padding: "5px 8px",
background: "var(--bg-deep)",
border: "1px solid var(--border)",
},
},
h(
"span",
{ class: "mono", style: { fontSize: "11px" } },
`${f.agencyName}${f.aiType === "ml" ? " [ML-AI]" : f.isAI ? " [AI]" : ""} → ${f.target.toUpperCase()}`,
),
h(
"button",
{
class: "btn xs primary",
onClick: () => navigate("launch", { spectateId: f.id }),
},
"Spectate",
),
),
);
}
}
sidebarEl.append(
h("h3", {}, "Selected Target Inspector"),
assetPreviewBox,
inspectorDetails,
h("h3", {}, "Active Agency Missions"),
flightsSection,
h("h3", {}, "Celestial Bodies"),
h(
"div",
{ class: "col", style: { gap: "2px" } },
...PLANETS.map((p) =>
h(
"div",
{
class: "legend-item",
onClick: () => void inspectSelection("body", p.id),
},
h("span", {
class: "legend-dot",
style: { background: `#${p.color.toString(16).padStart(6, "0")}` },
}),
h("span", {}, p.name),
),
),
),
h("h3", {}, `Active NASA Probes & Stations (${NASA_ASSETS.length})`),
h(
"div",
{ class: "col", style: { gap: "2px" } },
...NASA_ASSETS.map((a) =>
h(
"div",
{
class: "legend-item",
onClick: () => void inspectSelection("asset", a.id),
},
h("span", {
class: "legend-dot",
style: { background: "var(--brand-blue)" },
}),
h("span", {}, `${a.name} (${a.parentBody.toUpperCase()})`),
),
),
),
);
renderFlights();
void inspectSelection("asset", "iss");
const timer = window.setInterval(async () => {
await refreshWorld();
renderFlights();
}, 5000);
root.appendChild(
h("div", { class: "screen map-root" }, viewportEl, sidebarEl),
);
return () => {
window.clearInterval(timer);
assetView.dispose();
view.dispose();
};
}

212
src/client/session.ts Normal file
View file

@ -0,0 +1,212 @@
// Handles server catalog population (Lesbian geckos), agency/world polling, and SSE dispatch.
import { api, connectEvents, getSettings, getToken, setToken } from "./api.js";
import {
applyThemeFromState,
getCurrentScreen,
type ModelIndexEntry,
type ServerInfo,
state,
} from "./state.js";
import { pushNotification, toast } from "./ui.js";
import type {
AgencyState,
ContractOffer,
MaterialSpec,
MissionTemplate,
Part,
Sponsor,
WorldSnapshot,
} from "../shared/types.js";
let eventSource: EventSource | null = null;
let worldTimer: number | null = null;
export async function loadCatalogs(): Promise<void> {
const [info, parts, materials, missions, sponsors, models] =
await Promise.all([
api.get<ServerInfo>("/api/info", false),
api.get<Part[]>("/api/parts", false),
api.get<MaterialSpec[]>("/api/materials", false),
api.get<MissionTemplate[]>("/api/missions", false),
api.get<Sponsor[]>("/api/sponsors", false),
api.get<ModelIndexEntry[]>("/api/models", false),
]);
state.serverInfo = info;
state.parts = parts;
state.materials = materials;
state.missions = missions;
state.sponsors = sponsors;
state.models = models;
}
export async function refreshMe(): Promise<AgencyState | null> {
if (!getToken()) return null;
try {
const me = await api.get<{
account: { name: string };
agency: AgencyState;
}>("/api/me", true);
state.account = me.account;
state.agency = me.agency;
try {
state.contracts = await api.get<ContractOffer[]>("/api/contracts", true);
} catch {}
applyThemeFromState();
return me.agency;
} catch {
setToken(null);
state.account = null;
state.agency = null;
return null;
}
}
export async function refreshWorld(): Promise<WorldSnapshot | null> {
if (!getToken()) return null;
try {
state.world = await api.get<WorldSnapshot>("/api/world", true);
applyThemeFromState();
return state.world;
} catch {
return null;
}
}
function handleLiveEvent(ev: {
type: string;
data?: Record<string, any>;
}): void {
const d = ev.data ?? {};
const notify = getSettings().notifications;
const myName = state.agency?.name;
const isMine = Boolean(myName && d.agency === myName);
if (ev.type === "world.weather") {
if (state.world && d.weather) {
state.world.weather = d.weather;
applyThemeFromState();
}
pushNotification(
`Space Weather Update: ${String(d.weather ?? "nominal").toUpperCase()}`,
"info",
"world",
);
} else if (ev.type === "world.hazards") {
if (state.world) {
if (d.activeHazards) state.world.activeHazards = d.activeHazards;
if (d.upcomingHazards) state.world.upcomingHazards = d.upcomingHazards;
}
pushNotification("Environmental Hazard Forecast Updated", "warn", "world");
} else if (ev.type === "mission.launched") {
if (!isMine) {
pushNotification(
`${d.agency} launched a vehicle toward ${String(d.target ?? "").toUpperCase()}.`,
"info",
"world",
);
}
void refreshWorld();
} else if (ev.type === "mission.completed") {
const mUsd = ((Number(d.payout) || 0) / 1e6).toFixed(1);
const msg = `${d.agency} completed mission (+$${mUsd}M).`;
pushNotification(
msg,
isMine ? "ok" : "info",
isMine ? "mine" : "world",
!isMine,
);
if (notify && isMine) {
toast(msg, "ok", false);
}
void refreshWorld();
if (isMine) void refreshMe();
} else if (ev.type === "mission.failed") {
const msg = `${d.agency} mission FAILED: ${d.reason ?? "flight anomaly"}`;
pushNotification(
msg,
isMine ? "err" : "warn",
isMine ? "mine" : "world",
!isMine,
);
if (notify && isMine) {
toast(msg, "err", false);
}
void refreshWorld();
if (isMine) void refreshMe();
} else if (ev.type === "agency.bankrupt") {
const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy.`;
pushNotification(
msg,
isMine ? "err" : "warn",
isMine ? "mine" : "world",
!isMine,
);
if (notify && isMine) {
toast(msg, "err", false);
}
void refreshWorld();
if (isMine) void refreshMe();
} else if (ev.type === "agency.founded") {
pushNotification(
`New competitor entered market: ${d.agency} (${String(d.sponsorId ?? "").toUpperCase()}).`,
"info",
"world",
);
void refreshWorld();
} else if (ev.type === "agency.bailout") {
const msg = isMine
? `Restructuring grant received: +$${((Number(d.grant) || 0) / 1e6).toFixed(1)}M.`
: `${d.agency} received emergency sponsor bailout (+$${((Number(d.grant) || 0) / 1e6).toFixed(1)}M).`;
pushNotification(
msg,
isMine ? "ok" : "info",
isMine ? "mine" : "world",
!isMine,
);
if (isMine) {
if (notify) toast(msg, "ok", false);
void refreshMe();
}
} else if (ev.type === "agency.tech_unlocked") {
pushNotification(
`${d.agency} unlocked R&D: ${d.techName ?? d.techId}`,
"info",
isMine ? "mine" : "world",
);
} else if (ev.type === "contract.claimed" && !isMine) {
pushNotification(
`${d.agency} signed contract ${d.missionId}.`,
"info",
"world",
);
void refreshWorld();
} else if (ev.type === "agency.updated" && isMine) {
if (state.agency && d.rocketDesign) {
state.agency.rocketDesign = d.rocketDesign;
}
if (state.agency && d.teamStations) {
state.agency.teamStations = d.teamStations;
}
window.dispatchEvent(new CustomEvent("sgywftp:agency-sync", { detail: d }));
void refreshMe().then(() => {
window.dispatchEvent(
new CustomEvent("sgywftp:agency-sync", { detail: d }),
);
});
}
}
export function startEvents(): void {
if (eventSource) return;
eventSource = connectEvents(handleLiveEvent);
if (worldTimer === null) {
worldTimer = window.setInterval(() => {
if (
getToken() &&
getCurrentScreen() !== "mainMenu" &&
getCurrentScreen() !== "auth"
) {
void refreshWorld();
}
}, 6000);
}
}

79
src/client/sound.ts Normal file
View file

@ -0,0 +1,79 @@
// Synthesized Web Audio API click, alert, countdown beep, stage separation, and ignition burst audio cues.
// In other words, button go boop.
import { getSettings } from "./api.js";
let ctx: AudioContext | null = null;
function getCtx(): AudioContext | null {
if (!getSettings().sound) return null;
if (!ctx) {
const AC =
window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext })
.webkitAudioContext;
if (AC) ctx = new AC();
}
if (ctx?.state === "suspended") {
ctx.resume().catch(() => {});
}
return ctx;
}
export function playClick(): void {
const ac = getCtx();
if (!ac) return;
const osc = ac.createOscillator();
const gain = ac.createGain();
osc.type = "triangle";
osc.frequency.setValueAtTime(620, ac.currentTime);
osc.frequency.exponentialRampToValueAtTime(320, ac.currentTime + 0.045);
gain.gain.setValueAtTime(0.05, ac.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ac.currentTime + 0.05);
osc.connect(gain);
gain.connect(ac.destination);
osc.start();
osc.stop(ac.currentTime + 0.055);
}
export function playAlert(kind: "ok" | "warn" | "err" = "ok"): void {
const ac = getCtx();
if (!ac) return;
const osc = ac.createOscillator();
const gain = ac.createGain();
osc.type = kind === "err" ? "sawtooth" : "sine";
const freq = kind === "err" ? 220 : kind === "warn" ? 440 : 660;
osc.frequency.setValueAtTime(freq, ac.currentTime);
osc.frequency.setValueAtTime(
freq * (kind === "ok" ? 1.25 : 0.85),
ac.currentTime + 0.09,
);
gain.gain.setValueAtTime(0.06, ac.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ac.currentTime + 0.22);
osc.connect(gain);
gain.connect(ac.destination);
osc.start();
osc.stop(ac.currentTime + 0.24);
}
export function playIgnitionBurst(): void {
const ac = getCtx();
if (!ac) return;
const bufferSize = ac.sampleRate * 1.4;
const buffer = ac.createBuffer(1, bufferSize, ac.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (ac.sampleRate * 0.6));
}
const src = ac.createBufferSource();
src.buffer = buffer;
const filter = ac.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = 260;
const gain = ac.createGain();
gain.gain.setValueAtTime(0.18, ac.currentTime);
gain.gain.exponentialRampToValueAtTime(0.005, ac.currentTime + 1.35);
src.connect(filter);
filter.connect(gain);
gain.connect(ac.destination);
src.start();
}

110
src/client/state.ts Normal file
View file

@ -0,0 +1,110 @@
// Client application state, screen route/parameter interfaces, contract lookup, and theme sync.
import { syncSimulationTheme } from "./theme.js";
import type {
ActiveMission,
AgencyState,
ContractOffer,
MaterialSpec,
MissionSettlement,
MissionTemplate,
Part,
SimResult,
Sponsor,
WorldSnapshot,
} from "../shared/types.js";
export type ScreenName =
| "mainMenu"
| "auth"
| "onboarding"
| "dashboard"
| "builder"
| "config"
| "launch"
| "debrief"
| "contracts"
| "worldMap";
export interface ModelIndexEntry {
file: string;
name: string;
category: string;
}
export interface ServerInfo {
name: string;
serverPasswordRequired: boolean;
simSecondsPerRealSecond: number;
}
export interface AppState {
serverInfo: ServerInfo | null;
account: { name: string } | null;
agency: AgencyState | null;
parts: Part[];
materials: MaterialSpec[];
missions: MissionTemplate[];
contracts: ContractOffer[];
sponsors: Sponsor[];
models: ModelIndexEntry[];
world: WorldSnapshot | null;
}
export const state: AppState = {
serverInfo: null,
account: null,
agency: null,
parts: [],
materials: [],
missions: [],
contracts: [],
sponsors: [],
models: [],
world: null,
};
let activeScreen: ScreenName = "mainMenu";
export function getCurrentScreen(): ScreenName {
return activeScreen;
}
export function setCurrentScreen(screen: ScreenName): void {
activeScreen = screen;
}
export interface LaunchScreenParams {
testResult?: SimResult;
spectateId?: string;
}
export interface DebriefScreenParams {
mission?: ActiveMission;
settlement?: MissionSettlement;
testResult?: SimResult;
isSpectating?: boolean;
}
export function currentContract(): ContractOffer | MissionTemplate | null {
if (!state.agency) return null;
if (state.agency.activeContract) return state.agency.activeContract;
if (state.agency.missionId) {
return (
state.contracts.find((c) => c.id === state.agency!.missionId) ??
state.missions.find((m) => m.id === state.agency!.missionId) ??
null
);
}
return null;
}
export function applyThemeFromState(
phase: "idle" | "ascent" | "orbit" | "failed" = "idle",
): void {
const c = currentContract();
syncSimulationTheme({
weather: state.world?.weather ?? "nominal",
target: c?.target ?? "leo",
phase,
});
}

83
src/client/theme.ts Normal file
View file

@ -0,0 +1,83 @@
// The saviour you needed for your eyes, cus mine were burning before making this shit
import { getSettings, saveSettings } from "./api.js";
import type { SpaceWeather } from "../shared/types.js";
export function getColorMode(): "dark" | "light" {
return getSettings().colorMode === "light" ? "light" : "dark";
}
export function isReducedEffects(): boolean {
return !!getSettings().reducedEffects;
}
export function applyVisualPreferences(): void {
const s = getSettings();
document.documentElement.dataset.colorMode = s.colorMode;
document.documentElement.classList.toggle(
"reduced-effects",
!!s.reducedEffects,
);
document.body.dataset.dynamicTheme =
s.dynamicTheme && !s.reducedEffects ? "on" : "off";
window.dispatchEvent(
new CustomEvent("sgywftp:theme-changed", {
detail: { colorMode: s.colorMode, reducedEffects: !!s.reducedEffects },
}),
);
}
export function setColorMode(mode: "dark" | "light"): void {
const s = getSettings();
s.colorMode = mode;
saveSettings(s);
applyVisualPreferences();
}
export function toggleColorMode(): "dark" | "light" {
const next = getColorMode() === "light" ? "dark" : "light";
setColorMode(next);
return next;
}
export function setReducedEffects(on: boolean): void {
const s = getSettings();
s.reducedEffects = on;
saveSettings(s);
applyVisualPreferences();
}
export function toggleReducedEffects(): boolean {
const next = !isReducedEffects();
setReducedEffects(next);
return next;
}
export function syncSimulationTheme(opts: {
weather?: SpaceWeather | null;
target?: string | null;
phase?: "idle" | "ascent" | "orbit" | "failed";
}): void {
const s = getSettings();
document.documentElement.dataset.colorMode = s.colorMode;
document.documentElement.classList.toggle(
"reduced-effects",
!!s.reducedEffects,
);
document.body.dataset.dynamicTheme =
s.dynamicTheme && !s.reducedEffects ? "on" : "off";
if (s.reducedEffects) {
document.body.dataset.weather = "nominal";
document.body.dataset.target = "earth";
document.body.dataset.phase = "idle";
return;
}
if (opts.weather) {
document.body.dataset.weather = opts.weather;
}
if (opts.target) {
document.body.dataset.target = opts.target;
}
if (opts.phase) {
document.body.dataset.phase = opts.phase;
}
}

View file

@ -0,0 +1,97 @@
// Cached GLTF/DRACO 3D model loader with bottom-anchoring and bounding-box normalization.
// Something something compression
import * as THREE from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("/vendor/addons/libs/draco/gltf/");
const gltfLoader = new GLTFLoader();
gltfLoader.setDRACOLoader(dracoLoader);
const modelCache = new Map<string, Promise<THREE.Group>>();
export function encodeModelPath(rel: string): string {
return (
"/models/" +
rel
.split("/")
.map((s) => encodeURIComponent(s))
.join("/")
);
}
export function loadModel(url: string): Promise<THREE.Group> {
if (!modelCache.has(url)) {
const promise = gltfLoader.loadAsync(url).then((gltf) => {
const root = gltf.scene;
root.traverse((obj: any) => {
if (obj.isMesh && obj.material) {
const mats = Array.isArray(obj.material)
? obj.material
: [obj.material];
mats.forEach((m: any) => {
if (m.metalness > 0.85 && m.roughness < 0.25) {
m.roughness = 0.35;
}
if (typeof m.transmission === "number" && m.transmission > 0) {
m.transmission = 0;
m.transparent = true;
m.opacity = Math.min(
typeof m.opacity === "number" ? m.opacity : 1,
0.55,
);
}
});
}
});
return root;
});
modelCache.set(url, promise);
}
return modelCache.get(url)!.then((scene) => scene.clone(true));
}
export async function loadFittedModel(
url: string,
opts: {
height?: number;
radius?: number | null;
anchorBottom?: boolean;
legacyCentering?: boolean;
} = {},
): Promise<THREE.Group> {
const obj = await loadModel(url);
const box = new THREE.Box3().setFromObject(obj);
const size = box.getSize(new THREE.Vector3());
const targetH = opts.height ?? 10;
const maxDim = Math.max(size.y, 1e-4);
const scale = targetH / maxDim;
const wrapper = new THREE.Group();
if (opts.legacyCentering) {
obj.position.sub(box.getCenter(new THREE.Vector3()));
obj.scale.setScalar(scale);
} else {
obj.scale.multiplyScalar(scale);
obj.updateMatrixWorld(true);
const center = new THREE.Box3()
.setFromObject(obj)
.getCenter(new THREE.Vector3());
obj.position.sub(center);
}
wrapper.add(obj);
if (opts.radius != null) {
const box2 = new THREE.Box3().setFromObject(wrapper);
const s2 = box2.getSize(new THREE.Vector3());
const maxHoriz = Math.max(s2.x, s2.z, 1e-4);
if (maxHoriz > opts.radius * 2) {
wrapper.scale.multiplyScalar((opts.radius * 2) / maxHoriz);
}
}
if (opts.anchorBottom) {
const finalBox = new THREE.Box3().setFromObject(wrapper);
wrapper.position.y -= finalBox.min.y;
}
return wrapper;
}

View file

@ -0,0 +1,7 @@
// Export Three.js rocket mesh builder, disposal utilities, launch pad complex (this never looks right), and plume (omagah FlanSırvır mentioned) helpers.
export { buildLaunchComplex, buildRocketMesh } from "./rocketMesh/assembly.js";
export {
disposeRocketMesh,
type RocketMeshHandle,
} from "./rocketMesh/materials.js";
export { setPlumeAtmosphere } from "./rocketMesh/plume.js";

View file

@ -0,0 +1,433 @@
// Avengers Assemble!
import * as THREE from "three";
import { encodeModelPath, loadFittedModel } from "../modelLoader.js";
import { resolveFairingDiameter } from "../../../shared/physics.js";
import type { PlacedComponent, RocketAssembly } from "../../../shared/types.js";
import {
buildFairingHalf,
buildGridFins,
buildEngineClusterStandard,
buildPayloadNode,
buildStageConnector,
fitPayloadInsideFairing,
} from "./geometry.js";
import {
addSelectionHalo,
AVIONICS_RING_MAT,
buildCgCpOverlay,
makeMaterialForStage,
type NozzleEmitter,
type RocketMeshHandle,
tagProUid,
} from "./materials.js";
import { buildSinglePartCopy } from "./partBuilder.js";
import { buildStagePlume } from "./plume.js";
export async function buildRocketMesh(
assembly: RocketAssembly,
opts: {
realModels?: boolean;
fairingCutaway?: boolean;
selectedUid?: string | null;
showCenters?: boolean;
} = {},
): Promise<RocketMeshHandle> {
const rocket = new THREE.Group();
rocket.name = "rocket";
const stageGroups: THREE.Group[] = [];
const stageDropTankGroups: THREE.Group[][] = [];
const stagePlumes: THREE.Group[] = [];
const stageNozzleAnchors: THREE.Group[] = [];
const proPartGroups = new Map<string, THREE.Group>();
const isPro = assembly.design.designTier === "pro";
for (const stage of assembly.stages) {
const stGroup = new THREE.Group();
stGroup.name = `stage-${stage.index + 1}`;
const stDropTanks: THREE.Group[] = [];
const emitters: NozzleEmitter[] = [];
const nextStageDia =
assembly.stages[stage.index + 1]?.diameter ?? stage.diameter;
for (const comp of stage.components) {
const compMat = makeMaterialForStage(comp.material ?? stage.material);
const isSelected = !!opts.selectedUid && comp.uid === opts.selectedUid;
if (comp.role === "fins") {
const finGroup = buildGridFins(
comp.diameter / 2,
comp.yBottom,
comp.symmetry ?? comp.count ?? 4,
comp.radialOffset ?? 0,
comp.radialAngleDeg ?? 45,
);
if (isSelected) {
const halo = new THREE.Group();
halo.position.y = comp.yBottom;
addSelectionHalo(halo, comp);
finGroup.add(halo);
}
tagProUid(finGroup, comp.uid);
if (comp.uid) proPartGroups.set(comp.uid, finGroup);
stGroup.add(finGroup);
continue;
}
if (!isPro && comp.role === "engine") {
const { group, emitters: stEmitters } = buildEngineClusterStandard(
stage,
comp,
);
tagProUid(group, comp.uid);
if (comp.uid) proPartGroups.set(comp.uid, group);
stGroup.add(group);
emitters.push(...stEmitters);
continue;
}
const wrapper = new THREE.Group();
const sym = Math.max(1, comp.symmetry ?? 1);
const rOff = comp.radialOffset ?? 0;
const baseAng = ((comp.radialAngleDeg ?? 0) * Math.PI) / 180;
for (let k = 0; k < sym; k++) {
const ang = baseAng + (k / sym) * Math.PI * 2;
const px = rOff > 0.01 ? Math.cos(ang) * rOff : 0;
const pz = rOff > 0.01 ? Math.sin(ang) * rOff : 0;
const copy = buildSinglePartCopy(
comp,
compMat,
nextStageDia,
isSelected,
stage.diameter,
);
copy.position.set(px, comp.yBottom, pz);
if (comp.isDropTank) {
copy.userData.radialDir = { x: Math.cos(ang), z: Math.sin(ang) };
if (rOff > 0.01) {
const coreR = stage.diameter / 2;
const tankR = comp.diameter / 2;
const radialGap = Math.max(0.1, rOff - coreR - tankR);
const strutLen = radialGap + 0.36;
const midInward = (rOff - coreR + tankR) * 0.5;
for (const yFrac of [0.22, 0.72]) {
const strut = new THREE.Mesh(
new THREE.BoxGeometry(
strutLen,
Math.max(0.16, tankR * 0.24),
Math.max(0.15, tankR * 0.22),
),
AVIONICS_RING_MAT,
);
strut.position.set(
-Math.cos(ang) * midInward,
Math.max(0.3, comp.length * yFrac),
-Math.sin(ang) * midInward,
);
strut.rotation.y = -ang;
copy.add(strut);
}
}
stDropTanks.push(copy);
}
wrapper.add(copy);
if (comp.role === "engine") {
emitters.push({
x: px,
y: comp.yBottom,
z: pz,
radius: Math.max(0.35, comp.diameter * 0.46),
propellantType: comp.part.propellantType ?? "kerolox",
});
}
}
tagProUid(wrapper, comp.uid);
if (comp.uid) proPartGroups.set(comp.uid, wrapper);
stGroup.add(wrapper);
}
const { plume, anchor } = buildStagePlume(emitters, stage.diameter);
stGroup.add(anchor, plume);
stagePlumes.push(plume);
stageNozzleAnchors.push(anchor);
rocket.add(stGroup);
stageGroups.push(stGroup);
stageDropTankGroups.push(stDropTanks);
}
const isCoreBody = (c: PlacedComponent) =>
(c.role === "tank" ||
c.role === "structure" ||
c.role === "heatshield" ||
c.role === "interstage") &&
!c.isDropTank &&
(c.radialOffset ?? 0) <= 0.15;
for (let i = 0; i < assembly.stages.length - 1; i++) {
const lowerCore = assembly.stages[i].components.filter(isCoreBody);
const upperCore = assembly.stages[i + 1].components.filter(
(c) => isCoreBody(c) && c.role !== "interstage",
);
if (!lowerCore.length || !upperCore.length) continue;
const lowerTopComp = lowerCore.reduce((a, b) => (b.yTop > a.yTop ? b : a));
const upperBottomComp = upperCore.reduce((a, b) =>
b.yBottom < a.yBottom ? b : a,
);
const yLow = lowerTopComp.yTop;
const yHigh = upperBottomComp.yBottom;
const gap = yHigh - yLow;
if (gap < 0.05) continue;
const lowerR =
(lowerTopComp.role === "interstage"
? (assembly.stages[i + 1]?.diameter ?? lowerTopComp.diameter)
: lowerTopComp.diameter) / 2;
const upperR = upperBottomComp.diameter / 2;
const connector = buildStageConnector(
lowerR,
upperR,
gap,
makeMaterialForStage(assembly.stages[i].material),
);
connector.position.y = yLow;
connector.name = `stage-${i + 1}-connector`;
stageGroups[i].add(connector);
}
if (!isPro && assembly.computerPart) {
const topDia =
assembly.stages[assembly.stages.length - 1]?.diameter ??
assembly.maxDiameter;
const cR = Math.max(0.6, topDia * 0.48);
const compGroup = new THREE.Group();
const housing = new THREE.Mesh(
new THREE.CylinderGeometry(cR * 1.03, cR * 1.03, 0.36, 28),
new THREE.MeshStandardMaterial({
color: 0x1e293b,
metalness: 0.75,
roughness: 0.25,
}),
);
const ringCol =
(assembly.computerPart.radHardeningLevel ?? 1) >= 3
? 0x34d399
: (assembly.computerPart.radHardeningLevel ?? 1) >= 2
? 0x38bdf8
: 0xf59e0b;
const beacon = new THREE.Mesh(
new THREE.TorusGeometry(cR * 1.04, 0.045, 8, 28),
new THREE.MeshBasicMaterial({ color: ringCol }),
);
beacon.rotation.x = Math.PI / 2;
compGroup.add(housing, beacon);
compGroup.position.y = Math.max(
0.5,
(assembly.fairingY || assembly.height * 0.78) - 0.18,
);
rocket.add(compGroup);
}
const topProFairing = isPro
? assembly.design.proParts?.find((p) => p.role === "fairing")
: undefined;
const fairingEnvelope = assembly.fairingPart
? {
radius:
(topProFairing?.diameter ??
resolveFairingDiameter(
assembly.fairingPart,
assembly.stages[assembly.stages.length - 1]?.diameter,
assembly.payloadPart,
)) / 2,
length: topProFairing?.length ?? assembly.fairingPart.length,
}
: null;
const topProPayload = isPro
? assembly.design.proParts?.find((p) => p.role === "payload")
: undefined;
let payloadGroup: THREE.Group | null = null;
if (assembly.payloadPart && opts.realModels !== false) {
const builtPayload = await buildPayloadNode(
assembly.payloadPart,
assembly.payloadY,
);
if (topProPayload) {
const ang = (topProPayload.radialAngleDeg * Math.PI) / 180;
builtPayload.position.x = Math.cos(ang) * topProPayload.radialOffset;
builtPayload.position.z = Math.sin(ang) * topProPayload.radialOffset;
tagProUid(builtPayload, topProPayload.uid);
proPartGroups.set(topProPayload.uid, builtPayload);
}
payloadGroup = builtPayload;
} else if (!isPro || topProPayload) {
const generic = new THREE.Mesh(
new THREE.CylinderGeometry(1.0, 1.2, 3.0, 16),
new THREE.MeshStandardMaterial({
color: 0x60a5fa,
metalness: 0.6,
roughness: 0.35,
}),
);
generic.position.y = assembly.payloadY + 1.5;
const genericGroup = new THREE.Group();
genericGroup.add(generic);
if (topProPayload) {
tagProUid(genericGroup, topProPayload.uid);
proPartGroups.set(topProPayload.uid, genericGroup);
}
payloadGroup = genericGroup;
}
if (payloadGroup) {
if (fairingEnvelope) {
fitPayloadInsideFairing(
payloadGroup,
assembly.fairingY,
fairingEnvelope.radius,
fairingEnvelope.length,
);
}
rocket.add(payloadGroup);
}
let fairingLeft: THREE.Group | null = null;
let fairingRight: THREE.Group | null = null;
if (assembly.fairingPart && fairingEnvelope) {
const fR = fairingEnvelope.radius;
const fLen = fairingEnvelope.length;
const cutaway = !!opts.fairingCutaway;
const fl = buildFairingHalf(fR, fLen, 1, cutaway);
const fr = buildFairingHalf(fR, fLen, -1, cutaway);
fl.position.y = assembly.fairingY;
fr.position.y = assembly.fairingY;
if (topProFairing) {
if (opts.selectedUid === topProFairing.uid) {
const marker = new THREE.Group();
addSelectionHalo(marker, {
role: "fairing",
part: assembly.fairingPart,
stageIndex: 0,
yBottom: 0,
yTop: fLen,
diameter: fR * 2,
length: fLen,
count: 1,
dryMass: 0,
propellantMass: 0,
cost: 0,
});
fl.add(marker);
}
tagProUid(fl, topProFairing.uid);
tagProUid(fr, topProFairing.uid);
proPartGroups.set(topProFairing.uid, fl);
}
fairingLeft = fl;
fairingRight = fr;
rocket.add(fl, fr);
}
const topProLas = isPro
? assembly.design.proParts?.find((p) => p.role === "las")
: undefined;
let lasGroup: THREE.Group | null = null;
if (assembly.lasPart) {
lasGroup = new THREE.Group();
const tower = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.75, assembly.lasPart.length, 16),
new THREE.MeshStandardMaterial({
color: 0xe2e8f0,
metalness: 0.4,
roughness: 0.5,
}),
);
tower.position.y = assembly.lasY + assembly.lasPart.length / 2;
const tip = new THREE.Mesh(
new THREE.ConeGeometry(0.28, 1.4, 16),
new THREE.MeshStandardMaterial({
color: 0xf87171,
metalness: 0.3,
roughness: 0.5,
}),
);
tip.position.y = assembly.lasY + assembly.lasPart.length + 0.7;
lasGroup.add(tower, tip);
if (topProLas) {
tagProUid(lasGroup, topProLas.uid);
proPartGroups.set(topProLas.uid, lasGroup);
}
rocket.add(lasGroup);
}
const noseAnchor = new THREE.Group();
noseAnchor.position.y = assembly.fairingPart
? assembly.fairingY +
(topProFairing?.length ?? assembly.fairingPart.length) * 0.7
: Math.max(4, assembly.height * 0.92);
rocket.add(noseAnchor);
if (opts.showCenters) {
rocket.add(buildCgCpOverlay(assembly));
}
return {
group: rocket,
stageGroups,
stageDropTankGroups,
stagePlumes,
stageNozzleAnchors,
proPartGroups,
noseAnchor,
fairingLeft,
fairingRight,
payloadGroup,
lasGroup,
};
}
export async function buildLaunchComplex(
rocketHeight = 50,
): Promise<THREE.Group> {
const complex = new THREE.Group();
const padMesh = new THREE.Mesh(
new THREE.CylinderGeometry(28, 34, 3, 36),
new THREE.MeshStandardMaterial({
color: 0x334155,
roughness: 0.9,
metalness: 0.15,
}),
);
padMesh.position.y = -1.5;
padMesh.receiveShadow = true;
complex.add(padMesh);
const padRing = new THREE.Mesh(
new THREE.RingGeometry(12, 13.2, 36),
new THREE.MeshBasicMaterial({
color: 0x60a5fa,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.45,
}),
);
padRing.rotation.x = -Math.PI / 2;
padRing.position.y = 0.05;
complex.add(padRing);
try {
const launcher = await loadFittedModel(
encodeModelPath("nasa_3d_glb/Mobile Launcher (assembled).glb"),
{
height: Math.max(48, rocketHeight * 1.15),
anchorBottom: true,
legacyCentering: true,
},
);
launcher.position.set(0, -1.5, 0);
complex.add(launcher);
} catch {
const tower = new THREE.Mesh(
new THREE.BoxGeometry(5, Math.max(45, rocketHeight * 1.1), 5),
new THREE.MeshStandardMaterial({
color: 0x991b1b,
metalness: 0.45,
roughness: 0.6,
}),
);
tower.position.set(-12, Math.max(45, rocketHeight * 1.1) / 2, 0);
complex.add(tower);
}
try {
const vab = await loadFittedModel(
encodeModelPath("nasa_3d_glb/Vehicle Assembly Building (VAB).glb"),
{
height: 55,
anchorBottom: true,
legacyCentering: true,
},
);
vab.position.set(-110, -2, -130);
complex.add(vab);
} catch {}
return complex;
}

View file

@ -0,0 +1,385 @@
// Procedural rocket meshes: parabolic engine bells (finally math comes in handy), ogive fairings (I don't think I implemented this correctly), payload placement, grid fins, and interstages.
import * as THREE from "three";
import type {
AssembledStage,
Part,
PlacedComponent,
} from "../../../shared/types.js";
import { encodeModelPath, loadFittedModel } from "../modelLoader.js";
import {
AVIONICS_RING_MAT,
ACCENT_STRIPE_MAT,
DARK_NOZZLE_MAT,
FAIRING_CUTAWAY_MAT,
FAIRING_SOLID_MAT,
type NozzleEmitter,
} from "./materials.js";
export function buildParabolicBellGeo(
exitR: number,
bellH: number,
): THREE.LatheGeometry {
const throatR = exitR * 0.26;
const topR = exitR * 0.36;
const pts: THREE.Vector2[] = [];
pts.push(new THREE.Vector2(throatR * 0.72, bellH * 0.94));
pts.push(new THREE.Vector2(topR, bellH));
pts.push(new THREE.Vector2(throatR, bellH * 0.84));
const segs = 9;
for (let i = 1; i <= segs; i++) {
const s = i / segs;
const r = throatR + (exitR - throatR) * (1 - Math.pow(1 - s, 1.75));
const y = bellH * 0.84 * (1 - s);
pts.push(new THREE.Vector2(r, y));
}
pts.push(new THREE.Vector2(exitR * 0.93, 0));
for (let i = segs - 1; i >= 1; i--) {
const s = i / segs;
const r =
throatR * 0.9 +
(exitR * 0.92 - throatR * 0.9) * (1 - Math.pow(1 - s, 1.75));
const y = bellH * 0.82 * (1 - s);
pts.push(new THREE.Vector2(r, y));
}
pts.push(new THREE.Vector2(throatR * 0.8, bellH * 0.82));
const geo = new THREE.LatheGeometry(pts, 24);
geo.computeVertexNormals();
return geo;
}
const FAIRING_BODY_FRAC = 0.46;
const FAIRING_NOSE_EXP = 0.72;
function fairingProfileRadius(
radius: number,
length: number,
z: number,
): number {
const bodyH = length * FAIRING_BODY_FRAC;
const noseH = length - bodyH;
if (z < 0 || z > length) return 0;
if (z <= bodyH * 0.14) {
const r0 = Math.max(0.3, radius * 0.95);
return r0 + (radius - r0) * (z / Math.max(1e-4, bodyH * 0.14));
}
if (z <= bodyH) return radius;
const t = (z - bodyH) / Math.max(1e-4, noseH);
return Math.max(
radius * 0.04,
radius *
Math.pow(Math.max(0, Math.cos(t * Math.PI * 0.5)), FAIRING_NOSE_EXP),
);
}
export function fitPayloadInsideFairing(
payload: THREE.Group,
fairingY: number,
fairingRadius: number,
fairingLength: number,
): void {
payload.updateMatrixWorld(true);
const BINS = 48;
const box = new THREE.Box3().setFromObject(payload);
if (box.isEmpty()) return;
const yMin = box.min.y;
const ySpan = Math.max(1e-4, box.max.y - yMin);
const binR = new Array<number>(BINS).fill(-1);
const v = new THREE.Vector3();
payload.traverse((child: any) => {
const pos = child.isMesh ? child.geometry?.attributes?.position : null;
if (!pos) return;
const stride = Math.max(1, Math.ceil(pos.count / 6000));
for (let i = 0; i < pos.count; i += stride) {
v.fromBufferAttribute(pos, i).applyMatrix4(child.matrixWorld);
const b = Math.min(
BINS - 1,
Math.max(0, Math.floor(((v.y - yMin) / ySpan) * BINS)),
);
const r = Math.hypot(v.x, v.z);
if (r > binR[b]) binR[b] = r;
}
});
const wall = 0.9;
const baseY = Math.max(yMin, fairingY + 0.3);
const lift = baseY - yMin;
const fits = (s: number): boolean => {
for (let b = 0; b < BINS; b++) {
if (binR[b] < 0) continue;
const zBot = baseY + s * ((b / BINS) * ySpan) - fairingY;
const zTop = baseY + s * (((b + 1) / BINS) * ySpan) - fairingY;
if (zTop > fairingLength * 0.985) return false;
const rAllowed = Math.min(
fairingProfileRadius(fairingRadius, fairingLength, zBot),
fairingProfileRadius(fairingRadius, fairingLength, zTop),
);
if (s * binR[b] > wall * rAllowed) return false;
}
return true;
};
let s = 1;
if (!fits(1)) {
let lo = 0;
let hi = 1;
for (let k = 0; k < 24; k++) {
const mid = (lo + hi) / 2;
if (fits(mid)) lo = mid;
else hi = mid;
}
s = Math.max(0.05, lo);
}
if (s === 1 && lift === 0) return;
payload.scale.multiplyScalar(s);
payload.position.set(
payload.position.x * s,
yMin + (payload.position.y - yMin) * s + lift,
payload.position.z * s,
);
}
export function buildOgiveFairingGeo(
radius: number,
length: number,
thetaStart = 0,
thetaLength = Math.PI * 2,
): THREE.LatheGeometry {
const bodyH = length * FAIRING_BODY_FRAC;
const noseH = length * 0.54;
const pts: THREE.Vector2[] = [];
pts.push(new THREE.Vector2(Math.max(0.3, radius * 0.95), 0));
pts.push(new THREE.Vector2(radius, bodyH * 0.14));
pts.push(new THREE.Vector2(radius, bodyH));
const noseSteps = 12;
for (let i = 1; i <= noseSteps; i++) {
const t = i / noseSteps;
const r = Math.max(
radius * 0.04,
radius * Math.pow(Math.max(0, Math.cos(t * Math.PI * 0.5)), 0.72),
);
pts.push(new THREE.Vector2(r, bodyH + t * noseH));
}
pts.push(new THREE.Vector2(0.01, length));
const geo = new THREE.LatheGeometry(pts, 28, thetaStart, thetaLength);
geo.computeVertexNormals();
return geo;
}
const CONNECTOR_RADIUS_FRAC = 0.94;
export function buildStageConnector(
botR: number,
topR: number,
len: number,
mat: THREE.Material,
): THREE.Group {
const g = new THREE.Group();
const bR = Math.max(0.15, botR * CONNECTOR_RADIUS_FRAC);
const tR = Math.max(0.15, topR * CONNECTOR_RADIUS_FRAC);
const body = new THREE.Mesh(
new THREE.CylinderGeometry(tR, bR, len, 48, 1, false),
mat,
);
body.position.y = len / 2;
body.castShadow = true;
body.receiveShadow = true;
g.add(body);
const flangeH = Math.min(0.22, len * 0.12);
const lerpR = (y: number) => bR + (tR - bR) * (y / len);
const ring = (y: number, h: number, scale: number, m: THREE.Material) => {
const y0 = Math.max(0, y - h / 2);
const y1 = Math.min(len, y + h / 2);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
lerpR(y1) * scale,
lerpR(y0) * scale,
y1 - y0,
48,
1,
true,
),
m,
);
mesh.position.y = (y0 + y1) / 2;
g.add(mesh);
};
ring(flangeH / 2, flangeH, 1.025, AVIONICS_RING_MAT);
ring(len - flangeH / 2, flangeH, 1.025, AVIONICS_RING_MAT);
if (len > 1.2) ring(len - flangeH * 2.2, 0.08, 1.012, ACCENT_STRIPE_MAT);
return g;
}
export function buildEngineClusterStandard(
stage: AssembledStage,
comp: PlacedComponent,
): { group: THREE.Group; emitters: NozzleEmitter[] } {
const cluster = new THREE.Group();
const emitters: NozzleEmitter[] = [];
const count = comp.count;
const stageR = stage.diameter / 2;
const nozzleScale = 0.85 + 0.15 * (stage.config.nozzleRatio ?? 1.0);
let singleR = Math.min(
stageR * 0.68,
(comp.part.diameter / 2) * nozzleScale * (count > 1 ? 0.52 : 0.82),
);
let ringR = count > 1 ? Math.max(singleR * 1.15, stageR * 0.56) : 0;
const maxExtent = stageR * CONNECTOR_RADIUS_FRAC * 0.9;
if (ringR + singleR > maxExtent) {
const k = maxExtent / (ringR + singleR);
ringR *= k;
singleR *= k;
}
const dome = new THREE.Mesh(
new THREE.CylinderGeometry(
stageR * 0.88,
stageR * 0.78,
comp.length * 0.28,
28,
),
AVIONICS_RING_MAT,
);
dome.position.y = comp.yBottom + comp.length * 0.86;
cluster.add(dome);
const offsets: Array<[number, number]> = [];
if (count === 1) {
offsets.push([0, 0]);
} else {
const ringCount = count >= 6 ? count - 1 : count;
if (count >= 6) offsets.push([0, 0]);
for (let i = 0; i < ringCount; i++) {
const ang = (i / ringCount) * Math.PI * 2;
offsets.push([Math.cos(ang) * ringR, Math.sin(ang) * ringR]);
}
}
for (const [ox, oz] of offsets) {
const bellH = comp.length * 0.78;
const bell = new THREE.Mesh(
buildParabolicBellGeo(singleR, bellH),
DARK_NOZZLE_MAT,
);
bell.position.set(ox, comp.yBottom, oz);
bell.castShadow = true;
bell.receiveShadow = true;
cluster.add(bell);
const lip = new THREE.Mesh(
new THREE.TorusGeometry(
singleR * 0.97,
Math.max(0.025, singleR * 0.06),
8,
22,
),
DARK_NOZZLE_MAT,
);
lip.rotation.x = Math.PI / 2;
lip.position.set(ox, comp.yBottom + 0.03, oz);
cluster.add(lip);
const jacket = new THREE.Mesh(
new THREE.TorusGeometry(
singleR * 0.62,
Math.max(0.02, singleR * 0.045),
8,
20,
),
AVIONICS_RING_MAT,
);
jacket.rotation.x = Math.PI / 2;
jacket.position.set(ox, comp.yBottom + bellH * 0.56, oz);
cluster.add(jacket);
emitters.push({
x: ox,
y: comp.yBottom,
z: oz,
radius: singleR,
propellantType: comp.part.propellantType ?? "kerolox",
});
}
return { group: cluster, emitters };
}
export function buildGridFins(
radius: number,
yPos: number,
symmetry = 4,
radialOffset = 0,
angleOffsetDeg = 45,
): THREE.Group {
const g = new THREE.Group();
const finMat = new THREE.MeshStandardMaterial({
color: 0x64748b,
metalness: 0.75,
roughness: 0.35,
});
const span = Math.max(0.8, radius * 0.65);
const attachR = Math.max(radius, radialOffset);
const baseRad = (angleOffsetDeg * Math.PI) / 180;
for (let i = 0; i < symmetry; i++) {
const ang = baseRad + (i / symmetry) * Math.PI * 2;
const fin = new THREE.Mesh(
new THREE.BoxGeometry(span, span * 0.75, 0.14),
finMat,
);
fin.position.set(
Math.cos(ang) * (attachR + span * 0.45),
yPos + span * 0.4,
Math.sin(ang) * (attachR + span * 0.45),
);
fin.rotation.y = -ang;
g.add(fin);
}
return g;
}
export function buildFairingHalf(
radius: number,
length: number,
sideSign: 1 | -1,
cutaway: boolean,
): THREE.Group {
const half = new THREE.Group();
const mat = cutaway ? FAIRING_CUTAWAY_MAT : FAIRING_SOLID_MAT;
const thetaStart = sideSign > 0 ? 0 : Math.PI;
const shroud = new THREE.Mesh(
buildOgiveFairingGeo(radius, length, thetaStart, Math.PI),
mat,
);
if (!cutaway) {
shroud.castShadow = true;
shroud.receiveShadow = true;
}
half.add(shroud);
return half;
}
export async function buildPayloadNode(
part: Part,
yPos: number,
): Promise<THREE.Group> {
if (part.modelFile) {
try {
const m = await loadFittedModel(encodeModelPath(part.modelFile), {
height: Math.max(1.2, part.length),
radius: Math.max(0.4, part.diameter / 2),
anchorBottom: true,
});
m.position.y += yPos;
return m;
} catch (err) {
console.warn("[rocketMesh] GLB payload fallback:", part.modelFile, err);
}
}
const g = new THREE.Group();
const body = new THREE.Mesh(
new THREE.CylinderGeometry(
part.diameter * 0.42,
part.diameter * 0.45,
part.length * 0.85,
20,
),
new THREE.MeshStandardMaterial({
color: 0x94a3b8,
metalness: 0.7,
roughness: 0.3,
}),
);
body.position.y = yPos + part.length * 0.425;
g.add(body);
return g;
}

View file

@ -0,0 +1,274 @@
//Three.js rocket materials, helpers we love helpers (please no memory leaks), and CG/CP overlay markers.
import * as THREE from "three";
import type {
MaterialSpec,
PlacedComponent,
RocketAssembly,
} from "../../../shared/types.js";
export interface RocketMeshHandle {
group: THREE.Group;
stageGroups: THREE.Group[];
stageDropTankGroups: THREE.Group[][];
stagePlumes: THREE.Group[];
stageNozzleAnchors: THREE.Group[];
proPartGroups: Map<string, THREE.Group>;
noseAnchor: THREE.Group;
fairingLeft: THREE.Group | null;
fairingRight: THREE.Group | null;
payloadGroup: THREE.Group | null;
lasGroup: THREE.Group | null;
}
interface PlumeStyle {
core: number;
inner: number;
outer: number;
diamond: number;
light: number;
lenFactor: number;
}
export interface NozzleEmitter {
x: number;
y: number;
z: number;
radius: number;
propellantType: string;
}
export const DARK_NOZZLE_MAT = new THREE.MeshStandardMaterial({
color: 0x262c36,
metalness: 0.88,
roughness: 0.28,
envMapIntensity: 0.95,
});
export const FAIRING_SOLID_MAT = new THREE.MeshPhysicalMaterial({
color: 0xeef2f7,
metalness: 0.14,
roughness: 0.32,
clearcoat: 0.52,
clearcoatRoughness: 0.22,
envMapIntensity: 0.85,
side: THREE.DoubleSide,
});
export const FAIRING_CUTAWAY_MAT = new THREE.MeshStandardMaterial({
color: 0x60a5fa,
metalness: 0.2,
roughness: 0.25,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide,
depthWrite: false,
});
export const AVIONICS_RING_MAT = new THREE.MeshStandardMaterial({
color: 0x1e2536,
metalness: 0.72,
roughness: 0.34,
envMapIntensity: 0.9,
});
export const ACCENT_STRIPE_MAT = new THREE.MeshBasicMaterial({
color: 0x60a5fa,
});
export const SHUTTLE_FOAM_MAT = new THREE.MeshStandardMaterial({
color: 0xc25929,
metalness: 0.08,
roughness: 0.78,
envMapIntensity: 0.45,
});
const SHARED_ROCKET_MATS = new Set<THREE.Material>([
DARK_NOZZLE_MAT,
FAIRING_SOLID_MAT,
FAIRING_CUTAWAY_MAT,
AVIONICS_RING_MAT,
ACCENT_STRIPE_MAT,
SHUTTLE_FOAM_MAT,
]);
export function disposeRocketMesh(
handle: RocketMeshHandle | null | undefined,
): void {
if (!handle) return;
const protectedNodes = new Set<THREE.Object3D>();
if (handle.payloadGroup) {
handle.payloadGroup.traverse((node) => {
protectedNodes.add(node);
});
}
handle.group.traverse((node) => {
if (protectedNodes.has(node) || node.userData?.sharedModelResource) return;
const obj = node as THREE.Object3D & {
geometry?: THREE.BufferGeometry;
material?: THREE.Material | THREE.Material[];
};
if (obj.geometry && typeof obj.geometry.dispose === "function") {
obj.geometry.dispose();
}
const mats = Array.isArray(obj.material)
? obj.material
: obj.material
? [obj.material]
: [];
for (const mat of mats) {
if (
mat &&
!SHARED_ROCKET_MATS.has(mat) &&
typeof mat.dispose === "function"
) {
mat.dispose();
}
}
});
}
export function getPlumeStyle(propellantType = "kerolox"): PlumeStyle {
switch (propellantType) {
case "hydrolox":
return {
core: 0xf0f9ff,
inner: 0x93c5fd,
outer: 0x3b82f6,
diamond: 0xe0f2fe,
light: 0x60a5fa,
lenFactor: 0.9,
};
case "methalox":
return {
core: 0xf5f3ff,
inner: 0xc084fc,
outer: 0x6366f1,
diamond: 0xe9d5ff,
light: 0xa78bfa,
lenFactor: 1.0,
};
case "solid":
return {
core: 0xffffff,
inner: 0xfde047,
outer: 0xf97316,
diamond: 0xfef9c3,
light: 0xfbbf24,
lenFactor: 1.18,
};
case "hypergolic":
return {
core: 0xfdf4ff,
inner: 0xf472b6,
outer: 0xa855f7,
diamond: 0xfbcfe8,
light: 0xe879f9,
lenFactor: 0.82,
};
case "xenon":
return {
core: 0xecfeff,
inner: 0x38bdf8,
outer: 0x0284c7,
diamond: 0xbae6fd,
light: 0x38bdf8,
lenFactor: 0.65,
};
default:
return {
core: 0xfff7ed,
inner: 0xfb923c,
outer: 0xf97316,
diamond: 0xfef08a,
light: 0xfb923c,
lenFactor: 1.05,
};
}
}
export function makeMaterialForStage(
matSpec: MaterialSpec,
): THREE.MeshPhysicalMaterial {
const metalness = matSpec.metalness ?? 0.65;
return new THREE.MeshPhysicalMaterial({
color: matSpec.colorHex || "#c8d2de",
metalness,
roughness: Math.max(0.14, matSpec.roughness ?? 0.34),
clearcoat: metalness > 0.55 ? 0.24 : 0.48,
clearcoatRoughness: 0.22,
envMapIntensity: 0.95,
});
}
export function tagProUid(obj: THREE.Object3D, uid?: string): void {
if (!uid) return;
obj.userData.proPartUid = uid;
obj.traverse((child: any) => {
child.userData.proPartUid = uid;
});
}
export function addSelectionHalo(
group: THREE.Group,
comp: PlacedComponent,
): void {
const r = Math.max(0.5, comp.diameter / 2 + 0.25);
const halo = new THREE.Mesh(
new THREE.CylinderGeometry(
r,
r,
Math.max(0.4, comp.length + 0.2),
24,
1,
true,
),
new THREE.MeshBasicMaterial({
color: 0x60a5fa,
transparent: true,
opacity: 0.32,
side: THREE.DoubleSide,
depthWrite: false,
}),
);
halo.position.y = comp.length / 2;
group.add(halo);
}
export function buildCgCpOverlay(assembly: RocketAssembly): THREE.Group {
const overlay = new THREE.Group();
const r = Math.max(1.8, assembly.maxDiameter * 0.72);
const cgGroup = new THREE.Group();
cgGroup.position.y = assembly.cgY;
const cgSphere = new THREE.Mesh(
new THREE.SphereGeometry(0.75, 16, 16),
new THREE.MeshBasicMaterial({ color: 0xf59e0b }),
);
const cgRing = new THREE.Mesh(
new THREE.TorusGeometry(r, 0.08, 8, 32),
new THREE.MeshBasicMaterial({
color: 0xf59e0b,
transparent: true,
opacity: 0.85,
}),
);
cgRing.rotation.x = Math.PI / 2;
cgGroup.add(cgSphere, cgRing);
const cpGroup = new THREE.Group();
cpGroup.position.y = assembly.cpY;
const cpCone = new THREE.Mesh(
new THREE.ConeGeometry(0.85, 1.6, 12),
new THREE.MeshBasicMaterial({
color: 0x38bdf8,
transparent: true,
opacity: 0.9,
}),
);
cpCone.rotation.x = Math.PI;
const cpRing = new THREE.Mesh(
new THREE.TorusGeometry(r, 0.08, 8, 32),
new THREE.MeshBasicMaterial({
color: 0x38bdf8,
transparent: true,
opacity: 0.85,
}),
);
cpRing.rotation.x = Math.PI / 2;
cpGroup.add(cpCone, cpRing);
overlay.add(cgGroup, cpGroup);
return overlay;
}

View file

@ -0,0 +1,213 @@
// Renders individual parts (tanks, engines, avionics, structures, shrouds).
import * as THREE from "three";
import type { PlacedComponent } from "../../../shared/types.js";
import {
buildOgiveFairingGeo,
buildParabolicBellGeo,
buildStageConnector,
} from "./geometry.js";
import {
ACCENT_STRIPE_MAT,
addSelectionHalo,
AVIONICS_RING_MAT,
DARK_NOZZLE_MAT,
FAIRING_SOLID_MAT,
SHUTTLE_FOAM_MAT,
} from "./materials.js";
export function buildSinglePartCopy(
comp: PlacedComponent,
tankMat: THREE.MeshStandardMaterial,
nextStageDia: number,
isSelected: boolean,
stageDia: number = comp.diameter,
): THREE.Group {
const g = new THREE.Group();
const r = comp.diameter / 2;
if (comp.role === "engine") {
const skirt = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.55, r * 0.38, comp.length * 0.22, 18),
AVIONICS_RING_MAT,
);
skirt.position.y = comp.length * 0.89;
g.add(skirt);
const bellH = comp.length * 0.8;
const bell = new THREE.Mesh(
buildParabolicBellGeo(r, bellH),
DARK_NOZZLE_MAT,
);
bell.castShadow = true;
bell.receiveShadow = true;
g.add(bell);
const lip = new THREE.Mesh(
new THREE.TorusGeometry(r * 0.97, Math.max(0.025, r * 0.06), 8, 22),
DARK_NOZZLE_MAT,
);
lip.rotation.x = Math.PI / 2;
lip.position.y = 0.03;
g.add(lip);
} else if (comp.role === "tank") {
if (comp.isDropTank) {
const barrelMat =
comp.part.id === "drop-tank-hydro-et" ? SHUTTLE_FOAM_MAT : tankMat;
const aftH = Math.max(0.28, comp.length * 0.06);
const noseH = Math.max(0.55, comp.length * 0.22);
const cylLen = Math.max(0.6, comp.length - aftH - noseH);
const aftCap = new THREE.Mesh(
new THREE.CylinderGeometry(r, r * 0.62, aftH, 32),
barrelMat,
);
aftCap.position.y = aftH / 2;
aftCap.castShadow = true;
aftCap.receiveShadow = true;
g.add(aftCap);
const tankMesh = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, cylLen, 36),
barrelMat,
);
tankMesh.position.y = aftH + cylLen / 2;
tankMesh.castShadow = true;
tankMesh.receiveShadow = true;
g.add(tankMesh);
const nose = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.14, r, noseH, 36),
barrelMat,
);
nose.position.y = aftH + cylLen + noseH / 2;
nose.castShadow = true;
g.add(nose);
const noseTip = new THREE.Mesh(
new THREE.SphereGeometry(r * 0.14, 16, 10),
AVIONICS_RING_MAT,
);
noseTip.position.y = aftH + cylLen + noseH;
g.add(noseTip);
for (const frac of [0.16, 0.54, 0.92]) {
const band = new THREE.Mesh(
new THREE.CylinderGeometry(r * 1.018, r * 1.018, 0.14, 36),
AVIONICS_RING_MAT,
);
band.position.y = aftH + cylLen * frac;
g.add(band);
}
} else {
const tankMesh = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, comp.length, 48),
tankMat,
);
tankMesh.position.y = comp.length / 2;
tankMesh.castShadow = true;
tankMesh.receiveShadow = true;
g.add(tankMesh);
for (const frac of [0.15, 0.5, 0.85]) {
const ring = new THREE.Mesh(
new THREE.CylinderGeometry(r * 1.012, r * 1.012, 0.16, 48),
AVIONICS_RING_MAT,
);
ring.position.y = comp.length * frac;
ring.castShadow = true;
g.add(ring);
}
const raceway = new THREE.Mesh(
new THREE.BoxGeometry(
Math.max(0.12, r * 0.08),
comp.length * 0.94,
Math.max(0.08, r * 0.06),
),
AVIONICS_RING_MAT,
);
raceway.position.set(0, comp.length / 2, r * 0.995);
g.add(raceway);
}
} else if (comp.role === "heatshield") {
const shield = new THREE.Mesh(
new THREE.CylinderGeometry(r * 1.03, r * 1.03, comp.length, 32),
new THREE.MeshStandardMaterial({
color: 0x451a03,
metalness: 0.3,
roughness: 0.85,
}),
);
shield.position.y = comp.length / 2;
g.add(shield);
} else if (comp.role === "structure") {
const avionics = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, comp.length, 48),
tankMat,
);
avionics.position.y = comp.length / 2;
avionics.castShadow = true;
avionics.receiveShadow = true;
g.add(avionics);
const botTrim = new THREE.Mesh(
new THREE.CylinderGeometry(
r * 1.008,
r * 1.008,
Math.min(0.24, comp.length * 0.22),
48,
),
AVIONICS_RING_MAT,
);
botTrim.position.y = Math.min(0.12, comp.length * 0.11);
g.add(botTrim);
const topTrim = new THREE.Mesh(
new THREE.CylinderGeometry(
r * 1.008,
r * 1.008,
Math.min(0.24, comp.length * 0.22),
48,
),
AVIONICS_RING_MAT,
);
topTrim.position.y = comp.length - Math.min(0.12, comp.length * 0.11);
g.add(topTrim);
const stripe = new THREE.Mesh(
new THREE.CylinderGeometry(r * 1.012, r * 1.012, 0.2, 48),
ACCENT_STRIPE_MAT,
);
stripe.position.y = comp.length * 0.5;
g.add(stripe);
} else if (comp.role === "interstage") {
const botR = stageDia / 2;
const topR = nextStageDia > 0.2 ? nextStageDia / 2 : r;
g.add(buildStageConnector(botR, topR, Math.max(0.6, comp.length), tankMat));
} else if (comp.role === "computer") {
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(
r * 1.02,
r * 1.02,
Math.max(0.45, comp.length),
24,
),
new THREE.MeshStandardMaterial({
color: 0x0f172a,
metalness: 0.72,
roughness: 0.28,
}),
);
collar.position.y = Math.max(0.45, comp.length) / 2;
const ledColor =
(comp.part.radHardeningLevel ?? 1) >= 3
? 0x34d399
: (comp.part.radHardeningLevel ?? 1) >= 2
? 0x38bdf8
: 0xf59e0b;
const busRing = new THREE.Mesh(
new THREE.TorusGeometry(r * 1.03, 0.055, 8, 28),
new THREE.MeshBasicMaterial({ color: ledColor }),
);
busRing.rotation.x = Math.PI / 2;
busRing.position.y = Math.max(0.45, comp.length) * 0.55;
g.add(collar, busRing);
} else if (comp.role === "fairing") {
const shroud = new THREE.Mesh(
buildOgiveFairingGeo(r, comp.length),
FAIRING_SOLID_MAT,
);
shroud.castShadow = true;
shroud.receiveShadow = true;
g.add(shroud);
}
if (isSelected) addSelectionHalo(g, comp);
return g;
}

View file

@ -0,0 +1,217 @@
// Volumetric GLSL shader exhaust plumes, mach shock diamonds (this doesn't look so much better than p1), and altitude/throttle plume scaling.
import * as THREE from "three";
import { getSoftParticleTexture } from "../sceneManager.js";
import { isReducedEffects } from "../../theme.js";
import { getPlumeStyle, type NozzleEmitter } from "./materials.js";
const PLUME_VERTEX_SHADER = `
uniform float uVacuum;
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
vUv = uv;
float t = clamp(1.0 - uv.y, 0.0, 1.0);
float flare = mix(1.0, 1.0 + uVacuum * 1.45 * pow(max(0.0001, t), 0.85), step(0.001, t));
vec3 pos = vec3(position.x * flare, position.y, position.z * flare);
vec4 worldPos = modelMatrix * vec4(pos, 1.0);
vNormalW = normalize((modelMatrix * vec4(normal, 0.0)).xyz);
vViewDir = normalize(cameraPosition - worldPos.xyz);
gl_Position = projectionMatrix * viewMatrix * worldPos;
}
`;
const PLUME_FRAGMENT_SHADER = `
uniform float uTime;
uniform float uVacuum;
uniform float uThrottle;
uniform float uReduced;
uniform vec3 uCoreColor;
uniform vec3 uInnerColor;
uniform vec3 uOuterColor;
uniform vec3 uDiamondColor;
varying vec2 vUv;
varying vec3 vNormalW;
varying vec3 vViewDir;
void main() {
float t = clamp(1.0 - vUv.y, 0.0, 1.0);
float ndv = abs(dot(normalize(vNormalW), normalize(vViewDir)));
float fresnel = pow(max(0.0001, clamp(ndv, 0.0, 1.0)), 1.25);
float entryFade = smoothstep(0.0, 0.05, t);
float tailLen = mix(0.95, 0.80, uVacuum);
float tailFade = pow(max(0.0001, 1.0 - smoothstep(0.14, tailLen, t)), 1.35);
float speed = (1.0 - uReduced) * uTime;
float turb = 0.5 + 0.5 * sin(t * 15.0 - speed * 22.0 + sin(vUv.x * 18.8495 + speed * 5.0) * 1.35);
float ripple = 0.84 + 0.16 * sin(t * 34.0 - speed * 31.0 + cos(vUv.x * 25.1327));
float machVis = 1.0 - uVacuum * 0.92;
float diamondWave = pow(max(0.0, sin(t * 24.0 + 0.4)), 4.0) * (1.0 - smoothstep(0.04, 0.72, t));
float throatHot = 1.0 - smoothstep(0.0, 0.24, t);
vec3 plumeCol = mix(uOuterColor, uInnerColor, smoothstep(0.0, 0.65, ndv) * (1.0 - t * 0.5));
plumeCol = mix(plumeCol, uCoreColor, throatHot * fresnel);
plumeCol += uDiamondColor * (diamondWave * machVis * 1.25);
float intensity = (0.85 + uThrottle * 0.7) * (0.72 + 0.28 * turb * ripple);
vec3 finalRgb = plumeCol * intensity;
float alpha = (fresnel * entryFade * tailFade * (0.64 + 0.32 * turb)) + (diamondWave * machVis * fresnel * 0.36);
alpha *= clamp(0.45 + uThrottle * 0.55, 0.35, 1.05);
if (alpha < 0.008) discard;
gl_FragColor = vec4(finalRgb, clamp(alpha, 0.0, 0.96));
}
`;
export function setPlumeAtmosphere(
plume: THREE.Group,
altKm: number,
throttle: number,
): void {
const vacuum = Math.max(0, Math.min(1, altKm / 65));
const thr = Math.max(0.15, Math.min(1.4, throttle));
plume.traverse((node: any) => {
const mat = node.material as THREE.ShaderMaterial | undefined;
if (mat?.userData?.isPlumeShader && mat.uniforms) {
mat.uniforms.uVacuum.value = vacuum;
mat.uniforms.uThrottle.value = thr;
if (mat.uniforms.uReduced) {
mat.uniforms.uReduced.value = isReducedEffects() ? 1.0 : 0.0;
}
}
});
}
export function buildStagePlume(
emitters: NozzleEmitter[],
stageDiameter: number,
): {
plume: THREE.Group;
anchor: THREE.Group;
} {
const plume = new THREE.Group();
plume.visible = false;
const anchor = new THREE.Group();
if (emitters.length === 0) {
emitters.push({
x: 0,
y: 0,
z: 0,
radius: Math.max(0.6, stageDiameter * 0.25),
propellantType: "kerolox",
});
}
let cx = 0;
let cy = 0;
let cz = 0;
for (const e of emitters) {
cx += e.x;
cy += e.y;
cz += e.z;
}
cx /= emitters.length;
cy /= emitters.length;
cz /= emitters.length;
anchor.position.set(cx, cy, cz);
plume.position.set(cx, cy, cz);
const maxVisualNozzles =
emitters.length <= 6 ? emitters : emitters.slice(0, 6);
const scaleBoost = emitters.length > 6 ? 1.35 : 1.0;
const glowTex = getSoftParticleTexture();
for (const e of maxVisualNozzles) {
const style = getPlumeStyle(e.propellantType);
const r = Math.max(0.35, e.radius * 0.95 * scaleBoost);
const plumeLen = Math.max(11, r * 18 * style.lenFactor);
const nozzlePlume = new THREE.Group();
nozzlePlume.position.set(e.x - cx, e.y - cy, e.z - cz);
const shaderMat = new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 },
uVacuum: { value: 0 },
uThrottle: { value: 1 },
uReduced: { value: isReducedEffects() ? 1.0 : 0.0 },
uCoreColor: { value: new THREE.Color(style.core).multiplyScalar(1.35) },
uInnerColor: {
value: new THREE.Color(style.inner).multiplyScalar(1.15),
},
uOuterColor: { value: new THREE.Color(style.outer) },
uDiamondColor: {
value: new THREE.Color(style.diamond).multiplyScalar(1.4),
},
},
vertexShader: PLUME_VERTEX_SHADER,
fragmentShader: PLUME_FRAGMENT_SHADER,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
side: THREE.DoubleSide,
});
shaderMat.userData.isPlumeShader = true;
const envelope = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.85, r * 2.1, plumeLen, 24, 20, true),
shaderMat,
);
envelope.position.y = -plumeLen * 0.5;
envelope.onBeforeRender = () => {
if (!isReducedEffects()) {
shaderMat.uniforms.uTime.value = performance.now() * 0.001;
}
};
nozzlePlume.add(envelope);
const innerCoreMat = new THREE.ShaderMaterial({
uniforms: {
uTime: shaderMat.uniforms.uTime,
uVacuum: shaderMat.uniforms.uVacuum,
uThrottle: shaderMat.uniforms.uThrottle,
uReduced: shaderMat.uniforms.uReduced,
uCoreColor: { value: new THREE.Color(style.core).multiplyScalar(1.6) },
uInnerColor: {
value: new THREE.Color(style.diamond).multiplyScalar(1.3),
},
uOuterColor: { value: new THREE.Color(style.inner) },
uDiamondColor: {
value: new THREE.Color(style.core).multiplyScalar(1.6),
},
},
vertexShader: PLUME_VERTEX_SHADER,
fragmentShader: PLUME_FRAGMENT_SHADER,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
side: THREE.DoubleSide,
});
innerCoreMat.userData.isPlumeShader = true;
const innerMesh = new THREE.Mesh(
new THREE.CylinderGeometry(
r * 0.42,
r * 0.95,
plumeLen * 0.62,
18,
12,
true,
),
innerCoreMat,
);
innerMesh.position.y = -(plumeLen * 0.62) * 0.5;
nozzlePlume.add(innerMesh);
const throatSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: glowTex,
color: style.core,
transparent: true,
opacity: 0.88,
blending: THREE.AdditiveBlending,
depthWrite: false,
}),
);
throatSprite.position.set(0, -r * 1.08, 0);
throatSprite.scale.set(r * 2.8, r * 2.2, 1);
nozzlePlume.add(throatSprite);
plume.add(nozzlePlume);
}
const primaryStyle = getPlumeStyle(emitters[0]?.propellantType);
const plumeLight = new THREE.PointLight(primaryStyle.light, 6.5, 160, 1.4);
plumeLight.position.set(0, -3.5, 0);
plume.add(plumeLight);
return { plume, anchor };
}

View file

@ -0,0 +1,7 @@
// Export Three.js view setup and particle texture helper.
export { getSoftParticleTexture } from "./sceneManager/studioEnv.js";
export {
createView,
type ManagedView,
type ViewOptions,
} from "./sceneManager/view.js";

View file

@ -0,0 +1,168 @@
// Generates procedural reflections and soft particle textures (this looks so much better than p1).
import * as THREE from "three";
function cubemapFaceDirection(
face: number,
s: number,
t: number,
): [number, number, number] {
let x = 0;
let y = 0;
let z = 0;
switch (face) {
case 0:
x = 1;
y = -t;
z = -s;
break;
case 1:
x = -1;
y = -t;
z = s;
break;
case 2:
x = s;
y = 1;
z = t;
break;
case 3:
x = s;
y = -1;
z = -t;
break;
case 4:
x = s;
y = -t;
z = 1;
break;
default:
x = -s;
y = -t;
z = -1;
break;
}
const invLen = 1 / Math.hypot(x, y, z);
return [x * invLen, y * invLen, z * invLen];
}
function evalStudioRadiance(
dx: number,
dy: number,
dz: number,
roughness: number,
): [number, number, number] {
const skyMix = Math.max(0, Math.min(1, dy * 0.5 + 0.5));
let r = 0.08 + 0.2 * skyMix;
let g = 0.1 + 0.28 * skyMix;
let b = 0.14 + 0.4 * skyMix;
const lobePow = 2 + Math.pow(1 - roughness, 2.2) * 34;
const lobeScale = 0.45 + 0.55 * (1 - roughness * 0.65);
const dKey = Math.max(0, dx * 0.44 + dy * 0.82 + dz * 0.36);
const k = Math.pow(dKey, lobePow) * 1.15 * lobeScale;
r += k * 1.0;
g += k * 0.96;
b += k * 0.88;
const dRim = Math.max(0, -dx * 0.72 + dy * 0.3 + -dz * 0.63);
const rm = Math.pow(dRim, lobePow * 0.75) * 0.75 * lobeScale;
r += rm * 0.42;
g += rm * 0.68;
b += rm * 1.0;
const dFill = Math.max(0, -dx * 0.35 + dy * 0.64 + dz * 0.68);
const fl = Math.pow(dFill, lobePow * 0.55) * 0.52 * lobeScale;
r += fl * 0.74;
g += fl * 0.84;
b += fl * 0.98;
const ground = Math.max(0, -dy);
const gb = Math.pow(ground, 2) * 0.14;
r += gb;
g += gb * 1.05;
b += gb * 1.15;
return [Math.min(1, r), Math.min(1, g), Math.min(1, b)];
}
function buildStudioFaceDataTextures(
size: number,
roughness: number,
): THREE.DataTexture[] {
const faces: THREE.DataTexture[] = [];
for (let face = 0; face < 6; face++) {
const data = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++) {
const t = ((y + 0.5) / size) * 2 - 1;
for (let x = 0; x < size; x++) {
const s = ((x + 0.5) / size) * 2 - 1;
const [dx, dy, dz] = cubemapFaceDirection(face, s, t);
const [lr, lg, lb] = evalStudioRadiance(dx, dy, dz, roughness);
const idx = (y * size + x) * 4;
data[idx] = Math.round(Math.pow(lr, 1 / 2.2) * 255);
data[idx + 1] = Math.round(Math.pow(lg, 1 / 2.2) * 255);
data[idx + 2] = Math.round(Math.pow(lb, 1 / 2.2) * 255);
data[idx + 3] = 255;
}
}
const faceTex = new THREE.DataTexture(
data,
size,
size,
THREE.RGBAFormat,
THREE.UnsignedByteType,
);
faceTex.colorSpace = THREE.SRGBColorSpace;
faces.push(faceTex);
}
return faces;
}
export function createStudioPMREMCubeTexture(): THREE.CubeTexture {
const baseSize = 64;
const maxLod = 5;
const baseFaces = buildStudioFaceDataTextures(baseSize, 0);
const cube = new THREE.CubeTexture(baseFaces);
cube.mapping = THREE.CubeReflectionMapping;
cube.format = THREE.RGBAFormat;
cube.type = THREE.UnsignedByteType;
cube.colorSpace = THREE.SRGBColorSpace;
cube.generateMipmaps = false;
cube.minFilter = THREE.LinearMipmapLinearFilter;
cube.magFilter = THREE.LinearFilter;
cube.mipmaps = [32, 16, 8, 4, 2, 1].map((sz, idx) => {
const r = Math.min(1, (idx + 1) / maxLod);
const roughness = 1 - Math.sqrt(Math.max(0, 1 - r));
return {
width: sz,
image: buildStudioFaceDataTextures(sz, roughness),
};
}) as unknown as THREE.CubeTexture[];
cube.isPMREMTexture = true;
cube.needsUpdate = true;
return cube;
}
let cachedSoftParticleTex: THREE.CanvasTexture | null = null;
export function getSoftParticleTexture(): THREE.CanvasTexture {
if (cachedSoftParticleTex) return cachedSoftParticleTex;
const size = 64;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (ctx) {
const half = size / 2;
const grad = ctx.createRadialGradient(half, half, 0, half, half, half);
grad.addColorStop(0.0, "rgba(255, 255, 255, 1.0)");
grad.addColorStop(0.25, "rgba(255, 255, 255, 0.72)");
grad.addColorStop(0.55, "rgba(255, 255, 255, 0.24)");
grad.addColorStop(0.85, "rgba(255, 255, 255, 0.05)");
grad.addColorStop(1.0, "rgba(255, 255, 255, 0.0)");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, size, size);
}
const tex = new THREE.CanvasTexture(canvas);
tex.generateMipmaps = false;
tex.minFilter = THREE.LinearFilter;
tex.magFilter = THREE.LinearFilter;
tex.needsUpdate = true;
cachedSoftParticleTex = tex;
return tex;
}

View file

@ -0,0 +1,246 @@
// Three.js WebGLRenderer, EffectComposer HDR bloom, OrbitControls, shadows.
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
import { getSettings } from "../../api.js";
import { getColorMode, isReducedEffects } from "../../theme.js";
import {
createStudioPMREMCubeTexture,
getSoftParticleTexture,
} from "./studioEnv.js";
export interface ViewOptions {
onFrame?: (dt: number, elapsed: number) => void;
fov?: number;
near?: number;
far?: number;
background?: number;
}
export interface ManagedView {
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer;
controls: OrbitControls;
addStars: (count?: number, radius?: number) => THREE.Points;
dispose: () => void;
}
export function createView(
container: HTMLElement,
opts: ViewOptions = {},
): ManagedView {
const quality = getSettings().quality;
const initW = Math.max(1, container.clientWidth);
const initH = Math.max(1, container.clientHeight);
const renderer = new THREE.WebGLRenderer({
antialias: quality !== "low",
alpha: true,
powerPreference: "high-performance",
});
const maxDpr = quality === "low" ? 1 : quality === "medium" ? 1.5 : 2;
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, maxDpr));
renderer.setSize(initW, initH);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.outputColorSpace = THREE.SRGBColorSpace;
if (quality !== "low") {
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.VSMShadowMap;
}
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
let envTex: THREE.CubeTexture | null = null;
try {
envTex = createStudioPMREMCubeTexture();
scene.environment = envTex;
scene.environmentIntensity = 0.85;
} catch {}
const aspect = initW / initH;
const camera = new THREE.PerspectiveCamera(
opts.fov ?? 48,
aspect,
opts.near ?? 0.2,
opts.far ?? 1e9,
);
let composer: EffectComposer | null = null;
let renderPass: RenderPass | null = null;
let bloomPass: UnrealBloomPass | null = null;
let outputPass: OutputPass | null = null;
const shouldUseBloom = () =>
quality !== "low" && !isReducedEffects() && getColorMode() === "dark";
try {
composer = new EffectComposer(renderer);
composer.setPixelRatio(renderer.getPixelRatio());
composer.setSize(initW, initH);
renderPass = new RenderPass(scene, camera);
bloomPass = new UnrealBloomPass(
new THREE.Vector2(initW, initH),
0.55,
0.4,
0.82,
);
outputPass = new OutputPass();
composer.addPass(renderPass);
composer.addPass(bloomPass);
composer.addPass(outputPass);
} catch {
composer = null;
}
let hasStars = false;
const applyScenePalette = () => {
const light = getColorMode() === "light";
const reduced = isReducedEffects();
if (opts.background !== undefined) {
scene.background = new THREE.Color(
light && opts.background === 0x0b0e14
? hasStars
? 0x1e293b
: 0xdce5f0
: opts.background,
);
} else {
scene.background = new THREE.Color(
light ? (hasStars ? 0x1e293b : 0xdce5f0) : 0x0b0e14,
);
}
renderer.toneMappingExposure = light ? (reduced ? 1.0 : 1.06) : 1.12;
if (bloomPass) {
bloomPass.enabled = shouldUseBloom();
}
};
applyScenePalette();
window.addEventListener("sgywftp:theme-changed", applyScenePalette);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.06;
scene.add(new THREE.HemisphereLight(0xb8d4ff, 0x161f30, 0.78));
const keyLight = new THREE.DirectionalLight(0xfff5e6, 2.35);
keyLight.position.set(60, 110, 48);
if (quality !== "low") {
keyLight.castShadow = true;
const shRes = quality === "high" ? 2048 : 1024;
keyLight.shadow.mapSize.set(shRes, shRes);
keyLight.shadow.camera.near = 5;
keyLight.shadow.camera.far = 360;
keyLight.shadow.camera.left = -95;
keyLight.shadow.camera.right = 95;
keyLight.shadow.camera.top = 120;
keyLight.shadow.camera.bottom = -65;
keyLight.shadow.blurSamples = 8;
keyLight.shadow.radius = 2.5;
keyLight.shadow.bias = -0.0002;
}
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5ea3ff, 0.85);
rimLight.position.set(-72, 32, -82);
scene.add(rimLight);
let raf = 0;
let disposed = false;
let lastT = performance.now();
let elapsed = 0;
function resize() {
if (disposed || !container.clientWidth || !container.clientHeight) return;
const w = container.clientWidth;
const h = container.clientHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
if (composer) {
composer.setPixelRatio(renderer.getPixelRatio());
composer.setSize(w, h);
}
}
const ro = new ResizeObserver(resize);
ro.observe(container);
window.addEventListener("resize", resize);
function animate() {
if (disposed) return;
const now = performance.now();
const dt = Math.min(0.1, (now - lastT) / 1000);
lastT = now;
elapsed += dt;
opts.onFrame?.(dt, elapsed);
controls.update();
if (composer && shouldUseBloom()) {
composer.render(dt);
} else {
renderer.render(scene, camera);
}
if (!disposed) {
raf = requestAnimationFrame(animate);
}
}
raf = requestAnimationFrame(animate);
return {
scene,
camera,
renderer,
controls,
addStars(count = 3500, radius = 6000) {
hasStars = true;
applyScenePalette();
const geo = new THREE.BufferGeometry();
const pos = new Float32Array(count * 3);
const col = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
const r = radius * (0.75 + Math.random() * 0.45);
pos[i * 3] = r * Math.sin(phi) * Math.cos(theta);
pos[i * 3 + 1] = r * Math.cos(phi);
pos[i * 3 + 2] = r * Math.sin(phi) * Math.sin(theta);
const tint = Math.random();
const mag = 0.55 + Math.random() * 0.5;
col[i * 3] = (tint > 0.85 ? 1.0 : 0.76 + tint * 0.22) * mag;
col[i * 3 + 1] = (0.82 + tint * 0.16) * mag;
col[i * 3 + 2] = (tint < 0.25 ? 0.74 : 1.0) * mag;
}
geo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
const pts = new THREE.Points(
geo,
new THREE.PointsMaterial({
size: Math.max(2.4, radius / 520),
sizeAttenuation: true,
map: getSoftParticleTexture(),
alphaTest: 0.01,
vertexColors: true,
transparent: true,
opacity: 0.92,
depthWrite: false,
blending: THREE.AdditiveBlending,
}),
);
scene.add(pts);
return pts;
},
dispose() {
disposed = true;
cancelAnimationFrame(raf);
ro.disconnect();
window.removeEventListener("resize", resize);
window.removeEventListener("sgywftp:theme-changed", applyScenePalette);
controls.dispose();
renderPass?.dispose?.();
bloomPass?.dispose?.();
outputPass?.dispose?.();
composer?.dispose?.();
envTex?.dispose();
renderer.dispose();
if (renderer.domElement.parentNode === container) {
container.removeChild(renderer.domElement);
}
scene.traverse((o: any) => {
o.geometry?.dispose?.();
if (o.material) {
const mats = Array.isArray(o.material) ? o.material : [o.material];
mats.forEach((m: any) => m.dispose?.());
}
});
},
};
}

View file

@ -0,0 +1,208 @@
// Builds compressed Three.js solar system, planet orbit rings, and NASA deep-space asset meshes.
import * as THREE from "three";
import {
AU_KM,
NASA_ASSETS,
PLANETS,
bodyPosition,
} from "../../shared/ephemeris.js";
export interface SolarSystemHandle {
group: THREE.Group;
planetMeshes: Map<string, THREE.Mesh>;
assetMeshes: Map<string, THREE.Mesh>;
update: (simTime: number, spinTime?: number) => void;
}
export function compressDistanceKm(km: number): number {
if (km <= 0) return 0;
const au = km / AU_KM;
return Math.pow(au, 0.56) * 240;
}
export function compressedPosition(
bodyId: string,
simTime: number,
): THREE.Vector3 {
if (bodyId === "sun") return new THREE.Vector3(0, 0, 0);
if (bodyId === "moon") {
const earth = compressedPosition("earth", simTime);
const moonRaw = bodyPosition("moon", simTime);
const earthRaw = bodyPosition("earth", simTime);
const dx = moonRaw[0] - earthRaw[0];
const dy = moonRaw[1] - earthRaw[1];
const dz = moonRaw[2] - earthRaw[2];
const len = Math.max(1, Math.hypot(dx, dy, dz));
const moonOrbitR = 14;
return new THREE.Vector3(
earth.x + (dx / len) * moonOrbitR,
earth.y + (dy / len) * moonOrbitR,
earth.z + (dz / len) * moonOrbitR,
);
}
const raw = bodyPosition(bodyId, simTime);
const dist = Math.hypot(raw[0], raw[1], raw[2]);
if (dist < 1) return new THREE.Vector3(0, 0, 0);
const compR = compressDistanceKm(dist);
return new THREE.Vector3(
(raw[0] / dist) * compR,
(raw[1] / dist) * compR,
(raw[2] / dist) * compR,
);
}
export function buildSolarSystem(
scene: THREE.Scene,
opts: { slowSpin?: boolean; showAssets?: boolean } = {},
): SolarSystemHandle {
const group = new THREE.Group();
const planetMeshes = new Map<string, THREE.Mesh>();
const assetMeshes = new Map<string, THREE.Mesh>();
const sun = new THREE.Mesh(
new THREE.SphereGeometry(22, 32, 32),
new THREE.MeshBasicMaterial({ color: 0xffd27a }),
);
const corona = new THREE.Mesh(
new THREE.SphereGeometry(32, 32, 32),
new THREE.MeshBasicMaterial({
color: 0xff9a3c,
transparent: true,
opacity: 0.16,
}),
);
const sunLight = new THREE.PointLight(0xfff5dc, 2.8, 0, 0);
group.add(sun, corona, sunLight);
planetMeshes.set("sun", sun);
const visualRadius: Record<string, number> = {
mercury: 2.6,
venus: 4.1,
earth: 4.6,
moon: 1.6,
mars: 3.4,
asteroid: 1.5,
jupiter: 11.5,
saturn: 9.6,
};
for (const body of PLANETS) {
if (body.id === "sun") continue;
if (!body.parent) {
const r = compressDistanceKm(body.aKm);
const ring = new THREE.Mesh(
new THREE.RingGeometry(r - 0.35, r + 0.35, 160),
new THREE.MeshBasicMaterial({
color: body.id === "earth" ? 0x60a5fa : 0x2c3a54,
transparent: true,
opacity: body.id === "earth" ? 0.48 : 0.32,
side: THREE.DoubleSide,
}),
);
ring.rotation.x = -Math.PI / 2;
ring.rotation.z = (body.incDeg * Math.PI) / 180;
group.add(ring);
}
const rVis = visualRadius[body.id] ?? 3.5;
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(rVis, 24, 24),
new THREE.MeshStandardMaterial({
color: body.color,
roughness: 0.72,
metalness: 0.08,
}),
);
mesh.userData.bodyId = body.id;
mesh.userData.label = body.name;
if (body.id === "saturn") {
const satRing = new THREE.Mesh(
new THREE.RingGeometry(rVis * 1.35, rVis * 2.2, 48),
new THREE.MeshBasicMaterial({
color: 0xd6c391,
transparent: true,
opacity: 0.55,
side: THREE.DoubleSide,
}),
);
satRing.rotation.x = Math.PI * 0.4;
mesh.add(satRing);
}
group.add(mesh);
planetMeshes.set(body.id, mesh);
}
const beltCount = 650;
const beltGeo = new THREE.BufferGeometry();
const beltPos = new Float32Array(beltCount * 3);
const rInner = compressDistanceKm(2.15 * AU_KM);
const rOuter = compressDistanceKm(3.2 * AU_KM);
for (let i = 0; i < beltCount; i++) {
const ang = Math.random() * Math.PI * 2;
const rr = rInner + Math.random() * (rOuter - rInner);
beltPos[i * 3] = Math.cos(ang) * rr;
beltPos[i * 3 + 1] = (Math.random() - 0.5) * 6;
beltPos[i * 3 + 2] = Math.sin(ang) * rr;
}
beltGeo.setAttribute("position", new THREE.BufferAttribute(beltPos, 3));
group.add(
new THREE.Points(
beltGeo,
new THREE.PointsMaterial({
color: 0x64748b,
size: 1.4,
transparent: true,
opacity: 0.65,
}),
),
);
if (opts.showAssets !== false) {
for (const asset of NASA_ASSETS) {
const m = new THREE.Mesh(
new THREE.SphereGeometry(0.9, 10, 10),
new THREE.MeshBasicMaterial({ color: 0x60a5fa }),
);
m.userData.assetId = asset.id;
m.userData.asset = asset;
group.add(m);
assetMeshes.set(asset.id, m);
}
}
scene.add(group);
return {
group,
planetMeshes,
assetMeshes,
update(simTime: number, spinTime = 0) {
for (const [id, mesh] of planetMeshes) {
if (id === "sun") {
mesh.rotation.y = spinTime * 0.08;
continue;
}
const p = compressedPosition(id, simTime);
mesh.position.copy(p);
mesh.rotation.y = spinTime * 0.25;
}
for (const asset of NASA_ASSETS) {
const mesh = assetMeshes.get(asset.id);
if (!mesh) continue;
if (asset.parentBody === "sun") {
const ang = asset.phaseRad + spinTime * 0.015;
const r = compressDistanceKm(7.5 * AU_KM);
mesh.position.set(Math.cos(ang) * r, 35, Math.sin(ang) * r);
} else {
const parentPos = compressedPosition(asset.parentBody, simTime);
const ang =
(simTime / Math.max(3000, asset.periodSec)) * Math.PI * 2 +
asset.phaseRad;
const baseR = visualRadius[asset.parentBody] ?? 4;
const orbitR = baseR + asset.orbitRadiusMult * 3.2;
const inc = (asset.incDeg * Math.PI) / 180;
mesh.position.set(
parentPos.x + Math.cos(ang) * orbitR,
parentPos.y + Math.sin(ang) * orbitR * Math.sin(inc),
parentPos.z + Math.sin(ang) * orbitR * Math.cos(inc),
);
}
}
if (opts.slowSpin) {
group.rotation.y = spinTime * 0.012;
}
},
};
}

18
src/client/ui.ts Normal file
View file

@ -0,0 +1,18 @@
// Re-export DOM helpers, notifications, modals, formatters, and glossary tooltips.
export {
type ChildInput,
h,
clear,
fmtMoney,
fmtNum,
fmtDuration,
} from "./ui/dom.js";
export {
type NotificationEntry,
renderNotificationDrawer,
initNotificationDrawer,
pushNotification,
toast,
} from "./ui/notifications.js";
export { type ModalAction, modal } from "./ui/modal.js";
export { hideTooltip, initTooltipController, term } from "./ui/tooltip.js";

82
src/client/ui/dom.ts Normal file
View file

@ -0,0 +1,82 @@
// Lightweight DOM element builder, element clear helper, and number formatters.
import { playClick } from "../sound.js";
export type ChildInput =
Node | string | number | null | undefined | false | ChildInput[];
// h my belowed, I love making everything OOP to the sky
export function h<K extends keyof HTMLElementTagNameMap>(
tag: K,
attrs: Record<string, any> = {},
...children: ChildInput[]
): HTMLElementTagNameMap[K] {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs ?? {})) {
if (v === null || v === undefined || v === false) continue;
if (k === "class") {
el.className = String(v);
} else if (k === "style" && typeof v === "object") {
Object.assign(el.style, v);
} else if (k.startsWith("on") && typeof v === "function") {
const eventName = k.slice(2).toLowerCase();
el.addEventListener(eventName, (ev) => {
if (eventName === "click" && tag === "button") playClick();
v(ev);
});
} else if (
k === "checked" ||
k === "disabled" ||
k === "selected" ||
k === "value"
) {
(el as any)[k] = v;
} else {
el.setAttribute(k, v === true ? "" : String(v));
}
}
const append = (item: ChildInput): void => {
if (item === null || item === undefined || item === false) return;
if (Array.isArray(item)) {
item.forEach(append);
} else if (item instanceof Node) {
el.appendChild(item);
} else {
el.appendChild(document.createTextNode(String(item)));
}
};
append(children);
return el;
}
export function clear(el: HTMLElement): void {
el.innerHTML = "";
}
export function fmtMoney(n: number | null | undefined): string {
if (n == null || !Number.isFinite(n)) return "—";
const abs = Math.abs(n);
const sign = n < 0 ? "-" : "";
if (abs >= 1e9) return `${sign}$${(abs / 1e9).toFixed(2)}B`;
if (abs >= 1e6) return `${sign}$${(abs / 1e6).toFixed(1)}M`;
if (abs >= 1e3) return `${sign}$${(abs / 1e3).toFixed(0)}k`;
return `${sign}$${Math.round(abs)}`;
}
export function fmtNum(n: number | null | undefined, digits = 0): string {
if (n == null || !Number.isFinite(n)) return "—";
return n.toLocaleString(undefined, {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
});
}
export function fmtDuration(sec: number | null | undefined): string {
if (sec == null || !Number.isFinite(sec)) return "—";
const s = Math.max(0, Math.round(sec));
const hPart = Math.floor(s / 3600);
const mPart = Math.floor((s % 3600) / 60);
const sPart = s % 60;
if (hPart > 0) return `${hPart}h ${mPart}m`;
if (mPart > 0) return `${mPart}m ${sPart}s`;
return `${sPart}s`;
}

52
src/client/ui/modal.ts Normal file
View file

@ -0,0 +1,52 @@
// Modal dialog builder.
import { type ChildInput, h } from "./dom.js";
export interface ModalAction {
label: string;
kind?: string;
onClick?: () => boolean | void | Promise<boolean | void>;
}
export function modal(
title: string,
body: ChildInput,
actions: ModalAction[] = [],
) {
const modalRoot = document.getElementById("modal-root") ?? document.body;
const overlay = h("div", { class: "modal-overlay" });
const card = h("div", { class: "panel modal" }, h("h3", {}, title));
const contentWrap = h("div", {}, body);
card.appendChild(contentWrap);
const close = () => overlay.remove();
if (actions.length) {
const footer = h("div", {
class: "row",
style: { justifyContent: "flex-end", marginTop: "18px" },
});
for (const act of actions) {
const btn = h(
"button",
{
class: `btn ${act.kind ?? "ghost"} sm`,
onclick: async () => {
if (!act.onClick) {
close();
return;
}
const res = await act.onClick();
if (res !== false) close();
},
},
act.label,
);
footer.appendChild(btn);
}
card.appendChild(footer);
}
overlay.addEventListener("click", (ev) => {
if (ev.target === overlay && actions.length === 0) close();
});
overlay.appendChild(card);
modalRoot.appendChild(overlay);
return { el: card, contentWrap, close };
}

View file

@ -0,0 +1,275 @@
// Prettier what the hell did you do to my h's
import { playAlert } from "../sound.js";
import { clear, h } from "./dom.js";
export interface NotificationEntry {
id: number;
timeLabel: string;
message: string;
kind: "info" | "ok" | "err" | "warn";
scope: "mine" | "world";
}
const NOTIF_MAX = 80;
const notifItems: NotificationEntry[] = [];
let notifNextId = 1;
let notifOpen = false;
let notifBarMinimized = false;
let notifFilter: "all" | "mine" | "world" = "all";
let notifUnread = 0;
function formatClockTime(): string {
const d = new Date();
return d.toTimeString().slice(0, 8);
}
export function renderNotificationDrawer(): void {
const root = document.getElementById("notif-drawer-root");
if (!root) return;
clear(root);
if (notifOpen) {
notifUnread = 0;
}
const filtered = notifItems.filter(
(n) => notifFilter === "all" || n.scope === notifFilter,
);
const latest = notifItems[0];
const wrap = h("div", {
class: `notif-drawer-wrap ${notifOpen ? "open" : ""}`,
});
if (notifOpen) {
const listEl = h("div", { class: "notif-list" });
if (!filtered.length) {
listEl.appendChild(
h(
"p",
{
class: "dim mono",
style: { fontSize: "11px", padding: "10px 4px" },
},
"No telemetry events in this channel.",
),
);
} else {
for (const item of filtered) {
listEl.appendChild(
h(
"div",
{ class: `notif-item ${item.kind}` },
h(
"div",
{ class: "spread", style: { marginBottom: "2px" } },
h(
"span",
{ class: `badge ${item.scope === "mine" ? "ok" : "info"}` },
item.scope === "mine" ? "YOU" : "WORLD",
),
h(
"span",
{ class: "faint mono", style: { fontSize: "9px" } },
item.timeLabel,
),
),
h("div", { class: "notif-msg" }, item.message),
),
);
}
}
const drawer = h(
"div",
{ class: "panel notif-drawer" },
h(
"div",
{ class: "notif-header spread" },
h(
"span",
{
class: "mono accent",
style: { fontSize: "11px", fontWeight: "700" },
},
"COMMS & TELEMETRY",
),
h(
"div",
{ class: "row", style: { gap: "4px" } },
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
notifItems.length = 0;
notifUnread = 0;
renderNotificationDrawer();
},
},
"Clear",
),
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
notifOpen = false;
renderNotificationDrawer();
},
},
"Hide ▾",
),
),
),
h(
"div",
{ class: "notif-tabs" },
...(
[
["all", `ALL (${notifItems.length})`],
[
"mine",
`MY AGENCY (${notifItems.filter((i) => i.scope === "mine").length})`,
],
[
"world",
`AI & WORLD (${notifItems.filter((i) => i.scope === "world").length})`,
],
] as const
).map(([key, label]) =>
h(
"button",
{
class: `btn xs ${notifFilter === key ? "selected" : "ghost"}`,
onClick: () => {
notifFilter = key;
renderNotificationDrawer();
},
},
label,
),
),
),
listEl,
);
wrap.appendChild(drawer);
}
if (notifBarMinimized && !notifOpen) {
wrap.appendChild(
h(
"button",
{
class: "btn xs notif-mini-pill",
title: "Show Comms & World Event Log",
onClick: () => {
notifBarMinimized = false;
renderNotificationDrawer();
},
},
"COMMS",
notifUnread > 0
? h("span", { class: "badge info" }, `${notifUnread}`)
: null,
),
);
} else {
const toggleBar = h(
"div",
{ class: "notif-toggle-bar" },
h(
"button",
{
class: "notif-toggle-main",
onClick: () => {
notifOpen = !notifOpen;
if (notifOpen) notifUnread = 0;
renderNotificationDrawer();
},
},
h(
"span",
{
class: "mono accent",
style: { fontSize: "10px", fontWeight: "700" },
},
"COMMS",
),
h(
"span",
{ class: `badge ${notifUnread > 0 ? "info" : ""}` },
notifUnread > 0 ? `${notifUnread} NEW` : `${notifItems.length}`,
),
h(
"span",
{ class: "notif-preview dim mono" },
latest ? latest.message : "Monitoring world telemetry...",
),
h(
"span",
{ class: "mono dim", style: { fontSize: "10px" } },
notifOpen ? "▾" : "▴",
),
),
!notifOpen
? h(
"button",
{
class: "notif-hide-btn",
title: "Minimize comms bar",
onClick: () => {
notifBarMinimized = true;
renderNotificationDrawer();
},
},
"×",
)
: null,
);
wrap.appendChild(toggleBar);
}
root.appendChild(wrap);
}
export function initNotificationDrawer(): void {
renderNotificationDrawer();
}
export function pushNotification(
message: string,
kind: "info" | "ok" | "err" | "warn" = "info",
scope: "mine" | "world" = "world",
countAsUnread = true,
): void {
notifItems.unshift({
id: notifNextId++,
timeLabel: formatClockTime(),
message,
kind,
scope,
});
if (notifItems.length > NOTIF_MAX) {
notifItems.length = NOTIF_MAX;
}
if (!notifOpen && countAsUnread) {
notifUnread++;
}
renderNotificationDrawer();
}
export function toast(
message: string,
kind: "info" | "ok" | "err" | "warn" = "info",
logToDrawer = true,
): void {
const root = document.getElementById("toast-root");
if (logToDrawer) {
pushNotification(message, kind, "mine", false);
}
if (!root) return;
if (kind === "err") playAlert("err");
else if (kind === "ok") playAlert("ok");
const cls = kind === "warn" ? "info" : kind;
const node = h("div", { class: `toast ${cls}` }, message);
root.appendChild(node);
setTimeout(() => {
node.style.opacity = "0";
node.style.transition = "opacity 0.25s";
setTimeout(() => node.remove(), 260);
}, 4200);
}

162
src/client/ui/tooltip.ts Normal file
View file

@ -0,0 +1,162 @@
// So like, wikipedia. oh wait no I should've written that to glossary.ts
import { TERMINOLOGY_GLOSSARY, type GlossaryKey } from "../glossary.js";
import { clear, h } from "./dom.js";
let tooltipEl: HTMLElement | null = null;
let tooltipAnchor: HTMLElement | null = null;
let tooltipPinned = false;
let tooltipInited = false;
export function hideTooltip(): void {
tooltipPinned = false;
if (tooltipAnchor) {
tooltipAnchor.removeAttribute("aria-describedby");
tooltipAnchor = null;
}
if (tooltipEl) {
tooltipEl.hidden = true;
}
}
function ensureTooltipEl(): HTMLElement {
if (tooltipEl && tooltipEl.isConnected) return tooltipEl;
tooltipEl = h("div", {
id: "hud-tooltip",
class: "hud-tooltip",
role: "tooltip",
hidden: true,
});
document.body.appendChild(tooltipEl);
return tooltipEl;
}
function showTooltipFor(anchor: HTMLElement): void {
const key = anchor.getAttribute("data-tip-key") as GlossaryKey | null;
if (!key) return;
const entry = TERMINOLOGY_GLOSSARY[key];
if (!entry) return;
const tip = ensureTooltipEl();
clear(tip);
tip.append(
h("div", { class: "hud-tooltip-cat" }, entry.category),
h("div", { class: "hud-tooltip-title" }, entry.title),
h("div", { class: "hud-tooltip-body" }, entry.summary),
);
if (entry.formula) {
tip.appendChild(h("div", { class: "hud-tooltip-formula" }, entry.formula));
}
tip.hidden = false;
tip.style.left = "0px";
tip.style.top = "0px";
if (tooltipAnchor && tooltipAnchor !== anchor) {
tooltipAnchor.removeAttribute("aria-describedby");
}
tooltipAnchor = anchor;
anchor.setAttribute("aria-describedby", "hud-tooltip");
const pad = 10;
const rect = anchor.getBoundingClientRect();
const tipRect = tip.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
let left = rect.left + rect.width / 2 - tipRect.width / 2;
left = Math.max(pad, Math.min(vw - tipRect.width - pad, left));
let top = rect.top - tipRect.height - 8;
if (top < pad) {
top = Math.min(vh - tipRect.height - pad, rect.bottom + 8);
}
tip.style.left = `${Math.round(left)}px`;
tip.style.top = `${Math.round(Math.max(pad, top))}px`;
}
export function initTooltipController(): void {
if (tooltipInited) return;
tooltipInited = true;
document.addEventListener("pointerover", (ev) => {
const target = (ev.target as HTMLElement | null)?.closest?.(
".tip-badge",
) as HTMLElement | null;
if (target) {
tooltipPinned = false;
showTooltipFor(target);
}
});
document.addEventListener("pointerout", (ev) => {
if (tooltipPinned) return;
const fromBadge = (ev.target as HTMLElement | null)?.closest?.(
".tip-badge",
) as HTMLElement | null;
if (!fromBadge) return;
const toEl = ev.relatedTarget as HTMLElement | null;
if (toEl?.closest?.(".tip-badge, #hud-tooltip")) return;
hideTooltip();
});
document.addEventListener("focusin", (ev) => {
const target = (ev.target as HTMLElement | null)?.closest?.(
".tip-badge",
) as HTMLElement | null;
if (target) {
showTooltipFor(target);
}
});
document.addEventListener("focusout", (ev) => {
if (tooltipPinned) return;
const fromBadge = (ev.target as HTMLElement | null)?.closest?.(
".tip-badge",
) as HTMLElement | null;
if (fromBadge) hideTooltip();
});
document.addEventListener("click", (ev) => {
const badge = (ev.target as HTMLElement | null)?.closest?.(
".tip-badge",
) as HTMLElement | null;
if (badge) {
ev.preventDefault();
ev.stopPropagation();
if (
tooltipPinned &&
tooltipAnchor === badge &&
tooltipEl &&
!tooltipEl.hidden
) {
hideTooltip();
} else {
tooltipPinned = true;
showTooltipFor(badge);
}
return;
}
if (!(ev.target as HTMLElement | null)?.closest?.("#hud-tooltip")) {
hideTooltip();
}
});
document.addEventListener("keydown", (ev) => {
if (ev.key === "Escape") hideTooltip();
});
window.addEventListener("scroll", () => hideTooltip(), {
capture: true,
passive: true,
});
}
export function term(
label: string,
key: GlossaryKey,
extraClass?: string,
): HTMLElement {
const entry = TERMINOLOGY_GLOSSARY[key];
return h(
"span",
{ class: extraClass ? `term-wrap ${extraClass}` : "term-wrap" },
h("span", { class: "term-text" }, label),
h(
"button",
{
type: "button",
class: "tip-badge",
"data-tip-key": key,
"aria-label": `Info: ${entry?.title ?? label}`,
},
"?",
),
);
}