Launch typed ground strikes from carriers and isolate presentation state (#118 #88 #89)
build / mod (push) Failing after 18s

Share read-only scene data for smoke and displayed blasts; preserve cold ejection and flight-relative recording samples. Keep finite typed depot inventory, expose per-world smoke readiness through the pinned API26 engine, and invalidate presentation resources on world changes.

Validation: core suite 156 unit tests plus 4 scenarios and the new targeted recording regression; adapter 50 unit tests, boundary check and 4 scenarios; real WASM contract 16 steps; asset pipeline and bounds checks; macOS Metal client build and HD frame.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-02 22:23:09 +03:00
parent e84a5e9fa7
commit d4adbb1e47
20 changed files with 1871 additions and 257 deletions
+2 -1
View File
@@ -161,7 +161,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef raid` — налёт, настроенный в меню; `/airdef target here` — отметить объект под ногами; `/airdef repair` — ремонт;
- `/airdef lastchance <on|off>` — «последний шанс»: комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт (по умолчанию вкл; сохраняется);
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
- `/airdef strike <номер ПУ>` — ручной приказ, **пока недоступен**: для текущей техники ещё не реализован подтверждённый совместимый боеприпас и режим удара по координатам (#118). Приказ объясняет причину, не запускает ракету от игрока и не тратит общий запас. Старые поля запаса сохраняются для совместимости формата; автоматически он больше не пополняется. Случайный перехват несуществующим «ПВО площадки» удалён. Механика полёта/коллизий/записи сохранена и проверяется отдельными тестовыми пусками. Следующий этап — физический носитель, поштучный совместимый боекомплект, подготовка пуска и снабжение; наземный режим не назначается всем зенитным ракетам по умолчанию.
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ списывает одну ударную ракету у носителя, а не создаёт её возле игрока. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть выброс, отложенное включение двигателя, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
- `/airdef ground-stock <номер склада> <количество>` — задать начальный запас RM48U для sandbox-сценария (по умолчанию 0, сам не пополняется). `/airdef ground-load <номер С-400>` — у живого склада в пределах 60 блоков загрузить одну RM48U, сохранив снятую ракету ПВО на складе; `/airdef ground-unload <номер С-400>` — вернуть её и восстановить снятую ракету ПВО, если она осталась. Запас сохраняется с миром. Автоматическая доставка RM48U через ТЗМ пока не реализована. Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
+5 -2
View File
@@ -59,6 +59,9 @@ pub fn tree() -> Tree {
Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()),
Node::lit("raid").runs(),
Node::lit("sites").runs(),
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
Node::lit("ground-unload").then(Node::arg("комплекс", Value::int_from(1)).runs()),
Node::lit("ground-load").then(Node::arg("комплекс", Value::int_from(1)).runs()),
Node::lit("strike").then(Node::arg("номер", Value::int_from(1)).runs()),
Node::lit("repair").runs(),
Node::lit("import").runs(),
@@ -234,10 +237,10 @@ mod tests {
fn completion_offers_the_next_word_only() {
let top = complete("", &[]);
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike"] {
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike", "ground-stock", "ground-load", "ground-unload"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 28);
assert_eq!(top.len(), 31);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
+23 -1
View File
@@ -23,6 +23,9 @@ pub struct SamRec {
pub dest: Option<DVec3>,
/// The parts, from the sensor on; older saves have fewer or none.
pub comps: Vec<f64>,
pub ground_rounds: u32,
pub ground_stock: u32,
pub air_48n6_stock: u32,
}
#[derive(Default)]
@@ -117,7 +120,16 @@ impl Layout {
None => break,
}
}
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps });
let ground_rounds = l.num(22, "заряжено RM48U", 0.0, 4.0)?.unwrap_or(0.0) as u32;
let ground_stock = l.num(23, "запас RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32;
let air_48n6_stock = l.num(24, "снятый боезапас ПВО", 0.0, COUNT)?.unwrap_or(0.0) as u32;
if (kind != SamKind::S400 && ground_rounds != 0) || (kind != SamKind::Depot && (ground_stock != 0 || air_48n6_stock != 0)) {
return Err(l.bad("боезапас", "несовместимый тип техники"));
}
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 {
return Err(l.bad("боезапас", "больше четырёх ячеек"));
}
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock });
}
"target" => {
if out.targets.len() >= MAX_UNITS {
@@ -221,6 +233,16 @@ mod tests {
let w = crate::wave::WaveConfig::default().text();
assert!(Layout::parse(&format!("wave {w}\n")).is_ok(), "{w}");
}
#[test]
fn typed_ground_ammo_is_persistent_and_incompatible_layout_is_refused() {
let text = "sam s400 0 70 0 0 30 1 0 2 0 0 0 - - - 1 1 1 1 1 1 2 0 0\nsam depot 0 70 10 0 0 1 30 0 0 0 0 - - - 1 1 1 1 1 1 0 7 2\n";
let layout = Layout::parse(text).unwrap();
assert_eq!((layout.sams[0].ground_rounds, layout.sams[0].ammo.unwrap().0), (2, 2));
assert_eq!((layout.sams[1].ground_stock, layout.sams[1].air_48n6_stock), (7, 2));
assert!(Layout::parse(&text.replace("s400", "patriot")).is_err());
assert!(Layout::parse(&text.replace("0 2 0 0 0 -", "0 4 0 0 0 -")).is_err());
}
#[test]
fn the_save_line_is_what_the_layout_reads() {
let mut d = crate::sim::doctrine::Doctrine { salvo: crate::sim::doctrine::Salvo::Economy, reserve: 3, ..Default::default() };
+265 -81
View File
@@ -23,6 +23,7 @@ mod panel;
mod presentation;
mod radar;
mod replay;
mod scene;
mod smoke;
pub use airdef_core::sim;
mod scenario;
@@ -53,8 +54,6 @@ struct AirDef {
presentation: presentation::Session<replay::Player, Export>,
/// The effects preset a film replaced: (shader, hd).
film_prev: Option<(bool, bool)>,
/// Counts the replay/film sessions started; an export belongs to the one it began with.
session: u64,
/// The world drawn beyond the render distance (replays and cameras see far off).
far: bool,
/// The acoustics asked for, until the game has them (its answer comes a tick later).
@@ -113,8 +112,8 @@ enum Stage {
Finishing,
}
struct Export {
/// The session (`AirDef::session`) whose film this export records.
session: u64,
/// The presentation generation whose film this export records.
generation: u64,
opts: ExportOpts,
stage: Stage,
ticks: u32,
@@ -155,13 +154,23 @@ fn source_op(kind: render::SourceOpKind, id: u32, v: &engines::Voice) -> render:
/// A sound heard later: when, what, where, and how loud and high it was.
struct PendingSound {
due: u64,
due: f64,
generation: u64,
created_at: presentation::Clock,
name: String,
at: DVec3,
volume: f32,
pitch: f32,
}
impl PendingSound {
fn invalidated_by(&self, generation: u64, clock: presentation::Clock) -> bool {
self.generation != generation
|| !self.created_at.same_domain(clock)
|| clock.value() < self.created_at.value()
}
}
/// Blocks a tick the sound travels (343 m/s).
const SOUND_SPEED: f64 = 17.15;
/// Past this the far variant plays: muffled, more rolling echo.
@@ -242,6 +251,18 @@ struct Shown {
replay: bool,
}
impl Shown {
fn from_context(ctx: &presentation::Context, scene: &scene::Snapshot<'_>) -> Self {
let recording = ctx.is_playback() && ctx.filming;
Self {
blasts: scene.blasts().into_owned(),
now: scene.time() as f32,
hold: if recording { 1.0 - ctx.rate.clamp(0.0, 1.0) } else { 0.0 },
replay: recording,
}
}
}
fn player() -> Option<game::Player> {
game::get_player()
}
@@ -381,8 +402,8 @@ impl AirDef {
/// The HD lighting's lights: flames, glowing warheads, flares, muzzle flashes, tracers,
/// blasts (a flash, then the fireball's glow dying down), burning wrecks and the
/// searchlights' spots.
fn lights(&self, out: &Out) -> Vec<PointLight> {
let shown = self.shown();
fn lights(&self, out: &Out, ctx: &presentation::Context) -> Vec<PointLight> {
let shown = self.shown(ctx);
let mut lights: Vec<PointLight> = Vec::new();
let mut add = |id: u32, at: DVec3, rgb: (f32, f32, f32), intensity: f32, radius: f32| {
if lights.len() < 500 && intensity > 0.05 {
@@ -392,7 +413,7 @@ impl AirDef {
let tick = shown.now as u64;
let flicker = |id: u32| 0.85 + 0.15 * (((tick as u32).wrapping_mul(2654435761) ^ id.wrapping_mul(97)) % 100) as f32 / 100.0;
// Blasts first, the nearest first: a crowded sky never costs the key intercept its light.
let viewer = self.viewer(&shown);
let viewer = self.viewer(ctx);
let mut near: Vec<&sim::Blast> = shown.blasts.iter().collect();
if let Some(e) = viewer {
near.sort_by(|a, b| a.at.distance_squared(e).total_cmp(&b.at.distance_squared(e)));
@@ -460,8 +481,8 @@ impl AirDef {
/// The searchlights' spot lights (HD): a cone from the head along its real direction, as far
/// as the beam runs free; at most 16, the renderer draws the nearest.
fn spots(&self) -> Vec<SpotLight> {
let shown = self.shown();
fn spots(&self, ctx: &presentation::Context) -> Vec<SpotLight> {
let shown = self.shown(ctx);
// A replay lights with the recording's searchlights, where and as they pointed.
let beams: Vec<sim::lights::Beam> = if shown.replay {
match self.presentation.playback().and_then(|r| self.sim.replay(r.rec).map(|rec| rec.beams(f64::from(shown.now)))) {
@@ -525,8 +546,8 @@ impl AirDef {
/// Hands the simulation's output to the game.
/// The post pass's parameters: blasts and glowing parts (shaders/effects.wgsl).
fn shader_params(&self, out: &Out) -> Vec<f32> {
let shown = self.shown();
fn shader_params(&self, out: &Out, ctx: &presentation::Context) -> Vec<f32> {
let shown = self.shown(ctx);
let mut p = vec![0.0f32; 4];
p[0] = shown.now;
p[3] = if self.smoke.hd { 2.0 } else if self.hd { 1.0 } else { 0.0 };
@@ -534,7 +555,7 @@ impl AirDef {
// The shader composites the volumes front to back with one shared transmittance, so
// the nearest to the player goes first. This is exact for volumes that do not
// overlap; where two intersect, no order by centre is right along every ray.
if let Some(e) = self.viewer(&shown) {
if let Some(e) = self.viewer(ctx) {
blasts.sort_by(|a, b| a.at.distance_squared(e).total_cmp(&b.at.distance_squared(e)));
}
p[1] = blasts.len() as f32;
@@ -575,37 +596,57 @@ impl AirDef {
/// The smoke volumes the renderer draws and the clock they are aged by: the live ones, or (in a
/// replay) the blasts' billows at the replay's moment, never the live raid's trails and fires.
/// The recorded scene is read directly; live simulation state is never replaced.
fn shown_smoke(&self) -> (f64, Vec<render::SmokeSegment>) {
let shown = self.shown();
if !shown.replay {
return (self.sim.tick as f64, self.smoke.segments(&self.sim));
}
// The recording alone, as a function of its time: the live Sim is not touched.
let segments = match self.sim.replay(self.presentation.playback().map_or(0, |r| r.rec)) {
Some(rec) => smoke::replay_smoke(rec, f64::from(shown.now)),
None => Vec::new(),
};
(f64::from(shown.now), segments)
fn shown_smoke(&self, ctx: &presentation::Context) -> (f64, Vec<render::SmokeSegment>) {
let scene = self.scene_snapshot(ctx);
(scene.time(), self.smoke.segments(&scene))
}
/// Where the picture is seen from: the replay's camera, or the player's eyes.
fn viewer(&self, shown: &Shown) -> Option<DVec3> {
match self.presentation.playback() {
Some(r) if shown.replay => Some(r.eye()),
_ => player().map(|pl| eye(&pl)),
fn viewer(&self, ctx: &presentation::Context) -> Option<DVec3> {
if ctx.is_playback() && ctx.filming {
self.presentation.playback().map(|r| r.eye())
} else {
Some(ctx.listener)
}
}
/// The blasts the effects show and the clock they run on: the live ones, or (in a replay) the
/// recording's at the replay's moment, never the live world's.
fn shown(&self) -> Shown {
if let Some(r) = self.presentation.playback()
&& r.filming()
&& let Some(rec) = self.sim.replay(r.rec)
{
return Shown { blasts: sim::record::replay_blasts(rec, r.time()), now: r.time() as f32, hold: 1.0 - r.rate().clamp(0.0, 1.0), replay: true };
fn presentation_context(&self) -> presentation::Context {
let world = self.world.clone();
if let Some(r) = self.presentation.playback() {
presentation::Context::playback(
if self.presentation.is_exporting() { presentation::Mode::Export } else { presentation::Mode::Replay },
self.presentation.generation(),
world,
self.sim.engine_tick,
self.sim.tick,
r.time(),
r.day_time(&self.sim),
r.rate(),
self.listener,
r.filming(),
)
} else {
presentation::Context::live(self.presentation.generation(), world, self.sim.engine_tick, self.sim.tick, self.sim.day_time, self.listener)
}
Shown { blasts: self.sim.blasts.clone(), now: self.sim.tick as f32, hold: 0.0, replay: false }
}
fn scene_snapshot(&self, ctx: &presentation::Context) -> scene::Snapshot<'_> {
if ctx.is_playback() && ctx.filming {
let source = self.presentation.playback()
.and_then(|r| self.sim.replay(r.rec))
.map(scene::Source::Recorded)
.unwrap_or(scene::Source::Empty);
scene::Snapshot::at_context(ctx, source)
} else {
scene::Snapshot::at_context(ctx, scene::Source::Live(&self.sim))
}
}
fn shown(&self, ctx: &presentation::Context) -> Shown {
let scene = self.scene_snapshot(ctx);
Shown::from_context(ctx, &scene)
}
/// The models to the game by handle: each name crosses once, the buffer stays allocated.
@@ -642,8 +683,8 @@ impl AirDef {
/// The engines the simulation or the replay declared become persistent sound sources (#95):
/// started, followed, stopped. The one-shots below stay as they were.
fn step_engines(&mut self, out: &mut Out) {
let replay = self.presentation.playback().is_some_and(|r| r.filming());
fn step_engines(&mut self, ctx: &presentation::Context, out: &mut Out) {
let replay = ctx.is_playback() && ctx.filming;
let cut = std::mem::take(&mut out.engine_cut) || replay != self.engines_replay;
self.engines_replay = replay;
let generation = render::sound_source_generation();
@@ -657,7 +698,7 @@ impl AirDef {
}
let ops: Vec<render::SourceOp> = self
.engines
.step(std::mem::take(&mut out.engines), cut, self.listener)
.step(std::mem::take(&mut out.engines), cut, ctx.listener)
.into_iter()
.map(|op| match op {
engines::Op::Start(id, v) => source_op(render::SourceOpKind::Start, id, &v),
@@ -692,24 +733,26 @@ impl AirDef {
}
fn emit(&mut self, mut out: Out) {
self.step_engines(&mut out);
let ctx = self.presentation_context();
self.step_engines(&ctx, &mut out);
if self.sim.shader {
render::set_params(&self.shader_params(&out));
render::set_params(&self.shader_params(&out, &ctx));
}
if self.hd {
// The camera's reaction to a near blast: a brief exposure and bloom punch.
let shown = self.shown();
let p = self.viewer(&shown).map_or(0.0, |e| {
let shown = self.shown(&ctx);
let p = self.viewer(&ctx).map_or(0.0, |e| {
shown.blasts.iter().map(|b| cinema::punch(b.size, shown.now - b.start as f32, b.at.distance(e))).fold(0.0, f32::max)
});
if (p - self.punch).abs() > 0.01 || (p == 0.0 && self.punch != 0.0) {
self.punch = p;
render::set_lighting(Lighting { hd: true, exposure: 1.0 + 0.4 * p, bloom: 0.55 + 0.9 * p });
}
render::set_lights(&self.lights(&out));
self.sim.spot_hd = render::set_spot_lights(&self.spots());
let (clock, segments) = self.shown_smoke();
self.smoke.hd = render::set_smoke(clock, &segments);
render::set_lights(&self.lights(&out, &ctx));
self.sim.spot_hd = render::set_spot_lights(&self.spots(&ctx));
let (clock, segments) = self.shown_smoke(&ctx);
render::set_smoke(clock, &segments);
self.smoke.hd = horizon_mod_sdk::smoke_can_replace_fallback(&render::smoke_status());
} else {
self.smoke.hd = false;
}
@@ -717,7 +760,7 @@ impl AirDef {
self.send_models(&out.models);
}
if !out.particles.is_empty() {
let hd_smoke = self.smoke.hd && !self.presentation.playback().is_some_and(|r| r.filming());
let hd_smoke = self.smoke.hd && !(ctx.is_playback() && ctx.filming);
let spawns: Vec<ParticleSpawn> = out
.particles
.into_iter()
@@ -739,14 +782,14 @@ impl AirDef {
.collect();
render::spawn_particles(&spawns);
}
let now = self.sim.tick;
let sound_clock = ctx.sound_clock();
// Blasts play layered (cinema.rs), the nearest ones in full.
let mut booms: Vec<(f64, usize, DVec3, f32, f32)> = Vec::new();
// The game muffles by walls and distance itself (#96): the near variants play out to the
// reach of its tracing, so nothing is muffled twice; past it the far ones still do.
let far = if render::acoustics() { ACOUSTIC_FAR } else { FAR };
for (event, at, volume, pitch) in out.sounds {
let dist = at.distance(self.listener);
let dist = at.distance(ctx.listener);
if let Some(power) = cinema::blast_power(event) {
booms.push((dist, power, at, volume, pitch));
} else if travels(event) {
@@ -756,7 +799,7 @@ impl AirDef {
if delay == 0 {
render::play_sound(&name, at.x, at.y, at.z, volume, pitch);
} else if self.pending.len() < 256 {
self.pending.push(PendingSound { due: now + delay, name, at, volume, pitch });
self.pending.push(PendingSound { due: sound_clock.deadline_after(delay), generation: ctx.generation, created_at: sound_clock, name, at, volume, pitch });
}
} else {
render::play_sound(event, at.x, at.y, at.z, volume, pitch);
@@ -770,13 +813,15 @@ impl AirDef {
if delay == 0 {
render::play_sound(&l.name, at.x, at.y, at.z, l.volume, l.pitch);
} else if self.pending.len() < 256 {
self.pending.push(PendingSound { due: now + delay, name: l.name, at, volume: l.volume, pitch: l.pitch });
self.pending.push(PendingSound { due: sound_clock.deadline_after(delay), generation: ctx.generation, created_at: sound_clock, name: l.name, at, volume: l.volume, pitch: l.pitch });
}
}
}
let mut i = 0;
while i < self.pending.len() {
if self.pending[i].due <= now {
if self.pending[i].invalidated_by(ctx.generation, sound_clock) {
self.pending.swap_remove(i);
} else if sound_clock.has_reached(self.pending[i].due) {
let s = self.pending.swap_remove(i);
render::play_sound(&s.name, s.at.x, s.at.y, s.at.z, s.volume, s.pitch);
} else {
@@ -822,7 +867,7 @@ impl AirDef {
let dest = s.dest.filter(|_| !fresh).map_or("- - -".to_string(), |d| format!("{} {} {}", d.x, d.y, d.z));
let new = Sam::new(0, s.kind, s.pos, s.heading);
let (health, cargo, missiles, bursts, empty, reloading) = if fresh {
(new.health, new.cargo, new.missiles, new.bursts, false, 0)
(new.health, new.cargo, new.missiles.saturating_sub(s.ground_rounds), new.bursts, false, 0)
} else {
(s.health, s.cargo, s.missiles, s.bursts, s.empty, s.reloading)
};
@@ -830,7 +875,7 @@ impl AirDef {
let comps = if fresh { new.comps } else { s.comps };
let parts = comps.0.iter().map(|v| format!("{v:.3}")).collect::<Vec<_>>().join(" ");
text += &format!(
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts}\n",
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {}\n",
s.kind.key(),
s.pos.x,
s.pos.y,
@@ -843,6 +888,7 @@ impl AirDef {
bursts,
u8::from(empty),
reloading,
s.ground_rounds, s.ground_stock, s.air_48n6_stock,
);
}
for (i, t) in self.sim.targets.iter().enumerate() {
@@ -950,6 +996,9 @@ impl AirDef {
for (v, c) in sam.comps.0.iter_mut().zip(&r.comps) {
*v = *c;
}
sam.ground_rounds = r.ground_rounds;
sam.ground_stock = r.ground_stock;
sam.air_48n6_stock = r.air_48n6_stock;
sam.fit_cells();
self.sim.sams.push(sam);
if let Some(to) = r.dest {
@@ -1042,8 +1091,9 @@ fn durable_mark(sim: &Sim) -> u64 {
let at = s.dest.unwrap_or(s.pos);
let place = (at.x * 10.0) as i64 as u64 ^ ((at.z * 10.0) as i64 as u64).rotate_left(21) ^ (if s.dest.is_some() { 0 } else { (s.heading * 100.0) as i64 as u64 }).rotate_left(42);
let ammo = u64::from(s.missiles) | u64::from(s.bursts) << 16 | u64::from(s.cargo) << 32 | u64::from(s.empty) << 48 | u64::from(s.reloading > 0) << 49;
let typed = u64::from(s.ground_rounds) ^ u64::from(s.ground_stock).rotate_left(17) ^ u64::from(s.air_48n6_stock).rotate_left(39);
let parts = s.comps.0.iter().fold(0u64, |a, v| a.wrapping_mul(131).wrapping_add((v * 100.0) as u64));
((s.health * 1000.0) as u64).wrapping_mul(1_000_003) ^ place ^ ammo.rotate_left(7) ^ parts.rotate_left(13)
((s.health * 1000.0) as u64).wrapping_mul(1_000_003) ^ place ^ ammo.rotate_left(7) ^ parts.rotate_left(13) ^ typed.rotate_left(29)
})
.chain(sim.target_health.iter().map(|h| (h * 10.0) as u64))
.fold(sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h))
@@ -1159,7 +1209,6 @@ impl AirDef {
let player = replay::Player::new(rec.number, mode, &self.sim);
// A film (its quality and effects) or another replay ends properly before this one.
self.end_session(presentation::ExitCause::Replaced);
self.session += 1;
self.presentation.replay(player);
self.grid = false;
input::claim_wheel(true);
@@ -1177,22 +1226,13 @@ impl AirDef {
/// Ends whatever replay or film shows, on every path: the film quality, the effects, the
/// clean HUD, the views and the time and camera overrides go back to the live game's.
fn end_session(&mut self, cause: presentation::ExitCause) {
let cleanup = self.presentation.end(cause);
if cleanup.cancel_capture {
render::capture_stop(true);
}
self.pending.clear();
render::set_film_quality(false);
if let Some((shader, hd)) = self.film_prev.take() {
self.set_effects(shader, hd);
}
self.show_world_at(0, 0.0, false);
render::set_time_override(None);
render::set_main_view(None);
input::claim_wheel(false);
render::set_hud(&[]);
render::set_views(&[]);
self.monitor_shown = false;
let cleanup = if cause == presentation::ExitCause::WorldChange {
self.presentation.world_changed()
} else {
self.presentation.end(cause)
};
let Some(cleanup) = cleanup else { return };
cleanup.apply(self);
}
/// Plays the director's film of the last raid at the best quality: HD effects on (restored after).
@@ -1220,7 +1260,6 @@ impl AirDef {
}
// What was shown ends first (its effects are remembered below, not lost).
self.end_session(presentation::ExitCause::Replaced);
self.session += 1;
self.presentation.replay(player);
self.grid = false;
input::claim_wheel(true);
@@ -1273,13 +1312,13 @@ impl AirDef {
}
};
say(&format!("Экспорт «{}»: {} fps, {}x{}; планирую кадры…", o.name, o.fps, o.size.0, o.size.1));
self.presentation.export(playback, Export { session: self.session, opts: o, stage: Stage::Planning, ticks: 0 });
self.presentation.export(playback, Export { generation: self.presentation.generation(), opts: o, stage: Stage::Planning, ticks: 0 });
Ok(())
}
/// Drives an export: plan, start the recorder, wait for its first frame, report, stop at the end.
fn export_step(&mut self, r: &mut replay::Player, ex: &mut Export) -> Option<Result<(), String>> {
if ex.session != self.session {
if ex.generation != self.presentation.generation() {
// The film this export recorded was replaced: the recorder stops, nothing else drives it.
say("Экспорт отменён: показ заменён другим");
return Some(Err("показ заменён другим".into()));
@@ -1641,6 +1680,28 @@ impl AirDef {
}
}
impl presentation::CleanupHost for AirDef {
fn apply_cleanup_action(&mut self, action: presentation::CleanupAction) {
match action {
presentation::CleanupAction::CancelCapture => render::capture_stop(true),
presentation::CleanupAction::ClearPendingSounds => self.pending.clear(),
presentation::CleanupAction::RestoreFilmQuality => render::set_film_quality(false),
presentation::CleanupAction::RestoreEffects => {
if let Some((shader, hd)) = self.film_prev.take() {
self.set_effects(shader, hd);
}
}
presentation::CleanupAction::RestoreWorldView => self.show_world_at(0, 0.0, false),
presentation::CleanupAction::ClearTimeOverride => render::set_time_override(None),
presentation::CleanupAction::ClearMainView => render::set_main_view(None),
presentation::CleanupAction::ReleaseWheel => input::claim_wheel(false),
presentation::CleanupAction::ClearHud => render::set_hud(&[]),
presentation::CleanupAction::ClearViews => render::set_views(&[]),
presentation::CleanupAction::HideMonitor => self.monitor_shown = false,
}
}
}
/// The help line: generated from the command tree (`commands.rs`), which the game checks lines with.
fn help() -> String {
commands::help()
@@ -1664,7 +1725,6 @@ impl Mod for AirDef {
block_log: None,
time_view: false,
film_prev: None,
session: 0,
smoke: Default::default(),
far: true,
acoustics: None,
@@ -1714,6 +1774,8 @@ impl Mod for AirDef {
let world = world_identity();
if self.world.as_ref() != Some(&world) {
self.open_world(world);
// `open_world` replaces Sim and resets its host clock; restore this callback's tick.
self.sim.engine_tick = tick;
}
let Some(p) = player() else { return };
for event in input::poll() {
@@ -1801,7 +1863,9 @@ impl Mod for AirDef {
self.sim.night = game::get_clock().is_some_and(|c| (13000..23000).contains(&(c.day_time % 24000)));
self.sim.day_time = game::get_clock().map(|c| c.day_time);
self.sim.step(&mut self.ground, Some(DVec3::new(p.x, p.y, p.z)), &mut out);
self.smoke.update(&self.sim);
let context = presentation::Context::live(self.presentation.generation(), self.world.clone(), self.sim.engine_tick, self.sim.tick, self.sim.day_time, self.listener);
let scene = scene::Snapshot::at_context(&context, scene::Source::Live(&self.sim));
self.smoke.update(&scene);
let wanted = self.ground.take_wanted();
if !wanted.is_empty() {
render::query_ground(&wanted);
@@ -1825,6 +1889,7 @@ impl Mod for AirDef {
if !sections.is_empty() {
render::query_sections(render::Policy::Collision, &sections);
}
let tick_context = self.presentation_context();
match self.presentation.take() {
presentation::State::Live => {}
presentation::State::Replay(mut playback) => {
@@ -1835,7 +1900,7 @@ impl Mod for AirDef {
out.engines.clear();
out.shake = None;
}
playback.tick(&self.sim, &mut self.ground, self.listener, &mut out);
playback.tick(&self.sim, &mut self.ground, tick_context.listener, &mut out);
if playback.done {
self.presentation.restore(presentation::State::Replay(playback));
self.end_session(presentation::ExitCause::Finished);
@@ -1844,7 +1909,7 @@ impl Mod for AirDef {
}
}
presentation::State::Export { mut playback, mut export } => {
let progress = if export.session != self.session {
let progress = if export.generation != self.presentation.generation() {
Some(Err("показ заменён другим".into()))
} else {
if playback.filming() {
@@ -1854,7 +1919,7 @@ impl Mod for AirDef {
out.engines.clear();
out.shake = None;
}
playback.tick(&self.sim, &mut self.ground, self.listener, &mut out);
playback.tick(&self.sim, &mut self.ground, tick_context.listener, &mut out);
self.export_step(&mut playback, &mut export)
};
let cause = match progress {
@@ -1875,6 +1940,7 @@ impl Mod for AirDef {
self.map_frame();
self.draw_hud(DVec3::new(p.x, p.y, p.z), p.yaw);
// The replay takes the screen; else the monitors and the cameras they show.
let ctx = self.presentation_context();
if let Some(r) = self.presentation.playback() {
let size = render::gui_size();
render::set_hud(&r.hud(&self.sim, size));
@@ -1882,7 +1948,7 @@ impl Mod for AirDef {
// The world through the director's camera, with the full pipeline (HD, the post pass).
render::set_main_view(r.filming().then(|| r.view_id()));
// The sky of the raid, not of now (None for a raid whose clock was unknown).
render::set_time_override(r.day_time(&self.sim));
render::set_time_override(ctx.day_time);
self.show_world_at(r.rec, r.time(), r.filming());
self.monitor_shown = true;
} else if self.grid {
@@ -2217,6 +2283,27 @@ impl Mod for AirDef {
}
None
}
["ground-stock", n, count] => {
let i = n.parse::<usize>().ok().and_then(|v| v.checked_sub(1)).ok_or("/airdef ground-stock <номер склада> <количество>")?;
let count = count.parse::<u32>().ok().filter(|v| *v <= 10000).ok_or("Количество: 0..10000")?;
let depot = self.sim.sams.get_mut(i).ok_or("Нет такого склада")?;
if depot.kind != SamKind::Depot || !depot.alive() { return Err("Нужен действующий склад".into()); }
depot.ground_stock = count;
self.dirty = true;
Some(format!("Sandbox: задан начальный запас склада №{}: RM48U {}", i + 1, count))
}
["ground-load", n] => {
let i = n.parse::<usize>().ok().and_then(|v| v.checked_sub(1)).ok_or("/airdef ground-load <номер комплекса>")?;
let message = self.sim.load_ground_round(i)?;
self.dirty = true;
Some(message)
}
["ground-unload", n] => {
let i = n.parse::<usize>().ok().and_then(|v| v.checked_sub(1)).ok_or("/airdef ground-unload <номер комплекса>")?;
let message = self.sim.unload_ground_round(i)?;
self.dirty = true;
Some(message)
}
["strike", n] => {
// A manual order: the simulation validates availability; player position is no launcher.
let p = player().ok_or("Нет игрока")?;
@@ -2366,12 +2453,109 @@ mod tests {
use super::*;
/// #83: while an export records no other replay or film replaces it; after it, they may.
#[test]
fn typed_ammunition_changes_mark_the_state_dirty() {
let mut sim = Sim::new(1);
sim.sams.push(Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0));
let before = durable_mark(&sim);
sim.sams[0].ground_rounds = 1;
assert_ne!(durable_mark(&sim), before);
let before = durable_mark(&sim);
sim.sams[0].ground_stock = 1;
assert_ne!(durable_mark(&sim), before);
}
#[test]
fn nothing_replaces_a_running_export() {
assert!(switch_allowed(true).is_err());
assert!(switch_allowed(false).is_ok());
}
#[test]
fn delayed_replay_audio_uses_recording_time_and_is_dropped_after_seek_back() {
let ctx = presentation::Context::playback(
presentation::Mode::Replay,
7,
None,
90_000,
900,
20.5,
None,
0.25,
DVec3::ZERO,
true,
);
let clock = ctx.sound_clock();
let due = clock.deadline_after(5);
let pending = PendingSound {
due,
generation: ctx.generation,
created_at: clock,
name: "test".into(),
at: DVec3::ZERO,
volume: 1.0,
pitch: 1.0,
};
assert_eq!(due, 25.5);
assert!(!presentation::Clock::Recording(25.25).has_reached(due));
assert!(!clock.has_reached(due), "slow playback has not advanced the delay yet");
assert!(pending.invalidated_by(ctx.generation, presentation::Clock::Recording(19.0)));
assert!(pending.invalidated_by(ctx.generation + 1, clock));
assert!(!pending.invalidated_by(ctx.generation, presentation::Clock::Recording(20.5)));
}
#[test]
fn shown_effects_follow_the_recording_clock_not_the_combat_clock() {
let live_blast = sim::Blast { id: 1, at: DVec3::ZERO, size: 4.0, start: 900, life: 60 };
let mut rec = sim::record::Recording::blank(100);
rec.events.push(sim::record::Event {
at: 12,
pos: DVec3::X,
kind: sim::record::EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 8, object: None, sam: None },
});
let ctx = presentation::Context::playback(
presentation::Mode::Replay,
5,
Some(Some("w".into())),
10_000,
10_001,
12.5,
Some(13000),
0.3,
DVec3::Z,
true,
);
let record_scene = scene::Snapshot::at_context(&ctx, scene::Source::Recorded(&rec));
let shown = Shown::from_context(&ctx, &record_scene);
assert!(shown.replay);
assert_eq!(shown.now, 12.5);
assert_eq!(shown.blasts.len(), 1);
assert_eq!(shown.blasts[0].id, 0x4000_0000);
assert!((shown.hold - 0.7).abs() < 1e-6);
let map = presentation::Context::playback(
presentation::Mode::Replay,
5,
Some(Some("w".into())),
10_020,
10_002,
20.0,
Some(13000),
1.0,
DVec3::Z,
false,
);
let mut live = Sim::new(1);
live.tick = 10_002;
live.blasts.push(live_blast);
let map_scene = scene::Snapshot::at_context(&map, scene::Source::Live(&live));
let shown_map = Shown::from_context(&map, &map_scene);
assert!(!shown_map.replay);
assert_eq!(shown_map.now, 10_002.0);
assert_eq!(shown_map.blasts[0].id, live_blast.id);
}
#[test]
fn strike_stock_and_refill_change_the_durable_mark() {
let mut sim = Sim::new(7);
+3 -2
View File
@@ -2325,6 +2325,7 @@ impl AirDef {
lines.push((sam.status(), WHITE));
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
if k.armed() {
if sam.kind == SamKind::S400 { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО)", sam.ground_rounds), WHITE)); }
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE));
}
@@ -2395,12 +2396,12 @@ impl AirDef {
(None, _) => lines.push(("Данных нет".into(), GREY)),
}
lines.push((format!("Пусков замечено: {}; последний {} с назад", k.launches, now.saturating_sub(k.last) / 20), GREY));
lines.push(("Удар недоступен: нет совместимого боеприпаса".into(), GREY));
lines.push(("Для удара нужен готовый С-400 с RM48U".into(), GREY));
if k.aimed {
lines.push(("Ракета по ней уже в полёте".into(), YELLOW));
}
if k.est.is_some_and(|e| e.fix) && !matches!(k.state, SiteState::Destroyed(_)) {
btns.push(("Почему удар недоступен?".into(), Act::Strike(id), false));
btns.push(("Нанести удар".into(), Act::Strike(id), false));
}
btns.push(("В центр".into(), Act::Centre, false));
}
+1
View File
@@ -255,6 +255,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
let mut line = String::new();
if !matches!(sam.kind, crate::sim::SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles);
if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
}
if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts);
+436 -41
View File
@@ -1,4 +1,6 @@
//! Presentation playback ownership and lifecycle transitions.
//! Presentation playback ownership, read-only view context and cleanup transitions.
use glam::DVec3;
/// The one active presentation mode. Export owns its playback so it cannot outlive its film.
pub enum State<P, E> {
@@ -17,18 +19,178 @@ pub enum ExitCause {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
Live,
Replay,
Export,
}
/// Clocks are deliberately tagged: recording time can seek or slow down without being confused
/// with the live simulation tick that ages durable combat state and live sound delays.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Clock {
Live(u64),
Recording(f64),
}
impl Clock {
pub fn value(self) -> f64 {
match self {
Self::Live(tick) => tick as f64,
Self::Recording(tick) => tick,
}
}
pub fn deadline_after(self, delay: u64) -> f64 {
self.value().max(0.0) + delay as f64
}
pub fn has_reached(self, deadline: f64) -> bool {
self.value() >= deadline
}
pub fn same_domain(self, other: Self) -> bool {
matches!(
(self, other),
(Self::Live(_), Self::Live(_)) | (Self::Recording(_), Self::Recording(_))
)
}
}
/// Immutable inputs for everything that presents a scene: clock, listener and environment.
/// The context is a snapshot; consumers cannot advance playback or mutate the live world through it.
#[derive(Clone, Debug, PartialEq)]
pub struct Context {
pub mode: Mode,
pub generation: u64,
pub world: Option<Option<String>>,
/// Combat/simulation time.
pub combat_tick: u64,
/// Host/UI callback time; it must not be substituted for recorded or combat time.
pub ui_tick: u64,
pub clock: Clock,
pub listener: DVec3,
pub day_time: Option<u64>,
/// Share of a live tick represented by the current presentation step.
pub rate: f32,
pub filming: bool,
}
impl Context {
pub fn live(
generation: u64,
world: Option<Option<String>>,
ui_tick: u64,
combat_tick: u64,
day_time: Option<u64>,
listener: DVec3,
) -> Self {
Self {
mode: Mode::Live,
generation,
world,
combat_tick,
ui_tick,
clock: Clock::Live(combat_tick),
listener,
day_time,
rate: 1.0,
filming: false,
}
}
pub fn playback(
mode: Mode,
generation: u64,
world: Option<Option<String>>,
ui_tick: u64,
combat_tick: u64,
time: f64,
day_time: Option<u64>,
rate: f32,
listener: DVec3,
filming: bool,
) -> Self {
debug_assert!(matches!(mode, Mode::Replay | Mode::Export));
Self {
mode,
generation,
world,
combat_tick,
ui_tick,
clock: Clock::Recording(time),
listener,
day_time,
rate,
filming,
}
}
pub fn is_playback(&self) -> bool {
!matches!(self.mode, Mode::Live)
}
/// Map playback presents the current world view; only a filmed replay advances recorded effects.
pub fn display_clock(&self) -> Clock {
if self.is_playback() && self.filming {
self.clock
} else {
Clock::Live(self.combat_tick)
}
}
/// The clock used to age audible delays: filmed playback follows its recording; live and map
/// playback follow the current combat timeline.
pub fn sound_clock(&self) -> Clock {
self.display_clock()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CleanupAction {
CancelCapture,
ClearPendingSounds,
RestoreFilmQuality,
RestoreEffects,
RestoreWorldView,
ClearTimeOverride,
ClearMainView,
ReleaseWheel,
ClearHud,
ClearViews,
HideMonitor,
}
/// A cleanup plan is produced once when an active presentation ends. A successful export has
/// already drained its capture, so its plan omits `CancelCapture`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cleanup {
pub was_export: bool,
pub cancel_capture: bool,
pub actions: Vec<CleanupAction>,
}
pub trait CleanupHost {
fn apply_cleanup_action(&mut self, action: CleanupAction);
}
impl Cleanup {
pub fn apply(&self, host: &mut impl CleanupHost) {
for &action in &self.actions {
host.apply_cleanup_action(action);
}
}
}
pub struct Session<P, E> {
state: State<P, E>,
generation: u64,
}
impl<P, E> Default for Session<P, E> {
fn default() -> Self {
Self { state: State::Live }
Self {
state: State::Live,
generation: 0,
}
}
}
@@ -41,6 +203,10 @@ impl<P, E> Session<P, E> {
matches!(self.state, State::Export { .. })
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn playback(&self) -> Option<&P> {
match &self.state {
State::Live => None,
@@ -66,14 +232,20 @@ impl<P, E> Session<P, E> {
self.is_live(),
"end the current presentation before replacing it"
);
self.generation = self.generation.wrapping_add(1).max(1);
self.state = State::Replay(playback);
}
/// Promote the current replay into an export without changing its generation.
pub fn export(&mut self, playback: P, export: E) {
assert!(
self.is_live(),
"end the current presentation before starting export"
);
assert!(
self.generation != 0,
"an export must belong to a started presentation"
);
self.state = State::Export { playback, export };
}
@@ -87,58 +259,281 @@ impl<P, E> Session<P, E> {
self.state = state;
}
/// Every exit converges here; a completed capture is already drained and must not be cancelled.
pub fn end(&mut self, cause: ExitCause) -> Cleanup {
/// Return no plan for an already-live session, so repeated stop/unload paths cannot repeat host cleanup.
pub fn end(&mut self, cause: ExitCause) -> Option<Cleanup> {
let was_export = self.is_exporting();
if self.is_live() {
return None;
}
let mut actions = Vec::with_capacity(11);
if was_export && cause != ExitCause::Finished {
actions.push(CleanupAction::CancelCapture);
}
actions.extend([
CleanupAction::ClearPendingSounds,
CleanupAction::RestoreFilmQuality,
CleanupAction::RestoreEffects,
CleanupAction::RestoreWorldView,
CleanupAction::ClearTimeOverride,
CleanupAction::ClearMainView,
CleanupAction::ReleaseWheel,
CleanupAction::ClearHud,
CleanupAction::ClearViews,
CleanupAction::HideMonitor,
]);
self.state = State::Live;
Cleanup {
was_export,
cancel_capture: was_export && cause != ExitCause::Finished,
self.generation = self.generation.wrapping_add(1).max(1);
Some(Cleanup { actions })
}
/// A world change invalidates live work too. Active playback uses the normal cleanup path,
/// which advances generation exactly once; Live advances generation without host cleanup.
pub fn world_changed(&mut self) -> Option<Cleanup> {
if self.is_live() {
self.generation = self.generation.wrapping_add(1).max(1);
None
} else {
self.end(ExitCause::WorldChange)
}
}
}
#[cfg(test)]
mod tests {
use super::{ExitCause, Session, State};
use super::{CleanupAction, CleanupHost, Clock, Context, ExitCause, Mode, Session, State};
use glam::DVec3;
#[test]
fn export_always_owns_its_playback_and_user_stop_cleans_capture() {
let mut session = Session::<u8, &str>::default();
session.export(7, "capture");
assert!(matches!(
session.take(),
State::Export {
playback: 7,
export: "capture"
}
));
session.export(7, "capture");
assert_eq!(session.end(ExitCause::UserStop).cancel_capture, true);
assert!(session.is_live());
#[derive(Default)]
struct HostFixture {
actions: Vec<CleanupAction>,
}
#[test]
fn world_change_and_failure_share_cleanup_while_success_drains() {
for cause in [ExitCause::WorldChange, ExitCause::Failed] {
let mut session = Session::<(), ()>::default();
session.export((), ());
assert_eq!(session.end(cause).cancel_capture, true);
assert!(session.is_live());
impl HostFixture {
fn apply(&mut self, cleanup: &super::Cleanup) {
cleanup.apply(self);
}
}
impl CleanupHost for HostFixture {
fn apply_cleanup_action(&mut self, action: CleanupAction) {
self.actions.push(action);
}
let mut session = Session::<(), ()>::default();
session.export((), ());
assert_eq!(session.end(ExitCause::Finished).cancel_capture, false);
assert!(session.is_live());
}
#[test]
fn replay_replacement_is_not_an_export_and_stop_is_idempotent() {
let mut session = Session::<u8, ()>::default();
fn playback_context_uses_recording_clock_and_captured_environment() {
let live = Context::live(
4,
Some(Some("world-a".into())),
890,
900,
Some(12000),
DVec3::X,
);
assert_eq!(live.clock, Clock::Live(900));
let replay = Context::playback(
Mode::Replay,
5,
live.world.clone(),
9010,
901,
31.25,
Some(13000),
0.3,
DVec3::Z,
true,
);
let slow = Context::playback(
Mode::Replay,
5,
live.world.clone(),
9020,
902,
31.55,
Some(13000),
0.3,
DVec3::Z,
true,
);
assert_eq!(replay.clock, Clock::Recording(31.25));
assert_eq!(replay.sound_clock(), Clock::Recording(31.25));
assert_eq!(replay.day_time, Some(13000));
assert_eq!(replay.listener, DVec3::Z);
assert_eq!(slow.clock, Clock::Recording(31.55));
let map = Context::playback(
Mode::Replay,
5,
live.world.clone(),
9011,
901,
31.25,
Some(13000),
1.0,
DVec3::Z,
false,
);
assert_eq!(map.sound_clock(), Clock::Live(901));
assert!(replay.is_playback());
assert_ne!(replay.clock.value(), live.clock.value());
assert_eq!(replay.generation, slow.generation);
}
#[test]
fn seek_and_slow_motion_change_only_the_recording_clock() {
let at = |live_tick, record_tick, rate| {
Context::playback(
Mode::Replay,
12,
Some(Some("w".into())),
live_tick * 10,
live_tick,
record_tick,
Some(8000),
rate,
DVec3::ZERO,
true,
)
};
let before = at(400, 80.0, 1.0);
let seek = at(401, 20.0, 0.0);
let slow = at(402, 20.3, 0.3);
assert_eq!(before.display_clock(), Clock::Recording(80.0));
assert_eq!(seek.display_clock(), Clock::Recording(20.0));
assert_eq!(slow.display_clock(), Clock::Recording(20.3));
assert_eq!(slow.sound_clock(), Clock::Recording(20.3));
assert_eq!(slow.sound_clock().deadline_after(5), 25.3);
assert!(!slow.sound_clock().has_reached(25.3));
assert!(Clock::Recording(25.5).has_reached(25.5));
assert_eq!((seek.ui_tick, slow.ui_tick), (4010, 4020));
assert_eq!((seek.combat_tick, slow.combat_tick), (401, 402));
assert_eq!(seek.world, slow.world);
assert_eq!(seek.day_time, slow.day_time);
assert_eq!(seek.generation, slow.generation);
assert_eq!(
seek.clock,
Clock::Recording(20.0),
"a context snapshot is not advanced by live ticks"
);
}
#[test]
fn world_change_invalidates_live_generation_and_cleans_active_once() {
let mut session = Session::<u8, &str>::default();
let initial = session.generation();
assert!(
session.world_changed().is_none(),
"Live has no presentation resources to clean up"
);
assert_ne!(session.generation(), initial);
session.replay(1);
assert!(session.playback().is_some());
assert_eq!(session.end(ExitCause::Replaced).was_export, false);
assert_eq!(session.end(ExitCause::UserStop).was_export, false);
assert!(session.is_live());
let active = session.generation();
let cleanup = session
.world_changed()
.expect("active playback needs cleanup");
assert_ne!(session.generation(), active);
let mut host = HostFixture::default();
host.apply(&cleanup);
let action_count = host.actions.len();
assert_eq!(
host.actions
.iter()
.filter(|a| **a == CleanupAction::ClearPendingSounds)
.count(),
1
);
assert!(
session.world_changed().is_none(),
"a second call sees Live state"
);
assert_eq!(host.actions.len(), action_count, "cleanup is not repeated");
}
#[test]
fn restart_gets_new_generation_and_export_keeps_its_parent_generation() {
let mut session = Session::<u8, &str>::default();
session.replay(1);
let first = session.generation();
assert_ne!(first, 0);
let State::Replay(player) = session.take() else {
panic!("replay state lost")
};
session.export(player, "capture");
assert_eq!(session.generation(), first);
let _ = session.end(ExitCause::UserStop);
session.replay(2);
assert_ne!(session.generation(), first);
}
#[test]
fn end_and_restart_emit_cleanup_once_for_stop_unload_failure_and_success() {
for cause in [
ExitCause::UserStop,
ExitCause::WorldChange,
ExitCause::Failed,
ExitCause::Finished,
] {
let mut session = Session::<(), ()>::default();
session.replay(());
let State::Replay(()) = session.take() else {
panic!("replay state lost")
};
session.restore(State::Replay(()));
let mut host = HostFixture::default();
let cleanup = session.end(cause).expect("active session must clean up");
host.apply(&cleanup);
assert!(
session.end(cause).is_none(),
"second end repeated cleanup for {cause:?}"
);
for action in cleanup.actions {
assert_eq!(
host.actions.iter().filter(|a| **a == action).count(),
1,
"{action:?} for {cause:?}"
);
}
assert!(
!host.actions.contains(&CleanupAction::CancelCapture),
"a replay has no capture to cancel"
);
}
}
#[test]
fn export_cleanup_cancels_only_interrupted_captures_and_success_drains() {
for (cause, cancels) in [
(ExitCause::UserStop, true),
(ExitCause::WorldChange, true),
(ExitCause::Failed, true),
(ExitCause::Finished, false),
] {
let mut session = Session::<(), ()>::default();
session.replay(());
let State::Replay(playback) = session.take() else {
panic!("replay state lost")
};
session.export(playback, ());
let cleanup = session.end(cause).expect("export must clean up");
let mut host = HostFixture::default();
host.apply(&cleanup);
assert_eq!(
host.actions.contains(&CleanupAction::CancelCapture),
cancels,
"{cause:?}"
);
for action in cleanup.actions {
assert_eq!(
host.actions.iter().filter(|a| **a == action).count(),
1,
"{action:?} for {cause:?}"
);
}
assert!(
session.end(cause).is_none(),
"second end repeated cleanup for {cause:?}"
);
}
}
}
+44 -2
View File
@@ -502,6 +502,12 @@ impl Player {
out.engine(key, event, at, vel, gain, pitch, false);
}
}
What::StrikeCarrier(_) => {
if self.t - tr.first as f64 >= crate::sim::strike::EJECT_TICKS as f64 {
let (event, gain, pitch) = crate::sim::MissileKind::M48n6.engine_voice();
out.engine(key, event, at, vel, gain, pitch, false);
}
}
What::Strike => {
// A counter-strike's motor from its launch, as the live flight has it (#109).
if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
@@ -548,6 +554,7 @@ impl Player {
let event = match tr.what {
What::Missile(kind, _) if rec.missile_launch(tr.id).is_none() => Some(kind.launch_sound()),
What::Missile(..) => None,
What::StrikeCarrier(_) => Some(crate::sim::MissileKind::M48n6.launch_sound()),
What::Strike => Some(DroneKind::Kalibr.launch_sound()),
What::Drone(_) => None,
};
@@ -557,7 +564,14 @@ impl Player {
out.sound(event, heard(p), 1.0, 1.0);
}
}
self.heard = self.t;
// Cold-ejected physical strikes light only after the same delay as live playback.
for tr in rec.tracks.iter().filter(|tr| matches!(tr.what, What::StrikeCarrier(_))) {
let at = tr.first as f64 + crate::sim::strike::EJECT_TICKS as f64;
if (self.heard..self.t).contains(&at) && let Some(p) = tr.at(rec.origin, at) {
out.sound("airdef:launch.s400", heard(p), 1.0, 1.0);
}
}
self.heard = self.t;
}
/// One tick of the film: its clock runs, the plan gives the camera and the replay's moment.
@@ -953,7 +967,7 @@ impl Player {
What::Drone(kind) if kind.spec().decoy => (0x70A0A0A0, 0xFFC0C0C0),
What::Drone(_) => (0x90FF4040, 0xFFFF6060),
What::Missile(..) => (0x90FFD040, 0xFFFFE070),
What::Strike => (0x90FFA040, 0xFFFFC060),
What::Strike | What::StrikeCarrier(_) => (0x90FFA040, 0xFFFFC060),
};
let upto = ((self.t - tr.first as f64) / STEP as f64).floor();
if upto < 0.0 {
@@ -1169,6 +1183,34 @@ mod engine_tests {
assert_eq!(out.sounds.len(), 1);
}
#[test]
fn physical_strike_replay_delays_ignition_and_resets_after_seek() {
let mut rec = Recording::blank(100);
rec.straight(1, What::StrikeCarrier(99), 10, 70, DVec3::ZERO, DVec3::new(0.0, 70.0, 300.0));
let mut p = player(&rec);
p.rate = 1.0;
p.heard = 9.0;
p.t = 11.0;
let mut out = Out::default();
p.sounds(&rec, DVec3::ZERO, &mut out);
p.engines(&rec, DVec3::ZERO, false, &mut out);
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400_eject"]);
assert!(out.engines.is_empty());
out = Out::default();
p.t = 16.0;
p.sounds(&rec, DVec3::ZERO, &mut out);
p.engines(&rec, DVec3::ZERO, false, &mut out);
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400"]);
assert_eq!(out.engines.len(), 1);
out = Out::default();
p.sounds(&rec, DVec3::ZERO, &mut out);
assert!(out.sounds.is_empty(), "held frames must not repeat ignition");
p.heard = 9.0;
p.t = 11.0;
p.engines(&rec, DVec3::ZERO, false, &mut out);
assert!(out.engine_cut && out.engines.is_empty(), "seek before ignition releases motor voice");
}
/// A host that remembers which sources run.
#[derive(Default)]
struct Host(std::collections::BTreeMap<u32, [f64; 3]>);
+329
View File
@@ -0,0 +1,329 @@
//! Read-only scene data shared by live rendering and recorded playback adapters.
use crate::{presentation::Context, sim};
use glam::DVec3;
use std::borrow::Cow;
pub enum Source<'a> {
Live(&'a sim::Sim),
Recorded(&'a sim::record::Recording),
Empty,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MoverKind {
Drone(sim::DroneKind),
Missile(sim::MissileKind),
Strike { physical: bool, engine_lit: bool },
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mover {
/// Stable identity within its `group`.
pub id: u32,
/// The old live-smoke trail categories: drone, interceptor, counter-strike.
pub group: u8,
pub kind: MoverKind,
pub pos: DVec3,
}
pub enum Fire<'a> {
Live(&'a sim::fires::Fire),
Recorded(sim::record::ReplayFire),
}
impl Fire<'_> {
pub fn key(&self) -> u32 {
match self {
Self::Live(f) => f.id,
Self::Recorded(f) => f.key as u32,
}
}
pub fn at(&self) -> DVec3 {
match self {
Self::Live(f) => f.at,
Self::Recorded(f) => f.at,
}
}
pub fn start(&self) -> u64 {
match self {
Self::Live(f) => f.start,
Self::Recorded(f) => f.start as u64,
}
}
pub fn age_offset(&self) -> u64 {
match self {
Self::Live(_) => 0,
Self::Recorded(f) => f.age_offset as u64,
}
}
pub fn size(&self) -> f32 {
match self {
Self::Live(f) => f.size,
Self::Recorded(f) => f.size,
}
}
pub fn quiet(&self) -> bool {
match self {
Self::Live(f) => f.quiet,
Self::Recorded(f) => f.quiet,
}
}
pub fn shown(&self) -> bool {
match self {
Self::Live(f) => f.shown,
Self::Recorded(f) => f.shown,
}
}
pub fn level(&self, tick: u64) -> (f32, f32) {
match self {
Self::Live(f) => f.level(tick),
Self::Recorded(f) => {
let (mut flame, mut smoke) = sim::fires::level(
tick.saturating_sub(self.start()) as f64 + self.age_offset() as f64,
f.life as f64,
);
if f.water == Some(true) {
flame = 0.0;
smoke *= 0.5;
}
(flame, smoke)
}
}
}
}
/// A selected instant from exactly one source. Recorded snapshots borrow only the recording;
/// changing the current live simulation cannot change their contents.
pub struct Snapshot<'a> {
source: Source<'a>,
time: f64,
}
impl<'a> Snapshot<'a> {
pub fn at_context(ctx: &Context, source: Source<'a>) -> Self {
let time = match &source {
Source::Live(_) => ctx.combat_tick as f64,
Source::Recorded(_) | Source::Empty => ctx.display_clock().value(),
};
Self { source, time }
}
pub fn source(&self) -> &'static str {
match &self.source {
Source::Live(_) => "live",
Source::Recorded(_) => "recorded",
Source::Empty => "empty",
}
}
pub fn time(&self) -> f64 {
self.time
}
pub fn movers(&self) -> Vec<Mover> {
match &self.source {
Source::Live(sim) => sim
.drones
.iter()
.map(|d| Mover {
id: d.id,
group: 0,
kind: MoverKind::Drone(d.kind),
pos: d.pos,
})
.chain(sim.missiles.iter().map(|m| Mover {
id: m.id,
group: 1,
kind: MoverKind::Missile(m.kind),
pos: m.pos,
}))
.chain(sim.strikes.flights.iter().map(|f| {
let physical = f.carrier.is_some();
Mover {
id: f.id,
group: 2,
kind: MoverKind::Strike {
physical,
engine_lit: !physical
|| (self.time.max(0.0) as u64).saturating_sub(f.start)
>= sim::strike::EJECT_TICKS as u64,
},
pos: f.pos,
}
}))
.collect(),
Source::Recorded(rec) => rec
.tracks
.iter()
.filter_map(|tr| {
let pos = tr.at(rec.origin, self.time)?;
let (group, kind) = match tr.what {
sim::record::What::Drone(kind) => (0, MoverKind::Drone(kind)),
sim::record::What::Missile(kind, _) => (1, MoverKind::Missile(kind)),
sim::record::What::Strike => (
2,
MoverKind::Strike {
physical: false,
engine_lit: true,
},
),
sim::record::What::StrikeCarrier(_) => (
2,
MoverKind::Strike {
physical: true,
engine_lit: (self.time - tr.first as f64).max(0.0) as u64
>= sim::strike::EJECT_TICKS as u64,
},
),
};
Some(Mover {
id: tr.id,
group,
kind,
pos,
})
})
.collect(),
Source::Empty => Vec::new(),
}
}
pub fn blasts(&self) -> Cow<'_, [sim::Blast]> {
match &self.source {
Source::Live(sim) => Cow::Borrowed(&sim.blasts),
Source::Recorded(rec) => Cow::Owned(sim::record::replay_blasts(rec, self.time)),
Source::Empty => Cow::Borrowed(&[]),
}
}
/// Smoke billows intentionally outlive the visual blast. Live blasts are already retained
/// according to their own lifetime; recorded events use the longer smoke projection.
pub fn smoke_blasts(&self) -> Cow<'_, [sim::Blast]> {
match &self.source {
Source::Live(sim) => Cow::Borrowed(&sim.blasts),
Source::Recorded(rec) => Cow::Owned(sim::record::replay_smoke_blasts(rec, self.time)),
Source::Empty => Cow::Borrowed(&[]),
}
}
pub fn fires(&self) -> Vec<Fire<'_>> {
match &self.source {
Source::Live(sim) => sim.fires.list.iter().map(Fire::Live).collect(),
Source::Recorded(rec) => sim::record::replay_fires(rec, self.time)
.into_iter()
.map(Fire::Recorded)
.collect(),
Source::Empty => Vec::new(),
}
}
pub fn recording(&self) -> Option<&sim::record::Recording> {
match &self.source {
Source::Live(_) => None,
Source::Recorded(rec) => Some(rec),
Source::Empty => None,
}
}
/// Whether this snapshot was selected from a playback presentation, including a missing
/// recording. An absent playback source must never expose cached live-only trails.
pub fn is_recorded_view(&self) -> bool {
matches!(&self.source, Source::Recorded(_) | Source::Empty)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::{Clock, Mode};
#[test]
fn recorded_snapshot_seek_is_independent_of_interleaved_live_simulations() {
use sim::record::{Event, EventKind, Recording, What};
let mut rec = Recording::blank(160);
rec.straight(
7,
What::Drone(sim::DroneKind::Geran3),
0,
160,
DVec3::new(3.0, 70.0, 0.0),
DVec3::new(3.0, 70.0, 160.0),
);
rec.events.push(Event {
at: 40,
pos: DVec3::new(3.0, 69.0, 40.0),
kind: EventKind::Hit {
drone: 7,
kind: sim::DroneKind::Geran3,
power: 2,
object: None,
sam: None,
},
});
let mut live_a = sim::Sim::new(1);
live_a.blasts.push(sim::Blast {
id: 101,
at: DVec3::X,
size: 4.0,
start: 40,
life: 60,
});
let mut live_b = sim::Sim::new(2);
live_b.blasts.push(sim::Blast {
id: 202,
at: DVec3::Y,
size: 8.0,
start: 40,
life: 60,
});
let recorded_at = |time| {
let ctx = Context::playback(
Mode::Replay,
3,
None,
0,
90_000,
time,
None,
0.25,
DVec3::ZERO,
true,
);
let scene = Snapshot::at_context(&ctx, Source::Recorded(&rec));
let mover = scene.movers().into_iter().find(|m| m.id == 7).unwrap();
let blast_ids = scene.blasts().iter().map(|b| b.id).collect::<Vec<_>>();
(scene.time(), mover.pos, blast_ids)
};
let first = recorded_at(40.0);
assert_eq!(first.0, 40.0);
assert_eq!(first.2, vec![0x4000_0000]);
let ctx_live = || Context::live(3, None, 0, 40, None, DVec3::ZERO);
let a_ctx = ctx_live();
let a_scene = Snapshot::at_context(&a_ctx, Source::Live(&live_a));
assert_eq!(a_scene.blasts()[0].id, 101);
let middle = recorded_at(120.0);
let b_ctx = ctx_live();
let b_scene = Snapshot::at_context(&b_ctx, Source::Live(&live_b));
assert_eq!(b_scene.blasts()[0].id, 202);
let again = recorded_at(40.0);
assert_eq!(
again, first,
"seek back to the same recording instant is deterministic"
);
assert_ne!(
middle.1, first.1,
"recorded mover poses advance with recording time"
);
assert_eq!(first.1, DVec3::new(3.0, 70.0, 40.0));
assert_ne!(first.2, vec![101]);
assert_ne!(first.2, vec![202]);
assert_eq!(a_scene.time(), 40.0);
assert_eq!(b_scene.time(), 40.0);
assert!(matches!(a_ctx.clock, Clock::Live(40)));
}
}
+13 -3
View File
@@ -21,11 +21,21 @@ impl Aircraft {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroundStrike {
/// The game has no confirmed compatible ground-attack loadout for this unit.
/// This is a content limitation, not a claim about the real equipment.
/// Game-only RM48U coordinate-strike profile for S-400. Evidence: official agency report,
/// not independent certification: https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html
/// The range and flight are game abstractions, not real parameters.
Rm48uGame,
/// No implemented game profile; this is not a claim of physical impossibility.
Unavailable { reason: &'static str },
}
impl GroundStrike {
/// Evidence describes provenance, not independent certification.
pub fn evidence(self) -> Option<&'static str> {
match self { GroundStrike::Rm48uGame => Some("official-agency-report"), GroundStrike::Unavailable { .. } => None }
}
}
#[derive(Clone, Copy, Debug)]
pub struct Unit {
pub kind: SamKind,
@@ -37,7 +47,7 @@ impl Unit {
/// Whether the unit has a gun; callers need no access to the private weapon profile.
pub fn has_gun(self) -> bool { self.kind.spec().gun.is_some() }
pub fn ground_strike(self) -> GroundStrike {
GroundStrike::Unavailable { reason: "Для этой техники не задан подтверждённый профиль удара по координатам" }
if self.kind == SamKind::S400 { GroundStrike::Rm48uGame } else { GroundStrike::Unavailable { reason: "Для этой техники не задан профиль удара по координатам" } }
}
}
+3 -2
View File
@@ -450,7 +450,8 @@ impl Sam {
/// Missiles above what the cells hold are lost with them.
pub fn fit_cells(&mut self) {
if self.kind.spec().missile.is_some() {
self.missiles = self.missiles.min(self.cells());
self.ground_rounds = self.ground_rounds.min(self.cells());
self.missiles = self.missiles.min(self.cells().saturating_sub(self.ground_rounds));
}
}
/// Ticks a reload takes: longer with a damaged launcher.
@@ -493,7 +494,7 @@ impl Sim {
// Rebuilt where it stands: a march under way is called off.
sam.dest = None;
sam.march = 0;
sam.missiles = spec.missile.as_ref().map_or(0, |m| m.magazine);
sam.missiles = spec.missile.as_ref().map_or(0, |m| m.magazine.saturating_sub(sam.ground_rounds));
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
}
for h in &mut self.target_health {
+40
View File
@@ -19,6 +19,46 @@ impl Sim {
self.sams.iter().any(|s| s.kind == SamKind::Depot)
}
/// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there.
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 { return Err("Для этого комплекса нет игрового профиля RM48U".into()); }
if !s.alive() || s.moving() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 {
return Err("Комплекс должен быть исправен и развёрнут".into());
}
if s.ground_rounds >= s.cells() { return Err("Нет свободной ячейки для RM48U".into()); }
let depot = self.sams.iter().enumerate().filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ground_stock > 0 && d.pos.distance(s.pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(s.pos).total_cmp(&b.pos.distance(s.pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j).ok_or("Нет живого склада с RM48U рядом (60 блоков)")?;
let displaced = u32::from(self.sams[i].missiles + self.sams[i].ground_rounds >= self.sams[i].cells());
let air_48n6_stock = self.sams[depot].air_48n6_stock.checked_add(displaced).ok_or("Запас склада переполнен")?;
self.sams[i].missiles -= displaced;
self.sams[i].ground_rounds += 1;
if self.sams[i].ground_rounds >= self.sams[i].cells() && self.sams[i].kind.spec().gun.is_none() { self.sams[i].empty = false; }
self.sams[depot].ground_stock -= 1;
self.sams[depot].air_48n6_stock = air_48n6_stock;
Ok(format!("С-400 №{}: загружена RM48U (игровой профиль), ударных {}, ПВО {}; на складе RM48U {}, снятых ракет ПВО {}", i + 1, self.sams[i].ground_rounds, self.sams[i].missiles, self.sams[depot].ground_stock, self.sams[depot].air_48n6_stock))
}
/// Return a loaded ground round to a nearby depot; restore a previously removed air round if available.
pub fn unload_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 || !s.alive() || s.moving() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 {
return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into());
}
let depot = self.sams.iter().enumerate().filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(s.pos).total_cmp(&b.pos.distance(s.pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j).ok_or("Нет живого склада рядом (60 блоков)")?;
let stock = self.sams[depot].ground_stock.checked_add(1).ok_or("Запас склада переполнен")?;
self.sams[i].ground_rounds -= 1;
self.sams[depot].ground_stock = stock;
if self.sams[depot].air_48n6_stock > 0 {
self.sams[depot].air_48n6_stock -= 1;
self.sams[i].missiles += 1;
}
Ok(format!("С-400 №{}: выгружена RM48U; ударных {}, ПВО {}", i + 1, self.sams[i].ground_rounds, self.sams[i].missiles))
}
/// Reloads from depots near the systems, and the trucks' rounds.
pub(super) fn step_supply(&mut self, out: &mut Out) {
if !self.logistics() {
+17 -5
View File
@@ -1365,6 +1365,11 @@ pub struct Sam {
yaw_vel: f64,
pitch_vel: f64,
pub missiles: u32,
/// Explicit RM48U game rounds loaded in shared launcher cells.
pub ground_rounds: u32,
/// Separate typed rounds and returned S-400 air rounds held by a depot.
pub ground_stock: u32,
pub air_48n6_stock: u32,
pub bursts: u32,
cooldown: u32,
gun_cooldown: u32,
@@ -1443,6 +1448,9 @@ impl Sam {
yaw_vel: 0.0,
pitch_vel: 0.0,
missiles: spec.missile.as_ref().map_or(0, |m| m.magazine),
ground_rounds: 0,
ground_stock: 0,
air_48n6_stock: 0,
bursts: spec.gun.as_ref().map_or(0, |g| g.bursts),
cooldown: 40,
gun_cooldown: 0,
@@ -1523,7 +1531,7 @@ impl Sam {
return text + " " + &self.state.name().to_lowercase();
}
match self.kind {
SamKind::Depot => return format!("{text}: запас {} перезарядок", self.cargo),
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", self.cargo, self.ground_stock, self.air_48n6_stock),
SamKind::Tzm => return format!("{text}: на борту {}/2{}", self.cargo, if self.job.is_some() { ", в пути" } else { "" }),
SamKind::Ew => {
let state = if self.ew_on { "ГЛУШИТ" } else if self.ew_lock { "остывает" } else { "готова" };
@@ -1549,10 +1557,14 @@ impl Sam {
text += &format!(" перезарядка {}с", self.reloading.div_ceil(20));
} else {
if let Some(m) = &spec.missile {
text += &format!(" ракеты {}/{}", self.missiles, m.magazine);
if self.kind == SamKind::S400 {
text += &format!(" ПВО {} · RM48U {} / {} ячеек", self.missiles, self.ground_rounds, self.cells());
} else {
text += &format!(" ракеты {}/{}", self.missiles, m.magazine);
}
}
if spec.gun.is_some() {
text += &format!(" снаряды {}", self.bursts);
text += &format!(" очереди {}", self.bursts);
}
}
text
@@ -2524,7 +2536,7 @@ impl Sim {
if sam.reloading > 0 {
sam.reloading -= 1;
if sam.reloading == 0 {
sam.missiles = sam.cells();
sam.missiles = sam.cells().saturating_sub(sam.ground_rounds);
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
}
@@ -2640,7 +2652,7 @@ impl Sim {
let Some(aim) = aim else {
// Out of missiles or of shells, and nothing to shoot: reload now (both, as a
// combined system's crew would), not only once both are spent.
let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0) || (spec.gun.is_some() && sam.bursts == 0);
let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0 && sam.cells() > sam.ground_rounds) || (spec.gun.is_some() && sam.bursts == 0);
if spent && sam.reloading == 0 && !sam.empty {
if logistics {
sam.empty = true;
+125 -2
View File
@@ -166,6 +166,8 @@ pub enum What {
Missile(MissileKind, u32),
/// A counter-strike missile on its way to a launch site (#109).
Strike,
/// An explicitly profiled ground strike and its physical carrier.
StrikeCarrier(u32),
}
pub struct Track {
@@ -467,13 +469,24 @@ pub fn blast_spec(kind: EventKind) -> (f32, u32) {
/// `Blast`s the live simulation keeps, with `start` in the recording's ticks and the event's
/// own id range. A pure function of `t`, so a seek or a pause shows the same frame.
pub fn replay_blasts(rec: &Recording, t: f64) -> Vec<Blast> {
replay_blasts_from_events(rec, t, false)
}
/// Recorded smoke billows persist after the short visual blast expires. Keep the same event
/// classification and geometry within the bounded 900-tick smoke window.
pub fn replay_smoke_blasts(rec: &Recording, t: f64) -> Vec<Blast> {
replay_blasts_from_events(rec, t, true)
}
fn replay_blasts_from_events(rec: &Recording, t: f64, keep_expired: bool) -> Vec<Blast> {
rec.events
.iter()
.enumerate()
.filter_map(|(k, e)| {
let (size, life) = blast_spec(e.kind);
let age = t - e.at as f64;
(0.0..life as f64).contains(&age).then_some(Blast { id: 0x4000_0000 | k as u32, at: e.pos, size, start: e.at as u64, life })
(if keep_expired { (0.0..=900.0).contains(&age) } else { (0.0..life as f64).contains(&age) })
.then_some(Blast { id: 0x4000_0000 | k as u32, at: e.pos, size, start: e.at as u64, life })
})
.collect()
}
@@ -750,6 +763,13 @@ impl Sim {
}
}
pub(super) fn record_strike_launch(&mut self, id: u32, carrier: u32, at: DVec3) {
self.begin_recording_if_active();
if let Some(r) = &mut self.rec {
r.point(0x7100_0000 | id, What::StrikeCarrier(carrier), at);
}
}
/// Once a tick: starts a recording with the first drone or counter-strike in the air, adds the tracks' points,
/// ends it when the sky has been clear 5 s.
pub(super) fn record(&mut self) {
@@ -775,10 +795,19 @@ impl Sim {
for m in &self.missiles {
r.point(m.id, What::Missile(m.kind, m.sam), m.pos);
}
for f in &self.strikes.flights {
for f in self.strikes.flights.iter().filter(|f| f.carrier.is_none()) {
r.point(f.track(), What::Strike, f.pos);
}
}
// Physical strikes start with an exact muzzle point at launch. Continue that track on a
// flight-relative STEP grid; global recording parity can be offset by the launch tick.
for f in &self.strikes.flights {
let Some(carrier) = f.carrier else { continue };
let age = self.tick.saturating_sub(f.start);
if age > 0 && age % STEP as u64 == 0 {
r.point(f.track(), What::StrikeCarrier(carrier), f.pos);
}
}
r.len += 1;
r.quiet = if busy { 0 } else { r.quiet + 1 };
if r.quiet >= 100 || r.len >= LONGEST {
@@ -848,6 +877,13 @@ impl Sim {
out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true);
}
}
What::StrikeCarrier(_) => super::strike::round_visual(
out,
id,
pos,
look(dir, 0.0),
t - tr.first as f64 >= super::strike::EJECT_TICKS as f64,
),
What::Strike => {
// The same model, flame and turn the live flight drew (#106, #109).
let spec = DroneKind::Kalibr.spec();
@@ -970,6 +1006,93 @@ mod tests {
}
}
fn physical_strike(record_len: Option<u32>) -> (Sim, u32, DVec3) {
use crate::sim::sites::{LaunchSite, SiteClass};
use crate::sim::strike::{Estimate, Known, SiteState};
use glam::DVec2;
let mut sim = Sim::new(11);
sim.tick = 100 + u64::from(record_len.unwrap_or(0));
if let Some(len) = record_len {
let mut rec = Recording::new(1, &sim);
rec.len = len;
sim.rec = Some(rec);
}
let site = 1;
sim.sites.list.push(LaunchSite {
id: site,
side: 0,
sector: 0,
bearing: 0.0,
class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 300.0),
range: 300.0,
water: false,
stock: 0,
planned: 0,
alive: true,
next_free: 0,
offmap: false,
});
sim.strikes.known.push(Known {
site,
class: SiteClass::Ramp,
obs: Vec::new(),
est: Some(Estimate {
pos: DVec2::new(0.0, 300.0),
radius: 5.0,
fix: true,
bearing: 0.0,
bearing_err: 0.01,
origin: DVec2::ZERO,
}),
launches: 1,
last: 0,
state: SiteState::Active,
aimed: false,
});
sim.order_test_strike(site, DVec3::new(0.0, 64.0, 0.0), &mut Out::default())
.unwrap();
let flight = &mut sim.strikes.flights[0];
let (id, muzzle) = (flight.id, flight.pos);
let carrier = 77;
flight.carrier = Some(carrier);
sim.record_strike_launch(id, carrier, muzzle);
(sim, id, muzzle)
}
#[test]
fn physical_strike_track_keeps_muzzle_and_samples_on_flight_relative_grid() {
// A fresh recording starts at launch; the other cases launch into odd/even positions on
// an existing recording's global grid.
for record_len in [None, Some(1), Some(2)] {
let (mut sim, id, muzzle) = physical_strike(record_len);
let track_id = 0x7100_0000 | id;
{
let rec = sim.rec.as_ref().unwrap();
let track = rec.track(track_id).unwrap();
assert_eq!(track.what, What::StrikeCarrier(77));
assert_eq!(track.points.len(), 1, "the launch records exactly one muzzle point");
assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle));
}
for age in 1..=4u64 {
sim.tick += 1;
let pos = muzzle + DVec3::Z * (age as f64 * 8.0);
sim.strikes.flights[0].pos = pos;
sim.record();
let rec = sim.rec.as_ref().unwrap();
let track = rec.track(track_id).unwrap();
let expected_samples = 1 + (age / STEP as u64) as usize;
assert_eq!(track.points.len(), expected_samples, "flight age {age}, recording len {}", record_len.unwrap_or(0));
assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle));
if age % STEP as u64 == 0 {
assert_eq!(track.at(rec.origin, (track.first + age as u32) as f64), Some(pos));
}
}
}
}
#[test]
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
let mut r = recording();
+154 -23
View File
@@ -10,18 +10,34 @@
//! Directly observed launches provide independent point sightings, combined by weighted least squares (`solve`).
//! A site without a sufficiently accurate fix remains a bearing and cannot be struck.
//!
//! **Striking it.** Production orders require a real carrier and an explicitly supported coordinate-strike
//! munition profile. No such loadout is currently implemented, so orders are rejected without spending ammunition.
//! The flight/impact mechanics remain available to test fixtures and existing flights; there is no virtual enemy
//! air defence. Only an actual simulated interceptor can justify an intercepted outcome.
//! **Striking it.** A manual order spends a prepared, explicitly typed round from a ready physical carrier.
//! There is no virtual enemy air defence. Only a simulated interceptor can justify an intercepted outcome.
//!
//! **Off the map** (`offmap`: no land was found or loaded, so no kit stands anywhere): the site is scouted like any other,
//! as bearing and range, but there is nothing to see burn. A strike that would have hit just ends its launches
//! ("halts" them) and says so; the result is not drawn, and a miss is lost beyond the loaded map.
use super::*;
use super::sites::{LaunchSite, SiteClass};
use super::sites::SiteClass;
#[cfg(test)]
use super::sites::LaunchSite;
use glam::DVec2;
/// Minecraft presentation profile; neither dimensions nor timing reproduce a real weapon.
pub const ROUND_MODEL: &str = "airdef:rm48u";
pub const ROUND_SCALE: f64 = 1.5;
pub const EJECT_TICKS: u64 = 5;
/// Shared live/replay appearance, including the unlit cold-ejection phase.
pub(super) fn round_visual(out: &mut Out, id: u32, pos: DVec3, rot: DQuat, lit: bool) {
out.model(id, ROUND_MODEL, pos, rot, ROUND_SCALE, false);
if lit {
let spec = MissileKind::M48n6.spec();
let back = (spec.rear - 8.0) / 16.0 * ROUND_SCALE + spec.flame;
out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true);
}
}
/// Every number of the mechanic.
pub struct Tune {
/// Angular error of a track pointing back (radians, 1 sigma): 3 degrees.
@@ -264,6 +280,8 @@ pub struct Target {
pub struct Flight {
pub id: u32,
pub site: u32,
/// Physical launcher id, absent only for old test fixtures.
pub carrier: Option<u32>,
/// Where it was fired from, and where it is now (the swept step, not the plan).
pub from: DVec3,
pub pos: DVec3,
@@ -554,7 +572,12 @@ impl Sim {
let below = ground.at(DVec3::new(f.land.x, 0.0, f.land.y), now);
let end = DVec3::new(f.land.x, below.unwrap_or(f.from.y), f.land.y);
let t = ((now - f.start) as f64 / (f.arrive - f.start).max(1) as f64).clamp(0.0, 1.0);
let planned = f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt());
let age = now.saturating_sub(f.start);
let planned = if f.carrier.is_some() && age < EJECT_TICKS {
f.from + DVec3::Y * (age as f64 * 0.7)
} else {
f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt())
};
let from = f.pos;
// Time spent waiting for world data must not accumulate into a faster step.
let delta = planned - from;
@@ -616,12 +639,22 @@ impl Sim {
let dir = (pos - from).normalize_or(end - f.from).normalize_or(DVec3::NEG_Z);
let rot = look(dir, 0.0);
let id = 0x7500_0000 + f.id * PARTS;
out.model(id, spec.model, pos, rot, spec.scale, false);
if f.carrier.is_some() {
round_visual(out, id, pos, rot, age >= EJECT_TICKS);
} else {
out.model(id, spec.model, pos, rot, spec.scale, false);
}
let flicker = 0.7 + 0.3 * self.vis.f();
if let Engine::Jet(up, back, size) = spec.engine {
if f.carrier.is_none() && let Engine::Jet(up, back, size) = spec.engine {
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
}
if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
if f.carrier.is_some() {
if age == EJECT_TICKS { out.sound("airdef:launch.s400", pos, 1.0, 1.0); }
if age >= EJECT_TICKS {
let (event, gain, pitch) = MissileKind::M48n6.engine_voice();
out.engine(id, event, pos, pos - from, gain, pitch, false);
}
} else if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
out.engine(id, event, pos, pos - from, 0.8, pitch, false);
}
f.pos = pos;
@@ -646,17 +679,42 @@ impl Sim {
v
}
/// A manual order never substitutes the player or a generic stock for a physical launcher.
pub fn order_strike(&mut self, id: u32, _from: DVec3, _out: &mut Out) -> Result<String, String> {
self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена: /airdef sites покажет известные"))?;
Err(if self.sams.is_empty() {
"Удар недоступен: нет собственной пусковой с совместимым боеприпасом".into()
} else {
let reason = match super::catalog::unit(self.sams[0].kind).ground_strike() {
super::catalog::GroundStrike::Unavailable { reason } => reason,
};
format!("Удар недоступен: {reason}; совместимый боеприпас не загружен")
})
/// Atomic manual launch from an already prepared, compatible carrier.
pub fn order_strike(&mut self, id: u32, _from: DVec3, out: &mut Out) -> Result<String, String> {
let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена"))?;
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: нужна разведка")?;
if matches!(k.state, SiteState::Destroyed(_)) { return Err("ПУ уже уничтожена".into()); }
if self.strikes.flights.iter().any(|f| f.site == id) { return Err("По этой ПУ ракета уже в полёте".into()); }
let site = self.sites.get(id).ok_or("ПУ уже нет на карте")?;
let snap = Target { pos: DVec2::new(site.pos.x, site.pos.z), stock: site.stock, offmap: site.offmap, alive: site.alive };
let (i, dist) = self.sams.iter().enumerate().filter_map(|(i,s)| {
let dist = (est.pos - DVec2::new(s.pos.x, s.pos.z)).length();
(matches!(catalog::unit(s.kind).ground_strike(), catalog::GroundStrike::Rm48uGame)
&& s.alive() && !s.moving() && s.reloading == 0 && s.cooldown == 0
&& s.part(Part::Launcher) > 0.0 && s.ground_rounds > 0 && dist <= TUNE.range)
.then_some((i, dist))
}).min_by(|(i,a), (j,b)| self.sams[*j].ground_rounds.cmp(&self.sams[*i].ground_rounds)
.then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id)))
.ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?;
let sam = &mut self.sams[i];
let carrier = sam.id;
let (start, _) = sam.muzzle(4 - sam.ground_rounds);
sam.ground_rounds -= 1;
sam.cooldown = 20;
sam.launched = 12;
sam.fired += 1;
self.intel.revealed.push((carrier, sam.pos, self.tick));
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
self.strikes.flights.push(Flight { id: self.strikes.next, site: id, carrier: Some(carrier), from: start, pos: start, aim: est.pos,
land: est.pos + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == id) { k.aimed = true; }
self.record_strike_launch(self.strikes.next, carrier, start);
out.sound("airdef:launch.s400_eject", start, 1.0, 1.0);
out.particles("minecraft:cloud", start, 0.6, DVec3::Y * 0.05, 0.05, 30);
Ok(format!("С-400 №{} запустил RM48U по ПУ №{id}; осталось ударных: {}", i + 1, self.sams[i].ground_rounds))
}
/// Synthetic launcher used only by flight/impact regression fixtures; absent from production builds.
@@ -693,6 +751,7 @@ impl Sim {
self.strikes.flights.push(Flight {
id: self.strikes.next,
site: id,
carrier: None,
from: start,
pos: start,
aim: est.pos,
@@ -850,7 +909,7 @@ impl Sim {
if v.is_empty() {
v.push("Известных ПУ нет: их находят РЛС по пускам и трекам вылетевших целей".into());
}
v.push("Удар по координатам недоступен: требуется реализованный совместимый носитель и боеприпас".into());
v.push("Удар: /airdef strike <ПУ>; подготовка RM48U: /airdef ground-load <номер С-400> у склада".into());
v
}
}
@@ -1149,13 +1208,85 @@ mod tests {
let stock = sim.strikes.stock;
for player in [DVec3::ZERO, DVec3::new(4000.0, 64.0, 300.0)] {
let e = sim.order_strike(id, player, &mut out).unwrap_err();
assert!(e.contains("боеприпас"), "{e}");
assert!(e.contains("RM48U"), "{e}");
assert!(sim.strikes.flights.is_empty());
assert_eq!(sim.strikes.stock, stock);
assert_eq!(sim.strikes.fired, 0);
}
sim.sams.clear();
assert!(sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err().contains("нет собственной"));
assert!(sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err().contains("Нет готового"));
}
#[test]
fn typed_preparation_and_atomic_carrier_selection() {
let (mut sim, mut ground, mut out, site) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
run(&mut sim, &mut ground, &mut out, 120);
let depot_id = sim.id();
sim.sams.push(Sam::new(depot_id, SamKind::Depot, DVec3::ZERO, 0.0));
let depot = sim.sams.len() - 1;
let a_id = sim.id();
sim.sams.push(Sam::new(a_id, SamKind::S400, DVec3::new(5.0, 0.0, 0.0), 0.0));
let a = sim.sams.len() - 1;
let b_id = sim.id();
sim.sams.push(Sam::new(b_id, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0));
let b = sim.sams.len() - 1;
assert_eq!((sim.sams[a].missiles, sim.sams[a].ground_rounds, sim.sams[depot].ground_stock), (4, 0, 0));
assert!(sim.load_ground_round(a).is_err());
sim.sams[depot].ground_stock = 4; // Explicit scenario supply.
sim.load_ground_round(a).unwrap();
sim.load_ground_round(b).unwrap();
sim.load_ground_round(b).unwrap();
assert_eq!((sim.sams[a].missiles, sim.sams[a].ground_rounds, sim.sams[b].missiles, sim.sams[b].ground_rounds), (3, 1, 2, 2));
assert_eq!((sim.sams[depot].ground_stock, sim.sams[depot].air_48n6_stock), (1, 3));
sim.unload_ground_round(a).unwrap();
assert_eq!((sim.sams[a].missiles, sim.sams[a].ground_rounds, sim.sams[depot].ground_stock, sim.sams[depot].air_48n6_stock), (4, 0, 2, 2));
sim.load_ground_round(a).unwrap();
sim.sams[a].cooldown = 0;
sim.sams[b].cooldown = 0;
let muzzle = sim.sams[b].muzzle(2).0;
let old_stock = sim.strikes.stock;
sim.order_strike(site, DVec3::new(99999.0, 0.0, 99999.0), &mut out).unwrap();
assert_eq!((sim.sams[a].ground_rounds, sim.sams[b].ground_rounds, sim.strikes.stock), (1, 1, old_stock));
let f = sim.strikes.flights.last().unwrap();
assert_eq!((f.carrier, f.from), (Some(b_id), muzzle));
assert!(sim.rec.as_ref().unwrap().tracks.iter().any(|t| t.what == record::What::StrikeCarrier(b_id)));
assert!(sim.order_strike(site, DVec3::ZERO, &mut out).is_err());
assert_eq!(sim.sams[b].ground_rounds, 1);
sim.repair();
assert!(sim.sams[b].missiles + sim.sams[b].ground_rounds <= 4);
}
#[test]
fn fully_loaded_ground_cells_do_not_consume_air_reload_cargo() {
let mut sim = Sim::new(1);
sim.sams.push(Sam::new(1, SamKind::Depot, DVec3::ZERO, 0.0));
sim.sams[0].ground_stock = 4;
sim.sams.push(Sam::new(2, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0));
for _ in 0..4 { sim.load_ground_round(1).unwrap(); }
let cargo = sim.sams[0].cargo;
let mut ground = Ground::default();
let mut out = Out::default();
run(&mut sim, &mut ground, &mut out, 30);
assert_eq!(sim.sams[0].cargo, cargo);
assert_eq!((sim.sams[1].missiles, sim.sams[1].ground_rounds), (0, 4));
}
#[test]
fn unavailable_carriers_cannot_spend_ground_rounds() {
let (mut sim, mut ground, mut out, site) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
run(&mut sim, &mut ground, &mut out, 120);
let id = sim.id();
let mut s = Sam::new(id, SamKind::S400, DVec3::ZERO, 0.0);
s.missiles = 2; s.ground_rounds = 2; s.cooldown = 0;
sim.sams.push(s);
let i = sim.sams.len() - 1;
sim.sams[i].health = 0.0;
assert!(sim.order_strike(site, DVec3::ZERO, &mut out).is_err());
sim.sams[i].health = 1.0; sim.sams[i].reloading = 5;
assert!(sim.order_strike(site, DVec3::ZERO, &mut out).is_err());
sim.sams[i].reloading = 0; sim.sams[i].state = SamState::Moving;
assert!(sim.order_strike(site, DVec3::ZERO, &mut out).is_err());
assert_eq!(sim.sams[i].ground_rounds, 2);
}
#[test]
+351 -91
View File
@@ -3,7 +3,10 @@
//! derives everything from a segment's age, so the columns and blasts are a pure function of the
//! tick (nothing grows twice when a frame is shown again); trails are the only state, and they are
//! cut back when the tick goes backwards.
use crate::sim::{Class, DroneKind, Sim};
use crate::{
scene::{MoverKind, Snapshot},
sim::{Class, DroneKind},
};
use glam::DVec3;
use horizon_mod_sdk::render::SmokeSegment;
use std::collections::HashMap;
@@ -47,10 +50,18 @@ fn seg(id: u32, a: DVec3, b: DVec3, born: u64, life: u32) -> SmokeSegment {
}
}
/// The column over one fire up to `tick`: a puff every 15 ticks (90 for the weaker fires) that
/// rises, spreads and thins. A pure function of the tick.
fn fire_column(out: &mut Vec<SmokeSegment>, fire_id: u32, at: DVec3, start: u64, size: f32, shown: bool, tick: u64, level: &dyn Fn(u64) -> (f32, f32)) {
fn fire_column(
out: &mut Vec<SmokeSegment>,
fire_id: u32,
at: DVec3,
start: u64,
size: f32,
shown: bool,
tick: u64,
level: &dyn Fn(u64) -> (f32, f32),
) {
// Only the strongest fires get a full column; the rest a thin puff now and then.
let step = if shown { 15 } else { 90 };
let first = start.max(tick.saturating_sub(520));
@@ -87,7 +98,13 @@ fn blast_billows(out: &mut Vec<SmokeSegment>, blasts: &[crate::sim::Blast], tick
}
let h = b.size as f64 * (0.2 + 0.5 * j as f64);
let at = b.at + DVec3::Y * h;
let mut s = seg(0x5000_0000 | (b.id.wrapping_mul(7) + j as u32) & 0x0fff_ffff, at, at, born, 800);
let mut s = seg(
0x5000_0000 | (b.id.wrapping_mul(7) + j as u32) & 0x0fff_ffff,
at,
at,
born,
800,
);
s.radius_start = b.size * 0.6;
s.radius_end = b.size * 3.2 + 4.0;
s.density = 2.4 / (1.0 + j as f32 * 0.25);
@@ -115,14 +132,42 @@ struct Look {
/// A rocket's white line, thicker for a bigger missile (`scale`: Pantsir 0.85, S-500 1.7).
fn rocket(scale: f32, density: f32, life: f32) -> Look {
let scale = scale.min(2.0);
Look { r0: 0.25 * scale, r1: 1.2 + 1.6 * scale, density, soot: 0.02, clear: 0.8 + 1.2 * scale, life: life + 250.0 * scale }
Look {
r0: 0.25 * scale,
r1: 1.2 + 1.6 * scale,
density,
soot: 0.02,
clear: 0.8 + 1.2 * scale,
life: life + 250.0 * scale,
}
}
fn drone_look(class: Class, scale: f32) -> Look {
match class {
Class::Drone => Look { r0: 0.4, r1: 1.8, density: 0.15, soot: 0.3, clear: 0.3, life: 250.0 },
Class::Jet => Look { r0: 0.5, r1: 2.5, density: 0.5, soot: 0.25, clear: 1.5, life: 500.0 },
Class::Cruise => Look { r0: 0.6, r1: 3.0, density: 0.6, soot: 0.3, clear: 2.0, life: 600.0 },
Class::Drone => Look {
r0: 0.4,
r1: 1.8,
density: 0.15,
soot: 0.3,
clear: 0.3,
life: 250.0,
},
Class::Jet => Look {
r0: 0.5,
r1: 2.5,
density: 0.5,
soot: 0.25,
clear: 1.5,
life: 500.0,
},
Class::Cruise => Look {
r0: 0.6,
r1: 3.0,
density: 0.6,
soot: 0.3,
clear: 2.0,
life: 600.0,
},
Class::Supersonic => rocket(scale, 0.9, 400.0),
Class::Ballistic => rocket(scale, 1.1, 500.0),
}
@@ -146,11 +191,8 @@ fn style(s: &mut SmokeSegment, l: Look) {
/// Points between a replay trail segment's ends (a segment every `TRAIL_GRID * STEP` ticks).
const TRAIL_GRID: usize = 4;
/// The smoke a recording shows at its tick `t`: trails behind everything that flew, columns over
/// the fires its events lit, billows over its blasts. A pure function of `t` (nothing is kept
/// between calls, so a seek, a pause or a cut shows exactly what playing through would), and it
/// touches no live state. Trail segments sit on a fixed grid of each track's points.
pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSegment> {
/// Trail segments sit on a fixed grid of each recorded track's points.
fn recorded_trails(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSegment> {
use crate::sim::record::{STEP, What};
let tick = t.max(0.0) as u64;
let mut out: Vec<SmokeSegment> = Vec::new();
@@ -162,8 +204,12 @@ pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSeg
Some(drone_look(spec.class, spec.trail_scale()))
}
What::Missile(kind, _) => missile_look(kind),
// A counter-strike leaves the trail of the cruise missile it is (#109).
What::Strike => Some(drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale())),
// Legacy fixtures retain their cruise trail; physical carriers use a rocket trail.
What::StrikeCarrier(_) => missile_look(crate::sim::MissileKind::M48n6),
What::Strike => Some(drone_look(
Class::Cruise,
DroneKind::Kalibr.spec().trail_scale(),
)),
};
let Some(look) = look else { continue };
let life = look.life as f64;
@@ -171,12 +217,32 @@ pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSeg
let lo = (((t - life - tr.first as f64) / stride).floor().max(0.0)) as usize;
let hi = (((t - tr.first as f64) / stride).floor().max(0.0)) as usize;
for g in lo.max(1)..=hi {
let (Some(a), Some(b)) = (tr.sample(rec.origin, (g - 1) * TRAIL_GRID), tr.sample(rec.origin, g * TRAIL_GRID)) else { break };
let (Some(mut a), Some(b)) = (
tr.sample(rec.origin, (g - 1) * TRAIL_GRID),
tr.sample(rec.origin, g * TRAIL_GRID),
) else {
break;
};
let born = tr.first as u64 + (g * TRAIL_GRID) as u64 * STEP as u64;
if born > tick || a.distance(b) >= 400.0 {
if born > tick
|| a.distance(b) >= 400.0
|| (matches!(tr.what, What::StrikeCarrier(_))
&& born < tr.first as u64 + crate::sim::strike::EJECT_TICKS)
{
continue;
}
let mut s = seg(0x2000_0000 | ((n as u32).wrapping_mul(7919) ^ g as u32) & 0x0fff_ffff, a, b, born, 1200);
if matches!(tr.what, What::StrikeCarrier(_)) {
let ignition = tr.first as f64 + crate::sim::strike::EJECT_TICKS as f64;
let segment_start = tr.first as f64 + (g - 1) as f64 * stride;
if segment_start < ignition { a = tr.at(rec.origin, ignition).unwrap_or(b); }
}
let mut s = seg(
0x2000_0000 | ((n as u32).wrapping_mul(7919) ^ g as u32) & 0x0fff_ffff,
a,
b,
born,
1200,
);
style(&mut s, look);
if (tick as f64) < born as f64 + s.life as f64 {
out.push(s);
@@ -188,33 +254,31 @@ pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSeg
let cut = out.len() - MAX_TRAIL;
out.drain(..cut);
}
// Fires, the strongest dozen in full (as the live ones are).
let mut fires = crate::sim::record::replay_fires(rec, t);
fires.sort_by(|a, b| b.size.total_cmp(&a.size).then(a.start.cmp(&b.start)));
for (rank, f) in fires.iter().enumerate() {
let life = f.life as f64;
fire_column(&mut out, 0x1000_0000 | f.key as u32, f.at, f.start as u64, f.size, f.shown && rank < crate::sim::fires::MAX, tick, &|k| {
let (mut flame, mut smoke) = crate::sim::fires::level(k.saturating_sub(f.start as u64) as f64 + f.age_offset as f64, life);
if f.water == Some(true) { flame = 0.0; smoke *= 0.5; }
(flame, smoke)
});
}
// Blasts keep their billows long after the fireball is out.
let blasts: Vec<crate::sim::Blast> = rec
.events
.iter()
.enumerate()
.filter(|(_, e)| e.at as u64 <= tick)
.map(|(k, e)| {
let (size, life) = crate::sim::record::blast_spec(e.kind);
crate::sim::Blast { id: 0x4000_0000 | k as u32, at: e.pos, size, start: e.at as u64, life }
})
.collect();
blast_billows(&mut out, &blasts, tick);
out.truncate(MAX_TOTAL);
out
}
/// A recording's smoke is just another read-only scene view; seeking rebuilds the same segments
/// from its tracks, fire transitions and blasts without consulting the current simulation.
#[cfg(test)]
pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSegment> {
let context = crate::presentation::Context::playback(
crate::presentation::Mode::Replay,
1,
None,
0,
0,
t,
None,
1.0,
DVec3::ZERO,
true,
);
Smoke::default().segments(&Snapshot::at_context(
&context,
crate::scene::Source::Recorded(rec),
))
}
impl Smoke {
fn trail(&mut self, key: (u8, u32), at: DVec3, tick: u64, look: Look) {
let Some(&(from, when)) = self.last.get(&key) else {
@@ -235,37 +299,58 @@ impl Smoke {
}
/// Follows the simulation one tick: new trail segments for what flies, old ones dropped.
pub fn update(&mut self, sim: &Sim) {
let tick = sim.tick;
pub fn update(&mut self, scene: &Snapshot<'_>) {
debug_assert_eq!(
scene.source(),
"live",
"incremental trails are sampled from live poses only"
);
let tick = scene.time().max(0.0) as u64;
if tick < self.last_tick {
self.trails.retain(|t| t.seg.born as u64 <= tick);
self.last.clear();
}
self.last_tick = tick;
for d in &sim.drones {
let spec = d.kind.spec();
self.trail((0, d.id), d.pos, tick, drone_look(spec.class, spec.trail_scale()));
}
for m in &sim.missiles {
if let Some(look) = missile_look(m.kind) {
self.trail((1, m.id), m.pos, tick, look);
let movers = scene.movers();
for mover in &movers {
match mover.kind {
MoverKind::Drone(kind) => {
let spec = kind.spec();
self.trail(
(mover.group, mover.id),
mover.pos,
tick,
drone_look(spec.class, spec.trail_scale()),
);
}
MoverKind::Missile(kind) => {
if let Some(look) = missile_look(kind) {
self.trail((mover.group, mover.id), mover.pos, tick, look);
}
}
MoverKind::Strike {
physical,
engine_lit,
} => {
if engine_lit {
let look = if physical {
rocket(crate::sim::strike::ROUND_SCALE as f32, 0.8, 250.0)
} else {
drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale())
};
self.trail((mover.group, mover.id), mover.pos, tick, look);
}
}
}
}
for f in &sim.strikes.flights {
self.trail((2, f.id), f.pos, tick, drone_look(Class::Cruise, crate::sim::DroneKind::Kalibr.spec().trail_scale()));
}
// Forget what is gone.
if tick % 100 == 0 {
let alive: std::collections::HashSet<(u8, u32)> = sim
.drones
.iter()
.map(|d| (0, d.id))
.chain(sim.missiles.iter().map(|m| (1, m.id)))
.chain(sim.strikes.flights.iter().map(|f| (2, f.id)))
.collect();
let alive: std::collections::HashSet<(u8, u32)> =
movers.iter().map(|m| (m.group, m.id)).collect();
self.last.retain(|k, _| alive.contains(k));
}
self.trails.retain(|t| tick < t.seg.born as u64 + t.seg.life as u64);
self.trails
.retain(|t| tick < t.seg.born as u64 + t.seg.life as u64);
if self.trails.len() > MAX_TRAIL {
let cut = self.trails.len() - MAX_TRAIL;
self.trails.drain(..cut);
@@ -273,17 +358,36 @@ impl Smoke {
}
/// Every segment alive at the simulation's tick: trails, fire columns, blast smoke.
pub fn segments(&self, sim: &Sim) -> Vec<SmokeSegment> {
let tick = sim.tick;
let mut out: Vec<SmokeSegment> = self.trails.iter().map(|t| t.seg.clone()).collect();
// A column over each fire: a puff every 15 ticks that rises, spreads and thins.
for f in &sim.fires.list {
if f.quiet && f.size < 1.0 {
pub fn segments(&self, scene: &Snapshot<'_>) -> Vec<SmokeSegment> {
let tick = scene.time().max(0.0) as u64;
let mut out = match scene.recording() {
Some(rec) => recorded_trails(rec, scene.time()),
None if scene.is_recorded_view() => Vec::new(),
None => self.trails.iter().map(|t| t.seg.clone()).collect(),
};
// The same fire and blast adapters serve live effects and seekable recorded effects.
let mut fires = scene.fires();
fires.sort_by(|a, b| {
b.size()
.total_cmp(&a.size())
.then(a.start().cmp(&b.start()))
});
for (rank, f) in fires.iter().enumerate() {
if f.quiet() && f.size() < 1.0 {
continue;
}
fire_column(&mut out, f.id, f.at, f.start, f.size, f.shown, tick, &|k| f.level(k));
fire_column(
&mut out,
0x1000_0000 | f.key(),
f.at(),
f.start(),
f.size(),
f.shown() && rank < crate::sim::fires::MAX,
tick,
&|k| f.level(k),
);
}
blast_billows(&mut out, &sim.blasts, tick);
blast_billows(&mut out, &scene.smoke_blasts(), tick);
out.truncate(MAX_TOTAL);
out
}
@@ -292,7 +396,16 @@ impl Smoke {
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{DroneKind, MissileKind};
use crate::scene;
use crate::{
presentation::Context,
sim::{DroneKind, MissileKind, Sim},
};
fn live_scene(sim: &Sim) -> Snapshot<'_> {
let ctx = Context::live(1, None, 0, sim.tick, None, DVec3::ZERO);
Snapshot::at_context(&ctx, scene::Source::Live(sim))
}
#[test]
fn replay_smoke_has_trails_and_fire_columns_and_is_a_function_of_time() {
@@ -301,11 +414,27 @@ mod tests {
let mut rec = Recording::blank(160);
for id in 1..=2 {
let x = (id - 1) as f64 * 30.0;
rec.straight(id, What::Drone(DroneKind::Geran3), 0, 160,
DVec3::new(x, 80.0, 0.0), DVec3::new(x, 80.0, 500.0));
rec.straight(
id,
What::Drone(DroneKind::Geran3),
0,
160,
DVec3::new(x, 80.0, 0.0),
DVec3::new(x, 80.0, 500.0),
);
}
assert_eq!(rec.tracks.len(), 2);
rec.events = vec![Event { at: 40, pos: DVec3::new(5.0, 70.0, 5.0), kind: EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: None, sam: None } }];
rec.events = vec![Event {
at: 40,
pos: DVec3::new(5.0, 70.0, 5.0),
kind: EventKind::Hit {
drone: 1,
kind: DroneKind::Geran3,
power: 2,
object: None,
sam: None,
},
}];
let live_state = (sim.tick, sim.fires.list.len());
let t = 130.0;
let a = replay_smoke(&rec, t);
@@ -315,13 +444,60 @@ mod tests {
let _ = replay_smoke(&rec, 10.0);
let _ = replay_smoke(&rec, 155.0);
let b = replay_smoke(&rec, t);
assert_eq!(a.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>(), b.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>());
assert_eq!(
a.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>(),
b.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>()
);
assert!(a.iter().all(|s| s.born <= t));
assert!(replay_smoke(&rec, -5.0).is_empty());
let ctx = Context::playback(
crate::presentation::Mode::Replay,
1,
None,
0,
0,
400.0,
None,
1.0,
DVec3::ZERO,
true,
);
let scene = Snapshot::at_context(&ctx, crate::scene::Source::Recorded(&rec));
assert!(scene.blasts().is_empty(), "the visual flash has expired");
assert_eq!(
scene.smoke_blasts().len(),
1,
"smoke persists on the recording timeline"
);
assert!(replay_smoke(&rec, 400.0).iter().any(|s| s.soot == 0.55));
assert_eq!((sim.tick, sim.fires.list.len()), live_state);
}
#[test]
fn missing_recording_never_falls_back_to_cached_live_trails() {
let ctx = Context::playback(
crate::presentation::Mode::Replay,
2,
None,
0,
900,
40.0,
None,
0.5,
DVec3::ZERO,
true,
);
let scene = Snapshot::at_context(&ctx, scene::Source::Empty);
let mut smoke = Smoke::default();
smoke.trails.push(Trail {
seg: seg(1, DVec3::ZERO, DVec3::Z, 10, 1200),
});
assert!(scene.is_recorded_view());
assert_eq!(scene.time(), 40.0);
assert!(smoke.segments(&scene).is_empty());
}
#[test]
fn live_counter_strike_leaves_a_trail_and_releases_its_source() {
use crate::sim::sites::{LaunchSite, SiteClass};
@@ -330,34 +506,107 @@ mod tests {
let mut sim = Sim::new(11);
let id = 1;
sim.sites.list.push(LaunchSite {
id, side: 0, sector: 0, bearing: 0.0, class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 300.0), range: 300.0, water: false,
stock: 0, planned: 0, alive: true, next_free: 0, offmap: false,
id,
side: 0,
sector: 0,
bearing: 0.0,
class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 300.0),
range: 300.0,
water: false,
stock: 0,
planned: 0,
alive: true,
next_free: 0,
offmap: false,
});
sim.strikes.known.push(Known {
site: id, class: SiteClass::Ramp, obs: Vec::new(),
est: Some(Estimate { pos: DVec2::new(0.0, 300.0), radius: 5.0, fix: true,
bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
launches: 1, last: 0, state: SiteState::Active, aimed: false,
site: id,
class: SiteClass::Ramp,
obs: Vec::new(),
est: Some(Estimate {
pos: DVec2::new(0.0, 300.0),
radius: 5.0,
fix: true,
bearing: 0.0,
bearing_err: 0.01,
origin: DVec2::ZERO,
}),
launches: 1,
last: 0,
state: SiteState::Active,
aimed: false,
});
sim.order_test_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut crate::sim::Out::default()).unwrap();
sim.order_test_strike(
id,
DVec3::new(0.0, 64.0, 0.0),
&mut crate::sim::Out::default(),
)
.unwrap();
let mut smoke = Smoke::default();
sim.tick = 1;
smoke.update(&sim);
smoke.update(&live_scene(&sim));
let from = sim.strikes.flights[0].pos;
sim.tick = 2;
sim.strikes.flights[0].pos += DVec3::Z * 8.0;
smoke.update(&sim);
let segments = smoke.segments(&sim);
assert_eq!(segments.len(), 1, "a live strike must emit the cruise trail also seen in replay");
smoke.update(&live_scene(&sim));
let segments = smoke.segments(&live_scene(&sim));
assert_eq!(
segments.len(),
1,
"a live strike must emit the cruise trail also seen in replay"
);
assert_eq!(segments[0].az, from.z);
assert_eq!(segments[0].bz, from.z + 8.0);
let expected = drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale());
assert_eq!(segments[0].density, expected.density);
// The same sampled poses now represent a physical cold-ejected round.
sim.strikes.flights[0].carrier = Some(99);
let mut smoke = Smoke::default();
sim.tick = 1;
smoke.update(&live_scene(&sim));
sim.tick = 2;
sim.strikes.flights[0].pos += DVec3::Y;
smoke.update(&live_scene(&sim));
assert!(
smoke.segments(&live_scene(&sim)).is_empty(),
"ejection is not rocket exhaust"
);
sim.tick = crate::sim::strike::EJECT_TICKS;
smoke.update(&live_scene(&sim));
sim.tick += 1;
sim.strikes.flights[0].pos += DVec3::Y * 8.0;
smoke.update(&live_scene(&sim));
let segments = smoke.segments(&live_scene(&sim));
assert_eq!(segments.len(), 1);
assert_eq!(
segments[0].soot, 0.02,
"a physical strike uses the rocket style in both sources"
);
assert!(
segments
.iter()
.all(|s| s.born >= crate::sim::strike::EJECT_TICKS as f64)
);
sim.strikes.flights.clear();
sim.tick = 100;
smoke.update(&sim);
assert!(smoke.last.is_empty(), "finished strikes must not leave source bookkeeping behind");
smoke.update(&live_scene(&sim));
assert!(
smoke.last.is_empty(),
"finished strikes must not leave source bookkeeping behind"
);
}
#[test]
fn recorded_physical_strike_trail_starts_at_ignition_not_at_the_muzzle() {
use crate::sim::record::{Recording, What};
let mut rec = Recording::blank(40);
rec.straight(1, What::StrikeCarrier(77), 10, 30, DVec3::ZERO, DVec3::Z * 20.0);
assert!(replay_smoke(&rec, 14.0).is_empty());
let segments = replay_smoke(&rec, 18.0);
assert_eq!(segments.len(), 1);
assert!((segments[0].az - 5.0).abs() < 1e-6);
assert!((segments[0].bz - 8.0).abs() < 1e-6);
}
#[test]
@@ -367,11 +616,22 @@ mod tests {
let pantsir = missile_look(MissileKind::M57e6).unwrap();
assert!(pantsir.r1 < rocket_look.r1);
let mut s = seg(0, DVec3::ZERO, DVec3::ZERO, 0, 0);
for class in [Class::Drone, Class::Jet, Class::Cruise, Class::Supersonic, Class::Ballistic] {
for class in [
Class::Drone,
Class::Jet,
Class::Cruise,
Class::Supersonic,
Class::Ballistic,
] {
style(&mut s, drone_look(class, 1.0));
assert_eq!(s.heat, 0.0);
}
for k in [MissileKind::Pac3, MissileKind::M57e6, MissileKind::M77n6, MissileKind::Amraam] {
for k in [
MissileKind::Pac3,
MissileKind::M57e6,
MissileKind::M77n6,
MissileKind::Amraam,
] {
style(&mut s, missile_look(k).unwrap());
assert_eq!(s.heat, 0.0);
}
+20
View File
@@ -11,6 +11,26 @@ command = "airdef deploy patriot"
[[step]]
command = "airdef deploy s400"
# Exercise the typed inventory through the actual WASM command boundary.
[[step]]
command = "airdef ground-load 2"
expect.error = "Нет живого склада с RM48U рядом (60 блоков)"
[[step]]
command = "airdef deploy depot"
[[step]]
command = "airdef ground-stock 3 2"
expect.feedback = "Sandbox: задан начальный запас склада №3: RM48U 2"
[[step]]
command = "airdef ground-load 2"
expect.feedback = "С-400 №2: загружена RM48U (игровой профиль), ударных 1, ПВО 3; на складе RM48U 1, снятых ракет ПВО 1"
[[step]]
command = "airdef ground-unload 2"
expect.feedback = "С-400 №2: выгружена RM48U; ударных 0, ПВО 4"
[[step]]
command = "airdef wave mix 40 1500"
+9
View File
@@ -51,3 +51,12 @@ runtime закреплённого движка. Используется вре
В CI проверка assets входит в лёгкий build. Wasmtime tier вынесен в ручной workflow
`wasm-contract`, чтобы не компилировать тяжёлый runtime на каждом push слабого общего runner.
## Готовность объёмного дыма (API 26)
`render.smoke-status` разделяет доступность API, включённый режим, принятую отправку этого мода
и готовность smoke/fog пути последнего подготовленного основного кадра. Возвращаются поколение мира
и причина (`awaiting-frame`, `disabled`, `path-unavailable`, `ready`). AirDef убирает обычный дым
только когда выполнены все четыре условия; после смены мира старые сегменты и часы очищаются.
Это подтверждение выбранного пути рендера, а не завершения GPU или видимости каждого сегмента.
Для акустики и capture аналогичное подтверждение этим API не реализовано.
+30
View File
@@ -0,0 +1,30 @@
# Состояние исходных 16 задач
Ветка `kimi-work`, 2 ноября 2026. Issues остаются открытыми по просьбе владельца.
«Реализовано» ниже означает проверенный объём кода, а не закрытие issue и не подтверждение всех платформ.
| Issue | Реализовано | Что остаётся для полной приёмки |
|---|---|---|
| #72 | Upstream Horizon 0.2.97 объединён с форком; сохранена история; локальные тесты и Metal-полигон | Windows/Linux, native HDR, сравнительная производительность |
| #87 | Каноническое SDK-free ядро `airdef-core`, используется модом и сценариями | Дальнейшее отделение текстового/визуального вывода домена от адаптера |
| #88 | Типизированный журнал измеренных переходов; read-only Snapshot для Smoke/Shown; записанные пожары, позы, пуски и зажигание | Перевести оставшиеся model/audio adapters и режиссёра на общий снимок; замер полной 10-минутной записи |
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа | Полный игровой цикл MP4 с отменой/ошибкой энкодера и проверкой хвоста очереди |
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей | Единый источник всех чисел, звуков и Python-регистраций; проверка вариантов комплексов |
| #92 | Authored overrides, проверка ссылок/PNG/границ, manifest, безопасная транзакционная генерация; registry/texture/icon modules | Дальнейшее ручное улучшение контента относится к #115 |
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах | Прослушивание, игровой массовый звук/CPU, акустика реального MP4; точность RT60 пока по допуску 35%, не 15% |
| #102 | Отдельный pinned engine, repo-local packer, build identity, настоящий WASM tier; API26 handshake дыма | Аналогичный статус для других возможностей, максимальные бюджеты и GPU/export tier |
| #104 | Движок вынесен в `chexit/horizon-airdef`, ветка `airdef`; AirDef использует точный gitlink | Отдельная Windows-проверка миграции старого standalone checkout |
| #107 | ПУ оценивается по наблюдениям: обратный курс не выдаёт точную ПУ | Повторная игровая проверка сценариев с маневрирующими целями |
| #110 | Изменения чанков инвалидируют акустические снимки/кэш; включено в pin и проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
| #111 | Вне области расчёта источник переходит на fallback вместо старой стены; проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
| #114 | Навигация учитывает footprint и окончательную authored-геометрию; остановка перед unread frontier; угловые пересечения | Массовая игровая проверка всех новых шасси на сложном рельефе |
| #115 | Три пилота с кадрами до/после, спокойные материалы; authored-проход по боевым и вспомогательным машинам | Крупные планы и точность прототипов ещё промежуточные; остальные летательные аппараты/ракеты, анимации, дальние виды и FPS |
| #116 | Streaming не освобождает busy-guard работающего acoustic worker; проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
| #118 | Ручной пуск из физического С-400 с отдельным RM48U; общие четыре ячейки, конечный склад, обмен/возврат; carrier в записи, холодный выброс и зажигание; фантомное ПВО удалено | Доставка RM48U через ТЗМ, расширение подтверждённых игровых профилей, включая оценку Бука; визуальная приёмка самого пуска |
Для #118 RM48U — явно условный Minecraft-профиль. Существование сочетания опирается на сообщение ведомства,
а игровые параметры не выдаются за реальные. `ground-stock` — команда подготовки sandbox-сценария,
по умолчанию запас нулевой; это не автономное пополнение и не производственная экономика.
Новые находки внешнего ревью и причины отказа от неверных замечаний: [REVIEW-FOLLOWUP-2026-11-02.md](REVIEW-FOLLOWUP-2026-11-02.md).
Картинки и ограничения художественного прохода: [MODEL-PILOTS.md](MODEL-PILOTS.md).
+1 -1
Submodule horizon updated: 2095590807...86b1014a92