From fc749505a5e9883ec384fb86bcffe6407fb7d610 Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Thu, 8 Oct 2026 08:47:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=80=E7=BA=A7=E5=8F=82=E6=95=B0=E6=8B=86?= =?UTF-8?q?=E5=88=86=E5=8A=A9=E6=8E=A8=E5=99=A8=E5=8F=A3=E5=BE=84=EF=BC=8C?= =?UTF-8?q?=E5=8F=91=E5=B0=84=E5=8F=B0=E5=8F=91=E5=8A=A8=E6=9C=BA=E4=BB=AA?= =?UTF-8?q?=E8=A1=A8=E7=A7=BB=E5=88=B0=E5=B7=A6=E4=BE=A7=E5=B9=B6=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E7=81=AB=E7=AE=AD=E5=8F=91=E5=B0=84=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增可选 boosters 字段:一级仍登记含助推器的合计值,芯级由减法推导, 助推器分离与一级关机时序不再互相顶牛;无该字段时物理完全退回旧模型 - 物理循环抽到 physics.ts / stageSplit.ts,可用脚本批量验证全部型号时序 - 阿丽亚娜6 的一级本就是 P120C 助推组、长征六号甲公开推力口径矛盾, 两者不登记拆分,避免芯级重复计算或分离后推重比不足 - 仪表台删掉左下角环境卡,发动机仪表按真实直径比例逐舱画在同一行 - 管理端菜单预置服务幂等补入「火箭发射事件」,新增对应只读页面 --- backend/app/api/rocket.py | 46 +++- backend/app/main.py | 15 +- backend/app/models/db/rocket.py | 2 + backend/app/services/menu_service.py | 73 +++++ backend/app/services/rocket_preset_service.py | 108 ++++++++ frontend/src/Router.tsx | 2 + .../src/features/rocket-simulator/physics.ts | 249 ++++++++++++++++++ .../rocket-simulator/rocket-simulator.css | 149 +++-------- .../features/rocket-simulator/stageSplit.ts | 53 ++++ .../src/features/rocket-simulator/types.ts | 25 ++ .../rocket-simulator/useRocketSimulation.ts | 214 +-------------- frontend/src/pages/RocketSimulator.tsx | 85 +++--- frontend/src/pages/admin/RocketEvents.tsx | 205 ++++++++++++++ frontend/src/pages/admin/Rockets.tsx | 25 +- 14 files changed, 870 insertions(+), 381 deletions(-) create mode 100644 backend/app/services/menu_service.py create mode 100644 frontend/src/features/rocket-simulator/physics.ts create mode 100644 frontend/src/features/rocket-simulator/stageSplit.ts create mode 100644 frontend/src/pages/admin/RocketEvents.tsx diff --git a/backend/app/api/rocket.py b/backend/app/api/rocket.py index 4cee464..28a38d5 100644 --- a/backend/app/api/rocket.py +++ b/backend/app/api/rocket.py @@ -3,7 +3,7 @@ from datetime import datetime from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Query, status -from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator, model_validator from sqlalchemy import func, or_, select from sqlalchemy.ext.asyncio import AsyncSession @@ -39,6 +39,21 @@ class RocketAppearance(BaseModel): fairing: bool | None = Field(default=None, description="是否有载荷整流罩;false 表示二级自身带头锥与襟翼(星舰)") +class RocketBoosters(BaseModel): + """捆绑助推器组合参数(可选)。 + + 口径与一级一致,但只统计助推器这一组:thrust_n / dry_mass_kg / fuel_mass_kg 都是 + 全部助推器加起来的合计值。芯级 = stage_1 减去本组,因此不会有两套数字互相矛盾; + 助推器比冲单独登记,芯级比冲沿用 stage_1.specific_impulse_s。 + """ + + count: int = Field(ge=1, le=8, description="助推器数量") + thrust_n: float = Field(gt=0, description="全部助推器合计推力,不含芯级") + specific_impulse_s: float = Field(gt=0, description="助推器比冲;芯级比冲取 stage_1") + dry_mass_kg: float = Field(gt=0, description="全部助推器合计干重") + fuel_mass_kg: float = Field(gt=0, description="全部助推器合计推进剂") + + class RocketBase(BaseModel): code: RocketCode name: str = Field(min_length=1, max_length=100) @@ -62,6 +77,7 @@ class RocketBase(BaseModel): stage_1: RocketStage stage_2: RocketStage appearance: RocketAppearance | None = None + boosters: RocketBoosters | None = None is_active: bool = True sort_order: int = 0 @@ -70,11 +86,30 @@ class RocketBase(BaseModel): def normalize_code(cls, value: str) -> str: return value.strip().lower() + @model_validator(mode="after") + def boosters_within_stage1(self) -> "RocketBase": + """助推器是一级的子集,否则一级数据自相矛盾(分离时会算出负推力/负质量)。""" + check_boosters_within_stage1(self.stage_1, self.boosters) + return self + class RocketCreate(RocketBase): pass +def check_boosters_within_stage1(stage_1: RocketStage | None, boosters: RocketBoosters | None) -> None: + if stage_1 is None or boosters is None: + return + pairs = ( + ("boosters.thrust_n", boosters.thrust_n, stage_1.max_thrust_n), + ("boosters.dry_mass_kg", boosters.dry_mass_kg, stage_1.dry_mass_kg), + ("boosters.fuel_mass_kg", boosters.fuel_mass_kg, stage_1.fuel_mass_kg), + ) + for name, value, total in pairs: + if value > total: + raise ValueError(f"{name} 不能大于 stage_1 的对应值({value:g} > {total:g})") + + class RocketUpdate(BaseModel): code: RocketCode | None = None name: str | None = Field(default=None, min_length=1, max_length=100) @@ -98,6 +133,7 @@ class RocketUpdate(BaseModel): stage_1: RocketStage | None = None stage_2: RocketStage | None = None appearance: RocketAppearance | None = None + boosters: RocketBoosters | None = None is_active: bool | None = None sort_order: int | None = None @@ -106,6 +142,12 @@ class RocketUpdate(BaseModel): def normalize_code(cls, value: str | None) -> str | None: return value.strip().lower() if value else value + @model_validator(mode="after") + def boosters_within_stage1(self) -> "RocketUpdate": + # 只改 boosters 不改 stage_1 时无法交叉校验,交给前端与预置保证口径 + check_boosters_within_stage1(self.stage_1, self.boosters) + return self + class RocketResponse(RocketBase): id: int @@ -117,7 +159,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", "appearance"): + for key in ("stage_1", "stage_2", "appearance", "boosters"): if key in values and values[key] is not None: values[key] = dict(values[key]) return values diff --git a/backend/app/main.py b/backend/app/main.py index 80c62b2..24b8385 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -82,19 +82,32 @@ 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, ensure_rocket_appearance + from app.services.rocket_preset_service import ( + ensure_high_frequency_rockets, + ensure_rocket_appearance, + ensure_rocket_boosters, + ) from app.services.rocket_event_service import ensure_launch_event_job + from app.services.menu_service import ensure_admin_menus 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) + # 捆绑助推器型号拆分助推器口径(要在外观预置之后,才能顺带修正外观发动机数) + boosted = await ensure_rocket_boosters(db) await ensure_launch_event_job(db) + # 补插新增后台页面所需的菜单(本次:火箭发射事件) + new_menus = await ensure_admin_menus(db) await db.commit() logger.info("✓ Default system settings initialized") if added_rockets: logger.info(f"✓ Rocket presets added: {', '.join(added_rockets)}") + if boosted: + logger.info(f"✓ Rocket booster presets added: {', '.join(boosted)}") + if new_menus: + logger.info(f"✓ Admin menus added: {', '.join(new_menus)}") # Preheat caches (load from database to Redis) await preheat_all_caches() diff --git a/backend/app/models/db/rocket.py b/backend/app/models/db/rocket.py index cdcf235..1db9da0 100644 --- a/backend/app/models/db/rocket.py +++ b/backend/app/models/db/rocket.py @@ -33,6 +33,8 @@ class RocketConfig(Base): stage_1 = Column(JSONB, nullable=False) stage_2 = Column(JSONB, nullable=False) appearance = Column(JSONB, nullable=True) + # 捆绑助推器组合参数;stage_1 始终是一级合计(含助推器),芯级由两者相减得到 + boosters = 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()) diff --git a/backend/app/services/menu_service.py b/backend/app/services/menu_service.py new file mode 100644 index 0000000..e44a543 --- /dev/null +++ b/backend/app/services/menu_service.py @@ -0,0 +1,73 @@ +"""管理端菜单预置。 + +后台菜单是数据库驱动的(menus + role_menus),新页面加进前端路由后, +老库里不会出现对应菜单,新一套环境也缺导航入口,因此这里做一次幂等回填: +只补插按 name 判断仍缺失的菜单,并把它授权给已经能看到父菜单的角色。 +管理端自己改过的标题、排序、图标一律不再改动。 +""" +import logging + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.db import Menu, RoleMenu + +logger = logging.getLogger(__name__) + +# 需要存在的后台菜单;parent 为父菜单 name,同层按 sort_order 升序展示 +ADMIN_MENUS: list[dict] = [ + { + "name": "rocket_events", + "title": "火箭发射事件", + "icon": "rocket", + "path": "/admin/rocket-events", + "component": "admin/RocketEvents", + "parent": "data_management", + "sort_order": 6, + }, +] + + +async def ensure_admin_menus(db: AsyncSession) -> list[str]: + """补插缺失的管理端菜单,返回新入库的菜单 name 列表。""" + existing = set((await db.execute(select(Menu.name))).scalars().all()) + missing = [item for item in ADMIN_MENUS if item["name"] not in existing] + if not missing: + return [] + + parents = { + menu.name: menu + for menu in (await db.execute( + select(Menu).where(Menu.name.in_({item["parent"] for item in missing})) + )).scalars().all() + } + + added: list[str] = [] + for item in missing: + parent = parents.get(item["parent"]) + if parent is None: + logger.warning("菜单预置跳过 %s:找不到父菜单 %s", item["name"], item["parent"]) + continue + menu = Menu( + parent_id=parent.id, + name=item["name"], + title=item["title"], + icon=item["icon"], + path=item["path"], + component=item["component"], + sort_order=item["sort_order"], + is_active=True, + ) + db.add(menu) + await db.flush() + # 能看到父菜单的角色即可看到新页面 + for role_id in (await db.execute( + select(RoleMenu.role_id).where(RoleMenu.menu_id == parent.id) + )).scalars().all(): + db.add(RoleMenu(role_id=role_id, menu_id=menu.id)) + added.append(item["name"]) + + if added: + await db.flush() + logger.info("管理端菜单预置补齐:%s", ", ".join(added)) + return added diff --git a/backend/app/services/rocket_preset_service.py b/backend/app/services/rocket_preset_service.py index ca0f457..527fba5 100644 --- a/backend/app/services/rocket_preset_service.py +++ b/backend/app/services/rocket_preset_service.py @@ -388,6 +388,114 @@ async def ensure_rocket_appearance(db: AsyncSession) -> list[str]: return updated +# 助推器组合预置:公开资料近似值,用于把「捆绑助推器」从一级里拆出来单独计量。 +# 数值都是一级里属于助推器的那一部分(合计口径),芯级由 stage_1 减去本组得到。 +# 说明几点口径选择: +# - 固体助推器登记的是平均推力(P120C 峰值 4.46 MN、平均 3.5 MN),模拟为等推力, +# 用平均推力才能烧出真实的助推器工作时间; +# - 猎鹰重型侧芯级与中心级是同款 F9 一级,但侧芯级提前几秒关机(省推进剂返场), +# 因此助推器推进剂登记得比单枚一级少,中心级余量更多,分离与 MECO 时序才对得上; +# - 芯级比冲沿用 stage_1.specific_impulse_s(登记的是整段一级的有效比冲)。 +ROCKET_BOOSTERS: dict[str, dict[str, Any]] = { + # 两枚 F9 一级作侧芯级:2×7.607 MN、2×25.6 t 干重 + "falcon-heavy": {"count": 2, "thrust_n": 15214000, "specific_impulse_s": 282, "dry_mass_kg": 51200, "fuel_mass_kg": 780000}, + # 4 枚 3.35 m 助推器,各 2 台 YF-100、推进剂 142.8 t、干重 13.8 t + "long-march-5": {"count": 4, "thrust_n": 9600000, "specific_impulse_s": 300, "dry_mass_kg": 55200, "fuel_mass_kg": 571200}, + # 联盟 2 的四个侧级(Blok B/V/G/D),各 1 台 RD-107 + "soyuz-2": {"count": 4, "thrust_n": 3352000, "specific_impulse_s": 255, "dry_mass_kg": 12000, "fuel_mass_kg": 166000}, + # 长征二号 F:4 个助推器各 1 台,与芯级 4 台各占一半推力 + "long-march-2f": {"count": 4, "thrust_n": 2979000, "specific_impulse_s": 263, "dry_mass_kg": 12000, "fuel_mass_kg": 150000}, + # 长征七号:4 个 2.25 m 助推器各 1 台 YF-100(1.179 MN),芯级 2 台 + "long-march-7": {"count": 4, "thrust_n": 4716000, "specific_impulse_s": 300, "dry_mass_kg": 20000, "fuel_mass_kg": 200000}, + "long-march-8": {"count": 2, "thrust_n": 4796000, "specific_impulse_s": 300, "dry_mass_kg": 12000, "fuel_mass_kg": 165000}, +} + +# 两个型号有意不登记 boosters: +# - ariane-6:它的一级本来就是 P120C 助推器组,主级在 stage_2,再拆一次会把芯级算两遍; +# - long-march-6a:公开推力口径互相矛盾(登记值里大部分发动机在助推器上), +# 拆分后芯级推重比不足,在本简化弹道模型里无法维持飞行。 + +# 一级口径修正:早期预置把「助推器推力 + 芯级推进剂」混在一起登记(长征五号一级 +# 只有芯级的 175 t 推进剂,却登记了含助推器的 10.6 MN 推力),拆分助推器之后必须 +# 统一成「一级合计」口径。只在库里仍是旧值且还没登记 boosters 时才改, +# 管理端改过的型号一律不动。 +STAGE1_TOTAL_FIXES: dict[str, dict[str, Any]] = { + "long-march-5": { + "expect": {"dry_mass_kg": 38000, "fuel_mass_kg": 175000}, + "stage_1": { + "name": "芯一级与四个助推器(YF-77×2 + YF-100×8)", + "dry_mass_kg": 90000, + "fuel_mass_kg": 736500, + }, + }, + "long-march-7": { + # 长征七号起飞用 6 台 YF-100(芯级 2 台 + 4 个助推器各 1 台),不是 10 台 + "expect": {"engine_count": 10}, + "stage_1": {"name": "芯一级与四个助推器(6 台 YF-100)", "engine_count": 6}, + "appearance": {"core_engine_count": 2, "engines_per_booster": 1}, + }, +} + + +async def ensure_rocket_boosters(db: AsyncSession) -> list[str]: + """按 ROCKET_BOOSTERS 登记助推器组合,并顺带统一一级口径。 + + 与外观预置一样是幂等回填:库里已经有 boosters 的型号(包括管理端自己填的) + 一律不动,因此一级口径修正也只会对旧数据执行一次。 + """ + codes = set(ROCKET_BOOSTERS) | set(STAGE1_TOTAL_FIXES) + column = await db.execute( + text("SELECT 1 FROM information_schema.columns " + "WHERE table_name = 'rocket_configs' AND column_name = 'boosters'") + ) + if column.first() is None: + logger.warning("rocket_configs.boosters 列不存在,跳过助推器参数回填(执行 upgrade_db.py --apply 后重启生效)") + return [] + result = await db.execute(select(RocketConfig).where(RocketConfig.code.in_(codes))) + + updated: list[str] = [] + for rocket in result.scalars().all(): + if rocket.boosters: + continue + fix = STAGE1_TOTAL_FIXES.get(rocket.code) + if fix: + current = dict(rocket.stage_1 or {}) + if all(current.get(key) == value for key, value in fix["expect"].items()): + current.update(fix["stage_1"]) + rocket.stage_1 = current + appearance = dict(rocket.appearance or {}) + appearance.update(fix.get("appearance", {})) + rocket.appearance = appearance + logger.info("火箭 %s 一级口径已统一为含助推器的合计值:%s", rocket.code, fix["stage_1"]) + else: + logger.info("火箭 %s 的一级参数已被修改过,跳过口径修正", rocket.code) + preset = ROCKET_BOOSTERS.get(rocket.code) + if not preset: + continue + # 口径修正没生效(管理端自己改过一级)时,助推器数值可能超出一级总量, + # 这种自相矛盾的数据宁可不登记,也不能让模拟算出负推力 + stage1 = rocket.stage_1 or {} + if not _boosters_fit_stage1(preset, stage1): + logger.warning("火箭 %s 的助推器预置超出其一级的总量,跳过登记", rocket.code) + continue + rocket.boosters = dict(preset) + updated.append(rocket.code) + + if updated: + await db.flush() + logger.info("火箭助推器参数回填:%s", ", ".join(updated)) + return updated + + +def _boosters_fit_stage1(boosters: dict[str, Any], stage_1: dict[str, Any]) -> bool: + pairs = ( + ("thrust_n", "max_thrust_n"), + ("dry_mass_kg", "dry_mass_kg"), + ("fuel_mass_kg", "fuel_mass_kg"), + ) + return all((boosters.get(key) or 0) <= (stage_1.get(total) or 0) for key, total in pairs) + + async def ensure_high_frequency_rockets(db: AsyncSession) -> list[str]: """补齐缺失的高频型号,返回新入库的 code 列表。""" existing = set((await db.execute(select(RocketConfig.code))).scalars().all()) diff --git a/frontend/src/Router.tsx b/frontend/src/Router.tsx index c01911c..bce81f9 100644 --- a/frontend/src/Router.tsx +++ b/frontend/src/Router.tsx @@ -24,6 +24,7 @@ const UserProfile = lazy(() => import('./pages/admin/UserProfile').then((module) const MyCelestialBodies = lazy(() => import('./pages/admin/MyCelestialBodies').then((module) => ({ default: module.MyCelestialBodies }))); const MyDevices = lazy(() => import('./pages/admin/MyDevices').then((module) => ({ default: module.MyDevices }))); const Rockets = lazy(() => import('./pages/admin/Rockets').then((module) => ({ default: module.Rockets }))); +const RocketEvents = lazy(() => import('./pages/admin/RocketEvents').then((module) => ({ default: module.RocketEvents }))); function RouteFallback() { return ( @@ -102,6 +103,7 @@ export function Router() { } /> } /> } /> + } /> {/* Fallback */} diff --git a/frontend/src/features/rocket-simulator/physics.ts b/frontend/src/features/rocket-simulator/physics.ts new file mode 100644 index 0000000..8946f08 --- /dev/null +++ b/frontend/src/features/rocket-simulator/physics.ts @@ -0,0 +1,249 @@ +import type { FlightEvent, RocketConfig, RocketStage, SimulationState } from './types'; +import { clamp, layoutForRocket } from './sceneMath'; +import { resolveStage1 } from './stageSplit'; + +const G0 = 9.80665; +const EARTH_RADIUS = 6_371_000; +const SEA_LEVEL_DENSITY = 1.225; +const SCALE_HEIGHT = 8_500; +/** 名义一级 / 二级工作时间(秒),用于把俯仰程序按级次进度归一化。 */ +const NOMINAL_STAGE1_BURN_S = 150; +const NOMINAL_STAGE2_BURN_S = 380; +/** 捆绑助推器在一级推进剂消耗到这个比例时分离。 */ +const BOOSTER_SEPARATION_FUEL_RATIO = 0.45; + +/** + * 上升制导(简易显式制导)。 + * + * 低空垂直起飞,之后按级次进度把俯仰角从 90° 逐渐压到接近水平; + * 同时跟踪一条随高度衰减的目标垂直速度曲线,垂速偏低就抬头、偏高就压平, + * 并在入轨前不允许掉高度。这样火箭能真正达到配置里的目标轨道高度与目标速度。 + */ +function guidancePitch({ + altitude, + verticalVelocity, + secondsInStage, + stage, + pitch, + dt, + targetAltitude, +}: { + altitude: number; + verticalVelocity: number; + secondsInStage: number; + stage: 1 | 2; + pitch: number; + dt: number; + targetAltitude: number; +}): number { + const progress = Math.min(1, Math.max(0, secondsInStage / (stage === 1 ? NOMINAL_STAGE1_BURN_S : NOMINAL_STAGE2_BURN_S))); + + let target: number; + if (stage === 1) { + target = altitude < 900 ? 90 : 90 - 58 * Math.pow(progress, 0.8); + } else { + target = Math.max(4, 30 - 26 * Math.pow(progress, 0.9)); + } + + // 目标垂直速度随高度衰减到 0;跟不上就抬头,超了就压平。 + const targetVertical = Math.max(0, 780 * Math.pow(Math.max(0, 1 - altitude / (targetAltitude * 1.2)), 1.5)); + const error = targetVertical - verticalVelocity; + if (error > 30) target = Math.min(90, target + Math.min(24, (error - 30) * 0.02)); + else if (error < -80) target = Math.max(0, target - Math.min(12, (-error - 80) * 0.015)); + + // 入轨前保持正垂速,避免在中途掉高度。 + if (stage === 2 && altitude < targetAltitude * 0.985 && verticalVelocity < 30) { + target = Math.max(target, 34); + } + + // 限制俯仰角变化速率,姿态过渡更平滑。 + const maxRate = 1.2 * dt; + return clamp(pitch + clamp(target - pitch, -maxRate, maxRate), 0, 90); +} + +export function addEvent(events: FlightEvent[], id: string, label: string, time: number) { + if (events.some((event) => event.id === id)) return events; + return [...events, { id, label, time }]; +} + +/** MAX-Q 要在步与步之间记住动压峰值,它不属于飞行状态,因此放在模拟上下文里。 */ +export interface SimulationContext { + maxQ: number; +} + +/** + * 单个物理步:推进 dt 秒的飞行状态与任务时序。 + * + * 直接改写传入的 state(调用方负责传副本)。这里不依赖 React, + * 因此可以用脚本把全部型号的完整任务跑一遍,验证分离与入轨时序。 + */ +export function stepSimulation( + next: SimulationState, + config: RocketConfig, + ctx: SimulationContext, + dt: number, +): void { + // 「助推器还在点火」要在烧油之前记下,否则同一帧内看不出它刚刚分离 + const boostersAttachedBefore = config.boosters != null && next.boosterFuel > 0; + + const phaseElapsed = next.time - next.phaseStartedAt; + const split = resolveStage1(config); + let activeStage: RocketStage | null = null; + + if (next.phase === 'stage1_burn') activeStage = config.stage_1; + if (next.phase === 'stage2_ignition' || next.phase === 'stage2_burn') activeStage = config.stage_2; + + if (next.phase === 'stage1_cutoff' && phaseElapsed >= 0.8) { + next.phase = 'separating'; + next.phaseStartedAt = next.time; + next.events = addEvent(next.events, 'separation', '一二级分离', next.time); + } else if (next.phase === 'separating' && phaseElapsed >= config.separation_delay_seconds) { + next.phase = 'stage2_ignition'; + next.phaseStartedAt = next.time; + next.events = addEvent(next.events, 'ses1', '二级发动机点火', next.time); + } else if ( + next.phase === 'stage2_ignition' && + phaseElapsed >= config.second_stage_ignition_delay_seconds + ) { + next.phase = 'stage2_burn'; + next.phaseStartedAt = next.time; + } else if (next.phase === 'orbit' && phaseElapsed >= 2) { + next.phase = 'payload_deploy'; + next.phaseStartedAt = 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; + next.events = addEvent(next.events, 'complete', '模拟任务完成', next.time); + } + + const stage1Attached = next.phase === 'stage1_burn' || next.phase === 'stage1_cutoff'; + const boostersAttached = stage1Attached && split.boosters !== null && next.boosterFuel > 0; + // stage1Fuel 是一级总余量(芯级 + 助推器),扣掉助推器余量才是芯级余量; + // 助推器分离后它的质量与推力一起从箭体上消失。 + const coreFuel = Math.max(0, next.stage1Fuel - next.boosterFuel); + const stage1Mass = stage1Attached + ? split.coreDryKg + coreFuel + (boostersAttached ? split.boosters!.dryKg + next.boosterFuel : 0) + : 0; + const totalMass = Math.max( + 1, + stage1Mass + config.stage_2.dry_mass_kg + next.stage2Fuel + config.payload_mass_kg, + ); + + let thrust = 0; + if (activeStage) { + const ignitionRamp = next.phase === 'stage2_ignition' + ? Math.min(1, phaseElapsed / Math.max(0.25, config.second_stage_ignition_delay_seconds)) + : 1; + if (activeStage === config.stage_1) { + const boosterThrustN = boostersAttached && split.boosters ? split.boosters.thrustN : 0; + thrust = (boosterThrustN + split.coreThrustN) * next.throttle * ignitionRamp; + const coreBurn = (split.coreThrustN * next.throttle * ignitionRamp) / (split.coreIspS * G0) * dt; + if (split.boosters) { + const boosterBurn = boostersAttached + ? Math.min(next.boosterFuel, (boosterThrustN * next.throttle * ignitionRamp) / (split.boosters.ispS * G0) * dt) + : 0; + next.boosterFuel -= boosterBurn; + next.stage1Fuel = Math.max(0, next.stage1Fuel - boosterBurn - coreBurn); + } else { + next.stage1Fuel = Math.max(0, next.stage1Fuel - coreBurn); + } + } else { + thrust = activeStage.max_thrust_n * next.throttle * ignitionRamp; + next.stage2Fuel = Math.max(0, next.stage2Fuel - thrust / (activeStage.specific_impulse_s * G0) * dt); + } + } + + if (next.phase === 'stage1_burn' && next.stage1Fuel <= 0) { + next.phase = 'stage1_cutoff'; + next.phaseStartedAt = next.time; + next.events = addEvent(next.events, 'meco', '一级发动机关机', next.time); + thrust = 0; + } + + // 捆绑助推器在一级飞行中先于芯级分离:登记了助推器参数就按助推器推进剂 + // 烧完的真实时刻,没登记才退回「一级推进剂消耗到 45%」的经验比例。 + if (next.phase === 'stage1_burn') { + if (split.boosters) { + if (boostersAttachedBefore && next.boosterFuel <= 0) { + next.events = addEvent(next.events, 'booster-sep', '助推器分离', next.time); + } + } else if ( + layoutForRocket(config).layout === 'boosters' && + next.stage1Fuel <= config.stage_1.fuel_mass_kg * BOOSTER_SEPARATION_FUEL_RATIO + ) { + next.events = addEvent(next.events, 'booster-sep', '助推器分离', next.time); + } + } + + const targetAltitude = config.target_orbit_km * 1000; + const stageElapsed = next.time - next.phaseStartedAt; + next.pitch = guidancePitch({ + altitude: next.altitude, + verticalVelocity: next.verticalVelocity, + secondsInStage: stageElapsed, + stage: stage1Attached ? 1 : 2, + pitch: next.pitch, + dt, + targetAltitude, + }); + + const velocity = Math.hypot(next.horizontalVelocity, next.verticalVelocity); + const density = next.altitude > 120_000 + ? 0 + : SEA_LEVEL_DENSITY * Math.exp(-next.altitude / SCALE_HEIGHT); + next.dynamicPressure = 0.5 * density * velocity * velocity; + + // MAX-Q: the moment aerodynamic pressure peaks and begins to fall on + // ascent. Track the running peak, then latch the event once q drops + // meaningfully below it (after a sensible threshold to avoid noise). + if (next.dynamicPressure > ctx.maxQ) { + ctx.maxQ = next.dynamicPressure; + } else if ( + ctx.maxQ > 8000 && + next.dynamicPressure < ctx.maxQ * 0.92 && + !next.events.some((event) => event.id === 'maxq') + ) { + next.events = addEvent(next.events, 'maxq', '最大动压 MAX-Q', next.time); + } + + const dragForce = next.dynamicPressure * config.drag_coefficient * config.reference_area_m2; + const pitchRadians = next.pitch * Math.PI / 180; + const gravity = G0 * Math.pow(EARTH_RADIUS / (EARTH_RADIUS + next.altitude), 2); + const dragX = velocity > 0 ? dragForce * next.horizontalVelocity / velocity : 0; + const dragY = velocity > 0 ? dragForce * next.verticalVelocity / velocity : 0; + // 离心卸载:水平速度越快,维持高度所需的垂直推力越小, + // 达到环绕速度后自然「浮」在轨道上(否则火箭无法真正入轨)。 + const centrifugal = next.horizontalVelocity * next.horizontalVelocity / (EARTH_RADIUS + next.altitude); + const ax = (thrust * Math.cos(pitchRadians) - dragX) / totalMass; + const ay = (thrust * Math.sin(pitchRadians) - dragY) / totalMass - gravity + centrifugal; + + next.horizontalVelocity = Math.max(0, next.horizontalVelocity + ax * dt); + next.verticalVelocity += ay * dt; + next.downrange += next.horizontalVelocity * dt; + next.altitude = Math.max(0, next.altitude + next.verticalVelocity * dt); + next.velocity = Math.hypot(next.horizontalVelocity, next.verticalVelocity); + next.acceleration = Math.hypot(ax, ay); + next.time += dt; + + // 只在二级动力飞行阶段判定入轨:否则入轨后条件持续成立, + // 会不断重置阶段计时,导致任务永远停在「轨道注入」。 + const poweredSecondStage = next.phase === 'stage2_burn' || next.phase === 'stage2_ignition'; + if ( + poweredSecondStage && + ( + next.stage2Fuel <= 0 || + (next.altitude >= targetAltitude && next.horizontalVelocity >= config.target_velocity_mps) + ) + ) { + next.phase = 'orbit'; + next.phaseStartedAt = next.time; + next.events = addEvent(next.events, 'seco', '二级发动机关机', next.time); + next.events = addEvent(next.events, 'orbit', '进入目标轨道', next.time); + } +} diff --git a/frontend/src/features/rocket-simulator/rocket-simulator.css b/frontend/src/features/rocket-simulator/rocket-simulator.css index d67852e..3d9c492 100644 --- a/frontend/src/features/rocket-simulator/rocket-simulator.css +++ b/frontend/src/features/rocket-simulator/rocket-simulator.css @@ -956,72 +956,6 @@ background: linear-gradient(0deg, rgba(3, 4, 5, 0.97) 55%, rgba(3, 4, 5, 0.72) 82%, transparent); } -.sx-bottom-left { - flex: 0 0 300px; - display: flex; - flex-direction: column; - gap: 8px; -} - -.sx-env { - padding: 8px 11px; - display: flex; - flex-direction: column; - border-left: 2px solid var(--amber); - background: rgba(255, 255, 255, 0.03); -} - -.sx-env-code { - color: var(--amber); - font-size: 8px; - font-weight: 800; - letter-spacing: 0.14em; - font-family: var(--mono); -} - -.sx-env strong { - margin-top: 2px; - font-size: 12.5px; - font-weight: 650; -} - -.sx-env small { - margin-top: 2px; - color: var(--muted); - font-size: 9px; -} - -.sx-next-event { - padding: 8px 11px; - display: flex; - align-items: baseline; - gap: 9px; - border-left: 2px solid var(--green); - background: rgba(255, 255, 255, 0.03); -} - -.sx-next-event > span { - color: #6d7573; - font-size: 8px; - font-weight: 750; - letter-spacing: 0.1em; -} - -.sx-next-event > b { - color: var(--green-bright); - font-size: 13px; - font-family: var(--mono); - letter-spacing: 0.06em; -} - -.sx-next-event > small { - overflow: hidden; - color: #9aa3a0; - font-size: 9px; - text-overflow: ellipsis; - white-space: nowrap; -} - .sx-bottom-center { flex: 1 1 auto; min-width: 240px; @@ -1091,76 +1025,69 @@ outline: none; } -/* ---------- engine gauge ---------- */ +/* ---------- engine bank ---------- */ -.sx-engine-gauge { +.sx-engine-bank { position: relative; - width: 108px; - height: 84px; - flex: 0 0 108px; - text-align: center; + z-index: 1; + flex: 0 0 auto; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; } -/* 发动机示意图容器:本身不画圆,圆由每个发动机舱(.sx-engine-group)画出 */ -.sx-engine-ring { - --engine-radius: 20px; - position: relative; - width: 66px; - height: 66px; - margin: 0 auto; +/* 芯级与每个助推器各占一格,排成一行并底部对齐,直径比例即真实的直径之比 */ +.sx-engine-row { + display: flex; + align-items: flex-end; + gap: 10px; } -/* 一组发动机 = 一个发动机舱;--gx/--gy 是舱心相对芯级轴心的平面位置 */ -.sx-engine-group { - --group-radius: 26px; - position: absolute; - top: 50%; - left: 50%; - width: calc(var(--group-radius) * 2); - height: calc(var(--group-radius) * 2); +.sx-engine-unit { + position: relative; + width: var(--unit); + height: var(--unit); box-sizing: border-box; - border: 2px solid rgba(235, 240, 238, 0.6); + border: 2px solid rgba(235, 240, 238, 0.55); border-radius: 50%; - transform: translate(-50%, -50%) translate(var(--gx, 0px), var(--gy, 0px)); } -.sx-engine-ring i { +/* 发动机点位:按 3D 模型同一套布局给出的归一化坐标定位 */ +.sx-engine-dot { position: absolute; top: 50%; left: 50%; width: var(--dot, 8px); height: var(--dot, 8px); + box-sizing: border-box; border: 1px solid #6a726f; border-radius: 50%; background: #232827; + transform: translate(-50%, -50%) + translate(calc(var(--dx) * var(--engine-radius)), calc(var(--dy) * var(--engine-radius))); transition: background 180ms, border-color 180ms, box-shadow 180ms; } -/* 发动机点位:按 3D 模型同一套布局给出的归一化坐标定位 */ -.sx-engine-dot { - transform: translate(-50%, -50%) - translate(calc(var(--dx) * var(--engine-radius)), calc(var(--dy) * var(--engine-radius))); -} - +/* 历史遗留的点位变体,当前 JSX 未再输出对应类名 */ .sx-engine-center { transform: translate(-50%, -50%); } .sx-engine-outer { transform: translate(-50%, -50%) rotate(var(--engine-angle)) translateY(calc(var(--engine-radius) * -1)); } -.sx-engine-ring i.active { +.sx-engine-unit.lit .sx-engine-dot { border-color: #ffe2a4; background: var(--amber); box-shadow: 0 0 6px rgba(245, 196, 81, 0.75); } -.sx-engine-gauge > span { - display: block; - margin-top: 3px; +.sx-engine-caption { color: #858d8a; - font-size: 7px; + font-size: 8px; font-weight: 750; - letter-spacing: 0.08em; + letter-spacing: 0.06em; + white-space: nowrap; } /* ---------- attitude gauge ---------- */ @@ -1270,7 +1197,6 @@ .sx-right { width: 258px; } .sx-data-row.hero strong { font-size: 23px; } .sx-bottom { gap: 14px; } - .sx-bottom-left { flex-basis: 260px; } .sx-clock { font-size: 38px; } } @@ -1280,7 +1206,7 @@ .sx-mission-status { min-width: 128px; } .sx-select:not(.sx-select--speed) { width: 240px; } .sx-left { display: none; } - .sx-bottom-right .sx-engine-gauge { display: none; } + .sx-engine-bank { display: none; } .sx-timeline-track { height: 32px; } .sx-timeline-node > span, @@ -1331,20 +1257,6 @@ gap: 10px; } - .sx-bottom-left { - flex: 0 0 150px; - } - - .sx-env { padding: 6px 9px; } - .sx-env strong { font-size: 10.5px; } - .sx-env small, - .sx-next-event > span, - .sx-next-event > small { - display: none; - } - - .sx-next-event { padding: 6px 9px; } - .sx-bottom-center { min-width: 0; } .sx-clock { font-size: 26px; } @@ -1359,7 +1271,6 @@ } @media (max-width: 380px) { - .sx-bottom-left { flex-basis: 118px; } .sx-clock { font-size: 21px; } .sx-launch { width: 84px; font-size: 9px; } } diff --git a/frontend/src/features/rocket-simulator/stageSplit.ts b/frontend/src/features/rocket-simulator/stageSplit.ts new file mode 100644 index 0000000..ae19d71 --- /dev/null +++ b/frontend/src/features/rocket-simulator/stageSplit.ts @@ -0,0 +1,53 @@ +import type { RocketConfig } from './types'; + +/** + * 一级里「芯级」与「捆绑助推器」的拆分口径。 + * + * 数据库里 stage_1 始终登记一级合计(含助推器),boosters 登记其中属于助推器的那一组, + * 芯级用减法得到,因此不会出现两套数字互相矛盾;助推器单独登记比冲, + * 芯级比冲沿用 stage_1(那是整段一级的有效比冲,反推芯级比冲会算出错误的燃烧时间)。 + */ +export interface BoosterGroup { + count: number; + /** 全部助推器合计推力 */ + thrustN: number; + /** 助推器比冲 */ + ispS: number; + /** 全部助推器合计干重 */ + dryKg: number; + /** 全部助推器合计推进剂 */ + fuelKg: number; +} + +export interface Stage1Split { + coreThrustN: number; + coreIspS: number; + coreDryKg: number; + /** 未登记助推器参数时为 null,此时物理退回「一级整段」模型 */ + boosters: BoosterGroup | null; +} + +export function resolveStage1(rocket: RocketConfig): Stage1Split { + const stage1 = rocket.stage_1; + const preset = rocket.boosters; + if (!preset) { + return { + coreThrustN: stage1.max_thrust_n, + coreIspS: stage1.specific_impulse_s, + coreDryKg: stage1.dry_mass_kg, + boosters: null, + }; + } + return { + coreThrustN: Math.max(0, stage1.max_thrust_n - preset.thrust_n), + coreIspS: stage1.specific_impulse_s, + coreDryKg: Math.max(0, stage1.dry_mass_kg - preset.dry_mass_kg), + boosters: { + count: preset.count, + thrustN: preset.thrust_n, + ispS: preset.specific_impulse_s, + dryKg: preset.dry_mass_kg, + fuelKg: Math.min(preset.fuel_mass_kg, stage1.fuel_mass_kg), + }, + }; +} diff --git a/frontend/src/features/rocket-simulator/types.ts b/frontend/src/features/rocket-simulator/types.ts index 7d39590..2af33dd 100644 --- a/frontend/src/features/rocket-simulator/types.ts +++ b/frontend/src/features/rocket-simulator/types.ts @@ -28,6 +28,25 @@ export interface RocketAppearance { fairing?: boolean | null; } +/** + * 捆绑助推器组合参数(可选)。 + * + * 口径与一级一致,但只统计助推器这一组:thrust_n / dry_mass_kg / fuel_mass_kg + * 都是全部助推器的合计值。stage_1 始终是「一级合计(含助推器)」, + * 芯级 = stage_1 减去本组,因此不存在两套数字互相矛盾。 + */ +export interface RocketBoosters { + count: number; + /** 全部助推器合计推力,不含芯级 */ + thrust_n: number; + /** 助推器比冲;芯级比冲沿用 stage_1.specific_impulse_s */ + specific_impulse_s: number; + /** 全部助推器合计干重 */ + dry_mass_kg: number; + /** 全部助推器合计推进剂 */ + fuel_mass_kg: number; +} + export interface RocketConfig { id: number; code: string; @@ -52,6 +71,7 @@ export interface RocketConfig { stage_1: RocketStage; stage_2: RocketStage; appearance?: RocketAppearance | null; + boosters?: RocketBoosters | null; is_active: boolean; sort_order: number; created_at?: string; @@ -93,6 +113,11 @@ export interface SimulationState { pitch: number; dynamicPressure: number; stage1Fuel: number; + /** + * 助推器剩余推进剂。stage1Fuel 是一级总余量(芯级 + 助推器), + * 芯级余量 = stage1Fuel - boosterFuel,所以分离后 S1% 的读法不变。 + */ + boosterFuel: number; stage2Fuel: number; throttle: number; phase: FlightPhase; diff --git a/frontend/src/features/rocket-simulator/useRocketSimulation.ts b/frontend/src/features/rocket-simulator/useRocketSimulation.ts index 294b8fa..7cd2722 100644 --- a/frontend/src/features/rocket-simulator/useRocketSimulation.ts +++ b/frontend/src/features/rocket-simulator/useRocketSimulation.ts @@ -1,65 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; -import type { FlightEvent, FlightPhase, RocketConfig, SimulationState } from './types'; -import { clamp, layoutForRocket } from './sceneMath'; - -const G0 = 9.80665; -const EARTH_RADIUS = 6_371_000; -const SEA_LEVEL_DENSITY = 1.225; -const SCALE_HEIGHT = 8_500; -/** 名义一级 / 二级工作时间(秒),用于把俯仰程序按级次进度归一化。 */ -const NOMINAL_STAGE1_BURN_S = 150; -const NOMINAL_STAGE2_BURN_S = 380; -/** 捆绑助推器在一级推进剂消耗到这个比例时分离。 */ -const BOOSTER_SEPARATION_FUEL_RATIO = 0.45; - -/** - * 上升制导(简易显式制导)。 - * - * 低空垂直起飞,之后按级次进度把俯仰角从 90° 逐渐压到接近水平; - * 同时跟踪一条随高度衰减的目标垂直速度曲线,垂速偏低就抬头、偏高就压平, - * 并在入轨前不允许掉高度。这样火箭能真正达到配置里的目标轨道高度与目标速度。 - */ -function guidancePitch({ - altitude, - verticalVelocity, - secondsInStage, - stage, - pitch, - dt, - targetAltitude, -}: { - altitude: number; - verticalVelocity: number; - secondsInStage: number; - stage: 1 | 2; - pitch: number; - dt: number; - targetAltitude: number; -}): number { - const progress = Math.min(1, Math.max(0, secondsInStage / (stage === 1 ? NOMINAL_STAGE1_BURN_S : NOMINAL_STAGE2_BURN_S))); - - let target: number; - if (stage === 1) { - target = altitude < 900 ? 90 : 90 - 58 * Math.pow(progress, 0.8); - } else { - target = Math.max(4, 30 - 26 * Math.pow(progress, 0.9)); - } - - // 目标垂直速度随高度衰减到 0;跟不上就抬头,超了就压平。 - const targetVertical = Math.max(0, 780 * Math.pow(Math.max(0, 1 - altitude / (targetAltitude * 1.2)), 1.5)); - const error = targetVertical - verticalVelocity; - if (error > 30) target = Math.min(90, target + Math.min(24, (error - 30) * 0.02)); - else if (error < -80) target = Math.max(0, target - Math.min(12, (-error - 80) * 0.015)); - - // 入轨前保持正垂速,避免在中途掉高度。 - if (stage === 2 && altitude < targetAltitude * 0.985 && verticalVelocity < 30) { - target = Math.max(target, 34); - } - - // 限制俯仰角变化速率,姿态过渡更平滑。 - const maxRate = 1.2 * dt; - return clamp(pitch + clamp(target - pitch, -maxRate, maxRate), 0, 90); -} +import type { FlightPhase, RocketConfig, SimulationState } from './types'; +import { addEvent, stepSimulation, type SimulationContext } from './physics'; function initialState(rocket: RocketConfig): SimulationState { return { @@ -73,6 +14,7 @@ function initialState(rocket: RocketConfig): SimulationState { pitch: 90, dynamicPressure: 0, stage1Fuel: rocket.stage_1.fuel_mass_kg, + boosterFuel: rocket.boosters?.fuel_mass_kg ?? 0, stage2Fuel: rocket.stage_2.fuel_mass_kg, throttle: 1, phase: 'ready', @@ -83,11 +25,6 @@ function initialState(rocket: RocketConfig): SimulationState { }; } -function addEvent(events: FlightEvent[], id: string, label: string, time: number) { - if (events.some((event) => event.id === id)) return events; - return [...events, { id, label, time }]; -} - export function useRocketSimulation(rocket: RocketConfig) { const [state, setState] = useState(() => initialState(rocket)); const [speed, setSpeed] = useState(1); @@ -95,7 +32,7 @@ export function useRocketSimulation(rocket: RocketConfig) { const rocketRef = useRef(rocket); const frameRef = useRef(0); const lastFrameRef = useRef(0); - const maxQRef = useRef(0); + const ctxRef = useRef({ maxQ: 0 }); const speedRef = useRef(speed); useEffect(() => { @@ -110,7 +47,7 @@ export function useRocketSimulation(rocket: RocketConfig) { const reset = useCallback(() => { const next = initialState(rocketRef.current); lastFrameRef.current = performance.now(); - maxQRef.current = 0; + ctxRef.current.maxQ = 0; commit(next); }, [commit]); @@ -158,147 +95,10 @@ export function useRocketSimulation(rocket: RocketConfig) { const steps = Math.max(1, Math.ceil(elapsed / 0.04)); const dt = elapsed / steps; const next = { ...current, events: [...current.events], history: [...current.history] }; + const config = rocketRef.current; - const hasBoosters = layoutForRocket(config).layout === 'boosters'; - for (let index = 0; index < steps; index += 1) { - const phaseElapsed = next.time - next.phaseStartedAt; - let activeStage = null; - - if (next.phase === 'stage1_burn') activeStage = config.stage_1; - if (next.phase === 'stage2_ignition' || next.phase === 'stage2_burn') activeStage = config.stage_2; - - if (next.phase === 'stage1_cutoff' && phaseElapsed >= 0.8) { - next.phase = 'separating'; - next.phaseStartedAt = next.time; - next.events = addEvent(next.events, 'separation', '一二级分离', next.time); - } else if (next.phase === 'separating' && phaseElapsed >= config.separation_delay_seconds) { - next.phase = 'stage2_ignition'; - next.phaseStartedAt = next.time; - next.events = addEvent(next.events, 'ses1', '二级发动机点火', next.time); - } else if ( - next.phase === 'stage2_ignition' && - phaseElapsed >= config.second_stage_ignition_delay_seconds - ) { - next.phase = 'stage2_burn'; - next.phaseStartedAt = next.time; - } else if (next.phase === 'orbit' && phaseElapsed >= 2) { - next.phase = 'payload_deploy'; - next.phaseStartedAt = 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; - next.events = addEvent(next.events, 'complete', '模拟任务完成', next.time); - } - - const stage1Attached = next.phase === 'stage1_burn' || next.phase === 'stage1_cutoff'; - const stage1Mass = stage1Attached ? config.stage_1.dry_mass_kg + next.stage1Fuel : 0; - const totalMass = Math.max( - 1, - stage1Mass + config.stage_2.dry_mass_kg + next.stage2Fuel + config.payload_mass_kg, - ); - - let thrust = 0; - if (activeStage) { - const ignitionRamp = next.phase === 'stage2_ignition' - ? Math.min(1, phaseElapsed / Math.max(0.25, config.second_stage_ignition_delay_seconds)) - : 1; - thrust = activeStage.max_thrust_n * next.throttle * ignitionRamp; - const burn = thrust / (activeStage.specific_impulse_s * G0) * dt; - if (activeStage === config.stage_1) { - next.stage1Fuel = Math.max(0, next.stage1Fuel - burn); - } else { - next.stage2Fuel = Math.max(0, next.stage2Fuel - burn); - } - } - - if (next.phase === 'stage1_burn' && next.stage1Fuel <= 0) { - next.phase = 'stage1_cutoff'; - next.phaseStartedAt = next.time; - next.events = addEvent(next.events, 'meco', '一级发动机关机', next.time); - thrust = 0; - } - - // 捆绑助推器(长征五号一类)在一级飞行中先于芯级分离 - if ( - hasBoosters && - next.phase === 'stage1_burn' && - next.stage1Fuel <= config.stage_1.fuel_mass_kg * BOOSTER_SEPARATION_FUEL_RATIO - ) { - next.events = addEvent(next.events, 'booster-sep', '助推器分离', next.time); - } - - const targetAltitude = config.target_orbit_km * 1000; - const stageElapsed = next.time - next.phaseStartedAt; - next.pitch = guidancePitch({ - altitude: next.altitude, - verticalVelocity: next.verticalVelocity, - secondsInStage: stageElapsed, - stage: stage1Attached ? 1 : 2, - pitch: next.pitch, - dt, - targetAltitude, - }); - - const velocity = Math.hypot(next.horizontalVelocity, next.verticalVelocity); - const density = next.altitude > 120_000 - ? 0 - : SEA_LEVEL_DENSITY * Math.exp(-next.altitude / SCALE_HEIGHT); - next.dynamicPressure = 0.5 * density * velocity * velocity; - - // MAX-Q: the moment aerodynamic pressure peaks and begins to fall on - // ascent. Track the running peak, then latch the event once q drops - // meaningfully below it (after a sensible threshold to avoid noise). - if (next.dynamicPressure > maxQRef.current) { - maxQRef.current = next.dynamicPressure; - } else if ( - maxQRef.current > 8000 && - next.dynamicPressure < maxQRef.current * 0.92 && - !next.events.some((event) => event.id === 'maxq') - ) { - next.events = addEvent(next.events, 'maxq', '最大动压 MAX-Q', next.time); - } - - const dragForce = next.dynamicPressure * config.drag_coefficient * config.reference_area_m2; - const pitchRadians = next.pitch * Math.PI / 180; - const gravity = G0 * Math.pow(EARTH_RADIUS / (EARTH_RADIUS + next.altitude), 2); - const dragX = velocity > 0 ? dragForce * next.horizontalVelocity / velocity : 0; - const dragY = velocity > 0 ? dragForce * next.verticalVelocity / velocity : 0; - // 离心卸载:水平速度越快,维持高度所需的垂直推力越小, - // 达到环绕速度后自然「浮」在轨道上(否则火箭无法真正入轨)。 - const centrifugal = next.horizontalVelocity * next.horizontalVelocity / (EARTH_RADIUS + next.altitude); - const ax = (thrust * Math.cos(pitchRadians) - dragX) / totalMass; - const ay = (thrust * Math.sin(pitchRadians) - dragY) / totalMass - gravity + centrifugal; - - next.horizontalVelocity = Math.max(0, next.horizontalVelocity + ax * dt); - next.verticalVelocity += ay * dt; - next.downrange += next.horizontalVelocity * dt; - next.altitude = Math.max(0, next.altitude + next.verticalVelocity * dt); - next.velocity = Math.hypot(next.horizontalVelocity, next.verticalVelocity); - next.acceleration = Math.hypot(ax, ay); - next.time += dt; - - // 只在二级动力飞行阶段判定入轨:否则入轨后条件持续成立, - // 会不断重置阶段计时,导致任务永远停在「轨道注入」。 - const poweredSecondStage = next.phase === 'stage2_burn' || next.phase === 'stage2_ignition'; - if ( - poweredSecondStage && - ( - next.stage2Fuel <= 0 || - (next.altitude >= targetAltitude && next.horizontalVelocity >= config.target_velocity_mps) - ) - ) { - next.phase = 'orbit'; - next.phaseStartedAt = next.time; - next.events = addEvent(next.events, 'seco', '二级发动机关机', next.time); - next.events = addEvent(next.events, 'orbit', '进入目标轨道', next.time); - } + stepSimulation(next, config, ctxRef.current, dt); } const lastPoint = next.history.at(-1); diff --git a/frontend/src/pages/RocketSimulator.tsx b/frontend/src/pages/RocketSimulator.tsx index 185f005..0b761e8 100644 --- a/frontend/src/pages/RocketSimulator.tsx +++ b/frontend/src/pages/RocketSimulator.tsx @@ -56,15 +56,6 @@ function formatTime(seconds: number) { return `T${sign}${h > 0 ? `${pad(h)}:` : ''}${pad(m)}:${pad(s)}`; } -function environmentAt(altitude: number, targetOrbitKm: number) { - if (altitude < 1_000) return { code: 'GROUND', label: '地面与近地层', detail: '对流层 · 稠密大气' }; - if (altitude < 12_000) return { code: 'TROPOSPHERE', label: '对流层', detail: '气动载荷区' }; - if (altitude < 50_000) return { code: 'STRATOSPHERE', label: '平流层', detail: '大气快速变稀' }; - if (altitude < 100_000) return { code: 'MESOSPHERE', label: '高层大气', detail: '接近卡门线' }; - if (altitude < targetOrbitKm * 950) return { code: 'SPACE', label: '近地太空', detail: '卡门线以上' }; - return { code: 'LEO', label: '低地球轨道', detail: `目标高度 ${targetOrbitKm.toFixed(0)} km` }; -} - /* ------------------------------------------------------------------ */ /* Vehicle stack: the dashboard shows exactly what the 3D scene shows — */ /* full rocket → second stage after separation → payload at deploy. */ @@ -394,11 +385,12 @@ function FlightData({ state, history, totalFuelPct, stage1FuelPct, stage2FuelPct /* ------------------------------------------------------------------ */ /** - * 发动机示意图:按真实平面构型画出芯级与每个助推器的发动机舱。 - * 分组取自 stage1EngineGroups,与 3D 模型的喷管/尾焰同源, - * 因此带助推器的火箭不会再把 27 台画成芯级上的一个圆环。 + * 发动机仪表组:芯级与每个助推器各自画一个圆环,助推器圆的直径按 + * 「助推器直径 / 芯级直径」等比缩放,全部排在同一行、底部对齐, + * 这样一眼就能看出几个助推器、每个舱里几台机、现在哪些在点火。 + * 分组取自 stage1EngineGroups,与 3D 模型的喷管/尾焰同源。 */ -function EngineGauge({ +function EngineBank({ label, groups, lit, @@ -413,38 +405,42 @@ function EngineGauge({ 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); - // 以最外侧发动机舱边缘为基准换算像素,保证三芯级并排也放得下 - const span = Math.max(...groups.map((group) => group.offset + group.radius)); - const pxPerUnit = 26 / span; + const coreEngines = groups.filter((group) => group.kind === 'core').reduce((sum, group) => sum + group.engines, 0); + const boosters = groups.filter((group) => group.kind === 'booster'); + // 直径以芯级为基准(radius = 1),按左侧栏可用宽度整体缩放,四助推器也放得下 + const gap = 10; + const diameterSum = groups.reduce((sum, group) => sum + group.radius, 0); + const base = Math.max(18, Math.min(58, (268 - gap * (groups.length - 1)) / diameterSum)); + const caption = boosters.length > 0 + ? `${label} · 芯级 ${coreEngines} + 助推器 ${boosters.length}×${boosters[0].engines} · 共 ${total} 台` + : `${label} · 共 ${total} 台`; + return ( -
-
+
+
{groups.map((group, index) => { - const cluster = group.radius * pxPerUnit; - const ringRadius = cluster * 0.7; + const unit = base * group.radius; // 机数多的舱室缩小点位,避免十几个点糊成一团 + const orbit = unit * 0.28; const dot = group.engines > 4 - ? Math.min(8, Math.max(3, (Math.PI * 2 * ringRadius) / (group.engines * 1.7))) - : Math.min(8, Math.max(4, cluster * 0.5)); - const placements = engineLayout(group.engines, 1); + ? Math.min(8, Math.max(3, (Math.PI * 2 * orbit) / (group.engines * 1.7))) + : Math.min(9, Math.max(4, unit * 0.2)); return (
- {placements.map((placement, dotIndex) => ( + {engineLayout(group.engines, 1).map((placement, dotIndex) => ( ))} @@ -452,7 +448,7 @@ function EngineGauge({ ); })}
- {label} + {caption}
); } @@ -486,7 +482,6 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) { const [viewScaleResetTrigger, setViewScaleResetTrigger] = useState(0); const rocket = rockets.find((item) => item.code === selectedCode) || rockets[0]; const { state, toggle, reset, speed, setSpeed } = useRocketSimulation(rocket); - const environment = environmentAt(state.altitude, rocket.target_orbit_km); const totalFuel = rocket.stage_1.fuel_mass_kg + rocket.stage_2.fuel_mass_kg; const remainingFuel = state.stage1Fuel + state.stage2Fuel; @@ -589,20 +584,14 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) { - {/* Bottom: environment + mission clock + progress + gauges + controls */} + {/* Bottom: engine bank + mission clock + progress + attitude + controls */}
-
-
- {environment.code} - {environment.label} - {rocket.launch_site_name} · {environment.detail} -
-
- NEXT EVENT - {nextMilestone ? nextMilestone.code : (state.phase === 'mission_complete' ? 'COMPLETE' : '—')} - {nextMilestone ? nextMilestone.label : '任务完成'} -
-
+
{clockText}
@@ -617,12 +606,6 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
-
diff --git a/frontend/src/pages/admin/RocketEvents.tsx b/frontend/src/pages/admin/RocketEvents.tsx new file mode 100644 index 0000000..a42845a --- /dev/null +++ b/frontend/src/pages/admin/RocketEvents.tsx @@ -0,0 +1,205 @@ +/** + * 火箭发射事件页面 + * + * 数据来自定时任务同步的 Launch Library,本页面只读: + * 按「即将发射 / 已结束 / 全部」浏览,并可模糊搜索任务、型号与发射场。 + */ +import { useCallback, useEffect, useState } from 'react'; +import { Segmented, Tag, Tooltip } from 'antd'; +import { RocketOutlined } from '@ant-design/icons'; +import type { ColumnsType } from 'antd/es/table'; +import { DataTable } from '../../components/admin/DataTable'; +import { AdminPage, HeaderStat } from '../../components/admin/AdminPage'; +import { useListPageSize } from './useListPageSize'; +import { request } from '../../utils/request'; +import { useToast } from '../../contexts/ToastContext'; + +interface RocketEvent { + id: number; + name: string; + mission_name: string | null; + mission_type: string | null; + rocket_name: string | null; + provider: string | null; + orbit: string | null; + launch_site_name: string | null; + location_name: string | null; + net: string; + status: string; + source_url: string | null; + rocket: { code: string; name: string; name_zh: string | null } | null; +} + +interface Stats { + total: number; + upcoming: number; + last_synced_at: string | null; +} + +/** 时间范围筛选:即将发射按时间升序,已结束按时间倒序。 */ +type RangeKey = 'upcoming' | 'past' | 'all'; + +const RANGE_OPTIONS = [ + { value: 'upcoming', label: '即将发射' }, + { value: 'past', label: '已结束' }, + { value: 'all', label: '全部' }, +] as const; + +/** 后端存的是不带时区的 UTC 时间,补上 Z 才能按本地时区正确显示。 */ +function formatNet(value: string) { + const iso = /Z|[+-]\d{2}:?\d{2}$/.test(value) ? value : `${value}Z`; + return new Date(iso).toLocaleString('zh-CN', { + month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', + }); +} + +export function RocketEvents() { + const systemPageSize = useListPageSize(); + const [data, setData] = useState([]); + const [loading, setLoading] = useState(false); + const [total, setTotal] = useState(0); + const [page, setPage] = useState(1); + const [range, setRange] = useState('upcoming'); + const [search, setSearch] = useState(''); + const [stats, setStats] = useState(null); + const toast = useToast(); + + const load = useCallback(async () => { + setLoading(true); + try { + const params = { + limit: systemPageSize, + offset: (page - 1) * systemPageSize, + upcoming: range === 'all' ? undefined : range === 'upcoming', + search: search.trim() || undefined, + }; + const [{ data: pageData }, { data: statsData }] = await Promise.all([ + request.get('/rocket-events', { params }), + request.get('/rocket-events/stats'), + ]); + setData(pageData.events || []); + setTotal(pageData.total || 0); + setStats(statsData); + } catch { + toast.error('加载火箭发射事件失败'); + } finally { + setLoading(false); + } + }, [page, range, search, systemPageSize, toast]); + + useEffect(() => { void load(); }, [load]); + + const columns: ColumnsType = [ + { + title: '发射时间', + dataIndex: 'net', + width: 130, + render: (value: string) => formatNet(value), + }, + { + title: '任务', + dataIndex: 'mission_name', + width: 240, + ellipsis: true, + render: (value: string | null, record) => value || record.name, + }, + { + title: '型号', + dataIndex: 'rocket_name', + width: 200, + ellipsis: true, + render: (value: string | null, record) => ( + + {value || '-'}{record.rocket ? 已关联 : null} + + ), + }, + { + title: '发射服务商', + dataIndex: 'provider', + width: 130, + render: (value: string | null) => value || '-', + }, + { + title: '轨道', + dataIndex: 'orbit', + width: 150, + ellipsis: true, + render: (value: string | null) => value || '-', + }, + { + title: '发射场', + dataIndex: 'launch_site_name', + width: 220, + ellipsis: true, + render: (value: string | null, record) => ( + + {value || record.location_name || '-'} + + ), + }, + { + title: '状态', + dataIndex: 'status', + width: 150, + render: (value: string) => {value || '-'}, + }, + { + title: '详情', + dataIndex: 'source_url', + width: 90, + render: (value: string | null) => ( + value + ? Launch Library + : '-' + ), + }, + ]; + + return ( + } + title="火箭发射事件" + description="由定时任务从 Launch Library 同步的真实发射计划,可与火箭数据管理的型号关联" + actions={ + <> + + + + + } + > + setPage(next)} + onRefresh={() => void load()} + onSearch={(value) => { setSearch(value); setPage(1); }} + searchPlaceholder="搜索任务名 / 型号 / 发射场" + toolbar={ + ({ value: item.value, label: item.label }))} + onChange={(value) => { setRange(value as RangeKey); setPage(1); }} + /> + } + rowKey="id" + showAdd={false} + showEdit={false} + /> + + ); +} + +function statusColor(status: string) { + const lower = status.toLowerCase(); + if (lower.includes('success')) return 'success'; + if (lower.includes('fail') || lower.includes('failure')) return 'error'; + if (lower.includes('launch') || lower.includes('go for')) return 'processing'; + if (lower.includes('hold')) return 'warning'; + return 'default'; +} diff --git a/frontend/src/pages/admin/Rockets.tsx b/frontend/src/pages/admin/Rockets.tsx index f4efdce..6fc4e0f 100644 --- a/frontend/src/pages/admin/Rockets.tsx +++ b/frontend/src/pages/admin/Rockets.tsx @@ -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, appearance: {} }; +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: {}, boosters: {} }; function NumberField({ name, label, suffix, min = 0, max, step }: { name: string | (string | number)[]; label: string; suffix?: string; min?: number; max?: number; step?: number }) { return ; @@ -47,6 +47,26 @@ function AppearanceFields() { ); } +/** + * 助推器参数(可选)。 + * + * 一级参数登记的是「芯级 + 助推器」的合计值,这里单独登记助推器那一组, + * 芯级由减法推导,因此捆绑构型的火箭才能算出真实的助推器分离与一级关机时序。 + * 整组留空即不拆分,一级按整体燃烧到关机。 + */ +function BoosterFields() { + return ( + + + + + + + + + ); +} + export function Rockets() { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); @@ -100,6 +120,8 @@ export function Rockets() { const save = async () => { try { const values = await form.validateFields(); + // 助推器是整组可选的:没填数量就当不拆分,避免把半个对象提交给后端 + if (!values.boosters?.count) values.boosters = null; if (editing) await request.put(`/rockets/admin/${editing.id}`, values); else await request.post('/rockets/admin', values); toast.success(editing ? '火箭配置已更新' : '火箭配置已创建'); @@ -182,6 +204,7 @@ export function Rockets() { { key: 'mission', label: '发射与任务', children: }, { key: 'stage1', label: '一级参数', children: }, { key: 'stage2', label: '二级参数', children: }, + { key: 'boosters', label: '助推器参数(可选)', children: }, { key: 'appearance', label: '外观构型(可选)', children: }, ]} />