SGYWFTP/src/client/screens/missionConfig/prelaunch.ts
2026-11-15 13:02:03 +03:00

544 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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