cosmo/frontend/src/pages/RocketSimulator.tsx

751 lines
35 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, ChevronLeft, ChevronRight, 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,
FOLLOW_VIEW_YAW,
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) => {
// 长度按登记的长度比,底面与芯级一级底面齐平(与 3D 模型同一口径)
const boosterH = s1H * geo.boosterLengthRatio;
const boosterTop = s1Top + s1H - boosterH;
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 */
/* ------------------------------------------------------------------ */
/** 底栏左侧留给发动机示意图的显示预算:宽 380、高 104(与中间计时器那一列同高,不会把底栏顶高) */
const BANK_WIDTH = 380;
const BANK_HEIGHT = 104;
/**
* 留空系数:真实位置是紧挨着的(同圈相邻喷管几乎相切、助推器舱与芯级舱相切),
* 照原样画圆与圆就粘在一起,所以整体按同一系数缩小,间隙出现、圆之间的大小比例不变。
*/
const DOT_GAP = 0.78;
const BAY_GAP = 0.94;
/**
* 发动机仪表组:按俯视平面布置画芯级与每个助推器的发动机舱,芯级大圆在正中,
* 助推器小圆贴在左右两侧(每侧两枚就是上下堆叠、相邻相切),
* 圆的直径按「助推器直径 / 芯级直径」等比缩放(diameter_ratio)。
* 舱内点位取自 engineLayout:位置是真实的舱内平面位置,
* 直径就是该规格发动机喷管出口的真实直径,于是「机少的火箭是大发动机、
* 星舰二级外圈 3 台大机 + 内圈 3 台小机」在示意图上和箭体完全一致。
* 分组与位置取自 stage1EngineGroups,与 3D 模型的喷管/尾焰同源。
*/
function EngineBank({
label,
groups,
lit,
boostersLit = lit,
}: {
label: string;
groups: EngineGroup[];
lit: boolean;
/** 助推器在一级飞行中段先分离,分离后其发动机不再点火 */
boostersLit?: boolean;
}) {
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);
// 舱心位置以「芯级半径」为单位。3D 机位相对箭体有固定方位角(FOLLOW_VIEW_YAW),
// 俯视图里把它减掉,左右两组助推器才对称。
const cells = groups.map((group) => ({
group,
x: Math.cos(group.angle + FOLLOW_VIEW_YAW) * group.offset,
y: Math.sin(group.angle + FOLLOW_VIEW_YAW) * group.offset,
}));
const edges = cells.reduce((box, cell) => ({
left: Math.min(box.left, cell.x - cell.group.radius),
right: Math.max(box.right, cell.x + cell.group.radius),
top: Math.min(box.top, cell.y - cell.group.radius),
bottom: Math.max(box.bottom, cell.y + cell.group.radius),
}), { left: -1, right: 1, top: -1, bottom: 1 });
// base 是一个芯级半径对应的像素数:整组按包围盒缩放到预算内最大的尺寸
const base = Math.min(
BANK_WIDTH / (edges.right - edges.left),
BANK_HEIGHT / (edges.bottom - edges.top),
);
return (
<div className="sx-engine-bank" aria-label={`${label} ${firing}/${total} 台点火`}>
<div
className="sx-engine-plan"
style={{
width: `${(edges.right - edges.left) * base}px`,
height: `${(edges.bottom - edges.top) * base}px`,
}}
>
{cells.map(({ group, x, y }, index) => {
const unit = base * 2 * group.radius * BAY_GAP;
// engineLayout 的归一化坐标与喷管半径都以「舱半径 = 1」为单位,
// 圆环内壁正好就是一个舱半径,所以点位按内壁半径等比换算即可,
// 发动机再多也只会挤到圆环内壁上,不会画到舱外。
const inner = unit / 2 - 2;
const placements = engineLayout(group.engines, 1);
return (
<div
key={`${group.kind}-${index}`}
className={`sx-engine-unit ${isLit(group) ? 'lit' : ''}`}
style={
{
left: `${(x - edges.left) * base}px`,
top: `${(edges.bottom - y) * base}px`,
'--unit': `${unit}px`,
'--engine-radius': `${inner}px`,
} as CSSProperties
}
>
{placements.map((placement, dotIndex) => (
<i
key={dotIndex}
className="sx-engine-dot"
style={
{
'--dx': placement.x,
'--dy': placement.z,
'--dot': `${Math.max(3, placement.bellRadius * 2 * inner * DOT_GAP)}px`,
} 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);
/*
* 左右两块面板:离地升空后自动收起,把画面让给箭体。
* 手动开合记成 override,没动过把手就完全交给「是否已升空」决定,
* 于是自动收起之后手动展开不会被再次收起,按重置回到发射台又会展开。
* 两块面板共用一个开关:窄屏下左侧面板整块隐藏,分开记状态可能出现
* 「收起之后没有把手能打开」。
*/
const [panelsOverride, setPanelsOverride] = useState<boolean | null>(null);
const panelsOpen = panelsOverride ?? state.altitude <= 0;
const togglePanels = () => setPanelsOverride(!panelsOpen);
return (
<main className={`rocket-simulator-page${panelsOpen ? '' : ' is-collapsed'}`}>
<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, 4, 8].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>
{/* 收起后贴在屏幕边缘的把手:点一下展开,再点一下收起 */}
<button
className="sx-panel-tab sx-panel-tab--left"
onClick={togglePanels}
title={panelsOpen ? '收起运载器面板' : '展开运载器面板'}
aria-label={panelsOpen ? '收起运载器面板' : '展开运载器面板'}
aria-expanded={panelsOpen}
>
{panelsOpen ? <ChevronLeft size={15} /> : <ChevronRight size={15} />}
</button>
<button
className="sx-panel-tab sx-panel-tab--right"
onClick={togglePanels}
title={panelsOpen ? '收起遥测面板' : '展开遥测面板'}
aria-label={panelsOpen ? '收起遥测面板' : '展开遥测面板'}
aria-expanded={panelsOpen}
>
{panelsOpen ? <ChevronRight size={15} /> : <ChevronLeft size={15} />}
</button>
{/* 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} />;
}