cosmo/frontend/src/pages/RocketSimulator.tsx

693 lines
32 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { useEffect, useMemo, useState, type CSSProperties } from 'react';
import { ArrowLeft, Camera, ChevronDown, Clock3, Orbit, Pause, Play, RotateCcw, Rocket, ZoomIn, ZoomOut } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { fetchRocketConfigs } from '../features/rocket-simulator/api';
import { PHASE_LABELS, type FlightEvent, type FlightPhase, type RocketConfig } from '../features/rocket-simulator/types';
import { useRocketSimulation } from '../features/rocket-simulator/useRocketSimulation';
import { RocketFlightScene, type CameraMode } from '../features/rocket-simulator/RocketFlightScene';
import { TelemetryChart } from '../features/rocket-simulator/TelemetryChart';
import {
engineLayout,
layoutForRocket,
stage1EngineGroups,
stageGeometry,
type EngineGroup,
} from '../features/rocket-simulator/sceneMath';
import '../features/rocket-simulator/rocket-simulator.css';
import { resolveStage1 } from '../features/rocket-simulator/stageSplit';
/**
* Canonical flight milestones, in order. Each maps to an event id emitted by
* the physics loop. This single list is the SOLE source of truth for both the
* mission profile timeline and the phase status readout, so they can never
* disagree.
*/
const MILESTONES: Array<{ id: string; code: string; label: string }> = [
{ id: 'liftoff', code: 'LIFTOFF', label: '点火起飞' },
{ id: 'maxq', code: 'MAX-Q', label: '最大动压' },
{ id: 'booster-sep', code: 'BS', label: '助推器分离' },
{ id: 'meco', code: 'MECO', label: '一级关机' },
{ id: 'separation', code: 'SEP', label: '级间分离' },
{ id: 'ses1', code: 'SES-1', label: '二级点火' },
{ id: 'seco', code: 'SECO-1', label: '二级关机' },
{ id: 'orbit', code: 'ORBIT', label: '轨道注入' },
{ id: 'deploy', code: 'PAYLOAD', label: '载荷部署' },
];
/**
* 里程碑清单:只有捆绑助推器的火箭(长征五号一类)才显示助推器分离节点;
* 没有整流罩的火箭(星舰)末端节点是飞船入轨,而不是载荷分离。
*/
function milestonesFor(rocket: RocketConfig) {
const hasBoosters = layoutForRocket(rocket).layout === 'boosters';
const list = hasBoosters ? MILESTONES : MILESTONES.filter((item) => item.id !== 'booster-sep');
if (rocket.appearance?.fairing === false) {
return list.map((item) => (item.id === 'deploy' ? { ...item, code: 'SHIP', label: '飞船入轨' } : item));
}
return list;
}
function formatTime(seconds: number) {
const sign = seconds < 0 ? '-' : '+';
const abs = Math.abs(Math.floor(seconds));
const h = Math.floor(abs / 3600);
const m = Math.floor((abs % 3600) / 60);
const s = abs % 60;
const pad = (n: number) => String(n).padStart(2, '0');
return `T${sign}${h > 0 ? `${pad(h)}:` : ''}${pad(m)}:${pad(s)}`;
}
/* ------------------------------------------------------------------ */
/* Vehicle stack: the dashboard shows exactly what the 3D scene shows — */
/* full rocket → second stage after separation → payload at deploy. */
/* ------------------------------------------------------------------ */
type StackMode = 'full' | 'stage2' | 'payload';
function stackModeFor(phase: FlightPhase): StackMode {
if (phase === 'ready' || phase === 'stage1_burn' || phase === 'stage1_cutoff') return 'full';
if (phase === 'payload_deploy' || phase === 'mission_complete') return 'payload';
return 'stage2';
}
const STACK_MODE_LABEL: Record<StackMode, { code: string; zh: string; detail: string }> = {
full: { code: 'FULL STACK', zh: '全箭组合体', detail: 'S1 + S2 + PAYLOAD · 待命' },
stage2: { code: 'STAGE 2', zh: '二级飞行', detail: 'S2 + PAYLOAD · 一级已分离' },
payload: { code: 'PAYLOAD', zh: '载荷部署', detail: '载荷分离 · 太阳翼展开' },
};
/** 无整流罩构型(星舰)的二级本身就是飞船,末端状态是飞船入轨。 */
const SHIP_MODE_LABEL: { code: string; zh: string; detail: string } = {
code: 'SPACECRAFT', zh: '飞船入轨', detail: '二级即飞船 · 无载荷分离',
};
/**
* Vertical schematic of the launch vehicle. Height proportions come from the
* real config (stageGeometry) — 箭体粗细、整流罩形状与发动机数量都与 3D 场景
* 使用同一套数据推导,因此示意图与真实火箭信息、三维模型三者始终一致。
* 图形状态由模式类(full / stage2 / payload)驱动,CSS 负责分离动画。
*/
function StackDiagram({ rocket }: { rocket: RocketConfig }) {
const geo = useMemo(() => stageGeometry(rocket), [rocket]);
const TOP = 16;
const BOTTOM = 212;
const CX = 58;
const scale = (BOTTOM - TOP) / geo.totalHeight;
const r1 = Math.max(8, geo.radius * scale);
const r2 = r1 * 0.97;
// 无整流罩构型的头锥与二级等直径,不会比箭体更细
const rf = geo.fairing ? Math.max(r1 + 1.5, geo.fairingRadius * scale) : r2;
const fairingH = geo.fairingHeight * scale;
const coneH = geo.fairingConeHeight * scale;
const s2H = geo.stage2Height * scale;
const interH = Math.max(geo.interstageHeight * scale, 4);
const s1H = geo.stage1Height * scale;
const fairingBottom = TOP + fairingH;
const coneTop = TOP;
const barrelTop = TOP + coneH;
const s2Top = fairingBottom;
const interTop = s2Top + s2H;
const s1Top = interTop + interH;
const engineY = s1Top + s1H;
const padY = engineY + 14;
const metal = '#aeb7bd';
/** 侧视图中的发动机:把发动机舱布局投影到水平方向,按位置去重后绘制。 */
const engineBells = (count: number, radius: number, baseY: number) => {
const drawn: Array<{ x: number; width: number }> = [];
engineLayout(count, radius).forEach((placement) => {
const x = CX + placement.x * scale;
if (drawn.some((item) => Math.abs(item.x - x) < placement.bellRadius * scale * 0.9)) return;
drawn.push({ x, width: Math.max(2.6, placement.bellRadius * 2 * scale) });
});
return drawn.map((bell, index) => (
<path
key={index}
d={`M ${bell.x - bell.width / 2} ${baseY} l 0 6 l ${bell.width * 0.2} 2.4 l ${bell.width * 0.6} 0 l ${bell.width * 0.2} -2.4 l 0 -6 Z`}
fill="#39414a"
/>
));
};
return (
<svg className="sx-stack" viewBox="0 0 120 240" role="img" aria-label="运载器结构示意图">
{/* measurement rail */}
<line className="sx-stack-axis" x1={CX} y1={4} x2={CX} y2={padY - 2} />
<line className="sx-stack-grid" x1={14} y1={padY} x2={102} y2={padY} />
<text className="sx-stack-dim" x={14} y={padY - 5}>{rocket.height_m.toFixed(1)} M</text>
<text className="sx-stack-dim" x={72} y={padY - 5}>Ø {rocket.diameter_m.toFixed(1)} M</text>
<line className="sx-stack-seam" x1={12} y1={s2Top} x2={104} y2={s2Top} />
<line className="sx-stack-seam" x1={12} y1={interTop} x2={104} y2={interTop} />
<line className="sx-stack-seam" x1={12} y1={s1Top} x2={104} y2={s1Top} />
{/* 助推器 / 侧芯级:按登记的直径比例画在芯级两侧(与芯级相切) */}
{geo.layout === 'boosters' &&
[-1, 1].map((direction) => {
const boosterH = s1H * 0.86;
const boosterTop = s1Top + s1H * 0.1;
const br = r1 * geo.boosterDiameterRatio;
const bx = CX + direction * (r1 + br);
return (
<g key={direction} className="sx-stack-booster">
<rect x={bx - br} y={boosterTop} width={br * 2} height={boosterH} rx={1.6} fill="#dfe4e8" className="sx-stack-body" />
<path
d={`M ${bx - br} ${boosterTop} Q ${bx} ${boosterTop - br * 2.6} ${bx + br} ${boosterTop} Z`}
fill="#b9c2c8"
/>
<rect x={bx - br} y={boosterTop + boosterH * 0.08} width={br * 2} height={boosterH * 0.06} fill="#c8d0d6" />
{/* 栅格翼:助推器自己可回收才画,贴在顶部两侧 */}
{geo.boosterRecoverable &&
[-1, 1].map((side) => {
const w = Math.max(3, br * 1.2);
const h = Math.max(2, br * 0.8);
return (
<rect
key={`fin-${side}`}
x={side < 0 ? bx - br - w : bx + br}
y={boosterTop + boosterH * 0.04}
width={w}
height={h}
rx={0.6}
fill="#39414a"
/>
);
})}
{engineBells(geo.enginesPerBooster, geo.radius * geo.boosterDiameterRatio * 1.08, boosterTop + boosterH)}
</g>
);
})}
{/* Stage 1 — drops away after separation */}
<g className="sx-stack-s1">
<rect x={CX - r1} y={s1Top} width={r1 * 2} height={s1H} rx={2.5} fill={rocket.color} className="sx-stack-body" />
<rect x={CX - r1} y={s1Top + s1H * 0.9} width={r1 * 2} height={s1H * 0.1} fill="#14171a" />
<rect x={CX - r1} y={s1Top + s1H * 0.06} width={r1 * 2} height={s1H * 0.05} fill="#2b3138" />
<rect x={CX + r1 - 2.4} y={s1Top + s1H * 0.12} width={2.4} height={s1H * 0.78} fill="#20262c" />
<rect x={CX - r1 - 1} y={engineY} width={r1 * 2 + 2} height={5} rx={2} fill="#101418" />
{/* 栅格翼:一级登记为可回收才画 */}
{geo.coreRecoverable && [-1, 1].map((direction) => {
const x = CX + direction * r1;
const y = s1Top + s1H * 0.06;
return (
<g key={direction}>
<path d={`M ${x} ${y} l ${direction * 11} 0 l 0 11 l ${-direction * 11} 0 Z`} fill="#39414a" />
{[3.5, 7].map((offset) => (
<line
key={offset}
x1={x + direction * offset}
y1={y + 0.8}
x2={x + direction * offset}
y2={y + 10.2}
stroke="#8f9aa3"
strokeWidth={0.7}
/>
))}
<line x1={x + direction * 0.8} y1={y + 5.5} x2={x + direction * 10.2} y2={y + 5.5} stroke="#8f9aa3" strokeWidth={0.7} />
</g>
);
})}
{engineBells(geo.layout === 'boosters' ? geo.coreEngines : geo.stage1Engines, geo.radius, engineY + 5)}
</g>
{/* Upper stack (interstage + S2) */}
<g className="sx-stack-s2">
<rect x={CX - r2} y={interTop} width={r2 * 2} height={interH} fill="#1c2228" />
<rect x={CX - r2} y={s2Top} width={r2 * 2} height={s2H} rx={2} fill={rocket.color} className="sx-stack-body" />
<rect x={CX - r2} y={s2Top + s2H * 0.07} width={r2 * 2} height={s2H * 0.07} fill="#2b3138" />
<rect x={CX - r2 - 0.8} y={s2Top + s2H} width={r2 * 2 + 1.6} height={3.4} fill="#101418" />
{engineBells(geo.stage2Engines, geo.radius * 0.97, s2Top + s2H + 3.4)}
</g>
{/* 头锥 / 整流罩:有整流罩时为两瓣卵形罩,载荷部署时分离;无整流罩时为飞船头锥 */}
{geo.fairing ? (
<g className="sx-stack-fairing">
<path
className="sx-fairing sx-fairing-left"
d={`M ${CX} ${fairingBottom} L ${CX - rf} ${fairingBottom} L ${CX - rf} ${barrelTop} Q ${CX - rf * 0.92} ${(barrelTop + coneTop) / 2}, ${CX} ${coneTop} Z`}
fill={metal}
/>
<path
className="sx-fairing sx-fairing-right"
d={`M ${CX} ${fairingBottom} L ${CX + rf} ${fairingBottom} L ${CX + rf} ${barrelTop} Q ${CX + rf * 0.92} ${(barrelTop + coneTop) / 2}, ${CX} ${coneTop} Z`}
fill={metal}
/>
<line className="sx-stack-seam" x1={CX} y1={coneTop} x2={CX} y2={fairingBottom} />
<line className="sx-stack-seam" x1={12} y1={barrelTop} x2={104} y2={barrelTop} />
</g>
) : (
<g className="sx-stack-nose">
<path
d={`M ${CX - rf} ${fairingBottom} L ${CX - rf} ${barrelTop} Q ${CX - rf} ${coneTop + rf}, ${CX} ${coneTop} Q ${CX + rf} ${coneTop + rf}, ${CX + rf} ${barrelTop} L ${CX + rf} ${fairingBottom} Z`}
fill={metal}
/>
{/* 前 / 后襟翼 */}
{[-1, 1].map((direction) => (
<g key={direction}>
<rect x={CX + direction * rf - (direction < 0 ? 5 : 0)} y={barrelTop + s2H * 0.04} width={5} height={s2H * 0.1} fill="#8f989f" />
<rect x={CX + direction * rf - (direction < 0 ? 7 : 0)} y={s2Top + s2H * 0.82} width={7} height={s2H * 0.16} fill="#8f989f" />
</g>
))}
</g>
)}
{/* Payload satellite — revealed at deploy */}
{geo.fairing && (
<g className="sx-stack-payload">
<circle cx={CX} cy={barrelTop - coneH * 0.2} r={3.4} fill="#e8ece9" />
<rect x={CX - 8} y={barrelTop + coneH * 0.04} width={16} height={11} rx={1.5} fill="#d8b25c" />
<g className="sx-stack-panel l">
<rect x={CX - 34} y={barrelTop + coneH * 0.08} width={25} height={5.5} rx={1} fill="#1d3f68" />
</g>
<g className="sx-stack-panel r">
<rect x={CX + 9} y={barrelTop + coneH * 0.08} width={25} height={5.5} rx={1} fill="#1d3f68" />
</g>
</g>
)}
</svg>
);
}
function VehiclePanel({ rocket, mode, stage1FuelPct, stage2FuelPct }: { rocket: RocketConfig; mode: StackMode; stage1FuelPct: number; stage2FuelPct: number }) {
const meta = mode === 'payload' && rocket.appearance?.fairing === false ? SHIP_MODE_LABEL : STACK_MODE_LABEL[mode];
const layout = layoutForRocket(rocket);
// 芯级与助推器各自登记自己的机数,规格里分开写清各是几台
const stage1Engines = layout.layout === 'boosters'
? `${layout.coreEngines}+${layout.boosterCount}×${layout.enginesPerBooster}`
: `${layout.coreEngines}`;
// 只登记了构型的助推器不参与物理,起飞推力仍按一级整段计
const split = resolveStage1(rocket);
const totalThrustMN = (split.coreThrustN + (split.boosters?.thrustN ?? 0)) / 1e6;
return (
<div className="sx-vehicle">
<div className="sx-panel-title"><span>VEHICLE</span><b>运载器状态</b></div>
<div className={`sx-vehicle-body sx-stack--${mode}`}>
<StackDiagram rocket={rocket} />
<div className="sx-vehicle-side">
<div className="sx-stack-caption">
<span>{meta.code}</span>
<strong>{meta.zh}</strong>
<small>{meta.detail}</small>
</div>
<div className="sx-spec">
<div className="sx-spec-row"><span>一级</span><b className="sx-spec-name">{rocket.stage_1.name}</b><em>{stage1FuelPct.toFixed(0)}%</em></div>
<div className="sx-spec-row"><span>二级</span><b className="sx-spec-name">{rocket.stage_2.name}</b><em>{stage2FuelPct.toFixed(0)}%</em></div>
<div className="sx-spec-divider" />
<div className="sx-spec-row"><span>箭体尺寸</span><b>{rocket.height_m.toFixed(1)} × Ø{rocket.diameter_m.toFixed(1)} m</b></div>
<div className="sx-spec-row"><span>发动机</span><b>{stage1Engines} + {rocket.stage_2.engine_count} 台</b></div>
<div className="sx-spec-row"><span>起飞推力</span><b>{totalThrustMN.toFixed(2)} MN</b></div>
<div className="sx-spec-row"><span>二级推力</span><b>{(rocket.stage_2.max_thrust_n / 1e6).toFixed(2)} MN</b></div>
<div className="sx-spec-row"><span>载荷</span><b>{(rocket.payload_mass_kg / 1000).toFixed(1)} t</b></div>
<div className="sx-spec-row"><span>目标轨道</span><b>{rocket.target_orbit_km} km</b></div>
{rocket.manufacturer ? (
<div className="sx-spec-row"><span>制造方</span><b className="sx-spec-name">{rocket.manufacturer}</b></div>
) : null}
</div>
</div>
</div>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Mission timeline: the mission clock progress bar IS the mission */
/* profile — every phase sits on the bar at its own node, so the */
/* progress readout and the phase list can never drift apart. */
/* ------------------------------------------------------------------ */
function MissionTimeline({
events,
next,
running,
milestones,
progress,
}: {
events: FlightEvent[];
next?: { id: string; code: string; label: string };
running: boolean;
milestones: Array<{ id: string; code: string; label: string }>;
progress: number;
}) {
const eventTime = (id: string) => events.find((event) => event.id === id)?.time ?? null;
return (
<div className="sx-timeline">
<div className="sx-timeline-track">
<div className="sx-timeline-line"><i style={{ width: `${progress}%` }} /></div>
{milestones.map((m, index) => {
const time = eventTime(m.id);
const reached = time !== null;
const isNext = next?.id === m.id && running;
const at = `${((index + 0.5) / milestones.length) * 100}%`;
return (
<span
key={m.id}
className={`sx-timeline-node ${reached ? 'reached' : ''} ${isNext ? 'next' : ''}`}
style={{ left: at }}
title={`${m.code} ${m.label} · ${reached ? formatTime(time as number).replace('T+', '+') : '待执行'}`}
>
<em />
<b>{m.code}</b>
<span>{m.label}</span>
<time>{reached ? formatTime(time as number).replace('T+', '+') : '--:--'}</time>
</span>
);
})}
</div>
<span className="sx-timeline-pct">{progress.toFixed(0)}%</span>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Flight data panel (big green monospace numbers) */
/* ------------------------------------------------------------------ */
function FlightData({ state, history, totalFuelPct, stage1FuelPct, stage2FuelPct }: {
state: ReturnType<typeof useRocketSimulation>['state'];
history: ReturnType<typeof useRocketSimulation>['state']['history'];
totalFuelPct: number;
stage1FuelPct: number;
stage2FuelPct: number;
}) {
return (
<div className="sx-data">
<div className="sx-panel-title"><span>FLIGHT DATA</span><b>飞行遥测</b></div>
<div className="sx-data-grid">
<div className="sx-data-row hero">
<span>ALTITUDE</span>
<div><strong>{(state.altitude / 1000).toFixed(1)}</strong><em>KM</em></div>
</div>
<div className="sx-data-row hero">
<span>VELOCITY</span>
<div><strong>{(state.velocity * 3.6).toFixed(0)}</strong><em>KM/H</em></div>
</div>
<div className="sx-data-row">
<span>ACCELERATION</span>
<div><strong>{(state.acceleration / 9.80665).toFixed(2)}</strong><em>G</em></div>
</div>
<div className="sx-data-row">
<span>DYNAMIC PRESS</span>
<div><strong>{(state.dynamicPressure / 1000).toFixed(1)}</strong><em>KPA</em></div>
</div>
<div className="sx-data-row">
<span>DOWNRANGE</span>
<div><strong>{(state.downrange / 1000).toFixed(1)}</strong><em>KM</em></div>
</div>
<div className="sx-data-row">
<span>PITCH</span>
<div><strong>{state.pitch.toFixed(0)}</strong><em>°</em></div>
</div>
</div>
<div className="sx-chart-wrap">
<div className="sx-chart-title"><span>ALT / VEL TRACE</span><b>高度 · 速度</b></div>
<TelemetryChart history={history} />
</div>
<div className="sx-fuel">
<div className="sx-fuel-head"><span>推进剂余量 / PROPELLANT</span><b>{totalFuelPct.toFixed(0)}%</b></div>
<div className="sx-fuel-row"><span>S1</span><div className="sx-fuel-track"><i className="s1" style={{ width: `${stage1FuelPct}%` }} /></div><b>{stage1FuelPct.toFixed(0)}%</b></div>
<div className="sx-fuel-row"><span>S2</span><div className="sx-fuel-track"><i className="s2" style={{ width: `${stage2FuelPct}%` }} /></div><b>{stage2FuelPct.toFixed(0)}%</b></div>
<div className="sx-fuel-total-row"><span>总推进剂</span><b>{totalFuelPct.toFixed(0)}%</b></div>
</div>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Small mission-control widgets */
/* ------------------------------------------------------------------ */
/**
* 仪表组的排列顺序:芯级放在正中,助推器平均分成左右两组挂在两侧,
* 与 3D 箭体的 boosterAngle(左右均分)同一口径,扫一眼就能对上号。
* 只调整显示顺序,不改变每组的数量与大小。
*/
function bankOrder(groups: EngineGroup[]): EngineGroup[] {
const strapped = groups.filter((group) => group.kind === 'booster');
if (strapped.length < 2) return groups;
const others = groups.filter((group) => group.kind !== 'booster');
const leftCount = Math.floor(strapped.length / 2);
return [...strapped.slice(0, leftCount), ...others, ...strapped.slice(leftCount)];
}
/**
* 发动机仪表组:芯级与每个助推器各自画一个圆环,助推器圆的直径按
* 「助推器直径 / 芯级直径」等比缩放,全部排在同一行、底部对齐,
* 这样一眼就能看出几个助推器、每个舱里几台机、现在哪些在点火。
* 分组取自 stage1EngineGroups,与 3D 模型的喷管/尾焰同源。
*/
function EngineBank({
label,
groups,
lit,
boostersLit = lit,
}: {
label: string;
groups: EngineGroup[];
lit: boolean;
/** 助推器在一级飞行中段先分离,分离后其发动机不再点火 */
boostersLit?: boolean;
}) {
// 芯级居中、助推器左右均分,只影响这一行的显示顺序
const units = bankOrder(groups);
const isLit = (group: EngineGroup) => (group.kind === 'core' ? lit : boostersLit);
const total = groups.reduce((sum, group) => sum + group.engines, 0);
const firing = groups.filter(isLit).reduce((sum, group) => sum + group.engines, 0);
// 直径以芯级为基准(radius = 1),按左侧栏可用宽度整体缩放,四助推器也放得下
const gap = 10;
const diameterSum = units.reduce((sum, group) => sum + group.radius, 0);
const base = Math.max(18, Math.min(58, (268 - gap * (units.length - 1)) / diameterSum));
return (
<div className="sx-engine-bank" aria-label={`${label} ${firing}/${total} 台点火`}>
<div className="sx-engine-row">
{units.map((group, index) => {
const unit = base * group.radius;
// 机数多的舱室缩小点位,避免十几个点糊成一团
const orbit = unit * 0.28;
const dot = group.engines > 4
? Math.min(8, Math.max(3, (Math.PI * 2 * orbit) / (group.engines * 1.7)))
: Math.min(9, Math.max(4, unit * 0.2));
return (
<div
key={`${group.kind}-${index}`}
className={`sx-engine-unit ${isLit(group) ? 'lit' : ''}`}
style={
{
'--unit': `${unit}px`,
'--engine-radius': `${orbit}px`,
'--dot': `${dot}px`,
} as CSSProperties
}
>
{engineLayout(group.engines, 1).map((placement, dotIndex) => (
<i
key={dotIndex}
className="sx-engine-dot"
style={{ '--dx': placement.x, '--dy': placement.z } as CSSProperties}
/>
))}
</div>
);
})}
</div>
</div>
);
}
function AttitudeGauge({ pitch }: { pitch: number }) {
const vehicleRotation = 45 - pitch;
return (
<div className="sx-attitude-gauge" aria-label={`火箭俯仰角 ${pitch.toFixed(0)} 度`}>
<div className="sx-attitude-dial">
<i className="sx-attitude-axis horizontal" />
<i className="sx-attitude-axis vertical" />
<div className="sx-attitude-vehicle" style={{ transform: `translate(-50%, -50%) rotate(${vehicleRotation}deg)` }}>
<Rocket size={24} strokeWidth={1.6} />
</div>
</div>
<span>PITCH</span>
<strong>{pitch.toFixed(0)}°</strong>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Page */
/* ------------------------------------------------------------------ */
function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
const navigate = useNavigate();
const [selectedCode, setSelectedCode] = useState(rockets[0].code);
const [cameraMode, setCameraMode] = useState<CameraMode>('follow');
const [viewScale, setViewScale] = useState(100);
const [viewScaleResetTrigger, setViewScaleResetTrigger] = useState(0);
const rocket = rockets.find((item) => item.code === selectedCode) || rockets[0];
const { state, toggle, reset, speed, setSpeed } = useRocketSimulation(rocket);
// 一级推进剂的起点是「芯级 + 助推器」的合计(与 initialState 同一口径),
// 助推器烧完先分离,余量也随之归零,因此 S1% 会在那一刻下一个台阶
const stage1FuelKg = rocket.stage_1.fuel_mass_kg + (resolveStage1(rocket).boosters?.fuelKg ?? 0);
const totalFuel = stage1FuelKg + rocket.stage_2.fuel_mass_kg;
const remainingFuel = state.stage1Fuel + state.stage2Fuel;
const stage1FuelPct = Math.max(0, state.stage1Fuel / stage1FuelKg * 100);
const stage2FuelPct = Math.max(0, state.stage2Fuel / rocket.stage_2.fuel_mass_kg * 100);
const totalFuelPct = Math.max(0, remainingFuel / totalFuel * 100);
const eventTime = (id: string) => state.events.find((event) => event.id === id)?.time ?? null;
const milestones = useMemo(() => milestonesFor(rocket), [rocket]);
const reachedCount = milestones.filter((m) => eventTime(m.id) !== null).length;
const progress = reachedCount / milestones.length * 100;
const nextMilestone = milestones.find((m) => eventTime(m.id) === null);
const stackMode = stackModeFor(state.phase);
// 仪表盘发动机示意:一级按芯级 + 助推器分组,二级只有芯级一组
const stage1Groups = useMemo(() => stage1EngineGroups(layoutForRocket(rocket)), [rocket]);
const stage2Groups: EngineGroup[] = [
{ kind: 'core', engines: Math.max(1, Math.round(rocket.stage_2.engine_count)), radius: 1, offset: 0, angle: 0 },
];
const stage: 1 | 2 = ['separating', 'stage2_ignition', 'stage2_burn', 'orbit', 'payload_deploy', 'mission_complete'].includes(state.phase) ? 2 : 1;
const stageFiring = stage === 1
? state.phase === 'stage1_burn'
: state.phase === 'stage2_ignition' || state.phase === 'stage2_burn';
const launchLabel = state.phase === 'mission_complete'
? '重新模拟'
: state.isRunning
? '暂停'
: state.phase === 'ready'
? '执行点火'
: '继续';
const clockText = state.phase === 'ready' && !state.isRunning ? 'T-00:00:00' : formatTime(state.time);
return (
<main className="rocket-simulator-page">
<RocketFlightScene
rocket={rocket}
state={state}
cameraMode={cameraMode}
viewScale={viewScale}
viewScaleResetTrigger={viewScaleResetTrigger}
onViewScaleChange={setViewScale}
/>
{/* Top bar: brand + mission status + vehicle selector + view controls */}
<header className="sx-topbar">
<button className="sx-icon-btn" onClick={() => navigate('/')} title="返回首页" aria-label="返回首页"><ArrowLeft size={18} /></button>
<div className="sx-brand"><Rocket size={18} /><div><strong>COSMO LAUNCH</strong><span>{rocket.name_zh || rocket.name} · {rocket.name}</span></div></div>
<div className="sx-mission-status">
<span className={state.isRunning ? 'sx-live' : ''} />
<div><small>MISSION STATUS</small><strong>{PHASE_LABELS[state.phase as FlightPhase]}</strong></div>
</div>
<div className="sx-topbar-right">
<label className="sx-select">
<span>运载器 / VEHICLE</span>
<div><select value={selectedCode} onChange={(event) => setSelectedCode(event.target.value)}>
{rockets.map((item) => <option key={item.code} value={item.code}>{item.name_zh || item.name}</option>)}
</select><ChevronDown size={13} /></div>
</label>
{/* 完整任务约 9 分钟,提供三段倍速开关便于观察分离、入轨与载荷部署 */}
<label className="sx-select sx-select--speed">
<span>倍速 / SPEED</span>
<div className="sx-speed-switch" role="group" aria-label="模拟倍速">
{[1, 2, 4].map((value) => (
<button
key={value}
type="button"
className={speed === value ? 'active' : ''}
onClick={() => setSpeed(value)}
aria-pressed={speed === value}
title={`${value} 倍速播放`}
>
{value}×
</button>
))}
</div>
</label>
<div className="sx-seg" role="group" aria-label="视角模式">
<button className={cameraMode === 'follow' ? 'active' : ''} onClick={() => setCameraMode('follow')} title="跟随视角"><Camera size={14} />跟随</button>
<button className={cameraMode === 'global' ? 'active' : ''} onClick={() => setCameraMode('global')} title="全局视角"><Orbit size={14} />全局</button>
</div>
<label className="sx-camera-slider" title="调整画面缩放比例">
<ZoomOut size={13} />
<input aria-label="画面缩放比例" type="range" min="50" max="250" step="5" value={viewScale} onChange={(event) => { setViewScale(Number(event.target.value)); setViewScaleResetTrigger((value) => value + 1); }} />
<span>{viewScale}%</span>
<ZoomIn size={13} />
</label>
</div>
</header>
{/* Left: mission profile + vehicle stack */}
<aside className="sx-left">
<VehiclePanel rocket={rocket} mode={stackMode} stage1FuelPct={stage1FuelPct} stage2FuelPct={stage2FuelPct} />
</aside>
{/* Right: flight telemetry */}
<aside className="sx-right">
<FlightData state={state} history={state.history} totalFuelPct={totalFuelPct} stage1FuelPct={stage1FuelPct} stage2FuelPct={stage2FuelPct} />
</aside>
{/* Bottom: engine bank + mission clock + progress + attitude + controls */}
<div className="sx-bottom">
<EngineBank
label={stage === 1 ? '一级发动机' : '二级发动机'}
groups={stage === 1 ? stage1Groups : stage2Groups}
lit={stageFiring}
boostersLit={stageFiring && eventTime('booster-sep') === null}
/>
<div className="sx-bottom-center">
<div className="sx-clock">{clockText}</div>
<div className="sx-realtime"><Clock3 size={12} />MISSION TIME · REAL TIME</div>
<MissionTimeline
events={state.events}
next={nextMilestone}
running={state.isRunning}
milestones={milestones}
progress={progress}
/>
</div>
<div className="sx-bottom-right">
<AttitudeGauge pitch={state.pitch} />
<div className="sx-controls">
<button className="sx-icon-btn" onClick={reset} title="重置" aria-label="重置"><RotateCcw size={16} /></button>
<button className="sx-launch" onClick={toggle}>{state.isRunning ? <Pause size={15} /> : <Play size={15} />}{launchLabel}</button>
</div>
</div>
</div>
</main>
);
}
export function RocketSimulator() {
const [rockets, setRockets] = useState<RocketConfig[]>([]);
const [error, setError] = useState('');
useEffect(() => {
fetchRocketConfigs().then(setRockets).catch(() => setError('火箭配置加载失败,请确认数据库升级脚本已执行。'));
}, []);
// 管理端改完参数、后端启动补完助推器口径之后,本页不会自己发现数据变了:
// 箭体外形与仪表圈都按打开页面时取到的直径比绘制,于是管理端明明填了 1,
// 这里还按旧值画。切回本页时静默重取一次,取到空列表则维持原状。
useEffect(() => {
const refetch = () => {
if (document.visibilityState !== 'visible') return;
fetchRocketConfigs()
.then((next) => { if (next.length > 0) setRockets(next); })
.catch(() => undefined);
};
document.addEventListener('visibilitychange', refetch);
return () => document.removeEventListener('visibilitychange', refetch);
}, []);
if (error) return <div className="rocket-page-message"><Rocket size={36} /><strong>{error}</strong><a href="/">返回首页</a></div>;
if (rockets.length === 0) return <div className="rocket-page-message"><Rocket className="loading-rocket" size={36} /><strong>正在载入发射任务</strong></div>;
return <RocketMission rockets={rockets} />;
}