增加了点火倒计时

main
mula.liu 2026-10-23 18:20:34 +08:00
parent 3ad329460c
commit 8153b4108f
10 changed files with 325 additions and 16 deletions

Binary file not shown.

View File

@ -6,7 +6,7 @@ import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib';
import type { RocketConfig, SimulationState } from './types';
import { useOptionalTexture } from '../../hooks/useOptionalTexture';
import { RocketModel } from './RocketModel';
import { clamp, fogColor, groundDrop, separationAge, skyColor, starOpacity, stageGeometry } from './sceneMath';
import { clamp, engineState, fogColor, groundDrop, separationAge, skyColor, starOpacity, stageGeometry } from './sceneMath';
export type CameraMode = 'follow' | 'global';
@ -334,7 +334,8 @@ function PadExhaust({ state }: { state: SimulationState }) {
useFrame(({ clock }) => {
if (!groupRef.current) return;
const burning = state.isRunning && state.throttle > 0.05 && state.altitude < 4_000;
// 只在发动机真正工作时喷烟:启动倒数阶段 isRunning 也是 true,不能提前起雾
const burning = engineState(state).stage1 && state.throttle > 0.05 && state.altitude < 4_000;
groupRef.current.visible = burning;
if (!burning) return;
const time = clock.elapsedTime * 0.5;

View File

@ -12,6 +12,9 @@ const NOMINAL_STAGE2_BURN_S = 380;
/** 捆绑助推器在一级推进剂消耗到这个比例时分离。 */
const BOOSTER_SEPARATION_FUEL_RATIO = 0.45;
/** 点火后的启动倒数时长(秒):火箭停在发射台上倒数 10→1,到零才真正起飞。 */
export const COUNTDOWN_SECONDS = 10;
/**
* 上升制导(简易显式制导)。
*
@ -93,6 +96,22 @@ export function stepSimulation(
if (next.phase === 'stage1_burn') activeStage = config.stage_1;
if (next.phase === 'stage2_ignition' || next.phase === 'stage2_burn') activeStage = config.stage_2;
// 启动倒数:箭体固定在发射台上,时间只用来驱动「10→1」的语音与显示,
// 到零才转入一级动力飞行并登记点火事件(此后物理循环才开始产生推力)。
if (next.phase === 'countdown') {
if (phaseElapsed >= COUNTDOWN_SECONDS) {
// 正式起飞:任务时间从 0 重新开始,之后所有事件与遥测都相对起飞时刻
next.phase = 'stage1_burn';
next.time = 0;
next.phaseStartedAt = 0;
next.history = [];
next.events = addEvent(next.events, 'liftoff', '点火起飞', 0);
return;
}
next.time += dt;
return;
}
if (next.phase === 'stage1_cutoff' && phaseElapsed >= 0.8) {
next.phase = 'separating';
next.phaseStartedAt = next.time;

View File

@ -1033,6 +1033,27 @@
letter-spacing: 0.02em;
}
/* 倒数归零、时钟从 T- 翻到 T+ 的那一刻:翻牌式翻转 + 一次辉光脉冲 */
.sx-clock--flip {
animation: sx-clock-flip 0.7s cubic-bezier(0.3, 0.9, 0.3, 1) both;
}
@keyframes sx-clock-flip {
0% {
transform: perspective(600px) rotateX(0deg) scale(1);
filter: brightness(1);
}
45% {
transform: perspective(600px) rotateX(90deg) scale(1.06);
filter: brightness(2.1);
text-shadow: 0 0 34px rgba(94, 234, 156, 0.95);
}
100% {
transform: perspective(600px) rotateX(0deg) scale(1);
filter: brightness(1);
}
}
.sx-realtime {
color: #8e9593;
display: flex;

View File

@ -440,7 +440,8 @@ export function starOpacity(altitude: number): number {
* still attached. Reads the recorded 'separation' event so it survives pauses.
*/
export function separationAge(state: SimulationState): number | null {
const attached = ['ready', 'stage1_burn', 'stage1_cutoff'].includes(state.phase);
// 启动倒数时箭体还钉在发射台上,一级同样未分离
const attached = ['ready', 'countdown', 'stage1_burn', 'stage1_cutoff'].includes(state.phase);
if (attached) return null;
const event = state.events.find((e) => e.id === 'separation');
if (!event) return Math.max(0, state.time - state.phaseStartedAt);

View File

@ -81,6 +81,7 @@ export interface RocketConfig {
export type FlightPhase =
| 'ready'
| 'countdown'
| 'stage1_burn'
| 'stage1_cutoff'
| 'separating'
@ -130,6 +131,7 @@ export interface SimulationState {
export const PHASE_LABELS: Record<FlightPhase, string> = {
ready: '等待点火',
countdown: '启动倒数',
stage1_burn: '一级动力飞行',
stage1_cutoff: '一级发动机关机',
separating: '一二级分离',

View File

@ -0,0 +1,180 @@
import { useEffect, useRef } from 'react';
import type { SimulationState } from './types';
/**
* 发射音效:
* - 启动倒数(countdown)阶段播一段 10→1→Lift off 的英文男声音频(预生成的
* countdown.m4a,整段一次播,始终按真实时间,不随模拟倍速缩放);
* - 点火起飞后启动一个用 Web Audio 合成的发动机轰鸣(噪声 + 低频脉动),
* 音量随飞行高度衰减,一级关机后彻底静下来。
* 两者共用一个 AudioContext,随暂停 / 重置 / 卸载一起停。
*/
const COUNTDOWN_SRC = '/upload/assets/countdown.m4a';
/** 火箭升到这个高度(米)时轰鸣基本听不见了,用来做音量衰减的终点。 */
const ROAR_FALLOFF_ALTITUDE = 45_000;
interface RoarNodes {
source: AudioBufferSourceNode;
gain: GainNode;
filter: BiquadFilterNode;
}
export function useLaunchAudio(state: SimulationState) {
const ctxRef = useRef<AudioContext | null>(null);
const countdownRef = useRef<HTMLAudioElement | null>(null);
const roarRef = useRef<RoarNodes | null>(null);
// 惰性建 AudioContext:必须在用户手势(点「执行点火」)之后才能 unlock。
const ensureContext = () => {
if (!ctxRef.current) {
const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
ctxRef.current = new Ctor();
}
if (ctxRef.current.state === 'suspended') {
void ctxRef.current.resume();
}
return ctxRef.current;
};
// 启动倒数:播 countdown.m4a,currentTime 归零重播;倒数不受倍速控制。
const playCountdown = () => {
const ctx = ensureContext();
if (!countdownRef.current) {
countdownRef.current = new Audio(COUNTDOWN_SRC);
countdownRef.current.preload = 'auto';
}
const audio = countdownRef.current;
if (audio.src !== COUNTDOWN_SRC) audio.src = COUNTDOWN_SRC;
audio.playbackRate = 1;
audio.currentTime = 0;
void audio.play().catch(() => undefined);
void ctx;
};
// 生成一小段循环的低频噪声缓冲,作为轰鸣的声源。
const makeRoarBuffer = (ctx: AudioContext) => {
const seconds = 2;
const buffer = ctx.createBuffer(1, ctx.sampleRate * seconds, ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i += 1) {
// 叠加两段不相关随机,再乘一个缓慢的正弦做「引擎脉动」,听起来更像涡轮而非白噪。
const lfo = Math.sin((i / ctx.sampleRate) * Math.PI * 2 * 7);
data[i] = (Math.random() * 2 - 1) * 0.5 + (Math.random() * 2 - 1) * 0.5 * lfo;
}
return buffer;
};
const startRoar = () => {
const ctx = ensureContext();
if (roarRef.current) return;
const source = ctx.createBufferSource();
source.buffer = makeRoarBuffer(ctx);
source.loop = true;
// 低通把噪声收窄到发动机低频段;截止频率随爬升下坠,轰鸣随之变闷。
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = 380;
filter.Q.value = 0.8;
const gain = ctx.createGain();
gain.gain.value = 0;
source.connect(filter);
filter.connect(gain);
gain.connect(ctx.destination);
source.start();
// 快速起噪到最大,随后交给 updateRoar 按高度衰减。
gain.gain.setTargetAtTime(0.9, ctx.currentTime, 0.15);
roarRef.current = { source, gain, filter };
};
const updateRoar = () => {
const ctx = ctxRef.current;
const roar = roarRef.current;
if (!ctx || !roar) return;
// 高度 0 时音量满格,升到 ROAR_FALLOFF_ALTITUDE 时归零,平方衰减更自然。
const t = Math.min(1, Math.max(0, state.altitude / ROAR_FALLOFF_ALTITUDE));
const level = (1 - t) * (1 - t) * 0.9;
const cutoff = 380 * (1 - t * 0.7);
roar.gain.gain.setTargetAtTime(level, ctx.currentTime, 0.2);
roar.filter.frequency.setTargetAtTime(cutoff, ctx.currentTime, 0.2);
};
const stopRoar = () => {
const ctx = ctxRef.current;
const roar = roarRef.current;
if (!ctx || !roar) return;
roar.gain.gain.setTargetAtTime(0, ctx.currentTime, 0.4);
const toStop = roar;
roarRef.current = null;
// 留出淡出时间后再销毁节点。
window.setTimeout(() => {
try {
toStop.source.stop();
toStop.source.disconnect();
toStop.filter.disconnect();
toStop.gain.disconnect();
} catch {
// 节点可能已被回收,忽略即可。
}
}, 1200);
};
const stopCountdown = () => {
const audio = countdownRef.current;
if (audio) {
audio.pause();
audio.currentTime = 0;
}
};
const running = state.isRunning;
const phase = state.phase;
// 音效的启停只看这两个离散输入;读到的都是 ref(上下文、节点),
// 不需要把每次渲染重建的辅助函数列进依赖。
/* eslint-disable react-hooks/exhaustive-deps -- 依赖刻意收窄,理由见上 */
useEffect(() => {
// 倒数阶段播放语音。进入发射阶段时不截断,让最后的 "Lift off" 自然播完。
if (running && phase === 'countdown') {
playCountdown();
}
if (!running) {
stopCountdown();
}
// 轰鸣:一级动力飞行(含关机瞬间)保持轰鸣并按高度衰减;其余阶段停掉。
if (running && (phase === 'stage1_burn' || phase === 'stage1_cutoff')) {
startRoar();
updateRoar();
} else {
stopRoar();
}
}, [running, phase]);
// 飞行高度变化只更新轰鸣音量与滤波,不重启声源。
useEffect(() => {
updateRoar();
}, [state.altitude]);
// 暂停:把语音与轰鸣一起停。
useEffect(() => {
if (!running) {
stopCountdown();
stopRoar();
}
}, [running]);
// 卸载时释放 AudioContext。
useEffect(
() => () => {
stopCountdown();
stopRoar();
void ctxRef.current?.close();
},
[],
);
return { unlock: ensureContext };
}

View File

@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { FlightPhase, RocketConfig, SimulationState } from './types';
import { addEvent, stepSimulation, type SimulationContext } from './physics';
import { stepSimulation, type SimulationContext } from './physics';
import { resolveStage1 } from './stageSplit';
function initialState(rocket: RocketConfig): SimulationState {
@ -75,12 +75,12 @@ export function useRocketSimulation(rocket: RocketConfig) {
const launching = current.phase === 'ready';
const next = {
...current,
phase: launching ? 'stage1_burn' as FlightPhase : current.phase,
// 点火先进入「启动倒数」阶段,火箭停在发射台上倒数 10→1;
// liftoff 事件在倒数到零、真正起飞时才由物理循环登记。
phase: launching ? 'countdown' as FlightPhase : current.phase,
phaseStartedAt: launching ? current.time : current.phaseStartedAt,
isRunning: !current.isRunning,
events: launching
? addEvent(current.events, 'liftoff', '点火起飞', current.time)
: current.events,
events: current.events,
};
lastFrameRef.current = performance.now();
commit(next);
@ -100,7 +100,9 @@ export function useRocketSimulation(rocket: RocketConfig) {
}
// 倍速播放:先限制单帧真实步长,再乘以倍速,避免切页回来时一次跳太多。
const elapsed = Math.min((timestamp - lastFrameRef.current) / 1000, 0.25) * speedRef.current;
// 启动倒数不吃倍速:无论几倍速都走满真实 10 秒,和倒数语音逐句对齐。
const multiplier = current.phase === 'countdown' ? 1 : speedRef.current;
const elapsed = Math.min((timestamp - lastFrameRef.current) / 1000, 0.25) * multiplier;
lastFrameRef.current = timestamp;
const steps = Math.max(1, Math.ceil(elapsed / 0.04));
const dt = elapsed / steps;

View File

@ -2,8 +2,10 @@ 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 { COUNTDOWN_SECONDS } from '../features/rocket-simulator/physics';
import { PHASE_LABELS, type FlightEvent, type FlightPhase, type RocketConfig } from '../features/rocket-simulator/types';
import { useRocketSimulation } from '../features/rocket-simulator/useRocketSimulation';
import { useLaunchAudio } from '../features/rocket-simulator/useLaunchAudio';
import { RocketFlightScene, type CameraMode } from '../features/rocket-simulator/RocketFlightScene';
import { TelemetryChart } from '../features/rocket-simulator/TelemetryChart';
import {
@ -48,14 +50,17 @@ function milestonesFor(rocket: RocketConfig) {
return list;
}
function formatTime(seconds: number) {
const sign = seconds < 0 ? '-' : '+';
function formatClock(start: 'T+' | 'T-', seconds: number) {
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)}`;
return `${start}${pad(h)}:${pad(m)}:${pad(s)}`;
}
function formatTime(seconds: number) {
return formatClock(seconds < 0 ? 'T-' : 'T+', seconds);
}
/* ------------------------------------------------------------------ */
@ -66,7 +71,7 @@ function formatTime(seconds: number) {
type StackMode = 'full' | 'stage2' | 'payload';
function stackModeFor(phase: FlightPhase): StackMode {
if (phase === 'ready' || phase === 'stage1_burn' || phase === 'stage1_cutoff') return 'full';
if (phase === 'ready' || phase === 'countdown' || phase === 'stage1_burn' || phase === 'stage1_cutoff') return 'full';
if (phase === 'payload_deploy' || phase === 'mission_complete') return 'payload';
return 'stage2';
}
@ -553,6 +558,8 @@ 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);
// 倒数语音 + 发动机轰鸣,全部走 Web Audio,随暂停/重置一起停
const launchAudio = useLaunchAudio(state);
// 一级推进剂的起点是「芯级 + 助推器」的合计(与 initialState 同一口径),
// 助推器烧完先分离,余量也随之归零,因此 S1% 会在那一刻下一个台阶
@ -587,7 +594,23 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
: state.phase === 'ready'
? '执行点火'
: '继续';
const clockText = state.phase === 'ready' && !state.isRunning ? 'T-00:00:00' : formatTime(state.time);
// 时钟:ready 显示 T-00:00:00;countdown 按整秒倒数 10→0(T-00:00:10 … T-00:00:00);
// 其余阶段是全新的 T+ 计时。倒数归零切换到 T+ 的瞬间触发一次翻转动画。
const countdownRemaining =
state.phase === 'countdown'
? Math.max(0, Math.ceil(COUNTDOWN_SECONDS - (state.time - state.phaseStartedAt)))
: null;
const clockText =
state.phase === 'ready' && !state.isRunning
? formatClock('T-', 0)
: countdownRemaining !== null
? formatClock('T-', countdownRemaining)
: formatTime(state.time);
// 倒数→T+ 的翻转动画直接从「liftoff 事件距今的时长」推导,不用 effect 改状态:
// 起飞后的头 0.7 秒时钟带着翻牌类名,之后自动消失。
const liftoffAt = state.events.find((event) => event.id === 'liftoff')?.time ?? null;
const clockFlip = liftoffAt !== null && state.time - liftoffAt < 0.7;
/*
* 左右两块面板:离地升空后自动收起,把画面让给箭体。
@ -699,7 +722,7 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
/>
<div className="sx-bottom-center">
<div className="sx-clock">{clockText}</div>
<div className={clockFlip ? 'sx-clock sx-clock--flip' : 'sx-clock'}>{clockText}</div>
<div className="sx-realtime"><Clock3 size={12} />MISSION TIME · REAL TIME</div>
<MissionTimeline
events={state.events}
@ -714,7 +737,7 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
<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>
<button className="sx-launch" onClick={() => { launchAudio.unlock(); toggle(); }}>{state.isRunning ? <Pause size={15} /> : <Play size={15} />}{launchLabel}</button>
</div>
</div>
</div>

View File

@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""生成火箭点火启动倒数(10→1 → Lift off)的英文男声语音,合成成一段约 10 秒的音频。
依赖系统自带的 `say`(macOS)与 `ffmpeg`。每个数字被放在倒数轴上的对应时刻:
"10" 在 t=0,"9" 在 t=1s … "1" 在 t=9s,"Lift off" 在 t=10s(即起飞那一刻)。
物理侧 COUNTDOWN_SECONDS=10,正好对上。
用法:python3 scripts/gen_countdown_voice.py
输出:backend/upload/assets/countdown.m4a(随 git 分发)。
"""
import subprocess
import sys
import tempfile
from pathlib import Path
ASSETS = Path(__file__).resolve().parent.parent / "backend" / "upload" / "assets"
OUT = ASSETS / "countdown.m4a"
VOICE = "Daniel" # macOS 内置的英文男声
COUNTDOWN_SECONDS = 10
def run(cmd):
subprocess.run(cmd, check=True, capture_output=True)
def main() -> None:
ASSETS.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
# 每句独立合成成 PCM(aiff 是 AIFF-C 压缩,交给 ffmpeg 统一转码更稳)
lines = [str(n) for n in range(COUNTDOWN_SECONDS, 0, -1)] + ["Lift off"]
clips = []
for i, text in enumerate(lines):
aiff = tmp / f"{i:02d}.aiff"
run(["say", "-v", VOICE, "-o", str(aiff), text])
clips.append((i, aiff))
# 用 adelay 把每句推到它该说的时刻(第 i 句在 i 秒处),再 amix 叠在一起。
inputs = []
filters = []
for i, aiff in clips:
delay = i * 1000
inputs += ["-i", str(aiff)]
filters.append(f"[{i}:a]aresample=44100,adelay={delay}|{delay},apad[a{i}]")
# normalize=0:各路互不重叠,直接相加即可,别被 amix 按路数摊薄
mix = "".join(f"[a{i}]" for i, _ in clips) + f"amix=inputs={len(clips)}:duration=longest:normalize=0[aout]"
filters.append(mix)
# 直接 aac 编码成 m4a(浏览器支持一致,体积也小)
run(["ffmpeg", "-y", *inputs, "-filter_complex", ";".join(filters),
"-map", "[aout]",
"-t", str(COUNTDOWN_SECONDS + 2), "-c:a", "aac", "-b:a", "128k", str(OUT)])
print(f"{OUT.name}: {OUT.stat().st_size // 1024} KB")
if __name__ == "__main__":
try:
main()
except subprocess.CalledProcessError as err:
sys.exit(f"audio 生成失败:\n{err.stderr.decode(errors='replace')}")