diff --git a/README.md b/README.md index 40c2d95..1bf823a 100644 --- a/README.md +++ b/README.md @@ -82,10 +82,23 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает мо самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда. Повторное J закрывает. -Клавиши N, K и J можно переназначить в «Настройки → Моды». +**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто +(хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**: +- **карта налёта** — вид сверху: комплексы и их зоны, объекты, треки целей (красные), ложных целей (серые) и + перехватчиков (жёлтые), сбития (x), прилёты, шкала времени с событиями; время идёт само, колесо мыши перематывает; +- **повтор момента** — клик по событию в списке: «призраки» дронов и ракет снова летят в мире, камера идёт за + целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется; +- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — скорость (×0.5–×16); +- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения + объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты. + +Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. R — выход. + +Клавиши N, K, J и R можно переназначить в «Настройки → Моды». Команды: - `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»); +- `/airdef replay [map|full|reel|stop]` — повтор последнего налёта; - `/airdef raid` — налёт, настроенный в меню; `/airdef target here` — отметить объект под ногами; `/airdef repair` — ремонт; - `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`; - `/airdef deploy ` — поставить комплекс в 8 блоках перед собой; diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index 6a8622f..4d05fb4 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -15,6 +15,7 @@ use horizon_mod_sdk::{ mod monitor; mod panel; mod radar; +mod replay; mod sim; mod wave; use sim::{Class, DroneKind, Ground, Out, Sam, SamKind, Sim}; @@ -53,6 +54,8 @@ struct AirDef { grid_ids: Vec, /// The raid the wave menu orders. wave: wave::WaveConfig, + /// A replay playing (it takes the screen and the mouse wheel). + replay: Option, /// The menu's page while it is open. menu: Option, /// Where the player is, for the sounds' delay and far variants. @@ -81,6 +84,8 @@ enum Page { WaveGo, /// Fire, repair, effects, damage. More, + /// The last raid's events and its replays. + Replays, } const MENU_KINDS: u32 = 1; @@ -99,6 +104,11 @@ const BTN_AIM: u32 = 33; const BTN_LAUNCH: u32 = 34; const BTN_NEXT: u32 = 35; const BTN_MORE: u32 = 17; +const BTN_REPLAYS: u32 = 18; +const REPLAY_EVENTS: u32 = 3; +const BTN_MAP: u32 = 40; +const BTN_FULL: u32 = 41; +const BTN_REEL: u32 = 42; const BTN_CLASS: u32 = 100; const BTN_ALL: u32 = 120; const BTN_DEFAULT: u32 = 121; @@ -319,8 +329,8 @@ impl AirDef { fn draw_hud(&mut self, player: DVec3, yaw: f32) { let air: Vec<&sim::Drone> = self.sim.drones.iter().filter(|d| d.alive()).collect(); - // The command post's grid covers the screen: the other panels wait under it. - if self.grid || (air.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) { + // The command post's grid and replays cover the screen: the other panels wait under them. + if self.grid || self.replay.is_some() || (air.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) { if self.hud_shown { hud::clear(); render::clear_corner(); @@ -402,6 +412,39 @@ impl AirDef { } impl AirDef { + /// Plays the last recorded raid: "map", "full", "reel" or (with `event`) a clip. + fn start_replay(&mut self, what: &str, event: Option) -> Result<(), String> { + let n = self.sim.replays.len(); + if n == 0 { + return Err("Повторов пока нет: запишется первый же налёт (когда небо очистится)".into()); + } + let rec = &self.sim.replays[n - 1]; + let mode = match (what, event) { + (_, Some(i)) if i < rec.events.len() => replay::Player::event_clip(rec, i), + ("full", _) => replay::Mode::Full, + ("reel", _) => { + let list = replay::reel(rec); + if list.is_empty() { + return Err("В этом налёте нечего показать".into()); + } + replay::Mode::Clips { list, at: 0, reel: true } + } + _ => replay::Mode::Map, + }; + self.replay = Some(replay::Player::new(n - 1, mode, &self.sim)); + self.grid = false; + input::claim_wheel(true); + Ok(()) + } + + fn stop_replay(&mut self) { + self.replay = None; + input::claim_wheel(false); + render::set_hud(&[]); + render::set_views(&[]); + self.monitor_shown = false; + } + /// What a raid strikes: the marked objects, else where the player stands. fn objects(&self, player: DVec3) -> Vec { let live: Vec = self @@ -487,8 +530,31 @@ impl AirDef { let _ = &self.monitor; widgets.push(Widget::Button(ButtonWidget { id: BTN_GRID, label: "Командный пункт: все комплексы (J)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_WAVE, label: "Налёт: состав и запуск…".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_REPLAYS, label: "Повторы…".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() })); } + Page::Replays => { + match self.sim.replays.last() { + Some(rec) => { + let kills = rec.events.iter().filter(|e| matches!(e.kind, sim::record::EventKind::Kill { .. })).count(); + title = format!("Налёт №{}: {} событий, сбито {kills} — клик: повтор момента", rec.number, rec.events.len()); + let rows = (0..rec.events.len().min(200)).map(|i| replay::row(rec, i)).collect(); + widgets.push(Widget::List(ListWidget { id: REPLAY_EVENTS, rows, selected: None })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_FULL, label: "Полный повтор".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) })); + } + None => { + title = "Повторы".into(); + widgets.push(Widget::Text(horizon_mod_sdk::ui::TextWidget { + id: 0, + text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(), + color: 0, + })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); + } + } + } Page::More => { title = "AirDef — управление".to_string(); widgets.push(Widget::Button(ButtonWidget { @@ -561,7 +627,7 @@ impl AirDef { } } -const HELP: &str = "/airdef menu | monitor | grid | raid | repair | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | shader on|off | hold on|off | roles [комплекс классы] | stats"; +const HELP: &str = "/airdef menu | monitor | grid | replay [map|full|reel|stop] | raid | repair | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | shader on|off | hold on|off | roles [комплекс классы] | stats"; impl Mod for AirDef { fn init() -> Result<(Self, Registration), String> { @@ -576,6 +642,7 @@ impl Mod for AirDef { grid: false, grid_ids: Vec::new(), wave: wave::WaveConfig::default(), + replay: None, menu: None, listener: DVec3::ZERO, pending: Vec::new(), @@ -583,6 +650,7 @@ impl Mod for AirDef { let _ = input::register_key("menu", "Меню AirDef", "key.keyboard.n"); let _ = input::register_key("monitor", "Монитор ПВО: следующий комплекс", "key.keyboard.k"); let _ = input::register_key("grid", "Командный пункт: все комплексы", "key.keyboard.j"); + let _ = input::register_key("replay", "Повтор налёта: карта / выход", "key.keyboard.r"); me.load(); input::claim_items(&ITEMS.map(String::from)); render::set_post(include_str!("../shaders/effects.wgsl")); @@ -598,6 +666,20 @@ impl Mod for AirDef { Event::KeyDown(k) if k == "menu" => self.open_menu(Page::Main), Event::KeyDown(k) if k == "monitor" => self.cycle_monitor(), Event::KeyDown(k) if k == "grid" => self.grid = !self.grid, + Event::KeyDown(k) if k == "replay" => { + if self.replay.is_some() { + self.stop_replay(); + } else if let Err(e) = self.start_replay("map", None) { + say(&e); + } + } + Event::Wheel(w) => { + if let Some(r) = &mut self.replay + && let Some(rec) = self.sim.replays.get(r.rec) + { + r.wheel(w, rec); + } + } _ => {} } } @@ -610,10 +692,24 @@ impl Mod for AirDef { if !wanted.is_empty() { render::query_ground(&wanted); } + if let Some(mut r) = self.replay.take() { + r.tick(&self.sim, self.listener, &mut out); + if r.done { + self.replay = Some(r); + self.stop_replay(); + } else { + self.replay = Some(r); + } + } self.emit(out); self.draw_hud(DVec3::new(p.x, p.y, p.z), p.yaw); - // The monitors and the cameras they show. - if self.grid { + // The replay takes the screen; else the monitors and the cameras they show. + if let Some(r) = &self.replay { + let size = render::gui_size(); + render::set_hud(&r.hud(&self.sim, size)); + render::set_views(&r.views(size)); + self.monitor_shown = true; + } else if self.grid { let stale = self.grid_ids.iter().any(|id| !self.sim.sams.iter().any(|s| s.id == *id)); if self.sim.tick % 40 == 0 || stale || self.grid_ids.len() < self.sim.sams.len().min(8) { self.pick_grid(); @@ -712,6 +808,30 @@ impl Mod for AirDef { self.open_menu(Page::Wave); return; } + (Page::Main, BTN_REPLAYS) => { + self.open_menu(Page::Replays); + return; + } + (Page::Replays, REPLAY_EVENTS | BTN_MAP | BTN_FULL | BTN_REEL) => { + let r = match id { + REPLAY_EVENTS => self.start_replay("clip", Some(row as usize)), + BTN_FULL => self.start_replay("full", None), + BTN_REEL => self.start_replay("reel", None), + _ => self.start_replay("map", None), + }; + match r { + Ok(()) => { + self.menu = None; + ui::close_screen(); + } + Err(e) => say(&e), + } + return; + } + (Page::Replays, BTN_BACK) => { + self.open_menu(Page::Main); + return; + } (Page::Main, BTN_MORE) => { self.open_menu(Page::More); return; @@ -809,6 +929,13 @@ impl Mod for AirDef { } None } + ["replay", rest @ ..] => { + match rest.first().copied().unwrap_or("map") { + "stop" => self.stop_replay(), + what => self.start_replay(what, None)?, + } + None + } ["raid"] => { self.launch_wave(&mut out)?; None diff --git a/airdef-mod/src/replay.rs b/airdef-mod/src/replay.rs new file mode 100644 index 0000000..5a6e0fa --- /dev/null +++ b/airdef-mod/src/replay.rs @@ -0,0 +1,629 @@ +//! Replays of recorded raids: the raid's map (every track over time), a clip +//! of any event, the whole raid, and a highlight reel of the best moments. +//! Clips are filmed: ghosts of the drones and interceptors fly again in the +//! world and a director's camera (a full-screen camera view) follows them — +//! behind the drone, then behind the interceptor or from the side — slowing +//! time round the moment itself. +use crate::panel::distance; +use crate::sim::record::{EventKind, Recording, What}; +use crate::sim::{Class, DroneKind, Out, Sim}; +use glam::DVec3; +use horizon_mod_sdk::render::{CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape}; + +/// Ghost models' ids, clear of the live ones. +const GHOSTS: u32 = 0x5000_0000; +/// The camera view's id (a new one each cut, so the game doesn't sweep between shots). +const VIEW: u32 = 0x7700_0000; + +pub enum Mode { + /// The raid from above, its tracks drawn as time runs (the wheel scrubs). + Map, + /// The whole raid filmed, the director choosing what to follow (the wheel sets the speed). + Full, + /// Clips one after another (the wheel skips): one event, or the highlight reel. + Clips { list: Vec, at: usize, reel: bool }, +} + +pub struct Clip { + pub event: usize, + from: f64, + to: f64, +} + +pub struct Player { + /// Which of the sim's recordings. + pub rec: usize, + pub mode: Mode, + t: f64, + speed: f64, + /// The director's current shot (event, shot) and the view id it films with. + shot: (usize, u8), + view: u32, + /// Ticks of black left after a cut, of the title card left. + fade: u32, + card: u32, + /// The camera where an interceptor met its target: it stays there after. + held: Option, + /// The eye this tick (sounds are heard from it). + eye: DVec3, + look: DVec3, + fov: f32, + /// The last tick whose events made their sounds. + heard: f64, + pub done: bool, +} + +fn fill(x: f32, y: f32, w: f32, h: f32, color: u32) -> Shape { + Shape::Fill(FillShape { rect: Rect { x, y, w, h }, color }) +} +fn text(t: impl Into, x: f32, y: f32, color: u32, centered: bool) -> Shape { + Shape::Text(TextShape { text: t.into(), at: Point { x, y }, color, centered, shadow: true }) +} +fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = (dx * dx + dy * dy).sqrt().max(0.01); + let (nx, ny) = (-dy / len * w * 0.5, dx / len * w * 0.5); + let p = |x: f32, y: f32| Point { x, y }; + Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color }) +} +fn clock(ticks: f64) -> String { + let s = (ticks / 20.0).max(0.0); + format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0) +} + +/// What an event was, in a line. +pub fn title(rec: &Recording, i: usize) -> String { + let e = &rec.events[i]; + match e.kind { + EventKind::Kill { kind, sam_kind, sam_index, missile, .. } => { + let how = if missile.is_some() { "ракетой" } else { "огнём пушек" }; + format!("{} №{} сбивает «{}» {how}", sam_kind.name(), sam_index + 1, kind.spec().name) + } + EventKind::Hit { kind, object: Some(o), .. } => format!("«{}» поражает объект №{}", kind.spec().name, o + 1), + EventKind::Hit { kind, sam: Some((sk, si)), .. } => format!("«{}» бьёт по {} №{}", kind.spec().name, sk.name(), si + 1), + EventKind::Hit { kind, .. } => format!("Прилёт: «{}»", kind.spec().name), + EventKind::SamLost { kind, index, .. } => format!("{} №{} уничтожен", kind.name(), index + 1), + EventKind::Split { .. } => "«Орешник»: разделение боевых блоков".into(), + } +} + +/// A short line for the event list: its time and what it was. +pub fn row(rec: &Recording, i: usize) -> String { + let e = &rec.events[i]; + let what = match e.kind { + EventKind::Kill { kind, sam_kind, sam_index, missile, .. } => { + format!("{}-{} > {}{}", sam_kind.name(), sam_index + 1, kind.spec().name, if missile.is_none() { " (пушки)" } else { "" }) + } + EventKind::Hit { kind, object: Some(o), .. } => format!("{} > объект {}", kind.spec().name, o + 1), + EventKind::Hit { kind, sam: Some((sk, si)), .. } => format!("{} > {}-{}", kind.spec().name, sk.name(), si + 1), + EventKind::Hit { kind, .. } => format!("{}: прилёт", kind.spec().name), + EventKind::SamLost { kind, index, .. } => format!("{}-{} уничтожен", kind.name(), index + 1), + EventKind::Split { .. } => "Орешник: разделение".into(), + }; + format!("{} {what}", clock(e.at as f64)) +} + +/// How worth watching an event is: the reel takes the best. +fn interest(rec: &Recording, i: usize) -> f64 { + let e = &rec.events[i]; + match e.kind { + EventKind::Kill { kind, missile, .. } => { + let spec = kind.spec(); + let class = match spec.class { + Class::Ballistic => 10.0, + Class::Supersonic => 7.0, + Class::Cruise => 5.0, + Class::Jet => 4.0, + Class::Drone => 2.0, + }; + let rare = match kind { + DroneKind::Kinzhal | DroneKind::Oreshnik | DroneKind::Zircon => 4.0, + DroneKind::OreshnikSub => -6.0, + _ => 0.0, + }; + // A kill close to what it was going for. + let close = rec.objects.iter().chain(rec.sams.iter().map(|s| &s.2)).any(|o| o.distance(e.pos) < 40.0); + class + rare + if spec.decoy { -3.0 } else { 0.0 } + if missile.is_none() { 1.0 } else { 0.0 } + if close { 3.0 } else { 0.0 } + } + EventKind::Hit { power, object, sam, .. } => { + power as f64 * 1.5 + if object.is_some() { 6.0 } else if sam.is_some() { 5.0 } else { 0.0 } + } + EventKind::SamLost { .. } => 12.0, + EventKind::Split { drone } => { + // The bus's split, not each block's. + let first = rec.events.iter().position(|o| matches!(o.kind, EventKind::Split { .. })); + if first == Some(i) || rec.track(drone).is_some_and(|t| t.what == What::Drone(DroneKind::Oreshnik)) { 11.0 } else { 0.0 } + } + } +} + +/// The clip of event `i`: from a while before it to a little after. +fn clip(rec: &Recording, i: usize) -> Clip { + let at = rec.events[i].at as f64; + let (before, after) = match rec.events[i].kind { + EventKind::Kill { .. } => (140.0, 50.0), + EventKind::Hit { .. } => (160.0, 60.0), + EventKind::SamLost { .. } => (80.0, 90.0), + EventKind::Split { .. } => (40.0, 170.0), + }; + Clip { event: i, from: (at - before).max(0.0), to: (at + after).min(rec.len as f64) } +} + +/// The best moments, a few seconds apart, in order. +pub fn reel(rec: &Recording) -> Vec { + let mut best: Vec<(f64, usize)> = (0..rec.events.len()).map(|i| (interest(rec, i), i)).filter(|b| b.0 >= 2.0).collect(); + best.sort_by(|a, b| b.0.total_cmp(&a.0)); + let mut chosen: Vec = Vec::new(); + for (_, i) in best { + if chosen.len() >= 8 { + break; + } + let at = rec.events[i].at as i64; + if chosen.iter().all(|&c| (rec.events[c].at as i64 - at).abs() > 90) { + chosen.push(i); + } + } + chosen.sort_by_key(|&i| rec.events[i].at); + chosen.into_iter().map(|i| clip(rec, i)).collect() +} + +impl Player { + pub fn new(rec: usize, mode: Mode, sim: &Sim) -> Self { + let start = match &mode { + Mode::Clips { list, .. } => list.first().map_or(0.0, |c| c.from), + _ => 0.0, + }; + let reel = matches!(mode, Mode::Clips { reel: true, .. }); + let speed = match mode { + Mode::Map => 8.0, + Mode::Full => 2.0, + Mode::Clips { .. } => 1.0, + }; + let _ = sim; + Player { + rec, + mode, + t: start, + speed, + shot: (usize::MAX, 0), + view: VIEW, + fade: 0, + card: if reel { 50 } else { 0 }, + held: None, + eye: DVec3::ZERO, + look: DVec3::NEG_Z, + fov: 50.0, + heard: start, + done: false, + } + } + + /// The wheel: scrubs the map, sets the full replay's speed, skips clips. + pub fn wheel(&mut self, steps: f32, rec: &Recording) { + match &mut self.mode { + Mode::Map => self.t = (self.t - steps as f64 * 60.0).clamp(0.0, rec.len as f64), + Mode::Full => { + const SPEEDS: [f64; 6] = [0.5, 1.0, 2.0, 4.0, 8.0, 16.0]; + let i = SPEEDS.iter().position(|s| *s >= self.speed).unwrap_or(2) as i32; + let j = (i - steps.signum() as i32).clamp(0, SPEEDS.len() as i32 - 1); + self.speed = SPEEDS[j as usize]; + } + Mode::Clips { list, at, reel } => { + let next = (*at as i32 - steps.signum() as i32).clamp(0, list.len() as i32 - 1) as usize; + if next != *at { + *at = next; + self.t = list[next].from; + self.heard = self.t; + self.fade = 6; + self.card = if *reel { 50 } else { 0 }; + } + } + } + } + + /// One tick: time runs, the ghosts fly, the director films. Models and sounds go to `out`. + pub fn tick(&mut self, sim: &Sim, listener: DVec3, out: &mut Out) { + let Some(rec) = sim.replays.get(self.rec) else { + self.done = true; + return; + }; + self.fade = self.fade.saturating_sub(1); + if self.card > 0 { + self.card -= 1; + } + // Time: slowed round the moment in clips, held still while a title card shows. + let mut speed = self.speed; + if let Mode::Clips { list, at, .. } = &self.mode { + let te = rec.events[list[*at].event].at as f64; + if (te - 14.0..te + 18.0).contains(&self.t) { + speed = 0.3; + } + if self.card > 25 { + speed = 0.0; + } + } + self.t += speed; + match &mut self.mode { + Mode::Map | Mode::Full => { + if self.t >= rec.len as f64 { + self.t = rec.len as f64; + if matches!(self.mode, Mode::Full) { + self.done = true; + } + } + } + Mode::Clips { list, at, reel } => { + if self.t >= list[*at].to { + if *at + 1 < list.len() { + *at += 1; + self.t = list[*at].from; + self.heard = self.t; + self.fade = 6; + self.card = if *reel { 50 } else { 0 }; + } else { + self.done = true; + } + } + } + } + if matches!(self.mode, Mode::Map) { + return; + } + sim.draw_ghosts(rec, self.t, GHOSTS, out); + self.direct(rec); + // Sounds as the camera hears them: moved so the player stands where the camera is. + let heard = |p: DVec3| listener + (p - self.eye); + for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) { + let event = match e.kind { + EventKind::Kill { .. } => "airdef:blast.air", + EventKind::Hit { power, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][(power as usize).min(4)], + EventKind::SamLost { .. } => "airdef:blast.big", + EventKind::Split { .. } => "airdef:boom.sonic", + }; + out.sound(event, heard(e.pos), 1.0, 1.0); + } + for tr in rec.tracks.iter().filter(|tr| (self.heard..self.t).contains(&(tr.first as f64))) { + if let What::Missile(kind, _) = tr.what + && let Some(p) = tr.at(rec.origin, tr.first as f64) + { + out.sound(kind.launch_sound(), heard(p), 1.0, 1.0); + } + } + self.heard = self.t; + } + + /// The event the camera films now, and how it shoots it: (eye, look, fov, shot). + fn shoot(&mut self, rec: &Recording, i: usize) -> (DVec3, DVec3, f32, u8) { + let e = rec.events[i]; + let t = self.t; + let te = e.at as f64; + let o = rec.origin; + let chase = |id: u32, back: f64, up: f64| -> Option<(DVec3, DVec3)> { + let tr = rec.track(id)?; + let p = tr.at(o, t)?; + let d = tr.dir(o, t); + Some((p - d * back + DVec3::Y * up, p + d * 10.0)) + }; + let side = |at: DVec3, from: DVec3, dist: f64| { + let across = DVec3::new(-(at - from).z, 0.0, (at - from).x).normalize_or(DVec3::X); + at + across * dist + DVec3::Y * dist * 0.18 + }; + match e.kind { + EventKind::Kill { drone, missile, sam, .. } => { + let target = rec.track(drone).and_then(|tr| tr.at(o, t)).unwrap_or(e.pos); + if t < te - 40.0 { + if let Some((eye, look)) = chase(drone, 12.0, 4.0) { + return (eye, look, 55.0, 0); + } + } + match missile.and_then(|m| rec.track(m)) { + Some(mt) => { + // Behind the interceptor until it meets the target, then where it was. + if t < te && let Some(p) = mt.at(o, t) { + let eye = p - mt.dir(o, t) * 9.0 + DVec3::Y * 1.5; + self.held = Some(eye); + return (eye, target, 50.0, 1); + } + let eye = self.held.unwrap_or_else(|| side(e.pos, o, 40.0)); + (eye, target.lerp(e.pos, 0.5), 50.0, 1) + } + None => { + // A gun kill, from the gun. + let at = rec.sam(sam).map_or(e.pos + DVec3::Y * 20.0, |s| s.1 + DVec3::Y * 4.0); + let dist = target.distance(at).max(1.0); + let fov = (2.0 * (10.0 / dist).atan()).to_degrees().clamp(6.0, 60.0) as f32; + (at, target, fov, 1) + } + } + } + EventKind::Hit { drone, .. } => { + if t < te - 50.0 { + if let Some((eye, look)) = chase(drone, 12.0, 4.0) { + return (eye, look, 55.0, 0); + } + } + let from = rec.track(drone).and_then(|tr| tr.at(o, te - 60.0)).unwrap_or(o); + let eye = side(e.pos, from, 55.0); + let look = rec.track(drone).and_then(|tr| tr.at(o, t)).filter(|_| t < te).unwrap_or(e.pos); + (eye, look, 50.0, 1) + } + EventKind::SamLost { .. } => (side(e.pos, o + DVec3::new(300.0, 0.0, 0.0), 45.0), e.pos, 50.0, 0), + EventKind::Split { .. } => { + let ground = DVec3::new(e.pos.x, o.y, e.pos.z); + let eye = ground + DVec3::new(170.0, 8.0, 40.0); + let k = ((t - te) / 170.0).clamp(0.0, 1.0); + (eye, e.pos.lerp(ground, k * 0.9), 60.0, 0) + } + } + } + + /// Chooses the shot and moves the camera; a new shot is a cut. + fn direct(&mut self, rec: &Recording) { + let focus = match &self.mode { + Mode::Clips { list, at, .. } => Some(list[*at].event), + // The full replay follows what comes next: the next event within 6 s, else the drone + // nearest its target. + Mode::Full => rec + .events + .iter() + .position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64))) + .or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }), + Mode::Map => None, + }; + let (eye, look, fov, shot) = match focus { + Some(i) => { + let s = self.shoot(rec, i); + (s.0, s.1, s.2, (i, s.3)) + } + None => { + // The drone closest to where it is going. + let o = rec.origin; + let lead = rec + .tracks + .iter() + .filter(|tr| matches!(tr.what, What::Drone(_)) && tr.fell.is_none_or(|f| f as f64 > self.t)) + .filter_map(|tr| tr.at(o, self.t).map(|p| (p, tr))) + .min_by(|a, b| a.0.distance(o).total_cmp(&b.0.distance(o))); + match lead { + Some((p, tr)) => { + let d = tr.dir(o, self.t); + (p - d * 14.0 + DVec3::Y * 5.0, p + d * 10.0, 55.0, (usize::MAX, (tr.id % 251) as u8)) + } + None => (o + DVec3::new(60.0, 30.0, 60.0), o, 60.0, (usize::MAX, 0)), + } + } + }; + if shot != self.shot { + self.shot = shot; + self.view = self.view.wrapping_add(1).max(VIEW); + self.held = None; + self.fade = self.fade.max(3); + } + self.eye = eye; + self.look = look; + self.fov = fov; + } + + /// The camera the game renders for the replay. + pub fn views(&self, (gw, gh): (f32, f32)) -> Vec { + if matches!(self.mode, Mode::Map) { + return Vec::new(); + } + let d = (self.look - self.eye).normalize_or(DVec3::NEG_Z); + let yaw = (-d.x).atan2(d.z).to_degrees() as f32; + let pitch = (-d.y).asin().to_degrees() as f32; + let width = 1280u32; + let height = ((width as f32) * gh / gw.max(1.0)) as u32; + vec![CameraView { id: self.view, x: self.eye.x, y: self.eye.y, z: self.eye.z, yaw, pitch, fov: self.fov, width, height: height.clamp(240, 1080) }] + } + + /// The replay's screen: the film with its titles, or the map. + pub fn hud(&self, sim: &Sim, (gw, gh): (f32, f32)) -> Vec { + let Some(rec) = sim.replays.get(self.rec) else { return Vec::new() }; + if matches!(self.mode, Mode::Map) { + return self.map(rec, gw, gh); + } + let mut s = vec![fill(0.0, 0.0, gw, gh, 0xFF000000)]; + s.push(Shape::View(ViewShape { view: self.view, rect: Rect { x: 0.0, y: 0.0, w: gw, h: gh }, mode: 0 })); + // Letterbox, the recording's marks. + let bar = (gh * 0.09).round(); + s.push(fill(0.0, 0.0, gw, bar, 0xFF000000)); + s.push(fill(0.0, gh - bar, gw, bar, 0xFF000000)); + let blink = (sim.tick / 10) % 2 == 0; + s.push(fill(8.0, bar / 2.0 - 3.0, 6.0, 6.0, if blink { 0xFFFF2020 } else { 0x60FF2020 })); + let what = match &self.mode { + Mode::Full => "ПОЛНЫЙ ПОВТОР".to_string(), + Mode::Clips { reel: true, at, list } => format!("ЛУЧШЕЕ · {}/{}", at + 1, list.len()), + _ => "ПОВТОР".to_string(), + }; + let head = format!("{what} · налёт №{}", rec.number); + let head_w = horizon_mod_sdk::render::text_width(&head); + s.push(text(head, 18.0, bar / 2.0 - 4.0, 0xFFFFFFFF, false)); + let speed = if let Mode::Clips { list, at, .. } = &self.mode { + let te = rec.events[list[*at].event].at as f64; + if (te - 14.0..te + 18.0).contains(&self.t) { 0.3 } else { 1.0 } + } else { + self.speed + }; + let time = format!("{} / {} ×{}", clock(self.t), clock(rec.len as f64), speed); + let tw = horizon_mod_sdk::render::text_width(&time); + s.push(text(time, gw - 8.0 - tw, bar / 2.0 - 4.0, 0xFFC0C0C0, false)); + // The controls between them, where they fit. + let hint = "колесо: ".to_string() + match self.mode { Mode::Full => "скорость", _ => "дальше / назад" } + " · R: выход"; + let hw = horizon_mod_sdk::render::text_width(&hint); + let (left, right) = (18.0 + head_w + 12.0, gw - 8.0 - tw - 12.0); + if right - left >= hw { + s.push(text(hint, left + (right - left - hw) / 2.0, bar / 2.0 - 4.0, 0x80FFFFFF, false)); + } + // Caption: what is happening. + let caption = match &self.mode { + Mode::Clips { list, at, .. } => Some(list[*at].event), + _ => (self.shot.0 != usize::MAX).then_some(self.shot.0), + }; + if let Some(i) = caption.filter(|&i| i < rec.events.len()) { + let e = &rec.events[i]; + s.push(text(title(rec, i), gw / 2.0, gh - bar + 4.0, 0xFFFFFFFF, true)); + let detail = match e.kind { + EventKind::Kill { sam, .. } => rec + .sam(sam) + .map(|(_, p)| format!("высота {:.0} м · {} от комплекса", e.pos.y - p.y, distance(e.pos.distance(p)))) + .unwrap_or_default(), + EventKind::Hit { power, .. } => format!("сила взрыва {}", ["хлопок", "средний", "сильный", "тяжёлый", "мощнейший"][(power as usize).min(4)]), + _ => String::new(), + }; + s.push(text(detail, gw / 2.0, gh - bar + 15.0, 0xFFB0B0B0, true)); + } + // Title card of a reel's moment. + if self.card > 0 && let Mode::Clips { list, at, .. } = &self.mode { + let a = ((self.card.min(15) as f32 / 15.0) * 255.0) as u32; + s.push(fill(0.0, gh / 2.0 - 22.0, gw, 44.0, (a.min(0xC0) << 24) | 0x000000)); + s.push(text(format!("МОМЕНТ {} — {}", at + 1, clock(rec.events[list[*at].event].at as f64)), gw / 2.0, gh / 2.0 - 14.0, (a << 24) | 0xFFD040, true)); + s.push(text(title(rec, list[*at].event), gw / 2.0, gh / 2.0 + 2.0, (a << 24) | 0xFFFFFF, true)); + } + if self.fade > 0 { + let a = (self.fade.min(6) * 42) as u32; + s.push(fill(0.0, 0.0, gw, gh, a << 24)); + } + s + } + + /// The raid from above: systems and their reach, objects, every track up to now, the events + /// so far, and a time line. + fn map(&self, rec: &Recording, gw: f32, gh: f32) -> Vec { + let mut s = vec![fill(0.0, 0.0, gw, gh, 0xF0060A08)]; + let o = rec.origin; + // The area: everything that flew, but not far beyond the systems. + let mut lo = (f64::MAX, f64::MAX); + let mut hi = (f64::MIN, f64::MIN); + let mut grow = |p: DVec3| { + lo = (lo.0.min(p.x), lo.1.min(p.z)); + hi = (hi.0.max(p.x), hi.1.max(p.z)); + }; + for tr in &rec.tracks { + if let What::Drone(k) = tr.what + && k.spec().ballistic.is_some() + { + continue; + } + for p in tr.path(o, 20, rec.len as f64) { + grow(p); + } + } + for sam in &rec.sams { + grow(sam.2 - DVec3::splat(60.0)); + grow(sam.2 + DVec3::splat(60.0)); + } + for p in &rec.objects { + grow(*p); + } + if lo.0 > hi.0 { + lo = (o.x - 200.0, o.z - 200.0); + hi = (o.x + 200.0, o.z + 200.0); + } + let (top, bottom) = (20.0f32, 34.0f32); + let (aw, ah) = (gw - 16.0, gh - top - bottom); + let k = (aw as f64 / (hi.0 - lo.0).max(1.0)).min(ah as f64 / (hi.1 - lo.1).max(1.0)); + let cx = 8.0 + (aw as f64 - (hi.0 - lo.0) * k) / 2.0; + let cy = top as f64 + (ah as f64 - (hi.1 - lo.1) * k) / 2.0; + let at = |p: DVec3| ((cx + (p.x - lo.0) * k) as f32, (cy + (p.z - lo.1) * k) as f32); + let inside = |(x, y): (f32, f32)| x > 0.0 && y > top - 4.0 && x < gw && y < gh - bottom + 4.0; + // Systems' reach (a few), positions. + let many = rec.sams.len() > 12; + for (_, kind, p) in &rec.sams { + let (x, y) = at(*p); + if !many { + let r = (kind.range() * k) as f32; + let seg = 24; + for i in 0..seg { + let a0 = i as f32 / seg as f32 * std::f32::consts::TAU; + let a1 = (i + 1) as f32 / seg as f32 * std::f32::consts::TAU; + let q = |a: f32| (x + a.sin() * r, y - a.cos() * r); + if inside(q(a0)) && inside(q(a1)) { + s.push(line(q(a0), q(a1), 1.0, 0x5040A0FF)); + } + } + } + s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFF40A0FF)); + } + for p in &rec.objects { + let (x, y) = at(*p); + s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFFFFF)); + } + // Tracks up to now: a budget of segments shared out. + let n = rec.tracks.len().max(1); + let per = (640 / n).clamp(2, 14); + for tr in &rec.tracks { + let (color, head) = match tr.what { + What::Drone(kind) if kind.spec().decoy => (0x70A0A0A0, 0xFFC0C0C0), + What::Drone(_) => (0x90FF4040, 0xFFFF6060), + What::Missile(..) => (0x90FFD040, 0xFFFFE070), + }; + let pts = tr.path(o, 1, self.t); + if pts.len() < 2 { + continue; + } + let every = pts.len().div_ceil(per).max(1); + let mut prev = at(pts[0]); + for (i, p) in pts.iter().enumerate().skip(1) { + if i % every != 0 && i != pts.len() - 1 { + continue; + } + let q = at(*p); + if inside(prev) && inside(q) { + s.push(line(prev, q, 1.0, color)); + } + prev = q; + } + // Its head while it flies. + if (self.t as u32) < tr.last() && tr.fell.is_none_or(|f| (f as f64) > self.t) && inside(prev) { + s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head)); + } + } + // Events so far. + for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) { + let (x, y) = at(e.pos); + if !inside((x, y)) { + continue; + } + match e.kind { + EventKind::Kill { .. } => { + s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040)); + s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040)); + } + EventKind::Hit { power, .. } => { + let r = 2.0 + power as f32; + s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020)); + } + EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)), + EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)), + } + } + // Header, legend, time line. + let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count(); + let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count(); + s.push(text(format!("КАРТА НАЛЁТА №{} · {} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t)), 8.0, 6.0, 0xFF9FE0FF, false)); + s.push(text("красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · ■ прилёт · колесо: время · R выход", 8.0, gh - 12.0, 0x90FFFFFF, false)); + let (tx, ty, tw) = (8.0, gh - bottom + 6.0, gw - 16.0); + s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF)); + let len = rec.len.max(1) as f32; + for e in &rec.events { + let x = tx + tw * e.at as f32 / len; + let c = match e.kind { + EventKind::Kill { .. } => 0xFFFFE040, + EventKind::Hit { .. } => 0xFFFF3020, + EventKind::SamLost { .. } => 0xFFFF00FF, + EventKind::Split { .. } => 0xFFFF9020, + }; + s.push(fill(x, ty - 2.0, 1.0, 7.0, c)); + } + s.push(fill(tx + tw * (self.t as f32 / len) - 1.0, ty - 4.0, 2.0, 11.0, 0xFFFFFFFF)); + s.truncate(1024); + s + } +} + +impl Player { + pub fn event_clip(rec: &Recording, i: usize) -> Mode { + Mode::Clips { list: vec![clip(rec, i)], at: 0, reel: false } + } +} diff --git a/airdef-mod/src/sim/damage.rs b/airdef-mod/src/sim/damage.rs index 1bbf897..a07d9ed 100644 --- a/airdef-mod/src/sim/damage.rs +++ b/airdef-mod/src/sim/damage.rs @@ -81,6 +81,7 @@ impl Sim { sam.bursts = 0; let pos = sam.pos + DVec3::Y; out.messages.push(format!("{} №{} УНИЧТОЖЕН", sam.kind.name(), i + 1)); + let (id, kind) = (sam.id, sam.kind); let charge = spec.missile.as_ref().map_or(0.0, |m| m.kind.charge() * missiles as f64) + bursts as f64 / 60.0; // The vehicle's own fuel and the first of its load at once, then the rest cooking off. let first = (1.0 + charge * 0.6).round().clamp(1.0, 8.0) as u32; @@ -91,6 +92,7 @@ impl Sim { let tnt = if charge > 4.0 && self.rng.chance(0.4) { 2 } else { 1 }; self.later.push((when, at, tnt, true)); } + self.log(pos, record::EventKind::SamLost { sam: id, kind, index: i }); // Shells pop in strings. for k in 0..(bursts / 12).min(14) { let when = now + 10 + (k as u64) * 6 + (self.rng.f() * 8.0) as u64; diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 1e5c2c6..b6b4552 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -11,6 +11,7 @@ use std::collections::HashMap; mod damage; mod raid; +pub mod record; mod sight; pub use raid::{Approach, Aim, RaidOrder}; @@ -686,6 +687,15 @@ struct MissileSpec { } impl MissileKind { + /// The sound of its launch. + pub fn launch_sound(self) -> &'static str { + match self { + MissileKind::Pac3 => "airdef:launch.patriot", + MissileKind::M57e6 => "airdef:launch.pantsir", + MissileKind::M48n6 => "airdef:launch.s400_eject", + MissileKind::M77n6 => "airdef:launch.s500_eject", + } + } fn spec(self) -> &'static MissileSpec { match self { MissileKind::Pac3 => &MissileSpec { @@ -1112,6 +1122,10 @@ pub struct Sim { pub target_health: Vec, /// The raid in progress, for its report. wave: Option, + /// The raid being recorded, the last ones recorded, and how many have been. + rec: Option, + pub replays: Vec, + recordings: u32, } /// Ids: objects get multiples of 16, their parts the low bits. @@ -1141,6 +1155,9 @@ impl Sim { queue: Vec::new(), target_health: Vec::new(), wave: None, + rec: None, + replays: Vec::new(), + recordings: 0, } } pub fn id(&mut self) -> u32 { @@ -1240,6 +1257,7 @@ impl Sim { self.draw_targets(out); self.step_wrecks(out); self.report_wave(out); + self.record(); let now = self.tick; self.blasts.retain(|b| now - b.start < b.life as u64); } @@ -1252,6 +1270,9 @@ impl Sim { let mut removed: Vec = Vec::new(); // Oreshnik pieces released this tick: kind, at, velocity, target. let mut released: Vec<(DroneKind, DVec3, DVec3, DVec3)> = Vec::new(); + // Warheads that reached their aim (for the replays): drone, kind, where, TNT; and splits. + let mut impacts: Vec<(u32, DroneKind, DVec3, u32)> = Vec::new(); + let mut splits: Vec<(u32, DVec3)> = Vec::new(); for d in &mut self.drones { d.age += 1; let spec = d.kind.spec(); @@ -1295,6 +1316,7 @@ impl Sim { || d.age > 4000; if hit { boom.push((d.pos, spec.warhead, false)); + impacts.push((d.id, d.kind, d.pos, spec.warhead)); removed.push(d.id); self.hits += 1; continue; @@ -1318,6 +1340,7 @@ impl Sim { released.push((piece, d.pos + v.normalize_or_zero() * (i as f64 * 0.3), v, aim)); } out.sound("airdef:boom.sonic", d.pos, 1.0, 0.7); + splits.push((d.id, d.pos)); // Its pieces count as launched instead of it. self.launched += 5; out.particles("minecraft:firework", d.pos, 1.5, DVec3::ZERO, 0.3, 40); @@ -1393,6 +1416,9 @@ impl Sim { let in_ground = below.is_some_and(|g| d.pos.y <= g + 0.2); if at_target || in_ground || d.age > 8000 { boom.push((d.pos, spec.warhead, spec.decoy)); + if !spec.decoy { + impacts.push((d.id, d.kind, d.pos, spec.warhead)); + } removed.push(d.id); if !spec.decoy { self.hits += 1; @@ -1417,6 +1443,21 @@ impl Sim { out.sound(event, d.pos, 1.0, pitch); } } + for (drone, pos) in splits { + self.log(pos, record::EventKind::Split { drone }); + } + for (drone, kind, pos, tnt) in impacts { + let power = match tnt { + 0 => 0, + 1 | 2 => 1, + 3..=5 => 2, + 6 | 7 => 3, + _ => 4, + }; + let object = self.targets.iter().position(|t| t.distance(pos) < 16.0); + let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i)); + self.log(pos, record::EventKind::Hit { drone, kind, power, object, sam }); + } for (pos, warhead, small) in boom { self.explode(pos, warhead, small, ground, player, out); } @@ -1546,11 +1587,16 @@ impl Sim { } /// A drone hit by air defence: a flash, pieces, and it falls burning. - fn shoot_down(&mut self, idx: usize, by: u32, out: &mut Out) { - let d = &mut self.drones[idx]; - if !d.alive() { + fn shoot_down(&mut self, idx: usize, by: u32, missile: Option, out: &mut Out) { + if !self.drones[idx].alive() { return; } + if let Some((i, s)) = self.sams.iter().enumerate().find(|(_, s)| s.id == by) { + let (drone, kind, pos) = (self.drones[idx].id, self.drones[idx].kind, self.drones[idx].pos); + let kill = record::EventKind::Kill { drone, kind, sam: by, sam_kind: s.kind, sam_index: i, missile }; + self.log(pos, kill); + } + let d = &mut self.drones[idx]; d.flight = Flight::Falling; d.age = 0; d.vel = d.vel * 0.6 + DVec3::new(0.0, 0.15, 0.0); @@ -1798,7 +1844,7 @@ impl Sim { } for (t, by) in gun_hits { if let Some(i) = self.drones.iter().position(|d| d.id == t) { - self.shoot_down(i, by, out); + self.shoot_down(i, by, None, out); } } for i in 0..self.sams.len() { @@ -1950,7 +1996,7 @@ impl Sim { if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) { self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1); if kill { - self.shoot_down(t, sam, out); + self.shoot_down(t, sam, Some(mid), out); } } // A missile that lost its target frees it for others. diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs new file mode 100644 index 0000000..0134332 --- /dev/null +++ b/airdef-mod/src/sim/record.rs @@ -0,0 +1,269 @@ +//! Raids are recorded for their replays: every drone's and interceptor's +//! track (a point every other tick, falling wrecks included) and what +//! happened (shot down, by what; hits; systems lost; the Oreshnik's split). +//! A recording starts with the first drone in the sky and ends when the sky +//! has been clear a while; the last few are kept. +use super::*; + +/// Ticks between a track's points. +pub const STEP: u32 = 2; +/// The longest recording (10 minutes) and how many are kept. +const LONGEST: u32 = 12_000; +const KEPT: usize = 3; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum What { + Drone(DroneKind), + /// An interceptor and the system that fired it. + Missile(MissileKind, u32), +} + +pub struct Track { + pub id: u32, + pub what: What, + /// The recording's tick of its first point. + pub first: u32, + /// Its points, `STEP` ticks apart, relative to the recording's origin. + points: Vec<[f32; 3]>, + /// When it was shot down (a drone falling from then on). + pub fell: Option, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum EventKind { + /// A drone shot down: by which system (its index then), with a missile or the guns. + Kill { drone: u32, kind: DroneKind, sam: u32, sam_kind: SamKind, sam_index: usize, missile: Option }, + /// A drone's warhead went off where it aimed: at an object, a system, or the land. + Hit { drone: u32, kind: DroneKind, power: u32, object: Option, sam: Option<(SamKind, usize)> }, + /// A system destroyed. + SamLost { sam: u32, kind: SamKind, index: usize }, + /// The Oreshnik's bus or a block splitting. + Split { drone: u32 }, +} + +#[derive(Clone, Copy, Debug)] +pub struct Event { + pub at: u32, + pub pos: DVec3, + pub kind: EventKind, +} + +pub struct Recording { + /// Which raid of the session (1, 2, …). + pub number: u32, + pub origin: DVec3, + /// Its length in ticks. + pub len: u32, + pub tracks: Vec, + index: HashMap, + pub events: Vec, + /// The systems and objects as they stood: (id, kind, where). + pub sams: Vec<(u32, SamKind, DVec3)>, + pub objects: Vec, + /// Ticks the sky has been clear. + quiet: u32, +} + +impl Track { + /// Where it was at `t` (the recording's ticks, fractional), if it was. + pub fn at(&self, origin: DVec3, t: f64) -> Option { + let k = (t - self.first as f64) / STEP as f64; + if k < 0.0 || self.points.is_empty() || k > (self.points.len() - 1) as f64 { + return None; + } + let i = (k.floor() as usize).min(self.points.len() - 1); + let j = (i + 1).min(self.points.len() - 1); + let f = k - i as f64; + let p = |q: [f32; 3]| DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64); + Some(origin + p(self.points[i]).lerp(p(self.points[j]), f)) + } + /// Which way it was flying at `t`. + pub fn dir(&self, origin: DVec3, t: f64) -> DVec3 { + let a = self.at(origin, t - STEP as f64).or_else(|| self.at(origin, t)); + let b = self.at(origin, t + STEP as f64).or_else(|| self.at(origin, t)); + match (a, b) { + (Some(a), Some(b)) => (b - a).normalize_or(DVec3::NEG_Z), + _ => DVec3::NEG_Z, + } + } + /// The tick of its last point. + pub fn last(&self) -> u32 { + self.first + (self.points.len().max(1) as u32 - 1) * STEP + } + /// Its points, every `every`-th, up to tick `t`. + pub fn path(&self, origin: DVec3, every: usize, t: f64) -> Vec { + let p = |q: &[f32; 3]| origin + DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64); + let upto = ((t - self.first as f64) / STEP as f64).floor(); + if upto < 0.0 { + return Vec::new(); + } + let upto = (upto as usize).min(self.points.len().saturating_sub(1)); + let mut out: Vec = self.points[..=upto].iter().step_by(every.max(1)).map(p).collect(); + if upto % every.max(1) != 0 { + out.push(p(&self.points[upto])); + } + out + } +} + +impl Recording { + fn new(number: u32, sim: &Sim) -> Self { + let origin = sim.targets.first().copied().or_else(|| sim.sams.first().map(|s| s.pos)).unwrap_or(DVec3::ZERO); + Recording { + number, + origin: origin.floor(), + len: 0, + tracks: Vec::new(), + index: HashMap::new(), + events: Vec::new(), + sams: sim.sams.iter().map(|s| (s.id, s.kind, s.pos)).collect(), + objects: sim.targets.clone(), + quiet: 0, + } + } + fn point(&mut self, id: u32, what: What, pos: DVec3) { + let rel = pos - self.origin; + let q = [rel.x as f32, rel.y as f32, rel.z as f32]; + let now = self.len; + match self.index.get(&id) { + Some(&i) => self.tracks[i].points.push(q), + None => { + self.index.insert(id, self.tracks.len()); + self.tracks.push(Track { id, what, first: now, points: vec![q], fell: None }); + } + } + } + pub fn track(&self, id: u32) -> Option<&Track> { + self.index.get(&id).map(|&i| &self.tracks[i]) + } + /// The system with this id as it stood. + pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> { + self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2)) + } +} + +impl Sim { + /// Something worth a replay happened. + pub(super) fn log(&mut self, pos: DVec3, kind: EventKind) { + if let Some(r) = &mut self.rec { + let at = r.len; + if let EventKind::Kill { drone, .. } = kind + && let Some(&i) = r.index.get(&drone) + { + r.tracks[i].fell = Some(at); + } + r.events.push(Event { at, pos, kind }); + } + } + + /// Once a tick: starts a recording with the first drone, adds the tracks' points, ends it + /// when the sky has been clear 5 s. + pub(super) fn record(&mut self) { + // Wrecks still falling (far off they fall a long while) don't keep it going. + let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty(); + if self.rec.is_none() { + // It starts with the first drone in the sky (not with a raid's drones still waiting). + if !self.drones.iter().any(|d| d.alive()) { + return; + } + self.recordings += 1; + self.rec = Some(Recording::new(self.recordings, self)); + } + let Some(r) = &mut self.rec else { return }; + if r.len % STEP == 0 { + for d in &self.drones { + r.point(d.id, What::Drone(d.kind), d.pos); + } + for m in &self.missiles { + r.point(m.id, What::Missile(m.kind, m.sam), m.pos); + } + } + r.len += 1; + r.quiet = if busy { 0 } else { r.quiet + 1 }; + if r.quiet >= 100 || r.len >= LONGEST { + let mut done = self.rec.take().unwrap(); + done.len = done.len.saturating_sub(done.quiet.saturating_sub(40)); + if !done.events.is_empty() { + self.replays.push(done); + if self.replays.len() > KEPT { + self.replays.remove(0); + } + } + } + } + + /// Draws the recording's drones and interceptors as they were at `t`, as ghosts: ids from `base`. + pub fn draw_ghosts(&self, rec: &Recording, t: f64, base: u32, out: &mut Out) { + for (k, tr) in rec.tracks.iter().enumerate() { + let Some(pos) = tr.at(rec.origin, t) else { continue }; + let dir = tr.dir(rec.origin, t); + let id = base + k as u32 * PARTS; + match tr.what { + What::Drone(kind) => { + let spec = kind.spec(); + let s = spec.scale; + let falling = tr.fell.is_some_and(|f| t >= f as f64); + let mut rot = look(dir, 0.0); + if falling { + let spin = (t - tr.fell.unwrap_or(0) as f64) * 0.35; + rot = rot * DQuat::from_rotation_z(spin) * DQuat::from_rotation_x(-0.6); + out.model(id, spec.model, pos, rot, s, false); + out.model(id + 1, "airdef:flame", pos, rot, 0.6 + 0.2 * ((t * 1.7).sin() + 1.0), true); + continue; + } + if !matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) { + out.model(id, spec.model, pos, rot, s, false); + } + match spec.engine { + Engine::Prop(back, size) => { + let at = pos + rot * DVec3::new(0.0, 0.0, back * s); + out.model(id + 1, "airdef:shahed_prop", at, rot * DQuat::from_rotation_z(t * 1.1), s * size, false); + } + Engine::Jet(up, back, size) => { + out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * s, back * s), rot, s * size, true); + } + Engine::Rocket(back, size) => { + if matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) { + out.model(id + 1, "airdef:reentry", pos, rot, s, true); + } else if spec.ballistic.is_none() || t - (tr.first as f64) < 60.0 { + out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back * s + size), rot, size, true); + } else { + out.model(id + 1, "airdef:reentry", pos, rot, s * 0.6, true); + } + } + } + } + What::Missile(kind, _) => { + let spec = kind.spec(); + let rot = look(dir, 0.0) * DQuat::from_rotation_z(t * 0.3); + out.model(id, spec.model, pos, rot, spec.scale, false); + if t - tr.first as f64 > spec.cold as f64 { + let back = (spec.rear - 8.0) / 16.0 * spec.scale + spec.flame; + out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true); + } + } + } + } + // Blasts: a fireball growing and fading for 1.5 s after each. + for (k, e) in rec.events.iter().enumerate() { + let age = t - e.at as f64; + if !(0.0..30.0).contains(&age) { + continue; + } + let size = match e.kind { + EventKind::Kill { .. } => 3.5, + EventKind::Hit { power, .. } => [2.5, 4.5, 7.0, 10.0, 13.0][(power as usize).min(4)], + EventKind::SamLost { .. } => 8.0, + EventKind::Split { .. } => 2.0, + }; + let f = age / 30.0; + let s = size * (f * 4.0).min(1.0) * (1.0 - f * f); + let id = base + 0x0080_0000 + k as u32 * PARTS; + let spin = DQuat::from_rotation_y(age * 0.05); + out.model(id, "airdef:fireball", e.pos + DVec3::Y * age * 0.04, spin, s.max(0.01), true); + if age < 4.0 { + out.model(id + 1, "airdef:flash", e.pos, spin, size * 0.6, true); + } + } + } +} diff --git a/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch b/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch index 8fa12ea..741ad18 100644 --- a/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch +++ b/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch @@ -1,7 +1,7 @@ From 3de7a6875140a107e28563cc44489b55f5794517 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 12:37:45 +0300 -Subject: [PATCH 1/6] Mod API (AirDef fork): world models, client particles, +Subject: [PATCH 1/7] Mod API (AirDef fork): world models, client particles, sounds, ground heights render.set-models draws block models with an interpolated pose per id; diff --git a/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch b/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch index b7c8f2f..a685475 100644 --- a/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch +++ b/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch @@ -1,7 +1,7 @@ From a6d64e6415bf618539af464e521091e72b72d72f Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 12:39:45 +0300 -Subject: [PATCH 2/6] cargo-horizon-mod: report particles and sounds +Subject: [PATCH 2/7] cargo-horizon-mod: report particles and sounds Co-Authored-By: Claude Opus 5.5 --- diff --git a/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch b/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch index a107930..2a6d328 100644 --- a/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch +++ b/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch @@ -1,7 +1,7 @@ From ee79b3562feebe51959a01f1585a9e85bd53ccb5 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 13:33:10 +0300 -Subject: [PATCH 3/6] Mod API (AirDef fork): full-screen post pass for mods +Subject: [PATCH 3/7] Mod API (AirDef fork): full-screen post pass for mods render.set-post compiles a mod's WGSL after a prelude (camera matrices, time, 256 vec4 of params, the world's colour and depth) and runs it after diff --git a/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch b/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch index df94986..8d82db2 100644 --- a/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch +++ b/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch @@ -1,7 +1,7 @@ From 2b137dbbedd540daeebc7f5e387847aeb56a1355 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 22:09:30 +0300 -Subject: [PATCH 4/6] Mod models: draw far models as scaled impostors past the +Subject: [PATCH 4/7] Mod models: draw far models as scaled impostors past the far plane, cull at 4096 --- diff --git a/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch b/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch index 8fdb54d..9e39a73 100644 --- a/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch +++ b/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch @@ -1,7 +1,7 @@ From c8ebca6e0af68630e65211844b34d25c5b985c03 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 22:31:00 +0300 -Subject: [PATCH 5/6] Mod cameras: render.set-views draws the world from other +Subject: [PATCH 5/7] Mod cameras: render.set-views draws the world from other points into pictures that HUD view shapes show (API level 9) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch b/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch index bc65c1d..c161d67 100644 --- a/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch +++ b/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch @@ -1,7 +1,7 @@ From 8d2261fc4f8072c32e454139cfea7a8c0cd9d664 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 23:08:21 +0300 -Subject: [PATCH 6/6] Mods: more fuel per tick and per event (AirDef plans +Subject: [PATCH 6/7] Mods: more fuel per tick and per event (AirDef plans raids) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch b/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch new file mode 100644 index 0000000..9b5d786 --- /dev/null +++ b/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch @@ -0,0 +1,42 @@ +From 6c548de34def8e4a624d734243418090798bd16a Mon Sep 17 00:00:00 2001 +From: chexit +Date: Wed, 28 Oct 2026 23:25:29 +0300 +Subject: [PATCH 7/7] Mod cameras up to 1920x1080 (full-screen replays) + +Co-Authored-By: Claude Opus 5.5 +--- + crates/horizon-mod-sdk/wit/horizon.wit | 2 +- + crates/horizon-mods/src/runtime.rs | 4 ++-- + 2 files changed, 3 insertions(+), 3 deletions(-) + +diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit +index 436455a19..e30f3a30e 100644 +--- a/crates/horizon-mod-sdk/wit/horizon.wit ++++ b/crates/horizon-mod-sdk/wit/horizon.wit +@@ -523,7 +523,7 @@ interface render { + pitch: f32, + /// Vertical field of view, degrees (1 to 110). + fov: f32, +- /// The picture's size in pixels (16 to 640 × 16 to 480). ++ /// The picture's size in pixels (16 to 1920 × 16 to 1080). + width: u32, + height: u32, + } +diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs +index a551b7376..1389407be 100644 +--- a/crates/horizon-mods/src/runtime.rs ++++ b/crates/horizon-mods/src/runtime.rs +@@ -1991,8 +1991,8 @@ impl render::Host for State { + v.yaw = angle(v.yaw); + v.pitch = angle(v.pitch).clamp(-90.0, 90.0); + v.fov = if v.fov.is_finite() { v.fov.clamp(1.0, 110.0) } else { 70.0 }; +- v.width = v.width.clamp(16, 640); +- v.height = v.height.clamp(16, 480); ++ v.width = v.width.clamp(16, 1920); ++ v.height = v.height.clamp(16, 1080); + v + }) + .collect(); +-- +2.54.0 (Apple Git-157) +