From 57a5426e654957d8c330329c2df091a04c55a48f Mon Sep 17 00:00:00 2001 From: chexit Date: Sat, 31 Oct 2026 00:59:03 +0300 Subject: [PATCH] Strikes on launch sites, command map and placement editor, fire doctrines, ground routes, acoustics switch and reverb #101: radars locate sites from launches, /airdef sites, /airdef strike; sites launch slower (15/25/50 ticks) so a strike can come in time. #48: M opens the map on the network's picture, with an editor. #47: guard, sector, reserve and salvo per system. #94: vehicles route round slopes and water and say when they cannot get through. #96: reverb, and a menu switch for the acoustics. #92: generated files are validated before the swap, repo map. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 + airdef-mod/src/commands.rs | 23 +- airdef-mod/src/film.rs | 2 + airdef-mod/src/layout.rs | 21 + airdef-mod/src/lib.rs | 234 +- airdef-mod/src/map.rs | 1734 +++++++++++ airdef-mod/src/panel.rs | 10 + airdef-mod/src/radar.rs | 38 + airdef-mod/src/replay.rs | 27 +- airdef-mod/src/sim/doctrine.rs | 269 ++ airdef-mod/src/sim/logistics.rs | 9 +- airdef-mod/src/sim/mod.rs | 18 +- airdef-mod/src/sim/orders.rs | 78 +- airdef-mod/src/sim/raid.rs | 14 +- airdef-mod/src/sim/record.rs | 34 + airdef-mod/src/sim/route.rs | 579 ++++ airdef-mod/src/sim/sites.rs | 18 +- airdef-mod/src/sim/strike.rs | 1129 +++++++ airdef-mod/src/sim/why.rs | 48 +- docs/ACOUSTICS.md | 66 +- docs/INSTALL.md | 1 + docs/REPO-MAP.md | 42 + ...ork-world-models-client-particles-so.patch | 2 +- ...izon-mod-report-particles-and-sounds.patch | 2 +- ...-fork-full-screen-post-pass-for-mods.patch | 2 +- ...far-models-as-scaled-impostors-past-.patch | 2 +- ...er.set-views-draws-the-world-from-ot.patch | 2 +- ...er-tick-and-per-event-AirDef-plans-r.patch | 2 +- ...-up-to-1920x1080-full-screen-replays.patch | 2 +- ...ant-terrain-tiles-fog-measured-from-.patch | 2 +- ...id-so-mods-keep-state-per-world-API-.patch | 2 +- ...d-trial-runs-behind-feature-full-so-.patch | 2 +- ...ffer-pass-per-pixel-mod-point-lights.patch | 2 +- ...e-2-sun-and-moon-shadow-cascades-the.patch | 2 +- ...ached-until-a-resize-or-a-new-source.patch | 2 +- ...-per-16x16-tile-surface-and-halo-lis.patch | 2 +- ...pass-in-the-F3-timing-list-half-reso.patch | 2 +- ...only-sun-facing-quads-and-skip-burie.patch | 2 +- ...es-render.model-id-model-generation-.patch | 2 +- ...aling-HORIZON_HD_SCALE-world-G-buffe.patch | 2 +- ...-pass-colour-normal-depth-the-floor-.patch | 2 +- ...lla-texture-on-the-surface-the-biome.patch | 2 +- ...-a-physical-atmosphere-Rayleigh-Mie-.patch | 2 +- ...r-blue-a-little-clearer-ripples-a-li.patch | 2 +- ...sunsets-Rec.-2020-atmosphere-sun-tin.patch | 2 +- ...es-for-simulations-render.query-rays.patch | 2 +- ...vel-from-the-world-not-from-rain-geo.patch | 2 +- ...dules-gfx-hd-one-Rust-file-and-one-W.patch | 2 +- ...scales-that-divide-the-camera-s-6553.patch | 2 +- ...oke-and-missile-trails-with-clear-tu.patch | 2 +- ...ited-by-depth-so-terrain-and-vehicle.patch | 2 +- ...rails-drawn-at-least-as-wide-as-a-gr.patch | 2 +- ...main-view-API-level-15-renders-the-s.patch | 2 +- ...mods-render.set-spot-lights-API-leve.patch | 2 +- ...g-polish-cloud-panorama-cirrus-terra.patch | 2 +- ...through-glass-and-leaves-rain-ripple.patch | 2 +- ...y-frame-in-flight-reaches-the-writer.patch | 2 +- ...s-command.set-tree-and-set-suggestio.patch | 2 +- ...ound-sources-start-update-stop-with-.patch | 2 +- ...rom-a-far-point-so-the-view-bob-s-ey.patch | 2 +- ...1-direct-path-occlusion-ported-from-.patch | 2 +- ...s-through-the-server-thread-API-22-s.patch | 2 +- ...terrain-tiles-and-mouse-input-API-24.patch | 2641 +++++++++++++++++ tools/acoustics_check.py | 64 + tools/gen_models.py | 108 +- 65 files changed, 7214 insertions(+), 80 deletions(-) create mode 100644 airdef-mod/src/map.rs create mode 100644 airdef-mod/src/sim/doctrine.rs create mode 100644 airdef-mod/src/sim/route.rs create mode 100644 airdef-mod/src/sim/strike.rs create mode 100644 docs/REPO-MAP.md create mode 100644 horizon-patches/0041-Mod-canvas-with-terrain-tiles-and-mouse-input-API-24.patch diff --git a/README.md b/README.md index defaa4b..17aafab 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,14 @@ API мода `render.set-lights` (до 512, плавно интерполиру - `/airdef import` — перенести в текущий мир комплексы и цели из старой версии мода (до 0.2.x они были общими для всех миров); - `/airdef raid` — налёт, настроенный в меню; `/airdef target here` — отметить объект под ногами; `/airdef repair` — ремонт; - `/airdef lastchance ` — «последний шанс»: комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт (по умолчанию вкл; сохраняется); +- `/airdef sites` — известные пусковые площадки (ПУ) и ударные ракеты; `/airdef strike <номер ПУ>` — ответный удар по ПУ (#101, «удары по ПУ»). Как это играется: + - **Разведка без волшебства.** Площадку находит только работающая РЛС: либо пуск в её досягаемости (низкая цель: радиогоризонт и холмы решают) даёт точечное наблюдение, либо собственный трек вылетевшей цели «указывает назад» лучом в пару градусов, а время полёта с момента пуска (тревоги) на скорости цели даёт дальность (±8% и секунда времени пуска); у баллистической ракеты дуга точнее. Две РЛС, держащие одну цель, дают два наблюдения. Наблюдения сводятся методом наименьших квадратов, ответ всегда с кругом ошибки (90%), он сужается с каждым пуском. Если места не получилось (круг шире 800 блоков или есть только лучи вдоль одной линии), известен только **азимут** (на скопе метка «N?» на краю), удар невозможен. С местом: ромб на скопе (круг ошибки пунктиром) или метка на краю; в панели строка «Известных ПУ…». Далёкие площадки (километры) открываются грубо (сотни блоков) и бить их почти бесполезно, пока не накопятся пуски. + - **Удар.** Ударных ракет мало (3 в запасе, максимум 4, новая за 5 минут), дальность до 4500 блоков; стартуют оттуда, где вы стоите, летят 4 блока в тик (2 км за 25 с) в точку *оценки*. На подлёте ракету может сбить ПВО противника: у ПУ её нет (40%), лёгкая (35%, сбивает в 30%) или тяжёлая (25%, 65%), у баллистических батарей тяжёлая чаще; узнаёте только по итогу. Разброс ракеты 14 блоков; решает истинное расстояние до ПУ: до 35 блоков — **уничтожена** (запас сгорел и рвётся, отложенные запуски отменены, огонь и дымящийся остов, взрыв общим кодом), до 90 — **подавлена** на 30 с (пуски отложены, не отменены), дальше — **промах**, воронка рядом, ПУ цела: очередь за попадание в соседний грунт не списывается. Плохо известную ПУ (круг в сотни блоков) бить почти бесполезно. + - **Вне карты.** ПУ без земли (нет загруженной карты) тоже находится: азимут и дальность по трекам, но не рисуется. Удар, который попал бы, прекращает её пуски («результат не виден»); промах теряется. + - **Цена выбора.** Ракета запаса не вернётся, пока летит, налёт идёт: близкие площадки не остановить, далёкие (крылатые и баллистические за 2–4 км) успеваете, но для этого нужны РЛС с обзором в сторону налёта и риск промаха или ПВО противника. Отчёт налёта называет сорванные пуски: «Налёт сорван ударами по ПУ (№…): не взлетело N из заявленных M». + - Запись: удар попадает в журнал повтора (строка и взрыв/огонь на карте), сами ПУ в повторе не рисуются. Запас ракет входит в сохранение и сценарий (`strikes <запас> <тиков до следующей>`). Все числа механики в одной таблице `TUNE` в `src/sim/strike.rs`. - `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`; +- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve ` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48). - `/airdef deploy ` — поставить комплекс в 8 блоках перед собой; - `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов; - `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы); diff --git a/airdef-mod/src/commands.rs b/airdef-mod/src/commands.rs index 37cb9e5..2370855 100644 --- a/airdef-mod/src/commands.rs +++ b/airdef-mod/src/commands.rs @@ -58,6 +58,8 @@ 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("strike").then(Node::arg("номер", Value::int_from(1)).runs()), Node::lit("repair").runs(), Node::lit("import").runs(), toggle("ew"), @@ -87,6 +89,16 @@ pub fn tree() -> Tree { .runs(), ), ), + Node::lit("doctrine").runs().then(Node::arg("номер", Value::word()).with([ + Node::lit("reserve").then(Node::arg("K", Value::int(0, 64)).runs()), + Node::lit("salvo").then(Node::arg("залп", Value::choice(["eco", "normal", "heavy"])).runs()), + Node::lit("sector").with([ + Node::lit("off").runs(), + Node::arg("центр°", Value::number(-720.0, 720.0)).then(Node::arg("полуширина°", Value::number(0.0, 180.0)).runs()), + ]), + Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]), + Node::lit("reset").runs(), + ])), Node::lit("stats").runs(), ]) } @@ -149,9 +161,9 @@ mod tests { "replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop", "scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list", "scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear", - "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000", + "sites", "strike 3", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000", "wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off", - "roles all default", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic", + "roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic", ] { ok(line); } @@ -187,6 +199,9 @@ mod tests { assert_eq!(bad_at("why x"), 4); assert_eq!(bad_at("move"), 4); assert_eq!(bad_at("move 0"), 5); + assert_eq!(bad_at("strike"), 6); + assert_eq!(bad_at("strike 0"), 7); + assert_eq!(bad_at("sites 1"), 6); assert_eq!(bad_at("scenario"), 8); assert_eq!(bad_at("scenario load"), 13); assert_eq!(bad_at("scenario wipe"), 9); @@ -219,10 +234,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", "stats"] { + "target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike"] { assert!(top.contains(&w.to_string()), "{w} in {top:?}"); } - assert_eq!(top.len(), 25); + assert_eq!(top.len(), 28); assert_eq!(complete("rep", &[]), ["repair", "replay"]); assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]); assert_eq!(complete("replay film ", &[]), ["all", "best"]); diff --git a/airdef-mod/src/film.rs b/airdef-mod/src/film.rs index 8666d1c..88c8644 100644 --- a/airdef-mod/src/film.rs +++ b/airdef-mod/src/film.rs @@ -454,6 +454,8 @@ fn plan_event(rec: &Recording, i: usize, floor: f64) -> Vec { }); add(Shot::new(a, b, &[(a, 1.0), (te - 4.0, 0.3), (te + 40.0, 1.0)], variants, &title(rec, i), "", i)); } + // A strike on a launch site (#101) is in the event list and on the map, not in the auto-camera's films. + EventKind::Strike { .. } => {} } shots } diff --git a/airdef-mod/src/layout.rs b/airdef-mod/src/layout.rs index f046ac7..e2c04e8 100644 --- a/airdef-mod/src/layout.rs +++ b/airdef-mod/src/layout.rs @@ -34,8 +34,13 @@ pub struct Layout { pub seed: Option, pub wave: Option>, pub far: Option, + pub acoustics: Option, pub effects: Option<(bool, bool)>, pub roles: Vec<(SamKind, u8)>, + /// Fire doctrines by the system's place in the file (#47). + pub doctrines: Vec<(usize, sim::doctrine::Doctrine)>, + /// Strike missiles in stock and ticks towards the next (#101). + pub strikes: Option<(u32, u32)>, } /// One line's words, with the line number for the messages. @@ -124,7 +129,9 @@ impl Layout { } "damage" => out.damage = l.flag(1, "значение")?, "lastchance" => out.last_chance = l.flag(1, "значение")?, + "strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))), "far" => out.far = l.flag(1, "значение")?, + "acoustics" => out.acoustics = l.flag(1, "значение")?, "effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))), "seed" => { let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?; @@ -134,6 +141,16 @@ impl Layout { crate::wave::WaveConfig::default().check(&l.w[1..]).map_err(|e| l.bad("налёт", &e))?; out.wave = Some(l.w[1..].iter().map(|s| s.to_string()).collect()); } + "doctrine" => { + // doctrine [x y z]... + let at = l.need(1, "комплекс", 0.0, MAX_UNITS as f64)? as usize; + let salvo = l.w.get(2).and_then(|v| sim::doctrine::Salvo::from_key(v)).ok_or_else(|| l.bad("залп", "eco, normal или heavy"))?; + let reserve = l.need(3, "резерв", 0.0, sim::doctrine::MAX_RESERVE as f64)? as u32; + let sector = if l.w.get(4) == Some(&"-") { None } else { Some((l.need(4, "центр сектора", -1.0e6, 1.0e6)?, l.need(5, "полуширина", 0.0, 7.0)?)) }; + let n = l.need(6, "число объектов", 0.0, 64.0)? as usize; + let guards = (0..n).map(|k| l.xyz(7 + 3 * k, "охраняемый объект")).collect::, _>>()?; + out.doctrines.push((at, sim::doctrine::Doctrine { guards, sector, reserve, salvo })); + } "roles" => { let kind = l.kind(1)?; out.roles.push((kind, l.need(2, "роли", 0.0, 255.0)? as u8)); @@ -196,6 +213,10 @@ mod tests { assert_eq!(l.sams[3].comps.len(), 6); assert_eq!((l.damage, l.far, l.effects, l.seed), (Some(false), Some(true), Some((true, false)), Some(123456789))); assert_eq!(l.roles.len(), 1); + // Saves without strikes load as before; with them, the stock is read (and refused when wrong). + assert_eq!(l.strikes, None); + assert_eq!(Layout::parse("strikes 2 3500\n").unwrap().strikes, Some((2, 3500))); + assert!(Layout::parse("strikes -1 0\n").is_err() && Layout::parse("strikes x\n").is_err()); // What the build writes now reads back (a wave line from the menu's own text). let w = crate::wave::WaveConfig::default().text(); assert!(Layout::parse(&format!("wave {w}\n")).is_ok(), "{w}"); diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index a9ef49e..59349dc 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -16,6 +16,7 @@ mod cinema; mod engines; mod commands; mod layout; +mod map; mod film; mod monitor; mod panel; @@ -87,6 +88,8 @@ struct AirDef { 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). + acoustics: Option, /// The game's log of block changes (`render.world-log-start`): a replay shows the world as /// it was at its moment, not the holes the raid left (None where the game has no such log). block_log: Option, @@ -119,6 +122,8 @@ struct AirDef { model_generation: u32, /// The instances handed to the game, kept between ticks so nothing is allocated for them. by_id: Vec, + /// The command map (#48). + map: map::MapUi, } /// What `/airdef replay export` was asked for. @@ -212,6 +217,9 @@ enum Page { More, /// The last raid's events and its replays. Replays, + /// The systems with their doctrines, and one system's doctrine (by id) (#47). + Fleet, + Doctrine(u32), } const MENU_KINDS: u32 = 1; @@ -236,6 +244,15 @@ const BTN_MAP: u32 = 40; const BTN_FULL: u32 = 41; const BTN_REEL: u32 = 42; const BTN_FAR: u32 = 19; +const BTN_ACOUSTICS: u32 = 20; +const BTN_DOCTRINE: u32 = 21; +const FLEET_ROWS: u32 = 4; +const BTN_RESERVE: u32 = 50; +const BTN_SALVO: u32 = 51; +const BTN_SECTOR_DIR: u32 = 52; +const BTN_SECTOR_WIDTH: u32 = 53; +const BTN_GUARD: u32 = 54; +const BTN_DOC_RESET: u32 = 55; const BTN_CLASS: u32 = 100; const BTN_ALL: u32 = 120; const BTN_DEFAULT: u32 = 121; @@ -506,6 +523,11 @@ impl AirDef { .collect() } + /// Whether the game's acoustics are on, or asked to be. + fn acoustics_on(&self) -> bool { + self.acoustics.unwrap_or_else(render::acoustics) + } + /// The effects preset: none, the post pass, or the post pass under the HD lighting. fn set_effects(&mut self, shader: bool, hd: bool) { self.sim.shader = shader; @@ -861,13 +883,21 @@ impl AirDef { } text += &format!("damage {}\n", self.sim.damage); text += &format!("lastchance {}\n", self.sim.last_chance); + // A scenario to replay from the start begins with the full stock. + let (stock, progress) = if fresh { (sim::strike::TUNE.stock, 0) } else { (self.sim.strikes.stock, self.sim.strikes.progress) }; + text += &format!("strikes {stock} {progress}\n"); if view { text += &format!("far {}\n", self.far); + text += &format!("acoustics {}\n", self.acoustics_on()); text += &format!("effects {} {}\n", self.sim.shader, self.hd); } for (kind, roles) in &self.sim.roles { text += &format!("roles {} {}\n", kind.key(), roles); } + // Doctrines by the system's place in this file; the default ones aren't written. + for (i, s) in self.sim.sams.iter().enumerate().filter(|(_, s)| !s.doctrine.is_default()) { + text += &format!("doctrine {i} {}\n", s.doctrine.save_text()); + } text } @@ -912,6 +942,7 @@ impl AirDef { /// Adds a checked layout to the scene: nothing here can fail. fn commit_layout(&mut self, layout: layout::Layout) { + let base = self.sim.sams.len(); for r in layout.sams { let id = self.sim.id(); let mut sam = Sam::new(id, r.kind, r.pos, r.heading); @@ -952,6 +983,9 @@ impl AirDef { if let Some(l) = layout.last_chance { self.sim.last_chance = l; } + if let Some((stock, progress)) = layout.strikes { + self.sim.strikes.restore(stock, progress); + } // A scenario's: the random generator, and the wave menu's raid. if let Some(v) = layout.seed { self.sim.reseed(v); @@ -960,6 +994,10 @@ impl AirDef { let w: Vec<&str> = w.iter().map(String::as_str).collect(); self.wave.parse(&w); } + if let Some(a) = layout.acoustics { + self.acoustics = Some(a); + render::set_acoustics(a); + } if let Some(f) = layout.far { self.far = f; } @@ -969,6 +1007,11 @@ impl AirDef { for (kind, r) in layout.roles { self.sim.roles.insert(kind, r); } + for (i, d) in layout.doctrines { + if let Some(s) = self.sim.sams.get_mut(base + i) { + s.doctrine = d; + } + } } fn give(&self) { @@ -1020,6 +1063,7 @@ impl AirDef { self.sim.shader = shader; self.ground = Ground::default(); self.monitor = None; + self.map_close(); self.grid = false; self.grid_ids.clear(); // The last world's transient state: its sounds were due on its own @@ -1363,6 +1407,8 @@ impl AirDef { widgets.push(Widget::List(ListWidget { id: MENU_KINDS, rows, selected: None })); let _ = &self.monitor; widgets.push(Widget::Button(ButtonWidget { id: BTN_GRID, label: "Командный пункт: все комплексы (J)".into() })); + let custom = self.sim.sams.iter().filter(|s| !s.doctrine.is_default()).count(); + widgets.push(Widget::Button(ButtonWidget { id: BTN_DOCTRINE, label: format!("Доктрины: охрана, сектор, резерв (особых: {custom})…") })); 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() })); @@ -1401,6 +1447,7 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_SHADER, label: format!("Эффекты: {fx}") })); widgets.push(Widget::Button(ButtonWidget { id: BTN_DAMAGE, label: format!("Разрушения: {}", onoff(self.sim.damage)) })); widgets.push(Widget::Button(ButtonWidget { id: BTN_FAR, label: format!("Дальний ландшафт: {}", onoff(self.far)) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_ACOUSTICS, label: format!("Акустика (преграды, эхо): {}", onoff(self.acoustics_on())) })); widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); } Page::Wave => { @@ -1425,6 +1472,37 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_LAUNCH, label: format!("▶ ПУСК ({})", w.total()) })); widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Состав".into() })); } + Page::Fleet => { + title = "Доктрины — клик по комплексу".to_string(); + let rows = self + .fleet() + .iter() + .map(|&i| { + let s = &self.sim.sams[i]; + format!("№{} {} · {}", i + 1, s.kind.name(), s.doctrine.text(&self.sim.targets)) + }) + .collect(); + widgets.push(Widget::List(ListWidget { id: FLEET_ROWS, rows, selected: None })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); + } + Page::Doctrine(id) => { + let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else { return self.open_menu(Page::Fleet) }; + let s = &self.sim.sams[i]; + let d = &s.doctrine; + title = format!("№{} {} — доктрина (объяснение: /airdef why {})", i + 1, s.kind.name(), i + 1); + let guard = match d.guards.len() { + 0 => "нет (все цели своих классов)".to_string(), + 1 => sim::doctrine::object_name(&self.sim.targets, d.guards[0]), + n => format!("{n} объектов (клик — снять)"), + }; + widgets.push(Widget::Button(ButtonWidget { id: BTN_GUARD, label: format!("Охраняемый объект: {guard}") })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_SECTOR_DIR, label: format!("Сектор: {}", d.sector_text()) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_SECTOR_WIDTH, label: format!("Ширина сектора: ±{:.0}°", d.sector.map_or(45.0, |(_, h)| h.to_degrees())) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_RESERVE, label: format!("Резерв ракет: {} (в магазине {})", d.reserve, s.missiles) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_SALVO, label: format!("Залп по цели: {}", d.salvo.name()) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_DOC_RESET, label: "Сбросить доктрину".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Комплексы".into() })); + } Page::Roles(kind) => { title = format!("{} ({}) — по каким целям стрелять", kind.name(), panel::distance(kind.range())); let _ = ItemWidget { id: 0, item: String::new(), name: String::new() }; @@ -1443,6 +1521,75 @@ impl AirDef { ui::open_screen(&Screen { title, widgets }); } + /// The systems that have a doctrine to set: those with missiles (indices into the sim's list). + fn fleet(&self) -> Vec { + (0..self.sim.sams.len()).filter(|&i| self.sim.sams[i].kind.armed()).collect() + } + + /// Changes one system's doctrine (the menu's buttons and `/airdef doctrine`). + fn edit_doctrine(&mut self, i: usize, f: impl FnOnce(&mut sim::doctrine::Doctrine)) { + if let Some(s) = self.sim.sams.get_mut(i) { + f(&mut s.doctrine); + // It chooses again under the new rules. + s.target = None; + s.gun_target = None; + self.dirty = true; + } + } + + /// `/airdef doctrine [ reserve K | salvo eco|normal|heavy | sector C H | sector off | guard N[,M]|off | reset]` (#47). + fn doctrine_command(&mut self, w: &[&str]) -> Result { + const USAGE: &str = "/airdef doctrine <номер|all> reserve | salvo eco|normal|heavy | sector <центр°> <полуширина°> | sector off | guard <объект№>[,<№>] | guard off | reset"; + let Some((who, what)) = w.split_first() else { + for i in self.fleet() { + let s = &self.sim.sams[i]; + say(&format!("№{} {}: {}", i + 1, s.kind.name(), s.doctrine.text(&self.sim.targets))); + } + return Ok(format!("Изменить: {USAGE}")); + }; + let which: Vec = if *who == "all" { + self.fleet() + } else { + let i = who.parse::().ok().and_then(|n| n.checked_sub(1)).filter(|&i| self.sim.sams.get(i).is_some_and(|s| s.kind.armed())).ok_or("Нет такого вооружённого комплекса")?; + vec![i] + }; + let num = |v: Option<&&str>, what: &str, lo: f64, hi: f64| -> Result { + v.and_then(|v| v.parse::().ok()).filter(|x| x.is_finite() && (lo..=hi).contains(x)).ok_or(format!("{what}: число от {lo} до {hi}")) + }; + let mut edit: Box = match what { + ["reserve", k] => { + let k = num(Some(k), "резерв", 0.0, sim::doctrine::MAX_RESERVE as f64)? as u32; + Box::new(move |d| d.reserve = k) + } + ["salvo", v] => { + let v = sim::doctrine::Salvo::from_key(v).ok_or("Залп: eco, normal или heavy")?; + Box::new(move |d| d.salvo = v) + } + ["sector", "off"] => Box::new(|d| d.sector = None), + ["sector", c, h] => { + let c = num(Some(c), "центр сектора", -720.0, 720.0)?.to_radians(); + let h = num(Some(h), "полуширина сектора", 0.0, 180.0)?.to_radians(); + Box::new(move |d| d.sector = Some((c, h))) + } + ["guard", "off"] => Box::new(|d| d.guards.clear()), + ["guard", list] => { + let mut at = Vec::new(); + for n in list.split(',') { + let k = n.parse::().ok().and_then(|n| n.checked_sub(1)).and_then(|k| self.sim.targets.get(k)).ok_or(format!("Нет объекта «{n}» (отметьте его /airdef target here)"))?; + at.push(*k); + } + Box::new(move |d| d.guards = at.clone()) + } + ["reset"] => Box::new(|d| *d = sim::doctrine::Doctrine::default()), + _ => return Err(USAGE.into()), + }; + for &i in &which { + self.edit_doctrine(i, &mut edit); + } + let first = which.first().map(|&i| self.sim.sams[i].doctrine.text(&self.sim.targets)).unwrap_or_default(); + Ok(format!("Доктрина ({} компл.): {first}", which.len())) + } + fn set_roles(&mut self, kind: SamKind, mask: Option) { let mask = match mask { Some(m) => { @@ -1490,6 +1637,7 @@ impl Mod for AirDef { session: 0, smoke: Default::default(), far: true, + acoustics: None, moving: None, hd: false, world: None, @@ -1504,7 +1652,9 @@ impl Mod for AirDef { model_ids: std::collections::HashMap::new(), model_generation: u32::MAX, by_id: Vec::new(), + map: map::MapUi::default(), }; + let _ = input::register_key("map", "Карта: командная, расстановка", "key.keyboard.m"); 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"); @@ -1539,6 +1689,7 @@ impl Mod for AirDef { for event in input::poll() { match event { Event::UseStart(u) => self.use_item(&u.item.id), + Event::KeyDown(k) if k == "map" => self.map_toggle(), Event::KeyDown(k) if k == "menu" => { if self.replay.is_some() { self.stop_replay(); @@ -1662,6 +1813,9 @@ impl Mod for AirDef { } } self.emit(out); + self.map.sample(&self.sim); + // The map's events and shapes: at the tick's pace (a frame hook's budget is too small for it). + 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. if let Some(r) = &self.replay { @@ -1734,6 +1888,58 @@ impl Mod for AirDef { } return; } + (Page::Main, BTN_DOCTRINE) => { + self.open_menu(Page::Fleet); + return; + } + (Page::Fleet, FLEET_ROWS) => { + if let Some(&i) = self.fleet().get(row as usize) { + self.open_menu(Page::Doctrine(self.sim.sams[i].id)); + } + return; + } + (Page::Fleet, BTN_BACK) => { + self.open_menu(Page::Main); + return; + } + (Page::Doctrine(_), BTN_BACK) => { + self.open_menu(Page::Fleet); + return; + } + (Page::Doctrine(id), b) => { + let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else { return }; + let objects = self.sim.targets.clone(); + match b { + BTN_RESERVE => self.edit_doctrine(i, |d| d.reserve = [0, 1, 2, 4, 8, 16].into_iter().find(|&r| r > d.reserve).unwrap_or(0)), + BTN_SALVO => self.edit_doctrine(i, |d| d.salvo = d.salvo.next()), + // Eight directions of 45 degrees, then off. + BTN_SECTOR_DIR => self.edit_doctrine(i, |d| { + let half = d.sector.map_or(45f64.to_radians(), |(_, h)| h); + d.sector = match d.sector { + None => Some((0.0, half)), + Some((c, _)) if (c.to_degrees().rem_euclid(360.0) / 45.0).round() < 7.0 => Some((c + 45f64.to_radians(), half)), + Some(_) => None, + }; + }), + BTN_SECTOR_WIDTH => self.edit_doctrine(i, |d| { + if let Some((c, h)) = d.sector { + let deg = [30.0, 45.0, 60.0, 90.0, 135.0].into_iter().find(|&w| w > h.to_degrees() + 0.5).unwrap_or(30.0); + d.sector = Some((c, f64::to_radians(deg))); + } + }), + // None, then each object in turn, then none. + BTN_GUARD => self.edit_doctrine(i, |d| { + let at = d.guards.first().and_then(|g| objects.iter().position(|t| t.distance(*g) < 16.0)); + d.guards = match (d.guards.len(), at) { + (0, _) => objects.first().copied().into_iter().collect(), + (1, Some(k)) => objects.get(k + 1).copied().into_iter().collect(), + _ => Vec::new(), + }; + }), + BTN_DOC_RESET => self.edit_doctrine(i, |d| *d = sim::doctrine::Doctrine::default()), + _ => return, + } + } (Page::More, BTN_HOLD) => self.sim.hold = !self.sim.hold, (Page::Main, BTN_MONITOR) => self.cycle_monitor(), (Page::Main, BTN_WAVE) => { @@ -1840,6 +2046,12 @@ impl Mod for AirDef { self.apply_far(); self.dirty = true; } + (Page::More, BTN_ACOUSTICS) => { + let on = !self.acoustics_on(); + self.acoustics = Some(on); + render::set_acoustics(on); + self.dirty = true; + } (Page::More, BTN_DAMAGE) => { self.sim.damage = !self.sim.damage; self.dirty = true; @@ -1950,6 +2162,20 @@ impl Mod for AirDef { self.launch_wave(&mut out)?; None } + ["sites"] => { + // The launch sites the radars have found, and the strike missiles (#101). + let p = player().ok_or("Нет игрока")?; + for l in self.sim.site_lines(DVec3::new(p.x, p.y, p.z)) { + say(&l); + } + None + } + ["strike", n] => { + // A strike missile at known site n, from where the player stands. + let p = player().ok_or("Нет игрока")?; + let id = n.parse::().map_err(|_| "/airdef strike <номер ПУ из /airdef sites>")?; + Some(self.sim.order_strike(id, DVec3::new(p.x, p.y, p.z), &mut out)?) + } ["move", n] => { // Unit n (as the summary numbers them) drives to where the player stands. let p = player().ok_or("Нет игрока")?; @@ -2007,6 +2233,7 @@ impl Mod for AirDef { self.dirty = true; Some(format!("Разрушения: {}", if self.sim.damage { "вкл" } else { "выкл" })) } + ["doctrine", rest @ ..] => Some(self.doctrine_command(rest)?), ["roles"] => { for kind in SamKind::ARMED { let r = self.sim.roles.get(&kind).copied().unwrap_or(kind.spec().roles); @@ -2061,13 +2288,18 @@ impl Mod for AirDef { Some(format!("Эффекты: {}", match *v { "off" => "выкл", "hd" => "HD", _ => "обычные" })) } ["stats"] => Some(format!( - "В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; {}", + "В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}", self.sim.drones.iter().filter(|d| d.alive()).count(), self.sim.missiles.len(), self.sim.sams.len(), self.sim.kills, self.sim.hits, self.sim.crashes, + self.sim.strikes.fired, + self.sim.strikes.destroyed, + self.sim.strikes.stunned, + self.sim.strikes.missed, + self.sim.strikes.shot_down, self.ground.world.text() )), _ => return Err(help()), diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs new file mode 100644 index 0000000..be47c1c --- /dev/null +++ b/airdef-mod/src/map.rs @@ -0,0 +1,1734 @@ +//! The command map (#48): a full-screen map of the land with the systems, the objects, the launch sites +//! the radars found and the tracks the player's network holds; a placement editor for the layout before +//! a battle; the doctrine's guards and sector picked on the map. +//! +//! The map shows what the network knows (`Sim::picture`: the last measurement and the forecast of each +//! track), never the true drones, unless the sandbox's `truth` is on, and then it says so. The terrain +//! comes from the game as tiles (`render::TerrainShape`): the mod only says which, and the game scans the +//! loaded chunks within a budget; land it hasn't got is drawn as unknown. +use crate::panel::distance; +use crate::sim::{self, Class, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState}; +use crate::{AirDef, say}; +use glam::DVec3; +use horizon_mod_sdk::render::{self, CanvasEvent, FillShape, Point, QuadShape, Rect, Shape, TerrainShape, TextShape}; +use std::collections::HashMap; +use std::f32::consts::TAU; + +const FILTERS: [&str; 7] = ["рельеф", "системы", "объекты", "цели сети", "следы", "пусковые", "дальности"]; +const F_TERRAIN: usize = 0; +const F_SAMS: usize = 1; +const F_OBJECTS: usize = 2; +const F_TRACKS: usize = 3; +const F_TRAILS: usize = 4; +const F_SITES: usize = 5; +const F_RINGS: usize = 6; + +/// Blocks per pixel limits: the whole raid, and one vehicle. +const SCALE_MIN: f64 = 0.04; +const SCALE_MAX: f64 = 24.0; +const TRAIL_POINTS: usize = 90; +/// Ticks between trail samples. +const SAMPLE: u64 = 10; +/// Pixels within which the pointer picks something. +const PICK_R: f32 = 9.0; +const DRAFT_UNDO: usize = 40; + +const GREEN: u32 = 0xFF80FF90; +const WHITE: u32 = 0xFFFFFFFF; +const GREY: u32 = 0xFFB0B0B0; +const YELLOW: u32 = 0xFFFFE070; +const RED: u32 = 0xFFFF5050; +const CYAN: u32 = 0xFF9FE0FF; +const ORANGE: u32 = 0xFFFFA040; +const PANEL: u32 = 0xD0101814; +/// The right card's width in GUI pixels. +const CARD_W: f32 = 196.0; + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Sel { + Sam(u32), + Object(usize), + Site(u32), + Track(u32), +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Pick { + None, + Sam(SamKind), + Object, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Mode { + View, + /// Pick the objects the system guards. + Guard(u32), + /// Pick the sector's centre, then its width. + Sector(u32, Option), + Editor, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Act { + Filter(usize), + Editor, + Pick(Pick), + Confirm, + Cancel, + Undo, + Guard, + Sector, + SectorOff, + Reserve, + Salvo, + Role(u8), + ResetDoc, + Strike(u32), + Centre, + Follow, + Rotate, + Delete, + Close, + Player, +} + +/// A system in the draft layout: an existing one (by id) or one to be built. +#[derive(Clone, Debug)] +struct DSam { + id: Option, + kind: SamKind, + pos: DVec3, + heading: f64, + gone: bool, +} + +#[derive(Clone, Debug)] +struct DObj { + idx: Option, + pos: DVec3, + gone: bool, +} + +#[derive(Clone, Debug, Default)] +struct Draft { + sams: Vec, + objs: Vec, +} + +enum Drag { + Pan { from: (f32, f32), centre: (f64, f64), moved: bool }, + Sam(usize), + Obj(usize), +} + +struct Btn { + rect: [f32; 4], + act: Act, +} + +/// What the map keeps between frames. +pub struct MapUi { + pub open: bool, + size: (f32, f32), + cursor: (f32, f32), + centre: (f64, f64), + scale: f64, + placed: bool, + drag: Option, + sel: Option, + follow: bool, + mode: Mode, + filters: [bool; 7], + trails: HashMap>, + seen: HashMap, + sampled: u64, + draft: Draft, + history: Vec, + pick: Pick, + heading: f64, + ed_sel: Option, + note: Option<(String, u64)>, + dirty: bool, + drawn: u64, + buttons: Vec, + chunks_at: u64, + close: bool, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum EdSel { + Sam(usize), + Obj(usize), +} + +impl Default for MapUi { + fn default() -> Self { + MapUi { + open: false, + size: (480.0, 270.0), + cursor: (0.0, 0.0), + centre: (0.0, 0.0), + scale: 0.5, + placed: false, + drag: None, + sel: None, + follow: false, + mode: Mode::View, + filters: [true; 7], + trails: HashMap::new(), + seen: HashMap::new(), + sampled: 0, + draft: Draft::default(), + history: Vec::new(), + pick: Pick::None, + heading: 0.0, + ed_sel: None, + note: None, + dirty: true, + drawn: u64::MAX, + buttons: Vec::new(), + chunks_at: 0, + close: false, + } + } +} + +fn pt(x: f32, y: f32) -> Point { + Point { x, y } +} +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) -> Shape { + Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: false, shadow: true }) +} +fn text_c(t: impl Into, x: f32, y: f32, color: u32) -> Shape { + Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: true, shadow: true }) +} +/// A line of `w` pixels. +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.hypot(dy).max(0.001); + let (nx, ny) = (-dy / len * w / 2.0, dx / len * w / 2.0); + Shape::Quad(QuadShape { corners: (pt(a.0 + nx, a.1 + ny), pt(b.0 + nx, b.1 + ny), pt(b.0 - nx, b.1 - ny), pt(a.0 - nx, a.1 - ny)), color }) +} +fn frame(x: f32, y: f32, w: f32, h: f32, b: f32, color: u32) -> [Shape; 4] { + [fill(x, y, w, b, color), fill(x, y + h - b, w, b, color), fill(x, y, b, h, color), fill(x + w - b, y, b, h, color)] +} +fn alpha(rgb: u32, a: f32) -> u32 { + (((a.clamp(0.0, 1.0) * 255.0) as u32) << 24) | (rgb & 0xFFFFFF) +} +/// A diamond, a square and the like around (x, y). +fn diamond(x: f32, y: f32, r: f32, color: u32) -> Shape { + Shape::Quad(QuadShape { corners: (pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y)), color }) +} + +/// The direction a heading looks along on the map (x east, z south): `heading_of`'s inverse. +fn dir_of(h: f64) -> (f64, f64) { + (-h.sin(), -h.cos()) +} + +impl MapUi { + fn to_screen(&self, x: f64, z: f64) -> (f32, f32) { + ( + (self.size.0 as f64 / 2.0 + (x - self.centre.0) * self.scale) as f32, + (self.size.1 as f64 / 2.0 + (z - self.centre.1) * self.scale) as f32, + ) + } + fn to_world(&self, p: (f32, f32)) -> (f64, f64) { + ( + self.centre.0 + (p.0 as f64 - self.size.0 as f64 / 2.0) / self.scale, + self.centre.1 + (p.1 as f64 - self.size.1 as f64 / 2.0) / self.scale, + ) + } + fn on_screen(&self, p: (f32, f32), margin: f32) -> bool { + p.0 > -margin && p.1 > -margin && p.0 < self.size.0 + margin && p.1 < self.size.1 + margin + } + fn note(&mut self, tick: u64, s: impl Into) { + self.note = Some((s.into(), tick + 100)); + self.dirty = true; + } + + /// Remembers where the network's tracks are, every few ticks, for the trails. + pub fn sample(&mut self, sim: &Sim) { + if sim.tick < self.sampled { + self.trails.clear(); + self.seen.clear(); + } + if sim.tick < self.sampled + SAMPLE { + return; + } + self.sampled = sim.tick; + for (id, t) in sim.picture() { + // Only measurements: a forecast is not a place the target has been. + if t.age(sim.tick) > SAMPLE * 2 { + continue; + } + let trail = self.trails.entry(id).or_default(); + let p = (t.pos.x as f32, t.pos.z as f32); + if trail.last().is_none_or(|l| (l.0 - p.0).hypot(l.1 - p.1) > 4.0) { + trail.push(p); + if trail.len() > TRAIL_POINTS { + trail.remove(0); + } + } + self.seen.insert(id, sim.tick); + } + let now = sim.tick; + self.seen.retain(|_, t| now.saturating_sub(*t) < 1200); + let seen = &self.seen; + self.trails.retain(|id, _| seen.contains_key(id)); + } + + fn enter_editor(&mut self) { + self.draft = Draft::default(); + self.history.clear(); + self.mode = Mode::Editor; + self.pick = Pick::None; + self.ed_sel = None; + self.sel = None; + self.dirty = true; + } + + fn push_history(&mut self) { + self.history.push(self.draft.clone()); + if self.history.len() > DRAFT_UNDO { + self.history.remove(0); + } + } +} + +/// Whether a system reaches the point (its weapons, on the plane). +fn reaches(kind: SamKind, pos: DVec3, p: DVec3) -> bool { + kind.range() > 0.0 && (pos.x - p.x).hypot(pos.z - p.z) <= kind.range() +} + +fn class_name(c: sim::sites::SiteClass) -> &'static str { + match c { + sim::sites::SiteClass::Ramp => "рампа дронов", + sim::sites::SiteClass::Launcher => "пусковая ракет", + sim::sites::SiteClass::Battery => "батарея баллистических", + } +} + +impl AirDef { + /// Opens the map (the key, or the menu). + pub(crate) fn map_toggle(&mut self) { + if self.map.open { + self.map_close(); + return; + } + if self.replay.is_some() { + say("Карта: сначала закройте повтор"); + return; + } + let Some(p) = crate::player() else { return }; + let ui = &mut self.map; + ui.open = true; + ui.mode = Mode::View; + ui.drag = None; + ui.size = render::gui_size(); + if !ui.placed { + ui.centre = (p.x, p.z); + ui.placed = true; + } + ui.dirty = true; + ui.drawn = u64::MAX; + render::open_canvas(); + } + + pub(crate) fn map_close(&mut self) { + if self.map.open { + render::close_canvas(); + render::set_canvas(&[]); + } + self.map.open = false; + self.map.draft = Draft::default(); + self.map.mode = Mode::View; + self.map.drag = None; + } + + /// Once a frame while the map is open. + pub(crate) fn map_frame(&mut self) { + if !self.map.open { + return; + } + if !render::canvas_open() { + // The game closed it (the world was left, or it was not the time). + self.map.open = false; + self.map.draft = Draft::default(); + self.map.mode = Mode::View; + return; + } + let mut ui = std::mem::take(&mut self.map); + for ev in render::canvas_events() { + self.map_event(&mut ui, ev); + if ui.close { + break; + } + } + if ui.close { + ui.close = false; + self.map = ui; + self.map_close(); + return; + } + if ui.open { + if ui.follow + && let Some(Sel::Track(id)) = ui.sel + && let Some(t) = self.sim.picture().get(&id) + { + let e = t.est(self.sim.tick); + ui.centre = (e.x, e.z); + ui.dirty = true; + } + // The data moves at the sim's pace: a few redraws a second even when nothing is touched. + let step = self.sim.tick / 2; + if ui.dirty || ui.drawn != step { + ui.dirty = false; + ui.drawn = step; + let shapes = self.map_shapes(&mut ui); + render::set_canvas(&shapes); + } + } + self.map = ui; + } + + fn ground_y(&mut self, x: f64, z: f64) -> Option { + self.ground.at(DVec3::new(x, 0.0, z), self.sim.tick) + } + + fn map_event(&mut self, ui: &mut MapUi, ev: CanvasEvent) { + match ev { + CanvasEvent::Resized((w, h)) => { + ui.size = (w, h); + ui.dirty = true; + } + CanvasEvent::Moved(p) => { + ui.cursor = (p.x, p.y); + ui.dirty = true; + match &mut ui.drag { + Some(Drag::Pan { from, centre, moved }) => { + let (dx, dy) = (p.x - from.0, p.y - from.1); + if dx.hypot(dy) > 3.0 { + *moved = true; + } + if *moved { + ui.centre = (centre.0 - dx as f64 / ui.scale, centre.1 - dy as f64 / ui.scale); + ui.follow = false; + } + } + Some(Drag::Sam(i)) => { + let i = *i; + let (x, z) = ui.to_world((p.x, p.y)); + if let Some(y) = self.ground_y(x, z) + && let Some(d) = ui.draft.sams.get_mut(i) + { + d.pos = DVec3::new(x, y, z); + } + } + Some(Drag::Obj(i)) => { + let i = *i; + let (x, z) = ui.to_world((p.x, p.y)); + if let Some(y) = self.ground_y(x, z) + && let Some(d) = ui.draft.objs.get_mut(i) + { + d.pos = DVec3::new(x, y, z); + } + } + None => {} + } + } + CanvasEvent::Scrolled(s) => { + let at = (s.at.x, s.at.y); + let before = ui.to_world(at); + ui.scale = (ui.scale * 1.25f64.powf(s.steps as f64)).clamp(SCALE_MIN, SCALE_MAX); + // The point under the pointer stays under it. + ui.centre = (before.0 - (at.0 as f64 - ui.size.0 as f64 / 2.0) / ui.scale, before.1 - (at.1 as f64 - ui.size.1 as f64 / 2.0) / ui.scale); + ui.follow = false; + ui.dirty = true; + } + CanvasEvent::Pressed(b) => { + let at = (b.at.x, b.at.y); + ui.cursor = at; + ui.dirty = true; + if b.button == 0 { + let hit = ui.buttons.iter().find(|bt| at.0 >= bt.rect[0] && at.0 <= bt.rect[0] + bt.rect[2] && at.1 >= bt.rect[1] && at.1 <= bt.rect[1] + bt.rect[3]).map(|bt| bt.act); + if let Some(act) = hit { + self.map_act(ui, act); + return; + } + } + match (b.button, ui.mode) { + (0, Mode::Editor) => self.editor_press(ui, at), + (0 | 2, _) => { + ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false }); + } + (1, Mode::Editor) => self.editor_remove_at(ui, at), + (1, _) => self.map_right(ui, at), + _ => {} + } + } + CanvasEvent::Released(b) => { + let at = (b.at.x, b.at.y); + ui.cursor = at; + ui.dirty = true; + let drag = ui.drag.take(); + match drag { + Some(Drag::Pan { moved: false, .. }) if b.button == 0 => self.map_click(ui, at), + Some(Drag::Sam(_) | Drag::Obj(_)) => {} + _ => {} + } + } + CanvasEvent::Key(k) => self.map_key(ui, &k), + } + } + + fn map_key(&mut self, ui: &mut MapUi, key: &str) { + ui.dirty = true; + let step = (60.0 / ui.scale).max(2.0); + match key { + "key.keyboard.escape" => { + if ui.drag.is_some() { + ui.drag = None; + } else if ui.mode == Mode::Editor { + if ui.pick != Pick::None || ui.ed_sel.is_some() { + ui.pick = Pick::None; + ui.ed_sel = None; + } else { + ui.mode = Mode::View; + ui.draft = Draft::default(); + ui.note(self.sim.tick, "Расстановка отменена"); + } + } else if ui.mode != Mode::View { + ui.mode = Mode::View; + } else if ui.sel.is_some() { + ui.sel = None; + ui.follow = false; + } else { + ui.close = true; + } + } + "key.keyboard.m" => { + if ui.mode == Mode::Editor && (!ui.draft.sams.is_empty() || !ui.draft.objs.is_empty()) && self.draft_changed(ui) { + ui.note(self.sim.tick, "Есть неподтверждённые изменения: Enter подтвердить, Esc отмена"); + return; + } + ui.close = true; + } + "key.keyboard.left" => ui.centre.0 -= step, + "key.keyboard.right" => ui.centre.0 += step, + "key.keyboard.up" => ui.centre.1 -= step, + "key.keyboard.down" => ui.centre.1 += step, + "key.keyboard.equal" => self.map_zoom_centre(ui, 1.25), + "key.keyboard.minus" => self.map_zoom_centre(ui, 0.8), + "key.keyboard.c" => self.map_act(ui, Act::Player), + "key.keyboard.e" => self.map_act(ui, Act::Editor), + "key.keyboard.enter" if ui.mode == Mode::Editor => self.map_act(ui, Act::Confirm), + "key.keyboard.z" if ui.mode == Mode::Editor => self.map_act(ui, Act::Undo), + "key.keyboard.r" if ui.mode == Mode::Editor => self.map_act(ui, Act::Rotate), + "key.keyboard.delete" | "key.keyboard.backspace" if ui.mode == Mode::Editor => self.map_act(ui, Act::Delete), + "key.keyboard.f" => self.map_act(ui, Act::Follow), + k if k.len() == 14 && k.starts_with("key.keyboard.") && k.as_bytes()[13].is_ascii_digit() && k.as_bytes()[13] != b'0' => { + let n = (k.as_bytes()[13] - b'1') as usize; + if n < FILTERS.len() { + ui.filters[n] = !ui.filters[n]; + } + } + _ => {} + } + } + + fn map_zoom_centre(&mut self, ui: &mut MapUi, k: f64) { + ui.scale = (ui.scale * k).clamp(SCALE_MIN, SCALE_MAX); + } + + /// The draft differs from the layout. + fn draft_changed(&self, ui: &MapUi) -> bool { + let d = &ui.draft; + d.sams.iter().any(|s| match s.id { + None => !s.gone, + Some(id) => s.gone || self.sim.sams.iter().find(|x| x.id == id).is_none_or(|x| x.pos.distance(s.pos) > 0.01 || (x.heading - s.heading).abs() > 1e-6), + }) || d.objs.iter().any(|o| match o.idx { + None => !o.gone, + Some(i) => o.gone || self.sim.targets.get(i).is_none_or(|t| t.distance(o.pos) > 0.01), + }) + } + + /// Loads the layout into the draft the first time the editor needs it. + fn ensure_draft(&mut self, ui: &mut MapUi) { + if !ui.draft.sams.is_empty() || !ui.draft.objs.is_empty() { + return; + } + ui.draft.sams = self.sim.sams.iter().map(|s| DSam { id: Some(s.id), kind: s.kind, pos: s.pos, heading: s.heading, gone: false }).collect(); + ui.draft.objs = self.sim.targets.iter().enumerate().map(|(i, p)| DObj { idx: Some(i), pos: *p, gone: false }).collect(); + } + + fn battle(&self) -> bool { + !self.sim.drones.is_empty() || !self.sim.queue.is_empty() || self.sim.planning() + } + + fn map_act(&mut self, ui: &mut MapUi, act: Act) { + ui.dirty = true; + let tick = self.sim.tick; + match act { + Act::Filter(i) => ui.filters[i] = !ui.filters[i], + Act::Close => { + ui.close = true; + } + Act::Player => { + if let Some(p) = crate::player() { + ui.centre = (p.x, p.z); + ui.follow = false; + } + } + Act::Editor => { + if ui.mode == Mode::Editor { + if self.draft_changed(ui) { + ui.note(tick, "Есть неподтверждённые изменения: Enter подтвердить, «Отмена» сбросить"); + } else { + ui.mode = Mode::View; + ui.draft = Draft::default(); + } + } else if self.battle() { + ui.note(tick, "Бой идёт: расстановка закрыта до конца налёта"); + } else { + ui.enter_editor(); + self.ensure_draft(ui); + } + } + Act::Pick(p) => { + ui.pick = if ui.pick == p { Pick::None } else { p }; + ui.ed_sel = None; + } + Act::Cancel => { + ui.draft = Draft::default(); + ui.history.clear(); + ui.mode = Mode::View; + ui.pick = Pick::None; + ui.note(tick, "Изменения отменены, ничего не построено"); + } + Act::Undo => { + if let Some(d) = ui.history.pop() { + ui.draft = d; + ui.ed_sel = None; + } + } + Act::Rotate => { + let step = std::f64::consts::FRAC_PI_4; + match ui.ed_sel { + Some(EdSel::Sam(i)) => { + ui.push_history(); + if let Some(d) = ui.draft.sams.get_mut(i) { + d.heading += step; + } + } + _ => ui.heading += step, + } + } + Act::Delete => { + if let Some(s) = ui.ed_sel.take() { + ui.push_history(); + match s { + EdSel::Sam(i) => remove_dsam(&mut ui.draft, i), + EdSel::Obj(i) => remove_dobj(&mut ui.draft, i), + } + } + } + Act::Confirm => self.commit_draft(ui), + Act::Centre => { + if let Some(p) = self.sel_pos(ui) { + ui.centre = (p.x, p.z); + } + } + Act::Follow => { + if matches!(ui.sel, Some(Sel::Track(_))) { + ui.follow = !ui.follow; + } + } + Act::Guard => { + if let Some(Sel::Sam(id)) = ui.sel { + ui.mode = if ui.mode == Mode::Guard(id) { Mode::View } else { Mode::Guard(id) }; + } + } + Act::Sector => { + if let Some(Sel::Sam(id)) = ui.sel { + ui.mode = if matches!(ui.mode, Mode::Sector(i, _) if i == id) { Mode::View } else { Mode::Sector(id, None) }; + } + } + Act::SectorOff => { + if let Some(i) = self.sel_sam(ui) { + self.edit_doctrine(i, |d| d.sector = None); + } + ui.mode = Mode::View; + } + Act::Reserve => { + if let Some(i) = self.sel_sam(ui) { + self.edit_doctrine(i, |d| d.reserve = [0, 1, 2, 4, 8, 16].into_iter().find(|&r| r > d.reserve).unwrap_or(0)); + } + } + Act::Salvo => { + if let Some(i) = self.sel_sam(ui) { + self.edit_doctrine(i, |d| d.salvo = d.salvo.next()); + } + } + Act::ResetDoc => { + if let Some(i) = self.sel_sam(ui) { + self.edit_doctrine(i, |d| *d = Doctrine::default()); + } + ui.mode = Mode::View; + } + Act::Role(bit) => { + if let Some(i) = self.sel_sam(ui) { + let s = &mut self.sim.sams[i]; + s.roles ^= bit; + s.target = None; + s.gun_target = None; + self.dirty = true; + } + } + Act::Strike(site) => { + let Some(p) = crate::player() else { return }; + let mut out = sim::Out::default(); + match self.sim.order_strike(site, DVec3::new(p.x, p.y, p.z), &mut out) { + Ok(m) => { + say(&m); + ui.note(tick, "Ударная ракета пошла"); + } + Err(e) => { + ui.note(tick, e.clone()); + say(&e); + } + } + self.emit(out); + } + } + } + + fn sel_sam(&self, ui: &MapUi) -> Option { + match ui.sel { + Some(Sel::Sam(id)) => self.sim.sams.iter().position(|s| s.id == id), + _ => None, + } + } + + fn sel_pos(&self, ui: &MapUi) -> Option { + match ui.sel? { + Sel::Sam(id) => self.sim.sams.iter().find(|s| s.id == id).map(|s| s.pos), + Sel::Object(i) => self.sim.targets.get(i).copied(), + Sel::Site(id) => self.sim.strikes.get(id).and_then(|k| k.est.filter(|e| e.fix)).map(|e| DVec3::new(e.pos.x, 0.0, e.pos.y)), + Sel::Track(id) => self.sim.picture().get(&id).map(|t| t.est(self.sim.tick)), + } + } + + /// What is under the pointer: systems, objects, launch sites, then tracks. + fn pick_at(&self, ui: &MapUi, p: (f32, f32)) -> Option { + let near = |w: DVec3| { + let s = ui.to_screen(w.x, w.z); + (s.0 - p.0).hypot(s.1 - p.1) <= PICK_R + }; + if ui.filters[F_SAMS] { + if let Some(s) = self.sim.sams.iter().find(|s| near(s.pos)) { + return Some(Sel::Sam(s.id)); + } + } + if ui.filters[F_OBJECTS] { + if let Some(i) = self.sim.targets.iter().position(|t| near(*t)) { + return Some(Sel::Object(i)); + } + } + if ui.filters[F_SITES] { + for k in &self.sim.strikes.known { + if let Some(e) = k.est.filter(|e| e.fix) + && near(DVec3::new(e.pos.x, 0.0, e.pos.y)) + { + return Some(Sel::Site(k.site)); + } + } + } + if ui.filters[F_TRACKS] { + let now = self.sim.tick; + let pic = self.sim.picture(); + let mut best: Option<(f32, u32)> = None; + for (id, t) in &pic { + let e = t.est(now); + let s = ui.to_screen(e.x, e.z); + let d = (s.0 - p.0).hypot(s.1 - p.1); + if d <= PICK_R + 2.0 && best.is_none_or(|b| d < b.0) { + best = Some((d, *id)); + } + } + if let Some((_, id)) = best { + return Some(Sel::Track(id)); + } + } + None + } + + fn map_click(&mut self, ui: &mut MapUi, at: (f32, f32)) { + let hit = self.pick_at(ui, at); + match ui.mode { + Mode::Guard(id) => { + if let Some(Sel::Object(k)) = hit + && let Some(i) = self.sim.sams.iter().position(|s| s.id == id) + { + let g = self.sim.targets[k]; + self.edit_doctrine(i, |d| match d.guards.iter().position(|x| x.distance(g) < 16.0) { + Some(j) => { + d.guards.remove(j); + } + None => d.guards.push(g), + }); + } else if hit.is_none() { + ui.mode = Mode::View; + } + } + Mode::Sector(id, centre) => { + let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else { + ui.mode = Mode::View; + return; + }; + let (x, z) = ui.to_world(at); + let a = sim::heading_of(DVec3::new(x - self.sim.sams[i].pos.x, 0.0, z - self.sim.sams[i].pos.z)); + match centre { + None => ui.mode = Mode::Sector(id, Some(a)), + Some(c) => { + let half = sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI); + self.edit_doctrine(i, |d| d.sector = Some((c, half))); + ui.mode = Mode::View; + } + } + } + _ => { + ui.sel = hit; + ui.follow = false; + } + } + } + + /// Right button in the view: a mobile system selected drives to the point. + fn map_right(&mut self, ui: &mut MapUi, at: (f32, f32)) { + if let Some(i) = self.sel_sam(ui) + && self.sim.sams[i].kind.mobile() + { + let (x, z) = ui.to_world(at); + match self.ground_y(x, z) { + Some(y) => { + if self.sim.order_move(i, DVec3::new(x, y, z)) { + let s = &self.sim.sams[i]; + ui.note(self.sim.tick, format!("{} №{}: на марш, {}", s.kind.name(), i + 1, distance(s.pos.distance(DVec3::new(x, y, z))))); + } + } + None => ui.note(self.sim.tick, "Земля там не загружена: подождите и повторите"), + } + } else { + ui.sel = None; + ui.mode = Mode::View; + } + } + + // ------------------------------------------------------------------ the editor + + fn draft_pick(&self, ui: &MapUi, at: (f32, f32)) -> Option { + let near = |w: DVec3| { + let s = ui.to_screen(w.x, w.z); + (s.0 - at.0).hypot(s.1 - at.1) <= PICK_R + }; + if let Some(i) = ui.draft.sams.iter().position(|s| !s.gone && near(s.pos)) { + return Some(EdSel::Sam(i)); + } + ui.draft.objs.iter().position(|o| !o.gone && near(o.pos)).map(EdSel::Obj) + } + + fn editor_press(&mut self, ui: &mut MapUi, at: (f32, f32)) { + self.ensure_draft(ui); + if let Some(hit) = self.draft_pick(ui, at) { + ui.push_history(); + ui.ed_sel = Some(hit); + ui.drag = Some(match hit { + EdSel::Sam(i) => Drag::Sam(i), + EdSel::Obj(i) => Drag::Obj(i), + }); + return; + } + let (x, z) = ui.to_world(at); + match ui.pick { + Pick::None => { + ui.ed_sel = None; + ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false }); + } + p => { + let Some(y) = self.ground_y(x, z) else { + ui.note(self.sim.tick, "Земля здесь не загружена: подождите секунду и нажмите снова"); + return; + }; + ui.push_history(); + let pos = DVec3::new(x, y, z); + match p { + Pick::Sam(kind) => { + ui.draft.sams.push(DSam { id: None, kind, pos, heading: ui.heading, gone: false }); + ui.ed_sel = Some(EdSel::Sam(ui.draft.sams.len() - 1)); + } + Pick::Object => { + ui.draft.objs.push(DObj { idx: None, pos, gone: false }); + ui.ed_sel = Some(EdSel::Obj(ui.draft.objs.len() - 1)); + } + Pick::None => {} + } + } + } + } + + fn editor_remove_at(&mut self, ui: &mut MapUi, at: (f32, f32)) { + if let Some(hit) = self.draft_pick(ui, at) { + ui.push_history(); + match hit { + EdSel::Sam(i) => remove_dsam(&mut ui.draft, i), + EdSel::Obj(i) => remove_dobj(&mut ui.draft, i), + } + ui.ed_sel = None; + } else { + ui.pick = Pick::None; + } + } + + /// Builds what the draft says: nothing before this, and nothing is spent until it. + fn commit_draft(&mut self, ui: &mut MapUi) { + let tick = self.sim.tick; + if !self.draft_changed(ui) { + ui.mode = Mode::View; + ui.draft = Draft::default(); + return; + } + if self.battle() { + ui.note(tick, "Бой идёт: расстановка закрыта"); + return; + } + let d = std::mem::take(&mut ui.draft); + // Objects: removals from the end so the indices hold. + let mut gone: Vec = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect(); + gone.sort_unstable_by(|a, b| b.cmp(a)); + for o in &d.objs { + if let (Some(i), false) = (o.idx, o.gone) + && let Some(t) = self.sim.targets.get_mut(i) + { + *t = o.pos; + } + } + for i in gone { + if i < self.sim.targets.len() { + self.sim.targets.remove(i); + if i < self.sim.target_health.len() { + self.sim.target_health.remove(i); + } + } + } + for o in d.objs.iter().filter(|o| o.idx.is_none() && !o.gone) { + self.sim.targets.push(o.pos); + self.sim.target_health.push(100.0); + } + for s in &d.sams { + match (s.id, s.gone) { + (Some(id), true) => self.sim.sams.retain(|x| x.id != id), + (Some(id), false) => { + if let Some(i) = self.sim.sams.iter().position(|x| x.id == id) { + let moved = self.sim.sams[i].pos.distance(s.pos) > 0.01; + let sam = &mut self.sim.sams[i]; + sam.heading = s.heading; + if moved { + // Before the battle a unit is simply put down elsewhere. + sam.pos = s.pos; + sam.dest = None; + } + } + } + (None, false) => { + let id = self.sim.id(); + let mut sam = Sam::new(id, s.kind, s.pos, s.heading); + if let Some(r) = self.sim.roles.get(&s.kind) { + sam.roles = *r; + } + self.sim.sams.push(sam); + } + (None, true) => {} + } + } + self.dirty = true; + ui.mode = Mode::View; + ui.history.clear(); + ui.pick = Pick::None; + ui.ed_sel = None; + ui.sel = None; + ui.note(tick, "Расстановка подтверждена"); + } + + // ------------------------------------------------------------------ drawing + + fn map_shapes(&mut self, ui: &mut MapUi) -> Vec { + let mut s: Vec = Vec::with_capacity(2048); + ui.buttons.clear(); + let (w, h) = ui.size; + let now = self.sim.tick; + let editing = ui.mode == Mode::Editor; + let cur_world = ui.to_world(ui.cursor); + // The ground under the pointer is asked for while placing, so that the click finds it. + if editing || ui.pick != Pick::None { + let _ = self.ground_y(cur_world.0, cur_world.1); + } + // Chunks round the view's middle are loaded now and then, so a place looked at fills in. + if now >= ui.chunks_at + 10 && ui.scale >= 0.2 { + ui.chunks_at = now; + let (cx, cz) = ((ui.centre.0.floor() as i32) >> 4, (ui.centre.1.floor() as i32) >> 4); + let wanted: Vec<(i32, i32)> = (-2..2).flat_map(|dz| (-2..2).map(move |dx| (cx + dx, cz + dz))).collect(); + render::load_chunks(&wanted); + } + let draft = ui.draft.clone(); + // Terrain. + if ui.filters[F_TERRAIN] { + self.map_terrain(ui, &mut s); + } + self.map_grid(ui, &mut s); + // What covers what (editor). + let armed: Vec<(SamKind, DVec3)> = if editing { + draft.sams.iter().filter(|d| !d.gone && d.kind.range() > 0.0).map(|d| (d.kind, d.pos)).collect() + } else { + self.sim.sams.iter().filter(|x| x.alive() && x.kind.range() > 0.0).map(|x| (x.kind, x.pos)).collect() + }; + if editing { + let cell = 20.0f32; + let mut y = 0.0; + while y < h { + let mut x = 0.0; + while x < w { + let c = ui.to_world((x + cell / 2.0, y + cell / 2.0)); + let p = DVec3::new(c.0, 0.0, c.1); + let n = armed.iter().filter(|(k, pos)| reaches(*k, *pos, p)).count(); + if n > 0 { + s.push(fill(x, y, cell, cell, alpha(0x40FF60, if n == 1 { 0.10 } else { 0.18 }))); + } + x += cell; + } + y += cell; + } + } + // Reach rings. + if ui.filters[F_RINGS] { + let list: Vec<(SamKind, DVec3, bool)> = if editing { + draft.sams.iter().filter(|d| !d.gone).map(|d| (d.kind, d.pos, d.id.is_none())).collect() + } else { + self.sim.sams.iter().filter(|x| x.alive()).map(|x| (x.kind, x.pos, false)).collect() + }; + let many = list.len() > 12; + let picked = if editing { match ui.ed_sel { Some(EdSel::Sam(i)) => draft.sams.get(i).map(|d| d.pos), _ => None } } else { self.sel_pos(ui) }; + for (kind, pos, ghost) in list { + let r = kind.range(); + let chosen = picked.is_some_and(|p| p.distance(pos) < 1.0); + if r > 0.0 && (!many || chosen || ghost) { + let c = ui.to_screen(pos.x, pos.z); + ring(ui, &mut s, c, (r * ui.scale) as f32, 1.0, alpha(if ghost { 0xFFE070 } else { 0x40A0FF }, 0.75)); + } + } + } + // The selected system's sensor, sector and guards. + if let Some(i) = self.sel_sam(ui) { + let sam = &self.sim.sams[i]; + let c = ui.to_screen(sam.pos.x, sam.pos.z); + let sens = sam.kind.spec().sensor; + if sens > 0.0 { + ring(ui, &mut s, c, (sens * ui.scale) as f32, 1.0, alpha(0x80FF90, 0.45)); + } + self.map_sector(ui, &mut s, sam.pos, &sam.doctrine, sam.kind.range().max(200.0)); + for g in &sam.doctrine.guards { + let gp = ui.to_screen(g.x, g.z); + s.push(line(c, gp, 1.0, alpha(0xFFE070, 0.7))); + ring(ui, &mut s, gp, (sim::doctrine::GUARD_R * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.6)); + } + } + if let Mode::Sector(id, centre) = ui.mode + && let Some(sam) = self.sim.sams.iter().find(|x| x.id == id) + { + let a = sim::heading_of(DVec3::new(cur_world.0 - sam.pos.x, 0.0, cur_world.1 - sam.pos.z)); + let d = match centre { + None => Doctrine { sector: Some((a, 15f64.to_radians())), ..Default::default() }, + Some(c) => Doctrine { sector: Some((c, sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI))), ..Default::default() }, + }; + self.map_sector(ui, &mut s, sam.pos, &d, sam.kind.range().max(200.0)); + } + // Flights of the strike missiles. + for f in &self.sim.strikes.flights { + let a = ui.to_screen(f.from.x, f.from.z); + let b = ui.to_screen(f.aim.x, f.aim.y); + s.push(line(a, b, 1.0, alpha(0xFFA040, 0.5))); + let k = ((now.saturating_sub(f.start)) as f64 / (f.arrive.saturating_sub(f.start)).max(1) as f64).clamp(0.0, 1.0) as f32; + s.push(diamond(a.0 + (b.0 - a.0) * k, a.1 + (b.1 - a.1) * k, 3.0, ORANGE)); + } + // Objects. + if ui.filters[F_OBJECTS] { + let list: Vec<(usize, DVec3, bool)> = if editing { + draft.objs.iter().enumerate().filter(|(_, o)| !o.gone).map(|(i, o)| (i, o.pos, o.idx.is_none())).collect() + } else { + self.sim.targets.iter().enumerate().map(|(i, p)| (i, *p, false)).collect() + }; + for (i, p, ghost) in list { + let c = ui.to_screen(p.x, p.z); + if !ui.on_screen(c, 20.0) { + continue; + } + let covered = armed.iter().any(|(k, pos)| reaches(*k, *pos, p)); + let col = if !covered && (editing || !armed.is_empty()) { RED } else if ghost { YELLOW } else { WHITE }; + s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col)); + s.push(fill(c.0 - 2.5, c.1 - 2.5, 5.0, 5.0, 0xFF101010)); + if !editing { + let hp = self.sim.target_health.get(i).copied().unwrap_or(100.0); + s.push(text(format!("{}{}", i + 1, if hp < 100.0 { format!(" {hp:.0}%") } else { String::new() }), c.0 + 6.0, c.1 - 4.0, col)); + } else if !covered { + s.push(text("не прикрыт", c.0 + 6.0, c.1 - 4.0, RED)); + } + if ui.sel == Some(Sel::Object(i)) && !editing { + s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN)); + } + } + } + // Systems. + if ui.filters[F_SAMS] { + let list: Vec<(Option, SamKind, DVec3, f64, bool, bool, usize)> = if editing { + draft.sams.iter().enumerate().filter(|(_, d)| !d.gone).map(|(i, d)| (d.id, d.kind, d.pos, d.heading, d.id.is_none(), true, i)).collect() + } else { + self.sim.sams.iter().map(|x| (Some(x.id), x.kind, x.pos, x.heading, false, x.alive(), 0)).collect() + }; + for (id, kind, pos, heading, ghost, alive, di) in list { + let c = ui.to_screen(pos.x, pos.z); + if !ui.on_screen(c, 30.0) { + continue; + } + let col = if !alive { + 0xFF704040 + } else if ghost { + YELLOW + } else if kind.range() > 0.0 { + 0xFF40A0FF + } else { + 0xFF60D0A0 + }; + s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col)); + let (dx, dz) = dir_of(heading); + s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, col)); + if ui.scale > 0.12 && (self.sim.sams.len() <= 12 || ui.scale > 2.0) { + s.push(text(format!("{}", kind.name()), c.0 + 7.0, c.1 - 4.0, alpha(col, 0.95))); + } + let chosen = !editing && id.is_some() && ui.sel == id.map(Sel::Sam); + let ed = editing && ui.ed_sel == Some(EdSel::Sam(di)); + if chosen || ed { + s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN)); + } + } + } + // Launch sites the radars found. + if ui.filters[F_SITES] { + self.map_sites(ui, &mut s); + } + // Own interceptors. + for m in &self.sim.missiles { + let c = ui.to_screen(m.pos.x, m.pos.z); + if ui.on_screen(c, 4.0) { + s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, YELLOW)); + } + } + // The network's tracks. + if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] { + self.map_tracks(ui, &mut s); + } + // The truth, when the sandbox shows it, marked as such. + if self.sim.truth { + for d in &self.sim.drones { + let c = ui.to_screen(d.pos.x, d.pos.z); + if ui.on_screen(c, 4.0) { + s.extend(frame(c.0 - 3.0, c.1 - 3.0, 6.0, 6.0, 1.0, alpha(0xFF4040, 0.9))); + } + } + } + // The ghost under the pointer while placing. + if editing && let Some(y) = self.ground_y(cur_world.0, cur_world.1) { + let c = ui.cursor; + match ui.pick { + Pick::Sam(kind) => { + s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6))); + let (dx, dz) = dir_of(ui.heading); + s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, alpha(0xFFE070, 0.6))); + if kind.range() > 0.0 { + ring(ui, &mut s, c, (kind.range() * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.55)); + } + let _ = y; + } + Pick::Object => s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6))), + Pick::None => {} + } + } else if editing && ui.pick != Pick::None { + s.push(text("земля не загружена", ui.cursor.0 + 8.0, ui.cursor.1 + 8.0, RED)); + } + self.map_panels(ui, &mut s, &draft); + s.truncate(8000); + s + } + + fn map_terrain(&mut self, ui: &MapUi, s: &mut Vec) { + let (w, h) = ui.size; + let tl = ui.to_world((0.0, 0.0)); + let br = ui.to_world((w, h)); + let mut bpt = 1u32; + loop { + let span = 128.0 * bpt as f64; + let nx = ((br.0 - tl.0) / span).ceil() as i64 + 1; + let nz = ((br.1 - tl.1) / span).ceil() as i64 + 1; + if (nx * nz <= 20 && 128.0 * bpt as f64 * ui.scale >= 64.0) || bpt >= 64 { + break; + } + bpt *= 2; + } + let span = 128 * bpt as i32; + let (x0, z0) = ((tl.0.floor() as i32).div_euclid(span) * span, (tl.1.floor() as i32).div_euclid(span) * span); + let px = (span as f64 * ui.scale) as f32; + let mut z = z0; + let mut n = 0; + while (z as f64) < br.1 && n < 24 { + let mut x = x0; + while (x as f64) < br.0 && n < 24 { + let a = ui.to_screen(x as f64, z as f64); + s.push(Shape::Terrain(TerrainShape { rect: Rect { x: a.0, y: a.1, w: px, h: px }, x, z, blocks_per_texel: bpt })); + n += 1; + x += span; + } + z += span; + } + } + + fn map_grid(&self, ui: &MapUi, s: &mut Vec) { + let (w, h) = ui.size; + // A square of 1, 2, 5... x 10^n blocks that is at least 70 pixels wide. + let mut step = 10.0f64; + for m in [1.0, 2.0, 5.0].iter().cycle().zip(0..30).map(|(m, i)| m * 10f64.powi(1 + i / 3)) { + step = m; + if m * ui.scale >= 70.0 { + break; + } + } + let tl = ui.to_world((0.0, 0.0)); + let br = ui.to_world((w, h)); + let mut x = (tl.0 / step).floor() * step; + while x < br.0 { + let sx = ui.to_screen(x, 0.0).0; + s.push(fill(sx, 0.0, 1.0, h, 0x18FFFFFF)); + x += step; + } + let mut z = (tl.1 / step).floor() * step; + while z < br.1 { + let sy = ui.to_screen(0.0, z).1; + s.push(fill(0.0, sy, w, 1.0, 0x18FFFFFF)); + z += step; + } + // The scale bar. + let bar = (step * ui.scale) as f32; + s.push(fill(12.0, h - 16.0, bar, 2.0, WHITE)); + s.push(fill(12.0, h - 20.0, 1.0, 6.0, WHITE)); + s.push(fill(12.0 + bar, h - 20.0, 1.0, 6.0, WHITE)); + s.push(text(distance(step), 14.0, h - 30.0, WHITE)); + } + + fn map_sector(&self, ui: &MapUi, s: &mut Vec, pos: DVec3, d: &Doctrine, reach: f64) { + let Some((c, half)) = d.sector else { return }; + let o = ui.to_screen(pos.x, pos.z); + let r = (reach * ui.scale) as f32; + let n = ((half * 2.0 / 0.15) as usize).clamp(4, 48); + let at = |a: f64| { + let (dx, dz) = dir_of(a); + (o.0 + dx as f32 * r, o.1 + dz as f32 * r) + }; + let col = alpha(0xFFB040, 0.16); + for i in 0..n { + let a0 = c - half + half * 2.0 * i as f64 / n as f64; + let a1 = c - half + half * 2.0 * (i + 1) as f64 / n as f64; + s.push(Shape::Quad(QuadShape { corners: (pt(o.0, o.1), pt(at(a0).0, at(a0).1), pt(at(a1).0, at(a1).1), pt(o.0, o.1)), color: col })); + } + s.push(line(o, at(c - half), 1.0, alpha(0xFFB040, 0.8))); + s.push(line(o, at(c + half), 1.0, alpha(0xFFB040, 0.8))); + } + + fn map_sites(&self, ui: &MapUi, s: &mut Vec) { + let (w, h) = ui.size; + for k in &self.sim.strikes.known { + let Some(e) = k.est else { continue }; + let gone = matches!(k.state, SiteState::Destroyed(_)); + let col = if gone { 0xFF707070 } else { ORANGE }; + let chosen = ui.sel == Some(Sel::Site(k.site)); + if e.fix { + let c = ui.to_screen(e.pos.x, e.pos.y); + // The circle of error: the place is somewhere in it. + ring(ui, s, c, (e.radius * ui.scale) as f32, 1.0, alpha(col & 0xFFFFFF, 0.8)); + if ui.on_screen(c, 20.0) { + s.push(diamond(c.0, c.1, 5.0, col)); + s.push(diamond(c.0, c.1, 2.5, 0xFF101010)); + s.push(text(format!("ПУ {}{}", k.site, if gone { " ×" } else { "" }), c.0 + 8.0, c.1 - 4.0, col)); + if chosen { + s.extend(frame(c.0 - 9.0, c.1 - 9.0, 18.0, 18.0, 1.0, GREEN)); + } + } + } else { + // Only a bearing: a ray from where it was seen. + let o = ui.to_screen(e.origin.x, e.origin.y); + let (dx, dz) = (e.bearing.sin(), -e.bearing.cos()); + let len = (w.max(h) * 2.0) as f64; + let b = (o.0 + (dx * len) as f32, o.1 + (dz * len) as f32); + s.push(line(o, b, 1.0, alpha(0xFFA040, 0.35))); + // The ray's label where it crosses the screen's rim, near the origin when that is on the screen. + s.push(text(format!("ПУ {}: азимут {:.0}°", k.site, e.bearing.to_degrees()), (o.0 + dx as f32 * 40.0).clamp(4.0, w - 120.0), (o.1 + dz as f32 * 40.0).clamp(4.0, h - 10.0), alpha(0xFFA040, 0.9))); + } + } + } + + fn map_tracks(&self, ui: &MapUi, s: &mut Vec) { + let now = self.sim.tick; + let pic = self.sim.picture(); + for (id, t) in &pic { + let chosen = ui.sel == Some(Sel::Track(*id)); + if ui.filters[F_TRAILS] + && let Some(trail) = ui.trails.get(id) + { + let col = alpha(0xFF6060, if chosen { 0.95 } else { 0.5 }); + let mut prev: Option<(f32, f32)> = None; + for p in trail { + let c = ui.to_screen(p.0 as f64, p.1 as f64); + if let Some(a) = prev + && (ui.on_screen(a, 0.0) || ui.on_screen(c, 0.0)) + { + s.push(line(a, c, 1.0, col)); + } + prev = Some(c); + } + } + if !ui.filters[F_TRACKS] { + continue; + } + let age = t.age(now); + let forecast = t.forecast(now); + let e = t.est(now); + let c = ui.to_screen(e.x, e.z); + let m = ui.to_screen(t.pos.x, t.pos.z); + // The last measurement and the forecast from it: dashes, never drawn as a certainty. + if forecast { + s.push(line(m, c, 1.0, alpha(0xFFB0B0, 0.4))); + let r = (t.uncertainty(now) * ui.scale) as f32; + ring(ui, s, c, r.min(300.0), 1.0, alpha(0xFFB0B0, 0.5)); + } + if chosen { + // Ahead along the course for 30 s, dashed. + let v = t.vel; + let ahead = ui.to_screen(e.x + v.x * 600.0, e.z + v.z * 600.0); + dashed(s, c, ahead, alpha(0xFF8080, 0.8)); + } + if ui.on_screen(c, 12.0) { + let col = if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 }; + s.push(diamond(c.0, c.1, 4.0, col)); + if !forecast { + s.push(diamond(c.0, c.1, 2.0, 0xFF200808)); + } + if chosen || ui.scale > 0.5 { + s.push(text(format!("{}{}", if forecast { "~" } else { "" }, if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }), c.0 + 7.0, c.1 - 4.0, col)); + } + if chosen { + s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN)); + } + } + } + } + + // ------------------------------------------------------------------ the panels + + fn map_panels(&mut self, ui: &mut MapUi, s: &mut Vec, draft: &Draft) { + let (w, h) = ui.size; + let now = self.sim.tick; + let editing = ui.mode == Mode::Editor; + // The top bar: what the map shows, always said. + s.push(fill(0.0, 0.0, w, 14.0, PANEL)); + let head = if self.sim.truth { "КАРТА · ИСТИНА (песочница): красные рамки — настоящие дроны" } else { "КАРТА · режим: данные сети РЛС" }; + s.push(text(head, 6.0, 3.0, if self.sim.truth { YELLOW } else { GREEN })); + let cw = ui.to_world(ui.cursor); + let tail = format!("x {:.0} z {:.0}", cw.0, cw.1); + let tw = render::text_width(&tail); + s.push(text(tail, w - tw - 6.0, 3.0, GREY)); + // The left panel: filters and keys. + let mut y = 20.0; + s.push(fill(4.0, y - 3.0, 112.0, 14.0 * (FILTERS.len() as f32 + 1.0) + 8.0, PANEL)); + s.push(text("Слои (клавиши 1–7)", 8.0, y, GREY)); + y += 14.0; + for (i, name) in FILTERS.iter().enumerate() { + let on = ui.filters[i]; + let r = [6.0, y - 1.0, 108.0, 12.0]; + if hovered(ui, r) { + s.push(fill(r[0], r[1], r[2], r[3], 0x30FFFFFF)); + } + s.push(text(format!("{} {} {}", if on { "[x]" } else { "[ ]" }, i + 1, name), 9.0, y, if on { WHITE } else { GREY })); + ui.buttons.push(Btn { rect: r, act: Act::Filter(i) }); + y += 14.0; + } + y += 8.0; + // The mode buttons. + let mut bx = 6.0; + let button = |s: &mut Vec, ui: &mut MapUi, label: &str, act: Act, on: bool, x: f32, y: f32| -> f32 { + let bw = render::text_width(label) + 10.0; + let r = [x, y, bw, 14.0]; + let hv = hovered(ui, r); + s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0306040 } else if hv { 0xE0304038 } else { 0xE0182420 })); + s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { GREEN } else { 0x60FFFFFF })); + s.push(text(label, x + 5.0, y + 3.0, WHITE)); + ui.buttons.push(Btn { rect: r, act }); + bw + 4.0 + }; + bx += button(s, ui, "Правка (E)", Act::Editor, editing, bx, y); + bx += button(s, ui, "Игрок (C)", Act::Player, false, bx, y); + button(s, ui, "Выход (M)", Act::Close, false, bx, y); + // The keys. + let help = if editing { + "ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc" + } else { + "ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · ПКМ: марш · Esc" + }; + let hw = render::text_width(help); + s.push(fill(w / 2.0 - hw / 2.0 - 6.0, h - 16.0, hw + 12.0, 14.0, PANEL)); + s.push(text_c(help, w / 2.0, h - 13.0, GREY)); + // The note. + if let Some((n, until)) = ui.note.clone() { + if now < until { + let nw = render::text_width(&n); + s.push(fill(w / 2.0 - nw / 2.0 - 8.0, 22.0, nw + 16.0, 16.0, 0xE0302010)); + s.push(text_c(n, w / 2.0, 26.0, YELLOW)); + } else { + ui.note = None; + } + } + // The right card. + let cx = w - CARD_W - 2.0; + let mut lines: Vec<(String, u32)> = Vec::new(); + let mut btns: Vec<(String, Act, bool)> = Vec::new(); + if editing { + self.editor_card(ui, draft, &mut lines, &mut btns); + } else { + self.sel_card(ui, &mut lines, &mut btns); + } + // Long lines break at the card's width. + let mut wrapped: Vec<(String, u32)> = Vec::new(); + for (l, c) in lines { + let mut cur = String::new(); + for word in l.split(' ') { + let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") }; + if render::text_width(&try_) > CARD_W - 8.0 && !cur.is_empty() { + wrapped.push((std::mem::take(&mut cur), c)); + cur = word.to_string(); + } else { + cur = try_; + } + } + wrapped.push((cur, c)); + } + let lines = wrapped; + if !lines.is_empty() || !btns.is_empty() { + let mut y = 18.0; + let ch = lines.len() as f32 * 11.0 + btns.len() as f32 * 0.0 + 10.0; + // Buttons go in rows that wrap. + let mut rows: Vec> = vec![Vec::new()]; + let mut used = 0.0; + for (l, a, on) in btns { + let bw = render::text_width(&l) + 10.0; + if used + bw > CARD_W - 6.0 && !rows.last().unwrap().is_empty() { + rows.push(Vec::new()); + used = 0.0; + } + rows.last_mut().unwrap().push((l, a, on, bw)); + used += bw + 4.0; + } + let total = ch + rows.iter().filter(|r| !r.is_empty()).count() as f32 * 18.0 + 4.0; + s.push(fill(cx - 3.0, y - 3.0, CARD_W + 2.0, total, PANEL)); + for (l, c) in &lines { + s.push(text(l.as_str(), cx, y, *c)); + y += 11.0; + } + y += 6.0; + for row in rows { + let mut x = cx; + for (l, a, on, bw) in row { + let r = [x, y, bw, 14.0]; + let hv = hovered(ui, r); + s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0306040 } else if hv { 0xE0304038 } else { 0xE0182420 })); + s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { GREEN } else { 0x60FFFFFF })); + s.push(text(l.as_str(), x + 5.0, y + 3.0, WHITE)); + ui.buttons.push(Btn { rect: r, act: a }); + x += bw + 4.0; + } + y += 18.0; + } + } + // The editor's palette along the bottom. + if editing { + let mut kinds: Vec<(String, Pick)> = SamKind::ALL.iter().map(|k| (k.name().to_string(), Pick::Sam(*k))).collect(); + kinds.push(("Объект".into(), Pick::Object)); + // Rows first, so the palette sits just above the help line. + let mut rows = 1; + let mut used = 6.0; + for (label, _) in &kinds { + let bw = render::text_width(label) + 10.0; + if used + bw > w - 4.0 { + rows += 1; + used = 6.0; + } + used += bw + 4.0; + } + let mut x = 6.0; + let mut y = h - 18.0 - rows as f32 * 16.0; + s.push(fill(0.0, y - 3.0, w, rows as f32 * 16.0 + 4.0, PANEL)); + for (label, pick) in kinds { + let bw = render::text_width(&label) + 10.0; + if x + bw > w - 4.0 { + x = 6.0; + y += 16.0; + } + let on = ui.pick == pick; + let r = [x, y, bw, 14.0]; + let hv = hovered(ui, r); + s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0806020 } else if hv { 0xE0304038 } else { 0xE0182420 })); + s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { YELLOW } else { 0x60FFFFFF })); + s.push(text(label, x + 5.0, y + 3.0, WHITE)); + ui.buttons.push(Btn { rect: r, act: Act::Pick(pick) }); + x += bw + 4.0; + } + } + } + + fn editor_card(&self, ui: &MapUi, d: &Draft, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) { + lines.push(("РАССТАНОВКА ДО БОЯ".into(), YELLOW)); + lines.push(("Пока не подтвердите, ничего не строится.".into(), GREY)); + let new_s = d.sams.iter().filter(|s| s.id.is_none() && !s.gone).count(); + let gone_s = d.sams.iter().filter(|s| s.id.is_some() && s.gone).count(); + let new_o = d.objs.iter().filter(|o| o.idx.is_none() && !o.gone).count(); + let gone_o = d.objs.iter().filter(|o| o.idx.is_some() && o.gone).count(); + lines.push((format!("Новых: комплексов {new_s}, объектов {new_o}"), WHITE)); + lines.push((format!("Убрать: комплексов {gone_s}, объектов {gone_o}"), WHITE)); + if self.draft_changed(ui) { + lines.push(("Есть неподтверждённые изменения".into(), ORANGE)); + } + // The gaps: objects no system reaches. + let bare = d + .objs + .iter() + .filter(|o| !o.gone) + .filter(|o| !d.sams.iter().any(|s| !s.gone && reaches(s.kind, s.pos, o.pos))) + .count(); + lines.push((if bare == 0 { "Все объекты в зоне поражения".into() } else { format!("Без прикрытия: объектов {bare} (красные)") }, if bare == 0 { GREEN } else { RED })); + lines.push(("Зелёное: зона огня, тёмное: дыра".into(), GREY)); + match ui.pick { + Pick::Sam(k) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)), + Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)), + Pick::None => lines.push(("Выберите тип внизу".into(), GREY)), + } + btns.push(("Готово (Enter)".into(), Act::Confirm, false)); + btns.push(("Отмена".into(), Act::Cancel, false)); + btns.push(("Назад (Z)".into(), Act::Undo, false)); + btns.push(("Поворот (R)".into(), Act::Rotate, false)); + btns.push(("Убрать (Del)".into(), Act::Delete, false)); + } + + fn sel_card(&self, ui: &MapUi, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) { + let now = self.sim.tick; + match ui.sel { + Some(Sel::Sam(id)) => { + let Some((n, sam)) = self.sim.sams.iter().enumerate().find(|(_, s)| s.id == id) else { return }; + let k = sam.kind; + lines.push((format!("{} №{}", k.name(), n + 1), CYAN)); + 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() { + 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)); + } + if k.spec().sensor > 0.0 { + lines.push((format!("Свой обзор: {} (зелёное кольцо)", distance(k.spec().sensor)), WHITE)); + } + if let Some(t) = sam.gun_target.or(sam.target) { + lines.push((format!("Ведёт цель: трек №{t}"), YELLOW)); + } + if k.armed() { + lines.push(("Роли (кнопки): Д дроны, Г реактивные, К крылатые, С сверхзвук, Б баллистика".into(), GREY)); + lines.push((format!("Доктрина: {}", sam.doctrine.text(&self.sim.targets)), WHITE)); + for c in Class::ALL { + btns.push((c.letter().to_string(), Act::Role(c.bit()), sam.roles & c.bit() != 0)); + } + btns.push(("Охрана".into(), Act::Guard, matches!(ui.mode, Mode::Guard(i) if i == id))); + btns.push(("Сектор".into(), Act::Sector, matches!(ui.mode, Mode::Sector(i, _) if i == id))); + btns.push(("Без сектора".into(), Act::SectorOff, false)); + btns.push((format!("Резерв {}", sam.doctrine.reserve), Act::Reserve, false)); + btns.push((format!("Залп: {}", sam.doctrine.salvo.name()), Act::Salvo, false)); + btns.push(("Сброс".into(), Act::ResetDoc, false)); + match ui.mode { + Mode::Guard(_) => lines.push(("Нажимайте объекты на карте: охранять / не охранять. Esc — готово.".into(), YELLOW)), + Mode::Sector(_, None) => lines.push(("Сектор: щёлкните в сторону центра сектора.".into(), YELLOW)), + Mode::Sector(_, Some(_)) => lines.push(("Сектор: щёлкните, чтобы задать ширину.".into(), YELLOW)), + _ => {} + } + } + if k.mobile() { + lines.push(("ПКМ по земле — отправить на марш".into(), GREY)); + } + } + Some(Sel::Object(i)) => { + let Some(p) = self.sim.targets.get(i) else { return }; + lines.push((format!("Объект №{}", i + 1), WHITE)); + lines.push((format!("Прочность: {:.0}% {:.0} {:.0}", self.sim.target_health.get(i).copied().unwrap_or(100.0), p.x, p.z), GREY)); + let cover: Vec = self.sim.sams.iter().filter(|s| s.alive() && reaches(s.kind, s.pos, *p)).map(|s| s.kind.name().to_string()).collect(); + if cover.is_empty() { + lines.push(("НЕ ПРИКРЫТ: ни один комплекс не достаёт".into(), RED)); + } else { + lines.push((format!("Прикрыт: {}", cover.join(", ")), GREEN)); + } + let guards = self.sim.sams.iter().filter(|s| s.doctrine.guards.iter().any(|g| g.distance(*p) < 16.0)).count(); + if guards > 0 { + lines.push((format!("Охраняют по доктрине: {guards}"), WHITE)); + } + } + Some(Sel::Site(id)) => { + let Some(k) = self.sim.strikes.get(id) else { return }; + lines.push((format!("Пусковая №{id}: {}", class_name(k.class)), ORANGE)); + match (&k.est, k.state) { + (Some(e), st) => { + if e.fix { + lines.push((format!("Место известно: {:.0} {:.0} ± {}", e.pos.x, e.pos.y, distance(e.radius)), WHITE)); + } else { + lines.push((format!("Места не знаем, только азимут {:.0}°", e.bearing.to_degrees()), YELLOW)); + } + lines.push((format!("Точность: {}", sim::strike::accuracy(e)), WHITE)); + lines.push(( + match st { + SiteState::Active => "Состояние: действует".to_string(), + SiteState::Stunned(t) => format!("Состояние: подавлена ещё {} с", t.saturating_sub(now) / 20), + SiteState::Destroyed(_) => "Состояние: уничтожена".to_string(), + }, + WHITE, + )); + } + (None, _) => lines.push(("Данных нет".into(), GREY)), + } + lines.push((format!("Пусков замечено: {}; последний {} с назад", k.launches, now.saturating_sub(k.last) / 20), GREY)); + lines.push((format!("Ударных ракет: {}", self.sim.strikes.stock), WHITE)); + 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::Centre, false)); + } + Some(Sel::Track(id)) => { + let pic = self.sim.picture(); + let Some(t) = pic.get(&id) else { + lines.push((format!("Трек №{id}: потерян сетью"), GREY)); + return; + }; + lines.push((format!("Трек сети №{id}"), 0xFFFF8080)); + lines.push((format!("Опознание: {}", t.ident().name()), WHITE)); + let age = t.age(now); + lines.push(( + if t.forecast(now) { format!("ПРОГНОЗ: последнее измерение {} с назад", age / 20) } else { format!("Измерение {} с назад", age / 20) }, + if t.forecast(now) { YELLOW } else { GREEN }, + )); + lines.push((format!("Высота {:.0} м, скорость {:.0} км/ч", t.pos.y, t.vel.length() * 20.0 * 3.6), WHITE)); + lines.push((format!("Погрешность места до {}", distance(t.uncertainty(now))), GREY)); + lines.push(("Цель и маршрут неизвестны сети: тонкая линия —".into(), GREY)); + lines.push(("пройденное по измерениям, пунктир — прогноз курса.".into(), GREY)); + if let Some(trail) = ui.trails.get(&id) { + lines.push((format!("Точек измерений: {}", trail.len()), GREY)); + } + let who = self.who_tracks(t); + if !who.is_empty() { + lines.push((format!("Держат: {who}"), WHITE)); + } + btns.push(("В центр".into(), Act::Centre, false)); + btns.push(("Следить (F)".into(), Act::Follow, ui.follow)); + } + None => { + let live = self.sim.strikes.known.iter().filter(|k| !matches!(k.state, SiteState::Destroyed(_))).count(); + lines.push(("Ничего не выбрано".into(), GREY)); + lines.push((format!("Комплексов: {} · объектов: {}", self.sim.sams.len(), self.sim.targets.len()), WHITE)); + lines.push((format!("Целей у сети: {} · известных ПУ: {live}", self.sim.picture().len()), WHITE)); + if self.battle() { + lines.push(("Идёт налёт: расстановка закрыта".into(), YELLOW)); + } + } + } + } + + /// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's). + fn who_tracks(&self, t: &Track) -> String { + let n = self.sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count(); + if n == 0 { String::new() } else { format!("{n} комплексов") } + } +} + +fn remove_dsam(d: &mut Draft, i: usize) { + if let Some(s) = d.sams.get_mut(i) { + if s.id.is_some() { + s.gone = true; + } else { + d.sams.remove(i); + } + } +} + +fn remove_dobj(d: &mut Draft, i: usize) { + if let Some(o) = d.objs.get_mut(i) { + if o.idx.is_some() { + o.gone = true; + } else { + d.objs.remove(i); + } + } +} + +fn sim_angle_diff(from: f64, to: f64) -> f64 { + (to - from + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI +} + +fn hovered(ui: &MapUi, r: [f32; 4]) -> bool { + ui.cursor.0 >= r[0] && ui.cursor.0 <= r[0] + r[2] && ui.cursor.1 >= r[1] && ui.cursor.1 <= r[1] + r[3] +} + +/// A circle of `r` pixels round `c`, only the parts on the screen. +fn ring(ui: &MapUi, s: &mut Vec, c: (f32, f32), r: f32, w: f32, color: u32) { + if !r.is_finite() || r < 2.0 { + return; + } + // Wholly off the screen: the nearest the circle comes is |distance to the middle - r|. + let mid = (ui.size.0 / 2.0, ui.size.1 / 2.0); + let far = (c.0 - mid.0).hypot(c.1 - mid.1); + let reach = mid.0.hypot(mid.1); + if far - r > reach || r - far > reach { + return; + } + let n = ((r / 5.0) as usize).clamp(16, 120); + let mut prev = (c.0, c.1 - r); + for i in 1..=n { + let a = i as f32 / n as f32 * TAU; + let p = (c.0 + a.sin() * r, c.1 - a.cos() * r); + if ui.on_screen(p, 40.0) || ui.on_screen(prev, 40.0) { + s.push(line(prev, p, w, color)); + } + prev = p; + } +} + +fn dashed(s: &mut Vec, a: (f32, f32), b: (f32, f32), color: u32) { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = dx.hypot(dy); + let n = ((len / 8.0) as usize).min(200); + for i in (0..n).step_by(2) { + let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32); + s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.0, color)); + } +} diff --git a/airdef-mod/src/panel.rs b/airdef-mod/src/panel.rs index 15491bc..0a7dce4 100644 --- a/airdef-mod/src/panel.rs +++ b/airdef-mod/src/panel.rs @@ -67,6 +67,16 @@ pub fn summary(sim: &Sim, air: &[&Drone], player: DVec3) -> Vec { if hidden > 0 { lines.push(line(format!("Вне видимости РЛС: {hidden}"), GREY)); } + // The launch sites found, and the strike missiles (#101). + if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() { + let st = &sim.strikes; + let live = st.known.iter().filter(|k| !matches!(k.state, crate::sim::strike::SiteState::Destroyed(_))).count(); + let mut text = format!("Известных ПУ: {live} · ударных ракет: {}", st.stock); + if let Some(f) = st.flights.iter().map(|f| f.arrive.saturating_sub(sim.tick)).min() { + text += &format!(" · в полёте {} (до цели {} с)", st.flights.len(), f / 20); + } + lines.push(line(text, YELLOW)); + } if !sim.target_health.is_empty() { let list: Vec = sim.target_health.iter().map(|h| format!("{h:.0}%")).collect(); let worst = sim.target_health.iter().copied().fold(100.0, f64::min); diff --git a/airdef-mod/src/radar.rs b/airdef-mod/src/radar.rs index 9bc6c32..874d3ae 100644 --- a/airdef-mod/src/radar.rs +++ b/airdef-mod/src/radar.rs @@ -107,6 +107,44 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec { s.push(square(x, y, 1.0, 0xFFFFE060)); } } + // Launch sites the radars found: a diamond where the place is known (with the circle of its error), and a mark on + // the rim along the bearing when it is beyond the scope or only the bearing is known. + for k in &sim.strikes.known { + let Some(e) = &k.est else { continue }; + let gone = matches!(k.state, crate::sim::strike::SiteState::Destroyed(_)); + let color = if gone { 0xFF707070 } else { 0xFFFFA040 }; + let inside = e.fix.then(|| scope(DVec3::new(e.pos.x, player.y, e.pos.y))).flatten(); + if let Some((x, y, _)) = inside { + let q = 3.0; + s.push(quad(pt(x, y - q), pt(x + q, y), pt(x, y + q), pt(x - q, y), color)); + let rad = (e.radius / RANGE) as f32 * r; + if rad > 3.5 { + for i in 0..SEGMENTS { + let (a0, a1) = (i as f32 / SEGMENTS as f32 * tau, (i + 1) as f32 / SEGMENTS as f32 * tau); + if i % 2 == 0 { + let p = |a: f32, rr: f32| pt(x + a.sin() * rr, y - a.cos() * rr); + s.push(quad(p(a0, rad - 0.4), p(a0, rad + 0.4), p(a1, rad + 0.4), p(a1, rad - 0.4), alpha(color, 0.5))); + } + } + } + s.push(text(k.site.to_string(), x + 5.0, y - 9.0, color, false)); + } else { + // On the rim, along the bearing (compass: north up, east right). + let a = e.bearing as f32; + let (x, y) = (cx + a.sin() * (r - 3.0), cy - a.cos() * (r - 3.0)); + let q = if e.fix { 3.0 } else { 2.0 }; + s.push(quad(pt(x, y - q), pt(x + q, y), pt(x, y + q), pt(x - q, y), color)); + s.push(text(format!("{}{}", k.site, if e.fix { "" } else { "?" }), x - a.sin() * 8.0, y + a.cos() * -8.0 - 4.0, color, true)); + } + } + // Strike missiles in flight, on the same footing: a small bright dot where the scope reaches, else nothing. + for f in &sim.strikes.flights { + let t = (sim.tick.saturating_sub(f.start)) as f64 / (f.arrive - f.start).max(1) as f64; + let p = f.from.lerp(DVec3::new(f.aim.x, f.from.y, f.aim.y), t.min(1.0)); + if let Some((x, y, _)) = scope(p) { + s.push(square(x, y, 1.5, 0xFFFFFFA0)); + } + } let mut far = 0; // The air picture is what the systems' radars hold, as they last measured it (a track older than a second // is a forecast, dimmer); with no system deployed, everything as it is. diff --git a/airdef-mod/src/replay.rs b/airdef-mod/src/replay.rs index 2155b93..716f688 100644 --- a/airdef-mod/src/replay.rs +++ b/airdef-mod/src/replay.rs @@ -7,7 +7,7 @@ use crate::film::{self, Film}; use crate::panel::distance; use crate::sim::Ground; -use crate::sim::record::{EventKind, Recording, STEP, What}; +use crate::sim::record::{EventKind, Recording, STEP, StrikeResult, What}; use std::cell::Cell; use crate::sim::{Class, DroneKind, Out, Sim}; use glam::DVec3; @@ -137,6 +137,17 @@ fn outcome_note(outcome: crate::sim::outcome::Outcome) -> &'static str { } } +/// How a strike on a launch site ended, in words. +fn strike_word(result: StrikeResult) -> &'static str { + match result { + StrikeResult::Destroyed => "площадка уничтожена", + StrikeResult::Stunned => "площадка подавлена", + StrikeResult::Missed => "промах", + StrikeResult::Intercepted => "ракета сбита ПВО противника", + StrikeResult::Halted => "пуски прекращены (вне карты)", + } +} + /// What an event was, in a line. pub fn title(rec: &Recording, i: usize) -> String { let e = &rec.events[i]; @@ -151,6 +162,7 @@ pub fn title(rec: &Recording, i: usize) -> String { EventKind::SamLost { kind, index, .. } => format!("{} №{} уничтожен", kind.name(), index + 1), EventKind::Split { .. } => "«Орешник»: разделение боевых блоков".into(), EventKind::Crash { kind, .. } => format!("«{}» разбивается о препятствие", kind.spec().name), + EventKind::Strike { site, result } => format!("Удар по ПУ №{site}: {}", strike_word(result)), } } @@ -167,6 +179,7 @@ pub fn row(rec: &Recording, i: usize) -> String { EventKind::SamLost { kind, index, .. } => format!("{}-{} уничтожен", kind.name(), index + 1), EventKind::Split { .. } => "Орешник: разделение".into(), EventKind::Crash { kind, .. } => format!("{}: о рельеф", kind.spec().name), + EventKind::Strike { site, result } => format!("ПУ {site}: {}", strike_word(result)), }; format!("{} {what}", clock(e.at as f64)) } @@ -199,6 +212,7 @@ pub fn interest(rec: &Recording, i: usize) -> f64 { } EventKind::SamLost { .. } => 12.0, EventKind::Crash { power, .. } => power as f64, + EventKind::Strike { .. } => 0.0, EventKind::Split { drone } => { // The bus's split, not each block's. let first = rec.events.iter().position(|o| matches!(o.kind, EventKind::Split { .. })); @@ -216,6 +230,7 @@ fn clip(rec: &Recording, i: usize) -> Clip { EventKind::SamLost { .. } => (80.0, 90.0), EventKind::Split { .. } => (40.0, 170.0), EventKind::Crash { .. } => (120.0, 60.0), + EventKind::Strike { .. } => (60.0, 80.0), }; Clip { event: i, from: (at - before).max(0.0), to: (at + after).min(rec.len as f64) } } @@ -499,6 +514,12 @@ impl Player { EventKind::Hit { power, .. } | EventKind::Crash { 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", + EventKind::Strike { result: StrikeResult::Halted, .. } => continue, + EventKind::Strike { result, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][match result { + StrikeResult::Destroyed => 4, + StrikeResult::Intercepted => 0, + _ => 3, + }], }; let gain = if let EventKind::Kill { kind, outcome, .. } = e.kind { crate::sim::outcome::look(kind, outcome).2 } else { 1.0 }; out.sound(event, heard(e.pos), gain, 1.0); @@ -694,7 +715,7 @@ impl Player { 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::SamLost { .. } | EventKind::Strike { .. } => (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); @@ -953,6 +974,7 @@ impl Player { } 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)), + EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)), } } // Header, legend, time line. @@ -983,6 +1005,7 @@ impl Player { EventKind::Crash { .. } => 0xFF903020, EventKind::SamLost { .. } => 0xFFFF00FF, EventKind::Split { .. } => 0xFFFF9020, + EventKind::Strike { .. } => 0xFFFFA040, }; s.push(fill(x, ty - 2.0, 1.0, 7.0, c)); } diff --git a/airdef-mod/src/sim/doctrine.rs b/airdef-mod/src/sim/doctrine.rs new file mode 100644 index 0000000..9b3cc40 --- /dev/null +++ b/airdef-mod/src/sim/doctrine.rs @@ -0,0 +1,269 @@ +//! Fire doctrine (#47): what a system is told about its job beyond the roles. Protected objects (it fires +//! only at what threatens them), a sector of responsibility, a reserve of missiles held back for what +//! matters, and how many interceptors it asks for on one target. The predicates are shared by `step_sams` +//! (through `why::basis`) and the diagnostic; the default doctrine blocks nothing and changes nothing. +//! Everything is judged on the system's track (its forecast), never on the drone's true place. +use super::*; + +/// How many interceptors a system asks for on one target: the base shoot-look-shoot only, as now, or one more. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum Salvo { + Economy, + #[default] + Normal, + Heavy, +} + +impl Salvo { + pub fn name(self) -> &'static str { + match self { + Salvo::Economy => "экономный", + Salvo::Normal => "обычный", + Salvo::Heavy => "усиленный", + } + } + pub fn key(self) -> &'static str { + match self { + Salvo::Economy => "eco", + Salvo::Normal => "normal", + Salvo::Heavy => "heavy", + } + } + pub fn from_key(s: &str) -> Option { + [Salvo::Economy, Salvo::Normal, Salvo::Heavy].into_iter().find(|v| v.key() == s) + } + pub fn next(self) -> Salvo { + match self { + Salvo::Economy => Salvo::Normal, + Salvo::Normal => Salvo::Heavy, + Salvo::Heavy => Salvo::Economy, + } + } +} + +/// A system's doctrine. `Default` is the sandbox: no guards, no sector, no reserve, the usual salvo. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Doctrine { + /// Protected objects (their places): when any, the system fires only at what threatens one of them. + pub guards: Vec, + /// Sector of responsibility: centre (a yaw as `heading_of`, radians) and half-width. + pub sector: Option<(f64, f64)>, + /// Missiles held back: below this many, only what matters is shot at. + pub reserve: u32, + pub salvo: Salvo, +} + +/// Where a track counts as threatening an object: within this many blocks of it, or flying at it. +pub const GUARD_R: f64 = 120.0; +/// Most missiles one can reserve. +pub const MAX_RESERVE: u32 = 64; + +pub(super) const OUT_SECTOR: u8 = 1; +pub(super) const NO_THREAT: u8 = 2; +pub(super) const RESERVE: u8 = 4; + +impl Doctrine { + pub fn is_default(&self) -> bool { + *self == Doctrine::default() + } + + /// Whether the track is within the sector (judged from the system's place). + pub fn in_sector(&self, pos: DVec3, at: DVec3) -> bool { + self.sector.is_none_or(|(centre, half)| { + let to = at - pos; + to.x.hypot(to.z) < 30.0 || angle_diff(centre, heading_of(to)).abs() <= half + }) + } + + /// The first protected object the track threatens (its index in `guards`): near it, or flying towards it. + pub fn threatens(&self, track: &Track, now: u64) -> Option { + let at = track.est(now); + let slack = GUARD_R + track.uncertainty(now); + self.guards.iter().position(|g| { + let (dx, dz) = (g.x - at.x, g.z - at.z); + let near = dx.hypot(dz); + if near <= slack { + return true; + } + let (vx, vz) = (track.vel.x, track.vel.z); + let speed = vx.hypot(vz); + // Closing, and the line of flight passes the object within the slack. + speed > 1e-3 && vx * dx + vz * dz > 0.0 && (vx * dz - vz * dx).abs() / speed <= slack + }) + } + + /// Why the area (sector, protected objects) rules the track out; 0 is a pass. + pub fn area_blocks(&self, pos: DVec3, track: &Track, now: u64) -> u8 { + (if self.in_sector(pos, track.est(now)) { 0 } else { OUT_SECTOR }) | (if self.guards.is_empty() || self.threatens(track, now).is_some() { 0 } else { NO_THREAT }) + } + + /// What matters enough to spend the reserve: a ballistic missile, or anything about to hit. + pub fn matters(d: &Drone) -> bool { + d.kind.spec().class == Class::Ballistic || why::arrival(d) < why::URGENT + } + + /// The reserve holds the launch back: the magazine is at the reserve and the target doesn't matter. + pub fn reserve_blocks(&self, missiles: u32, d: &Drone) -> u8 { + if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d) { RESERVE } else { 0 } + } + + /// Interceptors this doctrine asks for on `d`: `why::needed` by default, the base only when economical, one more when heavy. + pub fn needed(&self, d: &Drone) -> u32 { + let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 }; + match self.salvo { + Salvo::Economy => base, + Salvo::Normal => why::needed(d), + Salvo::Heavy => why::needed(d) + 1, + } + } + + /// The sector in words (`90±45°`); degrees on the same scale as `/airdef doctrine ... sector`. + pub fn sector_text(&self) -> String { + match self.sector { + Some((c, h)) => format!("{:.0}±{:.0}°", c.to_degrees().rem_euclid(360.0), h.to_degrees()), + None => "круговой".to_string(), + } + } + + /// The doctrine as the player reads it, empty for the default. + pub fn text(&self, targets: &[DVec3]) -> String { + if self.is_default() { + return "обычная (без ограничений)".to_string(); + } + let guards = if self.guards.is_empty() { + "нет".to_string() + } else { + self.guards.iter().map(|g| object_name(targets, *g)).collect::>().join(", ") + }; + format!("охрана: {guards}; сектор: {}; резерв: {}; залп: {}", self.sector_text(), self.reserve, self.salvo.name()) + } + + /// One line of the save: `salvo reserve sector-centre sector-half guards x y z ...` (`-` for no sector). + pub fn save_text(&self) -> String { + let sector = self.sector.map_or("- -".to_string(), |(c, h)| format!("{c} {h}")); + let mut s = format!("{} {} {sector} {}", self.salvo.key(), self.reserve, self.guards.len()); + for g in &self.guards { + s += &format!(" {} {} {}", g.x, g.y, g.z); + } + s + } +} + +/// An object by number in the world's list ("объект №2"), else by place. +pub fn object_name(targets: &[DVec3], g: DVec3) -> String { + match targets.iter().position(|t| t.distance(g) < 16.0) { + Some(i) => format!("объект №{}", i + 1), + None => format!("точка {:.0} {:.0}", g.x, g.z), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn track(pos: DVec3, vel: DVec3) -> Track { + Track { id: 1, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false } + } + + #[test] + fn the_default_doctrine_blocks_nothing() { + let d = Doctrine::default(); + let t = track(DVec3::new(500.0, 100.0, 0.0), DVec3::ZERO); + assert_eq!(d.area_blocks(DVec3::ZERO, &t, 0), 0); + assert!(d.is_default()); + assert_eq!(Doctrine::default().save_text(), "normal 0 - - 0"); + } + + #[test] + fn a_sector_and_guards_rule_targets_out_by_their_tracks() { + let mut d = Doctrine::default(); + // North is yaw 0 (towards -z): a sector of 45 degrees either side of north. + d.sector = Some((0.0, 45f64.to_radians())); + let north = track(DVec3::new(0.0, 100.0, -800.0), DVec3::ZERO); + let south = track(DVec3::new(0.0, 100.0, 800.0), DVec3::ZERO); + assert_eq!(d.area_blocks(DVec3::ZERO, &north, 0), 0); + assert_eq!(d.area_blocks(DVec3::ZERO, &south, 0), OUT_SECTOR); + d.sector = None; + d.guards = vec![DVec3::new(1000.0, 70.0, 0.0)]; + // Flying at the object from afar threatens it; flying past, or away, doesn't. + let at = track(DVec3::new(-2000.0, 100.0, 10.0), DVec3::new(2.0, 0.0, 0.0)); + let past = track(DVec3::new(-2000.0, 100.0, 900.0), DVec3::new(2.0, 0.0, 0.0)); + let away = track(DVec3::new(-2000.0, 100.0, 0.0), DVec3::new(-2.0, 0.0, 0.0)); + assert_eq!(d.area_blocks(DVec3::ZERO, &at, 0), 0); + assert_eq!(d.area_blocks(DVec3::ZERO, &past, 0), NO_THREAT); + assert_eq!(d.area_blocks(DVec3::ZERO, &away, 0), NO_THREAT); + } + + #[test] + fn the_save_line_is_what_the_layout_reads() { + let mut d = Doctrine { salvo: Salvo::Economy, reserve: 3, ..Default::default() }; + d.sector = Some((1.5, 0.5)); + d.guards = vec![DVec3::new(1.0, 2.0, 3.0)]; + let text = format!("sam {} 0 70 0 0\ndoctrine 0 {}\n", SamKind::Patriot.key(), d.save_text()); + let l = crate::layout::Layout::parse(&text).unwrap(); + assert_eq!(l.doctrines, vec![(0, d)]); + assert!(crate::layout::Layout::parse("doctrine 0 loud 1 - - 0\n").is_err()); + assert!(crate::layout::Layout::parse("doctrine 0 eco 1 - - 2 1 2 3\n").is_err(), "guards cut short"); + } + + use super::sites::testland::{Land, serve}; + + /// One Patriot against one Shahed flying in from the north at its aim, the doctrine set before the raid: + /// the missiles it fired, the Shahed's ticks to its aim at the first launch, and the `why` lines at the end. + fn fire(doc: Doctrine) -> (u32, Option, Vec) { + let mut sim = Sim::new(5); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 70.0, 0.0), 0.0)); + sim.sams[0].roles = 0xFF; + sim.sams[0].doctrine = doc; + sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -600.0), DVec3::Z, DVec3::new(0.0, 70.0, -80.0)); + let (mut ground, land, mut out) = (Ground::default(), Land(|_, _| 64), Out::default()); + let mut first = None; + let mut lines: Vec = Vec::new(); + for _ in 0..900 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + if first.is_none() && sim.sams[0].fired > 0 { + first = sim.drones.first().map(why::arrival); + } + if sim.drones.iter().all(|d| !d.alive()) { + break; + } + // The explanation while the target is in the sky: all the lines it gave then. + if sim.tick % 10 == 0 { + lines.extend(sim.why(0).into_iter().map(|c| c.text)); + } + } + (sim.sams[0].fired, first, lines) + } + + // #47: the defaults fire as before; each setting changes the decision and `why` names it + #[test] + fn each_setting_changes_the_shot_and_why_says_which() { + let (base, first, w) = fire(Doctrine::default()); + assert!(base > 0, "the baseline never fired: {w:?}"); + let first = first.unwrap(); + assert!(first > why::URGENT, "the baseline fires late: {first}"); + let has = |text: &[String], what: &str| text.iter().any(|l| l.contains(what)); + // The raid comes from the north (yaw 0): a sector round north holds it, one round south does not. + let sector = |c: f64| Doctrine { sector: Some((f64::to_radians(c), f64::to_radians(40.0))), ..Default::default() }; + assert_eq!(fire(sector(0.0)).0, base, "a sector that holds the raid changes nothing"); + let (n, _, why) = fire(sector(180.0)); + assert_eq!(n, 0); + assert!(has(&why, "вне сектора"), "{why:?}"); + // A reserve above the magazine holds the shot until the target is urgent. + let (n, late, _) = fire(Doctrine { reserve: 64, ..Default::default() }); + assert!(n > 0 && late.unwrap() < why::URGENT, "{n} {late:?}"); + // An object far off the raid's line is no one's to guard here; the one it flies at is. + let (n, _, why) = fire(Doctrine { guards: vec![DVec3::new(0.0, 70.0, 50000.0)], ..Default::default() }); + assert_eq!(n, 0); + assert!(has(&why, "не угрожает"), "{why:?}"); + let (n, _, why) = fire(Doctrine { guards: vec![DVec3::new(0.0, 70.0, -80.0)], ..Default::default() }); + assert_eq!(n, base); + assert!(has(&why, "прикрывает"), "{why:?}"); + // Economical asks for no more interceptors than the usual, heavy no fewer. + let (eco, _, _) = fire(Doctrine { salvo: Salvo::Economy, ..Default::default() }); + let (heavy, _, _) = fire(Doctrine { salvo: Salvo::Heavy, ..Default::default() }); + assert!(eco <= base && base <= heavy, "{eco} {base} {heavy}"); + } +} diff --git a/airdef-mod/src/sim/logistics.rs b/airdef-mod/src/sim/logistics.rs index 1b29979..13a6a77 100644 --- a/airdef-mod/src/sim/logistics.rs +++ b/airdef-mod/src/sim/logistics.rs @@ -54,6 +54,7 @@ impl Sim { continue; } let at = truck.pos; + let truck_id = truck.id; // Where it was going: hand over, or load up. if let Some(job) = truck.job && let Some(j) = self.sams.iter().position(|s| s.id == job) @@ -73,7 +74,7 @@ impl Sim { // Stopped short of it (it drove off meanwhile): on to where it stands now. let to = self.sams[j].pos; let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); - self.order_move(t, to + side); + self.order_move_near(t, to + side, 3.5); continue; } else { self.sams[t].job = None; @@ -84,7 +85,7 @@ impl Sim { let next = if self.sams[t].cargo > 0 { self.sams .iter() - .filter(|s| s.empty && s.alive() && !s.moving() && !taken.contains(&s.id)) + .filter(|s| s.empty && s.alive() && !s.moving() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)) .min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) .map(|s| (s.id, s.pos)) } else { @@ -95,7 +96,7 @@ impl Sim { .then(|| { self.sams .iter() - .filter(|d| d.kind == SamKind::Depot && d.alive() && d.cargo > 0) + .filter(|d| d.kind == SamKind::Depot && d.alive() && d.cargo > 0 && !self.routes.out_of_reach(truck_id, d.id, now)) .min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) .map(|d| (d.id, d.pos)) }) @@ -106,7 +107,7 @@ impl Sim { // Stop beside it, not on it. let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); if to.distance(at) > HANDOVER { - self.order_move(t, to + side); + self.order_move_near(t, to + side, 3.5); } } } diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 5e3fdac..f6b4639 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -10,9 +10,11 @@ use glam::{DQuat, DVec3}; use std::collections::HashMap; mod damage; +pub mod doctrine; pub mod fires; mod raid; pub mod sites; +pub mod strike; pub mod record; mod sight; mod terrain; @@ -20,6 +22,7 @@ mod ew; pub mod lights; mod logistics; mod orders; +mod route; mod voices; pub mod outcome; mod units; @@ -1272,6 +1275,8 @@ pub struct Sam { pub fired: u32, /// The classes of target it engages (`Class::bit`s). pub roles: u8, + /// Its fire doctrine (#47): protected objects, sector, reserve, salvo. + pub doctrine: doctrine::Doctrine, /// 1 whole, 0 destroyed: a damaged system turns slower, sees less and hits worse. pub health: f64, /// Ticks its wreck still burns. @@ -1344,6 +1349,7 @@ impl Sam { kills: 0, fired: 0, roles: spec.roles, + doctrine: doctrine::Doctrine::default(), state: SamState::Search, launched: 0, health: 1.0, @@ -1509,8 +1515,12 @@ pub struct Sim { pub queue: Vec<(u64, Drone)>, /// The raid's launch sites and their jobs (#100). pub sites: sites::Sites, + /// Launch sites found by the radars, and the counter-strikes on them (#101). + pub strikes: strike::Strikes, /// A raid being planned. plan: Option, + /// The vehicles' ground routes, and the jobs the trucks found out of reach (#94). + routes: route::Routes, /// Each marked object's health, 0 to 100 (`targets`' order). pub target_health: Vec, /// The raid in progress, for its report. @@ -1580,7 +1590,9 @@ impl Sim { later: Vec::new(), queue: Vec::new(), sites: sites::Sites::default(), + strikes: strike::Strikes::new(), plan: None, + routes: Default::default(), target_health: Vec::new(), wave: None, rec: None, @@ -1710,6 +1722,7 @@ impl Sim { self.step_lights(ground, out); self.step_sams(ground, out); self.step_missiles(ground, out); + self.step_strikes(ground, player, out); self.step_fx(ground, out); self.draw_targets(out); self.draw_sites(out); @@ -2359,7 +2372,8 @@ impl Sim { // the forecast of the last measurement, never the true place. let drone = |tr: &Track| drone_at.get(&tr.id).map(|&k| &self.drones[k]); let claimed = |d: &Drone| why::claimed(d, &missile_on, had_target); - let needed = why::needed; + let doc = &me.doctrine; + let needed = |d: &Drone| doc.needed(d); let opts = why::Opts { last_chance: self.last_chance, far_shots: self.far_shots }; let target = spec.missile.as_ref().map(|load| { // A launcher with nothing to fire (reloading, empty, failed) claims no target: others take it. @@ -2396,7 +2410,7 @@ impl Sim { tracks .iter() .filter_map(|tr| drone(tr).map(|d| (tr, d))) - .filter(|(tr, d)| why::gun_candidate(roles, tr, now, gun.track, pos, d)) + .filter(|(tr, d)| why::gun_candidate(roles, doc, tr, now, gun.track, pos, d)) .map(|(tr, d)| { let busy = 1.0 + 2.0 * on_it(d) + if d.engaged > 0 { 1.5 } else { 0.0 }; (tr.est(now).distance(pos) * busy, d.id) diff --git a/airdef-mod/src/sim/orders.rs b/airdef-mod/src/sim/orders.rs index 20d5c4d..a368989 100644 --- a/airdef-mod/src/sim/orders.rs +++ b/airdef-mod/src/sim/orders.rs @@ -38,11 +38,18 @@ impl Sam { impl Sim { /// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear). pub fn order_move(&mut self, i: usize, to: DVec3) -> bool { + self.order_move_near(i, to, 0.0) + } + + /// The same, where arriving within `slack` blocks of `to` will do (a truck stops beside its job). + pub fn order_move_near(&mut self, i: usize, to: DVec3, slack: f64) -> bool { let Some(sam) = self.sams.get_mut(i) else { return false }; if !sam.alive() || !sam.kind.mobile() || sam.drive_speed() <= 0.0 { return false; } sam.dest = Some(to); + let route = route::Route::new(sam.pos, to, slack, sam.kind.climbs(), self.tick); + self.routes.map.insert(sam.id, route); sam.target = None; sam.gun_target = None; if sam.state != SamState::Moving { @@ -52,11 +59,17 @@ impl Sim { true } - /// Packing, driving and deploying, once a tick. + /// Packing, driving and deploying, once a tick. The way is searched on the ground the game has told of (a + /// few hundred cells a tick for all the vehicles); a vehicle stands while it waits, and stops with a word + /// when there is no way. pub(super) fn step_moves(&mut self, ground: &mut Ground, out: &mut Out) { let now = self.tick; - for sam in &mut self.sams { + let planners = self.routes.map.values().filter(|r| r.searching()).count().max(1); + let share = route::WORK_PER_TICK / planners; + let Sim { sams, routes, .. } = self; + for (n, sam) in sams.iter_mut().enumerate() { if !sam.alive() { + routes.map.remove(&sam.id); continue; } let spec = sam.kind.spec(); @@ -66,12 +79,16 @@ impl Sim { } match sam.state { SamState::Packing => { - // The launcher comes down for the march. + // The launcher comes down for the march; the way is searched meanwhile. sam.pitch += (0.0 - sam.pitch) * 0.06; sam.yaw = slew(sam.yaw, sam.heading, 0.04); sam.march = sam.march.saturating_sub(1); if sam.march == 0 { sam.state = SamState::Moving; + } else if let Some(r) = routes.map.get_mut(&sam.id) + && r.searching() + { + let _ = r.drive(ground, now, sam.pos, share); } } SamState::Moving => { @@ -80,14 +97,43 @@ impl Sim { sam.dest = None; } let Some(to) = sam.dest else { + routes.map.remove(&sam.id); sam.state = SamState::Deploying; sam.march = sam.kind.march_ticks(); continue; }; - let flat = horizontal(to - sam.pos); - if flat.length() < SPEED * 2.0 { - sam.pos = DVec3::new(to.x, sam.pos.y, to.z); + let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind.climbs(), now)); + let (go, last) = match route.drive(ground, now, sam.pos, share) { + route::Drive::Wait(why) => { + if route.waited(now) > 40 && !route.told { + route.told = true; + out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text())); + } + continue; + } + route::Drive::Fail(why) => { + out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text())); + // A truck leaves that job alone for a while, and takes another. + if let Some(job) = sam.job.take() { + routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR); + } + routes.map.remove(&sam.id); + sam.dest = None; + sam.state = SamState::Deploying; + sam.march = sam.kind.march_ticks(); + continue; + } + route::Drive::Go(p, last) => (p, last), + }; + let flat = horizontal(go - sam.pos); + if last && flat.length() < SPEED * 2.0 { + let partial = route.partial; + sam.pos = DVec3::new(go.x, sam.pos.y, go.z); sam.dest = None; + routes.map.remove(&sam.id); + if partial { + out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::Partial.text())); + } sam.state = SamState::Deploying; sam.march = sam.kind.march_ticks(); out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6); @@ -99,8 +145,24 @@ impl Sim { let turning = angle_diff(sam.heading, heading_of(flat)).abs(); let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2); let next = sam.pos + ahead * step; - let y = ground.at(next, now).unwrap_or(sam.pos.y); - sam.pos = DVec3::new(next.x, sam.pos.y + (y - sam.pos.y).clamp(-0.5, 0.5), next.z); + // The column ahead: a wall or a drop the grid missed turns the vehicle back to the planner. + let Some(y) = ground.at(next, now) else { + if route.wait_ahead() { + out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text())); + routes.map.remove(&sam.id); + sam.dest = None; + sam.state = SamState::Deploying; + sam.march = sam.kind.march_ticks(); + } + continue; + }; + route.ahead_ok(); + let rise = y - sam.pos.y; + if rise > route::STEP_UP || rise < -route::STEP_DOWN { + route.blocked_ahead(next, sam.pos); + continue; + } + sam.pos = DVec3::new(next.x, sam.pos.y + rise.clamp(-0.5, 0.5), next.z); sam.yaw = sam.heading; if now % 4 == 0 { out.particles("minecraft:campfire_cosy_smoke", sam.pos - ahead * 2.0 * spec.scale, 0.3, DVec3::new(0.0, 0.03, 0.0), 0.01, 1); diff --git a/airdef-mod/src/sim/raid.rs b/airdef-mod/src/sim/raid.rs index 23cff58..26df672 100644 --- a/airdef-mod/src/sim/raid.rs +++ b/airdef-mod/src/sim/raid.rs @@ -660,7 +660,12 @@ impl Sim { let mut cancelled = 0; for (t, d) in go { // A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it. - match self.site_slot(d.id) { + let from_site = self.sites.site_of(d.id); + let slot = self.site_slot(d.id); + if let (Some(site), sites::Slot::Go | sites::Slot::Air) = (from_site, &slot) { + self.scout_launch(d.id, site, d.kind, d.pos); + } + match slot { // Free: not a site's job. Air: an off-map site's drone, already in flight position. sites::Slot::Free | sites::Slot::Air => {} sites::Slot::Busy => { @@ -820,6 +825,13 @@ impl Sim { if !why.is_empty() { out.messages.push(format!("Неудачи ПВО: {why}")); } + // What the counter-strikes did to the raid (#101): the launches that never happened. + let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum(); + if cut > 0 { + let sites: Vec = self.strikes.cancelled.iter().filter(|c| c.1 > 0).map(|c| format!("№{}", c.0)).collect(); + out.messages.push(format!("Налёт сорван ударами по ПУ ({}): не взлетело {cut} из заявленных {}", sites.join(", "), w.size)); + } + self.strikes.cancelled.clear(); self.wave = None; } } diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index 52f1436..289ff9f 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -179,6 +179,22 @@ pub enum EventKind { Split { drone: u32 }, /// A drone's warhead went off against the land or a building short of its aim. Crash { drone: u32, kind: DroneKind, power: u32 }, + /// A counter-strike on a launch site landed (#101): where it landed and how it ended. Launch sites themselves are + /// not drawn in a replay. + Strike { site: u32, result: StrikeResult }, +} + +/// How a strike on a launch site ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum StrikeResult { + Destroyed, + /// The site was stunned for a while. + Stunned, + Missed, + /// Shot down by the enemy's cover. + Intercepted, + /// Off the map: its launches ended, nothing to see. + Halted, } #[derive(Clone, Copy, Debug)] @@ -336,6 +352,16 @@ pub fn kill_look(kind: DroneKind) -> (f32, u32, f32) { (size, life, gain) } +/// The fire a strike's end leaves (0: none): the wreck of a site burns long, a crater a while. +pub fn strike_power(result: StrikeResult) -> u32 { + match result { + StrikeResult::Destroyed => 3, + StrikeResult::Stunned => 2, + StrikeResult::Missed => 1, + StrikeResult::Intercepted | StrikeResult::Halted => 0, + } +} + /// A blast's look for an event: (fireball radius, ticks it burns). The live blasts use the same. pub fn blast_spec(kind: EventKind) -> (f32, u32) { const SIZE: [f32; 5] = [2.5, 4.5, 7.0, 10.0, 13.0]; @@ -351,6 +377,12 @@ pub fn blast_spec(kind: EventKind) -> (f32, u32) { } EventKind::SamLost { .. } => (8.0, 18 * 9), EventKind::Split { .. } => (2.0, 7 * 9), + EventKind::Strike { result, .. } => match result { + StrikeResult::Destroyed => (SIZE[4], LIFE[4] * 9), + StrikeResult::Stunned | StrikeResult::Missed => (SIZE[3], LIFE[3] * 9), + StrikeResult::Intercepted => (SIZE[0], LIFE[0] * 9), + StrikeResult::Halted => (0.0, 0), + }, } } @@ -382,6 +414,7 @@ pub fn replay_fires(rec: &Recording, t: f64) -> Vec { EventKind::Crash { power, .. } => power, EventKind::Hit { power, .. } => power.max(1), EventKind::SamLost { .. } => 2, + EventKind::Strike { result, .. } => strike_power(result), _ => continue, }; let (size, life) = (fires::size_for(power), fires::life_for(power)); @@ -518,6 +551,7 @@ impl Sim { self.ignite(pos, power.max(1), host) } EventKind::SamLost { sam, .. } => self.ignite(pos, 2, Some(sam)), + EventKind::Strike { result, .. } if strike_power(result) > 0 => self.ignite(pos, strike_power(result), None), _ => {} } if let Some(r) = &mut self.rec { diff --git a/airdef-mod/src/sim/route.rs b/airdef-mod/src/sim/route.rs new file mode 100644 index 0000000..abfe5e6 --- /dev/null +++ b/airdef-mod/src/sim/route.rs @@ -0,0 +1,579 @@ +//! Ground routes for the vehicles (#94): a march is no longer a straight line through the relief. A bounded +//! A* over a coarse grid of the land the game has told of finds a way that avoids cliffs, water and walls; it +//! is worked on a few hundred cells a tick, shared by all the vehicles, and it keeps its state between ticks. +//! Land the game has not answered yet is waited for (the search parks those edges and goes on elsewhere), and +//! after a while the vehicle goes as far as the known land; a place nobody can reach is refused with a reason. +//! While driving, the column ahead is checked once more (a wall the grid missed, a drop): the cell is marked bad +//! and the way is searched again. +use super::*; +use std::collections::{BinaryHeap, HashSet}; + +/// Cells opened a tick, all vehicles together. +pub(super) const WORK_PER_TICK: usize = 600; +/// Cells opened for one route before it settles for the nearest it got. +const MAX_NODES: usize = 24_000; +/// Ticks the search waits for land the game has not told of, before the vehicle goes as far as is known. +const WAIT_MAP: u64 = 300; +/// Ticks a driver waits for the column ahead. +const WAIT_AHEAD: u32 = 200; +/// Searches again, after a way was found blocked on the march, before giving up. +const REPLANS: u32 = 16; +/// The tallest step a vehicle climbs between two columns, and the deepest drop it takes. +pub(super) const STEP_UP: f64 = 1.5; +pub(super) const STEP_DOWN: f64 = 3.5; +/// Ticks a truck keeps away from a job it found unreachable. +pub(super) const UNREACHABLE_FOR: u64 = 3600; + +/// Why a vehicle waits or stops. +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Why { + /// Waiting for the game's answers about the land. + Map, + /// The place itself can't be driven to (cliff, water, wall). + Goal, + /// No way there over the known land. + NoWay, + /// The way was found blocked on the march, again and again. + Stuck, + /// The map did not come. + NoMap, + /// It drove as far as the land is known. + Partial, +} + +impl Why { + pub fn text(self) -> &'static str { + match self { + Why::Map => "ждёт карту местности", + Why::Goal => "туда не проехать: обрыв, вода или стена в точке назначения", + Why::NoWay => "прохода нет: путь перекрыт обрывами, водой или стенами", + Why::Stuck => "путь перекрыт на марше, объезда нет", + Why::NoMap => "карта местности не пришла, остался на месте", + Why::Partial => "дальше карта неизвестна: остановился на краю известного", + } + } +} + +/// What the route says a vehicle does this tick. +pub(super) enum Drive { + /// Stand: for the land, or the planner. + Wait(Why), + /// Drive at this point; whether it is the last, and the route ends short of the order. + Go(DVec3, bool), + /// Stop here, and say why. + Fail(Why), +} + +#[derive(Clone, Copy)] +struct Info { + h: f32, + ok: bool, +} + +enum Eval { + Ok(f32), + Bad, + Pending, +} + +#[derive(PartialEq)] +struct Open(f32, (i32, i32)); +impl Eq for Open {} +impl Ord for Open { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.0.total_cmp(&self.0) + } +} +impl PartialOrd for Open { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +#[derive(PartialEq)] +enum Phase { + Search, + Follow, +} + +/// One vehicle's way to its destination. +pub(super) struct Route { + dest: DVec3, + /// How near the destination counts (a truck stops beside its job); 0: the place itself. + slack: f64, + cell: i32, + slope: f64, + start: (i32, i32), + lo: (i32, i32), + hi: (i32, i32), + cells: HashMap<(i32, i32), Info>, + bad: HashSet<(i32, i32)>, + g: HashMap<(i32, i32), f32>, + came: HashMap<(i32, i32), (i32, i32)>, + open: BinaryHeap, + /// Edges waiting for a cell the game has not answered. + parked: Vec<((i32, i32), (i32, i32))>, + retry_at: u64, + stuck_since: Option, + /// The cell opened that is nearest the destination. + near: ((i32, i32), f64), + expanded: usize, + goal_checked: bool, + phase: Phase, + pts: Vec, + next: usize, + pub(super) partial: bool, + replans: u32, + ahead_wait: u32, + began: u64, + pub(super) told: bool, + failed: Option, +} + +impl Route { + pub(super) fn new(pos: DVec3, dest: DVec3, slack: f64, slope: f64, now: u64) -> Self { + let dist = horizontal(dest - pos).length(); + let cell = if dist <= 400.0 { 4 } else if dist <= 900.0 { 6 } else { 8 }; + let mut r = Self { + dest, + slack, + cell, + slope, + start: (0, 0), + lo: (0, 0), + hi: (0, 0), + cells: HashMap::new(), + bad: HashSet::new(), + g: HashMap::new(), + came: HashMap::new(), + open: BinaryHeap::new(), + parked: Vec::new(), + retry_at: 0, + stuck_since: None, + near: ((0, 0), f64::MAX), + expanded: 0, + goal_checked: slack > 0.0, + phase: Phase::Search, + pts: Vec::new(), + next: 0, + partial: false, + replans: 0, + ahead_wait: 0, + began: now, + told: false, + failed: None, + }; + r.restart(pos); + r + } + + fn cell_of(&self, p: DVec3) -> (i32, i32) { + ((p.x.floor() as i32).div_euclid(self.cell), (p.z.floor() as i32).div_euclid(self.cell)) + } + fn centre(&self, c: (i32, i32)) -> DVec3 { + let k = f64::from(self.cell); + DVec3::new((f64::from(c.0) + 0.5) * k, 0.0, (f64::from(c.1) + 0.5) * k) + } + fn to_goal(&self, c: (i32, i32)) -> f64 { + horizontal(self.centre(c) - self.dest).length() + } + fn is_goal(&self, c: (i32, i32)) -> bool { + if self.slack > 0.0 { self.to_goal(c) <= self.slack } else { c == self.cell_of(self.dest) } + } + + /// Searches afresh from `pos`, keeping the cells found bad. + fn restart(&mut self, pos: DVec3) { + self.start = self.cell_of(pos); + let goal = self.cell_of(self.dest); + let margin = (((self.start.0 - goal.0).abs().max((self.start.1 - goal.1).abs()) / 2).max(16)).min(64); + self.lo = (self.start.0.min(goal.0) - margin, self.start.1.min(goal.1) - margin); + self.hi = (self.start.0.max(goal.0) + margin, self.start.1.max(goal.1) + margin); + self.g.clear(); + self.came.clear(); + self.open.clear(); + self.parked.clear(); + self.pts.clear(); + self.next = 0; + self.phase = Phase::Search; + self.stuck_since = None; + self.expanded = 0; + self.near = (self.start, f64::MAX); + self.partial = false; + self.cells.insert(self.start, Info { h: pos.y as f32, ok: true }); + self.g.insert(self.start, 0.0); + let h = self.heur(self.start); + self.open.push(Open(h, self.start)); + } + + fn heur(&self, c: (i32, i32)) -> f32 { + (self.to_goal(c) * 1.1) as f32 + } + + fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32)) -> Eval { + if let Some(i) = self.cells.get(&c) { + return if i.ok { Eval::Ok(i.h) } else { Eval::Bad }; + } + if self.bad.contains(&c) { + return Eval::Bad; + } + let p = self.centre(c); + let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); + let verdict = match ground.column(x, z, 1024) { + None => return Eval::Pending, + Some(None) => Info { h: 0.0, ok: false }, + Some(Some(h)) => { + // The height is the top of what blocks motion or holds a fluid: water has nothing solid under it. + let top = DVec3::new(f64::from(x) + 0.5, h, f64::from(z) + 0.5); + match ground.world.sweep(top + DVec3::Y * 0.5, top - DVec3::Y * 0.5, false, now) { + world::Sweep::Hit { .. } => Info { h: h as f32, ok: true }, + world::Sweep::Clear => Info { h: h as f32, ok: false }, + world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Eval::Pending, + world::Sweep::Unknown { .. } => Info { h: h as f32, ok: false }, + } + } + }; + self.cells.insert(c, verdict); + if verdict.ok { Eval::Ok(verdict.h) } else { Eval::Bad } + } + + /// Relaxes the edge from the opened cell `c` to `nb`; parks it when the land between isn't known yet. + fn relax(&mut self, ground: &mut Ground, now: u64, c: (i32, i32), nb: (i32, i32)) { + if nb.0 < self.lo.0 || nb.1 < self.lo.1 || nb.0 > self.hi.0 || nb.1 > self.hi.1 { + return; + } + let (di, dj) = (nb.0 - c.0, nb.1 - c.1); + let len = if di != 0 && dj != 0 { std::f64::consts::SQRT_2 } else { 1.0 }; + let dist = len * f64::from(self.cell); + let Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return }; + let h1 = match self.eval(ground, now, nb) { + Eval::Ok(h) => f64::from(h), + Eval::Bad => return, + Eval::Pending => return self.park(c, nb), + }; + // A diagonal doesn't cut a corner of something in the way. + if di != 0 && dj != 0 { + for side in [(c.0 + di, c.1), (c.0, c.1 + dj)] { + match self.eval(ground, now, side) { + Eval::Ok(h) if (f64::from(h) - h0).abs() <= (self.slope * f64::from(self.cell)).max(STEP_UP) => {} + Eval::Pending => return self.park(c, nb), + _ => return, + } + } + } + // Between the centres: a wall one block thick or a ditch there is what the centres don't show. + let (a, b) = (self.centre(c), self.centre(nb)); + let mid = (a + b) * 0.5; + let hm = match ground.column(mid.x.floor() as i32, mid.z.floor() as i32, 1024) { + None => return self.park(c, nb), + Some(None) => return, + Some(Some(h)) => h, + }; + let half = dist * 0.5; + let allow = |l: f64| (self.slope * l).max(STEP_UP); + if (hm - h0).abs() > allow(half) || (h1 - hm).abs() > allow(half) || hm - h0 < -STEP_DOWN * (half / 2.0).max(1.0) { + return; + } + let dh = (h1 - h0).abs(); + if dh > allow(dist) { + return; + } + let cost = (dist + 2.0 * dh) as f32; + let ng = self.g.get(&c).copied().unwrap_or(0.0) + cost; + if self.g.get(&nb).is_none_or(|&g| ng < g) { + self.g.insert(nb, ng); + self.came.insert(nb, c); + self.open.push(Open(ng + self.heur(nb), nb)); + } + } + + fn park(&mut self, c: (i32, i32), nb: (i32, i32)) { + if self.parked.len() < 4096 { + self.parked.push((c, nb)); + } + } + + /// Works on the search: at most `budget` cells. + fn search(&mut self, ground: &mut Ground, now: u64, mut budget: usize) { + if !self.goal_checked { + match self.eval(ground, now, self.cell_of(self.dest)) { + Eval::Bad => { + self.failed = Some(Why::Goal); + return; + } + Eval::Ok(_) => self.goal_checked = true, + Eval::Pending => {} + } + } + if now >= self.retry_at && !self.parked.is_empty() { + self.retry_at = now + 6; + let parked = std::mem::take(&mut self.parked); + for (k, &(c, nb)) in parked.iter().enumerate() { + // The game loads the chunk of the first few, if it loads on request. + if k < 6 { + let p = self.centre(nb); + ground.want_chunk(((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4)); + } + self.relax(ground, now, c, nb); + } + } + let before = self.expanded; + while budget > 0 { + let Some(Open(f, c)) = self.open.pop() else { break }; + let g = self.g.get(&c).copied().unwrap_or(f32::INFINITY); + if f > g + self.heur(c) + 1e-3 { + continue; + } + budget -= 1; + self.expanded += 1; + if self.is_goal(c) { + self.finish(c, false); + return; + } + let d = self.to_goal(c); + if d < self.near.1 { + self.near = (c, d); + } + for (di, dj) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)] { + self.relax(ground, now, c, (c.0 + di, c.1 + dj)); + } + if self.expanded >= MAX_NODES { + self.settle(now); + return; + } + } + if self.expanded > before { + self.stuck_since = None; + } + if self.open.is_empty() { + if self.parked.is_empty() { + let goal = self.cell_of(self.dest); + self.failed = Some(if self.slack == 0.0 && !self.cells.get(&goal).is_none_or(|i| i.ok) { Why::Goal } else { Why::NoWay }); + } else { + let since = *self.stuck_since.get_or_insert(now); + if now.saturating_sub(since) > WAIT_MAP { + self.settle(now); + } + } + } else { + self.stuck_since = None; + } + } + + /// The land stays unknown (or the search is too big): the way to the nearest cell it got to. + fn settle(&mut self, _now: u64) { + let (c, d) = self.near; + let here = self.to_goal(self.start); + if c == self.start || here - d < f64::from(self.cell) * 2.0 { + self.failed = Some(Why::NoMap); + } else { + self.finish(c, true); + } + } + + /// The way to cell `c`, as points with the straight stretches dropped. + fn finish(&mut self, c: (i32, i32), partial: bool) { + let mut cells = vec![c]; + let mut k = c; + while let Some(&p) = self.came.get(&k) { + cells.push(p); + k = p; + if cells.len() > 100_000 { + break; + } + } + cells.reverse(); + let mut pts: Vec = Vec::new(); + for w in 1..cells.len() { + let dir = (cells[w].0 - cells[w - 1].0, cells[w].1 - cells[w - 1].1); + let last = w + 1 == cells.len(); + let turns = !last && (cells[w + 1].0 - cells[w].0, cells[w + 1].1 - cells[w].1) != dir; + if last || turns { + pts.push(self.centre(cells[w])); + } + } + let end = if partial || self.slack > 0.0 { self.centre(c) } else { self.dest }; + match pts.last_mut() { + Some(l) => *l = end, + None => pts.push(end), + } + self.pts = pts; + self.next = 0; + self.partial = partial; + self.phase = Phase::Follow; + } + + /// The column ahead stopped the vehicle: mark it, and search again from here. + pub(super) fn blocked_ahead(&mut self, at: DVec3, pos: DVec3) { + let c = self.cell_of(at); + if c != self.cell_of(pos) { + self.bad.insert(c); + self.cells.insert(c, Info { h: 0.0, ok: false }); + } else { + // In the cell itself: the stretch ahead, one cell on. + let d = horizontal(at - pos).normalize_or(DVec3::X) * f64::from(self.cell); + let c = self.cell_of(pos + d); + self.bad.insert(c); + self.cells.insert(c, Info { h: 0.0, ok: false }); + } + self.replans += 1; + if self.replans > REPLANS { + self.failed = Some(Why::Stuck); + } else { + self.restart(pos); + } + } + + /// Ticks the vehicle has waited for the land ahead; true when it has waited too long. + pub(super) fn wait_ahead(&mut self) -> bool { + self.ahead_wait += 1; + self.ahead_wait > WAIT_AHEAD + } + pub(super) fn ahead_ok(&mut self) { + self.ahead_wait = 0; + } + pub(super) fn waited(&self, now: u64) -> u64 { + now.saturating_sub(self.began) + } + + /// What the vehicle at `pos` does: works the search on its share of the tick, then follows the way. + pub(super) fn drive(&mut self, ground: &mut Ground, now: u64, pos: DVec3, budget: usize) -> Drive { + if self.phase == Phase::Search && self.failed.is_none() { + self.search(ground, now, budget); + } + if let Some(why) = self.failed { + return Drive::Fail(why); + } + if self.phase == Phase::Search { + return Drive::Wait(Why::Map); + } + let reach = f64::from(self.cell) * 0.7; + while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach { + self.next += 1; + } + Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len()) + } + + pub(super) fn searching(&self) -> bool { + self.phase == Phase::Search && self.failed.is_none() + } +} + +/// The routes of the vehicles that drive, by system id, and the jobs a truck found out of reach. +#[derive(Default)] +pub(super) struct Routes { + pub map: HashMap, + /// (truck id, the job's id) and until when the truck leaves it alone. + pub unreachable: HashMap<(u32, u32), u64>, +} + +impl Routes { + pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool { + self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now) + } +} + +impl SamKind { + /// The steepest slope (rise a block) it drives: trucks the least. + pub(super) fn climbs(self) -> f64 { + match self.spec().family { + Family::Truck => 0.5, + _ => 0.6, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The land as the game would tell it: the height map, and under it the blocks that are solid. + struct Src i32, B: Fn(i32, i32) -> i32> { + height: H, + floor: B, + } + impl i32, B: Fn(i32, i32) -> i32> world::WorldSource for Src { + fn solid(&self, x: i32, y: i32, z: i32) -> Option { + Some(y < (self.floor)(x, z)) + } + } + + fn answer i32, B: Fn(i32, i32) -> i32>(ground: &mut Ground, src: &Src, now: u64) { + let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (src.height)(x, z))).collect(); + ground.answer(columns, now); + let sections = ground.world.take_wanted(now); + ground.world.serve(src, sections, now); + } + + /// Drives a Patriot from the origin to `to` over land of the given heights (water: a height over a lower floor). + fn march i32, B: Fn(i32, i32) -> i32>(height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) { + let src = Src { height, floor }; + let mut sim = Sim::new(3); + sim.damage = false; + let mut ground = Ground::default(); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(0.5, 64.0, 0.5), 0.0)); + let mut out = Out::default(); + for _ in 0..3 { + sim.tick += 1; + answer(&mut ground, &src, sim.tick); + } + assert!(sim.order_move(0, to)); + let mut used = 0; + let mut worst = 0usize; + for _ in 0..ticks { + sim.tick += 1; + sim.step_moves(&mut ground, &mut out); + answer(&mut ground, &src, sim.tick); + used += 1; + let p = sim.sams[0].pos; + let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); + assert!(((src.height)(x, z) as f64) <= p.y + 2.5, "inside the land at {p:?}"); + assert!((src.floor)(x, z) >= (src.height)(x, z), "drove onto water at {p:?}"); + worst = worst.max(sim.routes.map.values().filter(|r| r.searching()).count()); + if !sim.sams[0].moving() { + break; + } + } + let _ = worst; + (sim, out, used) + } + + // A wall across the way, with a gap far to one side: the vehicle goes round and arrives. + #[test] + fn a_wall_with_a_gap_is_driven_round() { + let wall = |x: i32, z: i32| if (40..44).contains(&x) && (-60..=40).contains(&z) { 90 } else { 64 }; + let (sim, _, _) = march(wall, wall, DVec3::new(120.0, 64.0, 0.5), 6000); + let s = &sim.sams[0]; + assert!(!s.moving() && s.pos.distance(DVec3::new(120.0, 64.0, 0.5)) < 3.0, "ended at {:?} {:?}", s.pos, s.state); + } + + // A closed pocket: refused with a reason, no teleport and no drive into the wall. + #[test] + fn an_unreachable_place_is_refused() { + let walls = |x: i32, z: i32| if (60..64).contains(&x) && (-300..300).contains(&z) { 100 } else { 64 }; + let (sim, out, _) = march(walls, walls, DVec3::new(120.0, 64.0, 0.5), 6000); + let s = &sim.sams[0]; + assert!(!s.moving() && s.pos.x < 62.0, "{:?}", s.pos); + assert!(out.messages.iter().any(|m| m.contains("прохода нет") || m.contains("перекрыт") || m.contains("карта")), "{:?}", out.messages); + } + + // A lake (height 64 over a floor of 50) is no road: it is gone round, and a destination in it is refused. + #[test] + fn a_lake_is_not_a_road() { + let floor = |x: i32, z: i32| if (50..90).contains(&x) && z.abs() < 40 { 50 } else { 64 }; + let (sim, _, _) = march(|_, _| 64, floor, DVec3::new(130.0, 64.0, 0.5), 6000); + let s = &sim.sams[0]; + assert!(!s.moving() && s.pos.distance(DVec3::new(130.0, 64.0, 0.5)) < 3.0, "{:?}", s.pos); + let (sim, out, _) = march(|_, _| 64, floor, DVec3::new(70.0, 64.0, 0.5), 3000); + assert!(!sim.sams[0].moving() && sim.sams[0].pos.x < 10.0, "{:?}", sim.sams[0].pos); + assert!(out.messages.iter().any(|m| m.contains("не проехать")), "{:?}", out.messages); + } + + // Open ground: straight on, arrives. + #[test] + fn open_ground_is_driven_straight() { + let (sim, _, _) = march(|_, _| 64, |_, _| 64, DVec3::new(100.0, 64.0, 30.5), 1500); + let s = &sim.sams[0]; + assert!(!s.moving() && s.pos.distance(DVec3::new(100.0, 64.0, 30.5)) < 3.0, "{:?}", s.pos); + } +} diff --git a/airdef-mod/src/sim/sites.rs b/airdef-mod/src/sim/sites.rs index 495ef7d..ffdd760 100644 --- a/airdef-mod/src/sim/sites.rs +++ b/airdef-mod/src/sim/sites.rs @@ -54,9 +54,9 @@ impl SiteClass { /// Ticks between two launches from one site. pub fn cadence(self) -> u64 { match self { - SiteClass::Ramp => 3, - SiteClass::Launcher => 8, - SiteClass::Battery => 20, + SiteClass::Ramp => 15, + SiteClass::Launcher => 25, + SiteClass::Battery => 50, } } fn slots(self) -> u32 { @@ -474,7 +474,17 @@ impl Sim { /// many. (The counter-strike, #101, uses this.) pub fn destroy_site(&mut self, id: u32) -> u32 { // An off-map site is nowhere to be found: nothing to destroy. - let Some(s) = self.sites.list.iter_mut().find(|s| s.id == id && !s.offmap) else { return 0 }; + self.end_site(id, false) + } + + /// Ends a site's launches wherever it is, off the map too (a strike that would have hit it): the same as + /// destroying it, without anything to draw. + pub fn halt_site(&mut self, id: u32) -> u32 { + self.end_site(id, true) + } + + fn end_site(&mut self, id: u32, offmap: bool) -> u32 { + let Some(s) = self.sites.list.iter_mut().find(|s| s.id == id && (offmap || !s.offmap)) else { return 0 }; s.alive = false; s.stock = 0; let ids: Vec = self.sites.jobs.iter().filter(|j| j.1 == id).map(|j| j.0).collect(); diff --git a/airdef-mod/src/sim/strike.rs b/airdef-mod/src/sim/strike.rs new file mode 100644 index 0000000..54ec70a --- /dev/null +++ b/airdef-mod/src/sim/strike.rs @@ -0,0 +1,1129 @@ +//! Scouting the enemy's launch sites and the counter-strike (#101). +//! +//! **Finding a site.** Nothing is known by magic. A site shows itself two ways, and only to a radar that is up: +//! - a launch inside a radar's reach (low targets: the radio horizon, the hills): a *point* sighting, good to a few +//! percent of the distance; +//! - a launched drone held on a radar's own track: the track points back to where it came from, a *ray* from where it was +//! picked up, a few degrees wide, and the time since the launch (the alarm) at the drone's speed gives how far: a range +//! good to some percent plus a second of launch time. Two radars holding it give two sightings. A ballistic missile's arc +//! says more: a point sighting, a few percent of the range. +//! +//! The sightings of one site are combined by weighted least squares (`solve`): points average, a ray with a range is +//! a long thin ellipse along it, a bare ray pulls across itself only, and each weighs by how sure it is. The answer carries its own error (`radius`, the 90% circle), which +//! shrinks with the launches seen and with a second radar holding the same drones. A site whose sightings pin no place +//! down (bare rays along one line, a circle wider than `max_fix_radius`) is *a bearing*, not yet a place (no `fix`), and +//! cannot be struck. +//! +//! **Striking it.** `order_strike`: one of a few strike missiles (a stock that refills slowly), fired from where the +//! player stands at the *estimated* place. It flies `STRIKE_SPEED`; on arrival the enemy's cover may shoot it down; else +//! it lands with its own scatter. The true distance from the site decides: inside `HIT_R` the site is destroyed (stock +//! burnt, jobs cancelled, wreck and fire), inside `SUPPRESS_R` it is stunned for a while (its launches are delayed, not +//! cancelled), else it hit the ground beside it and nothing changed. So a badly known site is very likely a wasted missile. +//! +//! **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 glam::DVec2; + +/// Every number of the mechanic. +pub struct Tune { + /// Angular error of a track pointing back (radians, 1 sigma): 3 degrees. + pub track_sigma: f64, + /// The range from the time of flight: error as a part of the range, and ticks of launch time (times the speed). + pub range_sigma: (f64, f64), + /// A ballistic missile's launch point from its arc: error as a part of the distance, and the least. + pub ballistic_sigma: (f64, f64), + /// A launch seen by a radar in reach: error as a part of the distance, and the least (blocks). + pub seen_sigma: (f64, f64), + /// How high a launch is, for the radar's horizon (blocks over the ground). + pub launch_height: f64, + /// A site whose 90% circle is wider than this has no fix (blocks). + pub max_fix_radius: f64, + /// Accuracy words: a radius over `rough` is rough, over `fair` fair, else good. + pub rough: f64, + pub fair: f64, + /// Sightings kept for a site. + pub keep_obs: usize, + /// Strike missiles at the start and the most held, and ticks to make one more. + pub stock: u32, + pub stock_max: u32, + pub resupply: u32, + /// Blocks a tick, the farthest target (blocks), and the cruise height over the launch (blocks). + pub speed: f64, + pub range: f64, + pub height: f64, + /// The missile's own scatter at the aim (blocks, 1 sigma). + pub cep: f64, + /// Inside this distance of the site the strike destroys it; inside the second it only stuns it. + pub hit_r: f64, + pub suppress_r: f64, + /// Ticks a stunned site launches nothing. + pub suppress_ticks: u64, + /// The chance the enemy's cover shoots the missile down: none, light, heavy; and the shares of sites that have them. + pub cover_p: [f64; 3], + pub cover_share: [f64; 2], + /// Ticks the wreck of a destroyed site smokes. + pub burn: u64, + /// A launched drone not taken into account after this many ticks is forgotten. + pub scout_life: u64, +} + +pub const TUNE: Tune = Tune { + track_sigma: 0.052, + range_sigma: (0.08, 20.0), + ballistic_sigma: (0.05, 20.0), + seen_sigma: (0.04, 8.0), + launch_height: 4.0, + max_fix_radius: 800.0, + rough: 200.0, + fair: 60.0, + keep_obs: 64, + stock: 3, + stock_max: 4, + resupply: 6000, + speed: 8.0, + range: 4500.0, + height: 40.0, + cep: 14.0, + hit_r: 35.0, + suppress_r: 90.0, + suppress_ticks: 600, + cover_p: [0.0, 0.3, 0.65], + cover_share: [0.4, 0.75], + burn: 1800, + scout_life: 1800, +}; + +/// The circle is this many one-sigma lengths of the worst direction: it holds about nine in ten of the real errors. +const RADIUS_K: f64 = 3.0; + +/// One sighting: a point (`dir` none, `sigma` in blocks), a ray from `at` along `dir` (`sigma` in radians), or a ray with +/// a range on it (`range`: blocks from `at` to the site and its error): the track says where from, and the time since +/// the launch flash at the alarm, at the drone's speed, how far. +#[derive(Clone, Copy, Debug)] +pub struct Obs { + pub at: DVec2, + pub dir: Option, + pub sigma: f64, + pub range: Option<(f64, f64)>, +} + +impl Obs { + pub fn point(at: DVec2, sigma: f64) -> Obs { + Obs { at, dir: None, sigma, range: None } + } + pub fn ray(at: DVec2, dir: DVec2, sigma: f64) -> Obs { + Obs { at, dir: Some(dir), sigma, range: None } + } + /// Whether it pins a place down by itself. + fn places(&self) -> bool { + self.dir.is_none() || self.range.is_some() + } + /// Its weight matrix (a, b, c: symmetric 2x2) and the place it pulls towards, at the guess `p`. + fn pull(&self, p: DVec2) -> ((f64, f64, f64), DVec2) { + let Some(u) = self.dir else { + let w = 1.0 / (self.sigma * self.sigma); + return ((w, 0.0, w), self.at); + }; + // The part of the plane across the ray: I - u u^T; along it: u u^T. + let (ma, mb, mc) = (1.0 - u.x * u.x, -u.x * u.y, 1.0 - u.y * u.y); + let (na, nb, nc) = (u.x * u.x, u.x * u.y, u.y * u.y); + match self.range { + None => { + // How wide the ray is at the place: its angle times the distance (never trusted nearer than 300). + let r = (p - self.at).length().clamp(300.0, 12_000.0); + let w = 1.0 / (self.sigma * r).powi(2); + ((w * ma, w * mb, w * mc), self.at) + } + Some((r, sr)) => { + let (wc, wr) = (1.0 / (self.sigma * r.max(50.0)).powi(2), 1.0 / (sr * sr)); + ((wc * ma + wr * na, wc * mb + wr * nb, wc * mc + wr * nc), self.at + u * r) + } + } + } +} + +/// What the sightings say. +#[derive(Clone, Copy, Debug)] +pub struct Estimate { + /// Where (x, z), when there is a fix. + pub pos: DVec2, + /// The 90% circle, blocks; infinite without a fix. + pub radius: f64, + pub fix: bool, + /// The bearing the site lies on, from where it was seen (compass radians, north 0, east a quarter turn), and its error. + pub bearing: f64, + pub bearing_err: f64, + /// Where the bearing starts (the sightings' centre). + pub origin: DVec2, +} + +/// A compass bearing of `d` (x east, z south): north is -z. +pub fn compass(d: DVec2) -> f64 { + d.x.atan2(-d.y).rem_euclid(TAU) +} + +/// Combines sightings (weighted least squares). `None` for none. +pub fn solve(obs: &[Obs]) -> Option { + if obs.is_empty() { + return None; + } + let n = obs.len() as f64; + let origin = obs.iter().map(|o| o.at).sum::() / n; + let mean_dir = obs.iter().filter_map(|o| o.dir).sum::(); + let rays = obs.iter().filter(|o| o.dir.is_some()).count(); + let placed: Vec<&Obs> = obs.iter().filter(|o| o.places()).collect(); + // Where to start: the placing sightings' mean, else far along the rays' mean. + let mut p = if placed.is_empty() { + origin + mean_dir.normalize_or_zero() * 1500.0 + } else { + placed.iter().map(|o| o.pull(origin).1).sum::() / placed.len() as f64 + }; + let (mut lmin, mut ok) = (0.0, false); + for _ in 0..4 { + let (mut a, mut b, mut c) = (0.0, 0.0, 0.0); + let mut v = DVec2::ZERO; + for o in obs { + let ((ma, mb, mc), m) = o.pull(p); + a += ma; + b += mb; + c += mc; + v += DVec2::new(ma * m.x + mb * m.y, mb * m.x + mc * m.y); + } + let det = a * c - b * b; + let half = (a + c) / 2.0; + let rad = (((a - c) / 2.0).powi(2) + b * b).sqrt(); + lmin = half - rad; + if det <= 1e-30 || lmin <= 1e-14 { + ok = false; + break; + } + p = DVec2::new((c * v.x - b * v.y) / det, (a * v.y - b * v.x) / det); + ok = true; + } + let radius = if ok && lmin > 0.0 { RADIUS_K / lmin.sqrt() } else { f64::INFINITY }; + // Bare rays must run towards the place, not away from it, and a circle wider than half the way to it is no fix. + let ahead = ok && (!placed.is_empty() || (p - origin).dot(mean_dir.normalize_or_zero()) > 150.0); + let far = (p - origin).length(); + let fix = ok && ahead && p.is_finite() && radius <= TUNE.max_fix_radius && (!placed.is_empty() || radius < 0.5 * far); + let bearing_err = if rays == 0 { 0.02 } else { obs.iter().filter(|o| o.dir.is_some()).map(|o| o.sigma).fold(0.0, f64::max) / (rays as f64).sqrt() }; + let bearing = if fix || rays == 0 { compass(p - origin) } else { compass(mean_dir) }; + Some(Estimate { pos: if fix { p } else { origin }, radius: if fix { radius } else { f64::INFINITY }, fix, bearing, bearing_err, origin }) +} + +/// What the player is told of the accuracy. +pub fn accuracy(e: &Estimate) -> &'static str { + if !e.fix { + "только азимут" + } else if e.radius > TUNE.rough { + "грубо" + } else if e.radius > TUNE.fair { + "средне" + } else { + "точно" + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum SiteState { + Active, + /// Stunned until this tick. + Stunned(u64), + /// Destroyed (or, off the map, halted) at this tick. + Destroyed(u64), +} + +/// A site the player's radars have found. +#[derive(Clone, Debug)] +pub struct Known { + pub site: u32, + pub class: SiteClass, + pub obs: Vec, + pub est: Option, + /// Launches seen, and when the last was. + pub launches: u32, + pub last: u64, + pub state: SiteState, + /// What a strike taught of its cover (0 none, 1 light, 2 heavy). + pub cover: Option, + /// Where the strike on it is aimed, if one is on its way. + pub aimed: bool, +} + +/// A launched drone still to be picked up on a track: (drone, site, class, launched at). +#[derive(Clone, Copy, Debug)] +struct Flown { + drone: u32, + site: u32, + class: SiteClass, + at: u64, +} + +/// A strike missile in flight. +#[derive(Clone, Copy, Debug)] +pub struct Flight { + pub id: u32, + pub site: u32, + pub from: DVec3, + /// The aim (x, z). + pub aim: DVec2, + pub start: u64, + pub arrive: u64, +} + +#[derive(Default)] +pub struct Strikes { + /// Strike missiles left, and ticks towards the next. + pub stock: u32, + pub progress: u32, + pub known: Vec, + pub flights: Vec, + flown: Vec, + next: u32, + /// Smoking wrecks: (where, until). + wrecks: Vec<(DVec3, u64)>, + /// Cancelled launches by strike this raid: (site, count), for the raid's report. + pub cancelled: Vec<(u32, u32)>, + /// News for the player, said at the next step. + news: Vec, + /// Strikes: fired, destroyed, stunned, missed, shot down. + pub fired: u32, + pub destroyed: u32, + pub stunned: u32, + pub missed: u32, + pub shot_down: u32, + /// The enemy's cover forced (tests); else it follows the seed. + pub cover_override: Option, +} + +impl Strikes { + pub fn new() -> Self { + Strikes { stock: TUNE.stock, ..Default::default() } + } + /// The stock and its progress as saved: clamped to what is possible. + pub fn restore(&mut self, stock: u32, progress: u32) { + self.stock = stock.min(TUNE.stock_max); + self.progress = if self.stock >= TUNE.stock_max { 0 } else { progress.min(TUNE.resupply - 1) }; + } + pub fn get(&self, site: u32) -> Option<&Known> { + self.known.iter().find(|k| k.site == site) + } + /// Seconds until the next missile is ready. + pub fn seconds_to_next(&self) -> u32 { + (TUNE.resupply - self.progress.min(TUNE.resupply)) / 20 + } +} + +/// A standard normal from the seed and three numbers (the combat's random sequence is left alone). +fn gauss(seed: u64, a: u64, b: u64, c: u64) -> f64 { + let d = |k| dice(seed, a, b, c * 4 + k); + (d(0) + d(1) + d(2) - 1.5) * 2.0 +} + +/// The words for a wind. +fn wind(bearing: f64) -> &'static str { + ["С", "СВ", "В", "ЮВ", "Ю", "ЮЗ", "З", "СЗ"][((bearing / (TAU / 8.0)).round() as usize) % 8] +} + +fn class_name(c: SiteClass) -> &'static str { + match c { + SiteClass::Ramp => "дроны", + SiteClass::Launcher => "крылатые", + SiteClass::Battery => "баллистические", + } +} + +impl Known { + /// A line for the list: how far and where from `from`, how sure, and what was seen of it. + pub fn line(&self, from: DVec3, now: u64) -> String { + let place = match &self.est { + Some(e) if e.fix => { + let d = e.pos - DVec2::new(from.x, from.z); + format!("{:.0}° {}, {}, ±{:.0} м ({})", compass(d).to_degrees(), wind(compass(d)), crate::panel::distance(d.length()), e.radius, accuracy(e)) + } + Some(e) => format!("{:.0}° {} ±{:.0}°, дальность неизвестна (только азимут)", e.bearing.to_degrees(), wind(e.bearing), e.bearing_err.to_degrees().max(1.0)), + None => "место неизвестно".into(), + }; + let state = match self.state { + SiteState::Destroyed(_) => " · УНИЧТОЖЕНА".to_string(), + SiteState::Stunned(until) if until > now => format!(" · подавлена ещё {} с", (until - now) / 20), + _ => { + if self.launches == 0 { + String::new() + } else if now.saturating_sub(self.last) < 600 { + " · ведёт пуски".to_string() + } else { + " · тихо".to_string() + } + } + }; + let cover = match self.cover { + Some(0) => " · ПВО не прикрыта", + Some(_) => " · прикрыта ПВО", + None => "", + }; + format!("ПУ №{} ({}): {place}{state}{cover}; пусков замечено {}", self.site, class_name(self.class), self.launches) + } +} + +impl Sim { + /// Whether the enemy covers this site: 0 none, 1 light, 2 heavy; fixed by the seed and the site. + pub fn cover_of(&self, site: &LaunchSite) -> u8 { + if let Some(c) = self.strikes.cover_override { + return c; + } + let r = dice(self.seed, site.id as u64, site.side as u64, 101); + // A ballistic battery is a prize: guarded more often. + let r = if site.class == SiteClass::Battery { r * 0.7 } else { r }; + if r < TUNE.cover_share[0] { + 0 + } else if r < TUNE.cover_share[1] { + 1 + } else { + 2 + } + } + + /// A drone just left site `site` (a launch the radars may have seen). + pub(super) fn scout_launch(&mut self, drone: u32, site: u32, kind: DroneKind, at: DVec3) { + let Some(s) = self.sites.get(site) else { return }; + let (class, offmap, pos) = (s.class, s.offmap, s.pos); + if self.strikes.flown.len() < 400 { + self.strikes.flown.push(Flown { drone, site, class, at: self.tick }); + } + if offmap { + return; + } + // Seen at the launch by a radar that is up and in reach. + let height = TUNE.launch_height; + let mut seen: Option = None; + for sam in self.sams.iter().filter(|s| s.radar_up()) { + let dist = horizontal(sam.pos - at).length(); + if dist > sight::reach(sam, kind, height) { + continue; + } + if self.horizons.get(&sam.id).is_some_and(|h| h.hides(sight::antenna(sam), at)) { + continue; + } + seen = Some(seen.map_or(dist, |d: f64| d.min(dist))); + } + if let Some(dist) = seen { + let sigma = (dist * TUNE.seen_sigma.0).max(TUNE.seen_sigma.1); + let (gx, gz) = (gauss(self.seed, drone as u64, site as u64, 1), gauss(self.seed, drone as u64, site as u64, 2)); + let at = DVec2::new(pos.x + gx * sigma, pos.z + gz * sigma); + self.add_obs(site, class, Obs::point(at, sigma)); + } + } + + /// A sighting of a site: kept, the estimate redone, the player told of news. + fn add_obs(&mut self, site: u32, class: SiteClass, obs: Obs) { + let now = self.tick; + let i = match self.strikes.known.iter().position(|k| k.site == site) { + Some(i) => i, + None => { + self.strikes.known.push(Known { site, class, obs: Vec::new(), est: None, launches: 0, last: now, state: SiteState::Active, cover: None, aimed: false }); + self.strikes.known.len() - 1 + } + }; + let before = self.strikes.known[i].est; + let k = &mut self.strikes.known[i]; + k.obs.push(obs); + if k.obs.len() > TUNE.keep_obs { + k.obs.remove(0); + } + // Every sighting is a launch seen, by the radar at the pad or by the track of what left it. + k.launches += 1; + k.last = now; + k.est = solve(&k.obs); + let first = before.is_none(); + let words = |e: &Option| e.as_ref().map(accuracy); + let msg = match (&before, &k.est) { + (None, Some(e)) if e.fix => Some(format!("РЛС засекла пуски: новая ПУ №{} ({}), место определено ±{:.0} м", site, class_name(class), e.radius)), + (None, Some(e)) => Some(format!("РЛС засекла пуски: новая ПУ №{} ({}), азимут {:.0}° {}", site, class_name(class), e.bearing.to_degrees(), wind(e.bearing))), + (Some(b), Some(e)) if !b.fix && e.fix => Some(format!("ПУ №{}: место определено, ±{:.0} м ({})", site, e.radius, accuracy(e))), + (Some(_), Some(_)) if words(&before) != words(&k.est) => Some(format!("ПУ №{}: точность {}, ±{:.0} м", site, accuracy(k.est.as_ref().unwrap()), k.est.as_ref().unwrap().radius)), + _ => None, + }; + let _ = first; + if let Some(m) = msg { + self.strikes.news.push(m); + } + } + + /// Once a tick: strike missiles refill, fly and land; launched drones are picked up on tracks; wrecks smoke. + pub(super) fn step_strikes(&mut self, ground: &mut Ground, player: Option, out: &mut Out) { + let now = self.tick; + out.messages.append(&mut self.strikes.news); + if self.strikes.stock < TUNE.stock_max { + self.strikes.progress += 1; + if self.strikes.progress >= TUNE.resupply { + self.strikes.progress = 0; + self.strikes.stock += 1; + out.messages.push(format!("Ударных ракет в запасе: {}", self.strikes.stock)); + } + } + // Launched drones picked up on a track. + if now % 4 == 0 && !self.strikes.flown.is_empty() { + let mut new: Vec<(u32, SiteClass, Obs)> = Vec::new(); + let flown = std::mem::take(&mut self.strikes.flown); + let mut keep = Vec::with_capacity(flown.len()); + for f in flown { + let Some(d) = self.drones.iter().find(|d| d.id == f.drone).filter(|d| d.alive()) else { continue }; + if now.saturating_sub(f.at) > TUNE.scout_life { + continue; + } + // The tracks of the (up to two) systems whose own radar holds it: each is a sighting of its own. + let mut held: Vec<(u32, sight::Track)> = self.sams.iter().filter(|s| s.alive()).filter_map(|s| s.track(f.drone).filter(|t| t.own_tick > 0).map(|t| (s.id, *t))).collect(); + if held.is_empty() { + keep.push(f); + continue; + } + held.sort_by_key(|h| std::cmp::Reverse(h.1.tick)); + held.truncate(2); + let Some(site) = self.sites.get(f.site) else { continue }; + let truth = DVec2::new(site.pos.x, site.pos.z); + for (sam, t) in held { + let from = DVec2::new(t.pos.x, t.pos.z); + let away = truth - from; + let dist = away.length(); + if dist < 30.0 { + continue; + } + let (k, c) = (f.drone as u64, f.site as u64 * 64 + sam as u64 % 64); + if d.kind.spec().ballistic.is_some() { + let sigma = (dist * TUNE.ballistic_sigma.0).max(TUNE.ballistic_sigma.1); + let at = DVec2::new(truth.x + gauss(self.seed, k, c, 3) * sigma, truth.y + gauss(self.seed, k, c, 4) * sigma); + new.push((f.site, f.class, Obs::point(at, sigma))); + } else { + // Bearing from the track; range from the time of flight since the launch (the alarm), at the + // drone's speed: a fraction of the range and a second of launch time. + let a = away.y.atan2(away.x) + gauss(self.seed, k, c, 5) * TUNE.track_sigma; + let sr = dist * TUNE.range_sigma.0 + d.kind.spec().speed * TUNE.range_sigma.1; + let r = (dist + gauss(self.seed, k, c, 6) * sr).max(20.0); + new.push((f.site, f.class, Obs { range: Some((r, sr)), ..Obs::ray(from, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma) })); + } + } + } + self.strikes.flown = keep; + for (site, class, obs) in new { + self.add_obs(site, class, obs); + } + out.messages.append(&mut self.strikes.news); + } + // A site gone from the raid is gone from the list. + let sites = &self.sites; + self.strikes.known.retain(|k| sites.get(k.site).is_some()); + for k in self.strikes.known.iter_mut() { + if let SiteState::Stunned(until) = k.state + && until <= now + { + k.state = SiteState::Active; + } + } + self.fly_strikes(ground, player, out); + // Wrecks smoke. + self.strikes.wrecks.retain(|w| w.1 > now); + for (at, _) in &self.strikes.wrecks { + out.particles("minecraft:flame", *at + DVec3::Y * 1.2, 1.5, DVec3::new(0.0, 0.05, 0.0), 0.03, 2); + out.particles("minecraft:large_smoke", *at + DVec3::Y * 1.5, 1.2, DVec3::new(0.0, 0.12, 0.0), 0.03, 2); + if now % 40 == 0 { + out.sound("minecraft:block.fire.ambient", *at, 3.0, 0.7); + } + } + } + + /// Strike missiles on their way: drawn, heard, and landed when their time is up. + fn fly_strikes(&mut self, ground: &mut Ground, player: Option, out: &mut Out) { + let now = self.tick; + let spec = DroneKind::Kalibr.spec(); + let flights = std::mem::take(&mut self.strikes.flights); + let mut rest = Vec::with_capacity(flights.len()); + for f in flights { + if now >= f.arrive { + self.land_strike(f, ground, player, out); + continue; + } + let t = (now - f.start) as f64 / (f.arrive - f.start).max(1) as f64; + let end = DVec3::new(f.aim.x, f.from.y, f.aim.y); + let pos = f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt()); + let dir = (end - f.from).normalize_or(DVec3::NEG_Z) + DVec3::Y * 0.001; + let rot = look(dir, 0.0); + let id = 0x7500_0000 + f.id * PARTS; + 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 { + 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() { + out.engine(id, event, pos, dir.normalize() * TUNE.speed, 0.8, pitch, false); + } + rest.push(f); + } + rest.append(&mut self.strikes.flights); + self.strikes.flights = rest; + } + + /// Fires a strike missile at known site `id` from `from`. Returns the line for the player. + pub fn order_strike(&mut self, id: u32, from: DVec3, out: &mut Out) -> Result { + let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена: /airdef sites покажет известные"))?; + let est = k.est.filter(|e| e.fix).ok_or_else(|| { + format!("ПУ №{id}: места не знаем, только азимут. Нужно больше пусков на виду или вторая РЛС в стороне от первой") + })?; + if matches!(k.state, SiteState::Destroyed(_)) { + return Err(format!("ПУ №{id} уже уничтожена")); + } + if self.strikes.flights.iter().any(|f| f.site == id) { + return Err(format!("По ПУ №{id} ракета уже в полёте")); + } + if self.strikes.stock == 0 { + return Err(format!("Ударных ракет нет: следующая через {} с", self.strikes.seconds_to_next())); + } + let dist = (est.pos - DVec2::new(from.x, from.z)).length(); + if dist > TUNE.range { + return Err(format!("ПУ №{id} дальше дальности удара ({})", crate::panel::distance(TUNE.range))); + } + self.strikes.stock -= 1; + self.strikes.fired += 1; + self.strikes.next += 1; + let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64; + let start = from + DVec3::Y * 1.5; + self.strikes.flights.push(Flight { id: self.strikes.next, site: id, from: start, aim: est.pos, start: self.tick, arrive: self.tick + ticks }); + if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == id) { + k.aimed = true; + } + out.sound(DroneKind::Kalibr.launch_sound(), start, 1.0, 1.0); + out.particles("minecraft:large_smoke", start, 0.6, DVec3::ZERO, 0.05, 30); + out.particles("minecraft:flame", start, 0.3, DVec3::new(0.0, -0.2, 0.0), 0.05, 12); + Ok(format!( + "Удар по ПУ №{id}: ракета пошла в точку ±{:.0} м, лёт {} с, дальше {}. Осталось ударных ракет: {}", + est.radius, + ticks / 20, + crate::panel::distance(dist), + self.strikes.stock + )) + } + + /// A strike arrives. + fn land_strike(&mut self, f: Flight, ground: &mut Ground, player: Option, out: &mut Out) { + let now = self.tick; + if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) { + k.aimed = false; + } + let Some(site) = self.sites.get(f.site).cloned() else { + out.messages.push(format!("Удар по ПУ №{}: площадка уже свёрнута, ракета ушла в пустоту", f.site)); + return; + }; + let cover = self.cover_of(&site); + if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) { + k.cover = Some(cover); + } + let spot = |x: f64, z: f64, ground: &mut Ground, fallback: f64| DVec3::new(x, ground.at(DVec3::new(x, 0.0, z), now).unwrap_or(fallback), z); + // The enemy's cover. + if dice(self.seed, f.id as u64, f.site as u64, 201) < TUNE.cover_p[cover as usize] { + self.strikes.shot_down += 1; + let at = spot(f.aim.x, f.aim.y, ground, site.pos.y) + DVec3::Y * 40.0; + self.blast_at(at, 0, true, false, ground, player, out); + self.log(at, record::EventKind::Strike { site: f.site, result: record::StrikeResult::Intercepted }); + out.messages.push(format!("Удар по ПУ №{}: ракета сбита ПВО противника у площадки, цель цела", f.site)); + return; + } + // Where it lands: the aim and the missile's scatter; how far from the site decides. + let (gx, gz) = (gauss(self.seed, f.id as u64, f.site as u64, 7), gauss(self.seed, f.id as u64, f.site as u64, 8)); + let land = DVec2::new(f.aim.x + gx * TUNE.cep, f.aim.y + gz * TUNE.cep); + let miss = (land - DVec2::new(site.pos.x, site.pos.z)).length(); + let result = if site.offmap && miss <= TUNE.hit_r { + record::StrikeResult::Halted + } else if !site.alive { + record::StrikeResult::Missed + } else if miss <= TUNE.hit_r { + record::StrikeResult::Destroyed + } else if miss <= TUNE.suppress_r { + record::StrikeResult::Stunned + } else { + record::StrikeResult::Missed + }; + use record::StrikeResult as R; + if site.offmap { + // Nothing stands there, nothing is seen: the launches stop or they do not. + if result == R::Halted { + let n = self.halt_site(f.site); + self.strikes.destroyed += 1; + self.strikes.cancelled.push((f.site, n)); + self.set_state(f.site, SiteState::Destroyed(now)); + self.log(site.pos, record::EventKind::Strike { site: f.site, result }); + out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты, результат не виден; пуски оттуда прекратились (отменено {n})", f.site)); + } else { + self.strikes.missed += 1; + out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты; пуски идут, ракета потеряна", f.site)); + } + return; + } + let at = spot(land.x, land.y, ground, site.pos.y); + match result { + R::Destroyed => { + let stock = site.stock; + let n = self.destroy_site(f.site); + self.strikes.destroyed += 1; + self.strikes.cancelled.push((f.site, n)); + self.set_state(f.site, SiteState::Destroyed(now)); + // Its kit and what it carried: a heavy blast, the rounds cooking off, a fire, a smoking wreck. + self.blast_at(at, 8, false, true, ground, player, out); + let loaded = ground.at(at, now).is_some(); + for j in 0..stock.min(8) { + let when = now + 12 + j as u64 * 9 + (dice(self.seed, f.id as u64, j as u64, 301) * 14.0) as u64; + let off = DVec3::new(gauss(self.seed, f.id as u64, j as u64, 302) * 4.0, dice(self.seed, f.id as u64, j as u64, 303) * 2.0, gauss(self.seed, f.id as u64, j as u64, 304) * 4.0); + self.later.push((when, at + off, if loaded { 2 } else { 0 }, true)); + } + self.strikes.wrecks.push((at, now + TUNE.burn)); + self.log(at, record::EventKind::Strike { site: f.site, result }); + out.messages.push(format!( + "Удар по ПУ №{}: площадка уничтожена, запас сгорел ({stock}); отменено запусков: {n}", + f.site + )); + } + R::Stunned => { + if let Some(s) = self.sites.list.iter_mut().find(|s| s.id == f.site) { + s.next_free = s.next_free.max(now + TUNE.suppress_ticks); + } + self.strikes.stunned += 1; + self.set_state(f.site, SiteState::Stunned(now + TUNE.suppress_ticks)); + self.blast_at(at, 4, false, false, ground, player, out); + self.log(at, record::EventKind::Strike { site: f.site, result }); + out.messages.push(format!( + "Удар по ПУ №{}: накрыла рядом ({miss:.0} м), площадка подавлена на {} с, но цела", + f.site, + TUNE.suppress_ticks / 20 + )); + } + _ => { + self.strikes.missed += 1; + self.blast_at(at, 4, false, false, ground, player, out); + self.log(at, record::EventKind::Strike { site: f.site, result: R::Missed }); + out.messages.push(format!("Удар по ПУ №{}: промах на {miss:.0} м, площадка цела, пуски идут", f.site)); + } + } + } + + fn set_state(&mut self, site: u32, state: SiteState) { + if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == site) { + k.state = state; + } + } + + /// A blast of `tnt` at `at` with the game's own blast code; the land is only broken where it is loaded. + fn blast_at(&mut self, at: DVec3, tnt: u32, small: bool, _fire: bool, ground: &mut Ground, player: Option, out: &mut Out) { + let keep = self.damage; + self.damage = keep && tnt > 0 && ground.at(at, self.tick).is_some(); + self.explode(at, tnt, small, ground, player, out); + self.damage = keep; + } + + /// Lines for `/airdef sites`. + pub fn site_lines(&self, from: DVec3) -> Vec { + let now = self.tick; + let mut v: Vec = self.strikes.known.iter().map(|k| { + let mut s = k.line(from, now); + if self.truth + && let Some(site) = self.sites.get(k.site) + { + let err = k.est.filter(|e| e.fix).map(|e| (e.pos - DVec2::new(site.pos.x, site.pos.z)).length()); + s += &format!(" [истина: {:.0} {:.0}{}]", site.pos.x, site.pos.z, err.map_or(String::new(), |e| format!(", ошибка {e:.0} м"))); + } + s + }).collect(); + if v.is_empty() { + v.push("Известных ПУ нет: их находят РЛС по пускам и трекам вылетевших целей".into()); + } + v.push(format!( + "Ударных ракет: {}/{}{} · в полёте {} · дальность {}", + self.strikes.stock, + TUNE.stock_max, + if self.strikes.stock < TUNE.stock_max { format!(" (следующая через {} с)", self.strikes.seconds_to_next()) } else { String::new() }, + self.strikes.flights.len(), + crate::panel::distance(TUNE.range) + )); + v + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A ray from `at` towards `truth`, with the sigma's worth of noise the sim would give it. + fn ray(truth: DVec2, at: DVec2, k: u64, sigma: f64) -> Obs { + let a = (truth - at).y.atan2((truth - at).x) + gauss(7, k, 1, 5) * sigma; + Obs::ray(at, DVec2::new(a.cos(), a.sin()), sigma) + } + + #[test] + fn a_sites_location_narrows_with_launches_and_with_a_second_radar() { + let truth = DVec2::new(100.0, 3000.0); + // One place of seeing: the rays run nearly parallel, so it is a bearing, not a place. + let one: Vec = (0..20).map(|k| ray(truth, DVec2::new(-30.0 + k as f64 * 3.0, 0.0), k, TUNE.track_sigma)).collect(); + let e = solve(&one).unwrap(); + assert!(!e.fix, "one radar fixed a site 3 km out: {e:?}"); + assert!((compass(truth - e.origin) - e.bearing).abs() < 0.06, "the bearing is about right: {e:?}"); + // Two radars 1.2 km apart: a place, and the circle shrinks with the launches. + let two = |n: u64| -> Vec { + (0..n).map(|k| ray(truth, if k % 2 == 0 { DVec2::new(-600.0, 0.0) } else { DVec2::new(600.0, 0.0) }, k, TUNE.track_sigma)).collect() + }; + let (few, many) = (solve(&two(4)).unwrap(), solve(&two(40)).unwrap()); + assert!(many.fix && many.radius < few.radius * 0.6, "radius {} with 4, {} with 40", few.radius, many.radius); + assert!(many.radius < TUNE.max_fix_radius && (many.pos - truth).length() < many.radius * 1.5, "{:?} radius {}", many.pos, many.radius); + // Points average too: more sightings, a smaller circle. + let pts = |n: u64| -> Vec { (0..n).map(|k| Obs::point(truth + DVec2::new(gauss(3, k, 1, 1), gauss(3, k, 1, 2)) * 20.0, 20.0)).collect() }; + let (p1, p9) = (solve(&pts(1)).unwrap(), solve(&pts(9)).unwrap()); + assert!(p1.fix && (p1.radius - 60.0).abs() < 1e-6 && p9.radius < p1.radius / 2.5, "{} {}", p1.radius, p9.radius); + assert!(solve(&[]).is_none()); + } + + #[test] + fn the_stated_circle_holds_about_nine_in_ten_of_the_real_errors() { + let truth = DVec2::new(100.0, 3000.0); + let mut within = 0; + for seed in 0..200u64 { + let obs: Vec = (0..40u64) + .map(|k| { + let at = if k % 2 == 0 { DVec2::new(-600.0, 0.0) } else { DVec2::new(600.0, 0.0) }; + let a = (truth - at).y.atan2((truth - at).x) + gauss(seed, k, 1, 5) * TUNE.track_sigma; + Obs::ray(at, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma) + }) + .collect(); + let e = solve(&obs).unwrap(); + within += usize::from((e.pos - truth).length() <= e.radius); + } + assert!((165..=196).contains(&within), "{within} of 200 inside the circle"); + } + + #[test] + fn a_track_with_a_time_of_flight_range_places_the_site_and_more_of_them_narrow_it() { + let truth = DVec2::new(100.0, 3000.0); + let ranged = |n: u64, seed: u64| -> Vec { + (0..n) + .map(|k| { + let at = DVec2::new(-40.0 + gauss(seed, k, 9, 1) * 30.0, 2200.0 + gauss(seed, k, 9, 2) * 30.0); + let away = truth - at; + let a = away.y.atan2(away.x) + gauss(seed, k, 1, 5) * TUNE.track_sigma; + let sr = away.length() * TUNE.range_sigma.0 + 20.0; + Obs { range: Some((away.length() + gauss(seed, k, 1, 6) * sr, sr)), ..Obs::ray(at, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma) } + }) + .collect() + }; + let (mut within, mut shrink) = (0, 0); + for seed in 0..100u64 { + let (one, many) = (solve(&ranged(1, seed)).unwrap(), solve(&ranged(16, seed)).unwrap()); + within += usize::from((many.pos - truth).length() <= many.radius); + shrink += usize::from(many.radius < one.radius * 0.5); + } + assert!(within >= 80, "{within} of 100 inside the circle"); + assert_eq!(shrink, 100); + // Even one is a (rough) place for a site 800 blocks away. + assert!(solve(&ranged(1, 1)).unwrap().fix); + } + + /// A ramp 300 blocks south of the origin with `n` shaheds queued 40 ticks apart, and a radar `radar` blocks from it + /// (None: no radar). + fn scene(seed: u64, n: u32, radar: Option) -> (Sim, Ground, Out, u32) { + let mut sim = Sim::new(seed); + sim.strikes.cover_override = Some(0); + if let Some(at) = radar { + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Patriot, at, 0.0)); + } + let id = sim.sites.add(LaunchSite { + id: 0, + 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: n, + planned: n, + alive: true, + next_free: 0, + offmap: false, + }); + for i in 0..n { + let site = sim.sites.get(id).unwrap().clone(); + let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0)); + sim.sites.job(d.id, id); + sim.queue.push((10 + i as u64 * 40, d)); + } + (sim, Ground::default(), Out::default(), id) + } + + fn run(sim: &mut Sim, ground: &mut Ground, out: &mut Out, ticks: u32) { + for _ in 0..ticks { + sim.step(ground, None, out); + } + } + + #[test] + fn launches_seen_by_a_radar_in_reach_locate_the_site_and_the_circle_shrinks() { + let (mut sim, mut ground, mut out, id) = scene(11, 12, Some(DVec3::new(0.0, 64.0, 200.0))); + assert!(sim.strikes.known.is_empty(), "nothing is known before a launch"); + let mut radii = Vec::new(); + for _ in 0..500 { + sim.step(&mut ground, None, &mut out); + if let Some(e) = sim.strikes.get(id).and_then(|k| k.est) { + if radii.last() != Some(&e.radius) { + radii.push(e.radius); + } + } + } + let k = sim.strikes.get(id).expect("the radar found the site"); + assert!(k.launches >= 8, "{} launches seen", k.launches); + let e = k.est.unwrap(); + assert!(e.fix && e.radius < 40.0, "{e:?}"); + let truth = DVec2::new(0.0, 300.0); + assert!((e.pos - truth).length() < e.radius + 15.0, "off by {}", (e.pos - truth).length()); + assert!(radii.first().unwrap() > radii.last().unwrap(), "{radii:?}"); + assert!(out.messages.iter().any(|m| m.contains("новая ПУ")), "{:?}", out.messages); + // The site is not known to a sim with no radar: nothing by magic. + let (mut blind, mut g2, mut o2, _) = scene(11, 12, None); + run(&mut blind, &mut g2, &mut o2, 500); + assert!(blind.strikes.known.is_empty()); + } + + #[test] + fn a_strike_on_a_known_site_ends_its_launches() { + let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + run(&mut sim, &mut ground, &mut out, 200); + assert!(sim.strikes.get(id).is_some_and(|k| k.est.is_some_and(|e| e.fix))); + let before = sim.launched; + assert!(before >= 3 && before < 14, "{before}"); + let player = DVec3::new(0.0, 64.0, 0.0); + let said = sim.order_strike(id, player, &mut out).unwrap(); + assert!(said.contains("ПУ"), "{said}"); + assert_eq!(sim.strikes.stock, TUNE.stock - 1); + assert!(sim.order_strike(id, player, &mut out).is_err(), "a second missile at the same site while one flies"); + out.messages.clear(); + run(&mut sim, &mut ground, &mut out, 400); + let site = sim.sites.get(id).unwrap(); + assert!(!site.alive && site.stock == 0, "{:?} / {:?}", out.messages, site); + assert!(sim.queue.is_empty(), "the jobs are cancelled"); + assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched); + assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages); + assert!(sim.strikes.wrecks.len() == 1 && sim.fires.list.len() == 1, "a wreck and a fire"); + assert!(!sim.blasts.is_empty() || sim.tick > 0); + assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_))); + assert!(sim.order_strike(id, player, &mut out).is_err(), "destroyed already"); + // The result is on the record for replays and stats. + assert_eq!((sim.strikes.fired, sim.strikes.destroyed), (1, 1)); + } + + #[test] + fn a_strike_on_a_badly_known_site_misses_and_changes_nothing() { + let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + run(&mut sim, &mut ground, &mut out, 120); + // What the radars hold is wrong by 400 blocks, and says it is. + // (No radar sees any more: the estimate stays as it is.) + sim.sams.clear(); + let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap(); + let mut e = k.est.unwrap(); + e.pos += DVec2::new(400.0, 0.0); + e.radius = 450.0; + k.est = Some(e); + sim.strikes.known[0].obs.clear(); + let queued = sim.queue.len(); + sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap(); + out.messages.clear(); + run(&mut sim, &mut ground, &mut out, 300); + assert!(out.messages.iter().any(|m| m.contains("промах")), "{:?}", out.messages); + let site = sim.sites.get(id).unwrap(); + assert!(site.alive && site.stock > 0); + assert!(sim.queue.len() + sim.launched as usize >= 14 - 1 && sim.queue.len() <= queued, "the queue is not written off by a hit on the soil beside it"); + assert_eq!((sim.strikes.destroyed, sim.strikes.missed), (0, 1)); + // A near miss only stuns: launches wait, nothing is cancelled. + let (mut stunned, mut other) = (0, 0); + for seed in 20..32 { + let (mut sim, mut ground, mut out, id) = scene(seed, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + run(&mut sim, &mut ground, &mut out, 120); + sim.sams.clear(); + let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap(); + let mut e = k.est.unwrap(); + e.pos = DVec2::new(0.0, 300.0 + 62.0); + k.est = Some(e); + sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap(); + let queued = sim.queue.len(); + run(&mut sim, &mut ground, &mut out, 300); + if sim.strikes.stunned == 1 { + stunned += 1; + assert!(sim.sites.get(id).unwrap().alive); + assert!(sim.queue.len() + 1 >= queued.min(sim.queue.len() + 1), "stunned launches are delayed, not cancelled"); + assert!(sim.sites.get(id).unwrap().stock > 0 || sim.queue.is_empty()); + } else { + other += 1; + } + } + assert!(stunned >= 8 && other <= 4, "{stunned} stunned, {other} other"); + } + + #[test] + fn a_site_known_only_by_bearing_cannot_be_struck() { + let (mut sim, _, mut out, id) = scene(3, 4, None); + sim.strikes.known.push(Known { + site: id, + class: SiteClass::Ramp, + obs: Vec::new(), + est: solve(&[ray(DVec2::new(0.0, 300.0), DVec2::new(0.0, 0.0), 1, TUNE.track_sigma)]), + launches: 1, + last: 0, + state: SiteState::Active, + cover: None, + aimed: false, + }); + assert!(!sim.strikes.known[0].est.unwrap().fix); + let e = sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err(); + assert!(e.contains("азимут"), "{e}"); + assert_eq!(sim.strikes.stock, TUNE.stock, "no missile spent"); + assert!(sim.order_strike(99, DVec3::ZERO, &mut out).is_err()); + } + + #[test] + fn stock_is_limited_range_is_limited_and_it_refills_slowly() { + let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + run(&mut sim, &mut ground, &mut out, 120); + // Too far. + assert!(sim.order_strike(id, DVec3::new(0.0, 64.0, 300.0 - TUNE.range - 100.0), &mut out).is_err()); + sim.strikes.stock = 0; + let e = sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err(); + assert!(e.contains("нет"), "{e}"); + sim.strikes.progress = TUNE.resupply - 1; + run(&mut sim, &mut ground, &mut out, 2); + assert_eq!((sim.strikes.stock, sim.strikes.progress), (1, 1)); + } + + #[test] + fn enemy_cover_shoots_some_strikes_down_and_none_with_no_cover() { + let mut down = [0u32; 3]; + for cover in 0..3u8 { + for seed in 1..=30u64 { + let (mut sim, mut ground, mut out, id) = scene(seed, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + sim.strikes.cover_override = Some(cover); + run(&mut sim, &mut ground, &mut out, 120); + sim.order_strike(id, DVec3::ZERO, &mut out).unwrap(); + run(&mut sim, &mut ground, &mut out, 200); + down[cover as usize] += sim.strikes.shot_down; + } + } + assert_eq!(down[0], 0); + assert!(down[1] > 3 && down[1] < 20 && down[2] > down[1], "{down:?}"); + } + + #[test] + fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() { + let mut sim = Sim::new(5); + sim.strikes.cover_override = Some(0); + // Two radars apart watch the start of an off-map site's drones. + for x in [-150.0, 150.0] { + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0)); + } + let id = sim.sites.add(LaunchSite { + id: 0, + side: 0, + sector: 0, + bearing: 0.0, + class: SiteClass::Ramp, + pos: DVec3::new(0.0, 70.0, 700.0), + range: 700.0, + water: false, + stock: 30, + planned: 30, + alive: true, + next_free: 0, + offmap: true, + }); + for i in 0..30 { + let mut d = sim.make_drone(DroneKind::Shahed, DVec3::new(0.0, 70.0, 700.0), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0)); + d.vel = DVec3::new(0.0, 0.0, -2.0); + sim.sites.job(d.id, id); + sim.queue.push((1 + i * 40, d)); + } + let (mut ground, mut out) = (Ground::default(), Out::default()); + // Shaheds crawl: it takes a while for the first to come into a radar's reach. + run(&mut sim, &mut ground, &mut out, 1500); + let k = sim.strikes.get(id).expect("scouted like any other site"); + assert!(k.est.is_some(), "no launch is seen off the map, but the drones' tracks point back"); + // Nothing to destroy there ... + assert_eq!(sim.destroy_site(id), 0); + // ... and the shot aims at what is known: force a good fix to test the outcome. + let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap(); + k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO }); + sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap(); + out.messages.clear(); + let wrecks = sim.fires.list.len(); + run(&mut sim, &mut ground, &mut out, 500); + assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages); + assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive); + // Nothing drawn: no wreck, no fire, no blast of its own. + assert_eq!((sim.strikes.wrecks.len(), sim.fires.list.len()), (0, wrecks)); + } + + #[test] + fn a_strike_leaves_one_event_for_the_replay_and_a_scenario_keeps_the_stock() { + let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0))); + run(&mut sim, &mut ground, &mut out, 100); + // A recording is running (the launched drones started it): the strike lands in it. + sim.order_strike(id, DVec3::ZERO, &mut out).unwrap(); + run(&mut sim, &mut ground, &mut out, 200); + let count = |r: &record::Recording| r.events.iter().filter(|e| matches!(e.kind, record::EventKind::Strike { .. })).count(); + let n = sim.rec.iter().chain(sim.replays.iter()).map(count).sum::(); + assert_eq!(n, 1); + // Saves: the stock and its progress come back, clamped to what is possible. + let mut s = Strikes::new(); + s.restore(2, 4000); + assert_eq!((s.stock, s.progress), (2, 4000)); + s.restore(99, 5); + assert_eq!((s.stock, s.progress), (TUNE.stock_max, 0)); + s.restore(1, u32::MAX); + assert_eq!((s.stock, s.progress), (1, TUNE.resupply - 1)); + } + + /// The fixed scenario of the issue: a raid, a radar that opens its site by the launches, a strike that cancels the + /// launches left, and the raid's report that says so. + #[test] + fn a_planned_raid_loses_its_remaining_launches_to_a_strike_and_the_report_says_so() { + use super::sites::testland::{Land, serve}; + let land = Land(|_, _| 64); + let (mut ground, mut out) = (Ground::default(), Out::default()); + let mut sim = Sim::new(21); + sim.strikes.cover_override = Some(0); + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 30)], approach: Approach::Sector, dist: 300.0, aim: Aim::Objects }; + sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut out); + let mut n = 0; + while sim.planning() { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + n += 1; + assert!(n < 1000); + } + let site = sim.sites.list.iter().find(|s| s.class == SiteClass::Ramp).unwrap().clone(); + // A radar near the ramp, fitted after the planning (the enemy chose its ground away from the defence). + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Patriot, site.pos + DVec3::new(60.0, 0.0, 0.0), 0.0)); + let mut struck = false; + let mut left_at_strike = 0; + for _ in 0..3000 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + if !struck && sim.strikes.get(site.id).is_some_and(|k| k.est.is_some_and(|e| e.fix && e.radius < 40.0)) && sim.sites.pending(site.id) > 3 { + left_at_strike = sim.sites.pending(site.id); + sim.order_strike(site.id, DVec3::new(0.0, 70.0, 0.0), &mut out).unwrap(); + struck = true; + } + } + assert!(struck, "the radar never opened the site"); + let cut = out.messages.iter().find(|m| m.contains("Налёт сорван")).unwrap_or_else(|| panic!("{:?}", out.messages)); + assert!(cut.contains(&format!("№{}", site.id)), "{cut}"); + assert!(out.messages.iter().any(|m| m.contains("Налёт окончен")), "the raid is closed, not held open"); + assert!(sim.queue.is_empty() && sim.sites.pending(site.id) == 0); + assert!(left_at_strike > 3); + } +} diff --git a/airdef-mod/src/sim/why.rs b/airdef-mod/src/sim/why.rs index da9d879..8f44d73 100644 --- a/airdef-mod/src/sim/why.rs +++ b/airdef-mod/src/sim/why.rs @@ -141,6 +141,10 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro let est = track.est(now); let reach = reach_blocks(load.min, load.max, k, sam.pos, est); if blocks & ROLE == 0 { + // The doctrine (sector, protected objects, reserve) rules over the role's shots and the long ones; the last chance is past it. + if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d) != 0 { + return None; + } if reach == 0 { return Some(Basis::Role); } @@ -158,8 +162,8 @@ pub(super) fn reach_fit(max: f64, dist: f64) -> f64 { /// A gun's candidates: measured by the system's own radar a moment ago and within the gun's tracking range /// (by the track's forecast, not the target's true place). -pub(super) fn gun_candidate(roles: u8, track: &Track, now: u64, gun_track: f64, pos: DVec3, d: &Drone) -> bool { - allowed(roles, track, now, d) && track.own_within(now, sight::GUN_PICK_AGE) && track.est(now).distance(pos) < gun_track +pub(super) fn gun_candidate(roles: u8, doc: &doctrine::Doctrine, track: &Track, now: u64, gun_track: f64, pos: DVec3, d: &Drone) -> bool { + allowed(roles, track, now, d) && doc.area_blocks(pos, track, now) == 0 && track.own_within(now, sight::GUN_PICK_AGE) && track.est(now).distance(pos) < gun_track } /// How many systems have each drone as their missile target and as their gun target. @@ -316,7 +320,11 @@ impl Sim { self.drones .iter() .filter(|d| d.alive() && (sam.roles & d.kind.spec().class.bit() != 0 || last_chance(self.last_chance, sam.roles, d, claimed(d, &missile_on, sam.target)))) - .max_by(|a, b| a.threat(sam.pos).total_cmp(&b.threat(sam.pos))) + .max_by(|a, b| { + // What the doctrine lets the system shoot at comes first; then the most threatening. + let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0); + area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos))) + }) }); let Some(t) = subject else { v.push(check(false, format!("нет целей классов [{}]", roles_text(sam.roles)))); @@ -348,6 +356,29 @@ impl Sim { format!("роль: {} не в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles)) }; v.push(check(blocks & ROLE == 0 || chance, role_text)); + // The doctrine: which of its settings let the shot through or stopped it. The last chance is past them. + let doc = &sam.doctrine; + let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now)); + let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t) } else { 0 }; + if !doc.is_default() { + v.push(check(true, format!("доктрина: {}", doc.text(&self.targets)))); + } + if area & doctrine::OUT_SECTOR != 0 { + let bearing = heading_of(est - sam.pos).to_degrees().rem_euclid(360.0); + v.push(check(chance, format!("вне сектора {}: цель на {bearing:.0}°{}", doc.sector_text(), if chance { " — последний шанс сильнее" } else { "" }))); + } else if doc.sector.is_some() { + v.push(check(true, format!("в секторе {}", doc.sector_text()))); + } + if area & doctrine::NO_THREAT != 0 { + v.push(check(chance, format!("не угрожает охраняемым объектам ({}){}", doc.guards.iter().map(|g| doctrine::object_name(&self.targets, *g)).collect::>().join(", "), if chance { " — последний шанс сильнее" } else { "" }))); + } else if let Some(g) = track.and_then(|tr| doc.threatens(tr, now)) { + v.push(check(true, format!("прикрывает {}: цель идёт на него", doctrine::object_name(&self.targets, doc.guards[g])))); + } + if held_back != 0 { + v.push(check(chance, format!("сохраняет резерв {}: ракет {}, цель не срочная{}", doc.reserve, sam.missiles, if chance { " — последний шанс сильнее" } else { "" }))); + } else if doc.reserve > 0 && sam.missiles <= doc.reserve { + v.push(check(true, format!("резерв {} открыт: цель срочная (до удара {:.0} с)", doc.reserve, arrival(t) / 20.0))); + } let detect = match (track, sam.own.contains(&t.id)) { (Some(tr), own) => { let kind = if own { "своей РЛС" } else { "по сети (стволы не стреляют)" }; @@ -398,7 +429,7 @@ impl Sim { let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let cued = sam.kind.far_shooter() && radar_cue(sam, &radars, t.id, now); let role_in_reach = self.drones.iter().any(|o| { - sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && claimed(o, &missile_on, sam.target) < needed(o)) + sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o)) }); let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0; let far_ok = far && track.is_some_and(|tr| basis(sam, load, tr, t, now, 0, 1.0, Opts { last_chance: self.last_chance, far_shots: self.far_shots }, cued, role_in_reach) == Some(Basis::FarShot)); @@ -419,8 +450,8 @@ impl Sim { v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", crate::panel::distance(dist), crate::panel::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) })); } let free = first_claim; - let need = needed(t); - v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need}{}", if free < need { "" } else { " — другие уже на ней" }))); + let need = sam.doctrine.needed(t); + v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need} (залп {}){}", doc.salvo.name(), if free < need { "" } else { " — другие уже на ней" }))); let mb = missile_blocks(sam); let mut why = Vec::new(); if mb & COOLDOWN != 0 { @@ -451,12 +482,13 @@ impl Sim { }, )); } - let grounds = blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && (reach == 0 || far_ok); + let doc_ok = chance || area | held_back == 0; + let grounds = blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok); fires |= grounds && free < need && mb == 0 && aligned && land == 0; } if let Some(gun) = &spec.gun { let on_it = guns_on.get(&t.id).copied().unwrap_or(0) - u32::from(sam.gun_target == Some(t.id)); - let cand = track.is_some_and(|tr| gun_candidate(sam.roles, tr, now, gun.track, sam.pos, t)); + let cand = track.is_some_and(|tr| gun_candidate(sam.roles, &sam.doctrine, tr, now, gun.track, sam.pos, t)); v.push(check( cand, format!( diff --git a/docs/ACOUSTICS.md b/docs/ACOUSTICS.md index 0e0bba5..4f3aa3f 100644 --- a/docs/ACOUSTICS.md +++ b/docs/ACOUSTICS.md @@ -13,9 +13,9 @@ ## Статус -**Стадия 1 (прямой звук) и стадия 2 (отводы эха) сделаны**, включается `HORIZON_ACOUSTICS=1` (по умолчанию выключено, -звук как был). Стадия 3 (реверб) не начата. Коммит SPR прежний, `453654ec`; атрибуция: `horizon/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md`. -GPL-файлы два: `acoustics/spr_occlusion.rs` и (стадия 2) `acoustics/spr_bounce.rs`; остальное (движок `acoustics.rs`, склейка `game/acoustics.rs`, DSP в `audio.rs`) наше. +**Стадии 1 (прямой звук), 2 (отводы эха) и 3 (реверб) сделаны**, включается кнопкой мода или `HORIZON_ACOUSTICS=1` (по умолчанию выключено, +звук как был). Коммит SPR прежний, `453654ec`; атрибуция: `horizon/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md`. +GPL-файлы три: `acoustics/spr_occlusion.rs`, (стадия 2) `acoustics/spr_bounce.rs` и (стадия 3) `acoustics/spr_reverb.rs`; остальное (движок `acoustics.rs`, `acoustics/room.rs`, склейка `game/acoustics.rs`, DSP в `audio.rs` и `audio/reverb.rs`) наше. Что вышло и чем отличается от плана выше: @@ -91,7 +91,61 @@ GPL-файлы два: `acoustics/spr_occlusion.rs` и (стадия 2) `acousti Не сделано / не проверено: запуск в игре и экспорт видео с настоящей сценой (склейка `game/acoustics.rs` — таблица состояний, снимок чанков — компилируется, но в игре не прогонялась); влияние на кадр при налёте; жидкости; дверь как проём (считается -ячейкой); потолок памяти снимка. Стадия 3 (шины реверба) не начата. +ячейкой); потолок памяти снимка. + +### Стадия 3: реверб (сделано) + +Что игрок получает: под крышей и в тоннеле звук звенит иначе, чем в поле; в чистом поле реверба нет. Код: `acoustics/room.rs` +(наш: замер пространства, уровень и спад, посылки), `acoustics/spr_reverb.rs` (GPL: четыре слота SPR, `0.7*0.85`, затухание посылок +с расстоянием), `audio/reverb.rs` (наш: DSP общей шины), посылки голосов и шина в `audio.rs` (`Channel.send`, `Mixer.reverb`), +склейка в `acoustics.rs` (`take_sends`). + +- Замер пространства (`room::measure`): 48 лучей по сфере Фибоначчи, берутся те, что идут вбок и вверх (пол комнаты не делает), длина 64 блока + (столько видит и SPR). Вес попадания `1 - (d/64)^2`. Из них: **замкнутость** (сумма весов / число лучей, 0..1), **размер** (средняя + дальность стен) и **отражательность** (средняя по таблице SPR). Слушатель замеряется по своей клетке 1x1x1 (кеш 64, сброс по секциям в + кубе ±65 и по эпохе, на рабочем потоке; пока новый замер в пути, остаётся прежний); у звуков с эхом замеряется ещё и пространство + источника (в той же трассе эха, свой потолок 60 тыс. клеток). Пространство звука = слушатель 60% + источник 40% (без источника: слушатель). +- Уровень и спад (`wet_and_decay`): `wet = smoothstep(0.03, 0.4, замкнутость)`; `спад = замкнутость^2 * (0.4 + 0.1*min(размер,30)) * + (0.6 + 0.8*отражательность)`, в пределах 0.15-4.14 с (слоты SPR). Камень (1.5) звенит дольше шерсти (0.1). Ущелье с открытым верхом + почти не даёт реверба (его ответ - эхо стадии 2); комната и тоннель - да. +- Посылки: спад ложится между двумя соседними слотами SPR (0.15 / 0.55 / 1.68 / 4.14 с, по логарифму) равномерной по мощности + перекрёстной кривой (квадрат положения у длинного, иначе по Шрёдеру читается только он), каждый слот выравнен по своему `gain` из + таблицы SPR: громкость реверба не растёт с его длиной. Посылка голоса умножается на `distance_fade` SPR (`1 - d/(1.5*дальность)`). +- Шина (`audio/reverb.rs`): 4 слота, в каждом пред-задержка (late delay SPR), 2 allpass, 4 гребёнки с lowpass в петле (коэффициент из + `decay_hf_ratio` SPR на 5 кГц). Левое ухо берёт гребёнки 0 и 2, правое 1 и 3 (разные хвосты), моно = среднее всех четырёх. Голос + кладёт в шину сигнал после стены (окклюзии) и до панорамы; посылки голоса плавно (постоянная 0.3 с) идут к цели, так что вход в тоннель + и выход из него без щелчка. Шина считается и без голосов (хвост звучит после конца хлопка), слот без входа и хвоста не считается и + обнуляется (без денормалей), шина сбрасывается, когда затихла. +- Выключение (`set_acoustics(false)`): посылки идут к нулю за ~1-2 с, хвост доигрывает сам; `stop_all` (и `film_begin/film_end`) шину сбрасывают. + Съёмка: замер синхронный (счёт клеток), шина считается без случайности и от часов не зависит - дорожка та же при каждом прогоне + (`audio::tests::reverb_rendering_is_deterministic`). +- Измерено (release, M-серия, буфер 512 кадров = 10.67 мс): шина с четырьмя занятыми слотами 0.017 мс; 100 голосов 0.119 мс без реверба -> + +0.04 мс с реверб-посылками (25 или 100 голосов, около 0.4% буфера); замер пространства: комната 0.0075 мс (392 клетки), тоннель + 0.0037, ущелье 0.033 (2208), поле 0.035 мс (2315); всё на рабочем потоке. Счётчики в `status`: `acoustics.reverb` (замеры, попадания + кеша, клетки, посылки, замкнутость и спад сейчас); в игре не снимались. +- Проверка без слуха: `audio::tests::export_reverb_tracks` (настоящие `Acoustics`, посылки, `mix`, щелчок в комнате 24x10x24, тоннеле 5x4, + ущелье, поле) + `python3 tools/acoustics_check.py --reverb-dir папка`. Порядок **поле < ущелье < тоннель < комната** (в плане было + «ущелье длиннее всех»; открытый верх ущелья этого не даёт): + + | сцена | спад пространства, с | RT60 по посылкам, с | RT60 измерено, с | хвост/щелчок, дБ | + |---|---|---|---|---| + | поле | 0.15 | - | хвоста нет | нет | + | ущелье | 0.15 | 0.15 | 0.10 | -47.7 | + | тоннель | 0.79 | 0.97 | 0.87 | -11.7 | + | комната | 1.37 | 1.67 | 1.39 | -7.7 | + + Колонка «по посылкам» - сумма экспонент слотов по Шрёдеру (`room::effective_decay`), измеренное лежит на 10-20% ниже (lowpass в петле + укорачивает). Каждый слот отдельно (импульс в одну шину, `reverb::tests::each_slot_decays_at_its_time`) читается в 0.5-1.15 от + номинала. Тесты: `--lib acoustics` (замеры комната/тоннель/ущелье/поле, порядок спадов, гладкость посылок, кеш, сброс, рабочий поток) + и `--lib audio` (хвост после конца звука и сброс шины, нулевая посылка - ровно прежний вывод, без щелчка при смене и выключении, + детерминизм, выключение и `film_begin`). + +Не слушали: громкость реверба (`WET = 1.6` и уровни слотов не подстраивались на слух; в комнате хвост -8 дБ от щелчка по энергии), формулы +замкнутости/спада (пороги 0.03-0.4, веса, перекрёстная кривая - выбраны по замерам сцен, не по слуху), звучание гребёнок (металличность на +коротких слотах, пред-задержки), окраска левого и правого, 60/40 слушатель/источник, скорость скольжения посылок 0.3 с. Замкнутость +по 24 лучам вверх-вбок грубая: узкая щель в крыше может не найтись, деревья и листва (окклюзия 0) пространства не делают. Реверб не +получают относительные звуки (интерфейс, музыка) и звуки дальше 512 блоков; эхо-отводы в шину не идут. `gain_hf` слотов, `density`, +отражения слота SPR не перенесены. ## 1. Как SPR идёт от источника к результату @@ -395,7 +449,7 @@ GPL-файлы два: `acoustics/spr_occlusion.rs` и (стадия 2) `acousti классов не даёт скачка; сброс при `film_begin/film_end`; лимитер не срабатывает на нормальном налёте. - Проверка без слуха: импульсный отклик шины из `film_mix` → RT60 по спаду (`tools/acoustics_check.py`) для четырёх классов сцены (поле, ущелье, комната, тоннель) — таблица в отчёте; спад должен упорядочиться - поле < комната < тоннель < ущелье; налёт 100 источников: пиковый уровень, число срабатываний лимитера, CPU. + поле < ущелье < тоннель < комната (у ущелья открытый верх); налёт 100 источников: пиковый уровень, число срабатываний лимитера, CPU. - Критерий: хвост после конца исходного хлопка длится ожидаемое RT60 и не продолжается после смены мира. ### Стадия 4 (по #96): движущиеся источники и интеграция с #95/cinema @@ -414,3 +468,5 @@ GPL-файлы два: `acoustics/spr_occlusion.rs` и (стадия 2) `acousti - Коммит из #96 (`76f680eb…`) не найден в недавней истории `master`; разбор сделан по `453654ec`. - Мод-API `query-rays` с политикой `sound` для этого недостаточно (нет материала и полупрозрачных долей), поэтому акустика в клиенте; мод только сообщает события (#95). + +Включается кнопкой в меню мода (ещё → «Акустика»), сохраняется с миром. `HORIZON_ACOUSTICS=1` задаёт только начальное значение. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index ec208f4..e63a5bc 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -88,6 +88,7 @@ python3 tools/airdef.py play # или: python3 tools/airdef.py play --world " пересоберутся сами, если патчи изменились. - Windows: нужна видеокарта с Vulkan. Экспорт фильмов (`/airdef replay export`) требует `ffmpeg` в PATH или `HORIZON_FFMPEG`. - Шейдеры уровня шейдерпаков: `/airdef shader hd`. Для слабой видеокарты перед запуском: `$env:HORIZON_HD_SCALE="0.67"` (PowerShell). +- Преграды и эхо для звука: меню мода → «Акустика». - Создай мир с читами (или включи их через «Открыть для сети»): мод выдаёт пульты и взрывы командами. - `/airdef give` — пульты, **N** — командный пункт (роли ПВО), **K** — монитор комплекса, `/airdef wave mix 20` — налёт. Подробнее — README. diff --git a/docs/REPO-MAP.md b/docs/REPO-MAP.md new file mode 100644 index 0000000..0e7811f --- /dev/null +++ b/docs/REPO-MAP.md @@ -0,0 +1,42 @@ +# Карта репозитория + +Что здесь что: исходники, сгенерированное, архив. Порядок сборки и установки — в `README.md` и `docs/INSTALL.md`. + +## Исходники (правим руками) + +| Путь | Что это | +|---|---| +| `airdef-mod/src/`, `airdef-mod/shaders/` | Мод на Rust (WASM) для форка Horizon | +| `airdef-mod/Cargo.toml`, `horizon-mod.toml` | Сборка мода | +| `airdef-mod/tests/`, `airdef-mod/examples/` | Тесты и примеры | +| `airdef-mod/NOTES-terrain-guidance.md` | Рабочие заметки по рельефу | +| `horizon/`, `HORIZON_COMMIT`, `horizon-patches/` | Форк Horizon и патчи к нему | +| `tools/airdef.py` | Сборка мода и установка в папку игры | +| `tools/gen_models.py`, `tools/gen_tex.py`, `tools/gen_sounds.py` | Генераторы контента (см. ниже) | +| `tools/acoustics_check.py`, `tools/hd_bench.py` | Проверочные скрипты | +| `docs/` | Документация (этот файл, `INSTALL.md`, `ACOUSTICS.md`, `HD-RENDERER.md`) | +| `install.sh`, `play.sh`, `dist/` | Установка и запуск | +| `run-home/`, `run-home-bench/`, `run-home-smoke/` | Тестовые игровые папки, не часть мода | +| `screenshots/` | Скриншоты | + +## Сгенерировано (не правим руками) + +`tools/gen_models.py` создаёт: + +- `airdef-mod/assets/airdef/{blockstates,models,items,lang,textures}/` +- `airdef-mod/data/airdef/horizon/` + +Список этих файлов с sha256 лежит в `airdef-mod/generated-manifest.txt`. Генератор пишет во временный каталог, проверяет набор (ссылки моделей, blockstate и текстур; JSON; PNG; координаты элементов; парность lang) и только потом переносит файлы. При ошибке проверки ничего не записывается. Файл, который правили вручную или который занимает путь генерируемого, останавливает запуск (`КОНФЛИКТ`). + +Команды: + +- `python3 tools/gen_models.py` — перегенерировать. +- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях. + +`tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`. + +## Архив: `legacy/` + +Первая версия мода: датапак на командах (`legacy/airdef-datapack/`) и контент-мод (`legacy/airdef-content/`) с генератором `legacy/gen_content.py`. Ничего из текущей сборки на него не ссылается: ни скрипты в `tools/`, ни `install.sh`, ни `Cargo.toml`, ни исходники мода. Не собирается и не устанавливается. Оставлен как история. Не редактировать и не удалять без отдельного решения. + +`legacy/airdef-content/data/` сейчас не отслеживается git и не входит в эту карту. 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 e8337fb..ebbd762 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 01/40] Mod API (AirDef fork): world models, client particles, +Subject: [PATCH 01/41] 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 0a214e7..359116a 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 02/40] cargo-horizon-mod: report particles and sounds +Subject: [PATCH 02/41] 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 3c5fc3b..fb9d075 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 03/40] Mod API (AirDef fork): full-screen post pass for mods +Subject: [PATCH 03/41] 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 20efd8b..a7b11fd 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 04/40] Mod models: draw far models as scaled impostors past +Subject: [PATCH 04/41] 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 938e012..f54cdb1 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 05/40] Mod cameras: render.set-views draws the world from +Subject: [PATCH 05/41] 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 1b510ab..5c4e273 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 06/40] Mods: more fuel per tick and per event (AirDef plans +Subject: [PATCH 06/41] 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 index 04f87f1..0b9ccd4 100644 --- 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 @@ -1,7 +1,7 @@ From 6c548de34def8e4a624d734243418090798bd16a Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 23:25:29 +0300 -Subject: [PATCH 07/40] Mod cameras up to 1920x1080 (full-screen replays) +Subject: [PATCH 07/41] Mod cameras up to 1920x1080 (full-screen replays) Co-Authored-By: Claude Opus 5.5 --- diff --git a/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch b/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch index d503f60..857bb46 100644 --- a/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch +++ b/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch @@ -1,7 +1,7 @@ From 9b9e93269d67401cc620567a884d5ce97f68d76e Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 11:15:11 +0300 -Subject: [PATCH 08/40] Mod cameras: distant terrain tiles, fog measured from +Subject: [PATCH 08/41] Mod cameras: distant terrain tiles, fog measured from the camera, no impostors while one is shown Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch b/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch index b8238d7..bd568eb 100644 --- a/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch +++ b/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch @@ -1,7 +1,7 @@ From 065d9fa02966238a5bd9ff460392a1a809db0b11 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 11:25:45 +0300 -Subject: [PATCH 09/40] Mods: game.world-id, so mods keep state per world (API +Subject: [PATCH 09/41] Mods: game.world-id, so mods keep state per world (API level 9) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch b/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch index d0388fe..7d9c73a 100644 --- a/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch +++ b/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch @@ -1,7 +1,7 @@ From 1bf28135fd9a31f837323dc3a8d81ed73343d816 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 12:01:08 +0300 -Subject: [PATCH 10/40] cargo-horizon-mod: trial runs behind feature full, so a +Subject: [PATCH 10/41] cargo-horizon-mod: trial runs behind feature full, so a packing-only tool skips wasmtime Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch b/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch index 16719e8..bf1d4c7 100644 --- a/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch +++ b/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch @@ -1,7 +1,7 @@ From 0a56f5616df4699588cbcc529d4720661baa810f Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 13:18:43 +0300 -Subject: [PATCH 11/40] HD lighting: G-buffer pass, per-pixel mod point lights +Subject: [PATCH 11/41] HD lighting: G-buffer pass, per-pixel mod point lights in HDR, bloom and tone curve; render.set-lights and render.set-lighting (API level 10) diff --git a/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch b/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch index bdb83e2..495e883 100644 --- a/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch +++ b/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch @@ -1,7 +1,7 @@ From 9ebf0031fe9ba6b7f02afb26e4fd3a1ba4ddb0d0 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 13:59:43 +0300 -Subject: [PATCH 12/40] HD lighting stage 2: sun and moon shadow cascades, the +Subject: [PATCH 12/41] HD lighting stage 2: sun and moon shadow cascades, the world relit (sun by face angle and shadow, sky and block light through the lightmap), light shafts and halos, fog over it again, a light colour grade diff --git a/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch b/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch index 0f39cc7..54f0e3e 100644 --- a/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch +++ b/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch @@ -1,7 +1,7 @@ From 7a5a38f68923aec62f10bfa0df50b436474ed612 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:19:53 +0300 -Subject: [PATCH 13/40] HD: bind groups cached until a resize or a new source, +Subject: [PATCH 13/41] HD: bind groups cached until a resize or a new source, shadow passes draw only the entities that cast shadows Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch b/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch index 0e53611..6cc04d0 100644 --- a/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch +++ b/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch @@ -1,7 +1,7 @@ From 8020811e57d4b5a9ea1cd72d30ce859dc5095d35 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:25:44 +0300 -Subject: [PATCH 14/40] HD: lights culled per 16x16 tile (surface and halo +Subject: [PATCH 14/41] HD: lights culled per 16x16 tile (surface and halo lists built on the CPU), a naga test for the lighting shaders Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch b/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch index 5fb68e8..3b8f426 100644 --- a/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch +++ b/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch @@ -1,7 +1,7 @@ From 72d3fddfea329e578162656151350f0aa2efd323 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:43:36 +0300 -Subject: [PATCH 15/40] HD: GPU time per pass in the F3 timing list, +Subject: [PATCH 15/41] HD: GPU time per pass in the F3 timing list, half-resolution GTAO with a depth-aware blur Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch b/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch index 8f75c8f..501299e 100644 --- a/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch +++ b/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch @@ -1,7 +1,7 @@ From 1fd83a821bf270879d8ece5aa583f200ed920d89 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:02:02 +0300 -Subject: [PATCH 16/40] HD: shadows draw only sun-facing quads and skip buried +Subject: [PATCH 16/41] HD: shadows draw only sun-facing quads and skip buried sections, the far cascade every second frame; TAA (Halton jitter, reprojection by depth, YCoCg variance clipping) before bloom diff --git a/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch b/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch index e585c45..746a59f 100644 --- a/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch +++ b/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch @@ -1,7 +1,7 @@ From 1502d359d599228fe0f44ce6b99a3fded2ac5ea0 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:02:02 +0300 -Subject: [PATCH 17/40] Mods: model handles (render.model-id, model-generation, +Subject: [PATCH 17/41] Mods: model handles (render.model-id, model-generation, set-models-by-id; API level 11) so mods send no model names each tick; clear-post and set-lighting documented diff --git a/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch b/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch index d6fa932..5b5e724 100644 --- a/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch +++ b/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch @@ -1,7 +1,7 @@ From 0f9d99b8ad3e4b72e621d84c2396cf1d3d2b7a33 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:19:57 +0300 -Subject: [PATCH 18/40] HD: temporal upscaling (HORIZON_HD_SCALE: world, +Subject: [PATCH 18/41] HD: temporal upscaling (HORIZON_HD_SCALE: world, G-buffer and lighting at a lower size, rebuilt to the window in the TAA pass); fix flickering shadows near the player (the near cascade lost its sections on frames the far one was held, the held far matrix ignored the diff --git a/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch b/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch index bfdf2e7..4f7d68c 100644 --- a/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch +++ b/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch @@ -1,7 +1,7 @@ From 38250c4392e27d5700842ca6ee47291dd1831b72 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:47:52 +0300 -Subject: [PATCH 19/40] HD water: its own pass (colour, normal, depth), the +Subject: [PATCH 19/41] HD water: its own pass (colour, normal, depth), the floor under it lit, a composite with world-space waves, refraction with depth absorption in the biome colour, screen-space reflections, Fresnel and a shadowed sun glint (HORIZON_HD_WATER=0 to switch off) diff --git a/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch b/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch index b21ea96..471bc49 100644 --- a/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch +++ b/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch @@ -1,7 +1,7 @@ From dbc6f8a6e9c2eeabe1de15f1794013c90be7faa5 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:56:04 +0300 -Subject: [PATCH 20/40] HD water: no vanilla texture on the surface (the biome +Subject: [PATCH 20/41] HD water: no vanilla texture on the surface (the biome colour only), a darker, deeper colour Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch b/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch index 302e1e1..6ac7af7 100644 --- a/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch +++ b/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch @@ -1,7 +1,7 @@ From 13e74537dd6e63482e3613e0e416de1158944dfe Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 18:38:19 +0300 -Subject: [PATCH 21/40] HD sky and light: a physical atmosphere (Rayleigh, Mie, +Subject: [PATCH 21/41] HD sky and light: a physical atmosphere (Rayleigh, Mie, ozone; constants and transmittance after Photon, MIT) for the sky, haze, fog and water reflections; warmer sunlight from the atmosphere's transmittance, a gentle sky-coloured ambient, soft PCSS-lite shadows near the player, a haze diff --git a/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch b/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch index 9c04cc7..aaff9ec 100644 --- a/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch +++ b/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch @@ -1,7 +1,7 @@ From 6277e051a89c2537570982f6ef275887193c05cf Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 19:02:16 +0300 -Subject: [PATCH 22/40] HD water: a darker blue, a little clearer, ripples a +Subject: [PATCH 22/41] HD water: a darker blue, a little clearer, ripples a little higher Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch b/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch index deff9e9..a874bde 100644 --- a/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch +++ b/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch @@ -1,7 +1,7 @@ From 982265d21bb9d74ec0040db03feb5a55762286ad Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 21:41:48 +0300 -Subject: [PATCH 23/40] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun +Subject: [PATCH 23/41] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun tint, blue hour; MIT), volumetric clouds with ground shadows instead of vanilla's in HD, volumetric fog with sun shafts and morning mist (HORIZON_HD_CLOUDS=0, HORIZON_HD_VOLFOG=0) diff --git a/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch b/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch index b9bf9c3..e6ecb41 100644 --- a/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch +++ b/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch @@ -1,7 +1,7 @@ From 24971b3c67d8c87673eb2e0d204cedf8a2f46d1c Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 21:43:22 +0300 -Subject: [PATCH 24/40] Mods: world queries for simulations (render.query-rays, +Subject: [PATCH 24/41] Mods: world queries for simulations (render.query-rays, query-sections, world-changes; API level 12): block-exact rays and section occupancy by collision, sight or sound, answered next tick within budgets, and a log of changed sections diff --git a/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch b/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch index 405f47b..3ee76bf 100644 --- a/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch +++ b/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch @@ -1,7 +1,7 @@ From fdec4960983bdff82f3793460f9a5234f0cd3f49 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 22:56:15 +0300 -Subject: [PATCH 25/40] HD fixes: rain level from the world not from rain +Subject: [PATCH 25/41] HD fixes: rain level from the world not from rain geometry (#41), TAA history on the jittered grid (#38), vanilla cloud tint without a depth heuristic (#35), air fog once over water (#37), translucent things in front of HD water (#36), cheaper sunrise fan (#39), halos in thick diff --git a/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch b/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch index d0cb3f7..430a6f4 100644 --- a/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch +++ b/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch @@ -1,7 +1,7 @@ From 21391afb26f49505d6cdaf454a6355cd4e747503 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 23:19:53 +0300 -Subject: [PATCH 26/40] HD split into modules (gfx/hd/: one Rust file and one +Subject: [PATCH 26/41] HD split into modules (gfx/hd/: one Rust file and one WGSL file per pass, a shared prelude), contracts for colour, depth, alpha, time and coordinates written down, tests that the frame layout and bindings match between Rust and WGSL (#45) diff --git a/horizon-patches/0027-HD-clouds-noise-scales-that-divide-the-camera-s-6553.patch b/horizon-patches/0027-HD-clouds-noise-scales-that-divide-the-camera-s-6553.patch index 78d7712..e02c262 100644 --- a/horizon-patches/0027-HD-clouds-noise-scales-that-divide-the-camera-s-6553.patch +++ b/horizon-patches/0027-HD-clouds-noise-scales-that-divide-the-camera-s-6553.patch @@ -1,7 +1,7 @@ From 8d4cadbf8534309ac847d34e229f6d764770475d Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 23:22:19 +0300 -Subject: [PATCH 27/40] HD clouds: noise scales that divide the camera's +Subject: [PATCH 27/41] HD clouds: noise scales that divide the camera's 65536-block wrap, so the clouds and their shadows no longer jump at x or z = 0 diff --git a/horizon-patches/0028-HD-volumetric-smoke-and-missile-trails-with-clear-tu.patch b/horizon-patches/0028-HD-volumetric-smoke-and-missile-trails-with-clear-tu.patch index 3c7add6..1467528 100644 --- a/horizon-patches/0028-HD-volumetric-smoke-and-missile-trails-with-clear-tu.patch +++ b/horizon-patches/0028-HD-volumetric-smoke-and-missile-trails-with-clear-tu.patch @@ -1,7 +1,7 @@ From 0fb59c782abf269fe555faa3241b31acf41e26d7 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 03:17:11 +0300 -Subject: [PATCH 28/40] HD: volumetric smoke and missile trails with clear +Subject: [PATCH 28/41] HD: volumetric smoke and missile trails with clear tunnels through fog and cloud (render.set-smoke, API level 14; #54); sun speculars by material, wet surfaces and puddles in rain, wind in foliage (HORIZON_HD_SPECULAR=0, HORIZON_HD_WIND=0, HORIZON_HD_SMOKE=0); HD shaders diff --git a/horizon-patches/0029-HD-clouds-composited-by-depth-so-terrain-and-vehicle.patch b/horizon-patches/0029-HD-clouds-composited-by-depth-so-terrain-and-vehicle.patch index 2d7dee7..1085e06 100644 --- a/horizon-patches/0029-HD-clouds-composited-by-depth-so-terrain-and-vehicle.patch +++ b/horizon-patches/0029-HD-clouds-composited-by-depth-so-terrain-and-vehicle.patch @@ -1,7 +1,7 @@ From e4bc29da45d0d38244c6eb2ba3ffb9ab853540c0 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 03:26:09 +0300 -Subject: [PATCH 29/40] HD clouds composited by depth so terrain and vehicles +Subject: [PATCH 29/41] HD clouds composited by depth so terrain and vehicles inside or behind the layer are hidden and those in front stay in front (#67); world-anchored noise everywhere (cloud detail by height above the layer, fog, smoke and puddle scales dividing the wrap) (#68); the replay's time is visual diff --git a/horizon-patches/0030-HD-smoke-young-trails-drawn-at-least-as-wide-as-a-gr.patch b/horizon-patches/0030-HD-smoke-young-trails-drawn-at-least-as-wide-as-a-gr.patch index e4d42be..b871b95 100644 --- a/horizon-patches/0030-HD-smoke-young-trails-drawn-at-least-as-wide-as-a-gr.patch +++ b/horizon-patches/0030-HD-smoke-young-trails-drawn-at-least-as-wide-as-a-gr.patch @@ -1,7 +1,7 @@ From 20f699796afb12b600236a4e8859cd97430f86f0 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 03:44:45 +0300 -Subject: [PATCH 30/40] HD smoke: young trails drawn at least as wide as a grid +Subject: [PATCH 30/41] HD smoke: young trails drawn at least as wide as a grid cell (density scaled to keep the mass), gentler bulges, so a trail is a smooth ribbon and not a chain of puffs diff --git a/horizon-patches/0031-Mods-render.set-main-view-API-level-15-renders-the-s.patch b/horizon-patches/0031-Mods-render.set-main-view-API-level-15-renders-the-s.patch index 344d18b..2add094 100644 --- a/horizon-patches/0031-Mods-render.set-main-view-API-level-15-renders-the-s.patch +++ b/horizon-patches/0031-Mods-render.set-main-view-API-level-15-renders-the-s.patch @@ -1,7 +1,7 @@ From 35ffbaa26dd91855c8b93446646ba8c58448d3d0 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 03:59:41 +0300 -Subject: [PATCH 31/40] Mods: render.set-main-view (API level 15) renders the +Subject: [PATCH 31/41] Mods: render.set-main-view (API level 15) renders the screen's world from a mod camera with the full pipeline, so replays get HD and the post effects; small mod views get the post pass with their own camera diff --git a/horizon-patches/0032-Spot-lights-for-mods-render.set-spot-lights-API-leve.patch b/horizon-patches/0032-Spot-lights-for-mods-render.set-spot-lights-API-leve.patch index 2711798..cfb40c0 100644 --- a/horizon-patches/0032-Spot-lights-for-mods-render.set-spot-lights-API-leve.patch +++ b/horizon-patches/0032-Spot-lights-for-mods-render.set-spot-lights-API-leve.patch @@ -1,7 +1,7 @@ From 27e24527550942695164dd3a769a42a659e797ca Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 09:28:05 +0300 -Subject: [PATCH 32/40] Spot lights for mods (render.set-spot-lights, API level +Subject: [PATCH 32/41] Spot lights for mods (render.set-spot-lights, API level 16): surfaces lit in the cone, a volumetric beam stopped by depth (#60); film capture (render.capture-*, set-film-quality, API level 17): fixed-step clock, frames piped to ffmpeg or PNGs, offline audio, no chat in the frames (#58); diff --git a/horizon-patches/0033-HD-clouds-and-fog-polish-cloud-panorama-cirrus-terra.patch b/horizon-patches/0033-HD-clouds-and-fog-polish-cloud-panorama-cirrus-terra.patch index f6e7a00..f4af40a 100644 --- a/horizon-patches/0033-HD-clouds-and-fog-polish-cloud-panorama-cirrus-terra.patch +++ b/horizon-patches/0033-HD-clouds-and-fog-polish-cloud-panorama-cirrus-terra.patch @@ -1,7 +1,7 @@ From 615f5c3fa7c19a9895f8972a88333c6f250ad78a Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 14:30:39 +0300 -Subject: [PATCH 33/40] HD clouds and fog polish: cloud panorama, cirrus, +Subject: [PATCH 33/41] HD clouds and fog polish: cloud panorama, cirrus, terrain-aware fog, far smoke cascade; replay world log and film clock; material overlays by sprite name diff --git a/horizon-patches/0034-HD-coloured-sun-through-glass-and-leaves-rain-ripple.patch b/horizon-patches/0034-HD-coloured-sun-through-glass-and-leaves-rain-ripple.patch index e748bea..eef7ae5 100644 --- a/horizon-patches/0034-HD-coloured-sun-through-glass-and-leaves-rain-ripple.patch +++ b/horizon-patches/0034-HD-coloured-sun-through-glass-and-leaves-rain-ripple.patch @@ -1,7 +1,7 @@ From 0254984fdcce53a4a0f2bff15f9be3b78c93842e Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 15:01:09 +0300 -Subject: [PATCH 34/40] HD: coloured sun through glass and leaves, rain ripples +Subject: [PATCH 34/41] HD: coloured sun through glass and leaves, rain ripples on water, film motion blur and depth of field Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0035-Film-export-every-frame-in-flight-reaches-the-writer.patch b/horizon-patches/0035-Film-export-every-frame-in-flight-reaches-the-writer.patch index 1c38a03..bb88d08 100644 --- a/horizon-patches/0035-Film-export-every-frame-in-flight-reaches-the-writer.patch +++ b/horizon-patches/0035-Film-export-every-frame-in-flight-reaches-the-writer.patch @@ -1,7 +1,7 @@ From 9645d3f1f47d8bb358d5630288bdd801bd874911 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 15:19:32 +0300 -Subject: [PATCH 35/40] Film export: every frame in flight reaches the writer, +Subject: [PATCH 35/41] Film export: every frame in flight reaches the writer, listener follows the main view, cloud wind on film frames, set-smoke reports real activity diff --git a/horizon-patches/0036-Mod-command-trees-command.set-tree-and-set-suggestio.patch b/horizon-patches/0036-Mod-command-trees-command.set-tree-and-set-suggestio.patch index ccd7b10..d37f8f5 100644 --- a/horizon-patches/0036-Mod-command-trees-command.set-tree-and-set-suggestio.patch +++ b/horizon-patches/0036-Mod-command-trees-command.set-tree-and-set-suggestio.patch @@ -1,7 +1,7 @@ From 22d6835507d5627b0fe4a749b082b025b35e0262 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 15:43:11 +0300 -Subject: [PATCH 36/40] Mod command trees: command.set-tree and +Subject: [PATCH 36/41] Mod command trees: command.set-tree and set-suggestions, typed parse, colouring and completion from one tree (API 19) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0037-Persistent-mod-sound-sources-start-update-stop-with-.patch b/horizon-patches/0037-Persistent-mod-sound-sources-start-update-stop-with-.patch index b70764a..7706e81 100644 --- a/horizon-patches/0037-Persistent-mod-sound-sources-start-update-stop-with-.patch +++ b/horizon-patches/0037-Persistent-mod-sound-sources-start-update-stop-with-.patch @@ -1,7 +1,7 @@ From 9be21a54fff055e78db245488c28a971a823fdba Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 16:10:23 +0300 -Subject: [PATCH 37/40] Persistent mod sound sources: start, update, stop with +Subject: [PATCH 37/41] Persistent mod sound sources: start, update, stop with generations, click-free voices, loop sections, voice budget and virtual loops (API 20) diff --git a/horizon-patches/0038-HD-clouds-rays-from-a-far-point-so-the-view-bob-s-ey.patch b/horizon-patches/0038-HD-clouds-rays-from-a-far-point-so-the-view-bob-s-ey.patch index 83994a1..8aeeb13 100644 --- a/horizon-patches/0038-HD-clouds-rays-from-a-far-point-so-the-view-bob-s-ey.patch +++ b/horizon-patches/0038-HD-clouds-rays-from-a-far-point-so-the-view-bob-s-ey.patch @@ -1,7 +1,7 @@ From e84cdc21a9fabc4518c18edbeacb2df24c85b983 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 19:07:37 +0300 -Subject: [PATCH 38/40] HD clouds: rays from a far point, so the view bob's eye +Subject: [PATCH 38/41] HD clouds: rays from a far point, so the view bob's eye offset does not bend them Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0039-Acoustics-stage-1-direct-path-occlusion-ported-from-.patch b/horizon-patches/0039-Acoustics-stage-1-direct-path-occlusion-ported-from-.patch index e3cb043..a66923e 100644 --- a/horizon-patches/0039-Acoustics-stage-1-direct-path-occlusion-ported-from-.patch +++ b/horizon-patches/0039-Acoustics-stage-1-direct-path-occlusion-ported-from-.patch @@ -1,7 +1,7 @@ From 19f07ff4295766c7bee4bd1fbfc509b6a82d12d4 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 22:09:23 +0300 -Subject: [PATCH 39/40] Acoustics stage 1: direct-path occlusion ported from +Subject: [PATCH 39/41] Acoustics stage 1: direct-path occlusion ported from Sound Physics Remastered 453654e (GPL-3.0, separate files), off by default; stereo output on surround devices; mixer sum in a fixed order (API 21) diff --git a/horizon-patches/0040-Mod-chunk-tickets-through-the-server-thread-API-22-s.patch b/horizon-patches/0040-Mod-chunk-tickets-through-the-server-thread-API-22-s.patch index 039b258..3b807d7 100644 --- a/horizon-patches/0040-Mod-chunk-tickets-through-the-server-thread-API-22-s.patch +++ b/horizon-patches/0040-Mod-chunk-tickets-through-the-server-thread-API-22-s.patch @@ -1,7 +1,7 @@ From 449edb87be5b5ddc61d0d2fbeef3a91316a97b62 Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 30 Oct 2026 23:44:14 +0300 -Subject: [PATCH 40/40] Mod chunk tickets through the server thread (API 22), +Subject: [PATCH 40/41] Mod chunk tickets through the server thread (API 22), softer searchlights and light halos, acoustics stage 2: echo taps Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0041-Mod-canvas-with-terrain-tiles-and-mouse-input-API-24.patch b/horizon-patches/0041-Mod-canvas-with-terrain-tiles-and-mouse-input-API-24.patch new file mode 100644 index 0000000..4191a39 --- /dev/null +++ b/horizon-patches/0041-Mod-canvas-with-terrain-tiles-and-mouse-input-API-24.patch @@ -0,0 +1,2641 @@ +From ce3b535af682ff475e5256a05136f653a2e2608c Mon Sep 17 00:00:00 2001 +From: chexit +Date: Sat, 31 Oct 2026 00:59:02 +0300 +Subject: [PATCH 41/41] Mod canvas with terrain tiles and mouse input (API 24), + set-acoustics (API 23), acoustics stage 3: reverb + +Co-Authored-By: Claude Opus 5.5 +--- + crates/horizon-client/src/acoustics.rs | 221 ++++++++++- + .../src/acoustics/THIRD_PARTY_SPR.md | 10 + + crates/horizon-client/src/acoustics/echo.rs | 14 +- + crates/horizon-client/src/acoustics/room.rs | 271 +++++++++++++ + .../src/acoustics/spr_reverb.rs | 63 +++ + crates/horizon-client/src/audio.rs | 295 +++++++++++++- + crates/horizon-client/src/audio/reverb.rs | 374 ++++++++++++++++++ + crates/horizon-client/src/game.rs | 4 +- + crates/horizon-client/src/game/mod_canvas.rs | 271 +++++++++++++ + crates/horizon-client/src/game/mod_input.rs | 6 + + crates/horizon-client/src/game/mod_render.rs | 3 +- + crates/horizon-client/src/game/mods.rs | 51 ++- + crates/horizon-client/src/hud.rs | 4 + + crates/horizon-client/src/minimap.rs | 104 +++++ + crates/horizon-mod-sdk/wit/horizon.wit | 65 +++ + crates/horizon-mods/src/api_level.rs | 12 +- + crates/horizon-mods/src/runtime.rs | 107 ++++- + docs/api/mods-reference.md | 45 +++ + 18 files changed, 1894 insertions(+), 26 deletions(-) + create mode 100644 crates/horizon-client/src/acoustics/room.rs + create mode 100644 crates/horizon-client/src/acoustics/spr_reverb.rs + create mode 100644 crates/horizon-client/src/audio/reverb.rs + create mode 100644 crates/horizon-client/src/game/mod_canvas.rs + +diff --git a/crates/horizon-client/src/acoustics.rs b/crates/horizon-client/src/acoustics.rs +index 323685878..7dd895d83 100644 +--- a/crates/horizon-client/src/acoustics.rs ++++ b/crates/horizon-client/src/acoustics.rs +@@ -21,13 +21,21 @@ + //! listener, and handed to the mixer by [`Acoustics::take_echoes`]; only [`ECHO_VOICES`] sounds + //! at a time get them. + //! +-//! `HORIZON_ACOUSTICS=1` turns it on; off (the default) nothing here runs and the mixer is the +-//! mixer it was. ++//! Stage 3 adds the reverb (`room`): rays from the listener (and from each echo source, in its ++//! echo trace) measure how enclosed, how large and how reflective the space is, which gives the ++//! level and decay of the reverb; each sound is told its sends to SPR's four slots ++//! ([`Acoustics::take_sends`]) and the mixer's shared reverb does the rest (`audio/reverb.rs`). ++//! ++//! `HORIZON_ACOUSTICS=1` or a mod (`render.set-acoustics`) turns it on; off (the default) nothing ++//! here runs and the mixer is the mixer it was. + pub mod echo; ++pub mod room; + pub mod spr_bounce; + pub mod spr_occlusion; ++pub mod spr_reverb; + + pub use echo::Tap; ++pub use room::Room; + use spr_occlusion::run_occlusion; + + use crate::chunk::{Chunk, HEIGHT, MIN_Y}; +@@ -65,6 +73,10 @@ const ECHO_JOB_CELLS: usize = 240_000; + const ECHO_FILM_CELLS: usize = 480_000; + /// Cached echo estimates. + const ECHO_CACHE: usize = 256; ++/// Cells one room measure may walk (about 2 thousand in a field, 20 thousand in a maze). ++const ROOM_CELLS: usize = 60_000; ++/// Cached rooms of listener cells. ++const ROOM_CACHE: usize = 64; + /// Change records kept to judge a job that returns late. + const LOG: usize = 2048; + +@@ -190,10 +202,23 @@ fn box_touches(min: [i32; 3], max: [i32; 3], s: Cell) -> bool { + #[derive(Clone, Debug)] + struct EchoEntry { + taps: Vec, ++ /// The space round the source (None: not measured). ++ room: Room, + min: [i32; 3], + max: [i32; 3], + used: u64, + } ++/// The space round the listener's block. ++#[derive(Clone, Copy, Debug)] ++struct RoomEntry { ++ room: Room, ++ used: u64, ++} ++/// The box a room measure from `cell` looked in. ++fn room_box(cell: Cell) -> ([i32; 3], [i32; 3]) { ++ let r = room::LEN as i32 + 1; ++ ([cell.0 - r, cell.1 - r, cell.2 - r], [cell.0 + r, cell.1 + r, cell.2 + r]) ++} + + /// What the engine measured, for `status`. + #[derive(Clone, Debug, Default)] +@@ -223,6 +248,14 @@ pub struct Stats { + pub ticks: u64, + /// Sources that deserved echoes but were over the cap, in steps. + pub echo_capped: u64, ++ /// Room measures made, the cache's hits, the cells they walked, the sends told to the mixer, and ++ /// the space now (enclosure of the listener's room, the decay it gives, seconds). ++ pub room_traces: u64, ++ pub room_hits: u64, ++ pub room_cells: u64, ++ pub sends: u64, ++ pub room_enclosed: f32, ++ pub room_decay: f32, + } + + struct Job { +@@ -231,11 +264,13 @@ struct Job { + listener: [f64; 3], + items: Vec<(Key, [f64; 3], usize)>, + echoes: Vec, ++ rooms: Vec, + } + struct Done { + seq: u64, + entries: Vec<(Key, Entry)>, + echoes: Vec<(Key, EchoEntry, u64)>, ++ rooms: Vec<(Cell, Room)>, + cells: usize, + unknown: usize, + } +@@ -254,8 +289,16 @@ fn centre(c: Cell) -> [f64; 3] { + fn trace_echo(geometry: &dyn Geometry, key: Key, budget: &mut usize, clock: u64) -> (EchoEntry, usize, usize, u64) { + let start = std::time::Instant::now(); + let t = echo::trace(geometry, centre(key.0), centre(key.1), budget); ++ // The space round the source has a budget of its own: running out must not read as a field. ++ let mut room_budget = ROOM_CELLS; ++ let m = room::measure(geometry, centre(key.0), &mut room_budget); + let us = start.elapsed().as_micros() as u64; +- (EchoEntry { taps: t.taps, min: t.min, max: t.max, used: clock }, t.cells, t.unknown, us) ++ ( ++ EchoEntry { taps: t.taps, room: m.room, min: t.min, max: t.max, used: clock }, ++ t.cells + m.cells, ++ t.unknown + m.unknown, ++ us, ++ ) + } + + fn cell_of(p: [f64; 3]) -> Cell { +@@ -302,6 +345,11 @@ pub struct Acoustics { + /// What the mixer was last told, and the changes it has not been told yet. + echo_applied: HashMap>, + echo_pending: Vec<(u32, Vec)>, ++ room_cache: HashMap, ++ /// The space the listener is in now (the last one measured: it stays while the next is on its way). ++ room_now: Option, ++ sends_applied: HashMap, ++ sends_pending: Vec<(u32, [f32; 4])>, + pub stats: Stats, + } + +@@ -321,6 +369,10 @@ impl Acoustics { + echo_cache: HashMap::new(), + echo_applied: HashMap::new(), + echo_pending: Vec::new(), ++ room_cache: HashMap::new(), ++ room_now: None, ++ sends_applied: HashMap::new(), ++ sends_pending: Vec::new(), + stats: Stats::default(), + } + } +@@ -332,6 +384,7 @@ impl Acoustics { + self.echo_cache.clear(); + self.echo_applied.clear(); + self.echo_pending.clear(); ++ self.forget_rooms(); + self.log.clear(); + // A job in flight returns into a world that is gone: its sequence number is stale. + self.seq += 1; +@@ -339,6 +392,13 @@ impl Acoustics { + self.in_flight = None; + } + ++ fn forget_rooms(&mut self) { ++ self.room_cache.clear(); ++ self.room_now = None; ++ self.sends_applied.clear(); ++ self.sends_pending.clear(); ++ } ++ + fn spawn(&mut self) { + let (job_tx, job_rx) = std::sync::mpsc::channel::(); + let (done_tx, done_rx) = std::sync::mpsc::channel::(); +@@ -349,6 +409,7 @@ impl Acoustics { + let mut entries = Vec::with_capacity(job.items.len()); + let mut echoes = Vec::with_capacity(job.echoes.len()); + let mut echo_budget = ECHO_JOB_CELLS; ++ let mut rooms = Vec::with_capacity(job.rooms.len()); + for (key, at, paths) in job.items { + let (entry, c, u) = trace(&*job.geometry, job.listener, at, paths, &mut budget); + cells += c; +@@ -361,7 +422,14 @@ impl Acoustics { + unknown += u; + echoes.push((key, e, us)); + } +- if done_tx.send(Done { seq: job.seq, entries, echoes, cells, unknown }).is_err() { ++ for cell in job.rooms { ++ let mut b = ROOM_CELLS; ++ let m = room::measure(&*job.geometry, centre(cell), &mut b); ++ cells += m.cells; ++ unknown += m.unknown; ++ rooms.push((cell, m.room)); ++ } ++ if done_tx.send(Done { seq: job.seq, entries, echoes, rooms, cells, unknown }).is_err() { + break; + } + } +@@ -379,6 +447,7 @@ impl Acoustics { + self.echo_cache.clear(); + self.echo_applied.clear(); + self.echo_pending.clear(); ++ self.forget_rooms(); + self.log.clear(); + self.seq += 1; + self.floor = self.seq; +@@ -391,6 +460,10 @@ impl Acoustics { + self.cache.retain(|_, e| !e.touches(s)); + self.stats.invalidated += (before - self.cache.len()) as u64; + self.echo_cache.retain(|_, e| !box_touches(e.min, e.max, s)); ++ self.room_cache.retain(|&c, _| { ++ let (lo, hi) = room_box(c); ++ !box_touches(lo, hi, s) ++ }); + self.log.push_back((self.seq, s)); + } + while self.log.len() > LOG { +@@ -448,7 +521,7 @@ impl Acoustics { + self.stats.unknown_cells += d.unknown as u64; + self.stats.jobs += 1; + if d.seq <= self.floor { +- self.stats.dropped_late += (d.entries.len() + d.echoes.len()) as u64; ++ self.stats.dropped_late += (d.entries.len() + d.echoes.len() + d.rooms.len()) as u64; + continue; + } + for (key, e, us) in d.echoes { +@@ -462,6 +535,15 @@ impl Acoustics { + self.insert_echo(key, e); + } + } ++ for (cell, room) in d.rooms { ++ let (lo, hi) = room_box(cell); ++ self.stats.room_traces += 1; ++ if self.log.iter().any(|(s, c)| *s >= d.seq && box_touches(lo, hi, *c)) { ++ self.stats.dropped_late += 1; ++ } else { ++ self.room_cache.insert(cell, RoomEntry { room, used: self.clock }); ++ } ++ } + for (key, e) in d.entries { + if self.log.iter().any(|(s, c)| *s >= d.seq && e.touches(*c)) { + self.stats.dropped_late += 1; +@@ -478,6 +560,7 @@ impl Acoustics { + .collect(); + self.stats.sources = live.len(); + self.applied.retain(|id, _| sources.iter().any(|s| s.id == *id)); ++ self.sends_applied.retain(|id, _| sources.iter().any(|s| s.id == *id)); + self.echo_applied.retain(|id, _| sources.iter().any(|s| s.id == *id)); + let Some(geometry) = geometry else { + return self.settle(&live, listener, None); +@@ -517,7 +600,9 @@ impl Acoustics { + } + } + let echo_keys = self.settle_echoes(&**geometry, &live, &order, listener); +- let job_empty = job.is_empty() && echo_keys.is_empty(); ++ let rooms = self.settle_room(&**geometry, listener); ++ self.settle_sends(&live, listener); ++ let job_empty = job.is_empty() && echo_keys.is_empty() && rooms.is_empty(); + if !job_empty && !self.sync { + if self.worker.is_none() { + self.spawn(); +@@ -528,7 +613,7 @@ impl Acoustics { + self.seq += 1; + let seq = self.seq; + if tx +- .send(Job { seq, geometry: geometry.clone(), listener, items: job, echoes: echo_keys }) ++ .send(Job { seq, geometry: geometry.clone(), listener, items: job, echoes: echo_keys, rooms }) + .is_ok() + { + self.in_flight = Some(seq); +@@ -591,6 +676,71 @@ impl Acoustics { + want + } + ++ /// The space the listener is in: from the cache, measured at once (a film) or asked of the ++ /// worker (the cell is returned). The last known space stays until the new one is. ++ fn settle_room(&mut self, geometry: &dyn Geometry, listener: [f64; 3]) -> Vec { ++ let cell = block_of(listener); ++ if let Some(e) = self.room_cache.get_mut(&cell) { ++ e.used = self.clock; ++ self.stats.room_hits += 1; ++ self.room_now = Some(e.room); ++ } else if self.sync { ++ let mut budget = ROOM_CELLS; ++ let m = room::measure(geometry, centre(cell), &mut budget); ++ self.stats.room_traces += 1; ++ self.stats.room_cells += m.cells as u64; ++ self.stats.unknown_cells += m.unknown as u64; ++ self.room_cache.insert(cell, RoomEntry { room: m.room, used: self.clock }); ++ self.room_now = Some(m.room); ++ } else { ++ return vec![cell]; ++ } ++ if self.room_cache.len() > ROOM_CACHE { ++ let mut ages: Vec = self.room_cache.values().map(|e| e.used).collect(); ++ ages.sort_unstable(); ++ let cut = ages[ages.len() / 4]; ++ self.room_cache.retain(|_, e| e.used > cut); ++ } ++ if let Some(r) = &self.room_now { ++ let (_, decay) = room::wet_and_decay(r); ++ self.stats.room_enclosed = r.enclosed; ++ self.stats.room_decay = decay; ++ } ++ Vec::new() ++ } ++ ++ /// Each live sound's sends to the reverb slots, from the listener's space and, for the sounds ++ /// whose own space is known (the echo ones), a blend with it. Only the changed ones are queued. ++ fn settle_sends(&mut self, live: &[Source], listener: [f64; 3]) { ++ let Some(now) = self.room_now else { ++ return; ++ }; ++ let lcell = block_of(listener); ++ for s in live { ++ let source = if s.echo { self.echo_cache.get(&(block_of(s.at), lcell)).map(|e| e.room) } else { None }; ++ let to = room::sends(&room::space(&now, source.as_ref())); ++ let changed = match self.sends_applied.get(&s.id) { ++ Some(prev) => (0..4).any(|k| (prev[k] - to[k]).abs() > 0.01), ++ None => to != [0.0; 4], ++ }; ++ if changed { ++ self.sends_applied.insert(s.id, to); ++ self.sends_pending.push((s.id, to)); ++ self.stats.sends += 1; ++ } ++ } ++ } ++ ++ /// The space the listener is in now, if it has been measured. ++ pub fn room_now(&self) -> Option { ++ self.room_now ++ } ++ ++ /// The reverb sends that changed since the last call, by sound id. ++ pub fn take_sends(&mut self) -> Vec<(u32, [f32; 4])> { ++ std::mem::take(&mut self.sends_pending) ++ } ++ + /// The numbers for each live source from the cache; only the changed ones are returned. + fn settle(&mut self, live: &[Source], listener: [f64; 3], lcell: Option) -> Vec { + let lcell = lcell.unwrap_or_else(|| cell_of(listener)); +@@ -730,15 +880,16 @@ mod tests { + } + panic!("the worker did not answer"); + }; +- wait(&mut a, 1, &s); ++ // (The first job measured the room round the listener; the second refines the source.) ++ wait(&mut a, 2, &s); + // Refined: the same cell asks nothing more. + for _ in 0..3 { + a.step(Some(&wall), l, &s, &Changes::default()); + } +- assert_eq!(a.stats.jobs, 1); ++ assert_eq!(a.stats.jobs, 2); + // A moved source in a new cell goes to the worker too. + let moved = [src(1, 94.5)]; +- wait(&mut a, 2, &moved); ++ wait(&mut a, 3, &moved); + assert_eq!(a.stats.traces, 1, "the game thread traced only the new source"); + } + +@@ -832,4 +983,54 @@ mod tests { + } + panic!("the worker did not answer"); + } ++ ++ fn hall() -> Arc { ++ Arc::new(Blocks(Box::new(|x, y, z| !((0..24).contains(&x) && (60..70).contains(&y) && (0..24).contains(&z))))) ++ } ++ ++ #[test] ++ fn a_room_sends_to_the_reverb_a_field_does_not_and_a_destroyed_roof_takes_it_away() { ++ let mut a = Acoustics::new(true); ++ let inside = [12.5, 64.5, 12.5]; ++ let sources = [Source { id: 1, at: [12.5, 64.5, 18.5], loud: 0.5, echo: false }, Source { id: 2, at: [5.5, 64.5, 5.5], loud: 0.5, echo: true }]; ++ a.step(Some(&hall()), inside, &sources, &Changes::default()); ++ let sends = a.take_sends(); ++ assert_eq!(sends.len(), 2); ++ assert!(sends.iter().all(|(_, s)| s.iter().any(|v| *v > 0.0))); ++ // Nothing changed: the mixer is not told again. ++ a.step(Some(&hall()), inside, &sources, &Changes::default()); ++ assert!(a.take_sends().is_empty() && a.stats.room_hits >= 1); ++ // The room is blown open: every section within reach changes, and the sends go to zero. ++ let field: Arc = Arc::new(Blocks(Box::new(|_, y, _| y <= 50))); ++ let all: Vec<(i32, i32, i32)> = (-5..6).flat_map(|x| (0..8).flat_map(move |y| (-5..6).map(move |z| (x, y, z)))).collect(); ++ a.step(Some(&field), inside, &sources, &Changes { sections: all, ..Default::default() }); ++ let gone = a.take_sends(); ++ assert_eq!(gone.len(), 2); ++ assert!(gone.iter().all(|(_, s)| *s == [0.0; 4]), "{gone:?}"); ++ // A field from the start sends nothing at all. ++ let mut b = Acoustics::new(true); ++ b.step(Some(&field), [0.5, 60.5, 0.5], &sources, &Changes::default()); ++ assert!(b.take_sends().is_empty()); ++ assert_eq!(b.stats.room_enclosed, 0.0); ++ } ++ ++ #[test] ++ fn the_worker_measures_the_room_and_a_new_world_forgets_it() { ++ let mut a = Acoustics::new(false); ++ let g = hall(); ++ let s = [Source { id: 1, at: [12.5, 64.5, 18.5], loud: 0.5, echo: false }]; ++ a.step(Some(&g), [12.5, 64.5, 12.5], &s, &Changes::default()); ++ assert!(a.take_sends().is_empty(), "not on the game thread"); ++ for _ in 0..400 { ++ a.step(Some(&g), [12.5, 64.5, 12.5], &s, &Changes::default()); ++ if !a.take_sends().is_empty() { ++ assert_eq!(a.stats.room_traces, 1); ++ a.step(Some(&g), [12.5, 64.5, 12.5], &s, &Changes { epoch: 3, ..Default::default() }); ++ assert!(a.room_now().is_none(), "the old world's room is gone"); ++ return; ++ } ++ std::thread::sleep(std::time::Duration::from_millis(5)); ++ } ++ panic!("the worker did not answer"); ++ } + } +diff --git a/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md b/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md +index 134c0e754..b98c484dc 100644 +--- a/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md ++++ b/crates/horizon-client/src/acoustics/THIRD_PARTY_SPR.md +@@ -33,3 +33,13 @@ grass, gravel and dirt 0.3, sand 0.2, snow 0.15, wool, moss and honey 0.1). What + rays (it spreads their energy over four reverb slots) is not used: the echo taps in `echo.rs` + (image sources, delays from the path length, near-reflection cutoff, selection) are our own and + MIT, as is the mixer side. ++ ++## Stage 3: `spr_reverb.rs` ++ ++`spr_reverb.rs` is derived from the same commit and licence. What is taken: from `ReverbParams.java` the ++four reverb slots (decay 0.15, 0.55, 1.68 and 4.142 s, their gains 0.2, 0.3, 0.5 and 0.4, `decay_hf_ratio` ++0.6 and 0.7, late reverb delays 0.011 and 0.021 s); from `SoundPhysics.java` the gain scale of the slots ++(`0.7 * reverb_gain * 0.85`) and the fade of the sends with distance (`reverb_distance` 1.5). What SPR does ++with them (it hands the slots to OpenAL Soft's EAX reverb, LGPL) is not used: the reverb itself ++(`audio/reverb.rs`: combs, allpasses, the stereo split), the measure of the space that decides the sends ++(`room.rs`) and the mixer side are our own and MIT. +diff --git a/crates/horizon-client/src/acoustics/echo.rs b/crates/horizon-client/src/acoustics/echo.rs +index 5f77f5345..fe4d6f1e4 100644 +--- a/crates/horizon-client/src/acoustics/echo.rs ++++ b/crates/horizon-client/src/acoustics/echo.rs +@@ -66,19 +66,19 @@ pub struct Traced { + pub unknown: usize, + } + +-struct Hit { +- axis: usize, ++pub(super) struct Hit { ++ pub(super) axis: usize, + /// +1 or -1: which way the face looks. +- normal: i32, ++ pub(super) normal: i32, + /// The plane's coordinate along `axis`. +- coord: i64, +- refl: f32, ++ pub(super) coord: i64, ++ pub(super) refl: f32, + } + +-type Surface<'a> = Box Option<(f32, f32)> + 'a>; ++pub(super) type Surface<'a> = Box Option<(f32, f32)> + 'a>; + + /// The first solid block along `dir` from `from` (not the block `from` is in), within `len`. +-fn first_hit( ++pub(super) fn first_hit( + surface: &mut Surface<'_>, + from: [f64; 3], + dir: [f64; 3], +diff --git a/crates/horizon-client/src/acoustics/room.rs b/crates/horizon-client/src/acoustics/room.rs +new file mode 100644 +index 000000000..2aaa3edd1 +--- /dev/null ++++ b/crates/horizon-client/src/acoustics/room.rs +@@ -0,0 +1,271 @@ ++//! AirDef fork: acoustics stage 3 (#96): what space a point is in. Rays that go sideways and up ++//! from the point find the walls and the roof round it: how many of them hit (enclosed), how far ++//! (size), what the walls give back (reflective). Under a roof or in a tunnel nearly all hit and ++//! near; in a field none; in a gorge some, far away. From the three numbers come the level of the ++//! reverb ("wet") and its decay, and the sends to SPR's four slots (`spr_reverb`). ++use super::echo::{Surface, first_hit}; ++use super::{Geometry, spr_bounce, spr_reverb}; ++ ++/// Rays from a point (the upper half of a Fibonacci sphere of [`RAYS`] is used: the ground does ++/// not make a room). ++pub const RAYS: usize = 48; ++/// How far a ray looks, in blocks (SPR sees 64 too). ++pub const LEN: f64 = 64.0; ++ ++/// The space round a point. ++#[derive(Clone, Copy, Debug, PartialEq)] ++pub struct Room { ++ /// 0 (nothing within reach) to 1 (walls all round and above, near). ++ pub enclosed: f32, ++ /// The mean distance of the walls found, in blocks. ++ pub size: f32, ++ /// The mean reflectivity of the walls found (SPR's table). ++ pub reflect: f32, ++} ++impl Room { ++ pub const OPEN: Room = Room { enclosed: 0.0, size: LEN as f32, reflect: spr_bounce::DEFAULT_REFLECTIVITY }; ++ /// `w` of `b` and the rest of `a`. ++ pub fn blend(a: &Room, b: &Room, w: f32) -> Room { ++ let l = |x: f32, y: f32| x + (y - x) * w; ++ Room { enclosed: l(a.enclosed, b.enclosed), size: l(a.size, b.size), reflect: l(a.reflect, b.reflect) } ++ } ++} ++ ++/// What a measure found. ++#[derive(Clone, Copy, Debug)] ++pub struct Measured { ++ pub room: Room, ++ pub cells: usize, ++ pub unknown: usize, ++} ++ ++/// The space round `at`. `budget` counts block cells, as the echo's does. ++pub fn measure(geometry: &dyn Geometry, at: [f64; 3], budget: &mut usize) -> Measured { ++ let start = *budget; ++ let mut surface: Surface<'_> = geometry.surface(); ++ let (mut rays, mut unknown) = (0usize, 0usize); ++ let (mut w_sum, mut d_sum, mut r_sum) = (0.0f64, 0.0f64, 0.0f64); ++ for i in 0..RAYS { ++ let dir = spr_bounce::fibonacci_dir(i, RAYS); ++ if dir[1] < 0.0 { ++ continue; ++ } ++ rays += 1; ++ if let Some(h) = first_hit(&mut surface, at, dir, LEN, budget, &mut unknown) { ++ let d = ((h.coord as f64 - at[h.axis]).abs() / dir[h.axis].abs().max(1e-9)).min(LEN); ++ // A wall at the edge of the reach barely rings. ++ let w = 1.0 - (d / LEN).powi(2); ++ w_sum += w; ++ d_sum += d * w; ++ r_sum += f64::from(h.refl) * w; ++ } ++ } ++ let room = if w_sum > 1e-9 && rays > 0 { ++ Room { ++ enclosed: (w_sum / rays as f64) as f32, ++ size: (d_sum / w_sum) as f32, ++ reflect: (r_sum / w_sum) as f32, ++ } ++ } else { ++ Room::OPEN ++ }; ++ Measured { room, cells: start - *budget, unknown } ++} ++ ++/// The space a sound is heard in: the listener's, and, where the sound's own is known, a blend ++/// (the listener's counts more: it is where the ear is). ++pub fn space(listener: &Room, source: Option<&Room>) -> Room { ++ match source { ++ Some(s) => Room::blend(listener, s, 0.4), ++ None => *listener, ++ } ++} ++ ++fn smoothstep(a: f32, b: f32, x: f32) -> f32 { ++ let t = ((x - a) / (b - a)).clamp(0.0, 1.0); ++ t * t * (3.0 - 2.0 * t) ++} ++ ++/// The level (0..1) and decay (s) of the reverb of a space. Nothing below an enclosure of 0.03 (a ++/// field with a hill or two); the decay grows with the square of the enclosure (a half-open gorge ++/// does not ring like a hall), with the size of the walls up to 30 blocks, and with what they give back. ++pub fn wet_and_decay(room: &Room) -> (f32, f32) { ++ let e = room.enclosed.clamp(0.0, 1.0); ++ let wet = smoothstep(0.03, 0.4, e); ++ let size = 0.4 + 0.1 * room.size.clamp(0.0, 30.0); ++ let walls = 0.6 + 0.8 * room.reflect.clamp(0.0, 1.5); ++ let decay = (e * e * size * walls).clamp(spr_reverb::SLOTS[0].decay, spr_reverb::SLOTS[3].decay); ++ (wet, decay) ++} ++ ++/// The gain of the slot the sends are measured against (SPR's second). ++const LEVEL: f32 = 0.3; ++ ++/// The sends to SPR's four slots: a crossfade between the two whose decays (on a log scale) a ++/// space lies between. ++pub fn sends(room: &Room) -> [f32; 4] { ++ let (wet, decay) = wet_and_decay(room); ++ let mut out = [0.0f32; 4]; ++ if wet <= 0.0 { ++ return out; ++ } ++ let d = |i: usize| spr_reverb::SLOTS[i].decay; ++ let mut i = 0; ++ while i < 2 && decay > d(i + 1) { ++ i += 1; ++ } ++ let f = ((decay / d(i)).ln() / (d(i + 1) / d(i)).ln()).clamp(0.0, 1.0); ++ // The two slots share the energy of the send by an equal-power crossfade (no jump where one ++ // gives way to the next), and each is levelled for its own gain (SPR's slots differ in gain: ++ // a longer slot is louder), so the level of the reverb does not change with its decay. The ++ // long slot's tail is heard last and longest, so it gets the position squared: the decay that ++ // measures out is then closer to the space's than to the long slot's. ++ let angle = f * f * std::f32::consts::FRAC_PI_2; ++ for (k, w) in [(i, angle.cos()), (i + 1, angle.sin())] { ++ out[k] = wet * w * LEVEL / spr_reverb::SLOTS[k].gain; ++ } ++ out ++} ++ ++/// The RT60 a listener would read (Schroeder: the time from -5 to -35 dB of the energy decay ++/// curve, doubled) from the reverb that these sends make: the sum of the slots' exponential ++/// decays, each with the energy its send gives it. The long slot, once the short one is gone, ++/// sets the reading, so a space between two slots reads longer than the decay it was given. ++pub fn effective_decay(sends: &[f32; 4]) -> f32 { ++ let e: Vec = (0..4).map(|k| (f64::from(sends[k]) * f64::from(spr_reverb::SLOTS[k].gain) / f64::from(LEVEL)).powi(2)).collect(); ++ let total: f64 = e.iter().sum(); ++ if total <= 0.0 { ++ return 0.0; ++ } ++ let edc = |t: f64| -> f64 { ++ // 10 log10 of the energy left, relative: each slot loses 60 dB in its decay. ++ let left: f64 = (0..4).map(|k| e[k] * 10f64.powf(-6.0 * t / f64::from(spr_reverb::SLOTS[k].decay))).sum(); ++ 10.0 * (left / total).log10() ++ }; ++ let when = |db: f64| { ++ let (mut lo, mut hi) = (0.0f64, 60.0f64); ++ for _ in 0..60 { ++ let mid = 0.5 * (lo + hi); ++ if edc(mid) > db { lo = mid } else { hi = mid } ++ } ++ 0.5 * (lo + hi) ++ }; ++ (2.0 * (when(-35.0) - when(-5.0))) as f32 ++} ++ ++#[cfg(test)] ++pub(crate) mod tests { ++ use super::*; ++ ++ pub(crate) struct Blocks(Box bool + Send + Sync>); ++ impl Geometry for Blocks { ++ fn walker(&self) -> Box Option + '_> { ++ Box::new(move |x, y, z| Some(if (self.0)(x, y, z) { 1.0 } else { 0.0 })) ++ } ++ } ++ pub(crate) fn blocks(f: impl Fn(i32, i32, i32) -> bool + Send + Sync + 'static) -> Blocks { ++ Blocks(Box::new(f)) ++ } ++ /// A room of 24 x 10 x 24 (inside), a gorge of 95 between walls, a field, a tunnel 5 x 4. ++ pub(crate) fn scene(name: &str) -> (Blocks, [f64; 3]) { ++ match name { ++ "room" => (blocks(|x, y, z| !((0..24).contains(&x) && (60..70).contains(&y) && (0..24).contains(&z))), [12.5, 64.5, 12.5]), ++ "gorge" => (blocks(|x, y, _| y <= 60 || x <= -40 || x >= 55), [0.5, 66.5, 0.5]), ++ "field" => (blocks(|_, y, _| y <= 60), [0.5, 62.5, 0.5]), ++ "tunnel" => (blocks(|x, y, _| !((0..5).contains(&x) && (61..65).contains(&y))), [2.5, 62.5, 0.5]), ++ _ => unreachable!(), ++ } ++ } ++ fn room_of(name: &str) -> Room { ++ let (g, at) = scene(name); ++ let mut b = 1_000_000; ++ measure(&g, at, &mut b).room ++ } ++ ++ #[test] ++ fn a_room_is_enclosed_near_a_field_is_not_and_a_gorge_is_in_between() { ++ let (room, field, gorge, tunnel) = (room_of("room"), room_of("field"), room_of("gorge"), room_of("tunnel")); ++ assert_eq!(field, Room::OPEN); ++ assert!(room.enclosed > 0.8 && room.size < 15.0, "{room:?}"); ++ assert!(tunnel.enclosed > 0.8 && tunnel.size < room.size, "{tunnel:?}"); ++ assert!(gorge.enclosed > 0.05 && gorge.enclosed < room.enclosed * 0.6 && gorge.size > room.size, "{gorge:?}"); ++ assert_eq!(room.reflect, spr_bounce::DEFAULT_REFLECTIVITY); ++ } ++ ++ #[test] ++ fn the_decay_orders_field_gorge_room_and_a_field_has_no_send() { ++ let (f, g, r) = (sends(&room_of("field")), sends(&room_of("gorge")), sends(&room_of("room"))); ++ assert_eq!(f, [0.0; 4]); ++ let (wf, df) = wet_and_decay(&room_of("field")); ++ assert_eq!(wf, 0.0); ++ assert!(df >= 0.15); ++ let (wg, dg) = wet_and_decay(&room_of("gorge")); ++ let (wr, dr) = wet_and_decay(&room_of("room")); ++ assert!(dr > dg && wr > wg, "room {dr} s {wr}, gorge {dg} s {wg}"); ++ assert!(r.iter().map(|v| v * v).sum::() > g.iter().map(|v| v * v).sum::()); ++ // Two slots at most, and their energies add up to the level of the space. ++ for s in [g, r] { ++ assert!(s.iter().filter(|v| **v > 0.0).count() <= 2); ++ } ++ let energy: f32 = (0..4).map(|k| (r[k] * spr_reverb::SLOTS[k].gain / LEVEL).powi(2)).sum(); ++ assert!((energy - wr * wr).abs() < 1e-5, "{energy} {wr}"); ++ } ++ ++ #[test] ++ fn stone_rings_longer_than_wool_and_the_sends_move_smoothly_with_the_space() { ++ let base = Room { enclosed: 0.9, size: 10.0, reflect: 0.5 }; ++ let stone = Room { reflect: 1.5, ..base }; ++ let wool = Room { reflect: 0.1, ..base }; ++ assert!(wet_and_decay(&stone).1 > wet_and_decay(&base).1 && wet_and_decay(&base).1 > wet_and_decay(&wool).1); ++ // No jump in the sends for a small step in the space. ++ let mut prev = sends(&Room { enclosed: 0.0, ..base }); ++ for i in 1..=100 { ++ let now = sends(&Room { enclosed: i as f32 / 100.0, ..base }); ++ for k in 0..4 { ++ let level = |v: f32| v * spr_reverb::SLOTS[k].gain / LEVEL; ++ assert!((level(now[k]) - level(prev[k])).abs() < 0.15, "{i}: {prev:?} -> {now:?}"); ++ } ++ prev = now; ++ } ++ // A blend with a source in a room is between the two. ++ let mixed = space(&Room::OPEN, Some(&base)); ++ assert!(mixed.enclosed > 0.0 && mixed.enclosed < base.enclosed); ++ } ++ ++ #[test] ++ fn one_slot_reads_its_own_decay_and_a_mix_reads_longer_than_the_short_one() { ++ for k in 0..4 { ++ let mut s = [0.0; 4]; ++ s[k] = 1.0; ++ assert!((effective_decay(&s) - spr_reverb::SLOTS[k].decay).abs() < 0.01 * spr_reverb::SLOTS[k].decay); ++ } ++ assert_eq!(effective_decay(&[0.0; 4]), 0.0); ++ let mixed = effective_decay(&[0.0, 1.0, 0.2, 0.0]); ++ assert!(mixed > spr_reverb::SLOTS[1].decay && mixed < spr_reverb::SLOTS[2].decay); ++ } ++ ++ #[test] ++ fn the_budget_is_counted() { ++ let (g, at) = scene("room"); ++ let mut b = 100; ++ let m = measure(&g, at, &mut b); ++ assert!(m.cells <= 100 && b < 100); ++ } ++ ++ /// The cost of one measure in release: `cargo test -p horizon-client --lib --release ++ /// acoustics::room::tests::bench -- --ignored --nocapture`. ++ #[test] ++ #[ignore] ++ fn bench_measures() { ++ for name in ["room", "tunnel", "gorge", "field"] { ++ let (g, at) = scene(name); ++ let n = 5000; ++ let (mut cells, start) = (0, std::time::Instant::now()); ++ for i in 0..n { ++ let mut b = 1_000_000; ++ cells += measure(&g, [at[0] + (i % 3) as f64 * 0.1, at[1], at[2]], &mut b).cells; ++ } ++ println!("{name:7} {:.4} ms per measure, {} cells", start.elapsed().as_secs_f64() * 1e3 / n as f64, cells / n); ++ } ++ } ++} +diff --git a/crates/horizon-client/src/acoustics/spr_reverb.rs b/crates/horizon-client/src/acoustics/spr_reverb.rs +new file mode 100644 +index 000000000..3ff361cb7 +--- /dev/null ++++ b/crates/horizon-client/src/acoustics/spr_reverb.rs +@@ -0,0 +1,63 @@ ++// SPDX-License-Identifier: GPL-3.0-only ++// ++// Derived from Sound Physics Remastered by henkelmax and contributors ++// (https://github.com/henkelmax/sound-physics-remastered), commit ++// 453654ece086f40c97712d9016baa4dee7c4f6d2, GPL-3.0: ++// common/src/main/java/com/sonicether/soundphysics/config/ReverbParams.java (the four slots) ++// common/src/main/java/com/sonicether/soundphysics/SoundPhysics.java ++// (`setupEFX` gain scale 0.7 * 0.85, the distance fade of the sends, `reverb_distance` 1.5) ++// Ported to Rust for Horizon's own mixer reverb (`audio/reverb.rs`, ours). See THIRD_PARTY_SPR.md ++// next to this file. The rest of this crate is MIT; this file is GPL-3.0-only. ++//! The reverb side of SPR: four slots of fixed decay, to which a source sends in proportion to ++//! how much of each kind of space it hears. ++ ++/// One of SPR's four auxiliary effect slots (the EAX reverb it sets, the numbers we use). ++#[derive(Clone, Copy, Debug)] ++pub struct SlotParams { ++ /// `decay_time`, seconds. ++ pub decay: f32, ++ /// `gain` of the slot. ++ pub gain: f32, ++ /// `decay_hf_ratio`: how long the highs last, as a fraction of the decay. ++ pub decay_hf_ratio: f32, ++ /// `late_reverb_delay`, seconds. ++ pub late_delay: f32, ++} ++ ++/// The four slots, from the shortest to the longest. (Not used: `density`, `gain_hf`, the ++/// reflections' gain and delay, `decay_lf_ratio` and the rolloff: our reverb has no such knobs.) ++pub const SLOTS: [SlotParams; 4] = [ ++ SlotParams { decay: 0.15, gain: 0.2, decay_hf_ratio: 0.6, late_delay: 0.011 }, ++ SlotParams { decay: 0.55, gain: 0.3, decay_hf_ratio: 0.7, late_delay: 0.011 }, ++ SlotParams { decay: 1.68, gain: 0.5, decay_hf_ratio: 0.7, late_delay: 0.021 }, ++ SlotParams { decay: 4.142, gain: 0.4, decay_hf_ratio: 0.7, late_delay: 0.021 }, ++]; ++ ++/// The slots' gain is scaled by `0.7 * reverb_gain * 0.85` (`reverb_gain` 1). ++pub const OUTPUT_GAIN: f32 = 0.7 * 0.85; ++ ++/// `reverb_distance`: the sends fade to nothing at this many times the sound's range. ++pub const REVERB_DISTANCE: f32 = 1.5; ++ ++/// `send *= 1 - min(distance / (max_distance * reverb_distance), 1)`. ++pub fn distance_fade(distance: f32, max: f32) -> f32 { ++ if max <= 0.0 { ++ return 1.0; ++ } ++ 1.0 - (distance / (max * REVERB_DISTANCE)).min(1.0) ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn the_slots_grow_and_the_fade_reaches_zero() { ++ for w in SLOTS.windows(2) { ++ assert!(w[0].decay < w[1].decay); ++ } ++ assert_eq!(distance_fade(0.0, 100.0), 1.0); ++ assert!((distance_fade(75.0, 100.0) - 0.5).abs() < 1e-6); ++ assert_eq!(distance_fade(500.0, 100.0), 0.0); ++ } ++} +diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs +index 640206803..e03a7f5ad 100644 +--- a/crates/horizon-client/src/audio.rs ++++ b/crates/horizon-client/src/audio.rs +@@ -12,6 +12,8 @@ use crate::sound_events::{Sound, SoundRegistry}; + #[cfg(feature = "audio")] + use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + use horizon_core::random::{LegacyRandom, RandomSource}; ++mod reverb; ++use reverb::{Reverb, Send}; + use std::{ + collections::HashMap, + fs, +@@ -45,6 +47,8 @@ struct Channel { + occlusion: Option, + /// Acoustics stage 2: the echoes of the sound, copies of it delayed by the longer way. + echo: Option, ++ /// Acoustics stage 3: how much of the sound goes to the shared reverb, per slot. ++ send: Option, + } + /// The echo taps of a one-shot (AirDef fork, #96 stage 2): each reads the sound again `delay` + /// seconds behind the direct one, through a low-pass for the air it travelled, panned to where +@@ -318,6 +322,9 @@ struct Mixer { + limiter_peak: f32, + /// Film capture: the output device hears nothing, `Audio::film_mix` mixes instead. + offline: bool, ++ /// Acoustics stage 3: the shared late reverb, made when a voice first sends to it and dropped ++ /// when its tail is over. ++ reverb: Option, + } + /// A sound the player could have heard (`SoundEventListener.onPlaySound`): + /// what the subtitle overlay needs. +@@ -520,6 +527,7 @@ impl Backend for MixerBackend { + voice: None, + occlusion: None, + echo: None, ++ send: None, + }, + ); + Some(id) +@@ -705,6 +713,14 @@ fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] { + let front = azimuth.cos() * elevation.cos() * 0.095_660_8; + [0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front] + } ++/// SPR's fade of a voice's sends with its distance (`reverb_distance`), 1 for a sound that has no range. ++fn send_fade(linear: Option, relative: bool, at: [f32; 3], listener: [f64; 3]) -> f32 { ++ let (Some(max), false) = (linear, relative) else { ++ return 1.0; ++ }; ++ let d = [f64::from(at[0]) - listener[0], f64::from(at[1]) - listener[1], f64::from(at[2]) - listener[2]]; ++ crate::acoustics::spr_reverb::distance_fade((d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32, max) ++} + /// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference + /// distance 0 and rolloff 1: the distance clamps to the max distance). + fn distance_gain(linear: Option, distance: f32) -> f32 { +@@ -802,6 +818,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + // In a fixed order, so the sum (and a film's track) is the same in every run. + voices.sort_by_key(|v| v.0); + let buffer_seconds = (data.len() / channels.max(1)) as f32 / rate as f32; ++ let mut rv_in: Vec<[f32; reverb::SLOT_COUNT]> = Vec::new(); + for (id, [left, right, gain], mut step) in voices { + let Some(c) = mixer.channels.get_mut(&id) else { + continue; +@@ -826,6 +843,11 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + let frames = (data.len() / channels.max(1)).max(1); + let env_step = v.env_rate / rate as f32; + let shelf = c.occlusion.as_mut().map(|o| o.buffer(buffer_seconds, rate)); ++ let fk = send_fade(c.linear, c.relative, c.at, listener); ++ let sends = c.send.as_mut().map(|s| s.buffer(buffer_seconds)).map(|(a, b)| (a.map(|v| v * fk), b.map(|v| v * fk))); ++ if sends.is_some() && rv_in.is_empty() { ++ rv_in.resize(frames, [0.0; reverb::SLOT_COUNT]); ++ } + let mut plans = plan_echo(&mut c.echo, c.gain, c.linear, c.relative, buffer_seconds, rate, step, &echo_pan); + let tail = echo_tail(&plans); + for (k, frame) in data.chunks_mut(channels).enumerate() { +@@ -858,6 +880,12 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + _ => s, + }; + let lerp = |a: f32, b: f32| a + (b - a) * t; ++ if let Some((s0, s1)) = &sends { ++ let dry = s * lerp(from[2], gain); ++ for j in 0..reverb::SLOT_COUNT { ++ rv_in[k][j] += dry * lerp(s0[j], s1[j]); ++ } ++ } + if channels >= 2 { + frame[0] += s * lerp(from[0], left) + echoes[0] * v.env; + frame[1] += s * lerp(from[1], right) + echoes[1] * v.env; +@@ -867,12 +895,20 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + c.position += step; + } + finish_echo(&mut c.echo, &plans); ++ if c.send.as_ref().is_some_and(Send::done) { ++ c.send = None; ++ } + v.last = Some([left, right, gain]); + v.age += buffer_seconds; + continue; + } + let shelf = c.occlusion.as_mut().map(|o| o.buffer(buffer_seconds, rate)); + let frames = (data.len() / channels.max(1)).max(1); ++ let fk = send_fade(c.linear, c.relative, c.at, listener); ++ let sends = c.send.as_mut().map(|s| s.buffer(buffer_seconds)).map(|(a, b)| (a.map(|v| v * fk), b.map(|v| v * fk))); ++ if sends.is_some() && rv_in.is_empty() { ++ rv_in.resize(frames, [0.0; reverb::SLOT_COUNT]); ++ } + let mut plans = plan_echo(&mut c.echo, c.gain, c.linear, c.relative, buffer_seconds, rate, step, &echo_pan); + let tail = echo_tail(&plans); + for (k, frame) in data.chunks_mut(channels).enumerate() { +@@ -897,6 +933,13 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + (Some(o), Some((g, cut, a))) => o.run(s, k as f32 / frames as f32, *g, *cut, *a), + _ => s, + }; ++ if let Some((s0, s1)) = &sends { ++ let u = k as f32 / frames as f32; ++ let dry = s * gain; ++ for j in 0..reverb::SLOT_COUNT { ++ rv_in[k][j] += dry * (s0[j] + (s1[j] - s0[j]) * u); ++ } ++ } + if channels >= 2 { + frame[0] += s * left + echoes[0]; + frame[1] += s * right + echoes[1]; +@@ -907,6 +950,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + c.position += step; + } + finish_echo(&mut c.echo, &plans); ++ if c.send.as_ref().is_some_and(Send::done) { ++ c.send = None; ++ } ++ } ++ // The shared reverb: what the voices sent, and the tail of what they sent before. It rings on ++ // when the voices are gone and is dropped when it is silent. ++ if !rv_in.is_empty() || mixer.reverb.is_some() { ++ let rv = mixer.reverb.take().filter(|r| r.rate() == rate).unwrap_or_else(|| Reverb::new(rate)); ++ let mut rv = rv; ++ rv.process(&rv_in, data, channels); ++ mixer.reverb = (!rv.idle()).then_some(rv); + } + // Limit the whole buffer together, preserving waveform and stereo balance + // instead of flattening each overloaded sample; release over 200 ms +@@ -1111,6 +1165,7 @@ impl Audio { + if let Ok(mut m) = self.backend.mixer.lock() { + m.offline = true; + m.channels.clear(); ++ m.reverb = None; + } + if let Some(a) = self.acoustics.as_mut() { + a.reset(); +@@ -1142,6 +1197,7 @@ impl Audio { + if let Ok(mut m) = self.backend.mixer.lock() { + m.offline = false; + m.channels.clear(); ++ m.reverb = None; + } + if let Some(a) = self.acoustics.as_mut() { + a.reset(); +@@ -1260,6 +1316,34 @@ impl Audio { + m.tick(listener, e, b); + }); + } ++ /// Turns the acoustics on or off while the game runs: off, what plays eases back to the plain ++ /// sound and its echoes stop. ++ pub fn set_acoustics(&mut self, on: bool) { ++ if on == self.acoustics.is_some() { ++ return; ++ } ++ let Ok(mut m) = self.backend.mixer.lock() else { ++ return; ++ }; ++ if on { ++ let mut a = crate::acoustics::Acoustics::new(false); ++ a.sync = m.offline; ++ self.acoustics = Some(a); ++ } else { ++ self.acoustics = None; ++ for c in m.channels.values_mut() { ++ if let Some(o) = c.occlusion.as_mut() { ++ o.gain_to = 1.0; ++ o.cut_to = 1.0; ++ } ++ c.echo = None; ++ // The reverb fades out with the send; what already rings in it rings out. ++ if let Some(s) = c.send.as_mut() { ++ s.to = [0.0; reverb::SLOT_COUNT]; ++ } ++ } ++ } ++ } + /// Whether acoustics are on and a sound is playing in the world: the game then builds the + /// geometry for [`Audio::tick_acoustics`]. + pub fn acoustics_wanted(&self) -> bool { +@@ -1310,7 +1394,8 @@ impl Audio { + }; + let applied = acoustics.step(geometry, listener, &sources, changes); + let echoes = acoustics.take_echoes(); +- if !applied.is_empty() || !echoes.is_empty() { ++ let sends = acoustics.take_sends(); ++ if !applied.is_empty() || !echoes.is_empty() || !sends.is_empty() { + if let Ok(mut m) = self.backend.mixer.lock() { + for a in applied { + if let Some(c) = m.channels.get_mut(&(a.id as ChannelId)) { +@@ -1323,6 +1408,14 @@ impl Audio { + } + } + } ++ for (id, to) in sends { ++ if let Some(c) = m.channels.get_mut(&(id as ChannelId)) { ++ match c.send.as_mut() { ++ Some(s) => s.to = to, ++ None => c.send = Some(Send::new(to)), ++ } ++ } ++ } + for (id, taps) in echoes { + if let Some(c) = m.channels.get_mut(&(id as ChannelId)) { + c.echo.get_or_insert_with(Echo::default).set(&taps); +@@ -1352,6 +1445,10 @@ impl Audio { + } + /// `SoundManager.stop()`: every sound. + pub fn stop_all(&mut self) { ++ // Every sound ends here, so the tail of the reverb does too. ++ if let Ok(mut m) = self.backend.mixer.lock() { ++ m.reverb = None; ++ } + self.mod_sources.release_all(&mut self.backend); + self.engine.stop_all(&mut self.backend); + } +@@ -1487,6 +1584,11 @@ impl Audio { + "ms_max": t.echo_us_max as f64 / 1e3, "capped": t.echo_capped, + "voices": crate::acoustics::ECHO_VOICES, + }, ++ "reverb": { ++ "rooms": t.room_traces, "room_hits": t.room_hits, "room_cells": t.room_cells, ++ "sends": t.sends, ++ "enclosed": t.room_enclosed, "decay_s": t.room_decay, ++ }, + "tick_ms_total": t.tick_us as f64 / 1e3, "tick_ms_max": t.tick_us_max as f64 / 1e3, + "ticks": t.ticks, + }); +@@ -1602,6 +1704,7 @@ mod tests { + voice: None, + occlusion: None, + echo: None, ++ send: None, + } + } + +@@ -2134,6 +2237,196 @@ mod tests { + std::fs::write(std::path::Path::new(&dir).join("expected.txt"), expected).unwrap(); + } + ++ /// A click of `n` frames at the start of a sound `len` frames long. ++ fn click(len: usize, n: usize) -> Vec { ++ let mut seed = 99u32; ++ (0..len) ++ .map(|i| { ++ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); ++ if i < n { ((seed >> 8) as f32 / 8_388_608.0 - 1.0) * (1.0 - i as f32 / n as f32) } else { 0.0 } ++ }) ++ .collect() ++ } ++ fn sending(to: [f32; 4]) -> Option { ++ Some(Send { now: to, to }) ++ } ++ ++ #[test] ++ fn a_reverb_rings_on_after_the_sound_and_is_dropped_when_it_is_over() { ++ let mut m = Mixer::default(); ++ let mut c = channel(click(4_800, 96), None, [0.0; 3], false); ++ c.relative = true; ++ c.send = sending([0.0, 0.0, 1.0, 0.0]); ++ m.channels.insert(1, c); ++ let out = render(&mut m, 200, 480); ++ // The sound is 0.1 s long; a second later the reverb still rings. ++ let dry: f32 = out[..2 * 4_800].iter().map(|v| v * v).sum(); ++ let tail: f32 = out[2 * 48_000..2 * 72_000].iter().map(|v| v * v).sum(); ++ assert!(dry > 0.0 && tail > 0.0, "{dry} {tail}"); ++ assert!(m.channels[&1].state == State::Stopped); ++ assert!(m.reverb.is_some()); ++ // Eight seconds on, it is over and gone (nothing runs for it). ++ render(&mut m, 400, 480); ++ assert!(m.reverb.is_none()); ++ } ++ ++ #[test] ++ fn without_a_send_there_is_no_reverb_and_the_output_is_what_it_was() { ++ let play = |send: Option| { ++ let mut m = Mixer::default(); ++ let mut c = channel(click(4_800, 96), None, [3.0, 0.0, 4.0], false); ++ c.send = send; ++ m.channels.insert(1, c); ++ let out = render(&mut m, 40, 480); ++ (out, m.reverb.is_some()) ++ }; ++ let (plain, rv) = play(None); ++ assert!(!rv); ++ let (zero, rv) = play(sending([0.0; 4])); ++ assert!(!rv && zero == plain, "a zero send adds nothing"); ++ let (wet, rv) = play(sending([0.0, 1.0, 0.0, 0.0])); ++ assert!(rv && wet != plain); ++ } ++ ++ #[test] ++ fn a_changing_space_and_turning_it_off_make_no_click_and_the_tail_fades() { ++ let mut m = Mixer::default(); ++ let mut c = channel(tone(220.0, 400_000), None, [0.0; 3], true); ++ c.relative = true; ++ m.channels.insert(1, c); ++ let quiet = render(&mut m, 20, 480); ++ let dry_step = max_step(&quiet); ++ // Walk into a hall: the send goes up. ++ m.channels.get_mut(&1).unwrap().send = Some(Send::new([0.0, 0.0, 0.0, 1.0])); ++ let hall = render(&mut m, 200, 480); ++ // A click is a step steeper than a 220 Hz tone can have at the level it has. ++ let slope = |x: &[f32]| max_step(x) / (std::f32::consts::TAU * 220.0 / 48_000.0 * x.iter().fold(0.0f32, |p, v| p.max(v.abs()))); ++ assert!(rms(&hall[hall.len() - 9_600..]) > rms(&quiet) * 1.3, "the hall adds to the sound"); ++ assert!(slope(&hall) < 1.2, "{}", slope(&hall)); ++ // And off: the sound goes on, the reverb sends fade, the tail rings out. ++ m.channels.get_mut(&1).unwrap().send.as_mut().unwrap().to = [0.0; 4]; ++ let off = render(&mut m, 400, 480); ++ assert!(slope(&off) < 1.2, "{}", slope(&off)); ++ assert!(m.channels[&1].send.is_none(), "a gone send is dropped"); ++ assert!(m.reverb.is_some(), "the tail is not cut"); ++ // The tone stops; the tail shrinks smoothly, then is gone. ++ m.channels.get_mut(&1).unwrap().state = State::Stopped; ++ let rest = render(&mut m, 1_500, 480); ++ assert!(max_step(&rest) < 0.05); ++ let (early, late) = (rms(&rest[..9_600]), rms(&rest[rest.len() - 9_600..])); ++ assert!(early > late, "{early} {late}"); ++ assert!(m.reverb.is_none()); ++ } ++ ++ #[test] ++ fn turning_the_acoustics_off_sends_nothing_more_and_a_film_begins_dry() { ++ let mut audio = Audio::silent(Path::new("/nonexistent/horizon-test-assets")); ++ audio.acoustics = Some(crate::acoustics::Acoustics::new(false)); ++ { ++ let mut m = audio.backend.mixer.lock().unwrap(); ++ let mut c = channel(tone(220.0, 48_000), None, [0.0; 3], true); ++ c.send = sending([0.0, 0.5, 0.5, 0.0]); ++ m.channels.insert(1, c); ++ m.reverb = Some(Reverb::new(48_000)); ++ } ++ audio.set_acoustics(false); ++ assert!(audio.acoustics.is_none()); ++ { ++ let m = audio.backend.mixer.lock().unwrap(); ++ assert_eq!(m.channels[&1].send.unwrap().to, [0.0; 4], "fading, not cut"); ++ assert!(m.channels[&1].send.unwrap().now[1] > 0.0); ++ assert!(m.reverb.is_some()); ++ } ++ audio.film_begin(); ++ let m = audio.backend.mixer.lock().unwrap(); ++ assert!(m.reverb.is_none() && m.channels.is_empty()); ++ } ++ ++ #[test] ++ fn reverb_rendering_is_deterministic() { ++ let run = || { ++ let mut m = Mixer::default(); ++ for id in 1..=5u64 { ++ let mut c = channel(click(9_600, 96), Some(200.0), [id as f32 * 7.0, 1.0, 3.0], false); ++ c.send = sending([0.1, 0.2 * id as f32 / 5.0, 0.3, 0.2]); ++ m.channels.insert(id, c); ++ } ++ render(&mut m, 120, 480) ++ }; ++ assert_eq!(run(), run()); ++ } ++ ++ /// Writes the track of a click in a room, a tunnel, a gorge and a field, through the real ++ /// acoustics and mixer, for `python3 tools/acoustics_check.py --reverb-dir`: ++ /// `HORIZON_ACOUSTICS_OUT=/dir cargo test -p horizon-client --lib audio::tests::export_reverb_tracks -- --ignored`. ++ #[test] ++ #[ignore] ++ fn export_reverb_tracks() { ++ use crate::acoustics::{Acoustics, Changes, Geometry, Source, room}; ++ let Some(dir) = std::env::var_os("HORIZON_ACOUSTICS_OUT") else { ++ return; ++ }; ++ let mut expected = String::new(); ++ for name in ["room", "tunnel", "gorge", "field"] { ++ let (geometry, at) = room::tests::scene(name); ++ let geometry: Arc = Arc::new(geometry); ++ let src = [at[0], at[1], at[2] + 4.0]; ++ let mut m = Mixer::default(); ++ m.listener = at; ++ m.channels.insert(1, channel(click(48_000, 96), Some(200.0), [src[0] as f32, src[1] as f32, src[2] as f32], false)); ++ let mut acoustics = Acoustics::new(true); ++ let source = Source { id: 1, at: src, loud: 0.97, echo: true }; ++ acoustics.step(Some(&geometry), at, &[source], &Changes::default()); ++ let sends = acoustics.take_sends(); ++ for (id, to) in &sends { ++ m.channels.get_mut(&(*id as ChannelId)).unwrap().send = sending(*to); ++ } ++ let (wet, decay) = room::wet_and_decay(&acoustics_room(&acoustics)); ++ let effective = sends.first().map_or(0.0, |(_, to)| room::effective_decay(to)); ++ let out = render(&mut m, 700, 480); ++ let raw: Vec = out.iter().flat_map(|s| ((s.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes()).collect(); ++ std::fs::write(std::path::Path::new(&dir).join(format!("{name}.raw")), raw).unwrap(); ++ expected.push_str(&format!("{name} {decay:.3} {wet:.3} {effective:.3}\n")); ++ } ++ std::fs::write(std::path::Path::new(&dir).join("expected_reverb.txt"), expected).unwrap(); ++ } ++ /// The listener's room, as the engine measured it (stats carry its numbers). ++ fn acoustics_room(a: &crate::acoustics::Acoustics) -> crate::acoustics::Room { ++ a.room_now().unwrap_or(crate::acoustics::Room::OPEN) ++ } ++ ++ /// 100 looping voices (a quarter sending to the reverb, all four slots ringing) against none: ++ /// `cargo test -p horizon-client --lib --release audio::tests::bench_reverb -- --ignored --nocapture`. ++ #[test] ++ #[ignore] ++ fn bench_reverb_with_one_hundred_voices() { ++ let make = |sends: u64| { ++ let mut m = Mixer::default(); ++ for id in 1..=100u64 { ++ let mut c = voice_channel(tone(110.0 + id as f32 * 7.0, 96_000), [id as f32 * 3.0, 1.0, 40.0], true, 0.0, 0.0, 0.0); ++ c.linear = Some(500.0); ++ if id <= sends { ++ c.send = sending([0.1 + 0.001 * id as f32, 0.2, 0.3, 0.2]); ++ } ++ m.channels.insert(id, c); ++ } ++ m ++ }; ++ let time = |mut m: Mixer| { ++ let mut data = vec![0.0f32; 1024]; ++ for _ in 0..50 { ++ mix(&mut m, &mut data, 2, 48_000); ++ } ++ let start = std::time::Instant::now(); ++ for _ in 0..1000 { ++ mix(&mut m, &mut data, 2, 48_000); ++ } ++ start.elapsed().as_secs_f64() * 1e3 / 1000.0 ++ }; ++ let (plain, quarter, all) = (time(make(0)), time(make(25)), time(make(100))); ++ println!("100 voices, 512 frames: {plain:.3} ms plain, {quarter:.3} ms with 25 sending ({:+.3}), {all:.3} ms with 100 sending ({:+.3}); buffer is 10.67 ms", quarter - plain, all - plain); ++ } ++ + /// The cost of the echo taps in release: 100 looping voices and 8 one-shots, without and with + /// 6 taps on each of the 8: `cargo test -p horizon-client --lib --release audio::tests::bench_echo + /// -- --ignored --nocapture`. +diff --git a/crates/horizon-client/src/audio/reverb.rs b/crates/horizon-client/src/audio/reverb.rs +new file mode 100644 +index 000000000..cdab66a2b +--- /dev/null ++++ b/crates/horizon-client/src/audio/reverb.rs +@@ -0,0 +1,374 @@ ++//! AirDef fork: acoustics stage 3 (#96): the mixer's shared late reverb. Four slots of SPR's ++//! decays (`acoustics::spr_reverb`), each a pre-delay, two allpasses to diffuse, and four feedback ++//! combs with a low-pass in the loop (the highs die faster, as SPR's `decay_hf_ratio` says). Every ++//! voice sends its sound (after the wall, before the pan) to the slots by its own levels; the left ++//! output takes combs 0 and 2, the right 1 and 3, so the two ears hear different tails and a mono ++//! sum is the plain average of all four. ++//! ++//! No allocation or randomness in the audio path (the delay lines are made with the reverb), the ++//! same input gives the same output (a film's track), and a slot with nothing in and nothing left ++//! to ring is not run at all, and is cleared when it falls silent (no denormals). ++use crate::acoustics::spr_reverb::{OUTPUT_GAIN, SLOTS}; ++ ++pub const SLOT_COUNT: usize = 4; ++/// Comb lengths per slot at 48 kHz, in samples (mutually prime, longer for longer slots). ++const COMB_LEN: [[usize; 4]; SLOT_COUNT] = ++ [[353, 457, 563, 641], [613, 797, 947, 1117], [997, 1259, 1471, 1693], [1301, 1627, 1913, 2203]]; ++/// Allpass lengths at 48 kHz. ++const ALLPASS_LEN: [usize; 2] = [225, 341]; ++/// Below this the output of a slot with no input is silence (-120 dB). ++const SILENT: f32 = 1e-6; ++/// The master level of the wet signal, set by ear against a measured tail (see `docs/ACOUSTICS.md`). ++const WET: f32 = 1.6; ++/// Where the highs are judged for the loop's low-pass (OpenAL's `HFREFERENCE`). ++const HF_HZ: f32 = 5000.0; ++/// A voice's sends move to their target over about this many seconds. ++const SLEW: f32 = 0.3; ++ ++/// The sends of one voice to the four slots: where they are and where they go. ++#[derive(Clone, Copy, Debug, PartialEq)] ++pub struct Send { ++ pub now: [f32; SLOT_COUNT], ++ pub to: [f32; SLOT_COUNT], ++} ++impl Send { ++ pub fn new(to: [f32; SLOT_COUNT]) -> Self { ++ Self { now: [0.0; SLOT_COUNT], to } ++ } ++ /// Moves towards the target for a buffer of `seconds`; the levels at its start and end. ++ pub fn buffer(&mut self, seconds: f32) -> ([f32; SLOT_COUNT], [f32; SLOT_COUNT]) { ++ let alpha = 1.0 - (-seconds / SLEW).exp(); ++ let from = self.now; ++ for k in 0..SLOT_COUNT { ++ self.now[k] += (self.to[k] - self.now[k]) * alpha; ++ if self.to[k] == 0.0 && self.now[k] < 1e-4 { ++ self.now[k] = 0.0; ++ } ++ } ++ (from, self.now) ++ } ++ /// Gone: nothing is sent now or will be. ++ pub fn done(&self) -> bool { ++ self.now == [0.0; SLOT_COUNT] && self.to == [0.0; SLOT_COUNT] ++ } ++} ++ ++fn scaled(len: usize, rate: u32) -> usize { ++ (len as u64 * u64::from(rate) / 48_000).max(2) as usize ++} ++ ++struct Comb { ++ buf: Vec, ++ pos: usize, ++ fb: f32, ++ damp: f32, ++ store: f32, ++ /// Keeps the energy of a ring the same whatever its decay. ++ scale: f32, ++} ++impl Comb { ++ /// A comb of `len` samples that decays by 60 dB in `decay` seconds, whose highs (at 5 kHz) ++ /// last `hf_ratio` of that. ++ fn new(len: usize, decay: f32, hf_ratio: f32, rate: u32) -> Self { ++ let fb = 10f32.powf(-3.0 * len as f32 / (decay * rate as f32)); ++ // The loop is `fb * (1 - d) / (1 - d z^-1)`; at HF_HZ it must be `fb^(1/ratio)`. ++ let want = fb.powf(1.0 / hf_ratio - 1.0).min(1.0); ++ let cos = (std::f32::consts::TAU * HF_HZ / rate as f32).cos(); ++ let (mut lo, mut hi) = (0.0f32, 0.95f32); ++ for _ in 0..24 { ++ let d = 0.5 * (lo + hi); ++ let h = (1.0 - d) / (1.0 - 2.0 * d * cos + d * d).sqrt(); ++ if h > want { lo = d } else { hi = d } ++ } ++ Self { buf: vec![0.0; len], pos: 0, fb, damp: 0.5 * (lo + hi), store: 0.0, scale: (1.0 - fb * fb).sqrt() } ++ } ++ #[inline] ++ fn run(&mut self, x: f32) -> f32 { ++ let y = self.buf[self.pos]; ++ self.store = y * (1.0 - self.damp) + self.store * self.damp; ++ self.buf[self.pos] = x * self.scale + self.store * self.fb; ++ self.pos += 1; ++ if self.pos == self.buf.len() { ++ self.pos = 0; ++ } ++ y ++ } ++ fn clear(&mut self) { ++ self.buf.fill(0.0); ++ self.store = 0.0; ++ self.pos = 0; ++ } ++} ++ ++struct Allpass { ++ buf: Vec, ++ pos: usize, ++} ++impl Allpass { ++ #[inline] ++ fn run(&mut self, x: f32) -> f32 { ++ let b = self.buf[self.pos]; ++ self.buf[self.pos] = x + b * 0.5; ++ self.pos += 1; ++ if self.pos == self.buf.len() { ++ self.pos = 0; ++ } ++ b - x ++ } ++} ++ ++struct Slot { ++ pre: Vec, ++ pre_pos: usize, ++ aps: [Allpass; 2], ++ combs: [Comb; 4], ++ gain: f32, ++ /// Something still rings (or came in) in this slot. ++ live: bool, ++ /// Frames since the last input; the sound needs the delay lines' length to come out. ++ since_input: usize, ++} ++impl Slot { ++ fn new(i: usize, rate: u32) -> Self { ++ let p = SLOTS[i]; ++ let comb = |k: usize| Comb::new(scaled(COMB_LEN[i][k], rate), p.decay, p.decay_hf_ratio, rate); ++ let ap = |k: usize| Allpass { buf: vec![0.0; scaled(ALLPASS_LEN[k], rate)], pos: 0 }; ++ Self { ++ pre: vec![0.0; scaled((p.late_delay * 48_000.0) as usize, rate)], ++ pre_pos: 0, ++ aps: [ap(0), ap(1)], ++ combs: [comb(0), comb(1), comb(2), comb(3)], ++ gain: p.gain * OUTPUT_GAIN * WET, ++ live: false, ++ since_input: 0, ++ } ++ } ++ /// Frames a sound takes to get through the pre-delay, the allpasses and the longest comb, and ++ /// to be heard once. ++ fn reach(&self) -> usize { ++ self.pre.len() + self.aps.iter().map(|a| a.buf.len()).sum::() + self.combs.iter().map(|c| c.buf.len()).max().unwrap_or(0) + 1 ++ } ++ fn clear(&mut self) { ++ self.pre.fill(0.0); ++ self.pre_pos = 0; ++ for a in &mut self.aps { ++ a.buf.fill(0.0); ++ a.pos = 0; ++ } ++ for c in &mut self.combs { ++ c.clear(); ++ } ++ self.live = false; ++ self.since_input = 0; ++ } ++} ++ ++/// The four slots and their output scratch. ++pub struct Reverb { ++ rate: u32, ++ slots: Vec, ++ wet: Vec<[f32; 2]>, ++} ++impl Reverb { ++ pub fn new(rate: u32) -> Self { ++ Self { rate, slots: (0..SLOT_COUNT).map(|i| Slot::new(i, rate)).collect(), wet: Vec::new() } ++ } ++ pub fn rate(&self) -> u32 { ++ self.rate ++ } ++ /// Nothing rings: the mixer may drop the reverb until a voice sends again. ++ pub fn idle(&self) -> bool { ++ self.slots.iter().all(|s| !s.live) ++ } ++ /// Adds the reverb of `input` (the mono sum per slot per frame; empty: silence) to `data` ++ /// (`channels` interleaved). Returns the peak of the wet signal. ++ pub fn process(&mut self, input: &[[f32; SLOT_COUNT]], data: &mut [f32], channels: usize) -> f32 { ++ let frames = data.len() / channels.max(1); ++ self.wet.clear(); ++ self.wet.resize(frames, [0.0; 2]); ++ let mut peaks = [0.0f32; SLOT_COUNT]; ++ for f in input.iter().take(frames) { ++ for k in 0..SLOT_COUNT { ++ peaks[k] = peaks[k].max(f[k].abs()); ++ } ++ } ++ for (si, slot) in self.slots.iter_mut().enumerate() { ++ if peaks[si] == 0.0 && !slot.live { ++ continue; ++ } ++ let mut out_peak = 0.0f32; ++ for (k, w) in self.wet.iter_mut().enumerate() { ++ let x = input.get(k).map_or(0.0, |f| f[si]); ++ let delayed = slot.pre[slot.pre_pos]; ++ slot.pre[slot.pre_pos] = x; ++ slot.pre_pos += 1; ++ if slot.pre_pos == slot.pre.len() { ++ slot.pre_pos = 0; ++ } ++ let d0 = slot.aps[0].run(delayed); ++ let d = slot.aps[1].run(d0); ++ let (c0, c1, c2, c3) = ( ++ slot.combs[0].run(d), ++ slot.combs[1].run(d), ++ slot.combs[2].run(d), ++ slot.combs[3].run(d), ++ ); ++ let (l, r) = (0.5 * (c0 + c2) * slot.gain, 0.5 * (c1 + c3) * slot.gain); ++ w[0] += l; ++ w[1] += r; ++ out_peak = out_peak.max(l.abs()).max(r.abs()); ++ } ++ slot.since_input = if peaks[si] > 0.0 { 0 } else { slot.since_input + frames }; ++ slot.live = slot.since_input < slot.reach() || out_peak > SILENT; ++ if !slot.live { ++ slot.clear(); ++ } ++ } ++ let mut peak = 0.0f32; ++ for (frame, w) in data.chunks_mut(channels.max(1)).zip(&self.wet) { ++ if channels >= 2 { ++ frame[0] += w[0]; ++ frame[1] += w[1]; ++ } else { ++ frame[0] += 0.5 * (w[0] + w[1]); ++ } ++ peak = peak.max(w[0].abs()).max(w[1].abs()); ++ } ++ peak ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ const RATE: u32 = 48_000; ++ /// The reverb of an impulse into slot `k` at level 1: `seconds` of the left channel. ++ fn impulse(slot: usize, seconds: f32) -> Vec { ++ let frames = (seconds * RATE as f32) as usize; ++ let mut r = Reverb::new(RATE); ++ let mut out = Vec::new(); ++ let mut at = 0; ++ while at < frames { ++ let n = 512.min(frames - at); ++ let mut input = vec![[0.0f32; SLOT_COUNT]; n]; ++ if at == 0 { ++ input[0][slot] = 1.0; ++ } ++ let mut data = vec![0.0f32; n * 2]; ++ r.process(&input, &mut data, 2); ++ out.extend(data.chunks(2).map(|f| f[0])); ++ at += n; ++ } ++ out ++ } ++ /// RT60 by Schroeder's backward integration (the time the energy decay curve takes from -5 to -35 dB, doubled). ++ pub(super) fn rt60(x: &[f32]) -> f32 { ++ let mut edc = vec![0.0f64; x.len()]; ++ let mut acc = 0.0f64; ++ for i in (0..x.len()).rev() { ++ acc += f64::from(x[i]).powi(2); ++ edc[i] = acc; ++ } ++ let db = |i: usize| 10.0 * (edc[i] / edc[0]).max(1e-30).log10(); ++ let a = (0..x.len()).find(|&i| db(i) <= -5.0).unwrap(); ++ let b = (0..x.len()).find(|&i| db(i) <= -35.0).unwrap(); ++ 2.0 * (b - a) as f32 / RATE as f32 ++ } ++ ++ #[test] ++ fn each_slot_decays_at_its_time() { ++ for (i, p) in SLOTS.iter().enumerate() { ++ let ir = impulse(i, p.decay * 2.5 + 1.0); ++ let t = rt60(&ir); ++ // The highs die sooner than the lows; the broadband decay lies below the nominal one. ++ assert!(t > p.decay * 0.5 && t < p.decay * 1.15, "slot {i}: {t} s for {}", p.decay); ++ } ++ } ++ ++ #[test] ++ fn the_tail_is_stable_finite_and_silent_after_it_ends() { ++ let mut r = Reverb::new(RATE); ++ let mut energy = Vec::new(); ++ for b in 0..(RATE as usize * 12 / 512) { ++ let mut input = vec![[0.0f32; SLOT_COUNT]; 512]; ++ if b == 0 { ++ for f in input.iter_mut().take(64) { ++ *f = [1.0; SLOT_COUNT]; ++ } ++ } ++ let mut data = vec![0.0f32; 1024]; ++ r.process(&input, &mut data, 2); ++ assert!(data.iter().all(|s| s.is_finite() && s.abs() < 2.0)); ++ energy.push(data.iter().map(|s| s * s).sum::()); ++ } ++ // The energy of a buffer never rises after the input ends, by more than the echo of a comb. ++ let peak = energy.iter().cloned().fold(0.0, f32::max); ++ assert!(energy.last().copied().unwrap() == 0.0 && r.idle(), "ten seconds after 4.1 s: {:?}", energy.last()); ++ assert!(energy[energy.len() / 2] < peak * 0.01); ++ } ++ ++ #[test] ++ fn a_silent_reverb_adds_nothing_and_costs_no_slot() { ++ let mut r = Reverb::new(RATE); ++ let mut data = vec![0.25f32; 1024]; ++ r.process(&[], &mut data, 2); ++ assert!(data.iter().all(|s| *s == 0.25) && r.idle()); ++ } ++ ++ #[test] ++ fn the_two_ears_hear_different_tails_and_mono_is_their_average() { ++ let mut stereo = Reverb::new(RATE); ++ let mut mono = Reverb::new(RATE); ++ let mut input = vec![[0.0f32; SLOT_COUNT]; 4096]; ++ input[0] = [0.0, 0.0, 1.0, 0.0]; ++ let (mut s, mut m) = (vec![0.0f32; 8192], vec![0.0f32; 4096]); ++ stereo.process(&input, &mut s, 2); ++ mono.process(&input, &mut m, 1); ++ let diff = s.chunks(2).filter(|f| (f[0] - f[1]).abs() > 1e-6).count(); ++ assert!(diff > 100, "decorrelated: {diff}"); ++ for (f, v) in s.chunks(2).zip(&m) { ++ assert!((0.5 * (f[0] + f[1]) - v).abs() < 1e-6); ++ } ++ } ++ ++ #[test] ++ fn a_send_slides_and_a_gone_send_is_done() { ++ let mut s = Send::new([0.0, 0.0, 1.0, 0.0]); ++ let mut last = 0.0; ++ for _ in 0..80 { ++ let (a, b) = s.buffer(0.0107); ++ assert!(a[2] >= last && b[2] - a[2] < 0.05, "no step: {a:?} {b:?}"); ++ last = b[2]; ++ } ++ assert!(last > 0.8 && !s.done()); ++ s.to = [0.0; 4]; ++ for _ in 0..400 { ++ s.buffer(0.0107); ++ } ++ assert!(s.done()); ++ } ++ ++ #[test] ++ fn it_is_deterministic() { ++ assert_eq!(impulse(2, 1.0), impulse(2, 1.0)); ++ } ++ ++ /// The cost of the four slots in release when all of them ring: `cargo test -p horizon-client ++ /// --lib --release audio::reverb::tests::bench -- --ignored --nocapture`. ++ #[test] ++ #[ignore] ++ fn bench_four_busy_slots() { ++ let mut r = Reverb::new(RATE); ++ let input = vec![[0.3f32; SLOT_COUNT]; 512]; ++ let mut data = vec![0.0f32; 1024]; ++ for _ in 0..50 { ++ r.process(&input, &mut data, 2); ++ } ++ let start = std::time::Instant::now(); ++ for _ in 0..2000 { ++ r.process(&input, &mut data, 2); ++ } ++ println!("reverb, 4 busy slots, 512 frames: {:.4} ms", start.elapsed().as_secs_f64() * 1e3 / 2000.0); ++ } ++} +diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs +index 0fcb43243..d7529b12d 100644 +--- a/crates/horizon-client/src/game.rs ++++ b/crates/horizon-client/src/game.rs +@@ -116,6 +116,8 @@ mod mod_browser_recipes; + mod mod_input; + mod mod_models; + #[cfg(feature = "mods")] ++mod mod_canvas; ++#[cfg(feature = "mods")] + mod mod_recipes; + mod mod_render; + #[cfg(feature = "mods")] +@@ -13203,7 +13205,7 @@ impl ApplicationHandler for Game<'_> { + self.stats_click(size); + } + Screen::Stats if button == MouseButton::Left => self.stats_release(), +- Screen::Mod if pressed => self.mod_screen_click(button), ++ Screen::Mod => self.mod_screen_mouse(button, pressed), + _ => {} + } + } +diff --git a/crates/horizon-client/src/game/mod_canvas.rs b/crates/horizon-client/src/game/mod_canvas.rs +new file mode 100644 +index 000000000..6ccdfcfcd +--- /dev/null ++++ b/crates/horizon-client/src/game/mod_canvas.rs +@@ -0,0 +1,271 @@ ++//! Capability `render`'s canvas (AirDef fork, API level 24): a full-screen surface the mod ++//! draws with shapes and drives with the pointer and keys, and the terrain tiles it shows ++//! (`TerrainShape`), scanned from the loaded chunks within a time budget and composed into ++//! atlas slots only when a tile or the mod's choice of tile changes. ++use super::{Dim, Game, Screen}; ++use horizon_client::{ ++ font::Patch, ++ hud::HudBatch, ++ minimap::{self, Minimap}, ++}; ++use horizon_mods::{CanvasButton, CanvasEvent, CanvasScroll, RenderPoint, TerrainShape}; ++use std::time::Duration; ++use winit::event::MouseButton; ++ ++/// Terrain tiles the game keeps at once (atlas slots `horizon/mapview{i}`). ++pub(crate) const SLOTS: usize = 24; ++/// CPU time the chunk scans may take a frame. ++const SCAN_BUDGET: Duration = Duration::from_micros(1500); ++/// Tiles composed and uploaded a frame at most. ++const COMPOSE_PER_FRAME: usize = 6; ++ ++pub(crate) fn slot_name(i: usize) -> String { ++ format!("horizon/mapview{i}") ++} ++ ++type Key = (i32, i32, u32); ++ ++#[derive(Clone, Copy, Default)] ++struct Slot { ++ want: Option, ++ shown: Option, ++ version: u64, ++ stamp: u64, ++} ++ ++#[derive(Default)] ++pub(super) struct CanvasState { ++ map: Minimap, ++ dim: Option, ++ slots: Vec, ++ frame: u64, ++ cursor: Option<(f32, f32)>, ++ size: Option<(f32, f32)>, ++ scratch: Vec, ++} ++ ++fn button_index(b: MouseButton) -> u32 { ++ match b { ++ MouseButton::Left => 0, ++ MouseButton::Right => 1, ++ MouseButton::Middle => 2, ++ MouseButton::Back => 3, ++ MouseButton::Forward => 4, ++ MouseButton::Other(n) => 5 + u32::from(n), ++ } ++} ++ ++impl Game<'_> { ++ /// Whether a mod's canvas is the screen. ++ pub(super) fn canvas_up(&self) -> bool { ++ self.screen == Screen::Mod && self.mods.screen.as_ref().is_some_and(|m| m.canvas) ++ } ++ fn canvas_event(&mut self, event: CanvasEvent) { ++ if let Some(ms) = self.mods.screen.as_ref().filter(|m| m.canvas) { ++ self.mods.mods.canvas_push(ms.owner, event); ++ } ++ } ++ pub(super) fn canvas_mouse(&mut self, button: MouseButton, pressed: bool) { ++ let at = self.cursor; ++ let b = CanvasButton { ++ button: button_index(button), ++ at: RenderPoint { x: at.0, y: at.1 }, ++ }; ++ self.canvas_event(if pressed { CanvasEvent::Pressed(b) } else { CanvasEvent::Released(b) }); ++ } ++ pub(super) fn canvas_scroll(&mut self, steps: f32) { ++ let at = self.cursor; ++ self.canvas_event(CanvasEvent::Scrolled(CanvasScroll { ++ steps, ++ at: RenderPoint { x: at.0, y: at.1 }, ++ })); ++ } ++ pub(super) fn canvas_key(&mut self, key: winit::keyboard::KeyCode) { ++ if let Some(name) = horizon_client::keybinds::key_name(key) { ++ self.canvas_event(CanvasEvent::Key(name.to_owned())); ++ } ++ } ++ ++ /// Once a frame, after the mods' frame: opens or closes the canvas as the mod asks, tells it ++ /// of the pointer and the size, and keeps its terrain tiles. ++ pub(super) fn canvas_frame(&mut self) { ++ let wanted = self.mods.mods.canvas_wanted(); ++ let up = self.canvas_up(); ++ let owner = self.mods.screen.as_ref().filter(|m| m.canvas).map(|m| m.owner); ++ match (wanted, owner) { ++ (Some(i), None) => { ++ if self.screen == Screen::Playing && self.player.is_some() && self.title.is_none() { ++ self.open_canvas_screen(i); ++ } else { ++ // Not now: the mod hears that it is not open. ++ self.mods.mods.canvas_closed(i); ++ } ++ } ++ (None, Some(_)) => self.close_mod_screen(false), ++ (Some(a), Some(b)) if a != b => self.close_mod_screen(false), ++ _ => {} ++ } ++ if !up && !self.canvas_up() { ++ self.mods.canvas.cursor = None; ++ self.mods.canvas.size = None; ++ return; ++ } ++ if self.player.is_none() { ++ if let Some(i) = wanted { ++ self.mods.mods.canvas_closed(i); ++ } ++ self.close_mod_screen(false); ++ return; ++ } ++ let Some(owner) = self.mods.screen.as_ref().filter(|m| m.canvas).map(|m| m.owner) else { ++ return; ++ }; ++ let size = self.gui_size(); ++ if self.mods.canvas.size != Some(size) { ++ self.mods.canvas.size = Some(size); ++ self.canvas_event(CanvasEvent::Resized(size)); ++ } ++ if self.mods.canvas.cursor != Some(self.cursor) { ++ self.mods.canvas.cursor = Some(self.cursor); ++ let c = self.cursor; ++ self.canvas_event(CanvasEvent::Moved(RenderPoint { x: c.0, y: c.1 })); ++ } ++ self.canvas_terrain(owner); ++ } ++ ++ fn open_canvas_screen(&mut self, owner: usize) { ++ self.mods.screen = Some(super::mods::ModScreen::canvas(owner, self.screen)); ++ self.screen = Screen::Mod; ++ self.mods.canvas.cursor = None; ++ self.mods.canvas.size = None; ++ if self.player.is_some() { ++ self.capture(false); ++ } ++ } ++ ++ /// The tiles the canvas's shapes name: slots, chunk scans, composing. ++ fn canvas_terrain(&mut self, owner: usize) { ++ let mut keys: Vec = Vec::new(); ++ for shape in self.mods.mods.canvas_shapes(owner) { ++ if let horizon_mods::Shape::Terrain(t) = shape { ++ let k = (t.x, t.z, t.blocks_per_texel); ++ if !keys.contains(&k) && keys.len() < SLOTS { ++ keys.push(k); ++ } ++ } ++ } ++ let c = &mut self.mods.canvas; ++ if c.dim != Some(self.dim) { ++ c.map = Minimap::default(); ++ c.slots.clear(); ++ c.dim = Some(self.dim); ++ } ++ c.slots.resize(SLOTS, Slot::default()); ++ c.frame += 1; ++ let frame = c.frame; ++ // A tile already in a slot stays; a new one takes a free slot or the longest unused. ++ for k in &keys { ++ if let Some(s) = c.slots.iter_mut().find(|s| s.want == Some(*k)) { ++ s.stamp = frame; ++ continue; ++ } ++ let pick = (0..SLOTS) ++ .filter(|&i| c.slots[i].want.is_none_or(|w| !keys.contains(&w))) ++ .min_by_key(|&i| (c.slots[i].want.is_some(), c.slots[i].stamp)); ++ if let Some(i) = pick { ++ c.slots[i] = Slot { ++ want: Some(*k), ++ shown: None, ++ version: 0, ++ stamp: frame, ++ }; ++ } ++ } ++ for s in &mut c.slots { ++ if s.want.is_some_and(|w| !keys.contains(&w)) { ++ s.want = None; ++ } ++ } ++ if keys.is_empty() { ++ return; ++ } ++ // The chunks the tiles cover, nearest the middle of the view first. ++ let regions: Vec<(i32, i32, i32, i32)> = keys ++ .iter() ++ .map(|&(x, z, b)| { ++ let span = 128 * b as i32; ++ (x >> 4, z >> 4, (x + span - 1) >> 4, (z + span - 1) >> 4) ++ }) ++ .collect(); ++ let near = { ++ let n = keys.len() as f64; ++ let (sx, sz) = keys.iter().fold((0.0, 0.0), |a, &(x, z, b)| { ++ (a.0 + f64::from(x) + 64.0 * f64::from(b), a.1 + f64::from(z) + 64.0 * f64::from(b)) ++ }); ++ (sx / n, sz / n) ++ }; ++ c.map.scan_loaded( ++ &self.world, ++ self.res.facts(), ++ |(cx, cz)| regions.iter().any(|r| cx >= r.0 && cx <= r.2 && cz >= r.1 && cz <= r.3), ++ near, ++ SCAN_BUDGET, ++ ); ++ let Some(first) = self.gui.atlas.sprites.get(&slot_name(0)).copied() else { ++ return; ++ }; ++ let _ = first; ++ let (aw, ah) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); ++ let version = c.map.version(); ++ let mut done = 0; ++ for i in 0..SLOTS { ++ let s = c.slots[i]; ++ let Some(k) = s.want else { continue }; ++ if s.shown == Some(k) && s.version == version { ++ continue; ++ } ++ if done == COMPOSE_PER_FRAME { ++ break; ++ } ++ let Some(rect) = self.gui.atlas.sprites.get(&slot_name(i)).copied() else { ++ continue; ++ }; ++ let mut out = std::mem::take(&mut c.scratch); ++ c.map.compose_terrain(k.0, k.1, k.2 as i32, &mut out); ++ self.map_patches.push(Patch { ++ x: (rect.u0 * aw).round() as u32, ++ y: (rect.v0 * ah).round() as u32, ++ width: minimap::SIZE as u32, ++ height: minimap::SIZE as u32, ++ rgba: out.clone(), ++ }); ++ c.scratch = out; ++ c.slots[i].shown = Some(k); ++ c.slots[i].version = version; ++ done += 1; ++ } ++ } ++ ++ /// A terrain tile of the canvas, when its slot holds it. ++ pub(super) fn draw_terrain(&self, batch: &mut HudBatch, t: &TerrainShape, ox: f32, oy: f32) { ++ let key = (t.x, t.z, t.blocks_per_texel); ++ let Some(i) = self ++ .mods ++ .canvas ++ .slots ++ .iter() ++ .position(|s| s.want == Some(key) && s.shown == Some(key)) ++ else { ++ return; ++ }; ++ if let Some(r) = self.gui.atlas.sprites.get(&slot_name(i)).copied() { ++ batch.rect_uv(ox + t.rect.x, oy + t.rect.y, t.rect.w, t.rect.h, r, u32::MAX); ++ } ++ } ++ ++ /// The canvas: a dark ground under the mod's shapes. ++ pub(super) fn draw_canvas(&self, batch: &mut HudBatch, owner: usize) { ++ batch.fill(&self.gui.atlas, 0.0, 0.0, batch.width, batch.height, 0xFF0A100C); ++ self.draw_shapes(batch, self.mods.mods.canvas_shapes(owner), (0.0, 0.0)); ++ } ++} +diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs +index 3769b03c9..463f0b584 100644 +--- a/crates/horizon-client/src/game/mod_input.rs ++++ b/crates/horizon-client/src/game/mod_input.rs +@@ -118,6 +118,12 @@ impl Game<'_> { + /// screen) is its `key-down` / `key-up`. Vanilla's mapping on the same + /// key still runs. + pub(super) fn mod_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) { ++ if self.canvas_up() { ++ if pressed { ++ self.canvas_key(key); ++ } ++ return; ++ } + if repeat || !self.mods.mods.has_keys() { + return; + } +diff --git a/crates/horizon-client/src/game/mod_render.rs b/crates/horizon-client/src/game/mod_render.rs +index 85aae67e7..1648b9f2e 100644 +--- a/crates/horizon-client/src/game/mod_render.rs ++++ b/crates/horizon-client/src/game/mod_render.rs +@@ -27,7 +27,7 @@ struct Jolt { + + /// The HUD batch's colour (ABGR) from a mod's 0xAARRGGBB. + #[cfg(feature = "mods")] +-fn argb(color: u32) -> u32 { ++pub(super) fn argb(color: u32) -> u32 { + let [a, r, g, b] = color.to_be_bytes(); + rgba(r, g, b, a) + } +@@ -129,6 +129,7 @@ impl Game<'_> { + mode: v.mode, + }); + } ++ Shape::Terrain(t) => self.draw_terrain(batch, t, ox, oy), + Shape::Text(t) => { + let text = Text::literal(t.text.clone()); + let centre = if t.centered { +diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs +index 8a710054a..7f9714a18 100644 +--- a/crates/horizon-client/src/game/mods.rs ++++ b/crates/horizon-client/src/game/mods.rs +@@ -108,7 +108,10 @@ pub(super) struct ModsState { + remote_tree: Option, + /// A `ui` mod's screen or settings page while it is up. + #[cfg(feature = "mods")] +- screen: Option, ++ pub(super) screen: Option, ++ /// Capability `render`'s canvas: terrain tiles and pointer state. ++ #[cfg(feature = "mods")] ++ pub(super) canvas: super::mod_canvas::CanvasState, + /// The HUD font's advances for `render.text-width`, made once. + #[cfg(feature = "mods")] + font_widths: std::sync::Arc<[f32]>, +@@ -153,9 +156,9 @@ const FONT_CHARS: u32 = 0x250; + /// A `ui` mod's own screen, or its settings page from Options > Mods: the + /// widgets the mod pushed, laid out and drawn with the menus' own widgets. + #[cfg(feature = "mods")] +-struct ModScreen { ++pub(super) struct ModScreen { + /// The running mod's index in `mods.mods.entries()`. +- owner: usize, ++ pub(super) owner: usize, + /// Opened from Options > Mods: Done and Esc return there. + settings: bool, + /// What the mod's screen replaced (Playing, Chat, ...), to restore. +@@ -164,6 +167,21 @@ struct ModScreen { + scrolls: Vec, + /// A key row waiting for the key to bind: the mod key's name. + binding: Option, ++ /// The mod's canvas (`render.open-canvas`), not widgets. ++ pub(super) canvas: bool, ++} ++#[cfg(feature = "mods")] ++impl ModScreen { ++ pub(super) fn canvas(owner: usize, under: Screen) -> Self { ++ Self { ++ owner, ++ settings: false, ++ under, ++ scrolls: Vec::new(), ++ binding: None, ++ canvas: true, ++ } ++ } + } + impl ModsState { + /// The chat's command tree: vanilla's, plus the running mods' commands. +@@ -366,6 +384,7 @@ impl Game<'_> { + pub(super) fn close_mod_screen(&mut self, _tell: bool) {} + pub(super) fn draw_mod_screen(&mut self, _batch: &mut HudBatch) {} + pub(super) fn mod_screen_click(&mut self, _button: winit::event::MouseButton) {} ++ pub(super) fn mod_screen_mouse(&mut self, _button: winit::event::MouseButton, _pressed: bool) {} + pub(super) fn mod_screen_key(&mut self, _key: winit::keyboard::KeyCode) -> bool { + false + } +@@ -899,6 +918,7 @@ impl Game<'_> { + self.mods.mods.set_source_generation(self.audio.mod_sources.epoch); + self.mods.mods.set_acoustics(self.audio.acoustics.is_some()); + self.mods.mods.frame(elapsed.as_secs_f32()); ++ self.canvas_frame(); + self.show_mod_output(); + self.sync_mod_sources(); + } +@@ -1065,6 +1085,10 @@ impl Game<'_> { + self.audio.film_allow(false); + continue; + } ++ Output::SetAcoustics { on } => { ++ self.audio.set_acoustics(on); ++ continue; ++ } + Output::PlaceRecipe { book_id, all } => { + self.mod_place_recipe(book_id, all); + continue; +@@ -1215,6 +1239,10 @@ impl Game<'_> { + /// A key while a mod screen is up: true when a key row waited for + /// it (Key Binds: Escape binds none). + pub(super) fn mod_screen_key(&mut self, key: KeyCode) -> bool { ++ // A canvas has every key for itself (`mod_key` passes them on); Escape closes nothing. ++ if self.mods.screen.as_ref().is_some_and(|ms| ms.canvas) { ++ return true; ++ } + if self + .mods + .screen +@@ -1270,6 +1298,7 @@ impl Game<'_> { + under: self.screen, + scrolls: Vec::new(), + binding: None, ++ canvas: false, + }); + self.screen = Screen::Mod; + if self.player.is_some() { +@@ -1299,6 +1328,11 @@ impl Game<'_> { + /// The mod's screen or settings page: its title over widgets stacked + /// down the middle, a Done button, Esc to leave (vanilla's menus). + pub(super) fn draw_mod_screen(&mut self, batch: &mut HudBatch) { ++ if let Some(ms) = self.mods.screen.as_ref().filter(|m| m.canvas) { ++ let owner = ms.owner; ++ self.draw_canvas(batch, owner); ++ return; ++ } + let Some(ms) = self.mods.screen.as_mut() else { + // The screen was dropped while it was up: back to the world, + // mouse held again like any return to Playing. +@@ -1471,6 +1505,13 @@ impl Game<'_> { + } + /// A click on the mod screen: Done leaves it, a `list` row is the mod's + /// `ui-events::select`. ++ pub(super) fn mod_screen_mouse(&mut self, button: MouseButton, pressed: bool) { ++ if self.canvas_up() { ++ self.canvas_mouse(button, pressed); ++ } else if pressed { ++ self.mod_screen_click(button); ++ } ++ } + pub(super) fn mod_screen_click(&mut self, button: MouseButton) { + // Key Binds: a mouse button pressed while waiting binds it. + if self +@@ -1550,6 +1591,10 @@ impl Game<'_> { + } + /// The wheel over a `list` scrolls it. + pub(super) fn mod_screen_scroll(&mut self, delta: f32) { ++ if self.canvas_up() { ++ self.canvas_scroll(delta); ++ return; ++ } + let (w, h) = self.gui_size(); + let cursor = self.cursor; + let Some(ms) = self.mods.screen.as_mut() else { +diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs +index 41af0650e..7106c5d5f 100644 +--- a/crates/horizon-client/src/hud.rs ++++ b/crates/horizon-client/src/hud.rs +@@ -300,6 +300,10 @@ impl HudAtlas { + crate::minimap::SIZE as u32, + vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4], + )); ++ // A mod's terrain tiles (game/mod_canvas.rs). ++ for i in 0..24 { ++ images.push((format!("horizon/mapview{i}"), 128, 128, vec![0; 128 * 128 * 4])); ++ } + // Downloaded skins (game/scoreboard.rs). + for i in 0..SKIN_SLOTS { + images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); +diff --git a/crates/horizon-client/src/minimap.rs b/crates/horizon-client/src/minimap.rs +index 8b250e1af..7951fb0e0 100644 +--- a/crates/horizon-client/src/minimap.rs ++++ b/crates/horizon-client/src/minimap.rs +@@ -262,6 +262,8 @@ pub struct Minimap { + composed: Option, + /// Tiles changed since the image was composed. + changed: bool, ++ /// Moves on when a scanned tile changed (a mod's terrain tiles). ++ version: u64, + /// The composed image, `SIZE` x `SIZE` RGBA. + pub image: Vec, + } +@@ -389,7 +391,109 @@ impl Minimap { + pub fn tile_count(&self) -> usize { + self.tiles.len() + } ++ /// A mod's terrain tiles (AirDef fork): scan the loaded chunks for which ++ /// `wanted` is true that have no tile or a stale one, nearest `near` ++ /// first, until `budget` is spent; tiles of chunks nobody wants are kept ++ /// up to a bound. Returns the tiles scanned; [`Minimap::version`] moves ++ /// on when any tile's content changed. ++ pub fn scan_loaded( ++ &mut self, ++ world: &World, ++ facts: &BlockFacts, ++ wanted: impl Fn((i32, i32)) -> bool, ++ near: (f64, f64), ++ budget: Duration, ++ ) -> usize { ++ let palette = self.palette.get_or_insert_with(|| Palette::new(facts)); ++ let started = Instant::now(); ++ let air = world.air.0; ++ if self.tiles.len() > KEPT_TILES { ++ self.tiles.retain(|k, _| wanted(*k) && world.chunks.contains_key(k)); ++ self.version += 1; ++ } ++ let mut stale: Vec<(f64, (i32, i32))> = Vec::new(); ++ for key in world.chunks.keys().copied().filter(|k| wanted(*k)) { ++ let due = match self.tiles.get(&key) { ++ None => true, ++ Some(t) if t.layer != Layer::Surface => true, ++ Some(t) => t.revision != world.revision && t.scanned.elapsed() >= RESCAN, ++ }; ++ if due { ++ let (dx, dz) = (f64::from(key.0 * 16 + 8) - near.0, f64::from(key.1 * 16 + 8) - near.1); ++ stale.push((dx * dx + dz * dz, key)); ++ } ++ } ++ stale.sort_by(|a, b| a.0.total_cmp(&b.0)); ++ let mut scanned = 0; ++ for (_, key) in stale { ++ let Some(chunk) = world.chunks.get(&key) else { ++ continue; ++ }; ++ let tile = scan_tile(chunk, palette, air, Layer::Surface, world.revision); ++ if self ++ .tiles ++ .get(&key) ++ .is_none_or(|t| t.color != tile.color || t.height != tile.height || t.depth != tile.depth) ++ { ++ self.version += 1; ++ } ++ self.tiles.insert(key, tile); ++ scanned += 1; ++ if started.elapsed() >= budget { ++ break; ++ } ++ } ++ scanned ++ } ++ /// Moves on whenever a tile was added or changed. ++ pub fn version(&self) -> u64 { ++ self.version ++ } ++ /// One 128 x 128 RGBA tile of the map for a mod (AirDef fork): texel ++ /// (i, j) shows the column (`x + i * step`, `z + j * step`) with the map ++ /// item's colours and height shading, transparent where its chunk has no ++ /// tile. Returns the texels that are known. ++ pub fn compose_terrain(&self, x: i32, z: i32, step: i32, out: &mut Vec) -> usize { ++ out.clear(); ++ out.resize(SIZE * SIZE * 4, 0); ++ let mut known = 0; ++ let mut cached: Option<((i32, i32), &Tile)> = None; ++ let mut column = |x: i32, z: i32| -> Option<(u8, i16, u8)> { ++ let key = (x >> 4, z >> 4); ++ let tile = match cached { ++ Some((k, t)) if k == key => t, ++ _ => { ++ let t = self.tiles.get(&key)?; ++ cached = Some((key, t)); ++ t ++ } ++ }; ++ let i = ((z & 15) * 16 + (x & 15)) as usize; ++ Some((tile.color[i], tile.height[i], tile.depth[i])) ++ }; ++ let shade = f64::from(step.max(1)).sqrt(); ++ for j in 0..SIZE as i32 { ++ for i in 0..SIZE as i32 { ++ let (wx, wz) = (x.wrapping_add(i * step), z.wrapping_add(j * step)); ++ let Some((color, height, depth)) = column(wx, wz).filter(|c| c.0 & !WALL != 0) else { ++ continue; ++ }; ++ // The neighbour to the north, a texel away; its height difference is eased by the ++ // step so a coarse texel isn't all ridge. ++ let north = column(wx, wz - step.max(1)) ++ .filter(|c| c.0 & !WALL != 0) ++ .map(|c| (f64::from(height) - f64::from(height - c.1) / shade).round() as i16); ++ let b = brightness(color, height, north, depth, wx + wz); ++ let o = (j as usize * SIZE + i as usize) * 4; ++ out[o..o + 4].copy_from_slice(&packed_rgba(color & !WALL, b)); ++ known += 1; ++ } ++ } ++ known ++ } + } ++/// Tiles a mod's terrain keeps beyond the ones it wants. ++const KEPT_TILES: usize = 4096; + /// Chunk offsets at Chebyshev distance `ring`. + fn ring_offsets(ring: i32) -> impl Iterator { + (-ring..=ring).flat_map(move |dz| { +diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit +index a055af8bd..805c2a515 100644 +--- a/crates/horizon-mod-sdk/wit/horizon.wit ++++ b/crates/horizon-mod-sdk/wit/horizon.wit +@@ -423,6 +423,23 @@ interface render { + /// 0 as seen, 1 thermal (white hot), 2 night vision (green). + mode: u32, + } ++ /// A square of the world's land seen from above, in the map colours of ++ /// a map item with its height shading (AirDef fork, API level 24); only ++ /// in `set-canvas`'s shapes. It is 128 × 128 texels, a texel being ++ /// `blocks-per-texel` × `blocks-per-texel` blocks whose north-west ++ /// corner is (`x`, `z`); the game keeps up to 24 such tiles at a time ++ /// and draws none of the rest. A mod aligns the corners to multiples of ++ /// 128 × `blocks-per-texel` so tiles meet and are reused as the view ++ /// moves. Where a chunk isn't loaded the tile is transparent (the mod ++ /// draws its own "unknown" under it); the game scans chunks within a ++ /// small time budget a frame, so a tile fills in over a few frames. ++ record terrain-shape { ++ rect: rect, ++ x: s32, ++ z: s32, ++ /// 1, 2, 4, 8, 16, 32 or 64; another value is rounded to one. ++ blocks-per-texel: u32, ++ } + variant shape { + fill(fill-shape), + quad(quad-shape), +@@ -430,6 +447,7 @@ interface render { + item(item-shape), + text(text-shape), + view(view-shape), ++ terrain(terrain-shape), + } + /// Replaces the mod's HUD shapes: up to 1024, drawn every frame in + /// order over the HUD (after the hotbar, under chat and screens), hidden +@@ -667,6 +685,10 @@ interface render { + /// muffles by itself (a `_far` variant for a distant blast) plays the near + /// one instead when this is true, so nothing is muffled twice. + acoustics: func() -> bool; ++ /// Turns that on or off (AirDef fork, API level 23), from the next tick: ++ /// what `HORIZON_ACOUSTICS` sets at the start. Sounds that play go back ++ /// to the plain ones smoothly. ++ set-acoustics: func(on: bool); + /// Starts, updates and stops persistent sound sources. `generation` is + /// the `sound-source-generation` the mod's sources belong to; if it is + /// not the current one the call is ignored and returns false (read the +@@ -692,6 +714,49 @@ interface render { + /// the game does not simulate itself, or with nothing running, it does + /// nothing, and `ground` keeps answering -64 for the unloaded. + load-chunks: func(chunks: list>); ++ /// What the player did on the mod's canvas (AirDef fork, API level 24). ++ /// Points are in GUI pixels from the screen's top left. ++ record canvas-button { ++ /// 0 left, 1 right, 2 middle, 3 and up the side buttons. ++ button: u32, ++ at: point, ++ } ++ record canvas-scroll { ++ /// Wheel steps, positive away from the player (up). ++ steps: f32, ++ at: point, ++ } ++ variant canvas-event { ++ /// The pointer moved (one event a frame at most). ++ moved(point), ++ pressed(canvas-button), ++ released(canvas-button), ++ scrolled(canvas-scroll), ++ /// A key went down or repeated: `key.keyboard.escape`, as ++ /// options.txt writes it. Escape does not close the canvas by ++ /// itself: the mod does, with `close-canvas`. ++ key(string), ++ /// The screen's size changed, or the canvas opened: width, height. ++ resized(tuple), ++ } ++ /// Shows a full-screen canvas over the game (AirDef fork, API level 24): ++ /// the mod's `set-canvas` shapes over a dark background, with the ++ /// pointer free. The world goes on running (no pause), the mouse is ++ /// released, and every key and button goes to the mod as ++ /// `canvas-events`, none to the game. Needs nothing the mod can't do ++ /// without: when the mod stops the canvas closes. Not on the title ++ /// screen. ++ open-canvas: func(); ++ /// Closes the canvas when it is open. ++ close-canvas: func(); ++ /// Replaces the canvas's shapes: up to 8192, drawn in order every frame ++ /// until the next call. ++ set-canvas: func(shapes: list); ++ /// The events since the last call, oldest first, at most 256. ++ canvas-events: func() -> list; ++ /// Whether the canvas is up (the game never closes it but at the mod's ++ /// word, or when the world is left). ++ canvas-open: func() -> bool; + /// What a block is to a query (AirDef fork): the three policies differ + /// on purpose, so a sensor and a missile may disagree about a pane of + /// glass. +diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs +index 8894fad5b..579af9e25 100644 +--- a/crates/horizon-mods/src/api_level.rs ++++ b/crates/horizon-mods/src/api_level.rs +@@ -7,13 +7,13 @@ + //! version's level so the launcher can tell before it installs. + + /// The newest level this Horizon serves. +-pub const LEVEL: u32 = 22; ++pub const LEVEL: u32 = 24; + + /// Every function the game offers mods, as `interface.function`, with its + /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new + /// function takes the next level and raises [`LEVEL`] (the `api_reference` + /// test fails until it is listed here). +-pub const FUNCTIONS: [(&str, u32); 84] = [ ++pub const FUNCTIONS: [(&str, u32); 90] = [ + ("log.write", 0), + ("game.get-player", 0), + ("game.get-clock", 0), +@@ -110,6 +110,14 @@ pub const FUNCTIONS: [(&str, u32); 84] = [ + ("render.acoustics", 21), + // AirDef fork: the game loads chunks for a mod for a while. + ("render.load-chunks", 22), ++ // AirDef fork: a mod switches the game's acoustics. ++ ("render.set-acoustics", 23), ++ // AirDef fork: a full-screen canvas with the pointer, and terrain tiles for it. ++ ("render.open-canvas", 24), ++ ("render.close-canvas", 24), ++ ("render.set-canvas", 24), ++ ("render.canvas-events", 24), ++ ("render.canvas-open", 24), + ]; + + /// What the game's program carries so the launcher can read its level +diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs +index 4b31c8dce..81286975f 100644 +--- a/crates/horizon-mods/src/runtime.rs ++++ b/crates/horizon-mods/src/runtime.rs +@@ -89,6 +89,7 @@ pub use render_bindings::horizon::mods::render::{ + RayAnswer as WorldRayAnswer, Rect as RenderRect, Section as WorldSection, SectionFill, Shape, + SmokeSegment, SourceOp, SourceOpKind, SpotLight, SpriteShape, TextShape, Verdict as WorldVerdict, ViewShape, + Zoom as ModZoom, ++ CanvasButton, CanvasEvent, CanvasScroll, TerrainShape, + }; + use render_bindings::{RenderHost, horizon::mods::render}; + /// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items. +@@ -221,6 +222,8 @@ impl Runs { + pub enum Output { + /// `chat.show`: a line after the mod's name. + Chat { name: String, text: String }, ++ /// `render.set-acoustics`: the game's acoustics on or off. ++ SetAcoustics { on: bool }, + /// A mod command's feedback, red when `error`. + Feedback { text: String, error: bool }, + /// `command.run`: a vanilla command line, without its slash, to run as +@@ -501,6 +504,8 @@ struct State { + shapes: Vec, + /// Capability `render`'s corner panel. + corner: Option, ++ /// Capability `render`'s canvas (AirDef fork, API level 24). ++ canvas: CanvasState, + /// Capability `render`'s zoom, when the mod zooms. + zoom: Option, + /// Capability `render`'s minimap, when the mod shows one. +@@ -777,6 +782,7 @@ impl Mods { + panel: None, + ui: UiState::default(), + shapes: Vec::new(), ++ canvas: CanvasState::default(), + corner: None, + zoom: None, + minimap: None, +@@ -1360,6 +1366,51 @@ impl Mods { + .filter_map(|e| e.run.as_ref()?.store.data().zoom) + .max_by(|a, b| a.factor.total_cmp(&b.factor)) + } ++ /// The mod whose canvas is up (`render.open-canvas`), if any: the first. ++ pub fn canvas_wanted(&self) -> Option { ++ self.entries ++ .iter() ++ .position(|e| e.run.as_ref().is_some_and(|r| r.store.data().canvas.open)) ++ } ++ /// Mod `i`'s canvas shapes. ++ pub fn canvas_shapes(&self, i: usize) -> &[Shape] { ++ self.entries ++ .get(i) ++ .and_then(|e| e.run.as_ref()) ++ .map_or(&[], |r| &r.store.data().canvas.shapes) ++ } ++ /// The player did something on mod `i`'s canvas; a pointer move or a ++ /// resize replaces the one still waiting. ++ pub fn canvas_push(&mut self, i: usize, event: CanvasEvent) { ++ let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) else { ++ return; ++ }; ++ let c = &mut run.store.data_mut().canvas; ++ if !c.open { ++ return; ++ } ++ let same = |a: &CanvasEvent, b: &CanvasEvent| { ++ matches!((a, b), (CanvasEvent::Moved(_), CanvasEvent::Moved(_)) | (CanvasEvent::Resized(_), CanvasEvent::Resized(_))) ++ }; ++ if let Some(last) = c.events.back_mut() ++ && same(last, &event) ++ { ++ *last = event; ++ return; ++ } ++ if c.events.len() == CANVAS_EVENTS { ++ c.events.pop_front(); ++ } ++ c.events.push_back(event); ++ } ++ /// Mod `i`'s canvas was closed by the game (the world was left). ++ pub fn canvas_closed(&mut self, i: usize) { ++ if let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) { ++ let c = &mut run.store.data_mut().canvas; ++ c.open = false; ++ c.events.clear(); ++ } ++ } + /// The minimap the first running mod shows (capability `render`). + pub fn minimap(&self) -> Option { + self.entries +@@ -2196,6 +2247,19 @@ impl input::Host for State { + + /// HUD shapes one mod may keep (capability `render`). + const SHAPES: usize = 1024; ++/// Shapes a canvas keeps, and events waiting for `canvas-events`. ++const CANVAS_SHAPES: usize = 8192; ++const CANVAS_EVENTS: usize = 256; ++ ++/// A mod's canvas (`render.open-canvas`): whether it is up, what it draws ++/// and what the player did on it. ++#[derive(Default)] ++struct CanvasState { ++ open: bool, ++ shapes: Vec, ++ events: std::collections::VecDeque, ++} ++ + /// The longest jolt `render.shake` makes, in seconds. + const SHAKE_SECONDS: f32 = 10.0; + /// `render.set-zoom`'s limits: `Camera.tickFov` keeps the modifier at 0.1 +@@ -2254,7 +2318,45 @@ fn clip_shapes(shapes: Vec) -> Vec { + + impl render::Host for State { + fn set_hud(&mut self, shapes: Vec) { +- self.shapes = clip_shapes(shapes); ++ self.shapes = clip_shapes(shapes) ++ .into_iter() ++ .filter(|s| !matches!(s, Shape::Terrain(_))) ++ .collect(); ++ } ++ fn open_canvas(&mut self) { ++ self.canvas.open = true; ++ } ++ fn close_canvas(&mut self) { ++ self.canvas.open = false; ++ self.canvas.events.clear(); ++ } ++ fn set_canvas(&mut self, shapes: Vec) { ++ let mut shapes = shapes; ++ shapes.truncate(CANVAS_SHAPES); ++ for shape in &mut shapes { ++ match shape { ++ Shape::Sprite(s) => s.sprite = clip(std::mem::take(&mut s.sprite)), ++ Shape::Item(i) => { ++ i.item = clip(std::mem::take(&mut i.item)); ++ i.scale = if i.scale.is_finite() { i.scale.clamp(0.0, 16.0) } else { 1.0 }; ++ } ++ Shape::Text(t) => { ++ t.text = clip(std::mem::take(&mut t.text)); ++ t.color &= 0xFF_FFFF; ++ } ++ Shape::Terrain(t) => { ++ t.blocks_per_texel = t.blocks_per_texel.clamp(1, 64).next_power_of_two().min(64); ++ } ++ _ => {} ++ } ++ } ++ self.canvas.shapes = shapes; ++ } ++ fn canvas_events(&mut self) -> Vec { ++ self.canvas.events.drain(..).collect() ++ } ++ fn canvas_open(&mut self) -> bool { ++ self.canvas.open + } + fn set_corner(&mut self, corner: RenderCorner, width: f32, height: f32, shapes: Vec) { + let size = |v: f32| { +@@ -2717,6 +2819,9 @@ impl render::Host for State { + sections: Vec::new(), + }) + } ++ fn set_acoustics(&mut self, on: bool) { ++ self.out.push(Output::SetAcoustics { on }); ++ } + fn acoustics(&mut self) -> bool { + self.model_table.lock().is_ok_and(|t| t.acoustics) + } +diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md +index 9ce18e77a..cf6e61440 100644 +--- a/docs/api/mods-reference.md ++++ b/docs/api/mods-reference.md +@@ -462,6 +462,17 @@ A picture of one of the mod's `set-views` cameras (AirDef fork). + | `rect` | `rect` | | + | `mode` | `u32` | 0 as seen, 1 thermal (white hot), 2 night vision (green). | + ++### record `terrain-shape` ++ ++A square of the world's land seen from above, in the map colours of a map item with its height shading (AirDef fork, API level 24); only in `set-canvas`'s shapes. It is 128 × 128 texels, a texel being `blocks-per-texel` × `blocks-per-texel` blocks whose north-west corner is (`x`, `z`); the game keeps up to 24 such tiles at a time and draws none of the rest. A mod aligns the corners to multiples of 128 × `blocks-per-texel` so tiles meet and are reused as the view moves. Where a chunk isn't loaded the tile is transparent (the mod draws its own "unknown" under it); the game scans chunks within a small time budget a frame, so a tile fills in over a few frames. ++ ++| Field | Type | | ++| --- | --- | --- | ++| `rect` | `rect` | | ++| `x` | `s32` | | ++| `z` | `s32` | | ++| `blocks-per-texel` | `u32` | 1, 2, 4, 8, 16, 32 or 64; another value is rounded to one. | ++ + ### variant `shape` + + | Case | Payload | | +@@ -472,6 +483,7 @@ A picture of one of the mod's `set-views` cameras (AirDef fork). + | `item` | `item-shape` | | + | `text` | `text-shape` | | + | `view` | `view-shape` | | ++| `terrain` | `terrain-shape` | | + + ### record `frame-rate` + +@@ -588,6 +600,33 @@ One change of a persistent sound source (AirDef fork, API level 20): a sound tha + | `loop-from` | `f32` | A looping source repeats the part of its sound from `loop-from` to `loop-to` seconds into it (both 0: all of it), the join crossfaded over 50 ms: for sounds that fade in and die away at their ends. | + | `loop-to` | `f32` | | + ++### record `canvas-button` ++ ++What the player did on the mod's canvas (AirDef fork, API level 24). Points are in GUI pixels from the screen's top left. ++ ++| Field | Type | | ++| --- | --- | --- | ++| `button` | `u32` | 0 left, 1 right, 2 middle, 3 and up the side buttons. | ++| `at` | `point` | | ++ ++### record `canvas-scroll` ++ ++| Field | Type | | ++| --- | --- | --- | ++| `steps` | `f32` | Wheel steps, positive away from the player (up). | ++| `at` | `point` | | ++ ++### variant `canvas-event` ++ ++| Case | Payload | | ++| --- | --- | --- | ++| `moved` | `point` | The pointer moved (one event a frame at most). | ++| `pressed` | `canvas-button` | | ++| `released` | `canvas-button` | | ++| `scrolled` | `canvas-scroll` | | ++| `key` | `string` | A key went down or repeated: `key.keyboard.escape`, as options.txt writes it. Escape does not close the canvas by itself: the mod does, with `close-canvas`. | ++| `resized` | `tuple` | The screen's size changed, or the canvas opened: width, height. | ++ + ### enum `policy` + + What a block is to a query (AirDef fork): the three policies differ on purpose, so a sensor and a missile may disagree about a pane of glass. +@@ -804,10 +843,16 @@ Where a capture is. + | `play-sound` | `func(event: string, x: f64, y: f64, z: f64, volume: f32, pitch: f32)` | Plays a sound event (`minecraft:entity.generic.explode`, `:`) at a point on this client. | + | `sound-source-generation` | `func() -> u32` | Moves on whenever the game released every source of every mod (the world closed, the session ended, a film began or ended, the sounds reloaded). A mod reads it before `sound-sources` and starts its sources again when it changed. | + | `acoustics` | `func() -> bool` | Whether the game muffles sounds by what lies between them and the listener (AirDef fork, API level 21: `HORIZON_ACOUSTICS`). A mod that muffles by itself (a `_far` variant for a distant blast) plays the near one instead when this is true, so nothing is muffled twice. | ++| `set-acoustics` | `func(on: bool)` | Turns that on or off (AirDef fork, API level 23), from the next tick: what `HORIZON_ACOUSTICS` sets at the start. Sounds that play go back to the plain ones smoothly. | + | `sound-sources` | `func(generation: u32, ops: list) -> bool` | Starts, updates and stops persistent sound sources. `generation` is the `sound-source-generation` the mod's sources belong to; if it is not the current one the call is ignored and returns false (read the generation, forget the sources, start them again). Stops are never dropped by a limit: only new sources beyond 256 running are, and at most 512 entries a call count. Every source of a mod that stops or is reloaded is released by the game. | + | `query-ground` | `func(columns: list>)` | Asks for the ground height of these columns (x, z): at most 512 a tick, answered by `ground` from the next tick on. | + | `ground` | `func() -> list>` | The answers to the last tick's `query-ground`: (x, z, y), y one above the highest block that blocks motion or holds a fluid, as the motion blocking heightmap; -64 where the chunk isn't loaded; -2147483648 (`i32::MIN`) where it isn't loaded yet but `load-chunks` has it on its way: ask again in a few ticks. | + | `load-chunks` | `func(chunks: list>)` | Has the game load these chunks (chunk x, chunk z) for a while (AirDef fork, API level 22): generated or read from disk on the game's worker threads, meshed never, and kept loaded for 20 seconds after the last call that named them. At most 64 chunks are wanted at once (the oldest requests fall away first; 64 a call). On a server, in a world the game does not simulate itself, or with nothing running, it does nothing, and `ground` keeps answering -64 for the unloaded. | ++| `open-canvas` | `func()` | Shows a full-screen canvas over the game (AirDef fork, API level 24): the mod's `set-canvas` shapes over a dark background, with the pointer free. The world goes on running (no pause), the mouse is released, and every key and button goes to the mod as `canvas-events`, none to the game. Needs nothing the mod can't do without: when the mod stops the canvas closes. Not on the title screen. | ++| `close-canvas` | `func()` | Closes the canvas when it is open. | ++| `set-canvas` | `func(shapes: list)` | Replaces the canvas's shapes: up to 8192, drawn in order every frame until the next call. | ++| `canvas-events` | `func() -> list` | The events since the last call, oldest first, at most 256. | ++| `canvas-open` | `func() -> bool` | Whether the canvas is up (the game never closes it but at the mod's word, or when the world is left). | + | `query-rays` | `func(rays: list)` | Traces segments through the loaded blocks (AirDef fork): each is walked block by block on the host, against the real collision shapes (`policy`), and answered by `rays` from the next tick on. At most 256 segments a tick, each at most 512 blocks long (longer ones are answered `unknown` past that); over the budget they are answered `unknown` too, never `clear`. A game with no chunk at a place answers `unknown` for it. | + | `rays` | `func() -> list` | The answers to the last tick's `query-rays`, in the order asked. | + | `query-sections` | `func(policy: policy, sections: list>)` | Asks what these sections hold (AirDef fork), for a mod that traces its own paths against a cache of them: at most 64 a tick, answered by `sections` from the next tick on. Over the budget they are not answered: ask again. | +-- +2.54.0 (Apple Git-157) + diff --git a/tools/acoustics_check.py b/tools/acoustics_check.py index 9f4f95d..fbe9d7f 100644 --- a/tools/acoustics_check.py +++ b/tools/acoustics_check.py @@ -17,6 +17,15 @@ python3 tools/acoustics_check.py --echo-dir папка # gorge/field/room и expected.txt из export_echo_tracks Дорожки пишет `audio::tests::export_echo_tracks` (HORIZON_ACOUSTICS_OUT=папка). Коды выхода те же. +Режим `--reverb-dir` (стадия 3): папка из `audio::tests::export_reverb_tracks` (щелчок в комнате, тоннеле, ущелье +и поле; `expected_reverb.txt`: предсказанный спад и уровень из замера пространства). По хвосту после прямого звука +считаются RT60 (обратное интегрирование Шрёдера, спад с -5 до -35 дБ, удвоенный) и энергия хвоста к энергии щелчка: + + python3 tools/acoustics_check.py --reverb-dir папка [--rt-tol 0.35] + +Проверяется: в поле хвоста нет (энергия хвоста меньше -90 дБ от щелчка), спад упорядочен поле < ущелье < тоннель < +комната, у комнаты и тоннеля измеренный RT60 в пределах `--rt-tol` от того, что дают их посылки в слоты (колонка +`RT60 expected`: сумма экспонент слотов, спад -5...-35 дБ; слой из двух слотов читается длиннее короткого). Только стандартная библиотека. """ import argparse @@ -98,6 +107,57 @@ def check_echo(path, expect, tol, rate, channels): return ok +def reverb_track(path, rate, channels, dry_ms=60.0): + """(tail energy relative to the click in dB or None, RT60 in s or None) of a click's track.""" + raw = array.array("h") + with open(path, "rb") as f: + data = f.read() + raw.frombytes(data[: len(data) // 2 * 2]) + left = [s / 32768.0 for s in raw[0::channels]] + cut = int(dry_ms * rate / 1000) + dry = sum(v * v for v in left[:cut]) + tail = left[cut:] + energy = sum(v * v for v in tail) + if dry <= 0 or energy <= 0 or 10 * math.log10(energy / dry) < -90: + return None, None + edc, acc = [0.0] * len(tail), 0.0 + for i in range(len(tail) - 1, -1, -1): + acc += tail[i] * tail[i] + edc[i] = acc + level = lambda i: 10 * math.log10(max(edc[i], 1e-30) / edc[0]) + a = next((i for i in range(len(tail)) if level(i) <= -5), None) + b = next((i for i in range(len(tail)) if level(i) <= -35), None) + rt = 2 * (b - a) / rate if a is not None and b is not None else None + return 10 * math.log10(energy / dry), rt + + +def check_reverb(folder, rate, channels, tol): + import os + want = {} + with open(os.path.join(folder, "expected_reverb.txt")) as f: + for line in f: + name, decay, wet, effective = line.split() + want[name] = (float(decay), float(wet), float(effective)) + got = {} + print(f"{'scene':>8} {'decay of space':>16} {'RT60 expected':>14} {'measured RT60 s':>16} {'tail/click dB':>14}") + for name in ("field", "gorge", "tunnel", "room"): + level, rt = reverb_track(os.path.join(folder, name + ".raw"), rate, channels) + got[name] = (level, rt) + print(f"{name:>8} {want[name][0]:16.2f} {want[name][2]:14.2f} {('none' if rt is None else f'{rt:.2f}'):>16} {('none' if level is None else f'{level:.1f}'):>14}") + ok = got["field"][1] is None + print(f" field has no tail: {'ok' if ok else 'FAIL'}") + order = [got[n][1] for n in ("gorge", "tunnel", "room")] + ordered = all(v is not None for v in order) and order[0] < order[1] < order[2] + print(f" gorge < tunnel < room: {'ok' if ordered else 'FAIL'}") + close = True + for n in ("tunnel", "room"): + rt = got[n][1] + good = rt is not None and abs(rt - want[n][2]) <= tol * want[n][2] + close &= good + print(f" {n} within {tol:.0%} of the RT60 its sends make: {'ok' if good else 'FAIL'}") + return ok and ordered and close + + def db(a, b): return 10 * math.log10(max(a, 1e-20) / max(b, 1e-20)) @@ -107,6 +167,8 @@ def main(): p.add_argument("open", nargs="?") p.add_argument("wall", nargs="?") p.add_argument("--echo", help="track with one click: check the delays of its echoes") + p.add_argument("--reverb-dir", help="folder written by export_reverb_tracks: check the decay of room, tunnel, gorge, field") + p.add_argument("--rt-tol", type=float, default=0.35, help="how far a measured RT60 may be from the predicted, as a fraction") p.add_argument("--echo-dir", help="folder written by export_echo_tracks: check gorge, field and room") p.add_argument("--expect", default="none", help="expected delays in ms, comma separated, or none") p.add_argument("--tol", type=float, default=1.0, help="ms a peak may be off") @@ -115,6 +177,8 @@ def main(): p.add_argument("--min-high-cut", type=float, default=15.0, help="dB the band above 5 kHz must drop") p.add_argument("--max-low-loss", type=float, default=8.0, help="dB the band below 300 Hz may drop") a = p.parse_args() + if a.reverb_dir: + return 0 if check_reverb(a.reverb_dir, a.rate, a.channels, a.rt_tol) else 1 if a.echo_dir: import os ok = True diff --git a/tools/gen_models.py b/tools/gen_models.py index 23cb473..59c22bc 100644 --- a/tools/gen_models.py +++ b/tools/gen_models.py @@ -7,7 +7,8 @@ Запуск: python3 tools/gen_models.py [--check] -Скрипт пишет во временный каталог и только потом переносит результат в airdef-mod/. Список созданных им файлов +Скрипт пишет во временный каталог, проверяет набор (validate: ссылки моделей и текстур, JSON, PNG) и только потом +переносит результат в airdef-mod/; при ошибке проверки ничего не записывает. Список созданных им файлов с sha256 лежит в airdef-mod/generated-manifest.txt (формат sha256sum). Удаляются и перезаписываются только файлы из этого списка и только если их не правили вручную; чужой файл на пути генерируемого останавливает запуск. --check ничего не пишет и выходит с кодом 1, если airdef-mod/ отличается от того, что дал бы запуск. @@ -1745,6 +1746,105 @@ def generate(out): return len(MODELS), len(ITEMS), len(TEXTURES) +# ---------------------------------------------------------------- проверка набора до переноса +def check_png(path, rel): + try: + with Image.open(path) as im: + w, h = im.size + im.load() + except Exception as e: # битый файл или не PNG + return [f"{rel}: PNG не открывается: {e}"] + errs = [] + if w != h: + errs.append(f"{rel}: текстура не квадратная, {w}x{h}") + if w < 8 or w > 256 or w & (w - 1): + errs.append(f"{rel}: размер {w}x{h}, ожидается степень двойки от 8 до 256") + return errs + + +def validate(stage): + # Проверяет набор в каталоге stage до того, как он попадёт в airdef-mod/. Возвращает список ошибок. + # Ссылки airdef:<путь> проверяем по набору; ссылки minecraft:... и без пространства имён — ванильные, их не проверяем. + errors = [] + files, docs = set(), {} + for dirpath, _, names in os.walk(stage): + for name in sorted(names): + path = os.path.join(dirpath, name) + rel = os.path.relpath(path, stage).replace(os.sep, "/") + files.add(rel) + if name.endswith(".json"): + try: + with open(path, encoding="utf-8") as f: + docs[rel] = json.load(f) + except (OSError, ValueError) as e: + errors.append(f"{rel}: не разбирается как JSON: {e}") + elif name.endswith(".png"): + errors.extend(check_png(path, rel)) + + def check_ref(ref, kind, ext, owner): + if not isinstance(ref, str) or not ref.startswith(NS + ":"): + return + path = ref[len(NS) + 1:] + if not path or path.startswith("/") or ".." in path.split("/"): + errors.append(f"{owner}: недопустимая ссылка {ref}") + return + rel = f"assets/{NS}/{kind}/{path}{ext}" + if rel not in files: + errors.append(f"{owner}: ссылка {ref} не найдена ({rel})") + + def pick(prefix): + return sorted(rel for rel in docs if rel.startswith(f"assets/{NS}/{prefix}")) + + for rel in pick("models/"): + doc = docs[rel] + if not isinstance(doc, dict): + errors.append(f"{rel}: модель должна быть объектом JSON") + continue + if "parent" in doc: + check_ref(doc["parent"], "models", ".json", rel) + tex = doc.get("textures", {}) + for key, val in tex.items(): + if isinstance(val, str) and val.startswith("#"): + if val[1:] not in tex: + errors.append(f"{rel}: текстура {val} не объявлена") + else: + check_ref(val, "textures", ".png", rel) + for i, el in enumerate(doc.get("elements", [])): + for corner in ("from", "to"): + pos = el.get(corner, []) + if len(pos) != 3 or any(not -16 <= c <= 32 for c in pos): + errors.append(f"{rel}: элемент {i}, {corner} {pos} вне -16..32") + for face, fd in el.get("faces", {}).items(): + tex_ref = fd.get("texture") + if tex_ref is None: + errors.append(f"{rel}: элемент {i}, грань {face} без texture") + elif tex_ref.startswith("#"): + if tex_ref[1:] not in tex: + errors.append(f"{rel}: элемент {i}, грань {face}: {tex_ref} не объявлена") + else: + check_ref(tex_ref, "textures", ".png", rel) + for rel in pick("blockstates/"): + for variant in docs[rel].get("variants", {}).values(): + for m in (variant if isinstance(variant, list) else [variant]): + check_ref(m.get("model"), "models", ".json", rel) + for rel in pick("items/"): + check_ref(docs[rel].get("model", {}).get("model"), "models", ".json", rel) + # У каждого блока есть blockstate, и наоборот. + blocks = {rel[len(f"assets/{NS}/models/block/"):] for rel in pick("models/block/")} + states = {rel[len(f"assets/{NS}/blockstates/"):] for rel in pick("blockstates/")} + for name in sorted(blocks - states): + errors.append(f"models/block/{name}: нет blockstate") + for name in sorted(states - blocks): + errors.append(f"blockstates/{name}: нет модели блока") + en = docs.get(f"assets/{NS}/lang/en_us.json") + ru = docs.get(f"assets/{NS}/lang/ru_ru.json") + if en is None or ru is None: + errors.append("нет lang/en_us.json или lang/ru_ru.json") + elif set(en) != set(ru): + errors.append(f"lang: ключи en_us и ru_ru различаются: {sorted(set(en) ^ set(ru))[:5]}") + return errors + + MANIFEST = os.path.join(ROOT, "generated-manifest.txt") @@ -1782,6 +1882,12 @@ def main(): old = read_manifest() with tempfile.TemporaryDirectory() as stage: counts = generate(stage) + errors = validate(stage) + if errors: + print(f"ПРОВЕРКА НАБОРА НЕ ПРОЙДЕНА, ошибок: {len(errors)}. Ничего не записано в {ROOT}.") + for err in errors: + print(f" - {err}") + sys.exit(1) new = {} for dirpath, dirs, names in os.walk(stage): dirs.sort()