Add a built-in wiki.

This commit is contained in:
tyuXX 2026-11-15 20:19:41 +03:00
parent 358a8f68fd
commit 567ac1a26d
28 changed files with 4030 additions and 118 deletions

View file

@ -112,6 +112,16 @@
.notif-drawer {
width: min(370px, calc(100vw - 32px)) !important;
}
.wiki-layout {
grid-template-columns: 1fr;
grid-template-rows: auto 1fr;
}
.wiki-sidebar {
max-height: 210px;
border-right: none;
border-bottom: 1px solid var(--border);
padding-bottom: 14px;
}
}
.builder-summary-bar {
@ -270,3 +280,55 @@
color: var(--brand-blue);
background: var(--bg-elevated);
}
.wiki-drawer-overlay {
z-index: 190;
padding: 18px;
}
.wiki-drawer-panel {
width: min(1160px, 100%);
height: min(88vh, 880px);
max-height: none;
padding: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
#walkthrough-coach-root {
position: fixed;
top: 62px;
left: calc(50% - var(--right-sidebar-offset, 0px) / 2);
transform: translateX(-50%);
z-index: 160;
max-width: min(470px, calc(100vw - var(--right-sidebar-offset, 0px) - 32px));
pointer-events: none;
}
#walkthrough-coach-root > * {
pointer-events: auto;
}
.walkthrough-card {
padding: 12px 14px;
border-color: var(--sim-accent);
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.55);
}
.walkthrough-pill {
padding: 6px 10px;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
border-color: var(--sim-accent);
}
.walkthrough-title {
font-family: var(--mono);
font-size: 12px;
font-weight: 700;
color: var(--text);
margin-bottom: 3px;
}
.walkthrough-hint {
font-size: 11px;
line-height: 1.45;
color: var(--text-dim);
}

View file

@ -218,3 +218,76 @@
.grade { font-size: 68px; font-weight: 800; font-family: var(--mono); line-height: 1; }
.grade.s { color: var(--brand-blue); } .grade.a { color: var(--green); }
.grade.b { color: var(--amber); } .grade.c { color: var(--red); } .grade.f { color: var(--red); }
.wiki-page { display: flex; flex-direction: column; height: 100%; overflow: hidden; background: var(--bg-deep); }
.wiki-topbar {
padding: 12px 20px; border-bottom: 1px solid var(--border); background: var(--bg-panel-solid);
display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; flex-shrink: 0;
}
.wiki-topbar-controls { flex-wrap: wrap; align-items: center; }
.wiki-search-input { width: clamp(210px, 24vw, 300px); min-width: 180px; }
.wiki-layout {
display: grid; grid-template-columns: 270px 1fr; flex: 1; min-height: 0; overflow: hidden;
}
.wiki-sidebar {
border-right: 1px solid var(--border); background: var(--bg-panel-solid);
padding: 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding-bottom: 64px;
}
.wiki-nav-group { display: flex; flex-direction: column; gap: 4px; }
.wiki-nav-cat {
font-family: var(--mono); font-size: 9px; font-weight: 700; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--text-faint); padding: 4px 6px;
}
.wiki-nav-item {
display: flex; align-items: center; justify-content: space-between; gap: 6px; width: 100%;
padding: 8px 10px; background: transparent; border: 1px solid transparent; clip-path: var(--chamfer-sm);
color: var(--text-dim); font-family: var(--mono); font-size: 11px; text-align: left; cursor: pointer;
transition: background-color 0.14s, border-color 0.14s, color 0.14s;
}
.wiki-nav-item:hover { background: var(--bg-elevated); color: var(--text); border-color: var(--border); }
.wiki-nav-item.active { background: var(--sim-glow); color: var(--sim-accent); border-color: var(--sim-accent); }
.wiki-search-hit {
display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 8px 10px;
background: var(--bg-deep); border: 1px solid var(--border); clip-path: var(--chamfer-sm);
color: var(--text); text-align: left; cursor: pointer;
}
.wiki-search-hit:hover { border-color: var(--sim-accent); background: var(--bg-elevated); }
.wiki-main {
overflow-y: auto; padding: 22px 26px 86px; display: flex; flex-direction: column; gap: 16px;
}
.wiki-main > * { max-width: 980px; }
.wiki-article-header h2 { font-size: 20px; color: var(--text); }
.wiki-callout {
display: flex; align-items: flex-start; gap: 10px; padding: 11px 14px;
background: rgba(52, 211, 153, 0.08); border: 1px solid rgba(52, 211, 153, 0.35);
clip-path: var(--chamfer-sm); color: var(--text);
}
.wiki-section { padding: 16px 18px; display: flex; flex-direction: column; gap: 10px; }
.wiki-prose { font-size: 13px; line-height: 1.62; color: var(--text-dim); }
.wiki-bullets {
padding-left: 18px; display: flex; flex-direction: column; gap: 6px;
font-size: 12px; line-height: 1.55; color: var(--text);
}
.wiki-formula {
padding: 8px 12px; background: var(--bg-deep); border: 1px solid var(--border-bright);
clip-path: var(--chamfer-sm); font-family: var(--mono); font-size: 12px; color: var(--brand-blue);
}
.wiki-lab-card { padding: 16px 18px; }
.wiki-lab-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; }
.wiki-checklist-item {
padding: 10px 12px; background: var(--bg-deep); border: 1px solid var(--border);
clip-path: var(--chamfer-sm); transition: border-color 0.15s;
}
.wiki-checklist-item.done { border-color: rgba(52, 211, 153, 0.45); }
.wiki-glossary-card { padding: 12px 14px; display: flex; flex-direction: column; gap: 4px; }
.wiki-glossary-card.highlighted { border-color: var(--sim-accent); box-shadow: 0 0 18px var(--sim-glow); }
.wiki-refs-section { margin-top: 4px; }
.wiki-ref-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
.wiki-ref-card {
display: block; text-decoration: none; color: inherit; padding: 12px 14px;
background: var(--bg-panel-solid); border: 1px solid var(--border); clip-path: var(--chamfer-sm);
transition: border-color 0.15s, background-color 0.15s;
}
.wiki-ref-card:hover { border-color: var(--brand-blue); background: var(--bg-elevated); }
.wiki-ext-link { text-decoration: none; }
.wiki-footer-nav { padding-top: 8px; border-top: 1px solid var(--border); }

View file

@ -113,7 +113,15 @@
:root.reduced-effects .launch-events,
:root.reduced-effects .comfort-btn,
:root.reduced-effects .notif-toggle-bar,
:root.reduced-effects .hud-tooltip {
:root.reduced-effects .hud-tooltip,
:root.reduced-effects .wiki-nav-item,
:root.reduced-effects .wiki-search-hit,
:root.reduced-effects .wiki-callout,
:root.reduced-effects .wiki-formula,
:root.reduced-effects .wiki-checklist-item,
:root.reduced-effects .wiki-ref-card,
:root.reduced-effects .walkthrough-card,
:root.reduced-effects .walkthrough-pill {
clip-path: none !important;
border-radius: 4px;
}
@ -168,6 +176,16 @@
.hud-tooltip[hidden] {
display: none;
}
.hud-tooltip.pinned {
pointer-events: auto;
}
.hud-tooltip-actions {
margin-top: 8px;
padding-top: 6px;
border-top: 1px solid var(--border);
display: flex;
justify-content: flex-end;
}
.hud-tooltip-cat {
font-family: var(--mono);
font-size: 9px;

View file

@ -10,8 +10,10 @@ import {
import {
applyThemeFromState,
type DebriefScreenParams,
getCurrentScreen,
type LaunchScreenParams,
state,
type WikiScreenParams,
} from "./state.js";
import {
getColorMode,
@ -35,7 +37,11 @@ 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 { renderWiki } from "./screens/wiki.js";
import { renderWorldMap } from "./screens/worldMap.js";
import { initWalkthroughController } from "./wiki/walkthrough.js";
import type { WikiArticleId } from "./wiki/wikiData.js";
import { openWikiDrawer } from "./wiki/wikiModal.js";
registerScreenRenderers({
mainMenu: (el) => renderMainMenu(el),
@ -48,6 +54,7 @@ registerScreenRenderers({
debrief: (el, p) => renderDebrief(el, p as DebriefScreenParams),
contracts: (el) => renderContracts(el),
worldMap: (el) => renderWorldMap(el),
wiki: (el, p) => renderWiki(el, p as WikiScreenParams),
});
function renderComfortToolbar(): void {
@ -122,6 +129,41 @@ async function boot(): Promise<void> {
window.addEventListener("sgywftp:theme-changed", renderComfortToolbar);
initNotificationDrawer();
initTooltipController();
initWalkthroughController();
window.addEventListener("sgywftp:open-wiki", (ev) => {
const detail =
(
ev as CustomEvent<{
articleId?: WikiArticleId;
glossaryKey?: string;
query?: string;
preferDrawer?: boolean;
}>
).detail ?? {};
const cur = getCurrentScreen();
const preserveScreens = new Set([
"builder",
"config",
"launch",
"debrief",
"contracts",
"worldMap",
]);
if (detail.preferDrawer || preserveScreens.has(cur)) {
openWikiDrawer({
articleId: detail.articleId,
glossaryKey: detail.glossaryKey,
query: detail.query,
});
} else {
navigate("wiki", {
articleId: detail.articleId,
glossaryKey: detail.glossaryKey,
query: detail.query,
returnTo: cur === "wiki" ? "dashboard" : cur,
});
}
});
const readyPromise = waitForStylesAndLoad();
try {
await loadCatalogs();

View file

@ -1,4 +1,6 @@
// Terminologic glossary, cus I forget what this shit means every 2 seconds pls don't ask me this, I not know rockeet siençe
import type { WikiArticleId } from "./wiki/wikiData.js";
export interface GlossaryEntry {
title: string;
summary: string;
@ -9,6 +11,9 @@ export interface GlossaryEntry {
| "Flight & Orbit"
| "Avionics & Bus"
| "Program & Compliance";
wikiArticleId?: WikiArticleId;
wikipediaTitle?: string;
wikipediaUrl?: string;
}
const TERMINOLOGY_GLOSSARY_RAW = {
@ -19,6 +24,9 @@ const TERMINOLOGY_GLOSSARY_RAW = {
formula:
"Δv = Isp · g0 · ln(m_wet / m_dry) (two-phase when jettisoning drop tanks)",
category: "Propulsion",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Delta-v",
wikipediaUrl: "https://en.wikipedia.org/wiki/Delta-v",
},
dv_margin: {
title: "Delta-v Margin",
@ -26,12 +34,18 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Tsiolkovsky rocket equation",
wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Delta-v",
wikipediaUrl: "https://en.wikipedia.org/wiki/Delta-v",
},
twr: {
title: "Thrust-to-Weight Ratio (TWR)",
@ -39,12 +53,18 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Thrust-to-weight ratio",
wikipediaUrl: "https://en.wikipedia.org/wiki/Thrust-to-weight_ratio",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Multistage rocket",
wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket",
},
isp: {
title: "Specific Impulse (Isp)",
@ -52,60 +72,91 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Specific impulse",
wikipediaUrl: "https://en.wikipedia.org/wiki/Specific_impulse",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "De Laval nozzle",
wikipediaUrl: "https://en.wikipedia.org/wiki/De_Laval_nozzle",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Gimbaled thrust",
wikipediaUrl: "https://en.wikipedia.org/wiki/Gimbaled_thrust",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Liquid-propellant rocket",
wikipediaUrl: "https://en.wikipedia.org/wiki/Liquid-propellant_rocket",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Propellant crossfeed",
wikipediaUrl: "https://en.wikipedia.org/wiki/Propellant_crossfeed",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Propellant crossfeed",
wikipediaUrl: "https://en.wikipedia.org/wiki/Propellant_crossfeed",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Tsiolkovsky rocket equation",
wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Rocket engine",
wikipediaUrl: "https://en.wikipedia.org/wiki/Rocket_engine",
},
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",
wikiArticleId: "propulsion-staging",
wikipediaTitle: "Tsiolkovsky rocket equation",
wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Center of pressure (fluid mechanics)",
wikipediaUrl:
"https://en.wikipedia.org/wiki/Center_of_pressure_(fluid_mechanics)",
},
stability_calibers: {
title: "Static Stability Margin (Calibers)",
@ -113,6 +164,9 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Center of mass",
wikipediaUrl: "https://en.wikipedia.org/wiki/Center_of_mass",
},
fineness: {
title: "Fineness Ratio (L / D)",
@ -120,6 +174,9 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Fineness ratio",
wikipediaUrl: "https://en.wikipedia.org/wiki/Fineness_ratio",
},
buckling: {
title: "Axial Buckling Ratio",
@ -127,6 +184,9 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Buckling",
wikipediaUrl: "https://en.wikipedia.org/wiki/Buckling",
},
max_q: {
title: "Max-Q (Maximum Dynamic Pressure)",
@ -134,252 +194,380 @@ const TERMINOLOGY_GLOSSARY_RAW = {
"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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Max Q",
wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Buckling",
wikipediaUrl: "https://en.wikipedia.org/wiki/Buckling",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Launch vehicle",
wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_vehicle",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Multistage rocket",
wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Grid fin",
wikipediaUrl: "https://en.wikipedia.org/wiki/Grid_fin",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Atmospheric entry",
wikipediaUrl: "https://en.wikipedia.org/wiki/Atmospheric_entry",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Payload fairing",
wikipediaUrl: "https://en.wikipedia.org/wiki/Payload_fairing",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Launch escape system",
wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_escape_system",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Apsis",
wikipediaUrl: "https://en.wikipedia.org/wiki/Apsis",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Apsis",
wikipediaUrl: "https://en.wikipedia.org/wiki/Apsis",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Orbital inclination",
wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_inclination",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Max Q",
wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Orbital spaceflight",
wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight",
},
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",
wikiArticleId: "structures-aero",
wikipediaTitle: "Spacecraft thermal control",
wikipediaUrl: "https://en.wikipedia.org/wiki/Spacecraft_thermal_control",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Gravity turn",
wikipediaUrl: "https://en.wikipedia.org/wiki/Gravity_turn",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Multistage rocket",
wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Low Earth orbit",
wikipediaUrl: "https://en.wikipedia.org/wiki/Low_Earth_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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Hohmann transfer orbit",
wikipediaUrl: "https://en.wikipedia.org/wiki/Hohmann_transfer_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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Orbital spaceflight",
wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Max Q",
wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Payload fairing",
wikipediaUrl: "https://en.wikipedia.org/wiki/Payload_fairing",
},
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",
wikiArticleId: "guidance-orbit",
wikipediaTitle: "Gravity turn",
wikipediaUrl: "https://en.wikipedia.org/wiki/Gravity_turn",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "General Mission Analysis Tool",
wikipediaUrl: "https://en.wikipedia.org/wiki/General_Mission_Analysis_Tool",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Radiation hardening",
wikipediaUrl: "https://en.wikipedia.org/wiki/Radiation_hardening",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Radiation hardening",
wikipediaUrl: "https://en.wikipedia.org/wiki/Radiation_hardening",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Single-event upset",
wikipediaUrl: "https://en.wikipedia.org/wiki/Single-event_upset",
},
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",
wikiArticleId: "compliance-qa",
wikipediaTitle: "Technology readiness level",
wikipediaUrl: "https://en.wikipedia.org/wiki/Technology_readiness_level",
},
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",
wikiArticleId: "compliance-qa",
wikipediaTitle: "Design review (U.S. government)",
wikipediaUrl:
"https://en.wikipedia.org/wiki/Design_review_(U.S._government)",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Satellite bus",
wikipediaUrl: "https://en.wikipedia.org/wiki/Satellite_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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Radioisotope thermoelectric generator",
wikipediaUrl:
"https://en.wikipedia.org/wiki/Radioisotope_thermoelectric_generator",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "NASA Deep Space Network",
wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "NASA Deep Space Network",
wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "Life-support system",
wikipediaUrl: "https://en.wikipedia.org/wiki/Life-support_system",
},
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",
wikiArticleId: "compliance-qa",
wikipediaTitle: "Range safety",
wikipediaUrl: "https://en.wikipedia.org/wiki/Range_safety",
},
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",
wikiArticleId: "compliance-qa",
wikipediaTitle: "Range safety",
wikipediaUrl: "https://en.wikipedia.org/wiki/Range_safety",
},
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",
wikiArticleId: "tech-tree-ref",
wikipediaTitle: "Technology readiness level",
wikipediaUrl: "https://en.wikipedia.org/wiki/Technology_readiness_level",
},
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",
wikiArticleId: "getting-started",
wikipediaTitle: "Spaceflight",
wikipediaUrl: "https://en.wikipedia.org/wiki/Spaceflight",
},
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",
wikiArticleId: "compliance-qa",
wikipediaTitle: "Launch vehicle",
wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_vehicle",
},
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",
wikiArticleId: "economy-world",
wikipediaTitle: "Launch window",
wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_window",
},
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",
wikiArticleId: "economy-world",
wikipediaTitle: "Space weather",
wikipediaUrl: "https://en.wikipedia.org/wiki/Space_weather",
},
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",
wikiArticleId: "economy-world",
wikipediaTitle: "Orbital spaceflight",
wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight",
},
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",
wikiArticleId: "bus-avionics-crew",
wikipediaTitle: "NASA Deep Space Network",
wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network",
},
} as const satisfies Record<string, GlossaryEntry>;

View file

@ -54,4 +54,7 @@ export function navigate(
if (typeof cleanup === "function") {
activeCleanup = cleanup;
}
window.dispatchEvent(
new CustomEvent("sgywftp:screen-changed", { detail: { screen } }),
);
}

View file

@ -463,63 +463,61 @@ export function renderDiagnosticsSection(ctx: BuilderContext): void {
},
headerTitle,
),
...ctx.latestCoach
.slice(0, 2)
.map((c) =>
...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: "11px",
marginTop: "4px",
paddingTop: "4px",
borderTop: "1px solid var(--border)",
fontSize: "10px",
color: "var(--green)",
marginTop: "2px",
},
},
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}`,
),
`Tip: ${c.actionHint}`,
),
),
),
),
);
}

View file

@ -25,6 +25,11 @@ import {
type DashboardSidebarDeps,
} from "./dashboard/sidebarCards.js";
import { openTechLabModal } from "./dashboard/techLabModal.js";
import {
dismissFirstRunTutorialOffer,
shouldShowFirstRunTutorialOffer,
startWalkthrough,
} from "../wiki/walkthrough.js";
export function renderDashboard(root: HTMLElement): () => void {
const agency = state.agency;
@ -160,6 +165,14 @@ export function renderDashboard(root: HTMLElement): () => void {
{ class: "mono dim", style: { fontSize: "11px" } },
state.world?.simDate ?? "Synchronizing ephemeris...",
),
h(
"button",
{
class: "btn xs",
onClick: () => navigate("wiki", { returnTo: "dashboard" }),
},
"Wiki & Tutorial",
),
h(
"button",
{ class: "btn xs ghost", onClick: () => navigate("mainMenu") },
@ -268,9 +281,68 @@ export function renderDashboard(root: HTMLElement): () => void {
const hazardPanel = createHazardPanel();
const lastSettlementCard = createLastSettlementCard(agency);
const navGrid = createNavGrid(deps);
const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(agency)
? h(
"div",
{
class: "panel",
style: { padding: "12px", borderColor: "var(--sim-accent)" },
},
h(
"div",
{ class: "col", style: { gap: "8px" } },
h(
"div",
{ class: "spread" },
h("h3", { class: "accent" }, "New Flight Director?"),
h("span", { class: "badge info" }, "TUTORIAL"),
),
h(
"p",
{ class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } },
"Open the Flight Wiki for interactive Δv, CG/CP & Gravity Turn labs, or launch the step-by-step Walkthrough.",
),
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"button",
{
class: "btn xs primary",
onClick: () => {
tutorialOfferBanner?.remove();
startWalkthrough(0);
},
},
"Start Walkthrough",
),
h(
"button",
{
class: "btn xs",
onClick: () => navigate("wiki", { returnTo: "dashboard" }),
},
"Open Wiki",
),
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
dismissFirstRunTutorialOffer();
tutorialOfferBanner?.remove();
},
},
"Dismiss",
),
),
),
)
: null;
if (terminatedBanner) sidebarEl.appendChild(terminatedBanner);
if (standdownBanner) sidebarEl.appendChild(standdownBanner);
if (bailoutBanner) sidebarEl.appendChild(bailoutBanner);
if (tutorialOfferBanner) sidebarEl.appendChild(tutorialOfferBanner);
sidebarEl.append(agencyStatsPanel, contractPanel);
if (hazardPanel) sidebarEl.appendChild(hazardPanel);
if (lastSettlementCard) sidebarEl.appendChild(lastSettlementCard);

View file

@ -509,6 +509,14 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement {
},
launchBtnLabel,
),
h(
"button",
{
class: "btn full-span ghost",
onClick: () => navigate("wiki", { returnTo: "dashboard" }),
},
"Flight Wiki & Interactive Tutorial",
),
);
return navGrid;
}

View file

@ -123,7 +123,8 @@ export function enterOrbitPhase(ctx: LaunchContext): void {
? new THREE.MeshBasicMaterial({ color: bodyColors[bodyId] })
: new THREE.MeshStandardMaterial({
map: bodyId === "earth" ? getEarthSurfaceTexture() : null,
color: bodyId === "earth" ? 0xffffff : (bodyColors[bodyId] ?? 0x4f9cf9),
color:
bodyId === "earth" ? 0xffffff : (bodyColors[bodyId] ?? 0x4f9cf9),
roughness: 0.72,
metalness: 0.08,
}),

View file

@ -331,6 +331,14 @@ export function renderMainMenu(root: HTMLElement): () => void {
)
: null,
h("button", { class: "btn", onClick: openSettingsModal }, "Settings"),
h(
"button",
{
class: "btn",
onClick: () => navigate("wiki", { returnTo: "mainMenu" }),
},
"Flight Wiki",
),
),
h(
"div",

View file

@ -0,0 +1,34 @@
// Wikipedia
import { navigate } from "../router.js";
import type { WikiScreenParams } from "../state.js";
import { h } from "../ui.js";
import { renderWikiWorkspace } from "../wiki/wikiWorkspace.js";
export function renderWiki(
root: HTMLElement,
params: WikiScreenParams = {},
): void {
const returnScreen =
params.returnTo && params.returnTo !== "wiki"
? params.returnTo
: "dashboard";
const backLabel =
returnScreen === "mainMenu"
? "← Main Menu"
: returnScreen === "contracts"
? "← Contracts"
: returnScreen === "worldMap"
? "← World Map"
: "← Dashboard";
const pageEl = h("div", { class: "screen wiki-page" });
renderWikiWorkspace(pageEl, {
initialArticleId: params.articleId,
initialGlossaryKey: params.glossaryKey,
initialQuery: params.query,
mode: "page",
backLabel,
onBack: () => navigate(returnScreen),
});
root.appendChild(pageEl);
}

View file

@ -133,9 +133,7 @@ function handleLiveEvent(ev: {
void refreshWorld();
if (isMine) void refreshMe();
} else if (ev.type === "agency.bankrupt") {
const reason = d.reason
? ` (${String(d.reason).replace(/_/g, " ")})`
: "";
const reason = d.reason ? ` (${String(d.reason).replace(/_/g, " ")})` : "";
const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy${reason}.`;
pushNotification(
msg,

View file

@ -1,4 +1,5 @@
// Client application state, screen route/parameter interfaces, contract lookup, and theme sync.
import type { WikiArticleId } from "./wiki/wikiData.js";
import { syncSimulationTheme } from "./theme.js";
import type {
ActiveMission,
@ -23,7 +24,8 @@ export type ScreenName =
| "launch"
| "debrief"
| "contracts"
| "worldMap";
| "worldMap"
| "wiki";
export interface ModelIndexEntry {
file: string;
@ -85,6 +87,13 @@ export interface DebriefScreenParams {
isSpectating?: boolean;
}
export interface WikiScreenParams {
articleId?: WikiArticleId;
glossaryKey?: string;
query?: string;
returnTo?: ScreenName;
}
export function currentContract(): ContractOffer | MissionTemplate | null {
if (!state.agency) return null;
if (state.agency.activeContract) return state.agency.activeContract;

View file

@ -144,7 +144,8 @@ function buildEarthSurface(): HTMLCanvasElement {
vg = lerp(vg, 112, rock * 0.7);
vb = lerp(vb, 104, rock * 0.7);
const snow =
(sstep(0.66, 0.74, elev) + sstep(0.8, 0.9, latN + (elev - 0.5) * 0.25)) *
(sstep(0.66, 0.74, elev) +
sstep(0.8, 0.9, latN + (elev - 0.5) * 0.25)) *
land;
const iceCap = sstep(0.86, 0.94, latN + (cont - 0.5) * 0.3) * land;
r = lerp(vr, 232, Math.min(1, snow * 0.9 + iceCap));
@ -241,9 +242,10 @@ function compressHighlights(
function upgradeTexture(tex: THREE.Texture, url: string, soften = false): void {
loader.load(url, (loaded) => {
tex.image = soften && loaded.image instanceof HTMLImageElement
? compressHighlights(loaded.image)
: loaded.image;
tex.image =
soften && loaded.image instanceof HTMLImageElement
? compressHighlights(loaded.image)
: loaded.image;
tex.needsUpdate = true;
});
}

View file

@ -15,6 +15,7 @@ export function hideTooltip(): void {
}
if (tooltipEl) {
tooltipEl.hidden = true;
tooltipEl.classList.remove("pinned");
}
}
@ -37,14 +38,46 @@ function showTooltipFor(anchor: HTMLElement): void {
if (!entry) return;
const tip = ensureTooltipEl();
clear(tip);
tip.classList.toggle("pinned", tooltipPinned);
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 + " -- Your favorite coach, ULTRACAT"),
h(
"div",
{ class: "hud-tooltip-body" },
entry.summary + " -- Your favorite coach, ULTRACAT",
),
);
if (entry.formula) {
tip.appendChild(h("div", { class: "hud-tooltip-formula" }, entry.formula));
}
if (tooltipPinned) {
tip.appendChild(
h(
"div",
{ class: "hud-tooltip-actions" },
h(
"button",
{
type: "button",
class: "btn xs primary",
onClick: () => {
hideTooltip();
window.dispatchEvent(
new CustomEvent("sgywftp:open-wiki", {
detail: {
articleId: entry.wikiArticleId ?? "glossary-index",
glossaryKey: key,
},
}),
);
},
},
"Open in Wiki →",
),
),
);
}
tip.hidden = false;
tip.style.left = "0px";
tip.style.top = "0px";

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,490 @@
// Cross-screen Guided Walkthrough coach bar and career milestone detector.
import { navigate } from "../router.js";
import {
currentContract,
getCurrentScreen,
type ScreenName,
state,
} from "../state.js";
import {
getDifficultyProfile,
TECH_TREE,
validateDesign,
} from "../../shared/physics.js";
import type { AgencyState } from "../../shared/types.js";
import { clear, h } from "../ui.js";
import type { WikiArticleId } from "./wikiData.js";
const STORAGE_KEY = "spacegaem_wiki_walkthrough_v1";
interface WalkthroughStorage {
active: boolean;
stepIndex: number;
collapsed: boolean;
dismissedOffer: boolean;
manualChecks: Record<string, boolean>;
}
export interface WalkthroughStepDef {
id: string;
title: string;
targetScreen: ScreenName;
targetScreenLabel: string;
wikiArticleId: WikiArticleId;
summary: string;
actionHint: (screen: ScreenName, agency: AgencyState | null) => string;
isComplete: (agency: AgencyState | null) => boolean;
}
function loadState(): WalkthroughStorage {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw) as Partial<WalkthroughStorage>;
return {
active: !!parsed.active,
stepIndex: Math.max(
0,
Math.min(WALKTHROUGH_STEPS.length - 1, Number(parsed.stepIndex) || 0),
),
collapsed: !!parsed.collapsed,
dismissedOffer: !!parsed.dismissedOffer,
manualChecks:
parsed.manualChecks && typeof parsed.manualChecks === "object"
? parsed.manualChecks
: {},
};
}
} catch {}
return {
active: false,
stepIndex: 0,
collapsed: false,
dismissedOffer: false,
manualChecks: {},
};
}
function saveState(st: WalkthroughStorage): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(st));
} catch {}
}
function evaluateAgencyValidation(agency: AgencyState | null) {
if (!agency?.rocketDesign?.stages?.length || !state.parts.length) return null;
try {
return validateDesign(agency.rocketDesign, state.parts, state.materials, {
mission: currentContract(),
simTime: state.world?.simTime ?? 0,
weather: state.world?.weather ?? "nominal",
activeHazards: state.world?.activeHazards ?? [],
unlockedTechs: agency.unlockedTechs ?? [],
difficulty: agency.difficulty,
crewedSeats: agency.crewConfig?.crewSize ?? 0,
eclssLevel: agency.crewConfig?.lifeSupport ?? 0,
});
} catch {
return null;
}
}
export const WALKTHROUGH_STEPS: WalkthroughStepDef[] = [
{
id: "contract",
title: "1. Sign an Active Mission Contract",
targetScreen: "contracts",
targetScreenLabel: "Contracts & Rank",
wikiArticleId: "getting-started",
summary:
"Every launch starts with a sponsor contract providing a 35% advance payout and defining payload mass, target orbit, and required Δv.",
actionHint: (screen, agency) => {
if (!agency)
return "Sign in or register an agency to accept a mission contract.";
if (currentContract()) {
return "Active contract signed! Advance to Step 2 or open Rocket Builder.";
}
return screen === "contracts"
? "Pick a Tier-1 Low Earth Orbit offer on the left and click 'Sign Contract'."
: "Click 'Go to Contracts & Rank' to browse and sign an inaugural Tier-1 contract.";
},
isComplete: () => !!currentContract(),
},
{
id: "propulsion",
title: "2. Design Rocket & Meet Δv / TWR",
targetScreen: "builder",
targetScreenLabel: "Rocket Builder",
wikiArticleId: "propulsion-staging",
summary:
"Stack stages, compatible propellant tanks, and engines so total Δv meets the mission requirement and Liftoff TWR ≥ 1.22.",
actionHint: (screen, agency) => {
const val = evaluateAgencyValidation(agency);
if (val && val.dvMargin >= 0 && val.twr >= 1.22) {
return "Propulsion budget & TWR look solid! Save your design and move to Step 3.";
}
if (screen === "builder") {
return "Check the top summary pills & Diagnostics bar: pair matching engines/tanks, add a 2nd stage or drop tanks for Δv, and click 'Save Design'.";
}
return "Open Rocket Builder to assemble stages and verify Δv margin and Liftoff TWR.";
},
isComplete: (agency) => {
const val = evaluateAgencyValidation(agency);
return !!val && val.dvMargin >= 0 && val.twr >= 1.05;
},
},
{
id: "compliance",
title: "3. Certify Compliance & Reach Flight-Ready",
targetScreen: "builder",
targetScreenLabel: "Rocket Builder",
wikiArticleId: "compliance-qa",
summary:
"Check CG/CP stability (add Grid Fins if < 0.40 calibers), ensure Fairing & Flight Computer fit, resolve NASA CML/TRL rules, and advance Maturity to FLIGHT-READY.",
actionHint: (screen, agency) => {
const val = evaluateAgencyValidation(agency);
const prof = getDifficultyProfile(agency?.difficulty);
const ready =
!!val?.valid &&
(agency?.rocketDesign?.maturity === "flight-ready" ||
prof.id === "sandbox");
if (ready) {
return "Vehicle is certified FLIGHT-READY! Save Design and proceed to Param Config.";
}
if (screen === "builder") {
return "Open the 'NASA CML / TRL' tab to clear blockers, toggle 'CG / CP' in the viewport, advance Maturity to FLIGHT-READY, and click 'Save Design'.";
}
return "Open Rocket Builder → 'NASA CML / TRL' tab to resolve blockers and advance Maturity.";
},
isComplete: (agency) => {
const val = evaluateAgencyValidation(agency);
const prof = getDifficultyProfile(agency?.difficulty);
return (
!!val?.valid &&
(agency?.rocketDesign?.maturity === "flight-ready" ||
prof.id === "sandbox")
);
},
},
{
id: "guidance",
title: "4. Tune Gravity Turn & Run Pre-Launch QA",
targetScreen: "config",
targetScreenLabel: "Param Config",
wikiArticleId: "guidance-orbit",
summary:
"Preview your 2D ascent trajectory, use 'Auto-Tune Flight Computer' if needed, verify Launch Window & Weather Hazards, and save your flight profile.",
actionHint: (screen) => {
if (screen === "config") {
return "Review the Ascent & Orbit preview. Try 'Auto-Tune Flight Computer', check Pre-Launch QA (Static Fire / Insurance), and click 'Save Profile' or 'Save & Proceed to Pad →'.";
}
return "Open 'Param Config' from the Dashboard (or Builder footer) to tune your Gravity Turn and save your launch profile.";
},
isComplete: (agency) =>
!!agency?.rocketDesign?.flightParams &&
(agency.missionsCompleted > 0 || agency.missionsFailed > 0),
},
{
id: "launch",
title: "5. Launch Mission & Review Debrief",
targetScreen: "dashboard",
targetScreenLabel: "Dashboard",
wikiArticleId: "guidance-orbit",
summary:
"Trigger 'Launch Mission' from the Dashboard (or Param Config), monitor staging/Max-Q/SECO in 3D, and study your After-Action Report.",
actionHint: (screen, agency) => {
if (
(agency?.missionsCompleted ?? 0) + (agency?.missionsFailed ?? 0) >
0
) {
return "First flight logged! Review your Debrief or proceed to Step 6.";
}
if (screen === "launch") {
return "Monitor Altitude, Dynamic Pressure (Max-Q), G-Load, and Flight Events through MECO/SECO.";
}
return "Head to Dashboard and click the highlighted 'Launch Mission' button (or launch from Param Config) when FLIGHT-READY.";
},
isComplete: (agency) =>
(agency?.missionsCompleted ?? 0) + (agency?.missionsFailed ?? 0) > 0,
},
{
id: "rd",
title: "6. Invest in R&D Tech Lab",
targetScreen: "dashboard",
targetScreenLabel: "Dashboard",
wikiArticleId: "tech-tree-ref",
summary:
"Spend earned Reputation (RP) and treasury cash in the R&D Tech Lab to unlock Hydrolox, Methalox, Composites, and Tier-2/3 Telemetry & GMAT.",
actionHint: () =>
"On Dashboard, open 'R&D Tech Lab' inside the Agency Telemetry panel to unlock new propulsion, alloys, or GMAT diagnostics.",
isComplete: (agency) => {
if (!agency) return false;
const prof = getDifficultyProfile(agency.difficulty);
if (prof.allTechUnlocked) return true;
return (
(agency.unlockedTechs ?? []).length > 1 ||
(agency.unlockedTechs ?? []).some(
(id) => id !== "starter" && TECH_TREE.some((t) => t.id === id),
)
);
},
},
];
let coachRootEl: HTMLElement | null = null;
let initialized = false;
export function getManualChecklistState(): Record<string, boolean> {
return { ...loadState().manualChecks };
}
export function setManualChecklistItem(stepId: string, checked: boolean): void {
const st = loadState();
st.manualChecks[stepId] = checked;
saveState(st);
}
export function resetWalkthroughProgress(): void {
const st = loadState();
st.manualChecks = {};
st.stepIndex = 0;
saveState(st);
syncWalkthroughOverlay(getCurrentScreen());
}
export function isWalkthroughActive(): boolean {
return loadState().active;
}
export function shouldShowFirstRunTutorialOffer(
agency: AgencyState | null,
): boolean {
if (!agency) return false;
const st = loadState();
if (st.active || st.dismissedOffer) return false;
return agency.missionsCompleted === 0 && agency.missionsFailed === 0;
}
export function dismissFirstRunTutorialOffer(): void {
const st = loadState();
st.dismissedOffer = true;
saveState(st);
}
export function startWalkthrough(stepIndex = 0): void {
const st = loadState();
st.active = true;
st.collapsed = false;
st.dismissedOffer = true;
st.stepIndex = Math.max(0, Math.min(WALKTHROUGH_STEPS.length - 1, stepIndex));
saveState(st);
syncWalkthroughOverlay(getCurrentScreen());
}
export function stopWalkthrough(): void {
const st = loadState();
st.active = false;
saveState(st);
syncWalkthroughOverlay(getCurrentScreen());
}
function requestOpenWikiArticle(articleId: WikiArticleId): void {
window.dispatchEvent(
new CustomEvent("sgywftp:open-wiki", {
detail: { articleId, preferDrawer: true },
}),
);
}
export function initWalkthroughController(): void {
if (initialized) return;
initialized = true;
coachRootEl = document.getElementById("walkthrough-coach-root");
if (!coachRootEl) {
coachRootEl = h("div", { id: "walkthrough-coach-root" });
document.body.appendChild(coachRootEl);
}
window.addEventListener("sgywftp:agency-sync", () => {
syncWalkthroughOverlay(getCurrentScreen());
});
window.addEventListener("sgywftp:screen-changed", (ev) => {
const screen = (ev as CustomEvent<{ screen?: ScreenName }>).detail?.screen;
syncWalkthroughOverlay(screen ?? getCurrentScreen());
});
syncWalkthroughOverlay(getCurrentScreen());
}
export function syncWalkthroughOverlay(screen: ScreenName): void {
if (!coachRootEl) return;
clear(coachRootEl);
const st = loadState();
if (
!st.active ||
screen === "mainMenu" ||
screen === "auth" ||
screen === "onboarding"
) {
return;
}
const idx = Math.max(0, Math.min(WALKTHROUGH_STEPS.length - 1, st.stepIndex));
const step = WALKTHROUGH_STEPS[idx];
const agency = state.agency;
const done = step.isComplete(agency) || !!st.manualChecks[step.id];
if (st.collapsed) {
coachRootEl.appendChild(
h(
"div",
{ class: "walkthrough-pill panel" },
h(
"span",
{ class: "badge info" },
`TUTORIAL ${idx + 1}/${WALKTHROUGH_STEPS.length}`,
),
h("span", { class: "mono", style: { fontSize: "11px" } }, step.title),
h(
"button",
{
class: "btn xs primary",
onClick: () => {
const next = loadState();
next.collapsed = false;
saveState(next);
syncWalkthroughOverlay(screen);
},
},
"Expand",
),
h(
"button",
{
class: "btn xs ghost",
onClick: () => stopWalkthrough(),
},
"Exit",
),
),
);
return;
}
const hintText = step.actionHint(screen, agency);
const needsScreenSwitch = screen !== step.targetScreen && screen !== "wiki";
coachRootEl.appendChild(
h(
"div",
{ class: "walkthrough-card panel" },
h(
"div",
{ class: "spread", style: { gap: "8px", marginBottom: "6px" } },
h(
"div",
{ class: "row", style: { gap: "6px" } },
h(
"span",
{ class: "badge info" },
`WALKTHROUGH ${idx + 1}/${WALKTHROUGH_STEPS.length}`,
),
done
? h("span", { class: "badge ok" }, "STEP READY ✓")
: h("span", { class: "badge warn" }, "IN PROGRESS"),
),
h(
"div",
{ class: "row", style: { gap: "4px" } },
h(
"button",
{
class: "btn xs ghost",
title: "Minimize walkthrough bar",
onClick: () => {
const next = loadState();
next.collapsed = true;
saveState(next);
syncWalkthroughOverlay(screen);
},
},
"—",
),
h(
"button",
{
class: "btn xs ghost",
title: "Close guided walkthrough",
onClick: () => stopWalkthrough(),
},
"✕",
),
),
),
h("div", { class: "walkthrough-title" }, step.title),
h("p", { class: "walkthrough-hint" }, hintText),
h(
"div",
{
class: "row",
style: { gap: "6px", marginTop: "8px", flexWrap: "wrap" },
},
idx > 0
? h(
"button",
{
class: "btn xs ghost",
onClick: () => {
const next = loadState();
next.stepIndex = Math.max(0, idx - 1);
saveState(next);
syncWalkthroughOverlay(screen);
},
},
"← Prev",
)
: null,
needsScreenSwitch
? h(
"button",
{
class: "btn xs primary",
onClick: () => navigate(step.targetScreen),
},
`Go to ${step.targetScreenLabel} →`,
)
: null,
h(
"button",
{
class: "btn xs",
onClick: () => requestOpenWikiArticle(step.wikiArticleId),
},
"Wiki Guide",
),
idx < WALKTHROUGH_STEPS.length - 1
? h(
"button",
{
class: `btn xs ${done ? "primary" : "ghost"}`,
onClick: () => {
const next = loadState();
next.stepIndex = Math.min(
WALKTHROUGH_STEPS.length - 1,
idx + 1,
);
saveState(next);
syncWalkthroughOverlay(screen);
},
},
"Next Step →",
)
: h(
"button",
{
class: "btn xs primary",
onClick: () => stopWalkthrough(),
},
"Finish Tutorial ✓",
),
),
),
);
}

687
src/client/wiki/wikiData.ts Normal file
View file

@ -0,0 +1,687 @@
// Wikipedia, but like, database
export type WikiArticleId =
| "getting-started"
| "propulsion-staging"
| "structures-aero"
| "guidance-orbit"
| "bus-avionics-crew"
| "compliance-qa"
| "economy-world"
| "glossary-index"
| "tech-tree-ref"
| "my-vehicle-inspector";
export type WikiCategory =
| "Tutorial & Career Loop"
| "Engineering & Physics"
| "Operations & Systems"
| "Live Reference Directories";
export type WikiLabKind =
| "checklist"
| "dv-staging"
| "stability-maxq"
| "gravity-turn"
| "compliance-directory"
| "glossary-directory"
| "tech-difficulty-directory"
| "vehicle-inspector";
export interface WikipediaRef {
title: string;
url: string;
summary: string;
}
export interface WikiSection {
heading: string;
paragraphs: string[];
bullets?: string[];
formula?: string;
}
export interface WikiArticle {
id: WikiArticleId;
title: string;
shortTitle: string;
category: WikiCategory;
summary: string;
coachTip: string;
relatedScreens: Array<{
screen: "dashboard" | "contracts" | "builder" | "config" | "worldMap";
label: string;
}>;
sections: WikiSection[];
labKind?: WikiLabKind;
wikipediaRefs: WikipediaRef[];
}
export const WIKI_CATEGORIES: WikiCategory[] = [
"Tutorial & Career Loop",
"Engineering & Physics",
"Operations & Systems",
"Live Reference Directories",
];
export const WIKI_ARTICLES: WikiArticle[] = [
{
id: "getting-started",
title: "Getting Started & Interactive Flight Tutorial",
shortTitle: "Interactive Tutorial & Career Loop",
category: "Tutorial & Career Loop",
summary:
"Learn the end-to-end agency loop from signing your first sponsor contract to building, certifying, configuring, launching, and upgrading via R&D.",
coachTip:
"Start with the interactive checklist below or hit 'Start Interactive Walkthrough' to keep a live step-by-step coach pinned while you jump across screens. -- ULTRACAT",
relatedScreens: [
{ screen: "contracts", label: "Contracts & Rank" },
{ screen: "builder", label: "Rocket Builder" },
{ screen: "config", label: "Param Config" },
],
labKind: "checklist",
sections: [
{
heading: "1. The 5-Step Mission Loop",
paragraphs: [
"Every orbital program in SGYWFTP follows a closed engineering-and-finance cycle. Signing a contract grants a 35% upfront advance, while the remaining payout (plus science, efficiency, and reusability bonuses) is settled only after orbital insertion.",
],
bullets: [
"1. Charter & Contract: Choose a space sponsor during onboarding or sign a mission in Contracts & Rank (Tier 1 LEO payloads first).",
"2. Rocket Builder: Stack propulsion stages, tanks, structures, fairings, flight computer, and spacecraft bus until Δv margin ≥ 0 and Liftoff TWR ≥ 1.22.",
"3. NASA CML/TRL Certification: Resolve or waive compliance blockers in the NASA CML / TRL tab and advance vehicle maturity from Concept → PDR → CDR → Flight-Ready.",
"4. Param Config & QA: Tune Gravity Turn parameters (or use Auto-Tune Flight Computer), inspect weather hazards & launch windows, and optionally buy Static Fire QA or Launch Insurance.",
"5. Launch & Debrief: Watch real-time 3D ascent & telemetry, then inspect your Mission After-Action Report and invest Reputation & Cash in the R&D Tech Lab.",
],
},
{
heading: "2. Difficulty Tiers, Bailouts & Stand-Downs",
paragraphs: [
"Your agency's difficulty tier (Sandbox, Explorer, Enthusiast, Engineer, Flight Director) sets starting treasury, orbital insertion corridor tolerances (±50% down to ±4%), hardware defect multipliers, bailout allowance, and whether Loss of Crew (LOC) revokes your operating license.",
"If a pad explosion damages Launch Complex 39A or a crewed anomaly triggers a Safety Board grounding, you can wait out the simulation timer or pay for Expedited Clearance on the Dashboard.",
],
},
],
wikipediaRefs: [
{
title: "Spaceflight",
url: "https://en.wikipedia.org/wiki/Spaceflight",
summary:
"Overview of astronautics, launch operations, orbital regimes, and spacecraft engineering.",
},
{
title: "Launch vehicle",
url: "https://en.wikipedia.org/wiki/Launch_vehicle",
summary:
"How multi-stage rockets deliver payloads from a planetary surface into Earth orbit or escape trajectories.",
},
{
title: "Orbital spaceflight",
url: "https://en.wikipedia.org/wiki/Orbital_spaceflight",
summary:
"Why reaching orbit requires achieving horizontal orbital velocity (~7.8 km/s in LEO), not just altitude.",
},
],
},
{
id: "propulsion-staging",
title: "Propulsion, Rocket Equation & Staging",
shortTitle: "Propulsion & Δv Staging Lab",
category: "Engineering & Physics",
summary:
"Master Tsiolkovsky's rocket equation, Specific Impulse (Isp), Thrust-to-Weight Ratio (TWR), propellant chemistries, and crossfeed drop tanks.",
coachTip:
"Adding more propellant to Stage 1 stops helping fast if Stage 2 is hauling heavy steel dead weight. Put high-Isp Hydrolox or Methalox Vacuum engines upstairs and drop empty tanks early! -- ULTRACAT",
relatedScreens: [{ screen: "builder", label: "Open Rocket Builder" }],
labKind: "dv-staging",
sections: [
{
heading: "1. Tsiolkovsky Rocket Equation & Staging",
paragraphs: [
"Delta-v (Δv) measures total velocity-change capability. Because propellant must accelerate both payload and remaining unburned propellant, Δv scales logarithmically with the wet-to-dry mass ratio. Dropping empty lower stages and disposable drop tanks dramatically shrinks dry mass mid-flight.",
],
formula: "Δv = Isp × g0 × ln(m_wet / m_dry) | g0 = 9.80665 m/s²",
bullets: [
"Mandatory PROP-03: Liftoff TWR must exceed 1.05 to clear the launch mount.",
"Recommended PROP-04: Liftoff TWR ≥ 1.22 minimizes gravity losses (typically 1.30–1.70 is ideal).",
"Upper Stages (PROP-05): Keep stage ignition TWR ≥ 0.45 so the upper stage climbs past apoapsis before gravity pulls it back.",
"Two-Phase Drop Tank Crossfeed: When external drop tanks feed the core engine, phase 1 burns drop-tank propellant, jettisons the empty external shells, and phase 2 burns the full core tank.",
],
},
{
heading: "2. Propellant Chemistries & Engine Controls",
paragraphs: [
"Every engine must match its tank chemistry (PROP-02). Higher Isp extracts more velocity per kilogram of propellant, while denser fuels keep stages compact and structurally lighter.",
],
bullets: [
"Kerolox (RP-1/LOX): Dense, high-thrust booster workhorse (Merlin-1D / MVac). Low tank volume and cost.",
"Methalox (CH4/LOX): Balanced density, full-flow staged combustion efficiency (Raptor SL/Vac), clean reusability.",
"Hydrolox (LH2/LOX): Highest chemical vacuum Isp (RL-10C, J-2X, RS-25) for upper stages and deep-space injection, but low density requires larger cryo-insulated tanks (THRM-01).",
"Hypergolic (NTO/MMH): Instant restartable storable thrusters (AJ10) for reliable orbital circularization.",
"Solid (PBAN SRB): High liftoff thrust and cheap strap-on kick, but non-throttleable and prohibited as Stage 1 for crewed flights (CREW-04).",
"Xenon Hall Ion (NEXT-C): ~3,200 s Isp electric thruster producing zero thrust below 110 km; requires ≥ 8,800 m/s of chemical lower stages (PROP-07).",
"Nozzle Ratio & Gimbal: Narrower bells resist sea-level overexpansion at liftoff; wider bells boost vacuum Isp. Stage 1 requires ≥ ±3° TVC gimbal (AERO-04).",
],
},
],
wikipediaRefs: [
{
title: "Tsiolkovsky rocket equation",
url: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation",
summary:
"Derivation and implications of Δv = ve ln(m0/mf) governing all chemical and electric rockets.",
},
{
title: "Delta-v",
url: "https://en.wikipedia.org/wiki/Delta-v",
summary:
"Orbital Δv budgets, gravity/drag losses, and transfer energy accounting.",
},
{
title: "Specific impulse",
url: "https://en.wikipedia.org/wiki/Specific_impulse",
summary:
"Propellant efficiency in seconds, exhaust velocity, and sea-level vs vacuum nozzle performance.",
},
{
title: "Thrust-to-weight ratio",
url: "https://en.wikipedia.org/wiki/Thrust-to-weight_ratio",
summary:
"Why boosters require TWR > 1.0 at liftoff while orbital stages operate effectively below 1.0.",
},
{
title: "Multistage rocket",
url: "https://en.wikipedia.org/wiki/Multistage_rocket",
summary:
"Serial and parallel staging mechanics that shed structural dead weight during ascent.",
},
{
title: "Propellant crossfeed",
url: "https://en.wikipedia.org/wiki/Propellant_crossfeed",
summary:
"Draining external boosters/drop tanks into the core engine first to jettison empty mass early.",
},
{
title: "De Laval nozzle",
url: "https://en.wikipedia.org/wiki/De_Laval_nozzle",
summary:
"Convergent-divergent supersonic bell geometry and nozzle expansion ratio trade-offs.",
},
{
title: "Liquid-propellant rocket",
url: "https://en.wikipedia.org/wiki/Liquid-propellant_rocket",
summary:
"Kerolox, Hydrolox, Methalox, and Hypergolic bipropellant systems and engine cycles.",
},
{
title: "Hall-effect thruster",
url: "https://en.wikipedia.org/wiki/Hall-effect_thruster",
summary:
"High-Isp electrostatic xenon propulsion used exclusively in vacuum orbital regimes.",
},
],
},
{
id: "structures-aero",
title: "Structures, Aerodynamics & Thermal",
shortTitle: "Structures, Aero & Stability Lab",
category: "Engineering & Physics",
summary:
"Balance Center of Gravity (CG) ahead of Center of Pressure (CP), prevent shell buckling and Max-Q breakup, and select optimal hull alloys and thermal protection.",
coachTip:
"Think of a dart or arrow: heavy mass at the nose (CG) and aerodynamic drag fins at the tail (CP). If CP climbs ahead of CG, your rocket wants to fly backwards under Max-Q! -- ULTRACAT",
relatedScreens: [{ screen: "builder", label: "Inspect CG/CP in Builder" }],
labKind: "stability-maxq",
sections: [
{
heading: "1. CG vs CP Static Stability & Aerodynamics",
paragraphs: [
"During atmospheric ascent, aerodynamic restoring/destabilizing forces act through the Center of Pressure (CP), while rotational inertia pivots around the Center of Gravity (CG). Static stability margin is measured in hull diameters ('calibers').",
],
formula:
"Static Stability Margin (Calibers) = (CG_y − CP_y) / Max Diameter (Target ≥ +0.40)",
bullets: [
"AERO-01: Keep CG ahead of (above) CP by ≥ 0.40 calibers. Enable Titanium Grid Fins on Stage 1 to pull CP downward.",
"Slenderness (STR-03): Keep Height / Max Diameter (L/D) ≤ 22 to avoid excessive bending loads.",
"Stage Taper (STR-04 & STR-05): Diameter steps > 25% need a Tapered Conical Adapter, and upper stages may never exceed 1.4× booster diameter.",
"Fairing (AERO-02 & PAY-02/03): Enclose satellites inside a fairing wider and taller than the payload; blunt exposed noses double drag.",
],
},
{
heading: "2. Max-Q, Buckling & Hull Materials",
paragraphs: [
"Max-Q (Maximum Dynamic Pressure) occurs in the lower stratosphere where rising supersonic speed meets dense air. Compressive thrust and wind shear can buckle thin tank walls or exceed shell yield limits.",
],
formula:
"q = ½ × ρ(altitude) × v² | Buckling Ratio = Axial Load / (0.65 × Yield Limit) < 1.0",
bullets: [
"Aluminum 7075-T6 (1.0× mass, 503 MPa, 450 K): Cheap baseline starter alloy.",
"Aluminum-Lithium 2195 (0.88× mass, 560 MPa, 490 K): Cryo-ready lightweight upgrade from R&D.",
"IM7 Carbon-Epoxy (0.68× mass, 780 MPa, 430 K): Ultralight composite; pair with a heatshield on hot ascent profiles (THRM-04).",
"Cryo-Hardened 304L Steel (1.28× mass, 680 MPa, 1150 K) & Inconel-718 (1.55× mass, 1030 MPa, 1450 K): High thermal survival for reentry/recovery and extreme heat flux.",
"PICA-X Heatshield & Launch Abort System (LAS): Heatshields protect boosters for recovery bonus and deep-space thermal corridors; LAS saves crew lives (0 casualties) during abort events.",
],
},
],
wikipediaRefs: [
{
title: "Max Q",
url: "https://en.wikipedia.org/wiki/Max_Q",
summary:
"Peak atmospheric dynamic pressure during ascent and why rockets throttle down through the transonic bucket.",
},
{
title: "Center of pressure (fluid mechanics)",
url: "https://en.wikipedia.org/wiki/Center_of_pressure_(fluid_mechanics)",
summary:
"Where aerodynamic lift and drag forces act on a launch vehicle airframe.",
},
{
title: "Center of mass",
url: "https://en.wikipedia.org/wiki/Center_of_mass",
summary:
"How propellant consumption shifts a rocket's balance point relative to aerodynamic forces.",
},
{
title: "Buckling",
url: "https://en.wikipedia.org/wiki/Buckling",
summary:
"Thin-walled cylindrical shell failure under axial compression and bending loads.",
},
{
title: "Fineness ratio",
url: "https://en.wikipedia.org/wiki/Fineness_ratio",
summary:
"Length-to-diameter ratio (L/D) balancing supersonic wave drag against structural bending.",
},
{
title: "Payload fairing",
url: "https://en.wikipedia.org/wiki/Payload_fairing",
summary:
"Clamshell nosecone shielding spacecraft from supersonic airloads and jettisoned above the dense atmosphere.",
},
{
title: "Grid fin",
url: "https://en.wikipedia.org/wiki/Grid_fin",
summary:
"Lattice aerodynamic stabilizers that pull CP aft and enable booster recovery steering.",
},
{
title: "Atmospheric entry",
url: "https://en.wikipedia.org/wiki/Atmospheric_entry",
summary:
"Aerothermal plasma heating, heat shields, and thermal protection systems (TPS).",
},
{
title: "Launch escape system",
url: "https://en.wikipedia.org/wiki/Launch_escape_system",
summary:
"Solid-motor escape tower designed to pull crewed capsules clear of failing boosters.",
},
],
},
{
id: "guidance-orbit",
title: "Flight Guidance, Gravity Turn & Orbital Mechanics",
shortTitle: "Guidance & Gravity Turn Lab",
category: "Engineering & Physics",
summary:
"Shape an efficient ascent trajectory using Gravity Turn parameters, Max-Q throttling, fairing separation, MECO/SECO, launch windows, and GMAT orbital analysis.",
coachTip:
"Going straight up doesn't keep you in space—moving sideways at ~7,800 m/s does! Let gravity naturally bend your velocity vector onto the horizon via a smooth pitch-over kick. -- ULTRACAT",
relatedScreens: [
{ screen: "config", label: "Open Param Config" },
{ screen: "worldMap", label: "Open World Map" },
],
labKind: "gravity-turn",
sections: [
{
heading: "1. Shaping the Gravity Turn",
paragraphs: [
"The Flight Parameter Configurator simulates your exact rocket along a curved-Earth 2D planar trajectory. Your goal is to leave the dense atmosphere cleanly while converting vertical speed into horizontal orbital speed before upper-stage burnout.",
],
bullets: [
"Gravity Turn Start Velocity (35–160 m/s): Airspeed where the rocket begins tilting east after clearing the pad tower.",
"Initial Pitch-Over Kick (3–18°): Small early angle tilt. Too small (< 5°) wastes Δv fighting gravity; too large (> 13°) plunges horizontally into thick air and spikes Max-Q & heat flux.",
"Gravity Turn Level-Off Alt (65–130 km): Altitude where guidance finishes flattening toward horizontal (0°).",
"Max-Q Throttle Bucket (0.50–1.00): Automatically throttles down near Mach 0.9–1.5 to tame peak dynamic pressure.",
"Fairing Jettison Alt (70–130 km): Must exceed the contract minimum (typically ≥ 80–90 km, AERO-03) to avoid payload aero loss.",
"Upper Burn Continuous Fraction (0.65–1.00): Controls coast vs continuous circularization burn split.",
],
},
{
heading: "2. Orbital Elements, Launch Windows & GMAT",
paragraphs: [
"A stable parking orbit requires both Apoapsis (highest point) and Periapsis (lowest point) to stay within your difficulty's tolerance corridor, with Periapsis safely above Earth's dense atmosphere (≥ 90 km).",
"Higher target inclinations reduce Earth's rotational eastward boost and cost extra Δv. Launch Windows oscillate over synodic periods—launching off-peak adds a Window Δv Penalty (ORB-04). Unlocking Tier-3 Avionics unlocks NASA GMAT-backed 3D orbital propagation graphs.",
],
},
],
wikipediaRefs: [
{
title: "Gravity turn",
url: "https://en.wikipedia.org/wiki/Gravity_turn",
summary:
"Zero-lift trajectory optimization turning vertical launch velocity smoothly into horizontal orbital speed.",
},
{
title: "Apsis",
url: "https://en.wikipedia.org/wiki/Apsis",
summary:
"Apoapsis (highest point) and periapsis (lowest point) defining an elliptical orbit.",
},
{
title: "Orbital inclination",
url: "https://en.wikipedia.org/wiki/Orbital_inclination",
summary:
"Tilt of an orbital plane relative to the equator and plane-change Δv penalties.",
},
{
title: "Low Earth orbit",
url: "https://en.wikipedia.org/wiki/Low_Earth_orbit",
summary:
"Orbital speeds (~7.8 km/s), atmospheric drag thresholds, and parking orbit mechanics.",
},
{
title: "Hohmann transfer orbit",
url: "https://en.wikipedia.org/wiki/Hohmann_transfer_orbit",
summary:
"Two-impulse elliptical transfer maneuver between circular orbits and planetary targets.",
},
{
title: "Launch window",
url: "https://en.wikipedia.org/wiki/Launch_window",
summary:
"Orbital alignment timing windows and the Δv penalty incurred outside optimal phase.",
},
{
title: "General Mission Analysis Tool",
url: "https://en.wikipedia.org/wiki/General_Mission_Analysis_Tool",
summary:
"NASA's high-precision trajectory propagation and mission optimization software integrated into SGYWFTP Tier-3 diagnostics.",
},
],
},
{
id: "bus-avionics-crew",
title: "Spacecraft Bus, Avionics & Crew Systems",
shortTitle: "Bus, Avionics & Crew",
category: "Operations & Systems",
summary:
"Size flight computers against CPU demand and radiation SEUs, balance spacecraft electrical power & deep-space comms links, and protect astronauts with ECLSS & LAS.",
coachTip:
"Solar arrays shrink dramatically past Mars (1/r²!). Switch to MMRTG or Kilopower fission and upgrade to X/Ka-Band + Global DSN before signing outer-planet contracts. -- ULTRACAT",
relatedScreens: [
{ screen: "builder", label: "Fairing & Payload Tab" },
{ screen: "config", label: "Crew & ECLSS Sliders" },
],
sections: [
{
heading: "1. Flight Computer (GNC), CPU Load & SEUs",
paragraphs: [
"Every rocket mounts a Guidance, Navigation & Control (GNC) flight computer in the Payload/Bus tab. Compute demand grows with stages, engine cluster count, science instruments, LAS, and split burns.",
"If peak CPU load approaches 100%, guidance can freeze mid-ascent (AVN-02). During solar/radiation storms or high-energy missions, cosmic particles trigger Single-Event Upsets (SEUs)—upgrade to RAD750, Aegis-IV, or Chronos-X for Triple/Quad Modular Redundancy and ECC fault scrubbing (AVN-03).",
],
},
{
heading: "2. Spacecraft Bus: Power, Comms & Science Instruments",
paragraphs: [
"Your payload's spacecraft bus determines electrical power margin (PAY-06), telemetry signal health (PAY-07), and bonus science payouts/RP.",
],
bullets: [
"Power Systems: Standard & ROSA Solar Arrays scale with solar flux (1/r²) and suffer eclipse drains; MMRTG (900 W) and Kilopower Fission (4.2 kW) output constant power in deep space.",
"Comms & Ground Network: S-Band works in LEO; Lunar, Mars, and Jupiter targets require X-Band or Ka-Band/Optical dishes paired with Global DSN or Deep Space Optical Array tracking.",
"Science Instruments: Adding compatible imagers, magnetometers, spectrometers, or laser relays boosts Science Bonus payout and Research Points—provided your bus power and downlink bandwidth cover them.",
],
},
{
heading: "3. Crew Capacity, ECLSS & Launch Abort System",
paragraphs: [
"Crewed contracts enforce strict human-rating rules: a crew-capable capsule (CREW-01), adequate ECLSS life support seats in Param Config (CREW-02), a Launch Abort System tower (CREW-03), and throttleable liquid Stage 1 engines (CREW-04).",
"Without LAS, a booster failure causes Loss of Crew (LOC), heavy inquiry fines, reputation collapse, and on Flight Director difficulty, permanent agency termination.",
],
},
],
wikipediaRefs: [
{
title: "Satellite bus",
url: "https://en.wikipedia.org/wiki/Satellite_bus",
summary:
"Spacecraft structural and service architecture supplying power, telemetry, thermal control, and attitude stability.",
},
{
title: "Radiation hardening",
url: "https://en.wikipedia.org/wiki/Radiation_hardening",
summary:
"Redundant voting logic (TMR) and shielding protecting flight avionics against cosmic radiation.",
},
{
title: "Single-event upset",
url: "https://en.wikipedia.org/wiki/Single-event_upset",
summary:
"Ionizing-particle bit flips causing transient resets or lockups in orbital processors.",
},
{
title: "Radioisotope thermoelectric generator",
url: "https://en.wikipedia.org/wiki/Radioisotope_thermoelectric_generator",
summary:
"Nuclear decay power supplies enabling outer-planet exploration far from sunlight.",
},
{
title: "NASA Deep Space Network",
url: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network",
summary:
"Global high-gain ground dish complexes sustaining telemetry across cislunar and interplanetary distances.",
},
{
title: "Life-support system",
url: "https://en.wikipedia.org/wiki/Life-support_system",
summary:
"ECLSS oxygen regeneration, CO2 scrubbing, thermal regulation, and crew survival systems.",
},
],
},
{
id: "compliance-qa",
title: "NASA CML/TRL Compliance, QA & Builder Modes",
shortTitle: "Compliance Rules & QA",
category: "Operations & Systems",
summary:
"Understand Concept → PDR → CDR → Flight-Ready maturity gates, mandatory vs waiverable compliance rules, Static Fire QA, Insurance, and Pro 3D Freeform mode.",
coachTip:
"Only grant a Waiver when a fix is genuinely out of reach—waivers add launch fees AND stack live anomaly risk! Static Fire QA in Param Config cuts hardware defect risk significantly. -- ULTRACAT",
relatedScreens: [
{ screen: "builder", label: "Compliance Tab" },
{ screen: "config", label: "Pre-Launch QA" },
],
labKind: "compliance-directory",
sections: [
{
heading: "1. Design Maturity Gates & Waivers",
paragraphs: [
"Except in Sandbox difficulty, a launch vehicle must reach FLIGHT-READY maturity before clearing the pad. Every design is evaluated against 42 engineering rules across Propulsion, Structures, Aerodynamics, Thermal, Payload & Bus, Crew, and Orbital rules.",
],
bullets: [
"Concept → PDR: Requires passing mandatory propulsion and payload rules.",
"PDR → CDR: Requires zero mandatory rule failures across the entire stack.",
"CDR → Flight-Ready: Requires zero unwaived advisory failures and zero locked R&D parts.",
"Waivers: Advisory ('waiverable') warnings can be waived for an added fee and +5% to +12% in-flight anomaly probability. Mandatory rules can never be waived.",
],
},
{
heading: "2. Guided vs Pro Freeform 3D & Blueprints",
paragraphs: [
"Guided fidelity tiers (Casual, Standard, Expert) arrange stages vertically with structured slots and symmetric drop-tank controls (Expert unlocks custom tank fill ratios). PRO mode unlocks direct 3D viewport part placement, radial symmetry clusters, and arbitrary offsets.",
"Use Blueprints & Share in Rocket Builder to save hangar designs, exchange portable SGYW1 share codes, or inspect Undo/Redo edit history.",
],
},
{
heading: "3. Static Fire QA & Launch Insurance",
paragraphs: [
"In Param Config's Pre-Launch QA box, you can run a Static Fire test (~4% of vehicle cost, min $450k) to verify the exact current design hash and cut hardware defect probability (-8% defect boost). Launch Insurance (8% premium on Enthusiast/Engineer/Director) reimburses 70% of vehicle hull cost on failure.",
],
},
],
wikipediaRefs: [
{
title: "Technology readiness level",
url: "https://en.wikipedia.org/wiki/Technology_readiness_level",
summary:
"NASA's 1–9 scale measuring flight maturity of spacecraft hardware and subsystems.",
},
{
title: "Design review (U.S. government)",
url: "https://en.wikipedia.org/wiki/Design_review_(U.S._government)",
summary:
"Preliminary Design Review (PDR), Critical Design Review (CDR), and Flight Readiness milestones.",
},
{
title: "Range safety",
url: "https://en.wikipedia.org/wiki/Range_safety",
summary:
"Pre-launch certification, flight termination safeguards, and waiver review procedures.",
},
],
},
{
id: "economy-world",
title: "Contracts, Economy, Space Weather & Co-Op",
shortTitle: "Economy, Weather & Co-Op",
category: "Operations & Systems",
summary:
"Navigate Tier 1–5 contracts, Custom & Convoluted missions, dynamic commodity part pricing, live space weather hazards, the 3D World Map, and 4-station Co-Op engineering.",
coachTip:
"Keep an eye on the Launch Environment Forecast! Launching during a Radiation Storm or Jet-Stream Shear spikes SEU lockups and Max-Q loads unless your rocket carries countermeasures. -- ULTRACAT",
relatedScreens: [
{ screen: "contracts", label: "Contracts & Exchange" },
{ screen: "worldMap", label: "3D World Map" },
],
sections: [
{
heading: "1. Contracts, Commodity Exchange & Reputation",
paragraphs: [
"Contracts & Rank lists offers across sponsors (with loyalty bonuses for your home sponsor), alongside the Custom Mission Architect and procedural Convoluted Missions for high-stakes payouts.",
"Part prices fluctuate in real time on the Commodity Exchange driven by global agency demand. Check Value Chart in Rocket Builder to compare Projected Net EV, Risk-Adjusted EV, and $/kg payload cost before launching.",
],
},
{
heading: "2. Space Weather, Hazards & World Map",
paragraphs: [
"Global space weather (Nominal, Solar Wind, Solar Storm, Radiation Storm, Micrometeoroid) and transient corridor hazards (Stray Radiation, Meteorite Streams, Jet-Stream Shear) shift dynamically via live server events.",
"Inspect active AI/player flights and 3D NASA probes (ISS, JWST, Hubble, Juno, Voyager, Parker Solar Probe, and more) in the Solar System Explorer (World Map), or spectate live launches from the Dashboard.",
],
},
{
heading: "3. Multi-Operator Co-Op Stations",
paragraphs: [
"Multiple users logged into the same agency synchronize Rocket Builder edits live over SSE. Claim one of the 4 mission control stations—PROP (Propulsion), STRC (Structures), GUID (Guidance), PAYL (Payload/Comms)—and toggle Ready status together.",
],
},
],
wikipediaRefs: [
{
title: "Space weather",
url: "https://en.wikipedia.org/wiki/Space_weather",
summary:
"Solar wind, geomagnetic storms, and orbital radiation variations affecting launch operations.",
},
{
title: "Solar particle event",
url: "https://en.wikipedia.org/wiki/Solar_particle_event",
summary:
"High-energy solar proton bursts that raise single-event upset (SEU) rates in spacecraft electronics.",
},
{
title: "Micrometeoroid",
url: "https://en.wikipedia.org/wiki/Micrometeoroid",
summary:
"Hypervelocity space dust hazards requiring fairings, Whipple protection, or window timing.",
},
{
title: "Ephemeris",
url: "https://en.wikipedia.org/wiki/Ephemeris",
summary:
"Time-indexed planetary and spacecraft position tables driving solar system trajectories.",
},
],
},
{
id: "glossary-index",
title: "Searchable Aerospace Terminology Glossary",
shortTitle: "Glossary & Formulas",
category: "Live Reference Directories",
summary:
"Complete reference of every HUD '?' tooltip term, engineering formula, and direct Wikipedia deep-dive link.",
coachTip:
"Remember: clicking any '?' badge anywhere in the HUD and hitting 'Open in Wiki →' lands right on the exact term here without discarding your rocket draft! -- ULTRACAT",
relatedScreens: [
{ screen: "builder", label: "Rocket Builder" },
{ screen: "config", label: "Param Config" },
],
labKind: "glossary-directory",
sections: [],
wikipediaRefs: [
{
title: "Rocket engine",
url: "https://en.wikipedia.org/wiki/Rocket_engine",
summary:
"General encyclopedia entry on rocket propulsion principles and terminology.",
},
{
title: "Spacecraft thermal control",
url: "https://en.wikipedia.org/wiki/Spacecraft_thermal_control",
summary:
"Managing aero-heating, solar flux, and radiator heat rejection.",
},
],
},
{
id: "tech-tree-ref",
title: "R&D Tech Tree & Difficulty Tier Reference",
shortTitle: "Tech Tree & Difficulty",
category: "Live Reference Directories",
summary:
"Live reference table generated directly from the game's R&D technology nodes and difficulty simulation profiles.",
coachTip:
"Prioritize Cryogenic Hydrolox and Telemetry & Fault-Scrubbing (Tier 2) early if you're aiming for GEO, Lunar, or severe weather windows! -- ULTRACAT",
relatedScreens: [{ screen: "dashboard", label: "Dashboard (Tech Lab)" }],
labKind: "tech-difficulty-directory",
sections: [],
wikipediaRefs: [
{
title: "Technology readiness level",
url: "https://en.wikipedia.org/wiki/Technology_readiness_level",
summary:
"How aerospace R&D programs mature new engines, alloys, and avionics from concept to flight.",
},
],
},
{
id: "my-vehicle-inspector",
title: "Live Agency & Rocket Diagnostic Inspector",
shortTitle: "My Rocket Inspector",
category: "Live Reference Directories",
summary:
"Inspect your agency's currently saved launch vehicle, active contract margins, compliance rule blockers, and jump straight to the matching Wiki fix guide.",
coachTip:
"Not sure why your rocket is stuck at Concept or failing insertion? Load your current ship here for plain-English links to the exact engineering rule! -- ULTRACAT",
relatedScreens: [
{ screen: "builder", label: "Fix in Rocket Builder" },
{ screen: "config", label: "Fix in Param Config" },
],
labKind: "vehicle-inspector",
sections: [],
wikipediaRefs: [
{
title: "Orbital spaceflight",
url: "https://en.wikipedia.org/wiki/Orbital_spaceflight",
summary:
"Key orbital insertion metrics and launch vehicle performance budgets.",
},
],
},
];
export function getWikiArticle(id?: string | null): WikiArticle {
return WIKI_ARTICLES.find((a) => a.id === id) ?? WIKI_ARTICLES[0];
}

View file

@ -0,0 +1,55 @@
// Modal? Like the runway ones?
import type { GlossaryKey } from "../glossary.js";
import { h } from "../ui.js";
import type { WikiArticleId } from "./wikiData.js";
import { renderWikiWorkspace } from "./wikiWorkspace.js";
let activeDrawer: HTMLElement | null = null;
let activeCleanup: (() => void) | null = null;
export function closeWikiDrawer(): void {
activeCleanup?.();
activeCleanup = null;
}
export function openWikiDrawer(opts: {
articleId?: WikiArticleId;
glossaryKey?: GlossaryKey | string;
query?: string;
} = {}): void {
closeWikiDrawer();
const modalRoot = document.getElementById("modal-root") ?? document.body;
const overlay = h("div", { class: "modal-overlay wiki-drawer-overlay" });
const drawerPanel = h("div", { class: "panel wiki-drawer-panel" });
const onKeyDown = (ev: KeyboardEvent) => {
if (ev.key === "Escape") {
ev.stopPropagation();
close();
}
};
const close = () => {
window.removeEventListener("keydown", onKeyDown, true);
overlay.remove();
if (activeDrawer === overlay) activeDrawer = null;
if (activeCleanup === close) activeCleanup = null;
};
renderWikiWorkspace(drawerPanel, {
initialArticleId: opts.articleId,
initialGlossaryKey: opts.glossaryKey,
initialQuery: opts.query,
mode: "drawer",
backLabel: "✕ Close Wiki",
onBack: close,
});
overlay.addEventListener("click", (ev) => {
if (ev.target === overlay) close();
});
window.addEventListener("keydown", onKeyDown, true);
overlay.appendChild(drawerPanel);
modalRoot.appendChild(overlay);
activeDrawer = overlay;
activeCleanup = close;
}

View file

@ -0,0 +1,441 @@
// Cool thnigy
import { navigate } from "../router.js";
import { TERMINOLOGY_GLOSSARY, type GlossaryKey } from "../glossary.js";
import { COMPLIANCE_RULES_META } from "../../shared/compliance.js";
import { TECH_TREE } from "../../shared/physics.js";
import { clear, h } from "../ui.js";
import { renderWikiLab } from "./interactiveLabs.js";
import {
isWalkthroughActive,
startWalkthrough,
stopWalkthrough,
} from "./walkthrough.js";
import {
getWikiArticle,
WIKI_ARTICLES,
WIKI_CATEGORIES,
type WikiArticleId,
} from "./wikiData.js";
export interface WikiWorkspaceOptions {
initialArticleId?: WikiArticleId;
initialGlossaryKey?: GlossaryKey | string;
initialQuery?: string;
mode: "page" | "drawer";
backLabel: string;
onBack: () => void;
}
interface SearchHit {
title: string;
subtitle: string;
badge: string;
onOpen: () => void;
}
export function renderWikiWorkspace(
container: HTMLElement,
opts: WikiWorkspaceOptions,
): void {
let activeArticleId: WikiArticleId = getWikiArticle(
opts.initialArticleId ??
(opts.initialGlossaryKey ? "glossary-index" : undefined),
).id;
let highlightGlossaryKey =
activeArticleId === "glossary-index" ? opts.initialGlossaryKey : undefined;
let query = opts.initialQuery ?? "";
const searchInput = h("input", {
class: "input wiki-search-input",
placeholder:
"Search guides, Δv, Max-Q, compliance rules, R&D tech, Wikipedia...",
value: query,
onInput: () => {
query = searchInput.value;
renderSidebarAndResults();
},
}) as HTMLInputElement;
const sidebarEl = h("aside", { class: "wiki-sidebar" });
const mainEl = h("main", { class: "wiki-main" });
const walkthroughBtn = h("button", { class: "btn xs primary" }, "");
function syncWalkthroughBtn(): void {
const active = isWalkthroughActive();
walkthroughBtn.className = `btn xs ${active ? "warn" : "primary"}`;
walkthroughBtn.textContent = active
? "Stop Walkthrough"
: "Start Interactive Walkthrough";
}
walkthroughBtn.addEventListener("click", () => {
if (isWalkthroughActive()) {
stopWalkthrough();
} else {
startWalkthrough(0);
if (opts.mode === "drawer") opts.onBack();
}
syncWalkthroughBtn();
});
function openArticle(id: WikiArticleId, glossaryKey?: string): void {
activeArticleId = id;
highlightGlossaryKey = glossaryKey;
renderSidebarAndResults();
renderArticleBody();
mainEl.scrollTop = 0;
}
function buildSearchHits(q: string): SearchHit[] {
const needle = q.trim().toLowerCase();
if (!needle) return [];
const hits: SearchHit[] = [];
const clip = (s: string) =>
s.length > 88 ? `${s.slice(0, 88)}...` : s;
for (const art of WIKI_ARTICLES) {
const hay =
`${art.title} ${art.summary} ${art.sections.map((s) => `${s.heading} ${s.paragraphs.join(" ")} ${(s.bullets ?? []).join(" ")}`).join(" ")}`.toLowerCase();
if (hay.includes(needle)) {
hits.push({
title: art.shortTitle,
subtitle: clip(art.summary),
badge: "GUIDE",
onOpen: () => openArticle(art.id),
});
}
}
for (const [k, entry] of Object.entries(TERMINOLOGY_GLOSSARY)) {
const hay =
`${entry.title} ${entry.summary} ${entry.formula ?? ""}`.toLowerCase();
if (hay.includes(needle)) {
hits.push({
title: entry.title,
subtitle: clip(entry.summary),
badge: "GLOSSARY",
onOpen: () => openArticle("glossary-index", k),
});
}
}
for (const rule of COMPLIANCE_RULES_META) {
const hay =
`${rule.code} ${rule.title} ${rule.description}`.toLowerCase();
if (hay.includes(needle)) {
hits.push({
title: `[${rule.code}] ${rule.title}`,
subtitle: rule.description,
badge: "RULE",
onOpen: () => openArticle("compliance-qa"),
});
}
}
for (const tech of TECH_TREE) {
const hay =
`${tech.name} ${tech.description} ${tech.unlocksIds.join(" ")}`.toLowerCase();
if (hay.includes(needle)) {
hits.push({
title: tech.name,
subtitle: tech.description,
badge: "R&D",
onOpen: () => openArticle("tech-tree-ref"),
});
}
}
return hits.slice(0, 24);
}
function renderSidebarAndResults(): void {
clear(sidebarEl);
const hits = buildSearchHits(query);
if (query.trim().length > 0) {
sidebarEl.appendChild(
h(
"div",
{ class: "col", style: { gap: "6px" } },
h(
"div",
{ class: "spread" },
h(
"span",
{ class: "slot-title" },
`Search Results (${hits.length})`,
),
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
query = "";
searchInput.value = "";
renderSidebarAndResults();
},
},
"Clear",
),
),
hits.length
? h(
"div",
{ class: "col", style: { gap: "6px" } },
...hits.map((hit) =>
h(
"button",
{
class: "wiki-search-hit",
onClick: hit.onOpen,
},
h(
"div",
{ class: "spread", style: { gap: "6px" } },
h(
"strong",
{ class: "mono", style: { fontSize: "11px" } },
hit.title,
),
h("span", { class: "badge info" }, hit.badge),
),
h(
"span",
{ class: "dim", style: { fontSize: "10px" } },
hit.subtitle,
),
),
),
)
: h(
"p",
{ class: "dim mono", style: { fontSize: "11px" } },
"No matching articles, terms, or rules.",
),
),
);
return;
}
for (const cat of WIKI_CATEGORIES) {
const groupArticles = WIKI_ARTICLES.filter((a) => a.category === cat);
if (!groupArticles.length) continue;
sidebarEl.appendChild(
h(
"div",
{ class: "wiki-nav-group" },
h("div", { class: "wiki-nav-cat" }, cat),
...groupArticles.map((art) =>
h(
"button",
{
class: `wiki-nav-item ${art.id === activeArticleId ? "active" : ""}`,
onClick: () => openArticle(art.id),
},
h("span", {}, art.shortTitle),
art.labKind ? h("span", { class: "badge info" }, "LAB") : null,
),
),
),
);
}
}
function renderArticleBody(): void {
clear(mainEl);
const article = getWikiArticle(activeArticleId);
const idx = WIKI_ARTICLES.findIndex((a) => a.id === article.id);
const prevArt = idx > 0 ? WIKI_ARTICLES[idx - 1] : null;
const nextArt =
idx >= 0 && idx < WIKI_ARTICLES.length - 1
? WIKI_ARTICLES[idx + 1]
: null;
const labEl = renderWikiLab(
article.labKind,
{
onOpenArticle: (id) => openArticle(id),
onCloseDrawer: opts.mode === "drawer" ? opts.onBack : undefined,
},
highlightGlossaryKey,
);
const nodes: Array<Node | null> = [
h(
"div",
{ class: "wiki-article-header" },
h(
"div",
{ class: "spread", style: { gap: "8px", flexWrap: "wrap" } },
h("span", { class: "badge info" }, article.category),
h(
"div",
{ class: "row", style: { gap: "6px", flexWrap: "wrap" } },
...article.relatedScreens.map((rs) =>
h(
"button",
{
class: "btn xs ghost",
onClick: () => {
if (opts.mode === "drawer") opts.onBack();
navigate(rs.screen);
},
},
`${rs.label} →`,
),
),
),
),
h("h2", { style: { marginTop: "8px" } }, article.title),
h(
"p",
{
class: "dim",
style: { fontSize: "13px", lineHeight: "1.55", marginTop: "6px" },
},
article.summary,
),
),
h(
"div",
{ class: "wiki-callout" },
h(
"span",
{ class: "badge ok", style: { flexShrink: "0" } },
"COACH ULTRACAT",
),
h(
"span",
{ style: { fontSize: "12px", lineHeight: "1.5" } },
article.coachTip,
),
),
...article.sections.map((sec) =>
h(
"section",
{ class: "wiki-section panel" },
h("h3", { class: "accent" }, sec.heading),
...sec.paragraphs.map((p) => h("p", { class: "wiki-prose" }, p)),
sec.formula ? h("div", { class: "wiki-formula" }, sec.formula) : null,
sec.bullets?.length
? h(
"ul",
{ class: "wiki-bullets" },
...sec.bullets.map((b) => h("li", {}, b)),
)
: null,
),
),
labEl,
article.wikipediaRefs.length
? h(
"section",
{ class: "wiki-refs-section" },
h(
"div",
{ class: "spread", style: { marginBottom: "8px" } },
h("h3", { class: "accent" }, "Further Reading on Wikipedia ↗"),
h(
"span",
{ class: "mono faint", style: { fontSize: "10px" } },
"External reference links open in a new tab",
),
),
h(
"div",
{ class: "wiki-ref-grid" },
...article.wikipediaRefs.map((ref) =>
h(
"a",
{
class: "wiki-ref-card",
href: ref.url,
target: "_blank",
rel: "noopener noreferrer",
},
h(
"div",
{ class: "spread", style: { gap: "6px" } },
h(
"strong",
{ class: "mono brand", style: { fontSize: "12px" } },
ref.title,
),
h("span", { class: "badge info" }, "WIKIPEDIA ↗"),
),
h(
"p",
{
class: "dim",
style: {
fontSize: "11px",
lineHeight: "1.45",
marginTop: "4px",
},
},
ref.summary,
),
),
),
),
)
: null,
h(
"div",
{ class: "spread wiki-footer-nav" },
prevArt
? h(
"button",
{ class: "btn sm ghost", onClick: () => openArticle(prevArt.id) },
`← ${prevArt.shortTitle}`,
)
: h("span"),
nextArt
? h(
"button",
{
class: "btn sm primary",
onClick: () => openArticle(nextArt.id),
},
`${nextArt.shortTitle} →`,
)
: h("span"),
),
];
mainEl.append(...nodes.filter((n): n is Node => n !== null));
}
syncWalkthroughBtn();
renderSidebarAndResults();
renderArticleBody();
const topbar = h(
"header",
{ class: "wiki-topbar" },
h(
"div",
{ class: "row", style: { gap: "10px" } },
h("button", { class: "btn sm", onClick: opts.onBack }, opts.backLabel),
h("h2", {}, "Flight Wiki & Interactive Tutorial"),
),
h(
"div",
{ class: "row wiki-topbar-controls", style: { gap: "8px" } },
searchInput,
h(
"button",
{
class: "btn xs",
onClick: () => openArticle("my-vehicle-inspector"),
},
"My Rocket Inspector",
),
walkthroughBtn,
),
);
clear(container);
container.append(
topbar,
h("div", { class: "wiki-layout" }, sidebarEl, mainEl),
);
}

View file

@ -100,16 +100,13 @@ function estimateAiMissionEconomics(
((validation.compliance.waivedCount ?? 0) === 0 ? 0.04 : 0),
) + gradeBonusRate;
const grossPayout = Math.round(budget * (0.65 + effBonusRate));
const scienceBonus = Math.round(
budget * ((bus?.scienceBonusPct ?? 0) / 100),
);
const scienceBonus = Math.round(budget * ((bus?.scienceBonusPct ?? 0) / 100));
const canRecover =
(contract.isReusable ||
(agency.unlockedTechs ?? []).includes("methalox-reusable")) &&
validation.dvMargin >= 450 &&
(!!design.stages?.[0]?.hasFins || (design.stages?.length ?? 0) >= 2);
const stage0Cost =
asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55);
const stage0Cost = asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55);
const reusabilityBonus = canRecover ? Math.round(stage0Cost * 0.28) : 0;
const successCash = grossPayout + scienceBonus + reusabilityBonus;
@ -121,11 +118,9 @@ function estimateAiMissionEconomics(
const padRepairExpected = exempt
? 0
: Math.round(
(6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) *
0.45,
(6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) * 0.45,
);
const crewInquiryExpected =
contract.crewed && !exempt ? 10_000_000 : 0;
const crewInquiryExpected = contract.crewed && !exempt ? 10_000_000 : 0;
const failureCash =
insurancePayout - breachPenalty - padRepairExpected - crewInquiryExpected;
@ -135,8 +130,7 @@ function estimateAiMissionEconomics(
Math.min(0.97, 0.88 + skill * 0.08 - anomalyRiskPct / 140),
);
const expectedCash = Math.round(
successProbability * successCash +
(1 - successProbability) * failureCash,
successProbability * successCash + (1 - successProbability) * failureCash,
);
const abandonCost =
Math.round(budget * 0.35) + Math.round(budget * profile.breachFineRate);
@ -204,8 +198,7 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null {
const estCost = estimateAiMissionCost(agency, offer);
const estMargin = expectedContractPayout(offer) - estCost;
let score =
offer.budget / 1e6 +
Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5;
offer.budget / 1e6 + Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5;
if (!feasible) {
score -= 1000;
}

View file

@ -138,7 +138,10 @@ export function ensureHazards(simTime: number): void {
}
const prevActiveIds = (world.activeHazards ?? []).map((h) => h.id).join(",");
const active = eventsForEpoch(curEpoch);
const upcoming = [...eventsForEpoch(curEpoch + 1), ...eventsForEpoch(curEpoch + 2)];
const upcoming = [
...eventsForEpoch(curEpoch + 1),
...eventsForEpoch(curEpoch + 2),
];
world.activeHazards = active;
world.upcomingHazards = upcoming;
world.hazardEpoch = curEpoch;

View file

@ -127,11 +127,9 @@ export function registerAgencyRoutes(router: Router): void {
return;
}
if (agency.treasury >= 25_000_000 && !agency.bankrupt) {
res
.status(400)
.json({
error: "Agency is solvent and ineligible for emergency bailout.",
});
res.status(400).json({
error: "Agency is solvent and ineligible for emergency bailout.",
});
return;
}
const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId);
@ -260,12 +258,10 @@ export function registerAgencyRoutes(router: Router): void {
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.",
});
res.status(400).json({
error:
"Build and save a rocket design before running a static fire test.",
});
return;
}
try {

View file

@ -36,11 +36,9 @@ export function registerContractRoutes(router: Router): void {
agency.activeContract ||
(agency.activeMissions ?? []).some((m) => !m.settled)
) {
res
.status(409)
.json({
error: "Already has an active contract. Complete it first.",
});
res.status(409).json({
error: "Already has an active contract. Complete it first.",
});
return;
}
if (agency.missionId) clearActiveContract(agency);
@ -83,11 +81,9 @@ export function registerContractRoutes(router: Router): void {
agency.activeContract ||
(agency.activeMissions ?? []).some((m) => !m.settled)
) {
res
.status(409)
.json({
error: "Already has an active contract. Complete it first.",
});
res.status(409).json({
error: "Already has an active contract. Complete it first.",
});
return;
}
if (agency.missionId) clearActiveContract(agency);

View file

@ -30,11 +30,9 @@ export function registerMissionRoutes(router: Router): void {
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).`,
});
res.status(400).json({
error: `Insufficient funds for test flight ($${(testFee / 1e6).toFixed(2)}M needed).`,
});
return;
}
agency.treasury -= testFee;
@ -91,12 +89,10 @@ export function registerMissionRoutes(router: Router): void {
return;
}
if (agency.bankrupt) {
res
.status(409)
.json({
error:
"Agency is bankrupt. Accept a Sponsor Restructuring Grant or Reset Agency first.",
});
res.status(409).json({
error:
"Agency is bankrupt. Accept a Sponsor Restructuring Grant or Reset Agency first.",
});
return;
}
const nowSim = getSimTime();
@ -115,11 +111,9 @@ export function registerMissionRoutes(router: Router): void {
return;
}
if ((agency.activeMissions ?? []).some((m) => !m.settled)) {
res
.status(409)
.json({
error: "A mission is already in flight. Wait for settlement.",
});
res.status(409).json({
error: "A mission is already in flight. Wait for settlement.",
});
return;
}
const contract = resolveContract(agency);
@ -149,11 +143,9 @@ export function registerMissionRoutes(router: Router): void {
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.`,
});
res.status(400).json({
error: `Design maturity is ${design.maturity.toUpperCase()}; advance to FLIGHT-READY in Rocket Builder.`,
});
return;
}
const insurancePremium =

View file

@ -1,3 +1,7 @@
// Export compliance evaluation entry point and context interface.
// Export compliance evaluation entry point, context interface, and read-only rule metadata.
export type { ComplianceEvalContext } from "./compliance/context.js";
export { evaluateCompliance } from "./compliance/evaluate.js";
export {
COMPLIANCE_RULES_META,
type ComplianceRuleMeta,
evaluateCompliance,
} from "./compliance/evaluate.js";

View file

@ -5,6 +5,8 @@ import type {
MaturityLevel,
RocketAssembly,
RocketDesign,
RuleCategory,
RuleSeverity,
} from "../types.js";
import type { ComplianceEvalContext, RuleDef } from "./context.js";
import { PROPULSION_RULES } from "./propulsionRules.js";
@ -19,6 +21,30 @@ const RULES: RuleDef[] = [
...CREW_ORBITAL_RULES,
];
export interface ComplianceRuleMeta {
id: string;
code: string;
category: RuleCategory;
title: string;
description: string;
severity: RuleSeverity;
dynamicSeverity: boolean;
waiverCost: number;
riskPenaltyPct: number;
}
export const COMPLIANCE_RULES_META: ComplianceRuleMeta[] = RULES.map((r) => ({
id: r.id,
code: r.code,
category: r.category,
title: r.title,
description: r.description,
severity: r.severity,
dynamicSeverity: !!r.getSeverity,
waiverCost: r.waiverCost,
riskPenaltyPct: r.riskPenaltyPct,
}));
export function evaluateCompliance(
design: RocketDesign,
assembly: RocketAssembly,