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}`,
},
"?",
),
);
}

10
src/server/ai.ts Normal file
View file

@ -0,0 +1,10 @@
// Export AI agency seeding, rocket synthesis, simulation tick, and leaderboard APIs.
export {
AI_DEFS,
STARTUP_POOL,
seedAI,
type AiDifficulty,
type AiAgencyDef,
} from "./ai/agencies.js";
export { synthesizeAiRocket } from "./ai/synthesizer.js";
export { aiTick, getLeaderboard } from "./ai/runner.js";

459
src/server/ai/agencies.ts Normal file
View file

@ -0,0 +1,459 @@
// AI competitor rosters, seeding/migration, tech unlocking, material/fairing selection, and dry-run scoring.
import { PARTS, SPONSORS } from "../catalogs.js";
import { emit } from "../events.js";
import { ML_AI_DEFS } from "../ml_ai.js";
import { getDb, putAgency } from "../store.js";
import {
autoTuneFlightParams,
getDifficultyProfile,
isPartUnlocked,
TECH_TREE,
} from "../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
FlightParams,
RocketDesign,
SimResult,
SpaceWeather,
} from "../../shared/types.js";
export type AiDifficulty = "enthusiast" | "engineer" | "director";
export interface AiAgencyDef {
name: string;
sponsorId: string;
difficulty: AiDifficulty;
skill: number;
aiType?: "standard" | "ml";
}
export const AI_DIFFICULTIES = new Set<AiDifficulty>([
"enthusiast",
"engineer",
"director",
]);
export const AI_DEFS: AiAgencyDef[] = [
{
name: "Jensen's Ultra Space Agency",
sponsorId: "gsdistance",
difficulty: "director",
skill: 0.96,
},
{ name: "SpaceX v2", sponsorId: "nasa", difficulty: "director", skill: 0.93 },
{
name: "Periapsis Heavy",
sponsorId: "jaxa",
difficulty: "engineer",
skill: 0.86,
},
{
name: "Dynamics & Shit",
sponsorId: "esa",
difficulty: "engineer",
skill: 0.78,
},
{
name: "Rei-Zen Corp",
sponsorId: "jaxa",
difficulty: "engineer",
skill: 0.72,
},
{
name: "Apotheosis",
sponsorId: "isro",
difficulty: "enthusiast",
skill: 0.62,
},
{
name: "Money & Co.",
sponsorId: "gsdistance",
difficulty: "enthusiast",
skill: 0.54,
},
{
name: "The Compendium Haters",
sponsorId: "gsdistance",
difficulty: "director",
skill: 0.86,
},
];
export const STARTUP_POOL: AiAgencyDef[] = [
{
name: "Helios Deep Space",
sponsorId: "jaxa",
difficulty: "director",
skill: 0.92,
},
{
name: "Thrust Vector Inc.",
sponsorId: "nasa",
difficulty: "director",
skill: 0.9,
},
{
name: "Le' Thronglers",
sponsorId: "esa",
difficulty: "engineer",
skill: 0.82,
},
{
name: "Orbital Catworks",
sponsorId: "csa",
difficulty: "engineer",
skill: 0.74,
},
{
name: "Valiant Launcher Ltd.",
sponsorId: "isro",
difficulty: "enthusiast",
skill: 0.64,
},
{
name: "Fortnite Syndrome LLC",
sponsorId: "gsdistance",
difficulty: "enthusiast",
skill: 0.56,
},
];
export const INSOLVENCY_THRESHOLD = 6_000_000;
let seeded = false;
export function clamp01(val: number): number {
if (!Number.isFinite(val)) return 0.65;
return Math.max(0, Math.min(1, Number(val)));
}
export function defaultTechsForDifficulty(difficulty: AiDifficulty): string[] {
return difficulty === "enthusiast"
? ["starter", "cryo-hydrolox"]
: ["starter"];
}
function mapLegacyDifficulty(skill: number, name: string): AiDifficulty {
const fromDef = [...AI_DEFS, ...STARTUP_POOL, ...ML_AI_DEFS].find(
(d) => d.name === name,
);
if (fromDef) return fromDef.difficulty;
if (skill >= 0.85) return "director";
if (skill >= 0.58) return "engineer";
return "enthusiast";
}
export function makeAiAgency(def: AiAgencyDef): AgencyState {
const skill = clamp01(def.skill);
const profile = getDifficultyProfile(def.difficulty);
const sponsor = SPONSORS.find((s) => s.id === def.sponsorId);
return {
name: def.name,
difficulty: def.difficulty,
sponsorId: def.sponsorId,
missionId: null,
activeContract: null,
treasury: Math.round(
profile.startingFunds * (sponsor?.budgetMult ?? 1.0) + skill * 4_000_000,
),
reputation: Math.round((1 + skill * 5) * 10) / 10,
missionsCompleted: Math.floor(skill * 2),
missionsFailed: Math.floor((1 - skill) * 2),
earnedTotal: 0,
rocketDesign: null,
crewConfig: { crewSize: 0, lifeSupport: 1 },
activeMissions: [],
contractHistory: [],
bankrupt: false,
bankruptAt: null,
bailoutsTaken: 0,
unlockedTechs: defaultTechsForDifficulty(def.difficulty),
partHeritage: {},
staticFiredDesignHash: null,
launchInsured: false,
groundedUntilSimTime: null,
padDamagedUntilSimTime: null,
casualtiesTotal: 0,
lastSettlement: null,
terminatedReason: null,
aiCooldownUntilSimTime: null,
aiContractReadyAtSimTime: null,
isAI: true,
aiType: def.aiType ?? "standard",
aiSkill: skill,
...(def.aiType === "ml"
? {
mlStats: {
episodes: 0,
avgReward: 0,
backend: "ts-contextual-bandit",
},
}
: {}),
};
}
export function seedAI(): void {
const db = getDb();
let migrated = false;
for (const agency of Object.values(db.agencies)) {
if (!agency.isAI) continue;
let dirty = false;
if ("aiAggression" in (agency as unknown as Record<string, unknown>)) {
delete (agency as unknown as Record<string, unknown>).aiAggression;
dirty = true;
}
const def = [...AI_DEFS, ...STARTUP_POOL, ...ML_AI_DEFS].find(
(d) => d.name === agency.name,
);
if (!agency.aiType) {
agency.aiType = (def as AiAgencyDef | undefined)?.aiType ?? "standard";
dirty = true;
}
const targetMinSkill = def ? def.skill : 0.65;
const skill = clamp01(
Math.max(agency.aiSkill ?? targetMinSkill, targetMinSkill),
);
if (agency.aiSkill !== skill) {
agency.aiSkill = skill;
dirty = true;
}
if (!AI_DIFFICULTIES.has(agency.difficulty as AiDifficulty)) {
agency.difficulty = mapLegacyDifficulty(skill, agency.name);
dirty = true;
}
if (!agency.unlockedTechs?.length) {
agency.unlockedTechs = defaultTechsForDifficulty(
agency.difficulty as AiDifficulty,
);
dirty = true;
}
if (!agency.partHeritage) {
agency.partHeritage = {};
dirty = true;
}
if (agency.bailoutsTaken == null) {
agency.bailoutsTaken = 0;
dirty = true;
}
if (agency.aiCooldownUntilSimTime === undefined) {
agency.aiCooldownUntilSimTime = null;
dirty = true;
}
if (agency.aiContractReadyAtSimTime === undefined) {
agency.aiContractReadyAtSimTime = null;
dirty = true;
}
if (dirty) {
putAgency(agency.name, agency);
migrated = true;
}
}
if (!seeded || migrated) {
seeded = true;
for (const def of [
...AI_DEFS,
...ML_AI_DEFS.map((m) => ({ ...m, aiType: "ml" as const })),
]) {
if (!db.agencies[def.name]) {
putAgency(def.name, makeAiAgency(def));
}
}
}
}
export function effectivePayloadMass(
agency: AgencyState,
contract: ContractOffer,
): number {
const crew = agency.crewConfig;
let extra = 0;
if (crew && contract.crewed) {
extra += crew.crewSize * 85;
extra += crew.crewSize * 15 * crew.lifeSupport;
extra += 500 * crew.lifeSupport;
}
return contract.payloadMass + extra;
}
export function chooseFairingForPayload(
agency: AgencyState,
payloadId?: string | null,
): string {
const p = payloadId ? PARTS.find((x) => x.id === payloadId) : null;
const fits = (fid: string) => {
const f = PARTS.find((x) => x.id === fid);
if (!f || !p) return true;
const maxD = f.maxPayloadDiameter ?? f.diameter * 0.9;
const maxL = f.maxPayloadLength ?? f.length * 0.9;
return p.diameter <= maxD && p.length <= maxL;
};
for (const cand of ["fairing-small", "fairing-standard", "fairing-wide"]) {
if (fits(cand) && isPartUnlocked(cand, agency)) return cand;
}
return isPartUnlocked("fairing-standard", agency)
? "fairing-standard"
: "fairing-small";
}
export function pickUnlockedMaterial(
agency: AgencyState,
skill: number,
role: "booster" | "upper",
weather: SpaceWeather,
target: string,
): string {
if (
role === "booster" &&
(weather === "solar-storm" ||
weather === "radiation-storm" ||
target === "solar") &&
isPartUnlocked("stainless-304l", agency)
) {
return "stainless-304l";
}
if (
role === "upper" &&
isPartUnlocked("carbon-epoxy", agency) &&
skill >= 0.65
) {
return "carbon-epoxy";
}
if (isPartUnlocked("al-li-2195", agency) && skill >= 0.48) {
return "al-li-2195";
}
return "al-7075";
}
export function maybeUnlockAiTech(
agency: AgencyState,
contract?: ContractOffer | null,
): void {
if (agency.terminatedReason || agency.bankrupt) return;
const skill = clamp01(agency.aiSkill ?? 0.65);
const unlocked = new Set(
agency.unlockedTechs ??
defaultTechsForDifficulty(agency.difficulty as AiDifficulty),
);
const payloadPart = contract?.recommendedPayloadId
? PARTS.find((p) => p.id === contract.recommendedPayloadId)
: null;
const needsWideFairing =
!!payloadPart && (payloadPart.diameter > 4.7 || payloadPart.length > 14.0);
const needsHighEnergy =
!!contract &&
(contract.requiredDv >= 11200 || contract.payloadMass >= 6500);
for (const node of TECH_TREE) {
if (unlocked.has(node.id)) continue;
if ((agency.reputation ?? 0) < node.minReputation) continue;
const directlyNeeded =
(node.id === "composite-airframes" && needsWideFairing) ||
((node.id === "cryo-hydrolox" ||
node.id === "methalox-reusable" ||
node.id === "heavy-lift") &&
needsHighEnergy) ||
node.id === "avionics-diagnostics-2";
const minReserve = directlyNeeded ? 18_000_000 : 24_000_000;
if (agency.treasury - node.cost < minReserve) continue;
const chance = directlyNeeded ? 0.55 + skill * 0.45 : 0.25 + skill * 0.55;
if (Math.random() <= chance) {
agency.treasury -= node.cost;
unlocked.add(node.id);
agency.unlockedTechs = Array.from(unlocked);
emit("agency.tech_unlocked", {
agency: agency.name,
techId: node.id,
techName: node.name,
ai: true,
});
return;
}
}
}
export function scoreDryRun(
sim: SimResult,
contract: ContractOffer,
fp: FlightParams,
): number {
let score = 0;
if (sim.orbitGrade === "nominal") score += 2000;
else if (sim.orbitGrade === "partial") score += 700;
else if (sim.success) score += 300;
else score -= 1600;
if (contract.targetOrbit.apoapsisKm <= 1200) {
const apKm = sim.apoapsis / 1000;
const peKm = sim.periapsis / 1000;
const apErr =
Math.abs(apKm - contract.targetOrbit.apoapsisKm) /
Math.max(100, contract.targetOrbit.apoapsisKm);
const peErr =
Math.abs(peKm - contract.targetOrbit.periapsisKm) /
Math.max(100, contract.targetOrbit.periapsisKm);
score -= (apErr + peErr) * 650;
} else {
const apKm = sim.apoapsis / 1000;
const parkErr =
Math.abs(apKm - fp.targetApoapsisKm) / Math.max(150, fp.targetApoapsisKm);
score -= parkErr * 350;
}
score += Math.min(180, (sim.dvRemaining ?? 0) * 0.12);
score -= Math.max(0, (sim.peakGLoad - contract.maxGLoad) * 200);
return score;
}
export function createDefaultParamsFor(contract: ContractOffer): FlightParams {
return autoTuneFlightParams(
{
name: "temp",
designTier: "standard",
maturity: "concept",
stages: [],
fairingId: "fairing-standard",
payloadMass: contract.payloadMass,
flightParams: {
gravityTurnStartVel: 75,
pitchOverDeg: 8,
turnEndAltKm: 92,
maxQThrottle: 0.72,
fairingSepAltKm: 95,
targetInclinationDeg: contract.targetOrbit.inclinationDeg,
targetApoapsisKm: Math.min(
850,
Math.max(180, contract.targetOrbit.apoapsisKm),
),
upperBurnSplit: 0.9,
},
},
{
design: {} as RocketDesign,
stages: [],
fairingY: 0,
payloadY: 0,
payloadMass: contract.payloadMass,
totalPayloadMass: contract.payloadMass,
lasY: 0,
liftoffMass: 200000,
height: 35,
maxDiameter: 3.7,
cgY: 16,
cpY: 14,
stabilityMarginCalibers: 0.6,
totalDv: 9500,
liftoffTwr: 1.4,
estimatedMaxQPa: 28000,
totalCost: 25000000,
aero: {
frontalAreaM2: 10.75,
baseCd: 0.25,
stepPenaltyCd: 0,
radialInterferenceCd: 0,
noseFinenessRatio: 2.5,
hasExposedBluntNose: false,
finRestoringMoment: 150,
summary: "",
},
},
contract,
);
}

463
src/server/ai/runner.ts Normal file
View file

@ -0,0 +1,463 @@
// AI agency ticks (bailouts, contract selection, launches, startups) and builds the leaderboard.
import { MATERIALS, PARTS, SPONSORS } from "../catalogs.js";
import { config } from "../config.js";
import {
acceptContract,
clearActiveContract,
listContracts,
} from "../contracts.js";
import { partUnitPrice, recordDesignDemand } from "../economy.js";
import { emit } from "../events.js";
import { getActiveHazards } from "../hazards.js";
import { predictMlDecisionSync } from "../ml_ai.js";
import { settleMissionOutcome } from "../settlement.js";
import { getDb, getWorld, listAgencies, putAgency } from "../store.js";
import { simulateAscent } from "../../shared/ascent_sim.js";
import {
computeLaunchWindow,
generateTrajectory,
} from "../../shared/ephemeris.js";
import {
buildRocket,
computeDesignHash,
computeDesignReliability,
getDifficultyProfile,
isPartUnlocked,
validateDesign,
} from "../../shared/physics.js";
import type {
ActiveMission,
AgencyState,
ContractOffer,
} from "../../shared/types.js";
import {
clamp01,
effectivePayloadMass,
INSOLVENCY_THRESHOLD,
makeAiAgency,
maybeUnlockAiTech,
seedAI,
STARTUP_POOL,
} from "./agencies.js";
import { synthesizeAiRocket } from "./synthesizer.js";
let lastStartupAt = 0;
function isContractFeasibleForAi(
agency: AgencyState,
offer: ContractOffer,
): boolean {
const advance = Math.round(offer.budget * 0.35);
const estCost = offer.budget * 0.62;
if (estCost > (agency.treasury + advance) * 0.72) return false;
if (agency.treasury + advance - estCost < 10_000_000) return false;
const prof = getDifficultyProfile(agency.difficulty);
if (!prof.allTechUnlocked && offer.requiredDv > 9800) {
const unlocked = new Set(agency.unlockedTechs ?? []);
if (
!unlocked.has("cryo-hydrolox") &&
!unlocked.has("methalox-reusable") &&
!unlocked.has("heavy-lift")
) {
return false;
}
}
return true;
}
function chooseContractForAi(agency: AgencyState): ContractOffer | null {
const offers = listContracts(agency);
if (!offers.length) return null;
if (agency.aiType === "ml") {
const world = getWorld();
const ml = predictMlDecisionSync(
agency,
offers,
world.weather,
getActiveHazards(),
);
if (ml.selectedOfferId) {
const hit = offers.find(
(o) =>
(o.offerId ?? o.id) === ml.selectedOfferId ||
o.id === ml.selectedTemplateId,
);
if (hit && isContractFeasibleForAi(agency, hit)) return hit;
}
}
const skill = clamp01(agency.aiSkill ?? 0.65);
const cryoUnlocked = isPartUnlocked("eng-rl10", agency);
const scored = offers.map((offer) => {
const postAdvanceCash = agency.treasury + Math.round(offer.budget * 0.35);
const estCost = offer.budget * 0.62;
let score = offer.budget / 1e6;
if (!isContractFeasibleForAi(agency, offer)) {
score -= 1000;
}
if (estCost > postAdvanceCash * 1.05 && offer.tier > 0) {
score -= 1000;
}
if (offer.requiredDv >= 11500 && !cryoUnlocked) {
score -= skill * 120;
}
if (offer.windowPenaltyDv > 200) {
score -= skill * 80;
}
if (offer.crewed && agency.difficulty === "director" && skill < 0.7) {
score -= 40;
}
score += (Math.random() - 0.5) * (1 - skill) * 140;
return { offer, score };
});
scored.sort((a, b) => b.score - a.score);
return scored[0]?.offer ?? offers[0];
}
export function aiTick(): void {
if (!config.aiEnabled) return;
seedAI();
const db = getDb();
const world = getWorld();
const simTime = world.simTime;
let activeAICount = 0;
for (const agency of Object.values(db.agencies)) {
if (!agency.isAI) continue;
if (agency.terminatedReason) {
agency.bankrupt = true;
putAgency(agency.name, agency);
continue;
}
const skill = clamp01(agency.aiSkill ?? 0.65);
const profile = getDifficultyProfile(agency.difficulty);
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
const maxAiBailouts = Math.min(3, profile.maxBailouts);
if (agency.bankrupt && (agency.bailoutsTaken ?? 0) >= maxAiBailouts) {
continue;
}
if (agency.activeMissions?.length) {
const remaining: ActiveMission[] = [];
let changed = false;
for (const m of agency.activeMissions) {
if (simTime < m.completeAt) {
remaining.push(m);
continue;
}
changed = true;
if (!m.settled) {
settleMissionOutcome(agency, m, simTime);
clearActiveContract(agency);
}
}
if (changed) {
agency.activeMissions = remaining;
putAgency(agency.name, agency);
}
}
if (
!agency.activeMissions?.length &&
(agency.bankrupt || agency.treasury < INSOLVENCY_THRESHOLD)
) {
if (
(agency.bailoutsTaken ?? 0) < maxAiBailouts &&
!agency.terminatedReason
) {
const grant = Math.round(
profile.bailoutGrant * 0.45 * (sponsor?.budgetMult ?? 1.0),
);
agency.treasury += grant;
agency.bankrupt = false;
agency.bankruptAt = null;
agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1;
agency.reputation = Math.max(
0,
Math.round((agency.reputation - 5.0) * 10) / 10,
);
agency.aiContractReadyAtSimTime = null;
agency.aiCooldownUntilSimTime = Math.max(
agency.aiCooldownUntilSimTime ?? 0,
simTime + 2700,
);
putAgency(agency.name, agency);
emit("agency.bailout", {
agency: agency.name,
grant,
bailoutsTaken: agency.bailoutsTaken,
ai: true,
});
} else {
if (!agency.bankrupt) {
agency.bankrupt = true;
agency.bankruptAt = simTime;
clearActiveContract(agency);
putAgency(agency.name, agency);
emit("agency.bankrupt", { agency: agency.name, isAI: true });
}
continue;
}
}
if (agency.bankrupt) continue;
activeAICount++;
if (
!agency.activeMissions?.length &&
(agency.aiCooldownUntilSimTime ?? 0) > simTime
) {
continue;
}
const padWait = (agency.padDamagedUntilSimTime ?? 0) > simTime;
const groundWait = (agency.groundedUntilSimTime ?? 0) > simTime;
if (padWait || groundWait) {
const fee = (padWait ? 4_000_000 : 0) + (groundWait ? 6_000_000 : 0);
if (skill >= 0.85 && agency.treasury >= fee + 45_000_000) {
agency.treasury -= fee;
agency.padDamagedUntilSimTime = null;
agency.groundedUntilSimTime = null;
agency.aiCooldownUntilSimTime = Math.max(
agency.aiCooldownUntilSimTime ?? 0,
simTime + 300,
);
putAgency(agency.name, agency);
}
continue;
}
if (!agency.activeMissions?.length) {
let contract = agency.activeContract;
if (!contract) {
const signChance = 0.14 + skill * 0.16;
if (Math.random() >= signChance) continue;
const chosen = chooseContractForAi(agency);
if (!chosen) continue;
try {
contract = acceptContract(agency, chosen.offerId ?? chosen.id);
} catch {
continue;
}
const advance = Math.round(contract.budget * 0.35);
agency.treasury += advance;
if (
contract.crewed &&
(!agency.crewConfig || agency.crewConfig.crewSize < 1)
) {
agency.crewConfig = { crewSize: 2, lifeSupport: 2 };
}
const prepSec = Math.max(
540,
Math.min(
1350,
Math.round(
(540 + (1 - skill) * 810) * (0.85 + Math.random() * 0.3),
),
),
);
agency.aiContractReadyAtSimTime = simTime + prepSec;
putAgency(agency.name, agency);
emit("contract.claimed", {
agency: agency.name,
missionId: contract.id,
sponsorId: agency.sponsorId,
ai: true,
});
continue;
}
if ((agency.aiContractReadyAtSimTime ?? 0) > simTime) {
continue;
}
const abandonContract = () => {
if (agency.activeContract) {
const cur = agency.activeContract;
const advanceRefund = Math.round(cur.budget * 0.35);
const breachFine = Math.round(cur.budget * profile.breachFineRate);
agency.treasury -= advanceRefund + breachFine;
agency.reputation = Math.max(
0,
Math.round((agency.reputation - 1.5) * 10) / 10,
);
agency.aiContractReadyAtSimTime = null;
agency.aiCooldownUntilSimTime = Math.max(
agency.aiCooldownUntilSimTime ?? 0,
simTime + 900,
);
clearActiveContract(agency);
putAgency(agency.name, agency);
}
};
maybeUnlockAiTech(agency, contract);
const design = synthesizeAiRocket(
agency,
contract,
world.weather,
simTime,
{ chargeDryRuns: true },
);
if (design.maturity !== "flight-ready") {
abandonContract();
continue;
}
const effectiveMission = {
...contract,
payloadMass: effectivePayloadMass(agency, contract),
};
const activeHazards = getActiveHazards();
const validation = validateDesign(design, PARTS, MATERIALS, {
mission: effectiveMission,
difficulty: agency.difficulty,
simTime,
weather: world.weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
waiverCostMult: sponsor?.waiverCostMult ?? 1.0,
crewedSeats: contract.crewed ? (agency.crewConfig?.crewSize ?? 2) : 0,
eclssLevel: contract.crewed ? (agency.crewConfig?.lifeSupport ?? 2) : 0,
priceOf: partUnitPrice,
});
if (
!validation.valid ||
validation.compliance.mandatoryFailed.length > 0
) {
abandonContract();
continue;
}
if (validation.totalMissionCost > agency.treasury) {
abandonContract();
continue;
}
const asm =
validation.assembly ??
buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission: effectiveMission,
difficulty: agency.difficulty,
weather: world.weather,
unlockedTechs: agency.unlockedTechs ?? [],
});
const precisionAi =
agency.difficulty === "director" || agency.difficulty === "engineer";
const hash = computeDesignHash(design);
if (profile.partDefectMult > 0 && agency.staticFiredDesignHash !== hash) {
const sfFee = Math.max(450_000, Math.round(asm.totalCost * 0.04));
const wantsSf = skill >= 0.82 || Math.random() < skill * 0.75;
if (
wantsSf &&
agency.treasury >= validation.totalMissionCost + sfFee + 5_000_000
) {
agency.treasury -= sfFee;
agency.staticFiredDesignHash = hash;
}
}
const insuranceWorthy =
contract.crewed ||
validation.totalMissionCost > agency.treasury * 0.38 ||
agency.difficulty === "director";
agency.launchInsured =
insuranceWorthy &&
(skill >= 0.8 || Math.random() < skill * 0.85) &&
agency.treasury >= validation.totalMissionCost * 1.08 + 4_000_000;
const insurancePremium = agency.launchInsured
? Math.round(validation.totalMissionCost * 0.08)
: 0;
const totalCost = validation.totalMissionCost + insurancePremium;
if (agency.treasury < totalCost) {
putAgency(agency.name, agency);
continue;
}
const reliability = computeDesignReliability(design, asm, agency);
const ascent = simulateAscent(design, PARTS, MATERIALS, {
weather: world.weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
mission: effectiveMission,
rollAnomalies: true,
sampleEvery: 0.8,
priceOf: partUnitPrice,
difficulty: agency.difficulty,
partDefectRiskPct: reliability.anomalyRiskPct,
});
const trajectory = generateTrajectory(contract.target, undefined, 240, {
altKm: design.flightParams.targetApoapsisKm,
incDeg: design.flightParams.targetInclinationDeg,
});
agency.treasury -= totalCost;
agency.staticFiredDesignHash = null;
agency.aiContractReadyAtSimTime = null;
recordDesignDemand(design);
const durationSec = contract.advanced ? 3600 : 1800;
const failDurationSec = 150 + Math.round(Math.random() * 30);
const flight: ActiveMission = {
id: `ai-${agency.name.replace(/\W+/g, "").toLowerCase()}-${Date.now()}`,
agencyName: agency.name,
isAI: true,
missionId: contract.id,
name: contract.name,
target: contract.target,
contract,
rocketDesign: design,
launchedAt: simTime,
completeAt: ascent.success
? simTime + durationSec
: simTime + failDurationSec,
cost: totalCost,
budget: contract.budget,
ascent,
trajectory,
validation,
};
agency.rocketDesign = design;
agency.missionId = contract.id;
agency.activeContract = contract;
agency.activeMissions = [flight];
putAgency(agency.name, agency);
emit("mission.launched", {
id: flight.id,
agency: agency.name,
missionId: contract.id,
target: contract.target,
ai: true,
});
}
}
if (activeAICount < 4 && simTime - lastStartupAt > 5400) {
const candidate = STARTUP_POOL.find((s) => !db.agencies[s.name]);
if (candidate) {
lastStartupAt = simTime;
const startup = makeAiAgency(candidate);
putAgency(startup.name, startup);
emit("agency.founded", {
agency: startup.name,
sponsorId: startup.sponsorId,
difficulty: startup.difficulty,
skill: startup.aiSkill,
});
}
}
}
export function getLeaderboard() {
seedAI();
return listAgencies()
.map((a) => {
const profile = getDifficultyProfile(a.difficulty);
return {
name: a.name,
isAI: !!a.isAI,
aiType: a.aiType,
mlStats: a.mlStats ?? null,
difficulty: profile.id,
difficultyLabel: profile.label,
aiSkill: a.isAI ? clamp01(a.aiSkill ?? 0.65) : null,
bankrupt: !!a.bankrupt,
sponsorId: a.sponsorId,
treasury: a.treasury,
reputation: Math.round(a.reputation * 10) / 10,
missionsCompleted: a.missionsCompleted,
missionsFailed: a.missionsFailed,
earnedTotal: a.earnedTotal,
score: Math.round(
(a.bankrupt ? -1000 : 0) +
a.reputation * 120 +
a.missionsCompleted * 300 -
a.missionsFailed * 90 +
Math.log10(Math.max(1, a.treasury) + 1) * 55,
),
};
})
.sort((a, b) => b.score - a.score);
}

View file

@ -0,0 +1,403 @@
// Initial AI rocket stage stack, avionics, fairing, heatshield, and propellant family for a mission contract.
import { MATERIALS, PARTS, SPONSORS } from "../catalogs.js";
import { getActiveHazards } from "../hazards.js";
import { predictMlDecisionSync, type MlDecision } from "../ml_ai.js";
import { getWorld } from "../store.js";
import { computeLaunchWindow } from "../../shared/ephemeris.js";
import {
createDefaultSpacecraftConfig,
isPartUnlocked,
normalizeDesign,
} from "../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
RocketDesign,
SpaceWeather,
StageSlotConfig,
} from "../../shared/types.js";
import {
chooseFairingForPayload,
clamp01,
createDefaultParamsFor,
effectivePayloadMass,
pickUnlockedMaterial,
} from "./agencies.js";
export interface InitialAiRocketContext {
design: RocketDesign;
effectiveMission: ContractOffer;
skill: number;
simTime: number;
waiverCostMult: number;
heavyStruct: string;
upperMat: string;
effReqDv: number;
methaUnlocked: boolean;
threeStageHeavy: boolean;
spotsMeteorHazard: boolean;
spotsShearHazard: boolean;
mlGuidance: MlDecision | null;
activeHazards: ReturnType<typeof getActiveHazards>;
}
export function buildInitialAiRocket(
agency: AgencyState,
contract: ContractOffer,
weather: SpaceWeather,
simTimeOverride?: number,
): InitialAiRocketContext {
const skill = clamp01(agency.aiSkill ?? 0.65);
const simTime = simTimeOverride ?? getWorld().simTime;
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
const waiverCostMult = sponsor?.waiverCostMult ?? 1.0;
if (contract.crewed) {
agency.crewConfig = {
crewSize: 2,
lifeSupport:
contract.advanced || contract.requiredDv > 11000
? 3
: skill >= 0.55
? 2
: 1,
};
}
const effPayloadMass = effectivePayloadMass(agency, contract);
const effectiveMission: ContractOffer = {
...contract,
payloadMass: effPayloadMass,
};
const payloadPartId = contract.recommendedPayloadId ?? "payload-cubesat-1u";
const fairingId = chooseFairingForPayload(agency, payloadPartId);
const win = computeLaunchWindow(
contract.target,
simTime,
contract.launchWindowPeriodSec,
);
const effReqDv = contract.requiredDv + win.penaltyDv;
const cryoUnlocked =
isPartUnlocked("eng-rl10", agency) &&
isPartUnlocked("tank-med-hydro", agency);
const methaUnlocked =
isPartUnlocked("eng-raptor-sl", agency) &&
isPartUnlocked("tank-med-metha", agency);
const largeMethaUnlocked =
isPartUnlocked("tank-large-metha", agency) &&
isPartUnlocked("eng-raptor-sl", agency);
const largeKeroUnlocked = isPartUnlocked("tank-large-kero", agency);
const heavyStruct = isPartUnlocked("struct-frame-heavy", agency)
? "struct-frame-heavy"
: "struct-frame-std";
const cryoStruct = isPartUnlocked("struct-cryo-frame", agency)
? "struct-cryo-frame"
: heavyStruct;
const activeHazards = getActiveHazards();
const hasRadHazard = activeHazards.some((h) => h.kind === "stray-radiation");
const hasMeteorHazard = activeHazards.some(
(h) => h.kind === "meteorite-stream",
);
const hasShearHazard = activeHazards.some(
(h) => h.kind === "jet-stream-shear",
);
const mlGuidance =
agency.aiType === "ml"
? predictMlDecisionSync(agency, [contract], weather, activeHazards)
: null;
const spotsRadHazard =
(hasRadHazard ||
weather === "radiation-storm" ||
weather === "solar-storm" ||
contract.radiationHazard === "extreme") &&
(skill >= 0.72 || Math.random() < 0.38 + skill * 0.62);
const spotsMeteorHazard =
hasMeteorHazard && (skill >= 0.7 || Math.random() < 0.35 + skill * 0.65);
const spotsShearHazard =
hasShearHazard && (skill >= 0.66 || Math.random() < 0.38 + skill * 0.62);
const chooseComputerForAi = (): string => {
const needRadHard = spotsRadHazard || !!mlGuidance?.suggestedPreferRadHard;
if (needRadHard) {
if (isPartUnlocked("comp-rad-quad", agency)) return "comp-rad-quad";
if (isPartUnlocked("comp-fault-tolerant", agency))
return "comp-fault-tolerant";
}
if (
(contract.tier >= 1 ||
contract.crewed ||
(contract.requiredInstrumentsMin ?? 0) >= 2) &&
isPartUnlocked("comp-fault-tolerant", agency)
) {
return "comp-fault-tolerant";
}
if (isPartUnlocked("comp-quantum-nav", agency) && contract.tier >= 2) {
return "comp-quantum-nav";
}
return "comp-std-avionics";
};
const computerId = chooseComputerForAi();
const boosterMat =
spotsMeteorHazard && isPartUnlocked("carbon-epoxy", agency) && skill >= 0.65
? "carbon-epoxy"
: pickUnlockedMaterial(
agency,
skill,
"booster",
weather,
contract.target,
);
const upperMat =
spotsMeteorHazard && isPartUnlocked("stainless-304l", agency)
? "stainless-304l"
: pickUnlockedMaterial(agency, skill, "upper", weather, contract.target);
const useFins = spotsShearHazard
? true
: skill >= 0.62
? true
: Math.random() < 0.42 + skill * 0.5;
const stormOrDeepHeatshield =
(spotsMeteorHazard ||
spotsRadHazard ||
contract.target === "solar" ||
contract.target === "moon-landing" ||
contract.id === "mars-rover-perseverance") &&
isPartUnlocked("heatshield-pica", agency);
const highEnergy =
effReqDv >= 11200 || (effPayloadMass >= 6000 && !contract.crewed);
const superHeavy = effReqDv >= 13000 || effPayloadMass >= 11500;
const threeStageHeavy =
superHeavy ||
effPayloadMass >= 6500 ||
(effReqDv >= 12200 && !cryoUnlocked);
const useHydroloxUpper =
cryoUnlocked &&
effPayloadMass < 5500 &&
(effReqDv >= 10000 || contract.maxGLoad <= 5.5 || skill >= 0.72);
const stages: StageSlotConfig[] = [];
if (threeStageHeavy) {
const useMethaBooster =
largeMethaUnlocked || (methaUnlocked && !largeKeroUnlocked);
const hasJ2X =
isPartUnlocked("eng-j2x", agency) &&
isPartUnlocked("tank-small-hydro", agency);
const hasRVac = isPartUnlocked("eng-raptor-vac", agency) && methaUnlocked;
const cryoTop = cryoUnlocked && effPayloadMass < 6000;
stages.push({
engineId: useMethaBooster ? "eng-raptor-sl" : "eng-merlin-1d",
engineCount: useMethaBooster ? 6 : 9,
nozzleRatio: 1.0,
gimbalDeg: useMethaBooster ? 7 : 5,
tankId: useMethaBooster
? largeMethaUnlocked
? "tank-large-metha"
: "tank-med-metha"
: largeKeroUnlocked
? "tank-large-kero"
: "tank-med-kero",
diameter: useMethaBooster
? largeMethaUnlocked
? 6.6
: 4.8
: largeKeroUnlocked
? 5.2
: 4.2,
length: useMethaBooster ? 34 : 31,
fillRatio: 1.0,
structureId: heavyStruct,
materialId: boosterMat,
wallThicknessFactor: skill >= 0.75 ? 1.05 : 0.96,
interstageId: "interstage-tapered",
hasFins: useFins,
hasHeatshield: stormOrDeepHeatshield,
});
stages.push({
engineId: hasRVac
? "eng-raptor-vac"
: methaUnlocked
? "eng-raptor-sl"
: "eng-merlin-vac",
engineCount: hasRVac ? 2 : 2,
nozzleRatio: 1.15,
gimbalDeg: 5,
tankId: methaUnlocked ? "tank-med-metha" : "tank-med-kero",
diameter: hasRVac ? 4.8 : 3.6,
length: hasRVac ? 20.0 : 14.0,
fillRatio: 1.0,
structureId: stormOrDeepHeatshield ? cryoStruct : heavyStruct,
materialId: upperMat,
wallThicknessFactor: 1.0,
interstageId: "interstage-tapered",
hasFins: false,
hasHeatshield: false,
});
stages.push({
engineId: hasJ2X
? "eng-j2x"
: cryoTop
? "eng-rl10"
: hasRVac
? "eng-raptor-vac"
: "eng-merlin-vac",
engineCount: hasJ2X ? 1 : cryoTop ? 2 : 1,
nozzleRatio: 1.25,
gimbalDeg: 4,
tankId: hasJ2X
? "tank-small-hydro"
: cryoTop
? "tank-med-hydro"
: methaUnlocked && hasRVac
? "tank-med-metha"
: "tank-small-kero",
diameter: hasJ2X ? 4.2 : 3.1,
length: hasJ2X ? 13.5 : 10.0,
fillRatio: 1.0,
structureId: cryoStruct,
materialId: upperMat,
wallThicknessFactor: 1.0,
hasFins: false,
hasHeatshield:
stormOrDeepHeatshield &&
(contract.target === "solar" || contract.target === "moon-landing"),
});
} else if (highEnergy) {
const useMethaBooster =
largeMethaUnlocked || (methaUnlocked && skill >= 0.75);
const hasJ2X = isPartUnlocked("eng-j2x", agency) && cryoUnlocked;
const hasRVac = isPartUnlocked("eng-raptor-vac", agency) && methaUnlocked;
stages.push({
engineId: useMethaBooster ? "eng-raptor-sl" : "eng-merlin-1d",
engineCount: useMethaBooster ? 5 : 7,
nozzleRatio: 1.0,
gimbalDeg: 5,
tankId: useMethaBooster
? largeMethaUnlocked
? "tank-large-metha"
: "tank-med-metha"
: largeKeroUnlocked
? "tank-large-kero"
: "tank-med-kero",
diameter: useMethaBooster ? 5.0 : largeKeroUnlocked ? 4.8 : 4.0,
length: 28,
fillRatio: 1.0,
structureId: heavyStruct,
materialId: boosterMat,
wallThicknessFactor: skill >= 0.75 ? 1.05 : 0.96,
interstageId: "interstage-tapered",
hasFins: useFins,
hasHeatshield: stormOrDeepHeatshield,
});
stages.push({
engineId: hasJ2X
? "eng-j2x"
: useHydroloxUpper
? "eng-rl10"
: hasRVac
? "eng-raptor-vac"
: "eng-merlin-vac",
engineCount: hasJ2X ? 1 : useHydroloxUpper ? 2 : 1,
nozzleRatio: 1.2,
gimbalDeg: 4,
tankId:
hasJ2X || useHydroloxUpper
? "tank-med-hydro"
: hasRVac
? "tank-med-metha"
: "tank-med-kero",
diameter: 3.6,
length: hasJ2X || useHydroloxUpper ? 15 : 13,
fillRatio: 1.0,
structureId: hasJ2X || useHydroloxUpper ? cryoStruct : "struct-frame-std",
materialId: upperMat,
wallThicknessFactor: 1.0,
hasFins: false,
hasHeatshield: false,
});
} else {
const heavyLeo =
effPayloadMass >= 2500 || effReqDv >= 10000 || contract.crewed;
stages.push({
engineId: "eng-merlin-1d",
engineCount: heavyLeo ? (effPayloadMass >= 7500 ? 8 : 7) : 4,
nozzleRatio: 1.0,
gimbalDeg: 5,
tankId: "tank-med-kero",
diameter: heavyLeo ? 4.0 : 3.7,
length: heavyLeo ? 26.5 : 25,
fillRatio: 1.0,
structureId: heavyLeo ? heavyStruct : "struct-frame-std",
materialId: boosterMat,
wallThicknessFactor: skill >= 0.72 ? 1.08 : 0.98,
interstageId: "interstage-tapered",
hasFins: useFins,
hasHeatshield: stormOrDeepHeatshield,
});
stages.push({
engineId: useHydroloxUpper ? "eng-rl10" : "eng-merlin-vac",
engineCount: useHydroloxUpper ? (heavyLeo ? 3 : 2) : heavyLeo ? 2 : 1,
nozzleRatio: 1.15,
gimbalDeg: 4,
tankId: useHydroloxUpper
? "tank-med-hydro"
: heavyLeo
? "tank-med-kero"
: "tank-small-kero",
diameter: heavyLeo ? 3.7 : 3.0,
length: useHydroloxUpper ? 13.5 : heavyLeo ? 14.5 : 9.0,
fillRatio: 1.0,
structureId:
useHydroloxUpper || stormOrDeepHeatshield
? cryoStruct
: "struct-frame-std",
materialId: upperMat,
wallThicknessFactor: 1.0,
hasFins: false,
hasHeatshield: false,
});
}
const baseReserve =
skill >= 0.8 ? 0.08 : skill >= 0.62 ? 0.048 : 0.015 + Math.random() * 0.035;
const reqReserveFrac =
threeStageHeavy && !methaUnlocked
? Math.min(baseReserve, 0.022)
: baseReserve;
const targetDvMargin = Math.max(
threeStageHeavy && !methaUnlocked ? 180 : skill >= 0.65 ? 320 : 180,
Math.round(effReqDv * reqReserveFrac),
);
let design: RocketDesign = normalizeDesign(
{
name: `${agency.name.split(" ")[0]}-${contract.tier + 1}`,
designTier: "standard",
maturity: "concept",
stages,
fairingId,
computerId,
payloadPartId,
payloadMass: effPayloadMass,
hasLaunchAbort: contract.crewed
? skill >= 0.58
? true
: Math.random() < 0.35 + skill * 0.55
: false,
waivedRuleIds: [],
flightParams: createDefaultParamsFor(contract),
spacecraftConfig: createDefaultSpacecraftConfig(contract),
},
PARTS,
MATERIALS,
);
return {
design,
effectiveMission,
skill,
simTime,
waiverCostMult,
heavyStruct,
upperMat,
effReqDv,
methaUnlocked,
threeStageHeavy,
spotsMeteorHazard,
spotsShearHazard,
mlGuidance,
activeHazards,
};
}

View file

@ -0,0 +1,481 @@
// Iterative AI rocket sizing, flight parameter dispersion/dry-run optimization, and compliance waiver checks.
import { MATERIALS, PARTS } from "../catalogs.js";
import { partUnitPrice } from "../economy.js";
import { simulateAscent } from "../../shared/ascent_sim.js";
import {
autoTuneFlightParams,
buildRocket,
isPartUnlocked,
normalizeDesign,
validateDesign,
} from "../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
FlightParams,
RocketDesign,
SimResult,
SpaceWeather,
} from "../../shared/types.js";
import { scoreDryRun } from "./agencies.js";
import { buildInitialAiRocket } from "./stagePresets.js";
export function synthesizeAiRocket(
agency: AgencyState,
contract: ContractOffer,
weather: SpaceWeather,
simTimeOverride?: number,
options?: { chargeDryRuns?: boolean },
): RocketDesign {
const {
design: initialDesign,
effectiveMission,
skill,
simTime,
waiverCostMult,
heavyStruct,
upperMat,
effReqDv,
methaUnlocked,
threeStageHeavy,
spotsMeteorHazard,
spotsShearHazard,
mlGuidance,
activeHazards,
} = buildInitialAiRocket(agency, contract, weather, simTimeOverride);
let design = initialDesign;
const baseReserve =
skill >= 0.8 ? 0.08 : skill >= 0.62 ? 0.048 : 0.015 + Math.random() * 0.035;
const reqReserveFrac =
threeStageHeavy && !methaUnlocked
? Math.min(baseReserve, 0.022)
: baseReserve;
const targetDvMargin = Math.max(
threeStageHeavy && !methaUnlocked ? 180 : skill >= 0.65 ? 320 : 180,
Math.round(effReqDv * reqReserveFrac),
);
const maxSizingIters = skill >= 0.8 ? 14 : skill >= 0.65 ? 9 : 6;
for (let iter = 0; iter < maxSizingIters; iter++) {
design = normalizeDesign(design, PARTS, MATERIALS);
const val = validateDesign(design, PARTS, MATERIALS, {
mission: effectiveMission,
difficulty: agency.difficulty,
simTime,
weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
waiverCostMult,
crewedSeats: contract.crewed ? (agency.crewConfig?.crewSize ?? 2) : 0,
eclssLevel: contract.crewed ? (agency.crewConfig?.lifeSupport ?? 2) : 0,
priceOf: partUnitPrice,
});
const asm = val.assembly;
if (!asm) break;
let changed = false;
const s0 = design.stages[0];
const sTop = design.stages[design.stages.length - 1];
const maxBoosterDia = s0.engineId === "eng-raptor-sl" ? 6.8 : 4.2;
if (
asm.height / Math.max(1, asm.maxDiameter) > 20.5 &&
asm.liftoffTwr >= 1.38 &&
s0.diameter < maxBoosterDia
) {
s0.diameter = Number(
Math.min(maxBoosterDia, s0.diameter * 1.08).toFixed(2),
);
s0.length = Number(Math.max(12, s0.length * 0.93).toFixed(2));
changed = true;
}
for (let i = 1; i < design.stages.length; i++) {
if (design.stages[i].diameter > design.stages[i - 1].diameter) {
design.stages[i].diameter = Number(
(design.stages[i - 1].diameter * 0.9).toFixed(2),
);
changed = true;
}
}
if (asm.liftoffTwr < 1.32) {
if (s0.engineCount < 9) {
s0.engineCount += 1;
} else if (
s0.dropTankId &&
(s0.dropTankCount ?? 0) > 0 &&
asm.liftoffTwr < 1.18
) {
s0.dropTankCount = 0;
s0.dropTankId = undefined;
} else if (design.stages.length >= 3 && val.dvMargin > 120) {
design.stages[1].length = Number(
Math.max(12, design.stages[1].length * 0.92).toFixed(2),
);
sTop.length = Number(Math.max(8.5, sTop.length * 0.92).toFixed(2));
} else {
s0.length = Number(Math.max(14, s0.length * 0.91).toFixed(2));
if (s0.diameter > 3.7) {
s0.diameter = Number(Math.max(3.6, s0.diameter * 0.95).toFixed(2));
}
}
changed = true;
} else if (skill >= 0.65 && asm.liftoffTwr > 1.75 && s0.length < 36) {
if (s0.engineCount > 3 && asm.liftoffTwr > 2.0) {
s0.engineCount -= 1;
} else {
s0.length = Number(Math.min(38, s0.length * 1.1).toFixed(2));
}
changed = true;
}
for (let i = 1; i < asm.stages.length; i++) {
if (asm.stages[i].twrAtIgnition < 0.52) {
if (design.stages[i].engineCount < 4) {
design.stages[i].engineCount += 1;
changed = true;
}
}
}
const maxQLim = asm.stages[0]?.maxQPaLimit ?? 55000;
const bucklingHit = asm.stages.some((st) => st.bucklingRatio > 0.95);
const maxQHit = asm.estimatedMaxQPa > maxQLim * 0.92;
if (bucklingHit || maxQHit) {
if (bucklingHit && s0.wallThicknessFactor < 1.45) {
s0.wallThicknessFactor = Number(
Math.min(1.45, s0.wallThicknessFactor + 0.14).toFixed(2),
);
changed = true;
} else if (maxQHit && s0.wallThicknessFactor < 1.12) {
s0.wallThicknessFactor = 1.12;
changed = true;
}
if (s0.structureId !== heavyStruct) {
s0.structureId = heavyStruct;
changed = true;
}
}
const s0Dv = asm.stages[0]?.dv ?? 0;
const minBoosterDv =
threeStageHeavy && !methaUnlocked
? Math.min(2750, effReqDv * 0.25)
: Math.min(4300, effReqDv * 0.36);
const s0EngPart = PARTS.find((p) => p.id === s0.engineId);
const availDropTanks =
skill >= 0.65 &&
s0EngPart &&
s0EngPart.propellantType &&
s0EngPart.propellantType !== "solid"
? PARTS.filter(
(p) =>
p.kind === "tank" &&
p.isDropTank &&
p.propellantType === s0EngPart.propellantType &&
isPartUnlocked(p.id, agency),
).sort((a, b) => (b.propellantMass ?? 0) - (a.propellantMass ?? 0))
: [];
const wantDropTanks =
!s0.dropTankId &&
availDropTanks.length > 0 &&
((val.dvMargin < targetDvMargin &&
(s0.length >= 28 || iter >= maxSizingIters - 3)) ||
(skill >= 0.75 && effReqDv >= 11_400 && iter >= 1));
if (wantDropTanks) {
const chosenDrop = availDropTanks[0];
const dropQty: 1 | 2 = chosenDrop.id === "drop-tank-hydro-et" ? 1 : 2;
if (
val.totalMissionCost + chosenDrop.cost * dropQty * 1.15 <=
agency.treasury * 0.95 &&
asm.liftoffTwr >= 1.25
) {
s0.dropTankId = chosenDrop.id;
s0.dropTankCount = dropQty;
changed = true;
}
}
if (
!changed &&
skill >= 0.65 &&
s0Dv < minBoosterDv &&
asm.liftoffTwr >= 1.38 &&
s0.length < 44
) {
s0.length = Number(Math.min(44, s0.length * 1.12).toFixed(2));
s0.diameter = Number(
Math.min(maxBoosterDia, s0.diameter * 1.05).toFixed(2),
);
changed = true;
} else if (!changed && val.dvMargin < targetDvMargin) {
const boostFactor = val.dvMargin < 0 ? 1.14 : 1.07;
const maxTopPreMid = design.stages.length >= 3 ? 15 : 22;
if (
sTop.length < maxTopPreMid &&
(asm.liftoffTwr < 1.38 || sTop.length < s0.length * 0.55)
) {
sTop.length = Number(
Math.min(maxTopPreMid, sTop.length * boostFactor).toFixed(2),
);
sTop.diameter = Number(
Math.min(s0.diameter, sTop.diameter * 1.04).toFixed(2),
);
changed = true;
} else if (design.stages.length >= 3 && design.stages[1].length < 20) {
const sMid = design.stages[1];
sMid.length = Number(
Math.min(20, sMid.length * boostFactor).toFixed(2),
);
sMid.diameter = Number(
Math.min(s0.diameter * 0.92, sMid.diameter * 1.04).toFixed(2),
);
changed = true;
} else if (
sTop.length < 22 &&
(asm.liftoffTwr < 1.38 || sTop.length < s0.length * 0.55)
) {
sTop.length = Number(
Math.min(22, sTop.length * boostFactor).toFixed(2),
);
sTop.diameter = Number(
Math.min(s0.diameter, sTop.diameter * 1.04).toFixed(2),
);
changed = true;
} else if (asm.liftoffTwr >= 1.38 && s0.length < 44) {
s0.length = Number(Math.min(44, s0.length * boostFactor).toFixed(2));
s0.diameter = Number(
Math.min(maxBoosterDia, s0.diameter * 1.05).toFixed(2),
);
changed = true;
} else if (sTop.length < 24) {
sTop.length = Number(
Math.min(24, sTop.length * boostFactor).toFixed(2),
);
changed = true;
} else if (design.stages.length === 2) {
sTop.engineCount = 1;
design.stages.splice(1, 0, {
engineId: "eng-merlin-vac",
engineCount: 2,
nozzleRatio: 1.15,
gimbalDeg: 4,
tankId: "tank-med-kero",
diameter: Number(Math.max(3.2, s0.diameter * 0.85).toFixed(2)),
length: 14.5,
fillRatio: 1.0,
structureId: heavyStruct,
materialId: upperMat,
wallThicknessFactor: 1.0,
interstageId: "interstage-tapered",
hasFins: false,
hasHeatshield: false,
});
changed = true;
}
} else if (
!changed &&
val.totalMissionCost > agency.treasury &&
val.dvMargin > targetDvMargin + 400
) {
if (s0.dropTankId && (s0.dropTankCount ?? 0) > 0) {
s0.dropTankCount = 0;
s0.dropTankId = undefined;
} else {
s0.length = Number(Math.max(14, s0.length * 0.9).toFixed(2));
sTop.length = Number(Math.max(5.5, sTop.length * 0.92).toFixed(2));
}
changed = true;
}
if (!changed) break;
}
design = normalizeDesign(design, PARTS, MATERIALS);
let baseAsm = buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission: effectiveMission,
difficulty: agency.difficulty,
weather,
unlockedTechs: agency.unlockedTechs ?? [],
});
const tunedFp = autoTuneFlightParams(design, baseAsm, effectiveMission);
tunedFp.targetInclinationDeg = contract.targetOrbit.inclinationDeg;
tunedFp.fairingSepAltKm = spotsMeteorHazard
? Math.max(118, (contract.minFairingAltKm ?? 80) + 12)
: Math.max(92, (contract.minFairingAltKm ?? 80) + 8);
if (spotsShearHazard) {
tunedFp.maxQThrottle = Math.min(tunedFp.maxQThrottle, 0.72);
}
if (mlGuidance) {
tunedFp.pitchOverDeg = Number(
((tunedFp.pitchOverDeg + mlGuidance.suggestedPitchKickDeg) * 0.5).toFixed(
1,
),
);
tunedFp.maxQThrottle = Math.min(
tunedFp.maxQThrottle,
mlGuidance.suggestedMaxQThrottle,
);
}
const errScale = Math.pow(Math.max(0, 1 - skill), 1.35);
if (errScale > 0.06) {
const jit = (mag: number) => (Math.random() - 0.5) * 2 * mag * errScale;
tunedFp.pitchOverDeg = Math.max(
3,
Math.min(18, Number((tunedFp.pitchOverDeg + jit(4.5)).toFixed(1))),
);
tunedFp.gravityTurnStartVel = Math.max(
35,
Math.min(140, Math.round(tunedFp.gravityTurnStartVel + jit(35))),
);
tunedFp.maxQThrottle = Math.max(
0.48,
Math.min(1.0, Number((tunedFp.maxQThrottle + jit(0.18)).toFixed(2))),
);
tunedFp.targetInclinationDeg = Math.max(
0,
Math.min(
115,
Number((tunedFp.targetInclinationDeg + jit(3.2)).toFixed(1)),
),
);
if (skill < 0.75 && contract.targetOrbit.apoapsisKm <= 2500) {
tunedFp.targetApoapsisKm = Math.max(
160,
Math.round(tunedFp.targetApoapsisKm * (1 + jit(0.1))),
);
}
}
design.flightParams = tunedFp;
if ((baseAsm.peakComputeLoadEstPct ?? 0) >= 92) {
const bestComp = PARTS.filter(
(p) => p.kind === "computer" && isPartUnlocked(p.id, agency),
).sort(
(a, b) => (b.computeCapacityIps ?? 100) - (a.computeCapacityIps ?? 100),
)[0];
if (bestComp && bestComp.id !== design.computerId) {
design.computerId = bestComp.id;
design = normalizeDesign(design, PARTS, MATERIALS);
baseAsm = buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission: effectiveMission,
difficulty: agency.difficulty,
weather,
unlockedTechs: agency.unlockedTechs ?? [],
});
}
}
const precisionAi =
agency.difficulty === "director" || agency.difficulty === "engineer";
const dryRunSample = precisionAi ? 1.5 : 4.0;
const chargeDryRuns = options?.chargeDryRuns ?? false;
const tryDryRun = (candDesign: RocketDesign): SimResult | null => {
if (chargeDryRuns) {
const simFee = Math.max(120_000, Math.round(baseAsm.totalCost * 0.015));
if (agency.treasury < simFee + 8_000_000) return null;
agency.treasury -= simFee;
}
return simulateAscent(candDesign, PARTS, MATERIALS, {
weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
mission: effectiveMission,
rollAnomalies: false,
sampleEvery: dryRunSample,
priceOf: partUnitPrice,
difficulty: agency.difficulty,
});
};
const maxDryRuns = skill < 0.7 ? 0 : skill < 0.86 ? 1 : 2;
let bestFp = tunedFp;
let bestSim: SimResult | null = null;
let bestScore = -1e9;
if (maxDryRuns >= 1) {
const firstSim = tryDryRun(design);
if (firstSim) {
bestSim = firstSim;
bestScore = scoreDryRun(firstSim, effectiveMission, bestFp);
}
}
const tgtApoKm = contract.targetOrbit.apoapsisKm;
const apogeeOffRatio =
bestSim && bestSim.apoapsis > 0 && tgtApoKm <= 1200
? Math.abs(bestSim.apoapsis / 1000 - tgtApoKm) / Math.max(1, tgtApoKm)
: 0;
if (
maxDryRuns >= 2 &&
bestSim &&
(bestSim.orbitGrade !== "nominal" || (precisionAi && apogeeOffRatio > 0.06))
) {
let adjustFp: FlightParams = { ...bestFp };
if (bestSim.orbitGrade !== "nominal") {
if (
bestSim.failureReason === "structural_failure" ||
bestSim.failureReason === "g_load_exceeded"
) {
adjustFp = {
...bestFp,
maxQThrottle: Math.min(bestFp.maxQThrottle, 0.58),
pitchOverDeg: Math.max(5.5, bestFp.pitchOverDeg - 1.0),
};
} else {
adjustFp = {
...bestFp,
pitchOverDeg: 6.5,
turnEndAltKm: 112,
maxQThrottle: Math.min(bestFp.maxQThrottle, 0.7),
};
}
} else if (apogeeOffRatio > 0.06) {
const achievedKm = bestSim.apoapsis / 1000;
const ratio = Math.max(0.9, Math.min(1.1, tgtApoKm / achievedKm));
adjustFp = {
...bestFp,
targetApoapsisKm: Math.max(
160,
Math.round(bestFp.targetApoapsisKm * ratio),
),
};
}
const secondSim = tryDryRun({ ...design, flightParams: adjustFp });
if (secondSim) {
const secondScore = scoreDryRun(secondSim, effectiveMission, adjustFp);
if (secondScore > bestScore) {
bestScore = secondScore;
bestSim = secondSim;
bestFp = adjustFp;
}
}
}
design.flightParams = bestFp;
const check = validateDesign(design, PARTS, MATERIALS, {
mission: effectiveMission,
difficulty: agency.difficulty,
simTime,
weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
waiverCostMult,
crewedSeats: contract.crewed ? (agency.crewConfig?.crewSize ?? 2) : 0,
eclssLevel: contract.crewed ? (agency.crewConfig?.lifeSupport ?? 2) : 0,
priceOf: partUnitPrice,
});
if (
check.compliance.waiverableFailed.length > 0 &&
check.compliance.mandatoryFailed.length === 0
) {
const waiveChance =
skill >= 0.8 ? 1.0 : skill >= 0.6 ? 0.92 : 0.45 + skill * 0.45;
if (
Math.random() <= waiveChance &&
check.cost + check.waiverCost <= agency.treasury
) {
design.waivedRuleIds = check.compliance.waiverableFailed.map((r) => r.id);
}
}
const finalCheck = validateDesign(design, PARTS, MATERIALS, {
mission: effectiveMission,
difficulty: agency.difficulty,
simTime,
weather,
activeHazards,
unlockedTechs: agency.unlockedTechs ?? [],
waiverCostMult,
crewedSeats: contract.crewed ? (agency.crewConfig?.crewSize ?? 2) : 0,
eclssLevel: contract.crewed ? (agency.crewConfig?.lifeSupport ?? 2) : 0,
priceOf: partUnitPrice,
});
design.maturity = finalCheck.compliance.maxAllowedMaturity;
return design;
}

153
src/server/auth.ts Normal file
View file

@ -0,0 +1,153 @@
// Scrypt password hashing, token issuance, registration/login/logout, and Express auth.
import crypto from "node:crypto";
import type { NextFunction, Request, Response } from "express";
import {
deleteToken,
getAccount,
getAgency,
getTokenRecord,
putAccount,
putAgency,
putToken,
saveDb,
} from "./store.js";
import type { AgencyState, DifficultyLevel } from "../shared/types.js";
import {
getDifficultyProfile,
normalizeDifficulty,
TECH_TREE,
} from "../shared/physics.js";
export interface AuthedRequest extends Request {
accountName?: string;
agency?: AgencyState;
}
function hashPassword(password: string): string {
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
return `${salt}:${hash}`;
}
function verifyPassword(password: string, stored: string): boolean {
const [salt, hash] = stored.split(":");
if (!salt || !hash) return false;
const derived = crypto.scryptSync(password, salt, 32);
const expected = Buffer.from(hash, "hex");
return (
derived.length === expected.length &&
crypto.timingSafeEqual(derived, expected)
);
}
function issueToken(name: string): string {
const token = crypto.randomBytes(24).toString("hex");
putToken(token, { name, createdAt: Date.now() });
saveDb(true);
return token;
}
export function registerAgency(
name: string,
password: string,
difficulty: DifficultyLevel = "enthusiast",
): { token: string; account: { name: string }; agency: AgencyState } {
const clean = (name ?? "").trim();
if (clean.length < 2 || clean.length > 32) {
throw new Error("Agency name must be 2-32 characters.");
}
if (!password || password.length < 3) {
throw new Error("Password must be at least 3 characters.");
}
if (getAccount(clean) || getAgency(clean)) {
throw new Error("An agency with that name already exists.");
}
const canonDiff = normalizeDifficulty(difficulty);
const profile = getDifficultyProfile(canonDiff);
putAccount(clean, {
name: clean,
hash: hashPassword(password),
createdAt: Date.now(),
});
const agency: AgencyState = {
name: clean,
difficulty: canonDiff,
sponsorId: null,
missionId: null,
activeContract: null,
treasury: profile.startingFunds,
reputation: 1,
missionsCompleted: 0,
missionsFailed: 0,
earnedTotal: 0,
rocketDesign: null,
crewConfig: { crewSize: 0, lifeSupport: 1 },
activeMissions: [],
contractHistory: [],
bankrupt: false,
bankruptAt: null,
bailoutsTaken: 0,
isAI: false,
unlockedTechs: profile.allTechUnlocked
? TECH_TREE.map((t) => t.id)
: canonDiff === "enthusiast"
? ["starter", "cryo-hydrolox"]
: ["starter"],
partHeritage: {},
staticFiredDesignHash: null,
launchInsured: canonDiff === "explorer" || canonDiff === "sandbox",
groundedUntilSimTime: null,
padDamagedUntilSimTime: null,
casualtiesTotal: 0,
lastSettlement: null,
terminatedReason: null,
};
putAgency(clean, agency);
const token = issueToken(clean);
return { token, account: { name: clean }, agency };
}
export function loginAgency(
name: string,
password: string,
): { token: string; account: { name: string }; agency: AgencyState } {
const clean = (name ?? "").trim();
const acc = getAccount(clean);
if (!acc || !verifyPassword(password ?? "", acc.hash)) {
throw new Error("Invalid agency name or password.");
}
const agency = getAgency(clean);
if (!agency) {
throw new Error("Agency record missing.");
}
const token = issueToken(clean);
return { token, account: { name: clean }, agency };
}
export function logoutToken(token: string): void {
if (!token) return;
deleteToken(token);
saveDb(true);
}
export function requireAuth(
req: AuthedRequest,
res: Response,
next: NextFunction,
): void {
const header = req.headers.authorization ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
const sess = token ? getTokenRecord(token) : null;
if (!sess) {
res.status(401).json({ error: "Not authenticated." });
return;
}
const agency = getAgency(sess.name);
if (!agency) {
res.status(401).json({ error: "Agency not found." });
return;
}
req.accountName = sess.name;
req.agency = agency;
next();
}

31
src/server/catalogs.ts Normal file
View file

@ -0,0 +1,31 @@
// Loads static JSON's (parts, materials, sponsors, missions, 3D model index) from data/.
import fs from "node:fs";
import path from "node:path";
import { APP_ROOT } from "./config.js";
import type {
MaterialSpec,
MissionTemplate,
Part,
Sponsor,
} from "../shared/types.js";
function loadJson<T>(filename: string): T {
const filePath = path.join(APP_ROOT, "data", filename);
return JSON.parse(fs.readFileSync(filePath, "utf8")) as T;
}
export interface ModelIndexEntry {
file: string;
name: string;
category: string;
description?: string;
}
export const PARTS: Part[] = loadJson<Part[]>("parts.json");
export const MATERIALS: MaterialSpec[] =
loadJson<MaterialSpec[]>("materials.json");
export const MISSIONS: MissionTemplate[] =
loadJson<MissionTemplate[]>("missions.json");
export const SPONSORS: Sponsor[] = loadJson<Sponsor[]>("sponsors.json");
export const MODELS_INDEX: { note?: string; models: ModelIndexEntry[] } =
loadJson("models_index.json");

25
src/server/config.ts Normal file
View file

@ -0,0 +1,25 @@
// Server runtime configuration resolving APP_ROOT, database, GMAT workspace, ML weights path, and environment defaults.
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const APP_ROOT = path.resolve(__dirname, "..", "..");
export const config = {
port: Number(process.env.PORT ?? 3100),
serverPassword: process.env.SPACEGAEM_PASSWORD ?? "",
dataFile: process.env.DATA_FILE || path.join(APP_ROOT, "data", "db.json"),
gmatBin:
process.env.GMAT_BIN ??
"/home/tyuxx/Projects/GMAT/GMAT-R2026a-Linux-x64/bin/GMAT-R2026a",
gmatConsoleBin: process.env.GMAT_CONSOLE_BIN ?? "",
gmatWorkDir: process.env.GMAT_WORK_DIR || path.join(APP_ROOT, ".gmat-work"),
simSecondsPerRealSecond: Number(process.env.SIM_RATE ?? 30),
aiEnabled: process.env.AI_DISABLED !== "1",
mlAiEnabled: process.env.ML_AI_ENABLED !== "0",
mlPythonBin: process.env.ML_PYTHON_BIN ?? "python3",
mlWeightsPath:
process.env.ML_WEIGHTS_PATH ||
path.join(APP_ROOT, "data", "ml_policy_weights.json"),
};

15
src/server/contracts.ts Normal file
View file

@ -0,0 +1,15 @@
// Export contract offer generation, custom contract builder, and lifecycle APIs.
export {
agencyTier,
deriveContract,
listContracts,
} from "./contracts/generator.js";
export {
createCustomContract,
type CustomContractInput,
} from "./contracts/custom.js";
export {
acceptContract,
recordContractCompletion,
clearActiveContract,
} from "./contracts/lifecycle.js";

View file

@ -0,0 +1,417 @@
// Creates custom and procedural multi-constraint orbital contracts with budget estimation and objectives.
import { PARTS, SPONSORS } from "../catalogs.js";
import { getWorld } from "../store.js";
import { computeLaunchWindow } from "../../shared/ephemeris.js";
import type {
AgencyState,
ContractOffer,
GroundNetworkTier,
MissionTemplate,
} from "../../shared/types.js";
import { currentEpoch } from "./generator.js";
export interface CustomContractInput {
proceduralConvoluted?: boolean;
name?: string;
description?: string;
target?: string;
periapsisKm?: number;
apoapsisKm?: number;
inclinationDeg?: number;
requiredDv?: number;
payloadMass?: number;
recommendedPayloadId?: string;
budget?: number;
maxGLoad?: number;
minFairingAltKm?: number;
crewed?: boolean;
crewCap?: number;
isReusable?: boolean;
isConvoluted?: boolean;
minSignalHealthPct?: number;
minPowerMarginPct?: number;
minEfficiencyScore?: number;
requiredGroundNetwork?: GroundNetworkTier;
eclipseFraction?: number;
radiationHazard?: "low" | "moderate" | "extreme";
requiredInstrumentsMin?: number;
}
const TARGET_PRESETS: Record<
string,
{
targetName: string;
baseDv: number;
apKm: number;
peKm: number;
incDeg: number;
payloadId: string;
payloadMass: number;
winSec: number;
}
> = {
vleo: {
targetName: "VLEO Earth Recon",
baseDv: 8700,
apKm: 280,
peKm: 240,
incDeg: 51.6,
payloadId: "payload-cubesat-2u",
payloadMass: 650,
winSec: 1800,
},
leo: {
targetName: "LEO Constellation",
baseDv: 9300,
apKm: 450,
peKm: 420,
incDeg: 51.6,
payloadId: "payload-hubble",
payloadMass: 4200,
winSec: 1800,
},
sso: {
targetName: "Sun-Synchronous Polar",
baseDv: 9800,
apKm: 720,
peKm: 700,
incDeg: 98.2,
payloadId: "payload-landsat8",
payloadMass: 2900,
winSec: 1500,
},
geo: {
targetName: "GEO / Molniya Relay",
baseDv: 12100,
apKm: 35786,
peKm: 500,
incDeg: 28.5,
payloadId: "payload-tdrs",
payloadMass: 3600,
winSec: 1800,
},
l1: {
targetName: "Sun-Earth L1/L2 Halo",
baseDv: 12500,
apKm: 1500000,
peKm: 220,
incDeg: 28.5,
payloadId: "payload-jwst",
payloadMass: 6200,
winSec: 2400,
},
lunar: {
targetName: "Lunar Polar Orbit",
baseDv: 13100,
apKm: 384400,
peKm: 120,
incDeg: 88.0,
payloadId: "payload-lro",
payloadMass: 2200,
winSec: 2000,
},
"moon-landing": {
targetName: "Lunar Surface South Pole",
baseDv: 14500,
apKm: 384400,
peKm: 100,
incDeg: 89.2,
payloadId: "payload-apollo-lm",
payloadMass: 15100,
winSec: 2200,
},
mars: {
targetName: "Mars Aerocapture Transfer",
baseDv: 14600,
apKm: 55000000,
peKm: 200,
incDeg: 28.5,
payloadId: "payload-perseverance",
payloadMass: 4100,
winSec: 2600,
},
asteroid: {
targetName: "Deep-Space Asteroid Rendezvous",
baseDv: 13400,
apKm: 32000000,
peKm: 200,
incDeg: 28.5,
payloadId: "payload-osiris",
payloadMass: 2400,
winSec: 2400,
},
jupiter: {
targetName: "Jovian Radiation Torus",
baseDv: 15300,
apKm: 628000000,
peKm: 300,
incDeg: 28.5,
payloadId: "payload-juno",
payloadMass: 4200,
winSec: 3200,
},
solar: {
targetName: "Inner Heliosphere / Venus Pass",
baseDv: 15600,
apKm: 140000000,
peKm: 250,
incDeg: 42.0,
payloadId: "payload-parker",
payloadMass: 1400,
winSec: 3000,
},
};
export function createCustomContract(
agency: AgencyState,
input: CustomContractInput,
): ContractOffer {
const simTime = getWorld().simTime;
const targets = Object.keys(TARGET_PRESETS);
let target =
input.target && TARGET_PRESETS[input.target] ? input.target : "geo";
let preset = TARGET_PRESETS[target];
let isConvoluted = input.isConvoluted ?? true;
let proceduralSeed = Math.floor(Math.random() * 9000 + 1000);
if (input.proceduralConvoluted) {
const convolutedPool = [
"sso",
"geo",
"l1",
"lunar",
"moon-landing",
"mars",
"asteroid",
"jupiter",
"solar",
];
target = convolutedPool[Math.floor(Math.random() * convolutedPool.length)];
preset = TARGET_PRESETS[target];
isConvoluted = true;
}
const apoapsisKm = Math.max(180, Number(input.apoapsisKm ?? preset.apKm));
const periapsisKm = Math.max(
120,
Math.min(apoapsisKm, Number(input.periapsisKm ?? preset.peKm)),
);
const inclinationDeg = Math.max(
0,
Math.min(
110,
Number(
input.inclinationDeg ??
(input.proceduralConvoluted
? Number((preset.incDeg + (Math.random() * 26 - 8)).toFixed(1))
: preset.incDeg),
),
),
);
const incPenaltyDv = Math.round(
Math.max(0, Math.abs(inclinationDeg - 28.5) * 14),
);
const eccRatio =
apoapsisKm <= 2000 ? Math.max(0, (apoapsisKm - 400) * 0.25) : 0;
const recommendedPayloadId =
input.recommendedPayloadId &&
PARTS.some(
(p) => p.id === input.recommendedPayloadId && p.kind === "payload",
)
? input.recommendedPayloadId
: preset.payloadId;
const recPart = PARTS.find((p) => p.id === recommendedPayloadId);
const rawPayloadMass = Math.max(
250,
Math.round(
Number(
input.payloadMass ??
(input.proceduralConvoluted
? Math.round(preset.payloadMass * (0.9 + Math.random() * 0.35))
: preset.payloadMass),
),
),
);
const payloadMass = recPart
? Math.max(rawPayloadMass, recPart.dryMass)
: rawPayloadMass;
const crewed =
input.crewed ??
(recommendedPayloadId === "payload-esas-crew" ||
recommendedPayloadId === "payload-apollo-lm" ||
recommendedPayloadId === "payload-gateway");
const crewCap = crewed
? Math.max(1, Math.min(6, Number(input.crewCap ?? 3)))
: undefined;
const isReusable =
input.isReusable ??
(input.proceduralConvoluted ? Math.random() > 0.45 : false);
const eclipseFraction = Math.max(
0.05,
Math.min(
0.45,
Number(input.eclipseFraction ?? (isConvoluted ? 0.28 : 0.16)),
),
);
const radiationHazard: "low" | "moderate" | "extreme" =
input.radiationHazard ??
(target === "jupiter" || target === "solar"
? "extreme"
: isConvoluted
? "moderate"
: "low");
const requiredGroundNetwork: GroundNetworkTier =
input.requiredGroundNetwork ??
(target === "jupiter"
? "optical-deep-space"
: [
"geo",
"l1",
"lunar",
"moon-landing",
"mars",
"asteroid",
"solar",
].includes(target)
? "global-dsn"
: "regional");
const minSignalHealthPct = Math.max(
45,
Math.min(
95,
Math.round(Number(input.minSignalHealthPct ?? (isConvoluted ? 76 : 62))),
),
);
const minPowerMarginPct = Math.max(
0,
Math.min(
50,
Math.round(Number(input.minPowerMarginPct ?? (isConvoluted ? 20 : 10))),
),
);
const minEfficiencyScore = Math.max(
35,
Math.min(
85,
Math.round(Number(input.minEfficiencyScore ?? (isConvoluted ? 64 : 50))),
),
);
const requiredInstrumentsMin = Math.max(
0,
Math.min(
4,
Math.round(
Number(input.requiredInstrumentsMin ?? (isConvoluted ? 2 : 0)),
),
),
);
const computedDv = Math.round(
preset.baseDv + eccRatio + Math.min(850, incPenaltyDv),
);
const requiredDv = Math.max(
8200,
Math.round(Number(input.requiredDv ?? computedDv)),
);
const tier =
requiredDv >= 13200 || payloadMass >= 9000
? 3
: requiredDv >= 11200 || isConvoluted
? 2
: requiredDv >= 9500
? 1
: 0;
const baseBudgetEstimate = Math.round(
(28_000_000 +
(requiredDv - 8500) * 18_500 +
payloadMass * 7_500 +
(isConvoluted ? 35_000_000 : 10_000_000) +
(crewed ? 45_000_000 : 0) +
requiredInstrumentsMin * 8_000_000 +
(requiredGroundNetwork === "optical-deep-space"
? 18_000_000
: requiredGroundNetwork === "global-dsn"
? 8_000_000
: 0)) *
(SPONSORS.find((s) => s.id === agency.sponsorId)?.budgetMult ?? 1.0),
);
const budget = Math.max(
25_000_000,
Math.round(Number(input.budget ?? baseBudgetEstimate)),
);
const title =
input.name?.trim() ||
(input.proceduralConvoluted
? `OP-${proceduralSeed}: Convoluted ${preset.targetName} Relay`
: `Custom Mission: ${preset.targetName}`);
const multiLegWaypoints = isConvoluted
? [
`Parking Orbit (${Math.round(Math.min(240, periapsisKm))} km @ ${inclinationDeg.toFixed(1)}°)`,
radiationHazard === "extreme"
? "High-Flux Radiation Belt Transit"
: "Eclipse Battery Hold",
`${preset.targetName} Insertion Burn`,
...(isReusable
? ["Booster Propulsive Recovery"]
: ["High-Rate Science Downlink"]),
]
: undefined;
const id = `custom-${Date.now()}-${proceduralSeed}`;
const win = computeLaunchWindow(target, simTime, preset.winSec);
const template: MissionTemplate = {
id,
name: title,
description:
input.description?.trim() ||
`Custom ${isConvoluted ? "convoluted multi-constraint" : "agency"} contract targeting ${periapsisKm}×${apoapsisKm} km (${inclinationDeg.toFixed(1)}°) with ${Math.round(eclipseFraction * 100)}% eclipse, ${radiationHazard} radiation, and >= ${minSignalHealthPct}% ground signal health.`,
requiredDv,
payloadMass,
recommendedPayloadId,
budget,
target,
targetName: preset.targetName,
targetOrbit: { periapsisKm, apoapsisKm, inclinationDeg },
maxGLoad: Math.max(
3.5,
Math.min(10, Number(input.maxGLoad ?? (crewed ? 4.5 : 6.8))),
),
minFairingAltKm: Math.max(
65,
Math.round(Number(input.minFairingAltKm ?? 90)),
),
launchWindowPeriodSec: preset.winSec,
tier,
crewed,
crewCap,
isReusable,
advanced: tier >= 1 || isConvoluted,
isConvoluted,
isCustom: true,
minSignalHealthPct,
minPowerMarginPct,
minEfficiencyScore,
requiredGroundNetwork,
eclipseFraction,
radiationHazard,
requiredInstrumentsMin,
multiLegWaypoints,
bonusObjectives: [
`Maintain >= ${minSignalHealthPct}% Ground Signal Health`,
`Achieve >= ${minPowerMarginPct}% EOL Bus Power Margin`,
...(requiredInstrumentsMin > 0
? [`Deploy >= ${requiredInstrumentsMin} Science Instruments`]
: []),
...(isReusable
? ["Reusable Stage 1 recovery kit"]
: [`Efficiency Grade target >= ${minEfficiencyScore}`]),
],
};
const offer: ContractOffer = {
...template,
templateId: template.id,
epoch: currentEpoch(),
windowPenaltyDv: win.penaltyDv,
windowPhase: win.phase,
isActive: true,
};
agency.missionId = offer.id;
agency.activeContract = offer;
return offer;
}

View file

@ -0,0 +1,289 @@
// Deterministic epoch contract derivation, contractor specialty matching, tier progression, and contract offer listing.
import { MISSIONS, PARTS, SPONSORS } from "../catalogs.js";
import { getMultipliers } from "../economy.js";
import { getWorld } from "../store.js";
import { computeLaunchWindow } from "../../shared/ephemeris.js";
import { normalizeDifficulty } from "../../shared/physics.js";
import type {
AgencyState,
CanonicalDifficulty,
ContractOffer,
MissionTemplate,
} from "../../shared/types.js";
export const EPOCH_SEC = 5400;
export const RECENT_LOCK = 3;
export const HISTORY_CAP = 16;
interface ContractorProfile {
color: string;
specialtyTargets: string[];
prefersConvoluted?: boolean;
prefersReusable?: boolean;
prefersCrewed?: boolean;
}
const CONTRACTOR_PROFILES: Record<string, ContractorProfile> = {
nasa: {
color: "#3b82f6",
specialtyTargets: ["leo", "lunar", "moon-landing", "l1"],
prefersCrewed: true,
},
esa: {
color: "#10b981",
specialtyTargets: ["sso", "l1", "mars", "vleo"],
prefersConvoluted: true,
},
jaxa: {
color: "#a855f7",
specialtyTargets: ["asteroid", "lunar", "mars", "jupiter", "solar"],
},
csa: {
color: "#ef4444",
specialtyTargets: ["leo", "geo", "l1", "lunar"],
prefersConvoluted: true,
prefersCrewed: true,
},
isro: {
color: "#f59e0b",
specialtyTargets: ["vleo", "sso", "geo", "lunar", "mars"],
},
gsdistance: {
color: "#06b6d4",
specialtyTargets: ["vleo", "leo", "geo", "sso"],
prefersReusable: true,
},
};
const DIFF_TIER_BONUS: Record<CanonicalDifficulty, number> = {
sandbox: 10,
explorer: 0,
enthusiast: 0,
engineer: 1,
director: 1,
};
const DIFF_DV_MULT: Record<CanonicalDifficulty, number> = {
sandbox: 0.95,
explorer: 0.97,
enthusiast: 1.0,
engineer: 1.04,
director: 1.08,
};
const DIFF_BUDGET_MULT: Record<CanonicalDifficulty, number> = {
sandbox: 1.5,
explorer: 1.25,
enthusiast: 1.0,
engineer: 0.88,
director: 0.76,
};
function hashStr(s: string): number {
let h = 2166136261;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
function mulberry32(seed: number): () => number {
return () => {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export function agencyTier(agency: AgencyState | null | undefined): number {
if (!agency) return 0;
let score = 0;
score += Math.max(0, (agency.reputation ?? 0) - 1) * 0.35;
score += (agency.missionsCompleted ?? 0) * 0.95;
score += DIFF_TIER_BONUS[normalizeDifficulty(agency.difficulty)] ?? 0;
return Math.max(0, Math.min(3, Math.floor(score)));
}
const MARKET_KINDS = new Set(["engine", "tank", "structure"]);
function marketIndex(): number {
const mult = getMultipliers();
const ids = PARTS.filter((p) => MARKET_KINDS.has(p.kind)).map((p) => p.id);
if (!ids.length) return 1;
return ids.reduce((s, id) => s + (mult[id] ?? 1), 0) / ids.length;
}
export function currentEpoch(): number {
return Math.floor(getWorld().simTime / EPOCH_SEC);
}
export function deriveContract(
agency: AgencyState,
template: MissionTemplate,
contractorIdOverride?: string,
): ContractOffer {
const ep = currentEpoch();
const simTime = getWorld().simTime;
const contractor =
SPONSORS.find((s) => s.id === (contractorIdOverride ?? agency.sponsorId)) ??
SPONSORS.find((s) => s.id === agency.sponsorId) ??
SPONSORS[0];
const contractorId = contractor?.id ?? "nasa";
const isHomeSponsor = contractorId === agency.sponsorId;
const loyaltyBonusPct = isHomeSponsor ? 8 : 0;
const offerId = `${contractorId}:${template.id}`;
const rnd = mulberry32(
hashStr(`${agency.name}|${contractorId}|${template.id}|${ep}`),
);
const tier = template.tier ?? 0;
const agencyLvl = agencyTier(agency);
const diff = normalizeDifficulty(agency.difficulty);
const contractorMult = contractor?.budgetMult ?? 1.0;
const dvJit = 0.96 + rnd() * 0.08;
const payJit = 0.92 + rnd() * 0.18;
const massJit = 0.9 + rnd() * 0.22;
const recPayload = template.recommendedPayloadId
? PARTS.find((p) => p.id === template.recommendedPayloadId)
: null;
const requiredDv = Math.round(
template.requiredDv *
dvJit *
(DIFF_DV_MULT[diff] ?? 1.0) *
(1 + Math.max(0, agencyLvl - tier) * 0.015),
);
const rawPayload = Math.max(100, Math.round(template.payloadMass * massJit));
const payloadMass = recPayload
? Math.max(rawPayload, recPayload.dryMass)
: rawPayload;
const budget = Math.round(
template.budget *
marketIndex() *
contractorMult *
(1 + loyaltyBonusPct / 100) *
(DIFF_BUDGET_MULT[diff] ?? 1.0) *
(1 + agencyLvl * 0.08) *
payJit,
);
const win = computeLaunchWindow(
template.target,
simTime,
template.launchWindowPeriodSec,
);
const activeOfferId = agency.activeContract?.offerId;
const isActive = activeOfferId
? activeOfferId === offerId
: agency.missionId === template.id && isHomeSponsor;
return {
...template,
templateId: template.id,
offerId,
contractorId,
contractorName: contractor?.name ?? "NASA",
contractorColor: CONTRACTOR_PROFILES[contractorId]?.color ?? "#38bdf8",
isHomeSponsor,
loyaltyBonusPct,
requiredDv,
payloadMass,
budget,
epoch: ep,
windowPenaltyDv: win.penaltyDv,
windowPhase: win.phase,
isActive,
};
}
export function recentSet(agency: AgencyState): Set<string> {
return new Set((agency.contractHistory ?? []).slice(-RECENT_LOCK));
}
export function tierAllowed(
agency: AgencyState,
template: MissionTemplate,
): boolean {
if (normalizeDifficulty(agency.difficulty) === "sandbox") return true;
if (template.isConvoluted || template.advanced) return true;
return (template.tier ?? 0) <= agencyTier(agency) + 1;
}
function resolvedEligibleTemplates(agency: AgencyState): MissionTemplate[] {
const tierEligible = MISSIONS.filter((t) => tierAllowed(agency, t));
const recent = recentSet(agency);
const nonLocked = tierEligible.filter((t) => !recent.has(t.id));
if (nonLocked.length > 0) return nonLocked;
if (tierEligible.length === 0) return [];
const history = agency.contractHistory ?? [];
const lastIndexOf = (id: string): number => {
for (let i = history.length - 1; i >= 0; i--) {
if (history[i] === id) return i;
}
return -1;
};
return [
[...tierEligible].sort((a, b) => lastIndexOf(a.id) - lastIndexOf(b.id))[0],
];
}
export function isEligible(
agency: AgencyState,
template: MissionTemplate,
): boolean {
return resolvedEligibleTemplates(agency).some((t) => t.id === template.id);
}
export function contractorCarriesTemplate(
contractorId: string,
template: MissionTemplate,
ep: number,
): boolean {
const prof = CONTRACTOR_PROFILES[contractorId];
const specialtyMatch =
!!prof &&
(prof.specialtyTargets.includes(template.target) ||
(prof.prefersConvoluted && template.isConvoluted) ||
(prof.prefersReusable && template.isReusable) ||
(prof.prefersCrewed && template.crewed));
const roll = (hashStr(`${contractorId}|${template.id}|${ep}`) % 1000) / 1000;
return roll < (specialtyMatch ? 0.64 : 0.36);
}
export function listContracts(agency: AgencyState): ContractOffer[] {
const ep = currentEpoch();
const eligibleTemplates = resolvedEligibleTemplates(agency);
const offers: ContractOffer[] = [];
for (const t of eligibleTemplates) {
let carriers = SPONSORS.filter((sp) =>
contractorCarriesTemplate(sp.id, t, ep),
);
if (carriers.length === 0) {
const idx = hashStr(`${t.id}|fallback|${ep}`) % SPONSORS.length;
carriers = [SPONSORS[idx]];
} else if (carriers.length > 4) {
carriers = carriers
.map((sp) => ({ sp, h: hashStr(`${sp.id}|cap|${t.id}|${ep}`) }))
.sort((a, b) => a.h - b.h)
.slice(0, 3 + (hashStr(t.id + ep) % 2))
.map((x) => x.sp);
}
for (const sp of carriers) {
offers.push(deriveContract(agency, t, sp.id));
}
}
if (agency.activeContract) {
const activeId = agency.activeContract.offerId ?? agency.activeContract.id;
if (!offers.some((o) => (o.offerId ?? o.id) === activeId)) {
offers.unshift({ ...agency.activeContract, isActive: true });
}
}
return offers.sort((a, b) =>
a.isActive
? -1
: b.isActive
? 1
: (a.tier ?? 0) - (b.tier ?? 0) ||
a.requiredDv - b.requiredDv ||
(a.isHomeSponsor ? -1 : b.isHomeSponsor ? 1 : 0),
);
}

View file

@ -0,0 +1,66 @@
// The contracts life is a short one, but... no that's it.
import { MISSIONS, SPONSORS } from "../catalogs.js";
import type { AgencyState, ContractOffer } from "../../shared/types.js";
import {
contractorCarriesTemplate,
currentEpoch,
deriveContract,
HISTORY_CAP,
isEligible,
recentSet,
tierAllowed,
} from "./generator.js";
export function acceptContract(
agency: AgencyState,
offerOrTemplateId: string,
): ContractOffer {
const parts = offerOrTemplateId.includes(":")
? offerOrTemplateId.split(":")
: [null, offerOrTemplateId];
const requestedContractorId = parts[0];
const templateId = parts[1] || offerOrTemplateId;
const template = MISSIONS.find((m) => m.id === templateId);
if (!template) throw new Error("Unknown contract template.");
if (!isEligible(agency, template)) {
const lockedByCooldown =
tierAllowed(agency, template) && recentSet(agency).has(template.id);
throw new Error(
lockedByCooldown
? "Contract on cooldown: complete 3 other contracts before repeating this mission."
: "That contract is currently locked by progression.",
);
}
let contractorId = requestedContractorId;
if (!contractorId) {
const ep = currentEpoch();
const activeCarriers = SPONSORS.filter((sp) =>
contractorCarriesTemplate(sp.id, template, ep),
);
const home = activeCarriers.find((sp) => sp.id === agency.sponsorId);
contractorId =
home?.id ?? activeCarriers[0]?.id ?? agency.sponsorId ?? "nasa";
}
if (!SPONSORS.some((sp) => sp.id === contractorId)) {
throw new Error("Unknown contractor agency.");
}
const contract = deriveContract(agency, template, contractorId);
agency.missionId = template.id;
agency.activeContract = contract;
return contract;
}
export function recordContractCompletion(
agency: AgencyState,
templateId: string,
): void {
agency.contractHistory = [
...(agency.contractHistory ?? []),
templateId,
].slice(-HISTORY_CAP);
}
export function clearActiveContract(agency: AgencyState): void {
agency.missionId = null;
agency.activeContract = null;
}

101
src/server/economy.ts Normal file
View file

@ -0,0 +1,101 @@
// Treasury adjustments, mission settlement accounting, bailouts, bankruptcy termination, and safety scoring.
import { MATERIALS, PARTS } from "./catalogs.js";
import { markDirty, type WorldRecord } from "./store.js";
import type { MaterialSpec, Part, RocketDesign } from "../shared/types.js";
import { buildRocket } from "../shared/physics.js";
const PART_MAP = new Map(PARTS.map((p) => [p.id, p]));
const MAT_MAP = new Map(MATERIALS.map((m) => [m.id, m]));
let multipliers: Record<string, number> = {};
export function initEconomy(world: WorldRecord): void {
world.market ??= {};
multipliers = world.market;
for (const p of PARTS) {
multipliers[p.id] ??= 0.94 + Math.random() * 0.14;
}
for (const m of MATERIALS) {
multipliers[`mat:${m.id}`] ??= 0.95 + Math.random() * 0.12;
}
markDirty();
}
export function getMultipliers(): Record<string, number> {
return multipliers;
}
export function partUnitPrice(part: Part, material?: MaterialSpec): number {
const partMult = multipliers[part.id] ?? 1.0;
const matMult = material
? (multipliers[`mat:${material.id}`] ?? 1.0) * material.costFactor
: 1.0;
return Math.round(part.cost * partMult * matMult);
}
export function getPrices() {
return [
...PARTS.filter((p) => p.kind !== "payload").map((p) => ({
id: p.id,
kind: p.kind,
name: p.name,
baseCost: p.cost,
price: Math.round(p.cost * (multipliers[p.id] ?? 1)),
changePct: Math.round(((multipliers[p.id] ?? 1) - 1) * 1000) / 10,
})),
...MATERIALS.map((m) => ({
id: `mat:${m.id}`,
kind: "material",
name: m.name,
baseCost: Math.round(m.costFactor * 100),
price: Math.round(m.costFactor * 100 * (multipliers[`mat:${m.id}`] ?? 1)),
changePct:
Math.round(((multipliers[`mat:${m.id}`] ?? 1) - 1) * 1000) / 10,
})),
];
}
export function designCost(design: RocketDesign): number {
const assembly = buildRocket(design, PARTS, MATERIALS, partUnitPrice);
return assembly.totalCost;
}
export function recordDesignDemand(design: RocketDesign): void {
for (const st of design.stages ?? []) {
const bump = (key: string, amount: number) => {
if (multipliers[key] != null) {
multipliers[key] = Math.min(2.6, multipliers[key] + amount);
}
};
bump(st.engineId, 0.015 * Math.max(1, st.engineCount * 0.4));
bump(st.tankId, 0.018);
bump(st.structureId, 0.012);
bump(`mat:${st.materialId}`, 0.016);
}
if (design.fairingId) {
const k = design.fairingId;
if (multipliers[k] != null)
multipliers[k] = Math.min(2.6, multipliers[k] + 0.01);
}
markDirty();
}
export function tickEconomy(): void {
for (const id of Object.keys(multipliers)) {
const drift = (Math.random() - 0.5) * 0.024;
const meanRevert = (1 - multipliers[id]) * 0.008;
multipliers[id] = Math.min(
2.6,
Math.max(0.55, multipliers[id] + drift + meanRevert),
);
}
markDirty();
}
export function getPartCatalogMap() {
return PART_MAP;
}
export function getMaterialCatalogMap() {
return MAT_MAP;
}

18
src/server/events.ts Normal file
View file

@ -0,0 +1,18 @@
// In-memory EventEmitter bus for SSE's across world ticks and mission telemetry.
export interface ServerEvent {
type: string;
data: Record<string, unknown>;
at: number;
}
type Broadcaster = (ev: ServerEvent) => void;
let broadcaster: Broadcaster | null = null;
export function setBroadcaster(fn: Broadcaster): void {
broadcaster = fn;
}
export function emit(type: string, data: Record<string, unknown> = {}): void {
broadcaster?.({ type, data, at: Date.now() });
}

320
src/server/gmat_runner.ts Normal file
View file

@ -0,0 +1,320 @@
// Runs GMAT console trajectories asynchronously with analytic Keplerian ephemeris fallback.
// So like.
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { config } from "./config.js";
import {
enrichTrajectoryPoint,
generateTrajectory,
orbitForTarget,
} from "../shared/ephemeris.js";
import type { TrajectoryPoint, TrajectoryResult } from "../shared/types.js";
const execFileAsync = promisify(execFile);
interface GmatTargetDef {
sma: number;
ecc: number;
inc: number;
raan: number;
aop: number;
ta: number;
days: number;
body: "Earth" | "Sun";
}
const TARGET_ORBITS: Record<string, GmatTargetDef> = {
vleo: {
sma: 6611,
ecc: 0.002,
inc: 51.6,
raan: 120,
aop: 80,
ta: 0,
days: 0.35,
body: "Earth",
},
leo: {
sma: 6791,
ecc: 0.002,
inc: 51.6,
raan: 120,
aop: 80,
ta: 0,
days: 0.45,
body: "Earth",
},
sso: {
sma: 7076,
ecc: 0.001,
inc: 98.2,
raan: 100,
aop: 80,
ta: 0,
days: 0.5,
body: "Earth",
},
geo: {
sma: 42164,
ecc: 0.0005,
inc: 0.5,
raan: 0,
aop: 0,
ta: 0,
days: 1.0,
body: "Earth",
},
l1: {
sma: 750000,
ecc: 0.985,
inc: 28.5,
raan: 45,
aop: 160,
ta: 0,
days: 12,
body: "Earth",
},
lunar: {
sma: 192000,
ecc: 0.96,
inc: 28.5,
raan: 60,
aop: 180,
ta: 0,
days: 10,
body: "Earth",
},
mars: {
sma: 188800000,
ecc: 0.21,
inc: 1.85,
raan: 49.5,
aop: 336.06,
ta: 0,
days: 180,
body: "Sun",
},
asteroid: {
sma: 158500000,
ecc: 0.14,
inc: 6.0,
raan: 2.0,
aop: 66.2,
ta: 0,
days: 150,
body: "Sun",
},
jupiter: {
sma: 463700000,
ecc: 0.68,
inc: 1.3,
raan: 100.5,
aop: 273.8,
ta: 0,
days: 420,
body: "Sun",
},
solar: {
sma: 83800000,
ecc: 0.78,
inc: 3.4,
raan: 45,
aop: 120,
ta: 0,
days: 120,
body: "Sun",
},
};
const N_CHUNKS = 200;
function buildGmatScript(def: GmatTargetDef): string {
const isHelio = def.body === "Sun";
const coordSys = isHelio ? "SunMJ2000Eq" : "EarthMJ2000Eq";
const pointMasses = isHelio
? "{Earth, Luna, Mars, Jupiter, Sun}"
: "{Earth, Luna, Sun}";
const lines = [
"% Auto-generated Space Gaem trajectory script",
...(isHelio
? [
"Create CoordinateSystem SunMJ2000Eq;",
"SunMJ2000Eq.Origin = Sun;",
"SunMJ2000Eq.Axes = MJ2000Eq;",
"",
]
: []),
"Create Spacecraft SC;",
"SC.DateFormat = UTCGregorian;",
"SC.Epoch = '01 Jan 2026 00:00:00.000';",
`SC.CoordinateSystem = ${coordSys};`,
"SC.DisplayStateType = Keplerian;",
"SC.AnomalyType = TA;",
`SC.SMA = ${def.sma};`,
`SC.ECC = ${def.ecc};`,
`SC.INC = ${def.inc};`,
`SC.RAAN = ${def.raan};`,
`SC.AOP = ${def.aop};`,
`SC.TA = ${def.ta};`,
"SC.DryMass = 1000;",
"",
"Create ForceModel FM;",
`FM.CentralBody = ${def.body};`,
`FM.PointMasses = ${pointMasses};`,
"FM.Drag = None;",
"FM.SRP = Off;",
"FM.ErrorControl = RSSStep;",
"",
"Create Propagator PROP;",
"PROP.FM = FM;",
"PROP.Type = RungeKutta89;",
"PROP.InitialStepSize = 60;",
"PROP.Accuracy = 1e-10;",
"PROP.MinStep = 0.001;",
"PROP.MaxStep = 86400;",
"PROP.MaxStepAttempts = 50;",
"",
"BeginMissionSequence",
"",
];
const chunkDays = def.days / N_CHUNKS;
for (let i = 0; i < N_CHUNKS; i++) {
lines.push(`Propagate PROP(SC) {SC.ElapsedDays = ${chunkDays.toFixed(8)}}`);
lines.push(
`Write SC.UTCGregorian SC.${coordSys}.X SC.${coordSys}.Y SC.${coordSys}.Z`,
);
}
lines.push("");
return lines.join("\n");
}
function parseGmatStdout(stdout: string): TrajectoryPoint[] {
const lines = stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const points: TrajectoryPoint[] = [];
for (let i = 0; i + 3 < lines.length; i++) {
const x = Number(lines[i + 1]);
const y = Number(lines[i + 2]);
const z = Number(lines[i + 3]);
if (
Number.isFinite(x) &&
Number.isFinite(y) &&
Number.isFinite(z) &&
/[A-Z][a-z]{2}/.test(lines[i])
) {
points.push({ t: points.length, x, y, z });
i += 3;
}
}
return points;
}
export function resolveGmatConsoleBin(): string | null {
if (config.gmatConsoleBin) {
return fs.existsSync(config.gmatConsoleBin) ? config.gmatConsoleBin : null;
}
const gmatDir = path.dirname(config.gmatBin);
if (fs.existsSync(gmatDir)) {
const found = fs
.readdirSync(gmatDir)
.find((f) => /^GmatConsole/.test(f) && !f.includes(".so"));
if (found) return path.join(gmatDir, found);
}
return null;
}
export async function runTrajectory(
target: string,
opts: { altKm?: number; incDeg?: number } = {},
): Promise<TrajectoryResult> {
const key = target === "moon-landing" ? "lunar" : target;
const baseDef = TARGET_ORBITS[key] ?? TARGET_ORBITS.leo;
const def: GmatTargetDef = {
...baseDef,
sma:
baseDef.body === "Earth" &&
opts.altKm &&
key !== "lunar" &&
key !== "l1" &&
key !== "geo"
? 6371 + opts.altKm
: baseDef.sma,
inc: opts.incDeg ?? baseDef.inc,
};
const durationSec = def.days * 86400;
const analytic = generateTrajectory(key, durationSec, 280, opts);
const consoleBin = resolveGmatConsoleBin();
if (!consoleBin) {
return {
...analytic,
source: "analytic",
reason: "GMAT console binary not available",
};
}
const gmatDir = path.dirname(consoleBin);
fs.mkdirSync(config.gmatWorkDir, { recursive: true });
const baseName = `${key}-${Date.now()}-${Math.floor(Math.random() * 999)}`;
const scriptPath = path.join(config.gmatWorkDir, `${baseName}.script`);
const logPath = path.join(config.gmatWorkDir, `${baseName}.log`);
const cleanup = () => {
fs.unlink(scriptPath, () => {});
fs.unlink(logPath, () => {});
};
try {
fs.writeFileSync(scriptPath, buildGmatScript(def));
const { stdout } = await execFileAsync(
consoleBin,
["-l", logPath, "-r", scriptPath],
{
cwd: gmatDir,
timeout: 30_000,
maxBuffer: 32 * 1024 * 1024,
},
);
cleanup();
const points = parseGmatStdout(stdout);
if (points.length > 10) {
const orb = orbitForTarget(key, opts);
const enriched = points.map((p, idx) => {
const t = (idx / (points.length - 1)) * durationSec;
const analyticPt =
analytic.points[
Math.min(
analytic.points.length - 1,
Math.round(
(idx / (points.length - 1)) * (analytic.points.length - 1),
),
)
];
const rGmat = Math.hypot(p.x, p.y, p.z);
const rAnalytic = analyticPt
? Math.hypot(analyticPt.x, analyticPt.y, analyticPt.z)
: rGmat;
const radialDrift = Math.abs(rGmat - rAnalytic);
return enrichTrajectoryPoint(orb, t, p.x, p.y, p.z, radialDrift);
});
return {
points: enriched,
period: analytic.period,
target: key,
source: "gmat",
};
}
return {
...analytic,
source: "analytic",
reason: `GMAT returned ${points.length} points`,
};
} catch (err) {
cleanup();
return {
...analytic,
source: "analytic",
reason: String((err as Error).message ?? err).slice(0, 160),
};
}
}

170
src/server/hazards.ts Normal file
View file

@ -0,0 +1,170 @@
// Manages world simulation clock, stochastic (stochastic fractal search algorithms mentioned?) space weather, and deterministic epoch orbital hazards.
import { emit } from "./events.js";
import { getWorld, markDirty } from "./store.js";
import type {
HazardKind,
PreLaunchHazardEvent,
SpaceWeather,
} from "../shared/types.js";
export const WEATHER_POOL: SpaceWeather[] = [
"nominal",
"nominal",
"nominal",
"nominal",
"solar-wind",
"solar-storm",
"micrometeoroid",
"radiation-storm",
];
const HAZARD_WINDOW_SEC = 2400;
function seededRand(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function buildHazardEvent(epoch: number, slot: number): PreLaunchHazardEvent {
const rnd = seededRand(epoch * 7919 + slot * 3571 + 17);
const kinds: HazardKind[] = [
"stray-radiation",
"meteorite-stream",
"jet-stream-shear",
];
const kind = kinds[(epoch + slot) % kinds.length];
const startsAtSimTime = epoch * HAZARD_WINDOW_SEC;
const endsAtSimTime =
startsAtSimTime + Math.round(HAZARD_WINDOW_SEC * (1.2 + rnd() * 0.55));
const sevRoll = rnd();
const severity: PreLaunchHazardEvent["severity"] =
sevRoll > 0.78 ? "extreme" : sevRoll > 0.42 ? "severe" : "moderate";
if (kind === "stray-radiation") {
const radFluxMultiplier = Number(
(severity === "extreme"
? 5.6
: severity === "severe"
? 4.4
: 3.4
).toFixed(2),
);
return {
id: `haz-${epoch}-${slot}-rad`,
kind,
title: "Solar Proton / SAA Flux Spike",
severity,
altMinKm: 65,
altMaxKm: 1200,
startsAtSimTime,
endsAtSimTime,
radFluxMultiplier,
description: `Elevated trapped proton & cosmic-ray flux (${radFluxMultiplier}x baseline) crossing 65–1200 km altitude band.`,
countermeasureHint:
"Equip Rad-Hardened Flight Computer (Rad-Hard >= 2), Fault-Tolerant Scrubbing, or unlock tier-2/3 Diagnostics.",
};
}
if (kind === "meteorite-stream") {
const impactRiskPct = Math.round(
severity === "extreme" ? 26 : severity === "severe" ? 20 : 14,
);
return {
id: `haz-${epoch}-${slot}-met`,
kind,
title: "Sporadic Taurid Micrometeoroid Stream",
severity,
altMinKm: 85,
altMaxKm: 450,
startsAtSimTime,
endsAtSimTime,
impactRiskPct,
description: `Debris/micrometeoroid density peak (~${impactRiskPct}% baseline collision risk) between 85–450 km.`,
countermeasureHint:
"Use Carbon-Epoxy or Stainless 304L airframe, Whipple heatshield, or raise Fairing Jettison >= 115 km.",
};
}
const windShearQMult = Number(
(severity === "extreme"
? 1.44
: severity === "severe"
? 1.35
: 1.28
).toFixed(2),
);
return {
id: `haz-${epoch}-${slot}-shear`,
kind,
title: "Upper-Troposphere Jet Stream Shear",
severity,
altMinKm: 8,
altMaxKm: 24,
startsAtSimTime,
endsAtSimTime,
windShearQMult,
description: `Severe upper-level crosswind shear (${windShearQMult}x Max-Q load impulse) in 8–24 km corridor.`,
countermeasureHint:
"Install aerodynamic fins, cap Max-Q TWR <= 1.8, or arm Flight Computer active throttling.",
};
}
export function ensureHazards(simTime: number): void {
const world = getWorld();
const curEpoch = Math.floor(simTime / HAZARD_WINDOW_SEC);
if (
world.hazardEpoch === curEpoch &&
(world.activeHazards?.length || world.upcomingHazards?.length)
) {
return;
}
const prevActiveIds = (world.activeHazards ?? []).map((h) => h.id).join(",");
const active: PreLaunchHazardEvent[] = [buildHazardEvent(curEpoch, 0)];
if (curEpoch % 2 === 1) {
active.push(buildHazardEvent(curEpoch, 1));
}
const upcoming: PreLaunchHazardEvent[] = [
buildHazardEvent(curEpoch + 1, 0),
buildHazardEvent(curEpoch + 2, 1),
];
world.activeHazards = active;
world.upcomingHazards = upcoming;
world.hazardEpoch = curEpoch;
const nextActiveIds = active.map((h) => h.id).join(",");
if (prevActiveIds !== nextActiveIds) {
emit("world.hazards", { activeHazards: active, upcomingHazards: upcoming });
}
}
export function getActiveHazards(): PreLaunchHazardEvent[] {
const world = getWorld();
ensureHazards(world.simTime);
return world.activeHazards ?? [];
}
export function getUpcomingHazards(): PreLaunchHazardEvent[] {
const world = getWorld();
ensureHazards(world.simTime);
return world.upcomingHazards ?? [];
}
export function initWorld(): void {
const world = getWorld();
world.simTime = world.simTime || Math.floor(Date.now() / 1000);
if (!world.weatherUntil || world.weatherUntil < world.simTime) {
world.weather = "nominal";
world.weatherUntil = world.simTime + 2400;
}
ensureHazards(world.simTime);
markDirty();
}
export function getSimTime(): number {
return getWorld().simTime;
}
export function getWeather(): SpaceWeather {
return getWorld().weather;
}

78
src/server/index.ts Normal file
View file

@ -0,0 +1,78 @@
// HTTP and Express server entrypoint mounting API routes, static bundles/assets, and starting background loops.
import express, { type Response } from "express";
import fs from "node:fs";
import path from "node:path";
import { seedAI } from "./ai.js";
import { APP_ROOT, config } from "./config.js";
import { initEconomy } from "./economy.js";
import { setBroadcaster } from "./events.js";
import { resolveGmatConsoleBin } from "./gmat_runner.js";
import { apiRouter } from "./routes.js";
import { getWorld, loadDb } from "./store.js";
import { initWorld, tick } from "./world.js";
const app = express();
app.use(express.json({ limit: "4mb" }));
app.use("/api", apiRouter);
const sseClients = new Set<Response>();
setBroadcaster((event) => {
const payload = `data: ${JSON.stringify(event)}\n\n`;
for (const res of sseClients) {
try {
res.write(payload);
} catch {
sseClients.delete(res);
}
}
});
app.get("/api/events", (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
});
res.write(`data: ${JSON.stringify({ type: "hello", at: Date.now() })}\n\n`);
sseClients.add(res);
req.on("close", () => sseClients.delete(res));
});
app.use("/bundle", express.static(path.join(APP_ROOT, "dist", "bundle")));
app.use(express.static(path.join(APP_ROOT, "public")));
app.use("/data", express.static(path.join(APP_ROOT, "data")));
const modelsDir = path.join(APP_ROOT, "models");
if (fs.existsSync(modelsDir)) {
app.use("/models", express.static(modelsDir, { maxAge: "1h" }));
}
app.get(/.*/, (req, res, next) => {
if (req.path.startsWith("/api/")) {
next();
return;
}
res.sendFile(path.join(APP_ROOT, "public", "index.html"));
});
loadDb();
initWorld();
initEconomy(getWorld());
seedAI();
setInterval(tick, 1000);
app.listen(config.port, () => {
const gmatConsole = resolveGmatConsoleBin();
console.log(
`Space Gaem: You Will Feel the Pain (TypeScript Prototype) on http://localhost:${config.port}`,
);
console.log(
` GMAT: ${gmatConsole ?? "NOT FOUND (analytic ephemeris fallback)"}`,
);
console.log(
` Server password: ${config.serverPassword ? "required" : "none"}`,
);
});

158
src/server/ml/bridge.ts Normal file
View file

@ -0,0 +1,158 @@
// Manages Python subprocess ML bridge probing, toggle state, request deduplication, and decision cache.
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { APP_ROOT, config } from "../config.js";
import { emit } from "../events.js";
import type { MlBridgeStatus, MlDecision } from "./types.js";
const SCRIPT_PATH = path.join(APP_ROOT, "scripts", "ml_agent.py");
const WEIGHTS_PATH = config.mlWeightsPath;
export const mlBridgeState: {
enabled: boolean;
pythonAvailable: boolean;
lastProbeStatus: MlBridgeStatus;
} = {
enabled: config.mlAiEnabled,
pythonAvailable: false,
lastProbeStatus: {
enabled: config.mlAiEnabled,
pythonAvailable: false,
pythonBin: config.mlPythonBin,
pythonVersion: null,
backend: config.mlAiEnabled
? "ts-contextual-bandit"
: "disabled-standard-fallback",
availablePackages: [],
episodes: 0,
avgReward: 0,
lastError: null,
lastCheckedAt: 0,
},
};
export const decisionCache = new Map<
string,
{ at: number; decision: MlDecision }
>();
export const pendingRequests = new Set<string>();
export function runPythonBridge<T = Record<string, any>>(
action: "status" | "predict" | "train",
payload?: Record<string, unknown>,
): Promise<T | null> {
return new Promise((resolve) => {
if (!fs.existsSync(SCRIPT_PATH)) {
resolve(null);
return;
}
const args = [SCRIPT_PATH, action, "--weights", WEIGHTS_PATH];
if (payload) {
args.push("--payload", JSON.stringify(payload));
}
const child = execFile(
config.mlPythonBin,
args,
{ timeout: 3500, maxBuffer: 2 * 1024 * 1024 },
(err, stdout) => {
if (err) {
mlBridgeState.lastProbeStatus.lastError = String(
err.message ?? err,
).slice(0, 140);
resolve(null);
return;
}
try {
const parsed = JSON.parse(String(stdout).trim()) as T & {
ok?: boolean;
};
if (!parsed || (parsed as any).ok === false) {
resolve(null);
return;
}
resolve(parsed);
} catch {
resolve(null);
}
},
);
child.stdin?.end();
});
}
export function isMlAiEnabled(): boolean {
return mlBridgeState.enabled;
}
export async function getMlBridgeStatus(
forceProbe = false,
): Promise<MlBridgeStatus> {
const stale =
Date.now() - mlBridgeState.lastProbeStatus.lastCheckedAt > 15_000;
if (!mlBridgeState.enabled) {
mlBridgeState.lastProbeStatus = {
...mlBridgeState.lastProbeStatus,
enabled: false,
backend: "disabled-standard-fallback",
};
return mlBridgeState.lastProbeStatus;
}
if (
!forceProbe &&
!stale &&
mlBridgeState.lastProbeStatus.lastCheckedAt > 0
) {
return mlBridgeState.lastProbeStatus;
}
const res = await runPythonBridge<{
ok: boolean;
pythonVersion?: string;
backend?: string;
availablePackages?: string[];
episodes?: number;
avgReward?: number;
}>("status");
if (res && res.ok) {
mlBridgeState.pythonAvailable = true;
mlBridgeState.lastProbeStatus = {
enabled: true,
pythonAvailable: true,
pythonBin: config.mlPythonBin,
pythonVersion: res.pythonVersion ?? null,
backend: res.backend ?? "python-stdlib-mlp",
availablePackages: res.availablePackages ?? [],
episodes: Number(res.episodes ?? 0),
avgReward: Number(res.avgReward ?? 0),
lastError: null,
lastCheckedAt: Date.now(),
};
} else {
mlBridgeState.pythonAvailable = false;
mlBridgeState.lastProbeStatus = {
enabled: true,
pythonAvailable: false,
pythonBin: config.mlPythonBin,
pythonVersion: null,
backend: "ts-contextual-bandit",
availablePackages: [],
episodes: mlBridgeState.lastProbeStatus.episodes,
avgReward: mlBridgeState.lastProbeStatus.avgReward,
lastError:
mlBridgeState.lastProbeStatus.lastError ??
"Python interpreter unavailable; using TypeScript ML policy fallback",
lastCheckedAt: Date.now(),
};
}
return mlBridgeState.lastProbeStatus;
}
export async function setMlAiEnabled(
enabled: boolean,
): Promise<MlBridgeStatus> {
mlBridgeState.enabled = enabled;
decisionCache.clear();
const status = await getMlBridgeStatus(true);
emit("ml.status", status as unknown as Record<string, unknown>);
return status;
}
void getMlBridgeStatus(true);

259
src/server/ml/policy.ts Normal file
View file

@ -0,0 +1,259 @@
// Provides TypeScript fallback contextual bandit policy, async Python policy inference, and episode reward training.
import { listAgencies, putAgency } from "../store.js";
import type {
ActiveMission,
AgencyState,
ContractOffer,
MissionSettlement,
PreLaunchHazardEvent,
SpaceWeather,
} from "../../shared/types.js";
import {
decisionCache,
mlBridgeState,
pendingRequests,
runPythonBridge,
} from "./bridge.js";
import type { MlDecision } from "./types.js";
function fallbackMlDecision(
agency: AgencyState,
candidates: ContractOffer[],
weather: SpaceWeather,
hazards: PreLaunchHazardEvent[],
): MlDecision {
const hasShear = hazards.some((h) => h.kind === "jet-stream-shear");
const hasRad =
hazards.some((h) => h.kind === "stray-radiation") ||
weather === "radiation-storm" ||
weather === "solar-storm";
const skill = agency.aiSkill ?? 0.85;
const unlocked = new Set(agency.unlockedTechs ?? ["starter"]);
const hasHighIsp =
agency.difficulty === "sandbox" ||
agency.difficulty === "explorer" ||
unlocked.has("cryo-hydrolox") ||
unlocked.has("methalox-reusable") ||
unlocked.has("heavy-lift") ||
unlocked.has("deep-space-ion");
let best: ContractOffer | null = null;
let bestScore = -1e9;
for (const c of candidates) {
const reqDv = c.requiredDv ?? 9400;
const estCost = Math.max(
6_000_000,
(reqDv / 9500) * 14_500_000 + (c.tier ?? 0) * 5_500_000,
);
const budgetPerDv = c.budget / 1e6 / Math.max(1, reqDv / 1000);
const homeBonus = c.isHomeSponsor ? 0.65 : 0;
const radPenalty = hasRad && c.radiationHazard === "extreme" ? -0.8 : 0;
const riskPenalty = c.crewed && skill < 0.7 ? -0.4 : 0;
const lockPenalty = !hasHighIsp && reqDv > 9800 ? -2.4 : 0;
const affordPenalty = estCost > agency.treasury * 0.68 ? -2.5 : 0;
const score =
budgetPerDv +
homeBonus +
(c.tier ?? 0) * 0.25 +
radPenalty +
riskPenalty +
lockPenalty +
affordPenalty;
if (score > bestScore) {
bestScore = score;
best = c;
}
}
const bestDv = best?.requiredDv ?? 9500;
return {
selectedOfferId: best?.offerId ?? best?.id ?? null,
selectedTemplateId: best?.templateId ?? best?.id ?? null,
policyConfidence: mlBridgeState.enabled ? 0.82 : 0.64,
suggestedPitchKickDeg: hasShear
? 7.4
: bestDv > 10600
? 10.1
: Number((8.8 + skill * 1.1).toFixed(1)),
suggestedMaxQThrottle: hasShear ? 0.66 : 0.78,
suggestedPreferRadHard: hasRad || best?.radiationHazard === "extreme",
backend: mlBridgeState.enabled
? "ts-contextual-bandit"
: "standard-ai-fallback",
};
}
export function predictMlDecisionSync(
agency: AgencyState,
candidates: ContractOffer[],
weather: SpaceWeather,
hazards: PreLaunchHazardEvent[],
): MlDecision {
if (!mlBridgeState.enabled || !candidates.length) {
return fallbackMlDecision(agency, candidates, weather, hazards);
}
const cacheKey = `${agency.name}|${candidates[0]?.epoch ?? 0}|${candidates.length}|${agency.unlockedTechs?.length ?? 1}|${Math.floor(agency.treasury / 12e6)}`;
const cached = decisionCache.get(cacheKey);
if (cached && Date.now() - cached.at < 20_000) {
return cached.decision;
}
if (!pendingRequests.has(cacheKey)) {
pendingRequests.add(cacheKey);
const slimCandidates = candidates.slice(0, 14).map((c) => ({
offerId: c.offerId ?? c.id,
id: c.id,
templateId: c.templateId ?? c.id,
requiredDv: c.requiredDv,
payloadMass: c.payloadMass ?? 0,
budget: c.budget,
tier: c.tier ?? 0,
isHomeSponsor: !!c.isHomeSponsor,
radiationHazard: c.radiationHazard ?? "low",
}));
void runPythonBridge<{
ok: boolean;
backend?: string;
selectedOfferId?: string;
selectedTemplateId?: string;
policyConfidence?: number;
suggestedPitchKickDeg?: number;
suggestedMaxQThrottle?: number;
suggestedPreferRadHard?: boolean;
}>("predict", {
agency: {
name: agency.name,
treasury: agency.treasury,
aiSkill: agency.aiSkill ?? 0.85,
reputation: agency.reputation,
difficulty: agency.difficulty,
unlockedTechs: agency.unlockedTechs ?? ["starter"],
},
candidates: slimCandidates,
weather,
hazards: hazards.map((h) => ({ kind: h.kind, severity: h.severity })),
})
.then((res) => {
if (res && res.ok) {
mlBridgeState.pythonAvailable = true;
decisionCache.set(cacheKey, {
at: Date.now(),
decision: {
selectedOfferId: res.selectedOfferId ?? null,
selectedTemplateId: res.selectedTemplateId ?? null,
policyConfidence: res.policyConfidence ?? 0.8,
suggestedPitchKickDeg: res.suggestedPitchKickDeg ?? 9.2,
suggestedMaxQThrottle: res.suggestedMaxQThrottle ?? 0.78,
suggestedPreferRadHard: !!res.suggestedPreferRadHard,
backend: res.backend ?? "python-stdlib-mlp",
},
});
if (!agency.mlStats) {
agency.mlStats = {
episodes: 0,
avgReward: 0,
backend: res.backend ?? "python-stdlib-mlp",
};
} else {
agency.mlStats.backend = res.backend ?? agency.mlStats.backend;
}
}
})
.finally(() => {
pendingRequests.delete(cacheKey);
});
}
return fallbackMlDecision(agency, candidates, weather, hazards);
}
export function recordMlEpisodeOutcome(
agency: AgencyState,
mission: ActiveMission,
settlement: MissionSettlement,
): void {
if (!agency.isAI || agency.aiType !== "ml") return;
const baseReward = settlement.success
? settlement.orbitGrade === "nominal"
? 1.0
: 0.5
: -0.65;
const roiTerm = Math.max(
-0.35,
Math.min(
0.6,
(settlement.netCashChange / Math.max(1e6, mission.cost)) * 0.25,
),
);
const safetyPenalty = (settlement.casualties ?? 0) > 0 ? -0.45 : 0;
const reward = Number(
Math.max(-1.5, Math.min(2.0, baseReward + roiTerm + safetyPenalty)).toFixed(
3,
),
);
const prev = agency.mlStats ?? {
episodes: 0,
avgReward: 0,
backend: mlBridgeState.enabled
? mlBridgeState.lastProbeStatus.backend
: "standard-ai-fallback",
};
const nextEp = prev.episodes + 1;
const nextAvg = Number(
((prev.episodes * prev.avgReward + reward) / nextEp).toFixed(3),
);
agency.mlStats = {
episodes: nextEp,
avgReward: nextAvg,
backend: mlBridgeState.enabled
? mlBridgeState.lastProbeStatus.backend
: "standard-ai-fallback",
lastUpdated: Date.now(),
};
if (!mlBridgeState.enabled) return;
void runPythonBridge<{
ok: boolean;
backend?: string;
episodes?: number;
avgReward?: number;
}>("train", {
agencyName: agency.name,
reward,
agency: {
name: agency.name,
treasury: agency.treasury,
aiSkill: agency.aiSkill ?? 0.75,
},
candidate: {
requiredDv: mission.contract?.requiredDv ?? 9500,
budget: mission.contract?.budget ?? 20e6,
tier: mission.contract?.tier ?? 0,
isHomeSponsor: !!mission.contract?.isHomeSponsor,
},
weather: "nominal",
hazards: [],
}).then((res) => {
if (res && res.ok) {
mlBridgeState.lastProbeStatus.episodes = Number(
res.episodes ?? mlBridgeState.lastProbeStatus.episodes,
);
mlBridgeState.lastProbeStatus.avgReward = Number(
res.avgReward ?? mlBridgeState.lastProbeStatus.avgReward,
);
const liveAgency = listAgencies().find((a) => a.name === agency.name);
if (liveAgency) {
liveAgency.mlStats = {
episodes: Number(
(res as any).agencyEpisodes ??
liveAgency.mlStats?.episodes ??
nextEp,
),
avgReward: Number(
(res as any).agencyAvgReward ??
liveAgency.mlStats?.avgReward ??
nextAvg,
),
backend: res.backend ?? mlBridgeState.lastProbeStatus.backend,
lastUpdated: Date.now(),
};
putAgency(liveAgency.name, liveAgency);
}
}
});
}

59
src/server/ml/types.ts Normal file
View file

@ -0,0 +1,59 @@
// Defines ML-managed AI agency rosters, policy decision structures, and Python bridge status metadata.
export interface MlAgencyDef {
name: string;
sponsorId: string;
difficulty: "enthusiast" | "engineer" | "director";
skill: number;
biasTarget: string[];
preferredColor: string;
}
export const ML_AI_DEFS: MlAgencyDef[] = [
{
name: "DeepOrbit RL",
sponsorId: "nasa",
difficulty: "engineer",
skill: 0.85,
biasTarget: ["leo", "sso", "geo", "lunar"],
preferredColor: "#38bdf8",
},
{
name: "AlphaThrust Neural",
sponsorId: "jaxa",
difficulty: "director",
skill: 0.92,
biasTarget: ["lunar", "mars", "asteroid", "l1", "jupiter"],
preferredColor: "#c084fc",
},
{
name: "Perceptron Aerospace",
sponsorId: "esa",
difficulty: "enthusiast",
skill: 0.76,
biasTarget: ["vleo", "leo", "sso", "geo"],
preferredColor: "#34d399",
},
];
export interface MlDecision {
selectedOfferId: string | null;
selectedTemplateId: string | null;
policyConfidence: number;
suggestedPitchKickDeg: number;
suggestedMaxQThrottle: number;
suggestedPreferRadHard: boolean;
backend: string;
}
export interface MlBridgeStatus {
enabled: boolean;
pythonAvailable: boolean;
pythonBin: string;
pythonVersion: string | null;
backend: string;
availablePackages: string[];
episodes: number;
avgReward: number;
lastError: string | null;
lastCheckedAt: number;
}

13
src/server/ml_ai.ts Normal file
View file

@ -0,0 +1,13 @@
// Export ML AI bridge controls, roster definitions, policy inference, and online training.
export {
ML_AI_DEFS,
type MlAgencyDef,
type MlDecision,
type MlBridgeStatus,
} from "./ml/types.js";
export {
isMlAiEnabled,
getMlBridgeStatus,
setMlAiEnabled,
} from "./ml/bridge.js";
export { predictMlDecisionSync, recordMlEpisodeOutcome } from "./ml/policy.js";

16
src/server/routes.ts Normal file
View file

@ -0,0 +1,16 @@
// Mounts all modular REST API route groups onto the shared Express apiRouter.
import { Router } from "express";
import { registerAgencyRoutes } from "./routes/agencyRoutes.js";
import { registerAuthRoutes } from "./routes/authRoutes.js";
import { registerContractRoutes } from "./routes/contractRoutes.js";
import { registerDesignRoutes } from "./routes/designRoutes.js";
import { registerMissionRoutes } from "./routes/missionRoutes.js";
import { registerPublicRoutes } from "./routes/publicRoutes.js";
export const apiRouter = Router();
registerPublicRoutes(apiRouter);
registerAuthRoutes(apiRouter);
registerAgencyRoutes(apiRouter);
registerDesignRoutes(apiRouter);
registerMissionRoutes(apiRouter);
registerContractRoutes(apiRouter);

View file

@ -0,0 +1,393 @@
// Self explanatory.
import type { Response, Router } from "express";
import { type AuthedRequest, requireAuth } from "../auth.js";
import { MATERIALS, PARTS, SPONSORS } from "../catalogs.js";
import { acceptContract } from "../contracts.js";
import { partUnitPrice } from "../economy.js";
import { emit } from "../events.js";
import { getSimTime, getWeather } from "../hazards.js";
import { putAgency, saveDb } from "../store.js";
import {
buildRocket,
computeDesignHash,
computeDesignReliability,
createStarterDesign,
getDifficultyProfile,
normalizeDesign,
normalizeDifficulty,
TECH_TREE,
} from "../../shared/physics.js";
import type { ContractOffer, RocketDesign } from "../../shared/types.js";
import { resolveContract } from "./helpers.js";
export function registerAgencyRoutes(router: Router): void {
router.post(
"/agency/onboard",
requireAuth,
(req: AuthedRequest, res: Response) => {
const { sponsorId, missionId } = (req.body ?? {}) as {
sponsorId?: string;
missionId?: string;
};
const sponsor = SPONSORS.find((s) => s.id === sponsorId);
if (!sponsor) {
res.status(400).json({ error: "Unknown sponsor." });
return;
}
if (!missionId) {
res.status(400).json({ error: "missionId required." });
return;
}
const agency = req.agency!;
let contract: ContractOffer;
try {
contract = acceptContract(agency, missionId);
} catch (err) {
res.status(409).json({ error: String((err as Error).message ?? err) });
return;
}
const canonDiff = normalizeDifficulty(agency.difficulty);
const profile = getDifficultyProfile(canonDiff);
agency.sponsorId = sponsorId ?? null;
agency.bankrupt = false;
agency.bankruptAt = null;
agency.terminatedReason = null;
if (!agency.unlockedTechs?.length) {
agency.unlockedTechs = profile.allTechUnlocked
? TECH_TREE.map((t) => t.id)
: canonDiff === "enthusiast"
? ["starter", "cryo-hydrolox"]
: ["starter"];
}
agency.launchInsured =
canonDiff === "explorer" || canonDiff === "sandbox";
agency.treasury = Math.round(
profile.startingFunds * sponsor.budgetMult + contract.budget * 0.35,
);
if (
contract.crewed &&
(!agency.crewConfig || agency.crewConfig.crewSize < 1)
) {
agency.crewConfig = { crewSize: 2, lifeSupport: 2 };
}
if (!agency.rocketDesign) {
agency.rocketDesign = createStarterDesign(contract, agency.difficulty);
}
putAgency(agency.name, agency);
saveDb(true);
emit("contract.claimed", {
agency: agency.name,
missionId: contract.id,
sponsorId,
});
res.json({ agency, contract });
},
);
router.post(
"/agency/crew",
requireAuth,
(req: AuthedRequest, res: Response) => {
const crew = req.body?.crew as
{ crewSize?: number; lifeSupport?: number } | undefined;
if (!crew || typeof crew.crewSize !== "number") {
res.status(400).json({ error: "crew.crewSize required." });
return;
}
const agency = req.agency!;
agency.crewConfig = {
crewSize: Math.max(0, Math.min(12, Math.floor(crew.crewSize))),
lifeSupport: Math.max(
0,
Math.min(3, Math.floor(crew.lifeSupport ?? 1)),
),
};
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, crew: agency.crewConfig });
},
);
router.post(
"/agency/bailout",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(400).json({
error:
"Agency license was revoked due to catastrophic Loss of Crew. Reset Agency to start a new campaign.",
});
return;
}
const profile = getDifficultyProfile(agency.difficulty);
if ((agency.bailoutsTaken ?? 0) >= profile.maxBailouts) {
res.status(400).json({
error: `Bailout cap reached for ${profile.label} difficulty (${profile.maxBailouts} max). Reset Agency to restart.`,
});
return;
}
if (agency.treasury >= 25_000_000 && !agency.bankrupt) {
res
.status(400)
.json({
error: "Agency is solvent and ineligible for emergency bailout.",
});
return;
}
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
const grant = Math.round(
profile.bailoutGrant * (sponsor?.budgetMult ?? 1.0),
);
agency.treasury += grant;
agency.bankrupt = false;
agency.bankruptAt = null;
agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1;
agency.reputation = Math.max(
0,
Math.round((agency.reputation - 2.5) * 10) / 10,
);
putAgency(agency.name, agency);
saveDb(true);
emit("agency.bailout", { agency: agency.name, grant });
res.json({ ok: true, grant, agency });
},
);
router.post(
"/agency/reset",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
const canonDiff = normalizeDifficulty(agency.difficulty);
const profile = getDifficultyProfile(canonDiff);
agency.sponsorId = null;
agency.missionId = null;
agency.activeContract = null;
agency.treasury = profile.startingFunds;
agency.reputation = 1;
agency.missionsCompleted = 0;
agency.missionsFailed = 0;
agency.earnedTotal = 0;
agency.rocketDesign = null;
agency.crewConfig = { crewSize: 0, lifeSupport: 1 };
agency.activeMissions = [];
agency.contractHistory = [];
agency.bankrupt = false;
agency.bankruptAt = null;
agency.bailoutsTaken = 0;
agency.unlockedTechs = profile.allTechUnlocked
? TECH_TREE.map((t) => t.id)
: canonDiff === "enthusiast"
? ["starter", "cryo-hydrolox"]
: ["starter"];
agency.partHeritage = {};
agency.staticFiredDesignHash = null;
agency.launchInsured =
canonDiff === "explorer" || canonDiff === "sandbox";
agency.groundedUntilSimTime = null;
agency.padDamagedUntilSimTime = null;
agency.casualtiesTotal = 0;
agency.lastSettlement = null;
agency.terminatedReason = null;
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, agency });
},
);
router.post(
"/agency/unlock-tech",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
const techId = String(req.body?.techId ?? "");
const node = TECH_TREE.find((t) => t.id === techId);
if (!node) {
res.status(400).json({ error: `Unknown technology node: ${techId}` });
return;
}
const unlocked = new Set(agency.unlockedTechs ?? ["starter"]);
if (unlocked.has(node.id)) {
res.json({
ok: true,
tech: node,
unlockedTechs: agency.unlockedTechs,
treasury: agency.treasury,
agency,
});
return;
}
if ((agency.reputation ?? 0) < node.minReputation) {
res.status(400).json({
error: `${node.name} requires ${node.minReputation} RP reputation (current: ${agency.reputation.toFixed(1)} RP).`,
});
return;
}
if (agency.treasury < node.cost) {
res.status(400).json({
error: `Insufficient funds to unlock ${node.name}: need $${(node.cost / 1e6).toFixed(1)}M.`,
});
return;
}
agency.treasury -= node.cost;
unlocked.add(node.id);
agency.unlockedTechs = Array.from(unlocked);
putAgency(agency.name, agency);
saveDb(true);
res.json({
ok: true,
tech: node,
unlockedTechs: agency.unlockedTechs,
treasury: agency.treasury,
agency,
});
},
);
router.post(
"/agency/static-fire",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
const rawDesign =
(req.body?.design as RocketDesign | undefined) ?? agency.rocketDesign;
if (!rawDesign?.stages?.length) {
res
.status(400)
.json({
error:
"Build and save a rocket design before running a static fire test.",
});
return;
}
try {
const design = normalizeDesign(rawDesign, PARTS, MATERIALS);
const mission = resolveContract(agency);
const assembly = buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission,
difficulty: agency.difficulty,
weather: getWeather(),
});
const hash = computeDesignHash(design);
if (agency.staticFiredDesignHash === hash) {
const reliability = computeDesignReliability(
design,
assembly,
agency,
);
res.json({
ok: true,
alreadyTested: true,
fee: 0,
reliability,
treasury: agency.treasury,
agency,
});
return;
}
const sfProfile = getDifficultyProfile(agency.difficulty);
const fee =
sfProfile.id === "sandbox"
? 0
: Math.max(450_000, Math.round(assembly.totalCost * 0.04));
if (agency.treasury < fee) {
res.status(400).json({
error: `Insufficient funds for static fire test ($${(fee / 1e6).toFixed(2)}M required).`,
});
return;
}
agency.treasury -= fee;
agency.rocketDesign = design;
agency.staticFiredDesignHash = hash;
putAgency(agency.name, agency);
saveDb(true);
const reliability = computeDesignReliability(design, assembly, agency);
res.json({
ok: true,
fee,
reliability,
treasury: agency.treasury,
agency,
});
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
},
);
router.post(
"/agency/insurance",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
const canonDiff = normalizeDifficulty(agency.difficulty);
const enabled = Boolean(req.body?.enabled);
agency.launchInsured =
canonDiff === "explorer" || canonDiff === "sandbox" ? true : enabled;
let estimatedPremium = 0;
if (agency.rocketDesign) {
try {
const assembly = buildRocket(agency.rocketDesign, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission: resolveContract(agency),
difficulty: agency.difficulty,
weather: getWeather(),
});
estimatedPremium =
canonDiff === "explorer" || canonDiff === "sandbox"
? 0
: Math.round(assembly.totalCost * 0.08);
} catch {
estimatedPremium = 0;
}
}
putAgency(agency.name, agency);
saveDb(true);
res.json({
ok: true,
launchInsured: agency.launchInsured,
estimatedPremium,
agency,
});
},
);
router.post(
"/agency/clear-standdown",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
const nowSim = getSimTime();
const padActive = (agency.padDamagedUntilSimTime ?? 0) > nowSim;
const groundActive = (agency.groundedUntilSimTime ?? 0) > nowSim;
if (!padActive && !groundActive) {
agency.padDamagedUntilSimTime = null;
agency.groundedUntilSimTime = null;
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, fee: 0, agency });
return;
}
const fee = (padActive ? 4_000_000 : 0) + (groundActive ? 6_000_000 : 0);
if (agency.treasury < fee) {
res.status(400).json({
error: `Insufficient funds to expedite clearance ($${(fee / 1e6).toFixed(1)}M needed).`,
});
return;
}
agency.treasury -= fee;
agency.padDamagedUntilSimTime = null;
agency.groundedUntilSimTime = null;
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, fee, treasury: agency.treasury, agency });
},
);
}

View file

@ -0,0 +1,89 @@
// Self explanatory.
import type { Response, Router } from "express";
import {
type AuthedRequest,
loginAgency,
logoutToken,
registerAgency,
requireAuth,
} from "../auth.js";
import { clearActiveContract } from "../contracts.js";
import { putAgency, saveDb } from "../store.js";
import { worldSnapshot } from "../world.js";
import {
createDefaultTeamStations,
getDifficultyProfile,
normalizeDifficulty,
TECH_TREE,
} from "../../shared/physics.js";
import type { DifficultyLevel } from "../../shared/types.js";
export function registerAuthRoutes(router: Router): void {
router.post("/auth/register", (req, res) => {
try {
const { name, password, difficulty } = (req.body ?? {}) as {
name?: string;
password?: string;
difficulty?: DifficultyLevel;
};
const result = registerAgency(name ?? "", password ?? "", difficulty);
res.json(result);
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
});
router.post("/auth/login", (req, res) => {
try {
const { name, password } = (req.body ?? {}) as {
name?: string;
password?: string;
};
res.json(loginAgency(name ?? "", password ?? ""));
} catch (err) {
res.status(401).json({ error: String((err as Error).message ?? err) });
}
});
router.post(
"/auth/logout",
requireAuth,
(req: AuthedRequest, res: Response) => {
const token = (req.headers.authorization ?? "").slice(7);
logoutToken(token);
res.json({ ok: true });
},
);
router.get("/me", requireAuth, (req: AuthedRequest, res: Response) => {
const a = req.agency!;
let dirty = false;
if (
a.missionId &&
!a.activeContract &&
!(a.activeMissions ?? []).some((m) => !m.settled)
) {
clearActiveContract(a);
dirty = true;
}
if (!a.unlockedTechs?.length) {
const canonDiff = normalizeDifficulty(a.difficulty);
const profile = getDifficultyProfile(canonDiff);
a.unlockedTechs = profile.allTechUnlocked
? TECH_TREE.map((t) => t.id)
: canonDiff === "enthusiast"
? ["starter", "cryo-hydrolox"]
: ["starter"];
dirty = true;
}
if (!a.teamStations) {
a.teamStations = createDefaultTeamStations();
dirty = true;
}
if (dirty) {
putAgency(a.name, a);
saveDb();
}
res.json({ account: { name: req.accountName }, agency: a });
});
router.get("/world", requireAuth, (_req, res) => {
res.json(worldSnapshot());
});
}

View file

@ -0,0 +1,115 @@
// Self explanatory.
import type { Response, Router } from "express";
import { type AuthedRequest, requireAuth } from "../auth.js";
import {
acceptContract,
clearActiveContract,
createCustomContract,
type CustomContractInput,
listContracts,
} from "../contracts.js";
import { emit } from "../events.js";
import { putAgency, saveDb } from "../store.js";
import type { ContractOffer } from "../../shared/types.js";
export function registerContractRoutes(router: Router): void {
router.get("/contracts", requireAuth, (req: AuthedRequest, res: Response) => {
const offers = listContracts(req.agency!);
res.json(offers);
});
router.post(
"/contracts/custom",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
if (agency.bankrupt) {
res
.status(409)
.json({ error: "Cannot create custom contracts while bankrupt." });
return;
}
if (
agency.activeContract ||
(agency.activeMissions ?? []).some((m) => !m.settled)
) {
res
.status(409)
.json({
error: "Already has an active contract. Complete it first.",
});
return;
}
if (agency.missionId) clearActiveContract(agency);
const input = (req.body ?? {}) as CustomContractInput;
const contract = createCustomContract(agency, input);
const advance = Math.round(contract.budget * 0.35);
agency.treasury += advance;
if (
contract.crewed &&
(!agency.crewConfig || agency.crewConfig.crewSize < 1)
) {
agency.crewConfig = { crewSize: contract.crewCap ?? 3, lifeSupport: 2 };
}
putAgency(agency.name, agency);
saveDb(true);
emit("contract.claimed", {
agency: agency.name,
missionId: contract.id,
isCustom: true,
});
res.json({ ok: true, agency, contract, advance });
},
);
router.post(
"/contracts/:id/accept",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
if (agency.bankrupt) {
res
.status(409)
.json({ error: "Cannot accept contracts while bankrupt." });
return;
}
if (
agency.activeContract ||
(agency.activeMissions ?? []).some((m) => !m.settled)
) {
res
.status(409)
.json({
error: "Already has an active contract. Complete it first.",
});
return;
}
if (agency.missionId) clearActiveContract(agency);
let contract: ContractOffer;
try {
contract = acceptContract(agency, String(req.params.id ?? ""));
} catch (err) {
res.status(409).json({ error: String((err as Error).message ?? err) });
return;
}
const advance = Math.round(contract.budget * 0.35);
agency.treasury += advance;
if (
contract.crewed &&
(!agency.crewConfig || agency.crewConfig.crewSize < 1)
) {
agency.crewConfig = { crewSize: 2, lifeSupport: 2 };
}
putAgency(agency.name, agency);
saveDb(true);
emit("contract.claimed", { agency: agency.name, missionId: contract.id });
res.json({ ok: true, agency, contract, advance });
},
);
}

View file

@ -0,0 +1,466 @@
// Self explanatory.
import type { Response, Router } from "express";
import { type AuthedRequest, requireAuth } from "../auth.js";
import { MATERIALS, PARTS } from "../catalogs.js";
import { partUnitPrice } from "../economy.js";
import { emit } from "../events.js";
import { getWeather } from "../hazards.js";
import {
deleteSharedBlueprint,
listSharedBlueprints,
putAgency,
putSharedBlueprint,
saveDb,
} from "../store.js";
import { simulateAscent } from "../../shared/ascent_sim.js";
import {
autoTuneFlightParams,
buildRocket,
computeDesignHash,
computeDesignReliability,
computeEffectivePayloadMass,
createDefaultTeamStations,
decodeRocketShareCode,
encodeRocketShareCode,
findLockedDesignItemsDetailed,
getDifficultyProfile,
normalizeDesign,
TEAM_STATION_DEFS,
} from "../../shared/physics.js";
import type {
MaturityLevel,
RocketDesign,
SavedRocketBlueprint,
TeamStationId,
} from "../../shared/types.js";
import { resolveContract, validateAgencyDesign } from "./helpers.js";
export function registerDesignRoutes(router: Router): void {
router.post(
"/agency/rocket",
requireAuth,
(req: AuthedRequest, res: Response) => {
const raw = req.body?.design as RocketDesign | undefined;
if (!raw?.stages?.length) {
res.status(400).json({ error: "design.stages required" });
return;
}
try {
const agency = req.agency!;
const clean = normalizeDesign(raw, PARTS, MATERIALS);
const mission = resolveContract(agency);
buildRocket(clean, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission,
difficulty: agency.difficulty,
weather: getWeather(),
unlockedTechs: agency.unlockedTechs ?? [],
});
agency.rocketDesign = clean;
if (
agency.staticFiredDesignHash &&
agency.staticFiredDesignHash !== computeDesignHash(clean)
) {
agency.staticFiredDesignHash = null;
}
putAgency(agency.name, agency);
saveDb(true);
emit("agency.updated", {
agency: agency.name,
sender: req.accountName,
rocketDesign: clean,
teamStations: agency.teamStations,
});
res.json({ ok: true, design: clean });
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
},
);
router.get(
"/agency/designs",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
const myDesigns = [...(agency.savedDesigns ?? [])].sort(
(a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0),
);
res.json({
ok: true,
myDesigns,
communityDesigns: listSharedBlueprints(),
});
},
);
router.post(
"/agency/designs/import",
requireAuth,
(req: AuthedRequest, res: Response) => {
try {
const agency = req.agency!;
const rawCode = String(req.body?.codeOrJson ?? "");
const decoded = decodeRocketShareCode(rawCode, PARTS, MATERIALS);
const unlockedTechs = agency.unlockedTechs ?? [];
const lockedItems = findLockedDesignItemsDetailed(
decoded,
PARTS,
MATERIALS,
unlockedTechs,
agency.difficulty,
);
const asm = buildRocket(decoded, PARTS, MATERIALS, {
priceOf: partUnitPrice,
difficulty: agency.difficulty,
weather: getWeather(),
unlockedTechs,
});
const shareCode = encodeRocketShareCode(decoded);
let blueprint: SavedRocketBlueprint | undefined;
if (req.body?.saveToHangar) {
const now = Date.now();
const rawName =
typeof req.body?.name === "string" ? req.body.name.trim() : "";
const safeName =
rawName.slice(0, 64) || decoded.name || "Imported Vehicle";
blueprint = {
id: `bp_${now.toString(36)}_${Math.random().toString(36).slice(2, 7)}`,
name: safeName,
authorAgency: agency.name,
createdAt: now,
updatedAt: now,
isPublic: false,
notes: "Imported from share code / JSON",
totalDv: Math.round(asm.totalDv),
totalCost: Math.round(asm.totalCost),
stageCount: decoded.stages.length,
designTier: decoded.designTier ?? "basic",
design: decoded,
};
agency.savedDesigns = [
blueprint,
...(agency.savedDesigns ?? []),
].slice(0, 40);
putAgency(agency.name, agency);
saveDb(true);
}
res.json({
ok: true,
design: decoded,
shareCode,
lockedItems,
summary: {
totalDv: Math.round(asm.totalDv),
totalCost: Math.round(asm.totalCost),
stageCount: decoded.stages.length,
designTier: decoded.designTier ?? "basic",
},
blueprint,
myDesigns: agency.savedDesigns ?? [],
});
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
},
);
router.post(
"/agency/designs",
requireAuth,
(req: AuthedRequest, res: Response) => {
try {
const agency = req.agency!;
const rawDesign = (req.body?.design ?? agency.rocketDesign) as
RocketDesign | undefined;
if (
!rawDesign ||
(!rawDesign.stages?.length && !rawDesign.proParts?.length)
) {
res.status(400).json({ error: "Valid design required." });
return;
}
const clean = normalizeDesign(rawDesign, PARTS, MATERIALS);
const unlockedTechs = agency.unlockedTechs ?? [];
const asm = buildRocket(clean, PARTS, MATERIALS, {
priceOf: partUnitPrice,
difficulty: agency.difficulty,
weather: getWeather(),
unlockedTechs,
});
const now = Date.now();
const list = [...(agency.savedDesigns ?? [])];
const reqId =
typeof req.body?.id === "string"
? req.body.id.trim().slice(0, 48)
: "";
const existingIdx = reqId ? list.findIndex((b) => b.id === reqId) : -1;
const id =
reqId ||
`bp_${now.toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
const rawName =
typeof req.body?.name === "string" ? req.body.name.trim() : "";
const safeName = rawName.slice(0, 64) || clean.name || "Unnamed Rocket";
const isPublic = Boolean(req.body?.isPublic);
const bp: SavedRocketBlueprint = {
id,
name: safeName,
authorAgency: agency.name,
createdAt: existingIdx >= 0 ? list[existingIdx].createdAt : now,
updatedAt: now,
isPublic,
notes:
typeof req.body?.notes === "string" && req.body.notes.trim()
? req.body.notes.trim().slice(0, 280)
: undefined,
targetHint:
typeof req.body?.targetHint === "string" &&
req.body.targetHint.trim()
? req.body.targetHint.trim().slice(0, 64)
: undefined,
totalDv: Math.round(asm.totalDv),
totalCost: Math.round(asm.totalCost),
stageCount: clean.stages.length,
designTier: clean.designTier ?? "basic",
design: clean,
};
if (existingIdx >= 0) {
list[existingIdx] = bp;
} else {
list.unshift(bp);
}
agency.savedDesigns = list
.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
.slice(0, 40);
if (isPublic) {
putSharedBlueprint(bp);
} else {
deleteSharedBlueprint(bp.id, agency.name);
}
putAgency(agency.name, agency);
saveDb(true);
res.json({
ok: true,
blueprint: bp,
shareCode: encodeRocketShareCode(clean),
myDesigns: agency.savedDesigns,
communityDesigns: listSharedBlueprints(),
});
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
},
);
router.delete(
"/agency/designs/:id",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
const id = String(req.params.id ?? "").trim();
const prev = agency.savedDesigns ?? [];
const next = prev.filter((b) => b.id !== id);
const removedShared = deleteSharedBlueprint(id, agency.name);
if (next.length === prev.length && !removedShared) {
res.status(404).json({ error: "Blueprint not found." });
return;
}
agency.savedDesigns = next;
putAgency(agency.name, agency);
saveDb(true);
res.json({
ok: true,
myDesigns: agency.savedDesigns,
communityDesigns: listSharedBlueprints(),
});
},
);
router.post(
"/agency/station",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
const stationId = String(req.body?.stationId ?? "") as TeamStationId;
const def = TEAM_STATION_DEFS.find((s) => s.id === stationId);
if (!def) {
res.status(400).json({ error: "Unknown mission control station." });
return;
}
agency.teamStations = agency.teamStations ?? createDefaultTeamStations();
const cur = agency.teamStations[stationId];
const operatorName =
typeof req.body?.operatorName === "string" &&
req.body.operatorName.trim()
? req.body.operatorName.trim().slice(0, 32)
: cur?.operatorName === "Unassigned"
? req.accountName || agency.name
: cur?.operatorName || req.accountName || agency.name;
const ready =
typeof req.body?.ready === "boolean"
? req.body.ready
: !(cur?.ready ?? false);
agency.teamStations[stationId] = {
stationId,
title: def.title,
operatorName,
ready,
updatedAt: Date.now(),
};
putAgency(agency.name, agency);
saveDb(true);
emit("agency.updated", {
agency: agency.name,
sender: req.accountName,
teamStations: agency.teamStations,
});
res.json({ ok: true, teamStations: agency.teamStations, agency });
},
);
router.post(
"/agency/flight-params",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (!agency.rocketDesign) {
res
.status(400)
.json({ error: "Build and save a rocket design first." });
return;
}
const fp = req.body?.flightParams;
if (!fp) {
res.status(400).json({ error: "flightParams required." });
return;
}
const updated = normalizeDesign(
{ ...agency.rocketDesign, flightParams: fp },
PARTS,
MATERIALS,
);
agency.rocketDesign = updated;
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, flightParams: updated.flightParams });
},
);
router.post(
"/agency/maturity",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (!agency.rocketDesign) {
res.status(400).json({ error: "No rocket design saved." });
return;
}
const targetMaturity = req.body?.maturity as MaturityLevel | undefined;
if (!targetMaturity) {
res.status(400).json({ error: "maturity required." });
return;
}
const mission = resolveContract(agency);
const { validation: val } = validateAgencyDesign(
agency,
agency.rocketDesign,
mission,
);
const profile = getDifficultyProfile(agency.difficulty);
const order: Record<MaturityLevel, number> = {
concept: 0,
pdr: 1,
cdr: 2,
"flight-ready": 3,
};
if (
profile.id !== "sandbox" &&
order[targetMaturity] > order[val.compliance.maxAllowedMaturity]
) {
res.status(400).json({
error: `Cannot advance to ${targetMaturity.toUpperCase()} — resolve or waive compliance blockers (max allowed: ${val.compliance.maxAllowedMaturity.toUpperCase()}).`,
compliance: val.compliance,
});
return;
}
agency.rocketDesign.maturity = targetMaturity;
putAgency(agency.name, agency);
saveDb(true);
res.json({ ok: true, maturity: targetMaturity, validation: val });
},
);
router.post(
"/agency/autotune",
requireAuth,
(req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (!agency.rocketDesign) {
res
.status(400)
.json({ error: "Build and save a rocket design first." });
return;
}
try {
const design = normalizeDesign(agency.rocketDesign, PARTS, MATERIALS);
const mission = resolveContract(agency);
const assembly = buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission,
difficulty: agency.difficulty,
weather: getWeather(),
});
const effectiveMission = mission
? {
...mission,
payloadMass: computeEffectivePayloadMass(
mission.payloadMass,
Boolean(mission.crewed),
agency.crewConfig,
),
}
: null;
const tuned = autoTuneFlightParams(design, assembly, effectiveMission);
design.flightParams = tuned;
agency.rocketDesign = design;
putAgency(agency.name, agency);
saveDb(true);
const reliability = computeDesignReliability(design, assembly, agency);
const preview = simulateAscent(design, PARTS, MATERIALS, {
weather: getWeather(),
mission: effectiveMission,
rollAnomalies: false,
sampleEvery: 2.5,
priceOf: partUnitPrice,
difficulty: agency.difficulty,
partDefectRiskPct: reliability.anomalyRiskPct,
});
res.json({ ok: true, flightParams: tuned, preview, agency });
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
},
);
router.post("/build", (req, res) => {
try {
const design = req.body?.design as RocketDesign | undefined;
if (!design?.stages) {
res.status(400).json({ error: "design.stages required" });
return;
}
res.json(buildRocket(design, PARTS, MATERIALS, partUnitPrice));
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
});
router.post("/validate", requireAuth, (req: AuthedRequest, res: Response) => {
try {
const { design, missionId } = (req.body ?? {}) as {
design: RocketDesign;
missionId?: string;
};
const agency = req.agency!;
const mission = resolveContract(agency, missionId);
const { validation, locked, reliability, coach } = validateAgencyDesign(
agency,
design,
mission,
);
res.json({ ...validation, locked, reliability, coach });
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
});
}

View file

@ -0,0 +1,99 @@
// Self explanatory.
import { type AuthedRequest } from "../auth.js";
import { MATERIALS, MISSIONS, PARTS, SPONSORS } from "../catalogs.js";
import { deriveContract } from "../contracts.js";
import { partUnitPrice } from "../economy.js";
import { getActiveHazards, getSimTime, getWeather } from "../hazards.js";
import {
buildRocket,
computeDesignReliability,
computeEffectivePayloadMass,
findLockedDesignItemsDetailed,
generateCoachDiagnostics,
validateDesign,
} from "../../shared/physics.js";
import type {
AgencyState,
ContractOffer,
RocketDesign,
} from "../../shared/types.js";
export function validateAgencyDesign(
agency: AgencyState,
design: RocketDesign,
mission: ContractOffer | null,
) {
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
const effectiveMission = mission
? {
...mission,
payloadMass: computeEffectivePayloadMass(
mission.payloadMass,
Boolean(mission.crewed),
agency.crewConfig,
),
}
: null;
const activeHazards = getActiveHazards();
const unlockedTechs = agency.unlockedTechs ?? [];
const validation = validateDesign(design, PARTS, MATERIALS, {
mission: effectiveMission,
difficulty: agency.difficulty,
simTime: getSimTime(),
weather: getWeather(),
activeHazards,
unlockedTechs,
waiverCostMult: sponsor?.waiverCostMult ?? 1.0,
crewedSeats: agency.crewConfig?.crewSize ?? 0,
eclssLevel: agency.crewConfig?.lifeSupport ?? 0,
priceOf: partUnitPrice,
});
const locked =
validation.lockedItems ??
findLockedDesignItemsDetailed(
design,
PARTS,
MATERIALS,
unlockedTechs,
agency.difficulty,
);
const assembly =
validation.assembly ??
buildRocket(design, PARTS, MATERIALS, {
priceOf: partUnitPrice,
mission: effectiveMission,
difficulty: agency.difficulty,
weather: getWeather(),
unlockedTechs,
});
const reliability = computeDesignReliability(design, assembly, agency);
const coach = generateCoachDiagnostics(
design,
assembly,
validation,
effectiveMission,
agency.difficulty,
);
return { validation, locked, reliability, coach, effectiveMission, assembly };
}
export function resolveContract(
agency: NonNullable<AuthedRequest["agency"]>,
missionId?: string | null,
): ContractOffer | null {
const wanted = missionId ?? agency.missionId;
if (!wanted) return null;
if (
agency.activeContract &&
(agency.activeContract.offerId === wanted ||
agency.activeContract.id === wanted ||
agency.activeContract.templateId === wanted)
) {
return { ...agency.activeContract };
}
const tplId = wanted.includes(":") ? wanted.split(":")[1] : wanted;
const tpl = MISSIONS.find((m) => m.id === tplId);
if (!tpl) return null;
const contractorId = wanted.includes(":") ? wanted.split(":")[0] : undefined;
return deriveContract(agency, tpl, contractorId);
}

View file

@ -0,0 +1,270 @@
// Self explanatory.
import type { Response, Router } from "express";
import { type AuthedRequest, requireAuth } from "../auth.js";
import { MATERIALS, PARTS } from "../catalogs.js";
import { clearActiveContract } from "../contracts.js";
import { partUnitPrice, recordDesignDemand } from "../economy.js";
import { emit } from "../events.js";
import { runTrajectory } from "../gmat_runner.js";
import { getActiveHazards, getSimTime, getWeather } from "../hazards.js";
import { settleMissionOutcome } from "../settlement.js";
import { findActiveMission, putAgency, saveDb } from "../store.js";
import { simulateAscent } from "../../shared/ascent_sim.js";
import {
generateCoachDiagnostics,
getDifficultyProfile,
} from "../../shared/physics.js";
import type { ActiveMission, RocketDesign } from "../../shared/types.js";
import { resolveContract, validateAgencyDesign } from "./helpers.js";
export function registerMissionRoutes(router: Router): void {
router.post("/simulate", requireAuth, (req: AuthedRequest, res: Response) => {
try {
const design = req.body?.design as RocketDesign;
const dryRun = !!req.body?.previewOnly;
const agency = req.agency!;
const mission = resolveContract(agency);
const { validation, reliability, effectiveMission, assembly } =
validateAgencyDesign(agency, design, mission);
let testFee = 0;
if (!dryRun) {
testFee = Math.max(120_000, Math.round(assembly.totalCost * 0.015));
if (agency.treasury < testFee) {
res
.status(400)
.json({
error: `Insufficient funds for test flight ($${(testFee / 1e6).toFixed(2)}M needed).`,
});
return;
}
agency.treasury -= testFee;
putAgency(agency.name, agency);
saveDb();
}
const result = simulateAscent(design, PARTS, MATERIALS, {
weather: getWeather(),
activeHazards: getActiveHazards(),
unlockedTechs: agency.unlockedTechs ?? [],
mission: effectiveMission,
rollAnomalies: false,
sampleEvery: dryRun ? 2.5 : 0.8,
priceOf: partUnitPrice,
difficulty: agency.difficulty,
partDefectRiskPct: reliability.anomalyRiskPct,
});
result.testFee = testFee;
const coach = generateCoachDiagnostics(
design,
assembly,
validation,
effectiveMission,
agency.difficulty,
result,
);
res.json({ ...result, reliability, coach });
} catch (err) {
res.status(400).json({ error: String((err as Error).message ?? err) });
}
});
router.post(
"/trajectory",
requireAuth,
async (req: AuthedRequest, res: Response) => {
try {
const target = String(req.body?.target ?? "leo");
const altKm = req.body?.altKm ? Number(req.body.altKm) : undefined;
const incDeg = req.body?.incDeg ? Number(req.body.incDeg) : undefined;
const traj = await runTrajectory(target, { altKm, incDeg });
res.json(traj);
} catch (err) {
res.status(500).json({ error: String((err as Error).message ?? err) });
}
},
);
router.post(
"/mission/launch",
requireAuth,
async (req: AuthedRequest, res: Response) => {
const agency = req.agency!;
if (agency.terminatedReason) {
res.status(409).json({ error: agency.terminatedReason });
return;
}
if (agency.bankrupt) {
res
.status(409)
.json({
error:
"Agency is bankrupt. Accept a Sponsor Restructuring Grant or Reset Agency first.",
});
return;
}
const nowSim = getSimTime();
if ((agency.groundedUntilSimTime ?? 0) > nowSim) {
const rem = Math.ceil(agency.groundedUntilSimTime! - nowSim);
res.status(409).json({
error: `Safety Board grounding order active for ${rem} sim sec. Wait or Expedite Clearance on Dashboard.`,
});
return;
}
if ((agency.padDamagedUntilSimTime ?? 0) > nowSim) {
const rem = Math.ceil(agency.padDamagedUntilSimTime! - nowSim);
res.status(409).json({
error: `Launch pad under repair for ${rem} sim sec. Wait or Expedite Repairs on Dashboard.`,
});
return;
}
if ((agency.activeMissions ?? []).some((m) => !m.settled)) {
res
.status(409)
.json({
error: "A mission is already in flight. Wait for settlement.",
});
return;
}
const contract = resolveContract(agency);
if (!contract) {
res.status(400).json({ error: "No active mission contract accepted." });
return;
}
const design = agency.rocketDesign;
if (!design) {
res.status(400).json({ error: "No rocket design saved." });
return;
}
const { validation, locked, reliability, effectiveMission } =
validateAgencyDesign(agency, design, contract);
if (!validation.valid) {
res.status(400).json({
error: locked.length
? "Design uses locked R&D technologies. Unlock them in R&D Tech Lab first."
: "Design has unresolved compliance failures.",
validation,
locked,
});
return;
}
const profile = getDifficultyProfile(agency.difficulty);
if (profile.id === "sandbox" && design.maturity !== "flight-ready") {
design.maturity = "flight-ready";
}
if (design.maturity !== "flight-ready") {
res
.status(400)
.json({
error: `Design maturity is ${design.maturity.toUpperCase()}; advance to FLIGHT-READY in Rocket Builder.`,
});
return;
}
const insurancePremium =
profile.id !== "explorer" &&
profile.id !== "sandbox" &&
agency.launchInsured
? Math.round(validation.totalMissionCost * 0.08)
: 0;
const cost = validation.totalMissionCost + insurancePremium;
if (agency.treasury < cost) {
res.status(400).json({
error: `Insufficient funds: need $${(cost / 1e6).toFixed(2)}M, have $${(agency.treasury / 1e6).toFixed(2)}M.`,
});
return;
}
const ascent = simulateAscent(design, PARTS, MATERIALS, {
weather: getWeather(),
activeHazards: getActiveHazards(),
unlockedTechs: agency.unlockedTechs ?? [],
mission: effectiveMission,
rollAnomalies: true,
sampleEvery: 0.6,
priceOf: partUnitPrice,
difficulty: agency.difficulty,
partDefectRiskPct: reliability.anomalyRiskPct,
});
const trajectory = await runTrajectory(contract.target, {
altKm: design.flightParams.targetApoapsisKm,
incDeg: design.flightParams.targetInclinationDeg,
});
agency.treasury -= cost;
agency.staticFiredDesignHash = null;
recordDesignDemand(design);
const active: ActiveMission = {
id: `m-${agency.name.replace(/\W+/g, "").toLowerCase()}-${Date.now()}`,
agencyName: agency.name,
isAI: false,
missionId: contract.id,
name: contract.name,
target: contract.target,
contract,
rocketDesign: design,
launchedAt: nowSim,
completeAt: ascent.success ? nowSim + 180 : nowSim,
cost,
budget: contract.budget,
ascent,
trajectory,
validation,
};
const settlement = settleMissionOutcome(agency, active, nowSim);
clearActiveContract(agency);
agency.activeMissions = ascent.success ? [active] : [];
putAgency(agency.name, agency);
saveDb(true);
emit("mission.launched", {
id: active.id,
agency: agency.name,
missionId: contract.id,
target: contract.target,
});
res.json({
ok: true,
mission: active,
settlement,
remainingTreasury: agency.treasury,
agency,
});
},
);
router.get(
"/missions/active",
requireAuth,
(req: AuthedRequest, res: Response) => {
const now = getSimTime();
const list = (req.agency!.activeMissions ?? []).map((m) => ({
...m,
trajectory: undefined,
remainingSec: Math.max(0, m.completeAt - now),
progress: Math.min(
1,
(now - m.launchedAt) / Math.max(1, m.completeAt - m.launchedAt),
),
}));
res.json(list);
},
);
router.get(
"/missions/spectate/:id",
requireAuth,
(req: AuthedRequest, res: Response) => {
const flight = findActiveMission(String(req.params.id ?? ""));
if (!flight) {
res
.status(404)
.json({ error: "Active flight not found or already settled." });
return;
}
const now = getSimTime();
res.json({
...flight,
simTime: now,
progress: Math.min(
1,
Math.max(
0,
(now - flight.launchedAt) /
Math.max(1, flight.completeAt - flight.launchedAt),
),
),
});
},
);
}

View file

@ -0,0 +1,62 @@
// Registers unauthenticated catalog, leaderboard, server info, and ML bridge status/toggle routes.
import type { Response, Router } from "express";
import { getLeaderboard } from "../ai.js";
import { type AuthedRequest, requireAuth } from "../auth.js";
import {
MATERIALS,
MISSIONS,
MODELS_INDEX,
PARTS,
SPONSORS,
} from "../catalogs.js";
import { config } from "../config.js";
import { getPrices } from "../economy.js";
import { getMlBridgeStatus, setMlAiEnabled } from "../ml_ai.js";
import { DIFFICULTY_PROFILES, TECH_TREE } from "../../shared/physics.js";
export function registerPublicRoutes(router: Router): void {
router.get("/info", (_req, res) => {
res.json({
name: "Space Gaem: You Will Feel the Pain (TypeScript Prototype)",
serverPasswordRequired: !!config.serverPassword,
simSecondsPerRealSecond: config.simSecondsPerRealSecond,
});
});
router.post("/join", (req, res) => {
if (
!config.serverPassword ||
req.body?.password === config.serverPassword
) {
res.json({ ok: true });
return;
}
res.status(403).json({ error: "Wrong server password." });
});
router.get("/parts", (_req, res) => res.json(PARTS));
router.get("/materials", (_req, res) => res.json(MATERIALS));
router.get("/missions", (_req, res) => res.json(MISSIONS));
router.get("/sponsors", (_req, res) => res.json(SPONSORS));
router.get("/models", (_req, res) => res.json(MODELS_INDEX.models));
router.get("/catalogs", (_req, res) =>
res.json({
techTree: TECH_TREE,
difficultyProfiles: DIFFICULTY_PROFILES,
}),
);
router.get("/prices", (_req, res) => res.json(getPrices()));
router.get("/leaderboard", (_req, res) => res.json(getLeaderboard()));
router.get("/ml-status", async (_req, res) => {
res.json(await getMlBridgeStatus(false));
});
router.post(
"/ml-toggle",
requireAuth,
async (req: AuthedRequest, res: Response) => {
const enabled =
typeof req.body?.enabled === "boolean" ? req.body.enabled : undefined;
const current = await getMlBridgeStatus(false);
const next = await setMlAiEnabled(enabled ?? !current.enabled);
res.json(next);
},
);
}

318
src/server/settlement.ts Normal file
View file

@ -0,0 +1,318 @@
// Settles completed player and AI orbital missions, calculates payouts/reputation/part heritage, and handles crew emergencies.
import { MISSIONS, SPONSORS } from "./catalogs.js";
import { clearActiveContract, recordContractCompletion } from "./contracts.js";
import { emit } from "./events.js";
import { recordMlEpisodeOutcome } from "./ml_ai.js";
import { getWorld, listAgencies, putAgency } from "./store.js";
import { getDifficultyProfile } from "../shared/physics.js";
import type {
ActiveMission,
AgencyState,
CrewEmergencyOutcome,
MissionSettlement,
OrbitInsertionGrade,
} from "../shared/types.js";
export function settleMissionOutcome(
agency: AgencyState,
m: ActiveMission,
simTime: number,
): MissionSettlement {
if (m.settled && m.settlement) return m.settlement;
const contract = m.contract ?? MISSIONS.find((x) => x.id === m.missionId);
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
const repMult = sponsor?.reputationMult ?? 1.0;
const profile = getDifficultyProfile(agency.difficulty);
const budget = contract?.budget ?? m.budget ?? m.cost * 2;
const orbitGrade: OrbitInsertionGrade =
m.ascent.orbitGrade ?? (m.ascent.success ? "nominal" : "failed");
const crewOutcome: CrewEmergencyOutcome =
m.ascent.crewOutcome ??
(contract?.crewed
? m.ascent.success
? "nominal"
: "loss_of_crew"
: "none");
const advancePayout = Math.round(budget * 0.35);
let grossPayout = 0;
let scienceBonus = 0;
let researchPointsEarned = 0;
let reusabilityBonus = 0;
let breachPenalty = 0;
let padRepairCost = 0;
let crewInquiryFine = 0;
let insurancePayout = 0;
let netCashChange = 0;
let reputationDelta = 0;
let casualties = 0;
let agencyTerminated = false;
let summary = "";
if (m.ascent.success) {
const balanceShare = orbitGrade === "partial" ? 0.3 : 0.65;
const reqDv = contract?.requiredDv ?? 9000;
const margin = m.validation
? Math.max(0, m.validation.dvMargin / Math.max(1, reqDv))
: 0.08;
const bus = m.validation?.assembly?.spacecraftBus;
const gradeBonusRate =
bus?.efficiencyGrade === "S"
? 0.05
: bus?.efficiencyGrade === "A"
? 0.025
: 0;
const effBonusRate =
orbitGrade === "nominal"
? Math.min(
0.1,
margin * 0.4 +
((m.validation?.compliance.waivedCount ?? 0) === 0 ? 0.04 : 0),
) + gradeBonusRate
: 0;
grossPayout = Math.round(budget * (balanceShare + effBonusRate));
scienceBonus =
orbitGrade === "nominal"
? Math.round(budget * ((bus?.scienceBonusPct ?? 0) / 100))
: 0;
researchPointsEarned = Number(
(
(orbitGrade === "nominal" ? 1.0 : 0.4) + (bus?.researchPointsBonus ?? 0)
).toFixed(2),
);
const canRecover =
(contract?.isReusable ||
(agency.unlockedTechs ?? []).includes("methalox-reusable")) &&
(m.ascent.dvRemaining ?? 0) >= 450 &&
(!!m.rocketDesign.stages?.[0]?.hasFins ||
(m.rocketDesign.stages?.length ?? 0) >= 2);
if (canRecover) {
const stage0Cost =
m.validation?.assembly?.stages?.[0]?.stageCost ??
Math.round(m.cost * 0.55);
reusabilityBonus = Math.round(stage0Cost * 0.28);
}
netCashChange = grossPayout + scienceBonus + reusabilityBonus;
agency.treasury += netCashChange;
const loyaltyRepMult = contract?.isHomeSponsor ? 1.15 : 1.0;
const repRaw =
(orbitGrade === "partial"
? 1.5 * repMult
: (3 + margin * 5 + (bus?.researchPointsBonus ?? 0) * 0.5) * repMult) *
loyaltyRepMult;
const nextRep = Math.round((agency.reputation + repRaw) * 10) / 10;
reputationDelta = Math.round((nextRep - agency.reputation) * 10) / 10;
agency.reputation = nextRep;
agency.missionsCompleted += 1;
agency.earnedTotal += netCashChange;
const heritage = { ...(agency.partHeritage ?? {}) };
for (const st of m.rocketDesign.stages ?? []) {
for (const id of [
st.engineId,
st.tankId,
st.structureId,
st.materialId,
st.interstageId,
].filter(Boolean) as string[]) {
heritage[id] = (heritage[id] ?? 0) + 1;
}
}
if (m.rocketDesign.fairingId) {
heritage[m.rocketDesign.fairingId] =
(heritage[m.rocketDesign.fairingId] ?? 0) + 1;
}
agency.partHeritage = heritage;
recordContractCompletion(agency, m.missionId);
const peKm = Math.round(m.ascent.periapsis / 1000);
const apKm = Math.round(m.ascent.apoapsis / 1000);
summary =
orbitGrade === "partial"
? `Partial orbit insertion (${peKm} × ${apKm} km) — reduced 30% contract balance paid.`
: `Nominal orbit insertion (${peKm} × ${apKm} km) — full 65% completion balance settled.`;
emit("mission.completed", {
agency: agency.name,
missionId: m.missionId,
payout: netCashChange,
orbitGrade,
ai: !!agency.isAI,
});
} else {
agency.missionsFailed += 1;
insurancePayout = agency.launchInsured ? Math.round(m.cost * 0.7) : 0;
breachPenalty =
profile.id === "explorer" ||
profile.id === "sandbox" ||
agency.launchInsured
? 0
: Math.round(budget * profile.breachFineRate);
const lowAltPadAccident = m.ascent.burnoutAltitude < 3500;
if (
lowAltPadAccident &&
profile.id !== "explorer" &&
profile.id !== "sandbox"
) {
padRepairCost =
6_000_000 + Math.min(8_000_000, Math.round(m.cost * 0.22));
agency.padDamagedUntilSimTime = simTime + 900;
}
const crewSize = contract?.crewed
? Math.max(1, agency.crewConfig?.crewSize || 2)
: 0;
let repPenalty = 0;
if (crewOutcome === "loss_of_crew") {
casualties = crewSize;
agency.casualtiesTotal = (agency.casualtiesTotal ?? 0) + casualties;
crewInquiryFine =
profile.id === "explorer" || profile.id === "sandbox" ? 0 : 18_000_000;
repPenalty =
profile.id === "sandbox"
? 0
: profile.id === "explorer"
? 2.5
: Math.max(28, Math.round(agency.reputation * 0.75 * 10) / 10);
if (profile.id !== "sandbox") {
agency.groundedUntilSimTime = simTime + 1800;
}
if (profile.locTerminatesAgency) {
agencyTerminated = true;
agency.terminatedReason =
"Catastrophic Loss of Crew — Flight Director License Revoked";
agency.bankrupt = true;
agency.bankruptAt = simTime;
}
summary =
profile.id === "sandbox"
? `Crew lost (${casualties}) — sandbox mode exempts agency from fines & stand-downs.`
: `Catastrophic crew loss (${casualties} casualties) — safety board inquiry & mandatory stand-down.`;
} else if (crewOutcome === "las_saved") {
casualties = 0;
repPenalty =
profile.id === "sandbox" ? 0 : profile.id === "explorer" ? 0.5 : 3.5;
summary =
"Mission aborted; Launch Abort System recovered crew safely (0 casualties).";
} else {
repPenalty =
profile.id === "sandbox"
? 0
: profile.id === "explorer"
? 0.5
: profile.id === "enthusiast"
? 3.0
: profile.id === "engineer"
? 4.5
: 6.0;
summary = lowAltPadAccident
? "Low-altitude range failure damaged launch pad; breach fine & rebuild costs assessed."
: `Mission failed (${m.ascent.failureReason ?? "ascent anomaly"}); contract breach penalties settled.`;
}
const nextRep = Math.max(
0,
Math.round((agency.reputation - repPenalty) * 10) / 10,
);
reputationDelta = Math.round((nextRep - agency.reputation) * 10) / 10;
agency.reputation = nextRep;
netCashChange =
insurancePayout - breachPenalty - padRepairCost - crewInquiryFine;
agency.treasury += netCashChange;
if (agency.treasury < 5_000_000 && !agency.bankrupt) {
agency.bankrupt = true;
agency.bankruptAt = simTime;
emit("agency.bankrupt", { agency: agency.name, isAI: !!agency.isAI });
}
emit("mission.failed", {
agency: agency.name,
missionId: m.missionId,
reason: m.ascent.failureDetail,
crewOutcome,
casualties,
ai: !!agency.isAI,
});
}
agency.launchInsured = profile.id === "explorer" || profile.id === "sandbox";
const settlement: MissionSettlement = {
missionId: m.missionId,
missionName: m.name,
settledAtSimTime: simTime,
success: m.ascent.success,
orbitGrade,
crewOutcome,
advancePayout,
grossPayout,
scienceBonus,
researchPointsEarned,
reusabilityBonus,
breachPenalty,
padRepairCost,
crewInquiryFine,
insurancePayout,
netCashChange,
reputationDelta,
casualties,
failureReason: m.ascent.failureReason,
failureDetail: m.ascent.failureDetail,
agencyTerminated,
summary,
};
m.settled = true;
m.settlement = settlement;
agency.lastSettlement = settlement;
if (agency.isAI && agency.aiType === "ml") {
recordMlEpisodeOutcome(agency, m, settlement);
}
if (agency.isAI) {
m.ascent.telemetry = downsampleEven(m.ascent.telemetry, 24);
if (m.trajectory?.points)
m.trajectory.points = downsampleEven(m.trajectory.points, 32);
agency.aiContractReadyAtSimTime = null;
if (
!agency.aiCooldownUntilSimTime ||
agency.aiCooldownUntilSimTime <= simTime
) {
const skill = Math.min(1, Math.max(0, agency.aiSkill ?? 0.55));
const minCd = m.ascent.success ? 1800 : 2700;
const maxCd = m.ascent.success ? 3000 : 4500;
const rawCd =
minCd +
(maxCd - minCd) *
(0.25 + (1 - skill) * 0.65) *
(0.85 + Math.random() * 0.3);
const cooldownSec = Math.max(1800, Math.min(4500, Math.round(rawCd)));
agency.aiCooldownUntilSimTime = Math.max(
agency.aiCooldownUntilSimTime ?? 0,
simTime + cooldownSec,
);
}
}
putAgency(agency.name, agency);
return settlement;
}
function downsampleEven<T>(arr: T[] | undefined, max: number): T[] {
if (!Array.isArray(arr) || arr.length <= max) return arr ?? [];
const out: T[] = [];
const step = (arr.length - 1) / (max - 1);
for (let i = 0; i < max; i++) out.push(arr[Math.round(i * step)]);
return out;
}
export function settlePlayerMissions(): void {
const world = getWorld();
for (const agency of listAgencies()) {
if (agency.isAI || !agency.activeMissions?.length) continue;
const remaining: ActiveMission[] = [];
let changed = false;
for (const m of agency.activeMissions) {
if (world.simTime < m.completeAt) {
remaining.push(m);
continue;
}
changed = true;
if (!m.settled) {
settleMissionOutcome(agency, m, world.simTime);
clearActiveContract(agency);
}
}
if (changed) {
agency.activeMissions = remaining;
putAgency(agency.name, agency);
}
}
}

230
src/server/store.ts Normal file
View file

@ -0,0 +1,230 @@
// JSON database store for accounts, agencies, tokens, world state, and shared blueprints.
// Not gonna bother with SQLite
import fs from "node:fs";
import path from "node:path";
import { config } from "./config.js";
import type {
ActiveMission,
AgencyState,
PreLaunchHazardEvent,
SpaceWeather,
} from "../shared/types.js";
export interface AccountRecord {
name: string;
hash: string;
createdAt: number;
}
export interface TokenRecord {
name: string;
createdAt: number;
}
export interface WorldRecord {
simTime: number;
weather: SpaceWeather;
weatherUntil: number;
market: Record<string, number>;
aiSeedEpoch?: number;
activeHazards?: PreLaunchHazardEvent[];
upcomingHazards?: PreLaunchHazardEvent[];
hazardEpoch?: number;
}
export type SavedRocketBlueprint =
import("../shared/types.js").SavedRocketBlueprint;
export interface DbSchema {
accounts: Record<string, AccountRecord>;
agencies: Record<string, AgencyState>;
tokens: Record<string, TokenRecord>;
world: WorldRecord;
sharedBlueprints?: SavedRocketBlueprint[];
}
const DEFAULT_DB: DbSchema = {
accounts: {},
agencies: {},
tokens: {},
world: {
simTime: Math.floor(Date.now() / 1000),
weather: "nominal",
weatherUntil: 0,
market: {},
},
sharedBlueprints: [],
};
let db: DbSchema = structuredClone(DEFAULT_DB);
let dirty = false;
const SAVE_DEBOUNCE_MS = 5000;
let pendingSaveTimer: NodeJS.Timeout | null = null;
export function loadDb(): DbSchema {
try {
if (fs.existsSync(config.dataFile)) {
const raw = JSON.parse(
fs.readFileSync(config.dataFile, "utf8"),
) as Partial<DbSchema>;
db = {
accounts: raw.accounts ?? {},
agencies: raw.agencies ?? {},
tokens: raw.tokens ?? {},
world: {
simTime: raw.world?.simTime ?? Math.floor(Date.now() / 1000),
weather: raw.world?.weather ?? "nominal",
weatherUntil: raw.world?.weatherUntil ?? 0,
market: raw.world?.market ?? {},
aiSeedEpoch: raw.world?.aiSeedEpoch ?? 0,
activeHazards: raw.world?.activeHazards ?? [],
upcomingHazards: raw.world?.upcomingHazards ?? [],
hazardEpoch: raw.world?.hazardEpoch ?? 0,
},
sharedBlueprints: Array.isArray(raw.sharedBlueprints)
? raw.sharedBlueprints
: [],
};
}
} catch (err) {
console.error("[store] failed to load db.json, resetting:", err);
db = structuredClone(DEFAULT_DB);
}
return db;
}
export function markDirty(): void {
dirty = true;
}
function flushDbNow(): void {
if (pendingSaveTimer) {
clearTimeout(pendingSaveTimer);
pendingSaveTimer = null;
}
dirty = false;
fs.mkdirSync(path.dirname(config.dataFile), { recursive: true });
const tmp = `${config.dataFile}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(db, null, 2));
fs.renameSync(tmp, config.dataFile);
}
export function saveDb(force = false): void {
if (force) {
flushDbNow();
return;
}
if (!dirty) return;
if (!pendingSaveTimer) {
pendingSaveTimer = setTimeout(() => {
pendingSaveTimer = null;
if (dirty) flushDbNow();
}, SAVE_DEBOUNCE_MS);
pendingSaveTimer.unref?.();
}
}
export function listSharedBlueprints(): SavedRocketBlueprint[] {
if (!db.sharedBlueprints) db.sharedBlueprints = [];
return [...db.sharedBlueprints].sort(
(a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0),
);
}
export function putSharedBlueprint(bp: SavedRocketBlueprint): void {
if (!db.sharedBlueprints) db.sharedBlueprints = [];
const idx = db.sharedBlueprints.findIndex((item) => item.id === bp.id);
if (idx >= 0) {
db.sharedBlueprints[idx] = bp;
} else {
db.sharedBlueprints.unshift(bp);
if (db.sharedBlueprints.length > 120) {
db.sharedBlueprints.length = 120;
}
}
markDirty();
}
export function deleteSharedBlueprint(
id: string,
authorAgency?: string,
): boolean {
if (!db.sharedBlueprints) return false;
const idx = db.sharedBlueprints.findIndex(
(item) =>
item.id === id && (!authorAgency || item.authorAgency === authorAgency),
);
if (idx < 0) return false;
db.sharedBlueprints.splice(idx, 1);
markDirty();
return true;
}
process.on("beforeExit", () => {
if (dirty) saveDb(true);
});
process.on("exit", () => {
if (dirty) saveDb(true);
});
for (const sig of ["SIGINT", "SIGTERM"] as const) {
process.once(sig, () => {
try {
if (dirty) saveDb(true);
} catch {}
if (process.listenerCount(sig) === 0) {
process.kill(process.pid, sig);
}
});
}
export function getDb(): DbSchema {
return db;
}
export function getAccount(name: string): AccountRecord | null {
return db.accounts[name] ?? null;
}
export function putAccount(name: string, account: AccountRecord): void {
db.accounts[name] = account;
dirty = true;
}
export function getAgency(name: string): AgencyState | null {
return db.agencies[name] ?? null;
}
export function putAgency(name: string, agency: AgencyState): void {
db.agencies[name] = agency;
dirty = true;
}
export function listAgencies(): AgencyState[] {
return Object.values(db.agencies);
}
export function getTokenRecord(token: string): TokenRecord | null {
return db.tokens[token] ?? null;
}
export function putToken(token: string, info: TokenRecord): void {
db.tokens[token] = info;
dirty = true;
}
export function deleteToken(token: string): void {
delete db.tokens[token];
dirty = true;
}
export function getWorld(): WorldRecord {
return db.world;
}
export function findActiveMission(id: string): ActiveMission | null {
for (const agency of Object.values(db.agencies)) {
const found = (agency.activeMissions ?? []).find((m) => m.id === id);
if (found) return found;
}
return null;
}

158
src/server/world.ts Normal file
View file

@ -0,0 +1,158 @@
// Advances the world simulation loop, and builds live WorldSnapshot views.
import { aiTick } from "./ai.js";
import { config } from "./config.js";
import { tickEconomy } from "./economy.js";
import { emit } from "./events.js";
import {
ensureHazards,
getActiveHazards,
getUpcomingHazards,
WEATHER_POOL,
} from "./hazards.js";
import { settlePlayerMissions } from "./settlement.js";
import {
getWorld,
listAgencies,
markDirty,
putAgency,
saveDb,
} from "./store.js";
import { bodyPosition } from "../shared/ephemeris.js";
import {
getDifficultyProfile,
normalizeDifficulty,
} from "../shared/physics.js";
import type { WorldSnapshot } from "../shared/types.js";
export {
getActiveHazards,
getSimTime,
getUpcomingHazards,
getWeather,
initWorld,
} from "./hazards.js";
export { settleMissionOutcome } from "./settlement.js";
let lastRealTick = Date.now();
let lastOverheadSimTime = 0;
export function tick(): void {
const now = Date.now();
const elapsed = Math.min(5, (now - lastRealTick) / 1000);
lastRealTick = now;
const world = getWorld();
world.simTime += elapsed * config.simSecondsPerRealSecond;
if (world.simTime > world.weatherUntil) {
const next = WEATHER_POOL[Math.floor(Math.random() * WEATHER_POOL.length)];
world.weather = next;
world.weatherUntil = world.simTime + 1800 + Math.random() * 4200;
emit("world.weather", {
weather: world.weather,
until: world.weatherUntil,
});
}
ensureHazards(world.simTime);
if (!lastOverheadSimTime) lastOverheadSimTime = world.simTime;
if (world.simTime - lastOverheadSimTime >= 1800) {
chargeFacilityOverhead(world.simTime);
lastOverheadSimTime = world.simTime;
}
tickEconomy();
aiTick();
settlePlayerMissions();
markDirty();
saveDb();
}
// This is actually kinda unfair - we should probably charge this based on the actual facilities that are active but I'm not dealing with that rn
function chargeFacilityOverhead(simTime: number): void {
return;
for (const agency of listAgencies()) {
if (!agency.sponsorId || agency.bankrupt || agency.terminatedReason)
continue;
const profile = getDifficultyProfile(agency.difficulty);
let fee = profile.facilityCostPerPeriod;
if (fee <= 0) continue;
agency.treasury -= fee;
if (agency.treasury < 0) {
agency.bankrupt = true;
agency.bankruptAt = simTime;
emit("agency.bankrupt", {
agency: agency.name,
isAI: !!agency.isAI,
reason: "Facility overhead insolvency",
});
}
putAgency(agency.name, agency);
}
}
export function worldSnapshot(): WorldSnapshot {
const world = getWorld();
const t = world.simTime;
const agencies = listAgencies();
const activeFlights: WorldSnapshot["activeFlights"] = [];
for (const a of agencies) {
const canonDiff = normalizeDifficulty(a.difficulty);
for (const m of a.activeMissions ?? []) {
activeFlights.push({
id: m.id,
agencyName: a.name,
isAI: !!a.isAI,
aiType: a.aiType,
difficulty: canonDiff,
aiSkill: a.isAI ? (a.aiSkill ?? null) : null,
name: m.name,
target: m.target,
launchedAt: m.launchedAt,
completeAt: m.completeAt,
progress: Math.min(
1,
Math.max(
0,
(t - m.launchedAt) / Math.max(1, m.completeAt - m.launchedAt),
),
),
});
}
}
return {
simTime: t,
simDate: new Date(t * 1000).toISOString(),
weather: world.weather,
weatherUntil: world.weatherUntil,
activeHazards: getActiveHazards(),
upcomingHazards: getUpcomingHazards(),
bodies: {
mercury: bodyPosition("mercury", t),
venus: bodyPosition("venus", t),
earth: bodyPosition("earth", t),
moon: bodyPosition("moon", t),
mars: bodyPosition("mars", t),
asteroid: bodyPosition("asteroid", t),
jupiter: bodyPosition("jupiter", t),
saturn: bodyPosition("saturn", t),
},
agencies: agencies.map((a) => {
const first = a.activeMissions?.[0];
return {
name: a.name,
isAI: !!a.isAI,
aiType: a.aiType,
difficulty: normalizeDifficulty(a.difficulty),
aiSkill: a.isAI ? (a.aiSkill ?? null) : null,
bankrupt: !!a.bankrupt,
treasury: a.treasury,
reputation: a.reputation,
missionsCompleted: a.missionsCompleted,
missionsFailed: a.missionsFailed,
sponsorId: a.sponsorId,
activeMissions: (a.activeMissions ?? []).length,
activeFlightId: first?.id ?? null,
activeFlightTarget: first?.target ?? null,
activeFlightName: first?.name ?? null,
};
}),
activeFlights,
};
}

View file

@ -0,0 +1,82 @@
// Physical constants, atmosphere model, Keplerian orbital elements, speed of sound, ground tracking, and ascent options.
import type {
DifficultyLevel,
GroundNetworkTier,
MaterialSpec,
MissionTemplate,
Part,
PreLaunchHazardEvent,
SpaceWeather,
} from "../types.js";
export const RHO0 = 1.225;
export const SCALE_HEIGHT = 8500;
export const MU = 3.986004418e14;
export const RE = 6371000;
export function airDensity(altM: number): number {
if (altM < 0) return RHO0;
if (altM > 220000) return 0;
return RHO0 * Math.exp(-altM / SCALE_HEIGHT);
}
export function orbitalElements(
rx: number,
ry: number,
vx: number,
vy: number,
) {
const rr = Math.hypot(rx, ry);
const v2 = vx * vx + vy * vy;
const energy = v2 / 2 - MU / rr;
const hSpec = rx * vy - ry * vx;
const a = energy < -1e-3 ? -MU / (2 * energy) : 1e12;
const eSq = Math.max(0, 1 + (2 * energy * hSpec * hSpec) / (MU * MU));
const e = Math.sqrt(eSq);
const periapsis = a * (1 - e) - RE;
const apoapsis = energy >= 0 ? 1e9 : a * (1 + e) - RE;
return { apoapsis, periapsis, energy, e };
}
export function speedOfSoundAtAlt(alt: number): number {
let tempK = 288.15;
if (alt < 11000) tempK = Math.max(216.65, 288.15 - 0.0065 * Math.max(0, alt));
else if (alt < 25000) tempK = 216.65;
else if (alt < 47000) tempK = 216.65 + 0.003 * (alt - 25000);
else tempK = Math.max(185, 282.65 - 0.002 * (alt - 47000));
return Math.sqrt(1.4 * 287.05 * tempK);
}
export function computeGroundStation(
alt: number,
downrange: number,
groundTier: GroundNetworkTier,
): string {
return alt < 35_000 && downrange < 60_000
? "PAD-39A OPTICAL/S-BAND"
: downrange < 450_000
? "CAPE CANAVERAL MILA"
: downrange < 1_400_000
? "BERMUDA DOWNRANGE"
: alt < 160_000
? "ATLANTIC TELEMETRY SHIP"
: groundTier === "optical-deep-space"
? "DEEP SPACE OPTICAL ARRAY"
: groundTier === "global-dsn"
? "GOLDSTONE / MADRID DSN"
: "TDRS RELAY NETWORK";
}
export interface AscentOptions {
dt?: number;
maxTime?: number;
sampleEvery?: number;
weather?: SpaceWeather;
activeHazards?: PreLaunchHazardEvent[];
unlockedTechs?: string[];
mission?: Partial<MissionTemplate> | null;
difficulty?: DifficultyLevel | string | null;
partDefectRiskPct?: number;
rollAnomalies?: boolean;
priceOf?: (part: Part, material?: MaterialSpec) => number;
}

View file

@ -0,0 +1,324 @@
// Compute remaining upper-stage delta-v, perform apogee circularization burn, grade orbit insertion, and build SimResult.
import { DifficultyProfile, G0 } from "../physics.js";
import type {
CrewEmergencyOutcome,
FlightParams,
OrbitInsertionGrade,
RocketAssembly,
RocketDesign,
SimFailure,
SimResult,
SpacecraftBusEvaluation,
TelemetrySample,
} from "../types.js";
import { type AscentOptions, MU, orbitalElements, RE } from "./environment.js";
export interface PostBurnoutInput {
rx: number;
ry: number;
vx: number;
vy: number;
t: number;
vRot: number;
stageIndex: number;
nStages: number;
assembly: RocketAssembly;
design: RocketDesign;
fp: FlightParams;
fairingJettisoned: boolean;
fairingMass: number;
fairingSepAltKm: number | null;
stageDropProp: number[];
stageCoreProp: number[];
stageDropDry: number[];
stageDropJettisoned: boolean[];
dropTankJettisons: Array<{
t: number;
stageIndex: number;
dryMassJettisonedKg: number;
}>;
mecoCoastToApogee: boolean;
failure: SimFailure | null;
failureDetail: string;
options: AscentOptions;
diffProfile: DifficultyProfile;
isCrewedMission: boolean;
peakGLoad: number;
maxQ: number;
maxQStage: number;
peakHeatFluxWcm2: number;
partRiskPct: number;
minSignalHealthPct: number;
sigCount: number;
sigSum: number;
baseSignalPct: number;
bus: SpacecraftBusEvaluation | undefined;
peakCpuLoadPct: number;
totalSeuCount: number;
peakRadFluxMsvHr: number;
telemetry: TelemetrySample[];
events: Array<{ t: number; label: string; kind: "info" | "warn" | "err" }>;
}
export function finalizeAscentSimulation(input: PostBurnoutInput): SimResult {
const {
rx,
ry,
vx,
vy,
t,
vRot,
stageIndex,
nStages,
assembly,
design,
fp,
fairingJettisoned,
fairingMass,
fairingSepAltKm,
stageDropProp,
stageCoreProp,
stageDropDry,
stageDropJettisoned,
dropTankJettisons,
mecoCoastToApogee,
options,
diffProfile,
isCrewedMission,
peakGLoad,
maxQ,
maxQStage,
peakHeatFluxWcm2,
partRiskPct,
minSignalHealthPct,
sigCount,
sigSum,
baseSignalPct,
bus,
peakCpuLoadPct,
totalSeuCount,
peakRadFluxMsvHr,
telemetry,
events,
} = input;
let { failure, failureDetail } = input;
const orbFinal = orbitalElements(rx, ry, vx, vy);
const altFinal = Math.hypot(rx, ry) - RE;
const speedFinal = Math.hypot(vx, vy);
let finalApM = Math.max(0, orbFinal.apoapsis);
let finalPeM = orbFinal.periapsis;
let dvRemaining = 0;
let massAbove =
assembly.totalPayloadMass - (fairingJettisoned ? fairingMass : 0);
for (let i = nStages - 1; i >= stageIndex; i--) {
const st = assembly.stages[i];
if (!st) continue;
const remDrop = Math.max(0, stageDropProp[i]);
const remCore = Math.max(0, stageCoreProp[i]);
const remDropDry = !stageDropJettisoned[i] ? stageDropDry[i] : 0;
const coreDry = Math.max(1, st.dryMass - stageDropDry[i]);
if (st.ispVacS > 0 && remDrop + remCore > 0) {
if (remDrop > 0 && !stageDropJettisoned[i]) {
const m0Phase1 = massAbove + coreDry + remDropDry + remCore + remDrop;
const mfPhase1 = m0Phase1 - remDrop;
if (mfPhase1 > 0)
dvRemaining += st.ispVacS * G0 * Math.log(m0Phase1 / mfPhase1);
const m0Phase2 = massAbove + coreDry + remCore;
const mfPhase2 = massAbove + coreDry;
if (remCore > 0 && mfPhase2 > 0)
dvRemaining += st.ispVacS * G0 * Math.log(m0Phase2 / mfPhase2);
} else {
const m0 = massAbove + coreDry + remDropDry + remCore;
const mf = massAbove + coreDry + remDropDry;
if (mf > 0) dvRemaining += st.ispVacS * G0 * Math.log(m0 / mf);
}
}
massAbove += coreDry + remDropDry + remDrop + remCore;
}
const reqOrbit = options.mission?.targetOrbit;
if (
!failure &&
finalApM >= 155000 &&
(finalPeM >= 85000 ||
(mecoCoastToApogee && altFinal >= 95000 && dvRemaining > 20))
) {
const goalPeM =
reqOrbit && reqOrbit.apoapsisKm <= 1200
? Math.min(
finalApM - 1500,
Math.max(120000, reqOrbit.periapsisKm * 1000),
)
: Math.min(finalApM - 1500, 185000);
if (finalPeM < goalPeM && dvRemaining > 8) {
const ra = RE + finalApM;
const rp1 = RE + finalPeM;
const a1 = (ra + rp1) * 0.5;
const va1 = Math.sqrt(Math.max(0, MU * (2 / ra - 1 / a1)));
const rp2 = RE + goalPeM;
const a2 = (ra + rp2) * 0.5;
const va2 = Math.sqrt(Math.max(0, MU * (2 / ra - 1 / a2)));
const dvNeeded = Math.max(0, va2 - va1);
const dvBurn = Math.min(dvRemaining, dvNeeded);
if (dvBurn > 1) {
const vaNew = va1 + dvBurn;
const epsNew = 0.5 * vaNew * vaNew - MU / ra;
if (epsNew < -1e-3) {
const aNew = -MU / (2 * epsNew);
const rpNew = Math.max(rp1, 2 * aNew - ra);
finalPeM = Math.min(goalPeM, rpNew - RE);
dvRemaining = Math.max(0, dvRemaining - dvBurn);
events.push({
t: t + 1,
label: `Apogee circularization burn (-${Math.round(dvBurn)} m/s) -> ${Math.round(finalPeM / 1000)}×${Math.round(finalApM / 1000)} km`,
kind: "info",
});
}
}
}
}
let orbitGrade: OrbitInsertionGrade = "failed";
if (!failure) {
if (finalApM < 155000 || finalPeM < 85000) {
failure = "propellant_depleted";
failureDetail = `Orbit below minimum safe envelope (${Math.round(finalPeM / 1000)}×${Math.round(finalApM / 1000)} km).`;
} else if (reqOrbit) {
const apKm = finalApM / 1000;
const peKm = finalPeM / 1000;
const incErr = Math.abs(
fp.targetInclinationDeg - reqOrbit.inclinationDeg,
);
if (reqOrbit.apoapsisKm <= 1200) {
const apErrPct =
(Math.abs(apKm - reqOrbit.apoapsisKm) /
Math.max(150, reqOrbit.apoapsisKm)) *
100;
const peErrPct =
(Math.abs(peKm - reqOrbit.periapsisKm) /
Math.max(120, reqOrbit.periapsisKm)) *
100;
const maxOrbitErrPct = Math.max(apErrPct, peErrPct);
if (
maxOrbitErrPct <= diffProfile.orbitTolPct &&
incErr <= diffProfile.incTolDeg &&
peKm >= 115
) {
orbitGrade = "nominal";
} else if (
maxOrbitErrPct <= diffProfile.orbitTolPct * 2.25 &&
incErr <= diffProfile.incTolDeg * 2.25 &&
peKm >= 95
) {
orbitGrade = "partial";
events.push({
t: t + 2,
label: `Partial orbit insertion (${Math.round(peKm)}×${Math.round(apKm)} km @ ${fp.targetInclinationDeg.toFixed(1)}°) — outside ±${diffProfile.orbitTolPct}% / ±${diffProfile.incTolDeg}° tolerance`,
kind: "warn",
});
} else {
orbitGrade = "failed";
failure = "orbital_misinjection";
failureDetail = `Orbital misinjection: achieved ${Math.round(peKm)}×${Math.round(apKm)} km @ ${fp.targetInclinationDeg.toFixed(1)}°, exceeding ${diffProfile.label} corridor (${reqOrbit.periapsisKm}×${reqOrbit.apoapsisKm} km ±${diffProfile.orbitTolPct}%, ${reqOrbit.inclinationDeg}° ±${diffProfile.incTolDeg}°).`;
events.push({ t: t + 2, label: failureDetail, kind: "err" });
}
} else {
const parkErrPct =
(Math.abs(apKm - fp.targetApoapsisKm) /
Math.max(150, fp.targetApoapsisKm)) *
100;
const reqDv = options.mission?.requiredDv ?? 11500;
const effectiveDeliveredDv = Math.min(
assembly.totalDv,
9600 + dvRemaining,
);
const transferShortfallPct =
((reqDv - effectiveDeliveredDv) / reqDv) * 100;
if (
incErr <= diffProfile.incTolDeg &&
parkErrPct <= diffProfile.orbitTolPct * 1.5 &&
transferShortfallPct <= 0 &&
peKm >= 120
) {
orbitGrade = "nominal";
} else if (
incErr <= diffProfile.incTolDeg * 2.2 &&
transferShortfallPct <= diffProfile.orbitTolPct * 0.15 &&
peKm >= 100
) {
orbitGrade = "partial";
events.push({
t: t + 2,
label:
"Partial transfer injection — off-nominal plane, parking corridor, or tight upper-stage reserve",
kind: "warn",
});
} else {
orbitGrade = "failed";
failure = "orbital_misinjection";
failureDetail = `Transfer injection missed corridor: parking ${Math.round(peKm)}×${Math.round(apKm)} km @ ${fp.targetInclinationDeg.toFixed(1)}°, ${Math.round(dvRemaining)} m/s upper reserve.`;
events.push({ t: t + 2, label: failureDetail, kind: "err" });
}
}
} else {
orbitGrade = "nominal";
}
}
let crewOutcome: CrewEmergencyOutcome = "none";
if (isCrewedMission) {
if (!failure) {
crewOutcome = "nominal";
} else if (
design.hasLaunchAbort &&
peakGLoad <= 15.0 &&
failure !== "g_load_exceeded"
) {
crewOutcome = "las_saved";
events.push({
t: t + 0.5,
label:
"LAS ESCAPE TOWER FIRED — Crew capsule separated safely under chutes",
kind: "warn",
});
} else {
crewOutcome = "loss_of_crew";
events.push({
t: t + 0.5,
label:
"CRITICAL: Loss of Crew (LOC) — No survivable Launch Abort envelope",
kind: "err",
});
}
}
return {
success: !failure,
failureReason: failure,
failureDetail,
telemetry,
maxQ,
maxQStage,
peakGLoad,
peakHeatFluxWcm2,
burnoutAltitude: Math.max(0, altFinal),
burnoutVelocity: speedFinal,
burnoutDownrange: Math.max(0, RE * (Math.atan2(rx, ry) - (vRot * t) / RE)),
apoapsis: finalApM,
periapsis: finalPeM,
inclinationDeg: fp.targetInclinationDeg,
dvRemaining,
finalTime: t,
stages: nStages,
fairingSepAltKm,
dropTankJettisons,
events,
orbitGrade,
crewOutcome,
reliabilityRiskPct: partRiskPct,
minSignalHealthPct: Math.round(minSignalHealthPct),
avgSignalHealthPct:
sigCount > 0 ? Math.round(sigSum / sigCount) : Math.round(baseSignalPct),
efficiencyScore: bus?.efficiencyScore,
efficiencyGrade: bus?.efficiencyGrade,
peakCpuLoadPct: Number(peakCpuLoadPct.toFixed(1)),
totalSeuCount,
peakRadFluxMsvHr: Number(peakRadFluxMsvHr.toFixed(2)),
};
}

400
src/shared/ascent/setup.ts Normal file
View file

@ -0,0 +1,400 @@
// Validate pad readiness, compute per-stage propulsion limits, roll anomaly hazards, and initialize ascent simulation context.
import { evaluateCompliance } from "../compliance.js";
import {
buildRocket,
DifficultyProfile,
G0,
getDifficultyProfile,
} from "../physics.js";
import type {
CrewEmergencyOutcome,
FlightParams,
GroundNetworkTier,
MaterialSpec,
Part,
PreLaunchHazardEvent,
RocketAssembly,
RocketDesign,
SimFailure,
SimResult,
SpacecraftBusEvaluation,
SpaceWeather,
TelemetrySample,
} from "../types.js";
import { type AscentOptions, RE } from "./environment.js";
export type AscentSimSetup =
| { earlyResult: SimResult }
| {
earlyResult: null;
dt: number;
maxTime: number;
sampleEvery: number;
weather: SpaceWeather;
assembly: RocketAssembly;
design: RocketDesign;
fp: FlightParams;
nStages: number;
stageDropProp: number[];
stageCoreProp: number[];
stageDropDry: number[];
stageDropJettisoned: boolean[];
stage0DropAreaReduction: number;
stageMdotVac: number[];
stageMaxQ: number[];
stageMaxTempK: number[];
vRot: number;
fairingMass: number;
diffProfile: DifficultyProfile;
isCrewedMission: boolean;
comp: Part;
hasTier2Ecc: boolean;
hasTier3Guidance: boolean;
compCapacity: number;
compRadHard: number;
compMaxG: number;
compMaxTemp: number;
compScrubRate: number;
hasCryoMli: boolean;
activeHazards: PreLaunchHazardEvent[];
anomalyTriggerTime: number | null;
anomalyKind: SimFailure;
anomalyMsg: string;
partRiskPct: number;
targetApM: number;
reqOrbitOuter:
NonNullable<AscentOptions["mission"]>["targetOrbit"] | undefined;
isBoundedOrbit: boolean;
turnEndAltM: number;
bus: SpacecraftBusEvaluation | undefined;
baseSignalPct: number;
busPowerBalanceW: number;
groundTier: GroundNetworkTier;
events: Array<{
t: number;
label: string;
kind: "info" | "warn" | "err";
}>;
};
export function prepareAscentSimulation(
rawDesign: RocketDesign,
catalog: Part[],
materialsCatalog: MaterialSpec[],
options: AscentOptions,
): AscentSimSetup {
const dt = options.dt ?? 0.1;
const maxTime = options.maxTime ?? 2400;
const sampleEvery = options.sampleEvery ?? 1.0;
const weather = options.weather ?? "nominal";
const assembly = buildRocket(rawDesign, catalog, materialsCatalog, {
priceOf: options.priceOf,
mission: options.mission,
difficulty: options.difficulty,
weather,
unlockedTechs: options.unlockedTechs,
});
const design = assembly.design;
const fp = design.flightParams;
const nStages = assembly.stages.length;
const compliance = evaluateCompliance(design, assembly, {
mission: options.mission,
difficulty: options.difficulty,
weather,
activeHazards: options.activeHazards,
unlockedTechs: options.unlockedTechs,
});
const stageDropProp = assembly.stages.map((s) =>
Math.max(0, s.dropTankPropellantMass ?? 0),
);
const stageCoreProp = assembly.stages.map((s, idx) =>
s.corePropellantMass != null
? Math.max(0, s.corePropellantMass)
: Math.max(0, s.propellantMass - stageDropProp[idx]),
);
const stageDropDry = assembly.stages.map((s) =>
Math.max(0, s.dropTankDryMass ?? 0),
);
const stageDropJettisoned = assembly.stages.map(
(_s, idx) => stageDropProp[idx] <= 0 && stageDropDry[idx] <= 0,
);
const dropTankJettisons: Array<{
t: number;
stageIndex: number;
dryMassJettisonedKg: number;
}> = [];
const s0DropComps =
assembly.stages[0]?.components.filter(
(c) => c.role === "tank" && c.isDropTank,
) ?? [];
const stage0DropAreaReduction = s0DropComps.reduce(
(sum, c) =>
sum +
Math.PI *
Math.pow(c.diameter / 2, 2) *
Math.max(1, c.symmetry ?? c.count ?? 1) *
0.18,
0,
);
const stageMdotVac = assembly.stages.map((s) =>
s.thrustN > 0 && s.ispVacS > 0 ? s.thrustN / (s.ispVacS * G0) : 0,
);
const stageMaxQ = assembly.stages.map((s) => s.maxQPaLimit);
const stageMaxTempK = assembly.stages.map((s) =>
s.config.hasHeatshield
? Math.max(1800, s.material.maxTempK)
: s.material.maxTempK,
);
let mass = assembly.liftoffMass;
const vRot =
410 * Math.cos(((fp.targetInclinationDeg ?? 28.5) * Math.PI) / 180);
let rx = 0;
let ry = RE;
let vx = vRot;
let vy = 0;
let stageIndex = 0;
let separationTimer = 0;
let jettisonPending: number | null = null;
let fairingJettisoned = false;
let fairingSepAltKm: number | null = null;
const fairingMass = assembly.fairingPart?.dryMass ?? 0;
let pitchDeg = 90;
let t = 0;
let nextSample = 0;
let maxQ = 0;
let maxQStage = 1;
let peakGLoad = 0;
let peakHeatFluxWcm2 = 0;
let failure: SimFailure | null = null;
let failureDetail = "";
const telemetry: TelemetrySample[] = [];
const events: Array<{
t: number;
label: string;
kind: "info" | "warn" | "err";
}> = [];
const diffProfile = getDifficultyProfile(options.difficulty);
const isCrewedMission = !!(
options.mission?.crewed || (options.mission?.crewCap ?? 0) > 0
);
const liftoffTwr = assembly.liftoffTwr;
if (liftoffTwr < 1.02) {
const crewOutcome: CrewEmergencyOutcome = isCrewedMission
? design.hasLaunchAbort
? "las_saved"
: "loss_of_crew"
: "none";
return {
earlyResult: {
success: false,
failureReason: "insufficient_twr",
failureDetail: `Liftoff TWR ${liftoffTwr.toFixed(2)} < 1.02 — vehicle stuck on pad.`,
telemetry: [],
maxQ: 0,
maxQStage: 1,
peakGLoad: 0,
peakHeatFluxWcm2: 0,
burnoutAltitude: 0,
burnoutVelocity: 0,
burnoutDownrange: 0,
apoapsis: 0,
periapsis: -RE,
inclinationDeg: fp.targetInclinationDeg,
dvRemaining: assembly.totalDv,
finalTime: 0,
stages: nStages,
fairingSepAltKm: null,
events: [
{ t: 0, label: "Pad abort: insufficient TWR", kind: "err" },
...(crewOutcome === "las_saved"
? [
{
t: 0.5,
label:
"LAS ESCAPE TOWER FIRED — Crew capsule safely recovered from pad",
kind: "warn" as const,
},
]
: crewOutcome === "loss_of_crew"
? [
{
t: 0.5,
label:
"CRITICAL: Pad failure without LAS — Loss of Crew (LOC)",
kind: "err" as const,
},
]
: []),
],
orbitGrade: "failed",
crewOutcome,
reliabilityRiskPct: options.partDefectRiskPct ?? 0,
},
};
}
const comp = assembly.computerPart;
if (!comp) {
return {
earlyResult: {
success: false,
failureReason: "computer_damaged",
failureDetail:
"No Flight Computer installed — vehicle has zero guidance or TVC authority on pad.",
telemetry: [],
maxQ: 0,
maxQStage: 1,
peakGLoad: 0,
peakHeatFluxWcm2: 0,
burnoutAltitude: 0,
burnoutVelocity: 0,
burnoutDownrange: 0,
apoapsis: 0,
periapsis: -RE,
inclinationDeg: fp.targetInclinationDeg,
dvRemaining: assembly.totalDv,
finalTime: 0,
stages: nStages,
fairingSepAltKm: null,
events: [
{
t: 0,
label: "Pad abort: Flight Computer missing (AVN-01)",
kind: "err",
},
],
orbitGrade: "failed",
crewOutcome: isCrewedMission
? design.hasLaunchAbort
? "las_saved"
: "loss_of_crew"
: "none",
reliabilityRiskPct: options.partDefectRiskPct ?? 0,
peakCpuLoadPct: 0,
totalSeuCount: 0,
peakRadFluxMsvHr: 0,
},
};
}
const unlockedSet = new Set(options.unlockedTechs ?? []);
const hasTier2Ecc =
diffProfile.allTechUnlocked || unlockedSet.has("avionics-diagnostics-2");
const hasTier3Guidance =
(diffProfile.allTechUnlocked ||
unlockedSet.has("gmat-orbital-diagnostics-3")) &&
(comp.diagnosticTier ?? 1) >= 3;
const compCapacity = Math.max(1, comp.computeCapacityIps ?? 140);
const compRadHard = comp.radHardeningLevel ?? 2;
const compMaxG = comp.maxGLoad ?? 13;
const compMaxTemp = comp.maxTempK ?? 450;
const compScrubRate =
(comp.faultScrubRate ?? 0.35) * (hasTier2Ecc ? 1.35 : 1.0);
const hasCryoMli = assembly.stages.some(
(s) => s.structurePart.id === "struct-cryo-frame",
);
const activeHazards = options.activeHazards ?? [];
let anomalyTriggerTime: number | null = null;
let anomalyKind: SimFailure = "waiver_anomaly";
let anomalyMsg = "";
const partRiskPct = options.partDefectRiskPct ?? 0;
if (options.rollAnomalies) {
const weatherRisk =
weather === "radiation-storm"
? 6
: weather === "solar-storm"
? 4
: weather === "micrometeoroid"
? 3
: 0;
const totalRiskPct = Math.min(
82,
compliance.anomalyRiskPct + weatherRisk + partRiskPct,
);
const roll = Math.random() * 100;
if (roll < totalRiskPct) {
anomalyTriggerTime = 24 + Math.random() * 115;
if (roll < partRiskPct) {
anomalyKind = "part_anomaly";
anomalyTriggerTime = 18 + Math.random() * 90;
anomalyMsg =
"Turbopump / feedline infant-mortality defect caused in-flight engine shutdown (run Static Fire tests & build flight heritage to prevent).";
} else if (roll < partRiskPct + weatherRisk && weather !== "nominal") {
anomalyKind = "weather_anomaly";
anomalyMsg = `Space weather (${weather}) induced avionics upset during ascent.`;
} else {
anomalyKind = "waiver_anomaly";
const waived = compliance.rules.find((r) => r.waived);
anomalyMsg = waived
? `Waived rule [${waived.code}] ${waived.title} manifested a flight failure.`
: "Unmitigated compliance risk caused structural/propulsion anomaly.";
}
}
}
if (assembly.stabilityMarginCalibers < -0.5) {
events.push({
t: 12,
label: "Aerodynamic instability detected",
kind: "err",
});
}
const targetApM = Math.max(160e3, fp.targetApoapsisKm * 1000);
const reqOrbitOuter = options.mission?.targetOrbit;
const isBoundedOrbit = reqOrbitOuter
? reqOrbitOuter.apoapsisKm <= 1200
: fp.targetApoapsisKm <= 1200;
const turnEndAltM = Math.max(45000, fp.turnEndAltKm * 1000);
let turnStarted = false;
let maxQPassed = false;
let mecoCoastToApogee = false;
let xenonWarnedStage = -1;
const bus = assembly.spacecraftBus;
const baseSignalPct = bus?.signalHealthPct ?? 88;
const busPowerBalanceW = bus?.powerMarginWatts ?? 650;
const groundTier = bus?.groundNetworkTier ?? "regional";
let lastStation = "";
return {
earlyResult: null,
dt,
maxTime,
sampleEvery,
weather,
assembly,
design,
fp,
nStages,
stageDropProp,
stageCoreProp,
stageDropDry,
stageDropJettisoned,
stage0DropAreaReduction,
stageMdotVac,
stageMaxQ,
stageMaxTempK,
vRot,
fairingMass,
diffProfile,
isCrewedMission,
comp,
hasTier2Ecc,
hasTier3Guidance,
compCapacity,
compRadHard,
compMaxG,
compMaxTemp,
compScrubRate,
hasCryoMli,
activeHazards,
anomalyTriggerTime,
anomalyKind,
anomalyMsg,
partRiskPct,
targetApM,
reqOrbitOuter,
isBoundedOrbit,
turnEndAltM,
bus,
baseSignalPct,
busPowerBalanceW,
groundTier,
events,
};
}

View file

@ -0,0 +1,699 @@
// Run curved-Earth 2D planar ascent integration with thrust, drag, heating, SEU faults, staging, and gravity turn steering.
// Random bullshit go!
import { G0 } from "../physics.js";
import type {
MaterialSpec,
Part,
RocketDesign,
SimFailure,
SimResult,
TelemetrySample,
} from "../types.js";
import {
airDensity,
type AscentOptions,
computeGroundStation,
MU,
orbitalElements,
RE,
RHO0,
speedOfSoundAtAlt,
} from "./environment.js";
import { finalizeAscentSimulation } from "./postBurnout.js";
import { prepareAscentSimulation } from "./setup.js";
import {
type AvionicsStepState,
stepAvionicsAndHazards,
} from "./stepAvionics.js";
export function simulateAscent(
rawDesign: RocketDesign,
catalog: Part[],
materialsCatalog: MaterialSpec[],
options: AscentOptions = {},
): SimResult {
const ctx = prepareAscentSimulation(
rawDesign,
catalog,
materialsCatalog,
options,
);
if (ctx.earlyResult) return ctx.earlyResult;
const {
dt,
maxTime,
sampleEvery,
weather,
assembly,
design,
fp,
nStages,
stageDropProp,
stageCoreProp,
stageDropDry,
stageDropJettisoned,
stage0DropAreaReduction,
stageMdotVac,
stageMaxQ,
stageMaxTempK,
vRot,
fairingMass,
diffProfile,
isCrewedMission,
comp,
hasTier2Ecc,
hasTier3Guidance,
compCapacity,
compRadHard,
compMaxG,
compMaxTemp,
compScrubRate,
hasCryoMli,
activeHazards,
anomalyTriggerTime,
anomalyKind,
anomalyMsg,
partRiskPct,
targetApM,
reqOrbitOuter,
isBoundedOrbit,
turnEndAltM,
bus,
baseSignalPct,
busPowerBalanceW,
groundTier,
events,
} = ctx;
const dropTankJettisons: Array<{
t: number;
stageIndex: number;
dryMassJettisonedKg: number;
}> = [];
let mass = assembly.liftoffMass;
let rx = 0;
let ry = RE;
let vx = vRot;
let vy = 0;
let stageIndex = 0;
let separationTimer = 0;
let jettisonPending: number | null = null;
let fairingJettisoned = false;
let fairingSepAltKm: number | null = null;
let pitchDeg = 90;
let t = 0;
let nextSample = 0;
let maxQ = 0;
let maxQStage = 1;
let peakGLoad = 0;
let peakHeatFluxWcm2 = 0;
let failure: SimFailure | null = null;
let failureDetail = "";
const telemetry: TelemetrySample[] = [];
let lastStageSepTime = -99;
let enteredShearHazard = false;
let turnStarted = false;
let maxQPassed = false;
let mecoCoastToApogee = false;
let xenonWarnedStage = -1;
let lastStation = "";
let minSignalHealthPct = baseSignalPct;
let sigSum = 0;
let sigCount = 0;
const avState: AvionicsStepState = {
t,
dt,
altKm: 0,
q: 0,
stageIndex,
nStages,
activeStage: null,
assembly,
design,
comp,
compCapacity,
compRadHard,
compScrubRate,
hasCryoMli,
fairingJettisoned,
weather,
activeHazards,
options,
lastStageSepTime,
activeSeus: 0,
totalSeuCount: 0,
peakCpuLoadPct: 0,
peakRadFluxMsvHr: 0,
overloadTimer: 0,
softOverloadWarned: false,
enteredRadHazard: false,
meteoriteRolledInBand: false,
hasShearHazard: false,
events,
};
while (t < maxTime && !failure) {
if (separationTimer > 0) {
separationTimer -= dt;
if (separationTimer <= 0 && jettisonPending != null) {
mass = Math.max(100, mass - jettisonPending);
jettisonPending = null;
events.push({
t,
label: `Stage ${stageIndex + 1} ignition`,
kind: "info",
});
}
}
const rr = Math.hypot(rx, ry);
const alt = rr - RE;
const altKm = Math.max(0, alt / 1000);
const inertialAngle = Math.atan2(rx, ry);
const padAngle = (vRot * t) / RE;
const downrange = Math.max(0, RE * (inertialAngle - padAngle));
const upX = rx / rr;
const upY = ry / rr;
const eastX = upY;
const eastY = -upX;
const speed = Math.hypot(vx, vy);
const atmRotMag = alt < 200000 ? vRot * Math.max(0, 1 - alt / 220000) : 0;
const airVx = vx - atmRotMag * eastX;
const airVy = vy - atmRotMag * eastY;
const airSpeed = Math.hypot(airVx, airVy);
const rho = airDensity(alt);
const shearHazard = activeHazards.find(
(h) =>
h.kind === "jet-stream-shear" &&
altKm >= h.altMinKm &&
altKm <= h.altMaxKm,
);
if (shearHazard && !enteredShearHazard) {
enteredShearHazard = true;
events.push({
t,
label: `Entered ${shearHazard.title} (${shearHazard.altMinKm}–${shearHazard.altMaxKm} km)`,
kind: "warn",
});
}
const q =
0.5 *
rho *
airSpeed *
airSpeed *
(shearHazard ? (shearHazard.windShearQMult ?? 1.32) : 1.0);
const activeStage =
stageIndex < nStages ? assembly.stages[stageIndex] : null;
avState.t = t;
avState.altKm = altKm;
avState.q = q;
avState.stageIndex = stageIndex;
avState.activeStage = activeStage;
avState.fairingJettisoned = fairingJettisoned;
avState.lastStageSepTime = lastStageSepTime;
avState.hasShearHazard = !!shearHazard;
const avRes = stepAvionicsAndHazards(avState);
const { radFluxMsvHr, cpuLoadPct, computerStatus } = avRes;
if (avRes.failure) {
failure = avRes.failure;
failureDetail = avRes.failureDetail;
break;
}
const maxG = Math.min(
options.mission?.maxGLoad ?? 12,
assembly.payloadPart?.maxGLoad ?? 12,
);
let throttle = 1.0;
if (activeStage && activeStage.enginePart.propellantType !== "solid") {
if (alt > 6500 && alt < 18000 && q > 12000) {
throttle = fp.maxQThrottle;
}
const maxAllowedThrust = mass * G0 * Math.max(3.5, maxG - 0.3);
if (
activeStage.thrustN * throttle > maxAllowedThrust &&
activeStage.thrustN > 0
) {
throttle = Math.min(
throttle,
Math.max(0.18, maxAllowedThrust / activeStage.thrustN),
);
}
}
if (
!fairingJettisoned &&
fairingMass > 0 &&
alt >= fp.fairingSepAltKm * 1000
) {
fairingJettisoned = true;
fairingSepAltKm = Math.round(alt / 1000);
mass = Math.max(100, mass - fairingMass);
events.push({
t,
label: `Fairing jettison at ${fairingSepAltKm} km`,
kind: "info",
});
const minSafeAltM = (options.mission?.minFairingAltKm ?? 68) * 1000;
if (alt < minSafeAltM && q > 4500) {
failure = "fairing_aero_loss";
failureDetail = `Fairing jettisoned too low (${fairingSepAltKm} km) at ${(q / 1000).toFixed(1)} kPa — payload crushed by dynamic pressure.`;
break;
}
}
if (anomalyTriggerTime != null && t >= anomalyTriggerTime) {
failure = anomalyKind;
failureDetail = anomalyMsg;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
if (assembly.stabilityMarginCalibers < -0.35 && q > 22000) {
failure = "unstable";
failureDetail = `Vehicle tumbled at Max-Q (CG/CP margin ${assembly.stabilityMarginCalibers.toFixed(2)} calibers — add Grid Fins).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
const isXenonInAtmo =
activeStage?.enginePart.propellantType === "xenon" && alt < 110_000;
if (isXenonInAtmo && xenonWarnedStage !== stageIndex) {
xenonWarnedStage = stageIndex;
events.push({
t,
label: `Stage ${stageIndex + 1} Ion Thruster locked out below 110 km atmosphere (0 N thrust)`,
kind: "warn",
});
}
if (isXenonInAtmo && stageIndex === 0 && alt < 500 && t > 1.5) {
failure = "insufficient_twr";
failureDetail =
"Hall-effect Xenon thruster produces zero thrust inside dense atmosphere (< 110 km).";
events.push({ t, label: failureDetail, kind: "err" });
break;
}
const orbCheck = orbitalElements(rx, ry, vx, vy);
const goalPeCheckM = (reqOrbitOuter?.periapsisKm ?? 150) * 1000;
if (
isBoundedOrbit &&
!mecoCoastToApogee &&
!isXenonInAtmo &&
alt >= 90_000 &&
orbCheck.apoapsis >= targetApM * 0.995 &&
orbCheck.periapsis < Math.max(85_000, goalPeCheckM * 0.85)
) {
mecoCoastToApogee = true;
events.push({
t,
label: `SECO-1 cutoff — coasting to ${Math.round(orbCheck.apoapsis / 1000)} km apogee`,
kind: "info",
});
}
const totalStageProp =
stageIndex < nStages
? stageDropProp[stageIndex] + stageCoreProp[stageIndex]
: 0;
const canBurn =
activeStage != null &&
!isXenonInAtmo &&
!mecoCoastToApogee &&
totalStageProp > 0 &&
stageMdotVac[stageIndex] > 0 &&
separationTimer <= 0;
let thrust = 0;
let thrusting = false;
if (canBurn && activeStage) {
const atmFrac = rho / RHO0;
const isp =
activeStage.ispSeaLevelS * atmFrac +
activeStage.ispVacS * (1 - atmFrac);
const effectiveThrust =
activeStage.thrustN *
throttle *
(isp / Math.max(1, activeStage.ispVacS));
const burn = stageMdotVac[stageIndex] * throttle * dt;
const dropUsed = Math.min(burn, stageDropProp[stageIndex]);
stageDropProp[stageIndex] -= dropUsed;
const coreUsed = Math.min(burn - dropUsed, stageCoreProp[stageIndex]);
stageCoreProp[stageIndex] -= coreUsed;
const used = dropUsed + coreUsed;
mass = Math.max(50, mass - used);
thrust = effectiveThrust * (used / Math.max(1e-9, burn));
thrusting = true;
if (
!stageDropJettisoned[stageIndex] &&
stageDropProp[stageIndex] <= 0 &&
stageDropDry[stageIndex] > 0
) {
const dryDrop = stageDropDry[stageIndex];
stageDropJettisoned[stageIndex] = true;
mass = Math.max(50, mass - dryDrop);
dropTankJettisons.push({ t, stageIndex, dryMassJettisonedKg: dryDrop });
events.push({
t,
label: `Stage ${stageIndex + 1} drop tanks depleted — jettisoned (-${(dryDrop / 1000).toFixed(1)}t)`,
kind: "info",
});
}
}
if (q > maxQ) {
maxQ = q;
maxQStage = stageIndex + 1;
}
if (!maxQPassed && maxQ > 12000 && q < maxQ * 0.7 && alt > 15000) {
maxQPassed = true;
events.push({
t,
label: `Max-Q cleared (${Math.round(maxQ / 1000)} kPa)`,
kind: "info",
});
}
if (activeStage && q > stageMaxQ[stageIndex]) {
failure = "structural_failure";
failureDetail = `Max-Q ${Math.round(q / 1000)} kPa exceeded Stage ${stageIndex + 1} structural limit (${Math.round(stageMaxQ[stageIndex] / 1000)} kPa).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
const heatFluxWcm2 =
(1.74e-8 * Math.sqrt(Math.max(0, rho)) * Math.pow(airSpeed, 3)) / 10000;
if (heatFluxWcm2 > peakHeatFluxWcm2) peakHeatFluxWcm2 = heatFluxWcm2;
const estWallTempK = 290 + heatFluxWcm2 * 14;
if (activeStage && estWallTempK > stageMaxTempK[stageIndex] * 1.15) {
failure = "thermal_failure";
failureDetail = `Aero heating (${Math.round(estWallTempK)} K) exceeded Stage ${stageIndex + 1} ${activeStage.material.name} thermal ceiling (${stageMaxTempK[stageIndex]} K).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
const speedOfSound = speedOfSoundAtAlt(alt);
const mach = alt < 140000 ? airSpeed / Math.max(1, speedOfSound) : 0;
const airVUp = airVx * upX + airVy * upY;
const airVEast = airVx * eastX + airVy * eastY;
const padVEast = vx * eastX + vy * eastY - vRot * (RE / rr);
const flightPathDeg =
alt < 25 || Math.hypot(padVEast, airVUp) < 1.5
? 90
: (Math.atan2(airVUp, Math.max(1e-6, padVEast)) * 180) / Math.PI;
const aoaDeg = Math.max(-45, Math.min(45, pitchDeg - flightPathDeg));
const coreStageDia = activeStage?.diameter ?? assembly.maxDiameter;
const coreArea = Math.max(Math.PI * Math.pow(coreStageDia / 2, 2), 1.5);
const area =
stageIndex === 0
? Math.max(
coreArea,
assembly.aero.frontalAreaM2 -
(stageDropJettisoned[0] && stageDropDry[0] > 0
? stage0DropAreaReduction
: 0),
)
: coreArea;
const waveDrag =
mach > 0.72 ? 0.16 * Math.exp(-Math.pow((mach - 1.08) / 0.28, 2)) : 0;
const cd =
assembly.aero.baseCd +
waveDrag +
(fairingJettisoned ? 0.22 : 0) +
0.0006 * aoaDeg * aoaDeg;
const dragMag = q * cd * area;
const gMag = MU / (rr * rr);
let fx = -mass * gMag * upX;
let fy = -mass * gMag * upY;
if (airSpeed > 1e-3) {
fx += (-dragMag * airVx) / airSpeed;
fy += (-dragMag * airVy) / airSpeed;
}
const radialVelNow = vx * upX + vy * upY;
if (!turnStarted && airSpeed >= fp.gravityTurnStartVel) {
turnStarted = true;
pitchDeg = 90 - fp.pitchOverDeg;
events.push({
t,
label: `Gravity turn pitch-over (${fp.pitchOverDeg}°)`,
kind: "info",
});
} else if (turnStarted) {
const altProgress = Math.min(1, Math.max(0, alt / turnEndAltM));
const smooth = altProgress * altProgress * (3 - 2 * altProgress);
let targetPitch = (90 - fp.pitchOverDeg) * (1 - smooth);
const orbNow = orbitalElements(rx, ry, vx, vy);
const desiredApM = Math.min(targetApM, 200_000);
if (
alt < 125_000 &&
orbNow.apoapsis < desiredApM &&
(radialVelNow < 550 || alt > 42_000)
) {
const apNeedPitch =
radialVelNow < 180 ? 34 : radialVelNow < 400 ? 24 : 15;
targetPitch = Math.max(targetPitch, apNeedPitch);
} else if (
alt >= 115_000 &&
orbNow.apoapsis >= desiredApM &&
radialVelNow > 50
) {
targetPitch = Math.max(-5, -radialVelNow * 0.025);
}
if (stageIndex > 0 && radialVelNow < 35 && speed < 7600) {
targetPitch = Math.min(
38,
Math.max(targetPitch, 20 - radialVelNow * 0.25),
);
}
if (
alt >= 110_000 &&
orbNow.apoapsis >= targetApM * 0.94 &&
orbNow.periapsis < 110_000
) {
targetPitch = Math.max(-16, Math.min(6, -radialVelNow * 0.035));
}
const steerRate =
computerStatus === "degraded" ? 0.9 : hasTier3Guidance ? 2.4 : 1.8;
pitchDeg += (targetPitch - pitchDeg) * Math.min(1, dt * steerRate);
if (computerStatus === "degraded" || computerStatus === "overloaded") {
const overFrac = Math.min(1.2, (cpuLoadPct - 100) / 30);
pitchDeg += Math.sin(t * 5.2) * (1.2 + overFrac * 2.2) * dt * 4;
}
}
if (
computerStatus === "degraded" &&
activeStage?.enginePart.propellantType !== "solid"
) {
throttle = Math.max(0.5, throttle * (1 - Math.sin(t * 7.1) * 0.08));
}
const pitchRad = (pitchDeg * Math.PI) / 180;
const dirX = eastX * Math.cos(pitchRad) + upX * Math.sin(pitchRad);
const dirY = eastY * Math.cos(pitchRad) + upY * Math.sin(pitchRad);
if (thrusting) {
fx += thrust * dirX;
fy += thrust * dirY;
}
const nonGravAccel = Math.hypot(
(fx + mass * gMag * upX) / mass,
(fy + mass * gMag * upY) / mass,
);
const gLoad = nonGravAccel / G0;
if (gLoad > peakGLoad) peakGLoad = gLoad;
if (gLoad > maxG * 1.15 && alt > 5000) {
failure = "g_load_exceeded";
failureDetail = `Peak acceleration ${gLoad.toFixed(1)} G exceeded payload/crew structural limit (${maxG.toFixed(1)} G).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
const bayTempK =
290 +
heatFluxWcm2 *
(stageIndex === 0 ? 1.8 : 3.2) *
(hasCryoMli ? 0.5 : 1.0) *
(fairingJettisoned ? 1.35 : 0.7);
if (gLoad > compMaxG * 1.08 && alt > 3000) {
failure = "computer_damaged";
failureDetail = `Peak acceleration ${gLoad.toFixed(1)} G damaged ${comp.name} avionics (limit ${compMaxG.toFixed(1)} G).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
if (bayTempK > compMaxTemp * 1.08) {
failure = "computer_damaged";
failureDetail = `Avionics bay temperature ${Math.round(bayTempK)} K exceeded ${comp.name} thermal limit (${compMaxTemp} K).`;
events.push({ t, label: failureDetail, kind: "err" });
break;
}
vx += (fx / mass) * dt;
vy += (fy / mass) * dt;
rx += vx * dt;
ry += vy * dt;
t += dt;
const remStageProp = activeStage
? stageDropProp[stageIndex] + stageCoreProp[stageIndex]
: 0;
if (
activeStage &&
remStageProp <= 0 &&
stageMdotVac[stageIndex] > 0 &&
separationTimer <= 0
) {
lastStageSepTime = t;
if (stageIndex < nStages - 1) {
events.push({
t,
label: `MECO / Stage ${stageIndex + 1} separation`,
kind: "info",
});
const remDropDryAtSep = stageDropJettisoned[stageIndex]
? stageDropDry[stageIndex]
: 0;
jettisonPending = Math.max(1, activeStage.dryMass - remDropDryAtSep);
separationTimer = 1.5;
stageIndex++;
} else {
events.push({ t, label: "SECO / Final stage burnout", kind: "info" });
stageIndex = nStages;
}
}
if (alt < -50) {
failure = "propellant_depleted";
failureDetail =
"Vehicle impacted Earth surface prior to orbit insertion.";
break;
}
const orb = orbitalElements(rx, ry, vx, vy);
const radialVel = vx * upX + vy * upY;
if (
mecoCoastToApogee &&
radialVel <= 0 &&
alt >= 95_000 &&
orb.apoapsis >= 155_000
) {
events.push({
t,
label: `Apogee arrived (${Math.round(alt / 1000)} km) — initiating circularization burn`,
kind: "info",
});
break;
}
if (orb.apoapsis >= targetApM && alt >= 115000 && orb.periapsis >= 90000) {
events.push({
t,
label: `Orbit insertion achieved (${Math.round(orb.apoapsis / 1000)}×${Math.round(orb.periapsis / 1000)} km)`,
kind: "info",
});
break;
}
const anyPropLeft =
stageIndex < nStages &&
stageDropProp[stageIndex] + stageCoreProp[stageIndex] > 0;
if (
!thrusting &&
!mecoCoastToApogee &&
separationTimer <= 0 &&
(!anyPropLeft || isXenonInAtmo)
) {
if (
orb.apoapsis >= targetApM &&
alt >= 100000 &&
radialVel >= -50 &&
!isXenonInAtmo
) {
break;
}
if (radialVel <= 0 && alt > 20000) {
if (orb.apoapsis >= 165000 && orb.periapsis >= 80000 && !isXenonInAtmo)
break;
failure = "propellant_depleted";
failureDetail = isXenonInAtmo
? `Ion thruster suborbital stall at ${Math.round(alt / 1000)} km (< 110 km ceiling) — chemical lower stages fell short of orbit.`
: `Suborbital burnout: apoapsis ${Math.round(Math.max(0, orb.apoapsis) / 1000)} km / periapsis ${Math.round(orb.periapsis / 1000)} km short of orbit.`;
break;
}
}
const groundStation = computeGroundStation(alt, downrange, groundTier);
const plasmaDip =
heatFluxWcm2 > 12
? Math.min(32, Math.round((heatFluxWcm2 - 12) * 0.9))
: 0;
const instSignalPct = Math.max(
8,
Math.min(
100,
baseSignalPct -
plasmaDip +
(groundStation === "PAD-39A OPTICAL/S-BAND" ? 4 : 0),
),
);
if (instSignalPct < minSignalHealthPct) minSignalHealthPct = instSignalPct;
sigSum += instSignalPct;
sigCount += 1;
if (lastStation !== groundStation) {
lastStation = groundStation;
events.push({
t,
label: `[MCC-CAPCOM] Link handoff → ${groundStation} (Signal ${instSignalPct}%)`,
kind: instSignalPct < 55 ? "warn" : "info",
});
}
if (t >= nextSample) {
nextSample += sampleEvery;
telemetry.push({
t,
altitude: Math.max(0, alt),
downrange: Math.max(0, downrange),
velocity: speed,
vx,
vy,
mass,
dynamicPressure: q,
gLoad,
heatFluxWcm2,
throttle,
stage: Math.min(stageIndex + 1, nStages),
thrusting,
fairingJettisoned,
pitchDeg,
mach: Number(mach.toFixed(2)),
cd: Number(cd.toFixed(3)),
dragForceN: Math.round(dragMag),
flightPathDeg: Number(flightPathDeg.toFixed(1)),
aoaDeg: Number(aoaDeg.toFixed(1)),
signalHealthPct: instSignalPct,
powerBalanceWatts: busPowerBalanceW,
groundStation,
cpuLoadPct: Number(cpuLoadPct.toFixed(1)),
seuCount: avState.totalSeuCount,
radFluxMsvHr: Number(radFluxMsvHr.toFixed(2)),
computerStatus,
});
}
}
return finalizeAscentSimulation({
rx,
ry,
vx,
vy,
t,
vRot,
stageIndex,
nStages,
assembly,
design,
fp,
fairingJettisoned,
fairingMass,
fairingSepAltKm,
stageDropProp,
stageCoreProp,
stageDropDry,
stageDropJettisoned,
dropTankJettisons,
mecoCoastToApogee,
failure,
failureDetail,
options,
diffProfile,
isCrewedMission,
peakGLoad,
maxQ,
maxQStage,
peakHeatFluxWcm2,
partRiskPct,
minSignalHealthPct,
sigCount,
sigSum,
baseSignalPct,
bus,
peakCpuLoadPct: avState.peakCpuLoadPct,
totalSeuCount: avState.totalSeuCount,
peakRadFluxMsvHr: avState.peakRadFluxMsvHr,
telemetry,
events,
});
}

View file

@ -0,0 +1,232 @@
// Evaluate in-flight radiation flux, SEU bit-flips, flight computer CPU load, overload lockup, and micrometeoroid hazards.
import type {
AssembledStage,
Part,
PreLaunchHazardEvent,
RocketAssembly,
RocketDesign,
SimFailure,
SpaceWeather,
TelemetrySample,
} from "../types.js";
import type { AscentOptions } from "./environment.js";
export interface AvionicsStepState {
t: number;
dt: number;
altKm: number;
q: number;
stageIndex: number;
nStages: number;
activeStage: AssembledStage | null;
assembly: RocketAssembly;
design: RocketDesign;
comp: Part;
compCapacity: number;
compRadHard: number;
compScrubRate: number;
hasCryoMli: boolean;
fairingJettisoned: boolean;
weather: SpaceWeather;
activeHazards: PreLaunchHazardEvent[];
options: AscentOptions;
lastStageSepTime: number;
activeSeus: number;
totalSeuCount: number;
peakCpuLoadPct: number;
peakRadFluxMsvHr: number;
overloadTimer: number;
softOverloadWarned: boolean;
enteredRadHazard: boolean;
meteoriteRolledInBand: boolean;
hasShearHazard: boolean;
events: Array<{ t: number; label: string; kind: "info" | "warn" | "err" }>;
}
export interface AvionicsStepResult {
radFluxMsvHr: number;
cpuLoadPct: number;
computerStatus: TelemetrySample["computerStatus"];
failure: SimFailure | null;
failureDetail: string;
}
export function stepAvionicsAndHazards(
s: AvionicsStepState,
): AvionicsStepResult {
const {
t,
dt,
altKm,
q,
stageIndex,
nStages,
activeStage,
assembly,
design,
comp,
compCapacity,
compRadHard,
compScrubRate,
hasCryoMli,
fairingJettisoned,
weather,
activeHazards,
options,
lastStageSepTime,
hasShearHazard,
events,
} = s;
const fp = design.flightParams;
let failure: SimFailure | null = null;
let failureDetail = "";
const incRadFactor =
1 + Math.max(0, (fp.targetInclinationDeg - 30) / 70) * 0.45;
let radFluxMsvHr =
(altKm > 140 ? Math.min(42, (altKm - 140) * 0.085) : 0.06) * incRadFactor;
if (weather === "radiation-storm") radFluxMsvHr *= 2.8;
else if (weather === "solar-storm") radFluxMsvHr *= 1.85;
else if (weather === "solar-wind") radFluxMsvHr *= 1.25;
const radHazard = activeHazards.find(
(h) =>
h.kind === "stray-radiation" &&
altKm >= h.altMinKm &&
altKm <= h.altMaxKm,
);
if (radHazard) {
if (!s.enteredRadHazard) {
s.enteredRadHazard = true;
events.push({
t,
label: `Transiting ${radHazard.title} (${radHazard.altMinKm}–${radHazard.altMaxKm} km)`,
kind: "warn",
});
}
radFluxMsvHr = radFluxMsvHr * (radHazard.radFluxMultiplier ?? 3.6) + 18;
}
if (radFluxMsvHr > s.peakRadFluxMsvHr) s.peakRadFluxMsvHr = radFluxMsvHr;
const shieldAtten =
(compRadHard >= 4
? 0.03
: compRadHard === 3
? 0.14
: compRadHard === 2
? 0.45
: 1.0) *
(hasCryoMli ? 0.7 : 1.0) *
(!fairingJettisoned ? 0.85 : 1.0);
const seuRatePerSec = Math.max(
0,
(radFluxMsvHr - 2.0) * 0.0085 * shieldAtten,
);
if (options.rollAnomalies) {
if (Math.random() < seuRatePerSec * dt) {
s.activeSeus += 1;
s.totalSeuCount += 1;
if (s.totalSeuCount <= 3) {
events.push({
t,
label: `Radiation SEU bit-flip #${s.totalSeuCount} detected on ${comp.name} (${radFluxMsvHr.toFixed(1)} mSv/hr)`,
kind: "warn",
});
}
}
} else if (
radFluxMsvHr * shieldAtten > 14 &&
s.activeSeus < 2 &&
Math.floor(t) % 18 === 0 &&
t > 20
) {
s.activeSeus += 0.6 * dt * 10;
}
if (s.activeSeus > 0) {
s.activeSeus = Math.max(0, s.activeSeus - compScrubRate * dt);
}
const instCount = design.spacecraftConfig?.instrumentIds?.length ?? 0;
const dynQDemand = q > 15000 ? Math.min(24, ((q - 15000) / 35000) * 20) : 0;
const stagingDemand = t - lastStageSepTime < 4.5 ? 22 : 0;
const shearDemand = hasShearHazard ? 12 : 0;
const seuDemand = s.activeSeus * 16;
const liveDemand =
26 +
nStages * 14 +
(activeStage?.config.engineCount ?? 0) * 5.2 +
instCount * 7.5 +
(design.hasLaunchAbort ? 6 : 0) +
dynQDemand +
stagingDemand +
shearDemand +
seuDemand;
const cpuLoadPct = (liveDemand / compCapacity) * 100;
if (cpuLoadPct > s.peakCpuLoadPct) s.peakCpuLoadPct = cpuLoadPct;
let computerStatus: TelemetrySample["computerStatus"] = "nominal";
if (cpuLoadPct > 130) {
computerStatus = "overloaded";
s.overloadTimer += dt;
if (s.overloadTimer >= 3.5) {
computerStatus = "failed";
failure =
s.totalSeuCount >= 2 || radHazard
? "radiation_seu_lockup"
: "computer_overload";
failureDetail =
failure === "radiation_seu_lockup"
? `Flight Computer ${comp.name} locked up under radiation SEU cascade (${s.totalSeuCount} SEUs, ${Math.round(cpuLoadPct)}% load) at ${Math.round(altKm)} km.`
: `Flight Computer ${comp.name} overloaded (${Math.round(cpuLoadPct)}% capacity) during Stage ${stageIndex + 1} flight — watchdog reset caused loss of TVC control.`;
events.push({ t, label: failureDetail, kind: "err" });
return {
radFluxMsvHr,
cpuLoadPct,
computerStatus,
failure,
failureDetail,
};
}
} else {
s.overloadTimer = Math.max(0, s.overloadTimer - dt * 0.5);
if (cpuLoadPct >= 100) {
computerStatus = "degraded";
if (!s.softOverloadWarned) {
s.softOverloadWarned = true;
events.push({
t,
label: `WARN: ${comp.name} soft overload (${Math.round(cpuLoadPct)}%) — TVC guidance jitter & throttle lag`,
kind: "warn",
});
}
}
}
const meteorHazard = activeHazards.find(
(h) =>
h.kind === "meteorite-stream" &&
altKm >= h.altMinKm &&
altKm <= h.altMaxKm,
);
if (meteorHazard && !s.meteoriteRolledInBand) {
s.meteoriteRolledInBand = true;
const shrouded = !fairingJettisoned;
const heavyShroud = assembly.fairingPart?.id === "fairing-wide";
const hasThermalShield =
!!activeStage?.config.hasHeatshield ||
activeStage?.material.id === "carbon-epoxy" ||
activeStage?.material.id === "stainless-304l";
const protMult =
(shrouded ? 0.35 : 1.0) *
(heavyShroud ? 0.35 : 1.0) *
(hasThermalShield ? 0.3 : 1.0);
const effStrikePct = (meteorHazard.impactRiskPct ?? 14) * protMult;
if (options.rollAnomalies && Math.random() * 100 < effStrikePct) {
failure = "meteorite_strike";
failureDetail = `Hypervelocity micrometeoroid impact in ${meteorHazard.title} band (${Math.round(altKm)} km) ruptured Stage ${stageIndex + 1}.`;
events.push({ t, label: failureDetail, kind: "err" });
return {
radFluxMsvHr,
cpuLoadPct,
computerStatus,
failure,
failureDetail,
};
}
}
return { radFluxMsvHr, cpuLoadPct, computerStatus, failure, failureDetail };
}

3
src/shared/ascent_sim.ts Normal file
View file

@ -0,0 +1,3 @@
// Export ascent trajectory simulator and options.
export { simulateAscent } from "./ascent/simulate.js";
export type { AscentOptions } from "./ascent/environment.js";

3
src/shared/compliance.ts Normal file
View file

@ -0,0 +1,3 @@
// Export compliance evaluation entry point and context interface.
export type { ComplianceEvalContext } from "./compliance/context.js";
export { evaluateCompliance } from "./compliance/evaluate.js";

View file

@ -0,0 +1,50 @@
// Shared types, evaluation context, and thermal protection helper for compliance rules.
import type {
DifficultyLevel,
MissionTemplate,
PreLaunchHazardEvent,
RocketAssembly,
RocketDesign,
RuleCategory,
RuleSeverity,
SpaceWeather,
} from "../types.js";
export interface ComplianceEvalContext {
mission?: Partial<MissionTemplate> | null;
difficulty?: DifficultyLevel | string | null;
effectiveRequiredDv?: number;
windowPenaltyDv?: number;
weather?: SpaceWeather;
activeHazards?: PreLaunchHazardEvent[];
unlockedTechs?: string[];
waiverCostMult?: number;
crewedSeats?: number;
eclssLevel?: number;
}
export interface RuleDef {
id: string;
code: string;
category: RuleCategory;
title: string;
description: string;
severity: RuleSeverity;
getSeverity?: (
ctx: ComplianceEvalContext,
assembly: RocketAssembly,
) => RuleSeverity;
waiverCost: number;
riskPenaltyPct: number;
check: (
design: RocketDesign,
assembly: RocketAssembly,
ctx: ComplianceEvalContext,
) => { passed: boolean; detail: string; stageIndex?: number | null };
}
export function hasHighThermalProtection(assembly: RocketAssembly): boolean {
return assembly.stages.some(
(s) => s.config.hasHeatshield || s.material.maxTempK >= 1000,
);
}

View file

@ -0,0 +1,325 @@
// Human-rating, orbital insertion profile, avionics hardening, and environmental hazard compliance rules.
import type { RuleDef } from "./context.js";
export const CREW_ORBITAL_RULES: RuleDef[] = [
{
id: "crew-capsule",
code: "CREW-01",
category: "crew",
title: "Human-Rated Crew Spacecraft",
description:
"Crewed contracts require ESAS Crew Module, Apollo LM, or Gateway Core.",
severity: "mandatory",
waiverCost: 0,
riskPenaltyPct: 0,
check: (_d, a, ctx) => {
if (!ctx.mission?.crewed)
return { passed: true, detail: "Uncrewed mission" };
const ok = !!a.payloadPart?.crewedCapable;
return {
passed: ok,
detail: ok
? `${a.payloadPart?.name} human-rated`
: "Install a crew-capable capsule",
};
},
},
{
id: "crew-roster",
code: "CREW-02",
category: "crew",
title: "Flight Crew & ECLSS Life Support",
description:
"Crewed flights require ≥ 1 astronaut and active ECLSS life support.",
severity: "mandatory",
waiverCost: 0,
riskPenaltyPct: 0,
check: (_d, _a, ctx) => {
if (!ctx.mission?.crewed)
return { passed: true, detail: "Uncrewed mission" };
const seats = ctx.crewedSeats ?? 0;
const eclss = ctx.eclssLevel ?? 0;
const ok = seats >= 1 && eclss >= 1;
return {
passed: ok,
detail: ok
? `${seats} crew · ECLSS Lv.${eclss}`
: "Configure crew & ECLSS in Parameter Config",
};
},
},
{
id: "crew-las",
code: "CREW-03",
category: "crew",
title: "Launch Abort System (LAS)",
description:
"Human-rated rockets require an active solid puller escape tower.",
severity: "waiverable",
waiverCost: 3_500_000,
riskPenaltyPct: 12,
check: (d, _a, ctx) => {
if (!ctx.mission?.crewed)
return { passed: true, detail: "Uncrewed mission" };
return {
passed: !!d.hasLaunchAbort,
detail: d.hasLaunchAbort
? "LAS Escape Tower armed"
: "No Launch Abort System equipped",
};
},
},
{
id: "crew-no-srb-human",
code: "CREW-04",
category: "crew",
title: "Throttleable Liquid First Stage",
description:
"Human-rated architectures avoid unthrottleable solid core boosters.",
severity: "waiverable",
waiverCost: 2_400_000,
riskPenaltyPct: 7,
check: (_d, a, ctx) => {
if (!ctx.mission?.crewed)
return { passed: true, detail: "Uncrewed mission" };
const solidCore = a.stages[0]?.enginePart.propellantType === "solid";
return {
passed: !solidCore,
detail: solidCore
? "Solid first stage lacks shutdown capability"
: "Liquid throttleable booster",
};
},
},
{
id: "orb-restartable",
code: "ORB-01",
category: "orbital",
title: "Restartable Upper Stage",
description:
"GEO, Lunar, and Deep Space injections require multi-burn restartable upper engines.",
severity: "waiverable",
waiverCost: 2_000_000,
riskPenaltyPct: 9,
check: (_d, a, ctx) => {
if (!ctx.mission?.advanced)
return { passed: true, detail: "Single-burn LEO insertion" };
const upper = a.stages[a.stages.length - 1];
return {
passed: !!upper?.enginePart.restartable,
detail: upper?.enginePart.restartable
? `${upper.enginePart.name} restartable`
: "Upper engine cannot restart for transfer burn",
};
},
},
{
id: "orb-dv-reserve",
code: "ORB-02",
category: "orbital",
title: "Propellant Flight Margin (≥ 4%)",
description:
"Keep at least 4% Δv reserve above nominal requirement for dispersion.",
severity: "waiverable",
waiverCost: 1_200_000,
riskPenaltyPct: 6,
check: (_d, a, ctx) => {
const req = ctx.effectiveRequiredDv ?? ctx.mission?.requiredDv ?? 0;
if (req <= 0) return { passed: true, detail: "No margin target" };
const pct = ((a.totalDv - req) / req) * 100;
return {
passed: pct >= 4,
detail: `Reserve ${pct.toFixed(1)}% (target ≥ 4.0%)`,
};
},
},
{
id: "orb-inclination",
code: "ORB-03",
category: "orbital",
title: "Target Inclination Alignment",
description:
"Launch azimuth inclination should match contract target orbit within ±5°.",
severity: "waiverable",
waiverCost: 1_400_000,
riskPenaltyPct: 5,
check: (d, _a, ctx) => {
const targetInc = ctx.mission?.targetOrbit?.inclinationDeg;
if (targetInc == null)
return { passed: true, detail: "Free inclination" };
const diff = Math.abs(d.flightParams.targetInclinationDeg - targetInc);
return {
passed: diff <= 5,
detail: `Set ${d.flightParams.targetInclinationDeg.toFixed(1)}° vs target ${targetInc.toFixed(1)}°`,
};
},
},
{
id: "orb-window",
code: "ORB-04",
category: "orbital",
title: "Synodic Launch Window Penalty",
description: "Launching off-window incurs Δv penalties above 200 m/s.",
severity: "waiverable",
waiverCost: 1_600_000,
riskPenaltyPct: 4,
check: (_d, _a, ctx) => {
const pen = ctx.windowPenaltyDv ?? 0;
return {
passed: pen <= 200,
detail:
pen <= 200
? `Window penalty +${pen} m/s`
: `Severe off-window penalty (+${pen} m/s)`,
};
},
},
{
id: "avn-computer-installed",
code: "AVN-01",
category: "payload",
title: "Flight Computer Hardware Installed",
description:
"Launch vehicle requires an active Flight Computer part to run guidance, TVC gimbal, and staging sequencers.",
severity: "mandatory",
waiverCost: 0,
riskPenaltyPct: 0,
check: (d, a) => {
const proOk =
d.designTier !== "pro" ||
(d.proParts ?? []).some((p) => p.role === "computer");
const ok = !!a.computerPart && proOk;
return {
passed: ok,
detail: ok
? `${a.computerPart!.name} (${a.computerPart!.computeCapacityIps ?? 140} IPS, Rad-Lv.${a.computerPart!.radHardeningLevel ?? 1})`
: "No Flight Computer installed — add one in Avionics Slot / Pro 3D parts",
};
},
},
{
id: "avn-compute-margin",
code: "AVN-02",
category: "payload",
title: "Flight Computer Compute Headroom",
description:
"Peak guidance & TVC transient compute load must stay within computer capacity to avoid guidance jitter or watchdog reset.",
severity: "waiverable",
getSeverity: (_ctx, assembly) =>
!assembly.computerPart || (assembly.peakComputeLoadEstPct ?? 0) > 130
? "mandatory"
: "waiverable",
waiverCost: 1_900_000,
riskPenaltyPct: 11,
check: (_d, a) => {
if (!a.computerPart)
return { passed: false, detail: "No flight computer installed" };
const peak = a.peakComputeLoadEstPct ?? 0;
return {
passed: peak <= 98,
detail: `Base ${a.computeLoadBasePct ?? 0}% / Peak ${peak}% of ${a.computerPart.computeCapacityIps ?? 140} IPS capacity`,
};
},
},
{
id: "avn-rad-hardening",
code: "AVN-03",
category: "thermal",
title: "Avionics Radiation & Deep-Space Hardening",
description:
"Radiation storms, deep-space orbits, or active stray radiation events require Rad-Hard Level ≥ 3 computer or Cryo-MLI shielding.",
severity: "waiverable",
waiverCost: 2_300_000,
riskPenaltyPct: 10,
check: (_d, a, ctx) => {
const target = ctx.mission?.target ?? "leo";
const deep = !["vleo", "leo", "sso"].includes(target);
const storm =
ctx.weather === "radiation-storm" || ctx.weather === "solar-storm";
const radHazard = (ctx.activeHazards ?? []).some(
(h) => h.kind === "stray-radiation",
);
if (!deep && !storm && !radHazard) {
return {
passed: true,
detail: `Rad-Lv.${a.computerPart?.radHardeningLevel ?? 1} nominal for LEO`,
};
}
const radLvl = a.computerPart?.radHardeningLevel ?? 1;
const hasMli = a.stages.some(
(s) => s.structurePart.id === "struct-cryo-frame",
);
const ok = radLvl >= 3 || (radLvl >= 2 && hasMli);
return {
passed: ok,
detail: ok
? `Rad-Lv.${radLvl}${hasMli ? " + Cryo-MLI" : ""} protected`
: `Rad-Lv.${radLvl} insufficient for ${radHazard ? "Stray Radiation" : storm ? ctx.weather : target.toUpperCase()} (need Rad-Lv. ≥ 3)`,
};
},
},
{
id: "env-stray-radiation",
code: "ENV-01",
category: "thermal",
title: "Corridor Stray Radiation Countermeasure",
description:
"Active Stray Radiation belt hazard requires Rad-Hard ≥ 3 Flight Computer or Tier-2/3 ECC fault scrubbing.",
severity: "waiverable",
waiverCost: 2_200_000,
riskPenaltyPct: 12,
check: (_d, a, ctx) => {
const haz = (ctx.activeHazards ?? []).find(
(h) => h.kind === "stray-radiation",
);
if (!haz)
return { passed: true, detail: "No active stray radiation hazard" };
const radLvl = a.computerPart?.radHardeningLevel ?? 1;
const scrub = a.computerPart?.faultScrubRate ?? 0;
const tier2 = (ctx.unlockedTechs ?? []).includes(
"avionics-diagnostics-2",
);
const ok = radLvl >= 3 || (scrub >= 0.35 && tier2);
return {
passed: ok,
detail: ok
? `Countered ${haz.title} (Rad-Lv.${radLvl}${tier2 ? " + ECC" : ""})`
: `Exposed in ${haz.altMinKm}–${haz.altMaxKm} km band (need Rad-Lv.3 or Tier-2 ECC)`,
};
},
},
{
id: "env-meteorite-stream",
code: "ENV-02",
category: "structures",
title: "Meteorite Stream Whipple / Shroud Protection",
description:
"Active Meteoroid stream hazard requires heavy/composite fairing, PICA heatshield, or delayed fairing separation (≥ 115 km).",
severity: "waiverable",
waiverCost: 2_500_000,
riskPenaltyPct: 14,
check: (d, a, ctx) => {
const haz = (ctx.activeHazards ?? []).find(
(h) => h.kind === "meteorite-stream",
);
if (!haz) return { passed: true, detail: "No active meteorite stream" };
const hasHeavyShroud = a.fairingPart?.id === "fairing-wide";
const hasShield = a.stages.some(
(s) =>
s.config.hasHeatshield ||
s.material.id === "carbon-epoxy" ||
s.material.id === "stainless-304l",
);
const delayedSep =
d.flightParams.fairingSepAltKm >=
Math.min(140, Math.max(115, haz.altMinKm + 20));
const ok = (hasHeavyShroud || hasShield) && delayedSep;
return {
passed: ok,
detail: ok
? `Whipple/shroud protection active through ${haz.altMinKm}–${haz.altMaxKm} km`
: `Unmitigated strike risk (${haz.impactRiskPct ?? 12}%) in ${haz.altMinKm}–${haz.altMaxKm} km — add PICA/Composite shield + sep ≥ 115 km`,
};
},
},
];

Some files were not shown because too many files have changed in this diff Show more