火箭外形改为显式外观配置,修正星舰/电子号/猎鹰重型构型

- rocket_configs 新增 appearance(JSONB):助推器数量/每台发动机数/直径比/栅格翼/有无整流罩,留空仍按原启发式推断
- 预置型号补写外观并新增启动幂等回填;列不存在时跳过,避免服务起不来
- 3D 与示意图按构型绘制:猎鹰重型三根等直径芯级、星舰等径头锥+襟翼且无整流罩、电子号整流罩不再过大
- 管理端火箭表单新增「外观构型(可选)」页签
- deploy.sh 在补列后重启 backend,使启动期数据回填生效
main
mula.liu 2026-10-08 06:51:44 +08:00
parent a19b78be3b
commit 54752484cc
11 changed files with 398 additions and 130 deletions

View File

@ -26,6 +26,16 @@ class RocketStage(BaseModel):
length_ratio: float = Field(gt=0, le=1)
class RocketAppearance(BaseModel):
"""3D 外观构型(可选)。留空的字段由前端按公开资料通用规律推断。"""
booster_count: int | None = Field(default=None, ge=0, le=8, description="捆绑助推器/侧芯级数量,0 为单芯级")
engines_per_booster: int | None = Field(default=None, ge=1, le=33, description="每个助推器的发动机数量")
booster_diameter_ratio: float | None = Field(default=None, gt=0, le=1, description="助推器直径 / 芯级直径")
grid_fins: bool | None = Field(default=None, description="一级顶部栅格翼(回收构型)")
fairing: bool | None = Field(default=None, description="是否有载荷整流罩;false 表示二级自身带头锥与襟翼(星舰)")
class RocketBase(BaseModel):
code: RocketCode
name: str = Field(min_length=1, max_length=100)
@ -48,6 +58,7 @@ class RocketBase(BaseModel):
second_stage_ignition_delay_seconds: float = Field(ge=0, le=30, default=1)
stage_1: RocketStage
stage_2: RocketStage
appearance: RocketAppearance | None = None
is_active: bool = True
sort_order: int = 0
@ -83,6 +94,7 @@ class RocketUpdate(BaseModel):
second_stage_ignition_delay_seconds: float | None = Field(default=None, ge=0, le=30)
stage_1: RocketStage | None = None
stage_2: RocketStage | None = None
appearance: RocketAppearance | None = None
is_active: bool | None = None
sort_order: int | None = None
@ -102,7 +114,7 @@ class RocketResponse(RocketBase):
def rocket_values(data: RocketCreate | RocketUpdate, *, exclude_unset: bool = False) -> dict:
values = data.model_dump(exclude_unset=exclude_unset)
for key in ("stage_1", "stage_2"):
for key in ("stage_1", "stage_2", "appearance"):
if key in values and values[key] is not None:
values[key] = dict(values[key])
return values

View File

@ -82,12 +82,14 @@ async def lifespan(app: FastAPI):
# Initialize default system settings
from app.database import AsyncSessionLocal
from app.services.system_settings_service import system_settings_service
from app.services.rocket_preset_service import ensure_high_frequency_rockets
from app.services.rocket_preset_service import ensure_high_frequency_rockets, ensure_rocket_appearance
from app.services.rocket_event_service import ensure_launch_event_job
async with AsyncSessionLocal() as db:
await system_settings_service.initialize_default_settings(db)
# 预置高频发射火箭型号 + 发射事件同步定时任务
added_rockets = await ensure_high_frequency_rockets(db)
# 早已入库的预置型号补写外观构型(管理端填过的不动)
await ensure_rocket_appearance(db)
await ensure_launch_event_job(db)
await db.commit()
logger.info("✓ Default system settings initialized")

View File

@ -32,6 +32,7 @@ class RocketConfig(Base):
second_stage_ignition_delay_seconds = Column(Double, nullable=False, default=1)
stage_1 = Column(JSONB, nullable=False)
stage_2 = Column(JSONB, nullable=False)
appearance = Column(JSONB, nullable=True)
is_active = Column(Boolean, nullable=False, default=True, index=True)
sort_order = Column(Integer, nullable=False, default=0)
created_at = Column(TIMESTAMP, server_default=func.now())

View File

@ -11,7 +11,7 @@ stage_1 沿用库里既有约定:捆绑助推器的发动机数量与推力并
import logging
from typing import Any
from sqlalchemy import func, select
from sqlalchemy import func, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.db import RocketConfig
@ -57,6 +57,11 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 6,
"length_ratio": 0.42,
},
"appearance": {
"booster_count": 0,
"grid_fins": True,
"fairing": False,
},
},
{
"code": "electron",
@ -96,6 +101,10 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 1,
"length_ratio": 0.34,
},
"appearance": {
"booster_count": 0,
"grid_fins": False,
},
},
{
"code": "long-march-2f",
@ -135,6 +144,12 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 1,
"length_ratio": 0.4,
},
"appearance": {
"booster_count": 4,
"engines_per_booster": 1,
"booster_diameter_ratio": 0.67,
"grid_fins": False,
},
},
{
"code": "long-march-7",
@ -174,6 +189,12 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 2,
"length_ratio": 0.38,
},
"appearance": {
"booster_count": 4,
"engines_per_booster": 2,
"booster_diameter_ratio": 0.67,
"grid_fins": False,
},
},
{
"code": "long-march-6a",
@ -213,6 +234,12 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 2,
"length_ratio": 0.4,
},
"appearance": {
"booster_count": 4,
"engines_per_booster": 2,
"booster_diameter_ratio": 0.79,
"grid_fins": False,
},
},
{
"code": "long-march-8",
@ -252,6 +279,12 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 2,
"length_ratio": 0.4,
},
"appearance": {
"booster_count": 2,
"engines_per_booster": 2,
"booster_diameter_ratio": 0.67,
"grid_fins": False,
},
},
{
"code": "falcon-heavy",
@ -291,10 +324,48 @@ HIGH_FREQUENCY_ROCKETS: list[dict[str, Any]] = [
"engine_count": 1,
"length_ratio": 0.35,
},
"appearance": {
"booster_count": 2,
"engines_per_booster": 9,
"booster_diameter_ratio": 1.0,
"grid_fins": True,
},
},
]
async def ensure_rocket_appearance(db: AsyncSession) -> list[str]:
"""为已存在的预置型号补写外观构型。
预置逻辑只补插缺失的型号,早已入库的型号不会带上 appearance,因此这里做一次
幂等回填:仅处理库里 appearance 仍为空的行,管理端填过的值一律不动。
"""
presets = {p["code"]: p["appearance"] for p in HIGH_FREQUENCY_ROCKETS if p.get("appearance")}
# 部署时 up -d 早于 upgrade_db.py,列可能还没加上;这里跳过而不是让服务起不来
column = await db.execute(
text("SELECT 1 FROM information_schema.columns "
"WHERE table_name = 'rocket_configs' AND column_name = 'appearance'")
)
if column.first() is None:
logger.warning("rocket_configs.appearance 列不存在,跳过外观构型回填(执行 upgrade_db.py --apply 后重启生效)")
return []
result = await db.execute(
select(RocketConfig.code).where(RocketConfig.appearance.is_(None), RocketConfig.code.in_(presets))
)
codes = list(result.scalars().all())
updated: list[str] = []
for code in codes:
rocket = (await db.execute(select(RocketConfig).where(RocketConfig.code == code))).scalar_one()
rocket.appearance = dict(presets[code])
updated.append(code)
if updated:
await db.flush()
logger.info("火箭外观构型回填:%s", ", ".join(updated))
return updated
async def ensure_high_frequency_rockets(db: AsyncSession) -> list[str]:
"""补齐缺失的高频型号,返回新入库的 code 列表。"""
existing = set((await db.execute(select(RocketConfig.code))).scalars().all())

View File

@ -2,7 +2,7 @@ import { useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import type { RocketConfig, SimulationState } from './types';
import { engineLayout, engineState, separationAge, separationTransform, stageGeometry } from './sceneMath';
import { boosterAngle, engineLayout, engineState, separationAge, separationTransform, stageGeometry } from './sceneMath';
/*
* 运载火箭 3D 模型
@ -332,8 +332,9 @@ function GridFins({ radius, y, color }: { radius: number; y: number; color: stri
}
/**
* 助推器:捆绑在芯级四周的两级半火箭助推器(长征五号 4×2 台发动机)。
* 每个助推器自带头锥、涂装、发动机与尾段。
* 捆绑助推器 / 侧芯级:并联在芯级四周,自带头锥、涂装、发动机与尾段。
* diameterRatio 是它与芯级的直径比(长征五号 0.45、猎鹰重型 1.0 等直径),
* 两者相切布置,因此猎鹰重型能画出真实的「三根并排芯级」。
*/
function StrapOnBooster({
radius,
@ -341,40 +342,43 @@ function StrapOnBooster({
color,
engines,
angle,
diameterRatio,
}: {
radius: number;
height: number;
color: string;
engines: number;
angle: number;
diameterRatio: number;
}) {
const offset = radius * 1.28;
const bodyRadius = radius * diameterRatio;
const offset = radius * (1 + diameterRatio);
const noseHeight = height * 0.22;
return (
<group position={[Math.cos(angle) * offset, 0, Math.sin(angle) * offset]}>
{/* 助推器箭体 */}
<mesh position={[0, height * 0.5, 0]} castShadow>
<cylinderGeometry args={[radius * 0.52, radius * 0.52, height, 28]} />
<cylinderGeometry args={[bodyRadius, bodyRadius, height, 28]} />
<meshStandardMaterial color={color} metalness={0.32} roughness={0.44} />
</mesh>
{/* 头锥 */}
<mesh position={[0, height + noseHeight * 0.5, 0]}>
<coneGeometry args={[radius * 0.52, noseHeight, 24]} />
<coneGeometry args={[bodyRadius, noseHeight, 24]} />
<meshStandardMaterial color={shade(color, -0.5)} metalness={0.35} roughness={0.45} />
</mesh>
{/* 涂装环 */}
<mesh position={[0, height * 0.9, 0]}>
<cylinderGeometry args={[radius * 0.528, radius * 0.528, height * 0.06, 28]} />
<cylinderGeometry args={[bodyRadius * 1.015, bodyRadius * 1.015, height * 0.06, 28]} />
<meshStandardMaterial color={shade(color, -0.6)} metalness={0.4} roughness={0.5} />
</mesh>
{/* 与芯级的连接件 */}
<mesh position={[-radius * 0.26, height * 0.62, 0]} rotation={[0, 0, Math.PI / 2]}>
<cylinderGeometry args={[radius * 0.06, radius * 0.06, radius * 0.5, 10]} />
<mesh position={[-bodyRadius - radius * 0.1, height * 0.62, 0]} rotation={[0, 0, Math.PI / 2]}>
<cylinderGeometry args={[radius * 0.06, radius * 0.06, radius * 0.34, 10]} />
<meshStandardMaterial color={DARK} metalness={0.6} roughness={0.45} />
</mesh>
{/* 助推器发动机 */}
<group position={[0, -radius * 0.08, 0]}>
<EngineCluster radius={radius * 0.56} count={engines} bellColor={shade(METAL, -0.15)} showActuators={false} />
<EngineCluster radius={bodyRadius * 1.08} count={engines} bellColor={shade(METAL, -0.15)} showActuators={false} />
</group>
</group>
);
@ -513,6 +517,58 @@ function FairingHalf({
);
}
/**
* 无整流罩构型(星舰)的飞船头锥:与二级等直径的钝头锥。
* 这类火箭的二级本身就是飞船,整流罩的位置只剩头锥。
*/
function ShipNose({ radius, height, color }: { radius: number; height: number; color: string }) {
const coneHeight = height * 0.78;
const barrelHeight = height - coneHeight;
const profile = useMemo(() => ogivePoints(radius, coneHeight), [coneHeight, radius]);
return (
<group>
<mesh position={[0, barrelHeight * 0.5, 0]}>
<cylinderGeometry args={[radius, radius, barrelHeight, 44]} />
<meshStandardMaterial color={color} metalness={0.55} roughness={0.34} />
</mesh>
<mesh position={[0, barrelHeight, 0]} castShadow>
<latheGeometry args={[profile, 40]} />
<meshStandardMaterial color={color} metalness={0.55} roughness={0.32} side={THREE.DoubleSide} />
</mesh>
</group>
);
}
/**
* 星舰二类构型的箭体襟翼:前 2 片小襟翼 + 后 2 片大襟翼,
* 上升段收拢贴在箭体两侧,与真实飞船一眼对应。
* 以二级(飞船)顶部为原点,因此 y 为负值。
*/
function ShipFlaps({ radius, height, color }: { radius: number; height: number; color: string }) {
const flaps = [
{ y: -height * 0.12, span: radius * 0.95, chord: radius * 0.6 },
{ y: -height * 0.86, span: radius * 1.55, chord: radius * 1.1 },
];
return (
<group>
{flaps.map((flap) => (
[-1, 1].map((direction) => (
<mesh
key={`${flap.y}-${direction}`}
position={[direction * (radius + flap.span * 0.4), flap.y, 0]}
rotation={[0, 0, direction * -0.16]}
castShadow
>
<boxGeometry args={[flap.span, flap.chord, radius * 0.1]} />
<meshStandardMaterial color={color} metalness={0.58} roughness={0.36} />
</mesh>
))
))}
</group>
);
}
/** 载荷适配器:二级顶部与卫星之间的锥形对接结构。 */
function PayloadAdapter({ radius, height }: { radius: number; height: number }) {
return (
@ -662,7 +718,7 @@ export function RocketModel({ rocket, state }: RocketModelProps) {
const visible = boosterAge < 3.2;
boosterRef.current.visible = visible;
boosterRef.current.children.forEach((child, index) => {
const angle = (index / Math.max(1, boosterRef.current!.children.length)) * Math.PI * 2 + Math.PI / 4;
const angle = boosterAngle(index, boosterRef.current!.children.length);
child.position.set(
Math.cos(angle) * spread,
-0.6 * boosterAge - 0.35 * boosterAge * boosterAge,
@ -675,7 +731,8 @@ export function RocketModel({ rocket, state }: RocketModelProps) {
}
if (upperStackRef.current) {
if (deployAge === null) {
// 无整流罩构型的二级就是飞船,入轨后继续留在画面里,不随载荷一起淡出
if (deployAge === null || !geo.fairing) {
upperStackRef.current.position.set(0, upperBaseY, 0);
upperStackRef.current.rotation.set(0, 0, 0);
upperStackRef.current.visible = true;
@ -730,36 +787,52 @@ export function RocketModel({ rocket, state }: RocketModelProps) {
</group>
{/* 载荷适配器 + 卫星(整流罩抛离后可见) */}
<group position={[0, fairingBaseY, 0]}>
<PayloadAdapter radius={geo.radius * 0.9} height={geo.fairingBarrelHeight * 0.3} />
</group>
{geo.fairing && (
<group position={[0, fairingBaseY, 0]}>
<PayloadAdapter radius={geo.radius * 0.9} height={geo.fairingBarrelHeight * 0.3} />
</group>
)}
<group ref={fairingRef} position={[0, fairingBaseY, 0]}>
{/* 每瓣外面再包一层,动画只作用于外层,避免覆盖半瓣自身的朝向 */}
<group>
<FairingHalf
{geo.fairing ? (
<group ref={fairingRef} position={[0, fairingBaseY, 0]}>
{/* 每瓣外面再包一层,动画只作用于外层,避免覆盖半瓣自身的朝向 */}
<group>
<FairingHalf
radius={geo.fairingRadius}
barrelHeight={geo.fairingBarrelHeight}
coneHeight={geo.fairingConeHeight}
color={fairingColor}
startAngle={0}
/>
</group>
<group>
<FairingHalf
radius={geo.fairingRadius}
barrelHeight={geo.fairingBarrelHeight}
coneHeight={geo.fairingConeHeight}
color={fairingColor}
startAngle={Math.PI}
/>
</group>
</group>
) : (
<group position={[0, fairingBaseY, 0]}>
<ShipNose
radius={geo.fairingRadius}
barrelHeight={geo.fairingBarrelHeight}
coneHeight={geo.fairingConeHeight}
color={fairingColor}
startAngle={0}
height={geo.fairingHeight}
color={shade(rocket.color, 0.02)}
/>
<ShipFlaps
radius={geo.radius * 0.97}
height={geo.stage2Height}
color={shade(rocket.color, -0.12)}
/>
</group>
<group>
<FairingHalf
radius={geo.fairingRadius}
barrelHeight={geo.fairingBarrelHeight}
coneHeight={geo.fairingConeHeight}
color={fairingColor}
startAngle={Math.PI}
/>
</group>
</group>
)}
</group>
{/* 载荷:部署后脱离上面级独立存在,上面级淡出后载荷仍然保留在场景中 */}
{deployAge !== null && (
{geo.fairing && deployAge !== null && (
<group
position={[
deployProgress * 0.8,
@ -780,7 +853,7 @@ export function RocketModel({ rocket, state }: RocketModelProps) {
color={rocket.color}
engineCount={geo.layout === 'boosters' ? geo.coreEngines : geo.stage1Engines}
label={firstStageLabel}
gridFins={geo.slenderCore}
gridFins={geo.gridFins}
/>
{/* 捆绑助推器:先于芯级分离,分离后向四周散开 */}
{geo.layout === 'boosters' && (
@ -792,7 +865,8 @@ export function RocketModel({ rocket, state }: RocketModelProps) {
height={geo.stage1Height * 0.86}
color={shade(rocket.color, -0.06)}
engines={geo.enginesPerBooster}
angle={(index / geo.boosterCount) * Math.PI * 2 + Math.PI / 4}
angle={boosterAngle(index, geo.boosterCount)}
diameterRatio={geo.boosterDiameterRatio}
/>
</group>
))}

View File

@ -1,4 +1,4 @@
import type { RocketConfig, SimulationState } from './types';
import type { RocketAppearance, RocketConfig, SimulationState } from './types';
/**
* Visual constants for the 3D flight scene. The rocket is always drawn at a
@ -7,22 +7,13 @@ import type { RocketConfig, SimulationState } from './types';
*/
export const VEHICLE_HEIGHT = 12;
/** 火箭布局:单芯级(猎鹰 9 一类)或带 4 个助推器(长征五号一类)。 */
/** 火箭布局:单芯级(猎鹰 9 一类)或捆绑助推器 / 侧芯级(长征五号、猎鹰重型)。 */
export type VehicleLayout = 'single-core' | 'boosters';
export interface StageGeometry {
totalHeight: number;
radius: number;
fairingRadius: number;
stage1Height: number;
stage2Height: number;
interstageHeight: number;
/** 整流罩总高度(圆柱段 + 头锥段) */
fairingHeight: number;
fairingBarrelHeight: number;
fairingConeHeight: number;
stage1Engines: number;
stage2Engines: number;
/** 未登记外观时的助推器细长比(长征五号 2.25m / 5.0m)。 */
const DEFAULT_BOOSTER_DIAMETER_RATIO = 0.45;
export interface VehicleLayoutInfo {
layout: VehicleLayout;
/** 助推器数量(单芯级为 0) */
boosterCount: number;
@ -30,46 +21,78 @@ export interface StageGeometry {
enginesPerBooster: number;
/** 芯级发动机数量 */
coreEngines: number;
/** 是否为细长多机回收构型(用于决定栅格翼等特征件) */
slenderCore: boolean;
/** 一级顶部是否画栅格翼(回收构型特征件) */
gridFins: boolean;
/** 助推器直径 / 芯级直径 */
boosterDiameterRatio: number;
}
export interface StageGeometry extends VehicleLayoutInfo {
totalHeight: number;
radius: number;
fairingRadius: number;
stage1Height: number;
stage2Height: number;
interstageHeight: number;
/** 整流罩(无整流罩构型则为飞船头锥)总高度:圆柱段 + 头锥段 */
fairingHeight: number;
fairingBarrelHeight: number;
fairingConeHeight: number;
stage1Engines: number;
stage2Engines: number;
/** 是否有载荷整流罩;false 表示二级自身带头锥与襟翼(星舰) */
fairing: boolean;
}
/**
* 由一级发动机数量推断布局:真实的两级半火箭把「芯级 + 4 个助推器」的
* 发动机数量合并登记在一级上(长征五号 10 = 芯级 2 + 4×2 助推器),
* 单芯级火箭则为「芯级中心机 + 外圈机」(猎鹰 9 = 1 + 8)。
* 构型优先取管理端登记的 appearance;没有登记时再按发动机数量推断:
* 真实的两级半火箭把「芯级 + 4 个助推器」的发动机数量合并登记在一级上
* (长征五号 10 = 芯级 2 + 4×2 助推器),单芯级火箭则为「芯级中心机 + 外圈机」
* (猎鹰 9 = 1 + 8)。猎鹰重型、星舰这类反例只能靠 appearance 表达。
*/
export function resolveVehicleLayout(stage1Engines: number, slenderness: number): {
layout: VehicleLayout;
boosterCount: number;
enginesPerBooster: number;
coreEngines: number;
slenderCore: boolean;
} {
const boosterCount = 4;
const remainder = stage1Engines - 2;
const supportsBoosters = stage1Engines > 9 && remainder % boosterCount === 0;
export function resolveVehicleLayout(
stage1Engines: number,
slenderness: number,
appearance: RocketAppearance = {},
): VehicleLayoutInfo {
const heuristicBoosters = stage1Engines > 9 && (stage1Engines - 2) % 4 === 0 ? 4 : 0;
const boosterCount = Math.round(appearance.booster_count ?? heuristicBoosters);
if (supportsBoosters) {
if (boosterCount <= 0) {
return {
layout: 'boosters',
boosterCount,
enginesPerBooster: remainder / boosterCount,
coreEngines: 2,
slenderCore: false,
layout: 'single-core',
boosterCount: 0,
enginesPerBooster: 0,
coreEngines: stage1Engines,
// 细长且多发动机的单芯级(猎鹰 9)才会带栅格翼这类回收构型特征件
gridFins: appearance.grid_fins ?? (stage1Engines >= 8 && slenderness >= 15),
boosterDiameterRatio: DEFAULT_BOOSTER_DIAMETER_RATIO,
};
}
// 4 个助推器时可按一级发动机数反推每台助推器的发动机数,其余构型需要登记
const inferredPerBooster = boosterCount === 4 ? (stage1Engines - 2) / 4 : 1;
const enginesPerBooster = Math.max(1, Math.round(appearance.engines_per_booster ?? inferredPerBooster));
return {
layout: 'single-core',
boosterCount: 0,
enginesPerBooster: 0,
coreEngines: stage1Engines,
// 细长且多发动机的单芯级(猎鹰 9)才会带栅格翼这类回收构型特征件
slenderCore: stage1Engines >= 8 && slenderness >= 15,
layout: 'boosters',
boosterCount,
enginesPerBooster,
coreEngines: Math.max(1, stage1Engines - boosterCount * enginesPerBooster),
gridFins: appearance.grid_fins ?? false,
boosterDiameterRatio: clamp(appearance.booster_diameter_ratio ?? DEFAULT_BOOSTER_DIAMETER_RATIO, 0.2, 1),
};
}
/**
* 助推器(侧芯级)的分布角:两个时与芯级并排成一线(猎鹰重型、长征八号),
* 四个时按 X 形对称布置(长征五号一类)。
*/
export function boosterAngle(index: number, count: number): number {
const base = count === 2 ? 0 : Math.PI / 4;
return (index / Math.max(1, count)) * Math.PI * 2 + base;
}
/** 便捷入口:直接由火箭配置判断布局(供物理模拟与仪表盘复用)。 */
export function layoutForRocket(rocket: RocketConfig) {
const heightM = Math.max(1, rocket.height_m);
@ -77,6 +100,7 @@ export function layoutForRocket(rocket: RocketConfig) {
return resolveVehicleLayout(
Math.max(1, Math.round(rocket.stage_1.engine_count)),
clamp(heightM / diameterM, 4, 26),
rocket.appearance ?? {},
);
}
@ -86,8 +110,10 @@ export function layoutForRocket(rocket: RocketConfig) {
* 全部尺寸都来自数据库里的真实参数,保证 3D 模型与火箭资料一致:
* - 长细比(height_m / diameter_m)决定箭体半径
* - 整流罩直径按真实运载火箭经验值(约 1.4 倍芯级直径,上限 5.4m)推导,
* 因此细长的猎鹰 9 会得到明显的「大整流罩」,而 5m 级的长征五号近乎等径
* 因此细长的猎鹰 9 会得到明显的「大整流罩」,而 5m 级的长征五号近乎等径;
* 电子号这类小直径火箭的整流罩只略粗于箭体,不会倒扣成「细脖子大头」
* - 整流罩长度约为其直径的 2.5 倍,与真实整流罩(约 12~13m)吻合
* - appearance.fairing = false 时不画整流罩,二级以等直径短头锥收尾(星舰)
* - length_ratio 决定一级 / 二级在箭体中的占比
*/
export function stageGeometry(rocket: RocketConfig): StageGeometry {
@ -100,15 +126,16 @@ export function stageGeometry(rocket: RocketConfig): StageGeometry {
const totalHeight = clamp(VEHICLE_HEIGHT * (heightM / 62), 10, 15);
const radius = totalHeight / slenderness / 2;
// 无整流罩构型(星舰):二级自身就是飞船,以等直径短头锥收尾
const hasFairing = rocket.appearance?.fairing !== false;
// 整流罩:约 1.4 倍芯级直径,最大 5.4m(与 5.2m 级真实整流罩一致)
const fairingDiameterM = clamp(diameterM * 1.4, 2.6, 5.4);
const fairingRadius = radius * (fairingDiameterM / diameterM);
const fairingHeight = clamp(
totalHeight * (fairingDiameterM * 2.5) / heightM,
totalHeight * 0.13,
totalHeight * 0.27,
);
const fairingConeHeight = fairingHeight * 0.62;
const fairingDiameterM = Math.min(diameterM * 1.4, 5.4);
const fairingRadius = hasFairing ? radius * (fairingDiameterM / diameterM) : radius * 0.97;
const fairingHeight = hasFairing
? clamp(totalHeight * (fairingDiameterM * 2.5) / heightM, totalHeight * 0.13, totalHeight * 0.27)
: totalHeight * 0.11;
const fairingConeHeight = hasFairing ? fairingHeight * 0.62 : fairingHeight;
const fairingBarrelHeight = fairingHeight - fairingConeHeight;
// 级间段:真实长度约 3~5m
@ -139,7 +166,8 @@ export function stageGeometry(rocket: RocketConfig): StageGeometry {
fairingConeHeight,
stage1Engines,
stage2Engines: Math.max(1, Math.round(rocket.stage_2.engine_count)),
...resolveVehicleLayout(stage1Engines, slenderness),
fairing: hasFairing,
...resolveVehicleLayout(stage1Engines, slenderness, rocket.appearance ?? {}),
};
}
@ -187,7 +215,8 @@ export function engineLayout(count: number, radius: number): EnginePlacement[] {
});
}
const coreCount = total > 9 ? 2 : 1;
// 20 台以上(超重型 33 台)与真实一样用 3 台中心机,10 台以上用 2 台
const coreCount = total > 20 ? 3 : total > 9 ? 2 : 1;
const outerCount = total - coreCount;
const outerBell = Math.min(radius * 0.3, (2 * Math.PI * ringRadius) / (outerCount * 2.45));
const coreBell = Math.min(radius * 0.34, outerBell * 1.12);
@ -195,9 +224,14 @@ export function engineLayout(count: number, radius: number): EnginePlacement[] {
const placements: EnginePlacement[] = [];
if (coreCount === 1) {
placements.push(make(0, 0, coreBell));
} else {
} else if (coreCount === 2) {
placements.push(make(-radius * 0.26, 0, coreBell));
placements.push(make(radius * 0.26, 0, coreBell));
} else {
for (let index = 0; index < coreCount; index += 1) {
const angle = (index / coreCount) * Math.PI * 2 - Math.PI / 2;
placements.push(make(Math.cos(angle) * radius * 0.24, Math.sin(angle) * radius * 0.24, coreBell));
}
}
for (let index = 0; index < outerCount; index += 1) {

View File

@ -8,6 +8,24 @@ export interface RocketStage {
length_ratio: number;
}
/**
* 外观构型(可选):真实火箭的构型差别无法只靠发动机数量推断,
* 例如猎鹰重型的 27 台是「3 根等直径芯级」,星舰则没有整流罩。
* 留空的字段由 sceneMath 按通用规律推断。
*/
export interface RocketAppearance {
/** 捆绑助推器 / 侧芯级数量,0 为单芯级 */
booster_count?: number | null;
/** 每个助推器的发动机数量 */
engines_per_booster?: number | null;
/** 助推器直径 / 芯级直径 */
booster_diameter_ratio?: number | null;
/** 一级顶部栅格翼(回收构型) */
grid_fins?: boolean | null;
/** 是否有载荷整流罩;false 表示二级自身带头锥与襟翼(星舰) */
fairing?: boolean | null;
}
export interface RocketConfig {
id: number;
code: string;
@ -31,6 +49,7 @@ export interface RocketConfig {
second_stage_ignition_delay_seconds: number;
stage_1: RocketStage;
stage_2: RocketStage;
appearance?: RocketAppearance | null;
is_active: boolean;
sort_order: number;
created_at?: string;

View File

@ -185,7 +185,12 @@ export function useRocketSimulation(rocket: RocketConfig) {
} else if (next.phase === 'orbit' && phaseElapsed >= 2) {
next.phase = 'payload_deploy';
next.phaseStartedAt = next.time;
next.events = addEvent(next.events, 'deploy', '载荷分离与太阳翼展开', next.time);
next.events = addEvent(
next.events,
'deploy',
config.appearance?.fairing === false ? '飞船入轨' : '载荷分离与太阳翼展开',
next.time,
);
} else if (next.phase === 'payload_deploy' && phaseElapsed >= 6) {
next.phase = 'mission_complete';
next.isRunning = false;

View File

@ -27,10 +27,17 @@ const MILESTONES: Array<{ id: string; code: string; label: string }> = [
{ id: 'deploy', code: 'PAYLOAD', label: '载荷部署' },
];
/** 只有捆绑助推器的火箭(长征五号一类)才显示助推器分离节点。 */
/**
* 里程碑清单:只有捆绑助推器的火箭(长征五号一类)才显示助推器分离节点;
* 没有整流罩的火箭(星舰)末端节点是飞船入轨,而不是载荷分离。
*/
function milestonesFor(rocket: RocketConfig) {
const hasBoosters = layoutForRocket(rocket).layout === 'boosters';
return hasBoosters ? MILESTONES : MILESTONES.filter((item) => item.id !== 'booster-sep');
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) {
@ -71,6 +78,11 @@ const STACK_MODE_LABEL: Record<StackMode, { code: string; zh: string; detail: st
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 场景
@ -86,7 +98,8 @@ function StackDiagram({ rocket }: { rocket: RocketConfig }) {
const r1 = Math.max(8, geo.radius * scale);
const r2 = r1 * 0.97;
const rf = Math.max(r1 + 1.5, geo.fairingRadius * scale);
// 无整流罩构型的头锥与二级等直径,不会比箭体更细
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;
@ -131,13 +144,13 @@ function StackDiagram({ rocket }: { rocket: RocketConfig }) {
<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 bx = CX + direction * r1 * 1.85;
const br = r1 * 0.52;
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" />
@ -146,7 +159,7 @@ function StackDiagram({ rocket }: { rocket: RocketConfig }) {
fill="#b9c2c8"
/>
<rect x={bx - br} y={boosterTop + boosterH * 0.08} width={br * 2} height={boosterH * 0.06} fill="#c8d0d6" />
{engineBells(geo.enginesPerBooster, geo.radius * 0.56, boosterTop + boosterH)}
{engineBells(geo.enginesPerBooster, geo.radius * geo.boosterDiameterRatio * 1.08, boosterTop + boosterH)}
</g>
);
})}
@ -159,7 +172,7 @@ function StackDiagram({ rocket }: { rocket: RocketConfig }) {
<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.slenderCore && [-1, 1].map((direction) => (
{geo.gridFins && [-1, 1].map((direction) => (
<path
key={direction}
d={`M ${CX + direction * r1} ${s1Top + s1H * 0.08} l ${direction * 7} 0 l 0 6 l ${-direction * 7} 0 Z`}
@ -178,39 +191,57 @@ function StackDiagram({ rocket }: { rocket: RocketConfig }) {
{engineBells(geo.stage2Engines, geo.radius * 0.97, s2Top + s2H + 3.4)}
</g>
{/* Payload 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>
{/* 头锥 / 整流罩:有整流罩时为两瓣卵形罩,载荷部署时分离;无整流罩时为飞船头锥 */}
{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 */}
<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" />
{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>
<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 = STACK_MODE_LABEL[mode];
const meta = mode === 'payload' && rocket.appearance?.fairing === false ? SHIP_MODE_LABEL : STACK_MODE_LABEL[mode];
return (
<div className="sx-vehicle">
<div className="sx-panel-title"><span>VEHICLE</span><b>运载器状态</b></div>

View File

@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { Button, Col, Form, Input, InputNumber, Row, Switch, Tabs } from 'antd';
import { Alert, Button, Col, Form, Input, InputNumber, Row, Switch, Tabs } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import { RocketOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
@ -12,7 +12,7 @@ import { useToast } from '../../contexts/ToastContext';
const defaultStage1 = { name: '一级推进器', dry_mass_kg: 25000, fuel_mass_kg: 400000, max_thrust_n: 7500000, specific_impulse_s: 285, engine_count: 9, length_ratio: 0.65 };
const defaultStage2 = { name: '二级推进器', dry_mass_kg: 4000, fuel_mass_kg: 100000, max_thrust_n: 1000000, specific_impulse_s: 350, engine_count: 1, length_ratio: 0.35 };
const createDefaults = { color: '#f8fafc', launch_site_name: '发射场', launch_latitude_deg: 0, launch_longitude_deg: 0, payload_mass_kg: 15000, drag_coefficient: 0.4, target_orbit_km: 200, target_velocity_mps: 7800, separation_delay_seconds: 2, second_stage_ignition_delay_seconds: 1, is_active: true, sort_order: 0, stage_1: defaultStage1, stage_2: defaultStage2 };
const createDefaults = { color: '#f8fafc', launch_site_name: '发射场', launch_latitude_deg: 0, launch_longitude_deg: 0, payload_mass_kg: 15000, drag_coefficient: 0.4, target_orbit_km: 200, target_velocity_mps: 7800, separation_delay_seconds: 2, second_stage_ignition_delay_seconds: 1, is_active: true, sort_order: 0, stage_1: defaultStage1, stage_2: defaultStage2, appearance: {} };
function NumberField({ name, label, suffix, min = 0, max, step }: { name: string | (string | number)[]; label: string; suffix?: string; min?: number; max?: number; step?: number }) {
return <Form.Item name={name} label={label} rules={[{ required: true, message: `请输入${label}` }]}><InputNumber min={min} max={max} step={step} style={{ width: '100%' }} suffix={suffix} /></Form.Item>;
@ -33,6 +33,19 @@ function StageFields({ index }: { index: 1 | 2 }) {
);
}
function AppearanceFields() {
return (
<Row gutter={16}>
<Col span={24}><Alert type="info" showIcon style={{ marginBottom: 16 }} message="留空即按发动机数量自动推断构型;仅当 3D 外形与真实不符时才需要填写。" /></Col>
<Col xs={24} md={8}><Form.Item name={['appearance', 'booster_count']} label="助推器数量" tooltip="捆绑助推器 / 侧芯级数量,0 为单芯级"><InputNumber min={0} max={8} style={{ width: '100%' }} placeholder="自动" /></Form.Item></Col>
<Col xs={24} md={8}><Form.Item name={['appearance', 'engines_per_booster']} label="单个助推器发动机数" tooltip="用于推算助推器尾焰规模"><InputNumber min={1} max={33} style={{ width: '100%' }} placeholder="自动" /></Form.Item></Col>
<Col xs={24} md={8}><Form.Item name={['appearance', 'booster_diameter_ratio']} label="助推器直径比" tooltip="助推器直径 / 芯级直径"><InputNumber min={0.01} max={1} step={0.01} style={{ width: '100%' }} placeholder="0.45" /></Form.Item></Col>
<Col xs={24} md={12}><Form.Item name={['appearance', 'grid_fins']} label="一级栅格翼" tooltip="回收构型一级顶部的栅格翼" valuePropName="checked"><Switch /></Form.Item></Col>
<Col xs={24} md={12}><Form.Item name={['appearance', 'fairing']} label="载荷整流罩" tooltip="关闭表示二级自身带头锥与襟翼(如星舰飞船)" valuePropName="checked"><Switch /></Form.Item></Col>
</Row>
);
}
export function Rockets() {
const [data, setData] = useState<RocketConfig[]>([]);
const [loading, setLoading] = useState(false);
@ -168,6 +181,7 @@ export function Rockets() {
{ key: 'mission', label: '发射与任务', children: <Row gutter={16}><Col span={24}><Form.Item name="launch_site_name" label="发射场名称" rules={[{ required: true, message: '请输入发射场名称' }]}><Input placeholder="例如:某某航天发射场" /></Form.Item></Col><Col xs={24} md={12}><NumberField name="launch_latitude_deg" label="发射场纬度" suffix="°" min={-90} max={90} step={0.0001} /></Col><Col xs={24} md={12}><NumberField name="launch_longitude_deg" label="发射场经度" suffix="°" min={-180} max={180} step={0.0001} /></Col><Col xs={24} md={12}><NumberField name="drag_coefficient" label="阻力系数 Cd" min={0.01} step={0.01} /></Col><Col xs={24} md={12}><NumberField name="reference_area_m2" label="参考面积" suffix="m²" /></Col><Col xs={24} md={12}><NumberField name="target_orbit_km" label="目标轨道高度" suffix="km" /></Col><Col xs={24} md={12}><NumberField name="target_velocity_mps" label="目标速度" suffix="m/s" /></Col><Col xs={24} md={12}><NumberField name="separation_delay_seconds" label="级间分离持续时间" suffix="s" /></Col><Col xs={24} md={12}><NumberField name="second_stage_ignition_delay_seconds" label="二级点火延时" suffix="s" /></Col><Col xs={24} md={12}><NumberField name="sort_order" label="排序" /></Col><Col xs={24} md={12}><Form.Item name="is_active" label="前台启用" valuePropName="checked"><Switch /></Form.Item></Col></Row> },
{ key: 'stage1', label: '一级参数', children: <StageFields index={1} /> },
{ key: 'stage2', label: '二级参数', children: <StageFields index={2} /> },
{ key: 'appearance', label: '外观构型(可选)', children: <AppearanceFields /> },
]} />
</Form>
</AdminModal>

View File

@ -254,6 +254,11 @@ update_system() {
docker-compose cp scripts/upgrade_db.py backend:/app/scripts/upgrade_db.py
docker-compose exec -T backend python scripts/upgrade_db.py --apply
# Boot-time tasks (preset rockets, appearance backfill) ran before the new
# columns existed, so restart once to let them see the upgraded schema.
log "Restarting backend to apply boot-time data migrations..."
docker-compose restart backend
log "✓ System updated"
}