Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c525feb465 |
@@ -2,7 +2,6 @@ run-home/
|
||||
.horizon-cache/
|
||||
airdef-mod/target/
|
||||
airdef-core/target/
|
||||
tools/rt-probe/target/
|
||||
__pycache__/
|
||||
/out/
|
||||
.DS_Store
|
||||
|
||||
@@ -182,20 +182,6 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда.
|
||||
Повторное J закрывает.
|
||||
|
||||
**Тактическая карта:** клавиша **M** открывает общую карту. Цели обозначены крупными отметками с классом,
|
||||
курсом и измеренной траекторией; наведение мыши показывает дистанцию, тип, состояние трека и перехват.
|
||||
По умолчанию доступны только данные сети РЛС. **T** переключает явно подписанный режим «Истина» для
|
||||
песочницы: в нём белые рамки показывают даже незамеченные аппараты, а жёлтый пунктир — их цель и будущий
|
||||
маршрут. Этот режим не меняет боевую логику.
|
||||
|
||||
**Обзор целей поверх мира:** удерживай **C** — вокруг видимых целей появляются квадратные метки с краткой
|
||||
строкой: класс, который оценили РЛС (неопознанная цель — «?», без утечки типа), и дистанция; устаревший
|
||||
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
|
||||
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
|
||||
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
|
||||
клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
|
||||
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется.
|
||||
|
||||
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
|
||||
(хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**:
|
||||
- **карта налёта** — вид сверху: комплексы и их зоны, объекты, треки целей (красные), ложных целей (серые) и
|
||||
@@ -214,7 +200,7 @@ API 31 форка) и следуют за взглядом покадрово;
|
||||
Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт
|
||||
(48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт».
|
||||
|
||||
Клавиши N, K, J, R, U и C (обзор целей, удержание) можно переназначить в «Настройки → Моды».
|
||||
Клавиши N, K, J, R и U можно переназначить в «Настройки → Моды».
|
||||
|
||||
Команды:
|
||||
- `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Дальность старта — от 60 до 4000 блоков (в меню: 200–4000); землю для площадок, которой нет в загруженных чанках, игра подгружает сама (API 22, `render.load-chunks`, пока идёт поиск), а где подгрузить нельзя (сервер) или нет пригодного места, дроны всё равно стартуют: «за картой», с высоты полёта на заказанной дальности, без площадки. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»);
|
||||
@@ -227,7 +213,7 @@ API 31 форка) и следуют за взглядом покадрово;
|
||||
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
|
||||
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
|
||||
- `/airdef ground-stock <номер склада> <количество>` — задать остаток RM48U для sandbox-сценария (по умолчанию 0). `/airdef ground-load <номер С-400>` загружает одну ракету у склада либо заказывает ТЗМ; `ground-unload` возвращает её у склада либо заказывает вывоз; `ground-cancel` отменяет ожидающую заявку. Доставка и обратный вывоз через ТЗМ реализованы, запас и груз сохраняются. [Пошаговый пример](docs/GROUND-STRIKES.md). Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
|
||||
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
|
||||
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — обзорная, сопровождающая и мачтовая игровые РЛС. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию, `/airdef radar <номер> multi|search|engagement|height` — роль отдельной РЛС. Обзорная РЛС передаёт подсказки; станция сопровождения должна сама получить свежее измерение, чтобы разрешить пуск. Старые С-400/С-500 сохраняют упрощённую сборную конфигурацию. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
|
||||
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
|
||||
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
|
||||
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
|
||||
@@ -237,23 +223,10 @@ API 31 форка) и следуют за взглядом покадрово;
|
||||
- `/airdef clear` — убрать дроны и ракеты;
|
||||
- `/airdef targets clear` — снять все цели;
|
||||
- `/airdef stats` — сводка.
|
||||
- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится.
|
||||
|
||||
Интерфейс:
|
||||
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение);
|
||||
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик».
|
||||
|
||||
**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет
|
||||
невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой
|
||||
только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип,
|
||||
прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит
|
||||
между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик —
|
||||
узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и
|
||||
счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник
|
||||
запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню
|
||||
N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и
|
||||
дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный
|
||||
HUD не выводится. Простые пресеты налёта фазу разведки не получают.
|
||||
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт;
|
||||
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели (с хвостом по курсу), жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара.
|
||||
|
||||
Комплексы ПВО и цели сохраняются между сессиями.
|
||||
|
||||
@@ -292,9 +265,7 @@ HUD не выводится. Простые пресеты налёта фазу
|
||||
|
||||
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
|
||||
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
|
||||
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
|
||||
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
|
||||
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
|
||||
**станция РЭБ** (`ew`), **прожектор** (`light`). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
|
||||
|
||||
**Согласование огня.** Комплексы делят цели между собой: на обычную цель идёт одна ракета, на баллистическую две; чем ближе цель к своей точке попадания,
|
||||
тем больше перехватчиков разрешено на неё сразу (за ~12 с до удара ещё один, за ~5 с — ещё один). Комплекс, у которого кончились ракеты
|
||||
|
||||
@@ -144,9 +144,7 @@ fn two_maximum_menu_raids_with_answered_flat_terrain() {
|
||||
let mut second = false;
|
||||
let mut overlap = false;
|
||||
let mut peak = 0;
|
||||
// Two maximum menu raids can keep the last supersonic contact in the air past
|
||||
// 5000 ticks under the radar profiles; the recording closes once the sky is clear.
|
||||
for now in 1..=8000 {
|
||||
for now in 1..=5000 {
|
||||
if !second && !sim.planning() {
|
||||
overlap = !sim.queue.is_empty() || sim.drones.iter().any(|d| d.alive());
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), expected);
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"model": {
|
||||
"type": "minecraft:model",
|
||||
"model": "airdef:item/deploy_optical"
|
||||
}
|
||||
}
|
||||
@@ -123,7 +123,6 @@
|
||||
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
|
||||
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
|
||||
"item.airdef.deploy_light": "Развернуть прожектор",
|
||||
"item.airdef.deploy_optical": "Развернуть оптический пост",
|
||||
"item.airdef.mover": "Пульт перемещения",
|
||||
"item.airdef.flare_gun": "Осветительная ракета",
|
||||
"item.airdef.remover": "Свернуть ПВО",
|
||||
|
||||
@@ -123,7 +123,6 @@
|
||||
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
|
||||
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
|
||||
"item.airdef.deploy_light": "Развернуть прожектор",
|
||||
"item.airdef.deploy_optical": "Развернуть оптический пост",
|
||||
"item.airdef.mover": "Пульт перемещения",
|
||||
"item.airdef.flare_gun": "Осветительная ракета",
|
||||
"item.airdef.remover": "Свернуть ПВО",
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"parent": "minecraft:item/generated",
|
||||
"textures": {
|
||||
"layer0": "airdef:item/deploy_radar"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"template": "minecraft:stick",
|
||||
"max_stack_size": 1
|
||||
}
|
||||
@@ -114,7 +114,6 @@ b50fe5804cbbe10df992ebbc7e095a32ce8b73fc35159fa19889640681e408e9 assets/airdef/
|
||||
0c9c5ee3fc87e2dc6d716bdb0bb5f30d3b265268bfd5083462b4861a8da65f0f assets/airdef/items/deploy_irist.json
|
||||
09e46a6c4b59f66c24060ac627e6a287bf6797c7b1e32a9ec6c9d9662fdc3de3 assets/airdef/items/deploy_light.json
|
||||
6983561b3558aee16662aa83d2d9af760fb6236cc7dbe79ba20802f8a2ff15b9 assets/airdef/items/deploy_nasams.json
|
||||
e39c555ff197ed6c7c8fdfab924b7a609b5d111a905ca599a75a7b1270448fcc assets/airdef/items/deploy_optical.json
|
||||
d8ac6a9258e2fc2e0791bbce18a3a07a72e471fbc72b6be7b5ca545c53f8d633 assets/airdef/items/deploy_p1sun.json
|
||||
e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json
|
||||
68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json
|
||||
@@ -137,8 +136,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
|
||||
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
|
||||
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
|
||||
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
|
||||
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/en_us.json
|
||||
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/ru_ru.json
|
||||
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/en_us.json
|
||||
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/ru_ru.json
|
||||
b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json
|
||||
c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json
|
||||
a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json
|
||||
@@ -255,7 +254,6 @@ a5d0450da8d6757b9b45f86e6b36977894dd9e3e1278c3668b99a8acab36f399 assets/airdef/
|
||||
e80ee81085241b9712e024bbef73ef744ef5493eebb88770f4912d8aae138fe6 assets/airdef/models/item/deploy_irist.json
|
||||
637b9bfe426ee50045f8fcbfd4f25dfbc1d819ce36dedbd60abdac63c274f088 assets/airdef/models/item/deploy_light.json
|
||||
3398844e90203f97ee73e35619684c775d1856c8ca3399b5ed682786170d9327 assets/airdef/models/item/deploy_nasams.json
|
||||
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_optical.json
|
||||
76019c05d070cf1141cdf95b744b3d6198ab99469dba1f88a6903de1de303bde assets/airdef/models/item/deploy_p1sun.json
|
||||
8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json
|
||||
d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json
|
||||
@@ -569,7 +567,6 @@ cc0877f40434365b45b03429222926aa0cf135e504017311be53263fd27c5f8f data/airdef/ho
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_irist.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_light.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_nasams.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_optical.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_p1sun.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json
|
||||
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json
|
||||
|
||||
+17
-188
@@ -1,34 +1,22 @@
|
||||
//! Player-facing labels for battery configuration and status.
|
||||
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
|
||||
use crate::sim::{Sam, SamKind};
|
||||
//! Player-facing labels for battery configuration snapshots.
|
||||
use crate::sim::battery::{BatteryStatus, RadarRole, SamMode};
|
||||
|
||||
/// One profile's functions in a line the player can read.
|
||||
pub fn radar_profile_line(profile: RadarProfile) -> String {
|
||||
let channels = if profile.channels == 0 { "без каналов уточнения".to_string() } else { format!("каналы {}", profile.channels) };
|
||||
format!(
|
||||
"{} [{}]: {}, оборот {:.1} с, {}, локальный поиск {}; развёртывание: {}",
|
||||
profile.name,
|
||||
profile.id,
|
||||
profile.products_text(),
|
||||
profile.cycle as f64 / 20.0,
|
||||
channels,
|
||||
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
|
||||
profile.deployment,
|
||||
)
|
||||
pub fn radar_role_name(role: RadarRole) -> &'static str {
|
||||
match role {
|
||||
RadarRole::Multifunction => "многофункциональная",
|
||||
RadarRole::Search => "обзорная",
|
||||
RadarRole::Engagement => "сопровождения",
|
||||
RadarRole::Height => "мачтовая",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(status: BatteryStatus) -> String {
|
||||
match status {
|
||||
BatteryStatus::Radar { index, role, emitting, operational } => {
|
||||
let profile = role.profile();
|
||||
format!(
|
||||
"№{} РЛС: {}; излучение {}, {}",
|
||||
index + 1,
|
||||
radar_profile_line(profile),
|
||||
if emitting { "вкл" } else { "выкл" },
|
||||
if operational { "работает" } else { "нет связи или РЛС не работает" }
|
||||
)
|
||||
}
|
||||
BatteryStatus::Radar { index, role, emitting, operational } => format!(
|
||||
"№{} РЛС: {}, излучение {}, {}", index + 1, radar_role_name(role),
|
||||
if emitting { "вкл" } else { "выкл" },
|
||||
if operational { "работает" } else { "нет связи или РЛС не работает" }
|
||||
),
|
||||
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
|
||||
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
|
||||
if mode == SamMode::LauncherOnly {
|
||||
@@ -38,174 +26,15 @@ pub fn status(status: BatteryStatus) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One system's line in the summary panel and on the map.
|
||||
pub fn sam_status(sam: &Sam) -> String {
|
||||
let spec = sam.kind.spec();
|
||||
let mut text = spec.name.to_string();
|
||||
if !sam.alive() {
|
||||
return text + " УНИЧТОЖЕН";
|
||||
}
|
||||
if sam.moving() {
|
||||
return text + " " + &sam.state.name().to_lowercase();
|
||||
}
|
||||
match sam.kind {
|
||||
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", sam.cargo, sam.ground_stock, sam.air_48n6_stock),
|
||||
SamKind::Tzm => return format!(
|
||||
"{text}: на борту {}/2, RM48U {}, снятых ПВО {}{}",
|
||||
sam.cargo,
|
||||
sam.ground_stock,
|
||||
sam.air_48n6_stock,
|
||||
if sam.return_cargo { ", везёт RM48U на склад" } else if sam.job().is_some() { ", в пути" } else { "" }
|
||||
),
|
||||
SamKind::Ew => {
|
||||
let state = if sam.ew_on { "ГЛУШИТ" } else if sam.ew_lock { "остывает" } else { "готова" };
|
||||
return format!("{text}: {state}, нагрев {:.0}%", sam.heat * 100.0);
|
||||
}
|
||||
SamKind::Radar => {
|
||||
let broken = if sam.comps.whole() { String::new() } else { format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)) };
|
||||
let profile = sam.radar_profile();
|
||||
let channels = if profile.channels == 0 {
|
||||
"без уточнения".to_string()
|
||||
} else {
|
||||
format!("каналы {}/{}", sam.own_channels_used(), profile.channels)
|
||||
};
|
||||
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
|
||||
}
|
||||
SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }),
|
||||
SamKind::Optical => {
|
||||
let mut t = format!("{text}: {}", sam.optical.status_text());
|
||||
if sam.health < 1.0 {
|
||||
t += &format!(" ({:.0}%)", sam.health * 100.0);
|
||||
}
|
||||
if !sam.comps.whole() {
|
||||
t += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(cell) = sam.preparing_cell() {
|
||||
text += &format!(" · открытие ТПК №{}", cell + 1);
|
||||
}
|
||||
if sam.empty && sam.missiles == 0 {
|
||||
text += " ЖДЁТ БК";
|
||||
}
|
||||
if sam.health < 1.0 {
|
||||
text += &format!(" ({:.0}%)", sam.health * 100.0);
|
||||
}
|
||||
if !sam.comps.whole() {
|
||||
text += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
|
||||
}
|
||||
if sam.reloading > 0 {
|
||||
text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20));
|
||||
} else {
|
||||
if let Some(magazine) = sam.kind.missile_magazine() {
|
||||
if sam.kind == SamKind::S400 {
|
||||
text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells());
|
||||
if sam.ground_return { text += " · ожидает вывоза RM48U"; }
|
||||
} else {
|
||||
text += &format!(" ракеты {}/{}", sam.missiles, magazine);
|
||||
}
|
||||
}
|
||||
if sam.kind.has_gun() {
|
||||
text += &format!(" очереди {}", sam.bursts);
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::battery::RadarRole;
|
||||
use crate::sim::{Part, Sam, SamKind, SamState};
|
||||
use glam::DVec3;
|
||||
|
||||
#[test]
|
||||
fn renders_system_status_in_existing_format() {
|
||||
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
|
||||
s400.missiles = 1;
|
||||
s400.ground_rounds = 2;
|
||||
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
|
||||
s400.ground_return = true;
|
||||
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
|
||||
|
||||
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
|
||||
pantsir.missiles = 7;
|
||||
pantsir.bursts = 100;
|
||||
assert_eq!(sam_status(&pantsir), "Панцирь-С1 ракеты 7/12 очереди 100");
|
||||
|
||||
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||||
worn.health = 0.5;
|
||||
worn.comps.0[Part::Sensor as usize] = 0.4;
|
||||
worn.reloading = 21;
|
||||
assert_eq!(sam_status(&worn), "Patriot (50%) [РЛС 40%] перезарядка 2с");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_special_system_lines_in_existing_format() {
|
||||
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
|
||||
radar.own.push(7);
|
||||
radar.comps.0[Part::Sensor as usize] = 0.0;
|
||||
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
|
||||
|
||||
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
|
||||
depot.cargo = 2;
|
||||
depot.ground_stock = 3;
|
||||
depot.air_48n6_stock = 1;
|
||||
assert_eq!(sam_status(&depot), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
|
||||
|
||||
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
|
||||
tzm.cargo = 1;
|
||||
tzm.return_cargo = true;
|
||||
assert_eq!(sam_status(&tzm), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
|
||||
|
||||
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
|
||||
ew.ew_on = true;
|
||||
ew.heat = 0.5;
|
||||
assert_eq!(sam_status(&ew), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
|
||||
|
||||
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
|
||||
light.target = Some(1);
|
||||
assert_eq!(sam_status(&light), "Прожектор: в луче цель");
|
||||
|
||||
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
|
||||
assert_eq!(sam_status(&optical), "Оптический пост: ищет");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_moving_and_destroyed_systems_in_existing_format() {
|
||||
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
|
||||
moving.state = SamState::Moving;
|
||||
assert_eq!(sam_status(&moving), "С-400 на марше");
|
||||
|
||||
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
|
||||
dead.health = 0.0;
|
||||
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_explain_their_different_functions() {
|
||||
for role in [RadarRole::Search, RadarRole::Height, RadarRole::Engagement, RadarRole::Multifunction] {
|
||||
let text = radar_profile_line(role.profile());
|
||||
assert!(text.contains(role.profile().id));
|
||||
assert!(text.contains(&format!("оборот {:.1} с", role.profile().cycle as f64 / 20.0)));
|
||||
}
|
||||
assert!(radar_profile_line(RadarRole::Search.profile()).contains("без каналов"));
|
||||
assert!(radar_profile_line(RadarRole::Engagement.profile()).contains("каналы 2"));
|
||||
assert!(radar_profile_line(RadarRole::Height.profile()).contains("уточнение"));
|
||||
}
|
||||
use crate::sim::SamKind;
|
||||
|
||||
#[test]
|
||||
fn renders_battery_status_in_existing_format() {
|
||||
assert_eq!(
|
||||
status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }),
|
||||
"№1 РЛС: дальнего обзора [radar_search]: обзор, оборот 8.5 с, без каналов уточнения, локальный поиск во всей дальности; развёртывание: крупная стационарная антенна; излучение выкл, нет связи или РЛС не работает"
|
||||
);
|
||||
assert_eq!(
|
||||
status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }),
|
||||
"№2 РЛС: сопровождения [radar_track]: обзор, уточнение, пуск, оборот 3.5 с, каналы 2, локальный поиск 12% дальности; развёртывание: мобильная панель; излучение вкл, работает"
|
||||
);
|
||||
assert_eq!(status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }), "№1 РЛС: обзорная, излучение выкл, нет связи или РЛС не работает");
|
||||
assert_eq!(status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }), "№2 РЛС: сопровождения, излучение вкл, работает");
|
||||
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
|
||||
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
|
||||
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn diagnostics() -> String {
|
||||
render::SmokeReason::Ready => "ready",
|
||||
};
|
||||
[
|
||||
"Возможности движка (API 31; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
|
||||
"Возможности движка (API 30; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
|
||||
line(
|
||||
"Дым",
|
||||
smoke.generation,
|
||||
|
||||
@@ -14,7 +14,7 @@ fn on_off() -> Value {
|
||||
/// `/airdef ...` as `lib.rs` accepts it.
|
||||
pub fn tree() -> Tree {
|
||||
let wave_kinds: Vec<&str> = DroneKind::ALL.iter().map(|k| k.spec().key).chain(["mix"]).collect();
|
||||
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(crate::sim::catalog::VARIANTS.iter().map(|v| v.id)).collect();
|
||||
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]).collect();
|
||||
let armed: Vec<&str> = SamKind::ARMED.iter().map(|k| k.key()).chain(["all"]).collect();
|
||||
let toggle = |word: &str| Node::lit(word).then(Node::arg("on/off", on_off()).runs());
|
||||
Tree::new("airdef").runs().with([
|
||||
@@ -73,7 +73,7 @@ pub fn tree() -> Tree {
|
||||
Node::lit("target").then(Node::lit("here").runs()),
|
||||
Node::lit("give").runs(),
|
||||
Node::lit("battery").runs().then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::choice(["integrated", "launcher"])).runs())),
|
||||
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).runs())),
|
||||
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("роль", Value::choice(["on", "off", "multi", "search", "engagement", "height"])).runs())),
|
||||
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
|
||||
Node::lit("wave").then(
|
||||
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
|
||||
@@ -106,7 +106,6 @@ pub fn tree() -> Tree {
|
||||
Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]),
|
||||
Node::lit("reset").runs(),
|
||||
])),
|
||||
Node::lit("recon").runs(),
|
||||
Node::lit("stats").runs(),
|
||||
])
|
||||
}
|
||||
@@ -163,7 +162,7 @@ mod tests {
|
||||
#[test]
|
||||
fn every_branch_of_the_handler_parses() {
|
||||
for line in [
|
||||
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles",
|
||||
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles",
|
||||
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
|
||||
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
|
||||
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
|
||||
@@ -242,10 +241,10 @@ mod tests {
|
||||
fn completion_offers_the_next_word_only() {
|
||||
let top = complete("", &[]);
|
||||
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] {
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] {
|
||||
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||
}
|
||||
assert_eq!(top.len(), 36);
|
||||
assert_eq!(top.len(), 35);
|
||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
||||
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
||||
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
||||
@@ -259,18 +258,6 @@ mod tests {
|
||||
assert!(complete("wave nothing ", &[]).is_empty());
|
||||
}
|
||||
|
||||
/// A station's profile is fixed at deployment: completion offers only emission, while an
|
||||
/// old role word still reaches the handler's explanation instead of a bare parse error.
|
||||
#[test]
|
||||
fn radar_completion_offers_emission_only() {
|
||||
let words = complete("radar 1 ", &[]);
|
||||
assert_eq!(words.len(), 2, "{words:?}");
|
||||
assert!(words.contains(&"on".to_string()) && words.contains(&"off".to_string()));
|
||||
for old in ["multi", "search", "engagement", "height"] {
|
||||
assert!(tree().parse(&format!("radar 1 {old}")).is_ok(), "`{old}` should reach the handler");
|
||||
}
|
||||
}
|
||||
|
||||
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
|
||||
#[test]
|
||||
fn scenario_names_follow_a_save_and_a_delete() {
|
||||
|
||||
@@ -31,9 +31,6 @@ pub struct SamRec {
|
||||
pub air_48n6_stock: u32,
|
||||
pub mode: sim::battery::SamMode,
|
||||
pub radar_role: sim::battery::RadarRole,
|
||||
/// The stable profile ID when the file names one (new saves); old files
|
||||
/// have only the role key, which migrates to the matching profile.
|
||||
pub radar_profile: Option<sim::battery::RadarProfile>,
|
||||
pub spent_cells: u8,
|
||||
pub radar_on: bool,
|
||||
}
|
||||
@@ -150,20 +147,10 @@ impl Layout {
|
||||
let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true);
|
||||
let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false);
|
||||
let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false);
|
||||
let radar_profile = match l.w.get(32) {
|
||||
None => None,
|
||||
Some(v) => Some(sim::battery::RadarProfile::from_id(v).ok_or_else(|| l.bad("профиль РЛС", "radar_multi, radar_search, radar_track или radar_height"))?),
|
||||
};
|
||||
if (ground_return && (kind != SamKind::S400 || ground_request || ground_rounds == 0)) || (return_cargo && (kind != SamKind::Tzm || ground_stock == 0)) { return Err(l.bad("возврат RM48U", "несовместимое состояние")); }
|
||||
if radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
|
||||
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
|
||||
}
|
||||
if let Some(profile) = radar_profile {
|
||||
if kind != SamKind::Radar { return Err(l.bad("профиль РЛС", "профиль поддерживается только отдельной РЛС")); }
|
||||
if profile.role() != radar_role { return Err(l.bad("профиль РЛС", "профиль и роль не совпадают")); }
|
||||
}
|
||||
// An old line has only the role: it migrates to the matching profile.
|
||||
let radar_profile = radar_profile.or((kind == SamKind::Radar).then(|| sim::battery::RadarProfile::of(radar_role)));
|
||||
if mode == sim::battery::SamMode::LauncherOnly && !matches!(kind, SamKind::S400 | SamKind::S500) {
|
||||
return Err(l.bad("режим", "пусковая поддерживается только С-400 и С-500"));
|
||||
}
|
||||
@@ -173,7 +160,7 @@ impl Layout {
|
||||
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 {
|
||||
return Err(l.bad("боезапас", "больше четырёх ячеек"));
|
||||
}
|
||||
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo });
|
||||
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, spent_cells, ground_request, radar_on, ground_return, return_cargo });
|
||||
}
|
||||
"target" => {
|
||||
if out.targets.len() >= MAX_UNITS {
|
||||
@@ -233,7 +220,6 @@ mod tests {
|
||||
assert_eq!(l.sams[0].mode, sim::battery::SamMode::LauncherOnly);
|
||||
assert_eq!(l.sams[0].spent_cells, 5);
|
||||
assert_eq!(l.sams[1].radar_role, sim::battery::RadarRole::Engagement);
|
||||
assert_eq!(l.sams[1].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT), "an old role-only line migrates");
|
||||
assert!(!Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 false")).unwrap().sams[0].radar_on);
|
||||
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 nope")).is_err());
|
||||
assert!(Layout::parse(&data.replace("engagement", "invalid")).is_err());
|
||||
@@ -244,13 +230,6 @@ mod tests {
|
||||
SamKind::Patriot.key()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_optical_post_loads_by_its_catalog_key() {
|
||||
let l = Layout::parse("sam optical 10 70 20 0.5\n").unwrap();
|
||||
assert_eq!(l.sams[0].kind, SamKind::Optical);
|
||||
assert_eq!(l.sams[0].mode, sim::battery::SamMode::Integrated);
|
||||
}
|
||||
|
||||
// #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line
|
||||
#[test]
|
||||
fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() {
|
||||
@@ -279,27 +258,6 @@ mod tests {
|
||||
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radar_profile_ids_round_trip_and_old_roles_map_to_them() {
|
||||
let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search";
|
||||
let l = Layout::parse(old).unwrap();
|
||||
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Search);
|
||||
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::SEARCH));
|
||||
let new = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement 0 0 true false false radar_track";
|
||||
let l = Layout::parse(new).unwrap();
|
||||
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT));
|
||||
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Engagement);
|
||||
assert_eq!(
|
||||
Layout::parse("sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 0 true false false radar_multi").unwrap().sams[0].radar_profile,
|
||||
Some(sim::battery::RadarProfile::MULTI)
|
||||
);
|
||||
// A profile and the legacy role must agree; a profile on a non-radar is refused.
|
||||
assert!(Layout::parse(&new.replace("engagement 0", "search 0")).is_err());
|
||||
assert!(Layout::parse(&new.replace("sam radar", "sam s400").replace("engagement", "multi")).is_err());
|
||||
assert!(Layout::parse(&new.replace("radar_track", "radar_unknown")).is_err());
|
||||
assert_eq!(sim::battery::RadarProfile::from_id("multi"), Some(sim::battery::RadarProfile::MULTI));
|
||||
}
|
||||
|
||||
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
|
||||
#[test]
|
||||
fn older_valid_saves_still_load() {
|
||||
|
||||
+35
-139
@@ -21,11 +21,9 @@ mod layout;
|
||||
mod map;
|
||||
mod film;
|
||||
mod monitor;
|
||||
mod overlay;
|
||||
mod panel;
|
||||
mod presentation;
|
||||
mod radar;
|
||||
mod recon_view;
|
||||
mod replay;
|
||||
mod scene;
|
||||
mod smoke;
|
||||
@@ -98,10 +96,6 @@ struct AirDef {
|
||||
by_id: Vec<ModelInstanceId>,
|
||||
/// The command map (#48).
|
||||
map: map::MapUi,
|
||||
/// The world overlay's key held (#132): markers over normal gameplay while it is.
|
||||
overlay_held: bool,
|
||||
/// The overlay's shapes are the mod's `set-hud` now: cleared when it lets go.
|
||||
overlay_shown: bool,
|
||||
}
|
||||
|
||||
/// What `/airdef replay export` was asked for.
|
||||
@@ -206,27 +200,33 @@ enum Page {
|
||||
More,
|
||||
/// The last raid's events and its replays.
|
||||
Replays,
|
||||
/// The enemy's recon picture and why it prices each mark: debug and after-action review (#135).
|
||||
Recon,
|
||||
/// The systems with their doctrines, and one system's doctrine (by id) (#47).
|
||||
Fleet,
|
||||
Doctrine(u32),
|
||||
}
|
||||
|
||||
const MENU_KINDS: u32 = 1;
|
||||
const BATTERY_ROWS: u32 = 5;
|
||||
const BTN_BATTERY: u32 = 22;
|
||||
const BATTERY_ROWS: u32 = sim::catalog::VARIANTS.len() as u32;
|
||||
const BATTERY_DEPLOY: [(&str, &str); 5] = [
|
||||
("s400_launcher", "С-400 — отдельная пусковая"),
|
||||
("s500_launcher", "С-500 — отдельная пусковая"),
|
||||
("radar_search", "РЛС обзора"),
|
||||
("radar_track", "РЛС сопровождения"),
|
||||
("radar_height", "Мачтовая РЛС"),
|
||||
];
|
||||
|
||||
/// A battery deploy piece from the catalog: a unit kind or one of its variants.
|
||||
fn deploy_configuration(key: &str) -> Option<(SamKind, sim::battery::SamMode, sim::battery::RadarRole)> {
|
||||
use sim::battery::{RadarRole as R, SamMode as M};
|
||||
match sim::catalog::variant(key) {
|
||||
Some(v) => Some((v.kind, v.mode, v.role)),
|
||||
// A bare kind deploys its ordinary integrated configuration.
|
||||
None => Some((SamKind::from_key(key)?, M::Integrated, R::Multifunction)),
|
||||
}
|
||||
Some(match key {
|
||||
"s400_launcher" => (SamKind::S400, M::LauncherOnly, R::Multifunction),
|
||||
"s500_launcher" => (SamKind::S500, M::LauncherOnly, R::Multifunction),
|
||||
"radar_search" => (SamKind::Radar, M::Integrated, R::Search),
|
||||
"radar_track" => (SamKind::Radar, M::Integrated, R::Engagement),
|
||||
"radar_height" => (SamKind::Radar, M::Integrated, R::Height),
|
||||
_ => (SamKind::from_key(key)?, M::Integrated, R::Multifunction),
|
||||
})
|
||||
}
|
||||
|
||||
const BTN_HOLD: u32 = 10;
|
||||
const BTN_SHADER: u32 = 11;
|
||||
const BTN_DAMAGE: u32 = 12;
|
||||
@@ -243,9 +243,7 @@ const BTN_LAUNCH: u32 = 34;
|
||||
const BTN_NEXT: u32 = 35;
|
||||
const BTN_MORE: u32 = 17;
|
||||
const BTN_REPLAYS: u32 = 18;
|
||||
const BTN_RECON: u32 = 23;
|
||||
const REPLAY_EVENTS: u32 = 3;
|
||||
const RECON_ROWS: u32 = 6;
|
||||
const BTN_MAP: u32 = 40;
|
||||
const BTN_FULL: u32 = 41;
|
||||
const BTN_REEL: u32 = 42;
|
||||
@@ -881,24 +879,7 @@ impl AirDef {
|
||||
}
|
||||
self.hud_shown = true;
|
||||
hud::set_panel(Corner::TopRight, &panel::summary(&self.sim, &pic, player));
|
||||
let truth_label = self.sim.truth && !pic.unaided;
|
||||
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::height(truth_label), &radar::draw(&self.sim, player, yaw));
|
||||
}
|
||||
|
||||
/// Whether the world overlay draws now (#132): its key held over normal gameplay — not under
|
||||
/// a replay, the grid, a monitor or the map, which own the screen themselves.
|
||||
fn overlay_active(&self) -> bool {
|
||||
self.overlay_held
|
||||
&& self.presentation.is_live()
|
||||
&& !self.grid
|
||||
&& self.monitor.is_none_or(|i| i >= self.sim.sams.len())
|
||||
&& !self.map.open
|
||||
}
|
||||
|
||||
fn draw_overlay(&mut self) {
|
||||
let Some(p) = player() else { return };
|
||||
let shapes = overlay::draw(&self.sim, DVec3::new(p.x, p.y, p.z), render::gui_size(), |w| render::project(w.x, w.y, w.z));
|
||||
render::set_hud(&shapes);
|
||||
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::SIZE + 12.0, &radar::draw(&self.sim, player, yaw));
|
||||
}
|
||||
|
||||
// ------------------------------------------------ saving
|
||||
@@ -926,9 +907,8 @@ impl AirDef {
|
||||
// The parts' states (sensor, mount, launcher, gun, tracks, comms) close the line; older saves lack them.
|
||||
let comps = if fresh { new.comps } else { s.comps };
|
||||
let parts = comps.0.iter().map(|v| format!("{v:.3}")).collect::<Vec<_>>().join(" ");
|
||||
let profile = if s.kind == SamKind::Radar { format!(" {}", s.radar_profile().id) } else { String::new() };
|
||||
text += &format!(
|
||||
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}{profile}\n",
|
||||
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}\n",
|
||||
s.kind.key(),
|
||||
s.pos.x,
|
||||
s.pos.y,
|
||||
@@ -1081,9 +1061,7 @@ impl AirDef {
|
||||
sam.air_48n6_stock = r.air_48n6_stock;
|
||||
sam.fit_cells();
|
||||
sam.set_mode(r.mode);
|
||||
// New saves name the stable profile; old ones only the role, which
|
||||
// parses to the same profile (`Layout::parse`).
|
||||
sam.set_radar_role(r.radar_profile.map_or(r.radar_role, |p| p.role()));
|
||||
sam.set_radar_role(r.radar_role);
|
||||
sam.radar_on = r.radar_on;
|
||||
sam.spent_cells = r.spent_cells;
|
||||
sam.sync_tube_cells();
|
||||
@@ -1229,9 +1207,6 @@ impl AirDef {
|
||||
self.map_close();
|
||||
self.grid = false;
|
||||
self.grid_ids.clear();
|
||||
// The overlay key lets go with the world: its camera projects nothing here anyway.
|
||||
self.overlay_held = false;
|
||||
self.overlay_shown = false;
|
||||
// The last world's transient state: its sounds were due on its own
|
||||
// clock, its picked unit may have another meaning in this one, and
|
||||
// its models would stay until the next full model list.
|
||||
@@ -1528,13 +1503,13 @@ impl AirDef {
|
||||
/// monitored one always; those shown keep a head start, so the grid doesn't flicker.
|
||||
fn pick_grid(&mut self) {
|
||||
let shown = &self.grid_ids;
|
||||
// Units that shoot, the radars and the passive optics; depots, trucks and lights have nothing to show.
|
||||
// Units that shoot, and the radars; depots, trucks and lights have nothing to show.
|
||||
let mut scored: Vec<(f64, u32)> = self
|
||||
.sim
|
||||
.sams
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar || s.kind == SamKind::Optical)
|
||||
.filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar)
|
||||
.map(|(i, s)| {
|
||||
let busy = if self.sim.showing_kill(s) { 98.0 } else { match s.state {
|
||||
sim::SamState::Launch | sim::SamState::Fire => 100.0,
|
||||
@@ -1548,11 +1523,7 @@ impl AirDef {
|
||||
sim::SamState::Waiting => 35.0,
|
||||
sim::SamState::Packing | sim::SamState::Moving | sim::SamState::Deploying => 40.0,
|
||||
} };
|
||||
let near = if s.kind == SamKind::Optical {
|
||||
0.0
|
||||
} else {
|
||||
self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0)))
|
||||
};
|
||||
let near = self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0)));
|
||||
let hurt = if s.alive() && s.health < 0.7 { 15.0 } else { 0.0 };
|
||||
let keep = if shown.contains(&s.id) { 12.0 } else { 0.0 };
|
||||
let pinned = if self.monitor == Some(i) { 1000.0 } else { 0.0 };
|
||||
@@ -1588,8 +1559,7 @@ impl AirDef {
|
||||
self.sim.sams.push(sam);
|
||||
self.sim.settle(id);
|
||||
self.dirty = true;
|
||||
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
|
||||
Ok(format!("{} развёрнут ({}, {}{profile})", kind.name(), mode.key(), role.key()))
|
||||
Ok(format!("{} развёрнут ({}, {})", kind.name(), mode.key(), role.key()))
|
||||
}
|
||||
|
||||
fn open_menu(&mut self, page: Page) {
|
||||
@@ -1616,16 +1586,11 @@ impl AirDef {
|
||||
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_RECON, label: "Разведка противника (разбор)…".into() }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() }));
|
||||
}
|
||||
Page::BatteryDeploy => {
|
||||
title = "Размещение батареи — клик создаёт технику перед игроком".into();
|
||||
widgets.push(Widget::List(ListWidget {
|
||||
id: BATTERY_ROWS,
|
||||
rows: sim::catalog::VARIANTS.iter().map(|v| format!("{} — {}", v.label, v.description)).collect(),
|
||||
selected: None,
|
||||
}));
|
||||
widgets.push(Widget::List(ListWidget { id: BATTERY_ROWS, rows: BATTERY_DEPLOY.iter().map(|(_, name)| (*name).to_string()).collect(), selected: None }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
||||
}
|
||||
Page::Replays => {
|
||||
@@ -1638,7 +1603,6 @@ impl AirDef {
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_FULL, label: "Полный повтор".into() }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
||||
}
|
||||
None => {
|
||||
title = "Повторы".into();
|
||||
@@ -1647,17 +1611,10 @@ impl AirDef {
|
||||
text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(),
|
||||
color: 0,
|
||||
}));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Page::Recon => {
|
||||
title = "Разведка противника — разбор (debug): что враг запомнил и почему".into();
|
||||
let rows: Vec<String> = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect();
|
||||
widgets.push(Widget::List(ListWidget { id: RECON_ROWS, rows, selected: None }));
|
||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
||||
}
|
||||
Page::More => {
|
||||
title = "AirDef — управление".to_string();
|
||||
widgets.push(Widget::Button(ButtonWidget {
|
||||
@@ -1896,12 +1853,8 @@ impl Mod for AirDef {
|
||||
model_generation: u32::MAX,
|
||||
by_id: Vec::new(),
|
||||
map: map::MapUi::default(),
|
||||
overlay_held: false,
|
||||
overlay_shown: false,
|
||||
};
|
||||
let _ = input::register_key("map", "Карта: командная, расстановка", "key.keyboard.m");
|
||||
// C is free in vanilla's bindings and the mod's own; the player may rebind it.
|
||||
let _ = input::register_key("overlay", "Обзор: метки целей вокруг видимых дронов и ракет (удерживать)", "key.keyboard.c");
|
||||
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");
|
||||
@@ -1938,9 +1891,6 @@ impl Mod for AirDef {
|
||||
for event in input::poll() {
|
||||
match event {
|
||||
Event::UseStart(u) => self.use_item(&u.item.id),
|
||||
// The overlay is a hold, not a toggle (#132): down draws, up clears.
|
||||
Event::KeyDown(k) if k == "overlay" => self.overlay_held = true,
|
||||
Event::KeyUp(k) if k == "overlay" => self.overlay_held = false,
|
||||
Event::KeyDown(k) if k == "map" => self.map_toggle(),
|
||||
Event::KeyDown(k) if k == "menu" => {
|
||||
if self.presentation.playback().is_some() {
|
||||
@@ -2137,15 +2087,6 @@ impl Mod for AirDef {
|
||||
render::set_views(&[]);
|
||||
self.monitor_shown = false;
|
||||
}
|
||||
// The world overlay owns the HUD while its key is held over normal gameplay;
|
||||
// the frame hook redraws it every frame, the tick keeps the ownership honest.
|
||||
if self.overlay_active() {
|
||||
self.draw_overlay();
|
||||
self.overlay_shown = true;
|
||||
} else if self.overlay_shown {
|
||||
render::set_hud(&[]);
|
||||
self.overlay_shown = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2175,8 +2116,8 @@ impl Mod for AirDef {
|
||||
return;
|
||||
}
|
||||
(Page::BatteryDeploy, BATTERY_ROWS) => {
|
||||
if let Some(v) = sim::catalog::VARIANTS.get(row as usize) {
|
||||
match self.deploy_configured(v.id) {
|
||||
if let Some((key, _)) = BATTERY_DEPLOY.get(row as usize) {
|
||||
match self.deploy_configured(key) {
|
||||
Ok(message) => say(&message),
|
||||
Err(error) => say(&error),
|
||||
}
|
||||
@@ -2321,16 +2262,6 @@ impl Mod for AirDef {
|
||||
self.open_menu(Page::Main);
|
||||
return;
|
||||
}
|
||||
(Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => {
|
||||
self.open_menu(Page::Recon);
|
||||
return;
|
||||
}
|
||||
(Page::Recon, BTN_BACK) => {
|
||||
self.open_menu(Page::Main);
|
||||
return;
|
||||
}
|
||||
// The review is read-only: a row click changes nothing.
|
||||
(Page::Recon, RECON_ROWS) => return,
|
||||
(Page::Main, BTN_MORE) => {
|
||||
self.open_menu(Page::More);
|
||||
return;
|
||||
@@ -2389,12 +2320,6 @@ impl Mod for AirDef {
|
||||
/// export still active there is ended, so its capture cannot go on recording the title.
|
||||
fn frame(&mut self, _seconds: f32) {
|
||||
if self.presentation.is_live() {
|
||||
// The overlay tracks the drawn camera frame by frame (`render.project` is at most a
|
||||
// frame behind); the other screens own the HUD at the tick's pace, as before.
|
||||
if self.overlay_active() {
|
||||
self.draw_overlay();
|
||||
self.overlay_shown = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(cleanup) = self.presentation.world_left(world_identity().as_deref()) {
|
||||
@@ -2427,7 +2352,7 @@ impl Mod for AirDef {
|
||||
["battery"] => {
|
||||
let status = self.sim.battery_status();
|
||||
for entry in status { say(&battery_view::status(entry)); }
|
||||
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off; профиль задаётся deploy radar_search|radar_track|radar_height".into())
|
||||
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off|multi|search|engagement|height".into())
|
||||
}
|
||||
["battery", n, mode] => {
|
||||
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер комплекса")?;
|
||||
@@ -2445,12 +2370,13 @@ impl Mod for AirDef {
|
||||
self.dirty = true;
|
||||
Some(format!("№{} {}: излучение РЛС {}", i + 1, sam.kind.name(), state))
|
||||
}
|
||||
["radar", _n, role] => {
|
||||
["radar", n, role] => {
|
||||
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер РЛС")?;
|
||||
let role = sim::battery::RadarRole::from_key(role).ok_or("Роль: multi, search, engagement или height")?;
|
||||
return Err(format!(
|
||||
"Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в {} не меняет оборудование. Доступно on/off.",
|
||||
role.key()
|
||||
));
|
||||
let sam = self.sim.sams.get_mut(i).ok_or("Нет такого комплекса")?;
|
||||
if !sam.set_radar_role(role) { return Err("Нужна отдельная РЛС".into()); }
|
||||
self.dirty = true;
|
||||
Some(format!("№{} РЛС: роль {}", i + 1, role.key()))
|
||||
}
|
||||
["wave", kind, rest @ ..] => {
|
||||
let count = rest.first().and_then(|v| v.parse().ok()).unwrap_or(5u32).clamp(1, 80);
|
||||
@@ -2662,14 +2588,6 @@ impl Mod for AirDef {
|
||||
self.set_effects(*v != "off", *v == "hd");
|
||||
Some(format!("Эффекты: {}", match *v { "off" => "выкл", "hd" => "HD", _ => "обычные" }))
|
||||
}
|
||||
["recon"] => {
|
||||
// The enemy's partial picture and why it prices each mark: explicit debug, never the
|
||||
// normal HUD (#135). The same lines fill the after-action review page.
|
||||
for l in recon_view::picture_lines(&self.sim.enemy_picture()) {
|
||||
say(&l);
|
||||
}
|
||||
None
|
||||
}
|
||||
["stats"] => Some(format!(
|
||||
"В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}",
|
||||
self.sim.drones.iter().filter(|d| d.alive()).count(),
|
||||
@@ -2703,9 +2621,8 @@ mod tests {
|
||||
assert_eq!(sim::catalog::UNITS[3].kind, SamKind::S400);
|
||||
assert_eq!(sim::catalog::UNITS[4].kind, SamKind::S500);
|
||||
assert_eq!(sim::catalog::UNITS[10].kind, SamKind::Radar);
|
||||
for v in sim::catalog::VARIANTS {
|
||||
let (actual, mode, role) = deploy_configuration(v.id).unwrap();
|
||||
assert_eq!((actual, mode, role), (v.kind, v.mode, v.role));
|
||||
for (key, _) in BATTERY_DEPLOY {
|
||||
assert!(deploy_configuration(key).is_some());
|
||||
}
|
||||
for kind in SamKind::ALL {
|
||||
let (actual, mode, role) = deploy_configuration(kind.key()).unwrap();
|
||||
@@ -2717,25 +2634,6 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn radar_profile_survives_a_state_round_trip() {
|
||||
let mut game = test_mod();
|
||||
for role in [sim::battery::RadarRole::Search, sim::battery::RadarRole::Height, sim::battery::RadarRole::Engagement] {
|
||||
let id = game.sim.id();
|
||||
let mut radar = Sam::new(id, SamKind::Radar, DVec3::new(role as i32 as f64 * 10.0, 70.0, 0.0), 0.0);
|
||||
radar.set_radar_role(role);
|
||||
game.sim.sams.push(radar);
|
||||
}
|
||||
let saved = game.state_text(false, false);
|
||||
assert!(saved.contains("radar_search") && saved.contains("radar_height") && saved.contains("radar_track"));
|
||||
let mut restored = test_mod();
|
||||
restored.apply_state(&saved).unwrap();
|
||||
assert_eq!(
|
||||
restored.sim.sams.iter().map(|s| s.radar_profile().id).collect::<Vec<_>>(),
|
||||
vec!["radar_search", "radar_height", "radar_track"]
|
||||
);
|
||||
}
|
||||
|
||||
fn test_mod() -> AirDef {
|
||||
AirDef {
|
||||
sim: Sim::new(1),
|
||||
@@ -2770,8 +2668,6 @@ mod tests {
|
||||
model_generation: u32::MAX,
|
||||
by_id: Vec::new(),
|
||||
map: map::MapUi::default(),
|
||||
overlay_held: false,
|
||||
overlay_shown: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+81
-591
@@ -7,7 +7,7 @@
|
||||
//! 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, Drone, LowSensor, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
|
||||
use crate::sim::{self, Class, LowSensor, 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};
|
||||
@@ -27,23 +27,15 @@ const F_TINT: usize = 8;
|
||||
|
||||
/// Classes of systems for the filter: missile systems, guns, radars, the rear.
|
||||
const SYS_CLASSES: [&str; 4] = ["ЗРК", "ЗАК", "РЛС", "тыл"];
|
||||
/// Classes of the network's targets: the class the tracks were *estimated* (#133), not what the
|
||||
/// targets are; the unidentified are always shown — they cannot be filtered by a class they don't have yet.
|
||||
/// Classes of the network's targets, by the speed of the track (the network doesn't know what a target is).
|
||||
const TGT_CLASSES: [&str; 5] = ["Д", "Г", "К", "С", "Б"];
|
||||
|
||||
/// Whether the track passes the class filter: its estimated class is switched on, or it has none yet.
|
||||
fn tclass_shown(t: &Track, on: &[bool; 5]) -> bool {
|
||||
t.class.class().is_none_or(|c| on[c as usize])
|
||||
}
|
||||
/// Speed (blocks a tick) below which a track is of the class: drones, jets, cruise, supersonic, the rest ballistic.
|
||||
const TGT_SPEED: [f64; 4] = [0.8, 1.8, 3.0, 6.5];
|
||||
|
||||
/// A label line's height, pixels the markers merge within, how far from the pointer labels are kept at
|
||||
/// a low zoom, and the most labels at once.
|
||||
const LH: f32 = 9.0;
|
||||
const CLUSTER_R: f32 = 9.0;
|
||||
/// Tracks merge within this many pixels: their markers are bigger than the systems' (#132).
|
||||
const TRACK_CLUSTER_R: f32 = 11.0;
|
||||
/// A track marker's half-size, and the room its label keeps clear of it.
|
||||
const TRACK_R: f32 = 6.0;
|
||||
const MAX_LABELS: usize = 70;
|
||||
/// Ticks a radar's computed coverage edge lives, and how many are recomputed in a redraw.
|
||||
const RIM_REFRESH: u64 = 100;
|
||||
@@ -129,15 +121,6 @@ enum Act {
|
||||
SaveScn,
|
||||
LoadScn(usize),
|
||||
ScnPage(i32),
|
||||
/// Switches the map between the network's data and the sandbox's truth (#132).
|
||||
Truth,
|
||||
}
|
||||
|
||||
/// What the pointer hovers: a network track, or a true drone in the truth mode.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Hover {
|
||||
Track(u32),
|
||||
Drone(u32),
|
||||
}
|
||||
|
||||
/// A system in the draft layout: an existing one (by id) or one to be built.
|
||||
@@ -239,11 +222,7 @@ pub struct MapUi {
|
||||
blocked: Vec<[f32; 4]>,
|
||||
widths: HashMap<String, f32>,
|
||||
trails: HashMap<u32, Vec<(f32, f32)>>,
|
||||
/// The true places sampled while the sandbox's truth mode is on (#132), apart from the network's.
|
||||
truth_trails: HashMap<u32, Vec<(f32, f32)>>,
|
||||
seen: HashMap<u32, u64>,
|
||||
/// When a true drone was last seen, kept apart from the network's `seen` (#132).
|
||||
truth_seen: HashMap<u32, u64>,
|
||||
sampled: u64,
|
||||
draft: Draft,
|
||||
history: Vec<Draft>,
|
||||
@@ -294,9 +273,7 @@ impl Default for MapUi {
|
||||
blocked: Vec::new(),
|
||||
widths: HashMap::new(),
|
||||
trails: HashMap::new(),
|
||||
truth_trails: HashMap::new(),
|
||||
seen: HashMap::new(),
|
||||
truth_seen: HashMap::new(),
|
||||
sampled: 0,
|
||||
draft: Draft::default(),
|
||||
history: Vec::new(),
|
||||
@@ -373,9 +350,7 @@ impl MapUi {
|
||||
pub fn sample(&mut self, sim: &Sim) {
|
||||
if sim.tick < self.sampled {
|
||||
self.trails.clear();
|
||||
self.truth_trails.clear();
|
||||
self.seen.clear();
|
||||
self.truth_seen.clear();
|
||||
}
|
||||
if sim.tick < self.sampled + SAMPLE {
|
||||
return;
|
||||
@@ -396,27 +371,10 @@ impl MapUi {
|
||||
}
|
||||
self.seen.insert(id, sim.tick);
|
||||
}
|
||||
// The truth mode keeps its own trail of the real places, never mixed into the network's (#132).
|
||||
if sim.truth {
|
||||
for d in sim.drones.iter().filter(|d| d.alive()) {
|
||||
let trail = self.truth_trails.entry(d.id).or_default();
|
||||
let p = (d.pos.x as f32, d.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.truth_seen.insert(d.id, sim.tick);
|
||||
}
|
||||
}
|
||||
let now = sim.tick;
|
||||
self.seen.retain(|_, t| now.saturating_sub(*t) < 1200);
|
||||
self.truth_seen.retain(|_, t| now.saturating_sub(*t) < 1200);
|
||||
let seen = &self.seen;
|
||||
self.trails.retain(|id, _| seen.contains_key(id));
|
||||
let truth_seen = &self.truth_seen;
|
||||
self.truth_trails.retain(|id, _| truth_seen.contains_key(id));
|
||||
}
|
||||
|
||||
fn enter_editor(&mut self) {
|
||||
@@ -465,7 +423,7 @@ impl MapUi {
|
||||
fn sys_class(k: SamKind) -> usize {
|
||||
if k.armed() {
|
||||
if k == SamKind::Gepard { 1 } else { 0 }
|
||||
} else if k == SamKind::Optical || k.spec().sensor > 0.0 {
|
||||
} else if k.spec().sensor > 0.0 {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
@@ -480,7 +438,6 @@ fn short_name(k: SamKind) -> &'static str {
|
||||
SamKind::Tzm => "ТЗМ",
|
||||
SamKind::Ew => "РЭБ",
|
||||
SamKind::Light => "Прож.",
|
||||
SamKind::Optical => "Опт.",
|
||||
SamKind::Pantsir => "Панцирь",
|
||||
SamKind::IrisT => "IRIS-T",
|
||||
SamKind::S400 => "С-400",
|
||||
@@ -492,8 +449,14 @@ fn short_name(k: SamKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The class of a track by its speed.
|
||||
fn tgt_class(t: &Track) -> usize {
|
||||
let v = t.vel.length();
|
||||
TGT_SPEED.iter().position(|&m| v < m).unwrap_or(TGT_SPEED.len())
|
||||
}
|
||||
|
||||
/// Markers within `r` pixels of the first of a group go with it: the groups, as indices into `pos`.
|
||||
pub(crate) fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
|
||||
fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
|
||||
let r2 = r * r;
|
||||
let mut g: Vec<Vec<usize>> = Vec::new();
|
||||
'next: for (i, p) in pos.iter().enumerate() {
|
||||
@@ -604,279 +567,6 @@ fn class_name(c: sim::sites::SiteClass) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pointer is over, in the view: a network track, or a true drone while the sandbox's truth mode is on.
|
||||
/// The network's tracks come from `Sim::picture` only; a drone the network has not measured is not hoverable
|
||||
/// outside the truth mode (#132). Panels and cards take the pointer first.
|
||||
fn hover_at(sim: &Sim, ui: &MapUi) -> Option<Hover> {
|
||||
let p = ui.cursor;
|
||||
if ui.blocked.iter().any(|r| p.0 >= r[0] && p.1 >= r[1] && p.0 <= r[0] + r[2] && p.1 <= r[1] + r[3]) {
|
||||
return None;
|
||||
}
|
||||
let near = PICK_R + 2.0;
|
||||
let mut best: Option<(f32, Hover)> = None;
|
||||
if ui.filters[F_TRACKS] {
|
||||
let now = sim.tick;
|
||||
for (id, t) in sim.picture() {
|
||||
if !tclass_shown(&t, &ui.tclass) {
|
||||
continue;
|
||||
}
|
||||
let e = t.est(now);
|
||||
let c = ui.to_screen(e.x, e.z);
|
||||
if !ui.on_screen(c, 6.0) {
|
||||
continue;
|
||||
}
|
||||
let d = (c.0 - p.0).hypot(c.1 - p.1);
|
||||
if d <= near && best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, Hover::Track(id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The true place wins over its own track: the mode is explicit and the card says so.
|
||||
if sim.truth {
|
||||
for d in sim.drones.iter().filter(|d| d.alive()) {
|
||||
let c = ui.to_screen(d.pos.x, d.pos.z);
|
||||
if !ui.on_screen(c, 6.0) {
|
||||
continue;
|
||||
}
|
||||
let dist = (c.0 - p.0).hypot(c.1 - p.1);
|
||||
if dist <= near && best.is_none_or(|b| dist <= b.0 + 0.5) {
|
||||
best = Some((dist, Hover::Drone(d.id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|b| b.1)
|
||||
}
|
||||
|
||||
/// The network's knowledge of one track: type, status, source, distance, speed, whatever holds or intercepts it.
|
||||
/// The target and the route are never known to the network unless the sandbox's truth mode adds them (#132).
|
||||
fn track_lines(sim: &Sim, t: &Track, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
|
||||
let now = sim.tick;
|
||||
let age = t.age(now);
|
||||
let forecast = t.forecast(now);
|
||||
lines.push((format!("Трек №{} · {}", t.id, t.class.name()), RED));
|
||||
lines.push((
|
||||
format!("Статус: {}{}", t.ident().name(), if forecast { format!(" · прогноз {} с", age / 20) } else { format!(" · измерение {} с назад", age / 20) }),
|
||||
if forecast { YELLOW } else { GREEN },
|
||||
));
|
||||
let source = sim.sams.iter().enumerate().find(|(_, s)| s.id == t.source).map_or(
|
||||
if t.source == 0 { "неизвестен".to_string() } else { format!("№? ({})", t.source) },
|
||||
|(n, s)| format!("№{} {} ({})", n + 1, s.kind.name(), s.radar_profile().id),
|
||||
);
|
||||
lines.push((format!("Источник: {} · измерил {}", if t.own_within(now, t.ttl as u64) { "своя РЛС" } else { "сеть (чужое измерение)" }, source), WHITE));
|
||||
lines.push((format!("Продукт: {} · качество {}%", t.product.name(), t.quality), WHITE));
|
||||
let authority = if t.own_authorizes(now) {
|
||||
"у измерившей станции пригодно для пуска".to_string()
|
||||
} else if t.own_tick > 0 {
|
||||
format!("измерение станции {} с назад, для пуска не пригодно", now.saturating_sub(t.own_tick) / 20)
|
||||
} else {
|
||||
"передано сетью: собственного измерения нет, нужен огневой трек станции".to_string()
|
||||
};
|
||||
lines.push((format!("Пуск: {authority}"), if t.own_authorizes(now) { GREEN } else { YELLOW }));
|
||||
if t.locked {
|
||||
lines.push(("Огневой захват: да".into(), YELLOW));
|
||||
}
|
||||
let e = t.est(now);
|
||||
if let Some(p) = player {
|
||||
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(e.distance(p)), e.y), WHITE));
|
||||
}
|
||||
lines.push((
|
||||
format!("Скорость: {:.0} км/ч · погрешность места {}", t.vel.length() * 20.0 * 3.6, distance(t.uncertainty(now))),
|
||||
WHITE,
|
||||
));
|
||||
let missiles = sim.missiles.iter().filter(|m| m.target() == t.id).count();
|
||||
lines.push((
|
||||
if missiles > 0 { format!("Перехват: {missiles} ракет в полёте") } else { "Перехват: ракет нет".into() },
|
||||
if missiles > 0 { GREEN } else { GREY },
|
||||
));
|
||||
let who = who_tracks(sim, t);
|
||||
if !who.is_empty() {
|
||||
lines.push((format!("Держат: {who}"), WHITE));
|
||||
}
|
||||
}
|
||||
|
||||
/// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's).
|
||||
fn who_tracks(sim: &Sim, t: &Track) -> String {
|
||||
let n = sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count();
|
||||
if n == 0 { String::new() } else { format!("{n} комплексов") }
|
||||
}
|
||||
|
||||
/// What a true drone is aimed at, in the sandbox's words: a unit, a marked object, or a bare point (#132).
|
||||
fn aim_text(sim: &Sim, d: &Drone) -> String {
|
||||
let unit = d.aim_unit();
|
||||
if unit != 0 {
|
||||
return match sim.sams.iter().position(|s| s.id == unit) {
|
||||
Some(i) => format!("{} №{}", sim.sams[i].kind.name(), i + 1),
|
||||
None => format!("комплекс №{unit}"),
|
||||
};
|
||||
}
|
||||
let aim = d.aim_pos();
|
||||
match sim.targets.iter().position(|p| p.distance(aim) < 8.0) {
|
||||
Some(i) => format!("объект №{}", i + 1),
|
||||
None => format!("точка {:.0} {:.0}", aim.x, aim.z),
|
||||
}
|
||||
}
|
||||
|
||||
/// The truth's lines for one drone: what it is, whether the network holds it, where it goes, what it is sent at,
|
||||
/// and who is shooting at it. Only the sandbox's truth mode asks for these (#132).
|
||||
fn truth_lines(sim: &Sim, d: &Drone, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
|
||||
let tracked = sim.picture().contains_key(&d.id);
|
||||
lines.push((format!("ИСТИНА · {} ({}) №{}", d.kind.spec().name, d.kind.spec().class.name(), d.id), YELLOW));
|
||||
lines.push((
|
||||
format!("Статус: {}{}", if d.jammed { "в воздухе, навигация подавлена" } else { "в воздухе" }, if tracked { ", в картине сети" } else { ", вне картины сети" }),
|
||||
if tracked { WHITE } else { ORANGE },
|
||||
));
|
||||
if d.kind.spec().decoy {
|
||||
lines.push(("Ложная цель: без боевой части".into(), GREY));
|
||||
}
|
||||
if let Some(p) = player {
|
||||
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(d.pos.distance(p)), d.pos.y), WHITE));
|
||||
}
|
||||
lines.push((format!("Скорость: {:.0} км/ч", d.vel.length() * 20.0 * 3.6), WHITE));
|
||||
lines.push((format!("Цель: {}", aim_text(sim, d)), YELLOW));
|
||||
let route = d.route();
|
||||
if route.is_empty() {
|
||||
lines.push(("Маршрут: прямо на цель".into(), YELLOW));
|
||||
} else {
|
||||
lines.push((format!("Маршрут: {} точек, следующая через {}", route.len(), distance(d.pos.distance(route[0]))), YELLOW));
|
||||
}
|
||||
let aim = d.aim_pos();
|
||||
let speed = d.vel.length().max(0.001);
|
||||
lines.push((format!("До цели: {} (~{:.0} с)", distance(d.pos.distance(aim)), d.pos.distance(aim) / speed / 20.0), WHITE));
|
||||
let missiles = sim.missiles.iter().filter(|m| m.target() == d.id).count();
|
||||
lines.push((
|
||||
if missiles > 0 || d.engaged > 0 {
|
||||
format!("Перехват: {missiles} ракет в полёте, наведено {}", d.engaged)
|
||||
} else {
|
||||
"Перехват: никто не ведёт".into()
|
||||
},
|
||||
if missiles > 0 || d.engaged > 0 { GREEN } else { GREY },
|
||||
));
|
||||
}
|
||||
|
||||
/// The truth layer: the real drones as white frames, their sampled path, the route and aim ahead in yellow, marked
|
||||
/// apart from the network's red tracks. Drawn only while the sandbox's truth mode is on (#132).
|
||||
fn map_truth(sim: &Sim, ui: &mut MapUi, hover: Option<Hover>, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
|
||||
for d in sim.drones.iter().filter(|d| d.alive()) {
|
||||
let c = ui.to_screen(d.pos.x, d.pos.z);
|
||||
if ui.filters[F_TRAILS]
|
||||
&& let Some(trail) = ui.truth_trails.get(&d.id)
|
||||
{
|
||||
let mut prev: Option<(f32, f32)> = None;
|
||||
for p in trail {
|
||||
let q = 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(q, 0.0))
|
||||
{
|
||||
s.push(line(a, q, 1.4, alpha(WHITE, 0.45)));
|
||||
}
|
||||
prev = Some(q);
|
||||
}
|
||||
}
|
||||
if !ui.on_screen(c, 20.0) {
|
||||
continue;
|
||||
}
|
||||
// The way ahead: the route's points, then the aim. Dashes, because a plan is not a measurement.
|
||||
let aim = ui.to_screen(d.aim_pos().x, d.aim_pos().z);
|
||||
let mut prev = c;
|
||||
for p in d.route().iter().map(|p| ui.to_screen(p.x, p.z)).chain(std::iter::once(aim)) {
|
||||
if ui.on_screen(prev, 0.0) || ui.on_screen(p, 0.0) {
|
||||
route_dashed(s, prev, p, alpha(0xFFE070, 0.55));
|
||||
}
|
||||
prev = p;
|
||||
}
|
||||
// The drone: a white frame, never the network's red diamond. A recon aircraft has a
|
||||
// sign of its own: an amber diamond, not the strike's frame (#135).
|
||||
let recon = sim.is_recon_drone(d.id);
|
||||
if recon {
|
||||
let p = [(c.0, c.1 - 5.0), (c.0 + 5.0, c.1), (c.0, c.1 + 5.0), (c.0 - 5.0, c.1)];
|
||||
for i in 0..4 {
|
||||
s.push(line(p[i], p[(i + 1) % 4], 1.2, alpha(0xFFC040, 0.95)));
|
||||
}
|
||||
} else {
|
||||
s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95)));
|
||||
}
|
||||
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, if recon { alpha(0xFFC040, 0.95) } else { WHITE }));
|
||||
if ui.on_screen(aim, 6.0) {
|
||||
s.push(diamond(aim.0, aim.1, 4.5, alpha(0xFFE070, 0.85)));
|
||||
s.push(fill(aim.0 - 1.0, aim.1 - 1.0, 2.0, 2.0, alpha(0xFFE070, 0.9)));
|
||||
}
|
||||
taken.push([c.0 - 6.0, c.1 - 6.0, 12.0, 12.0]);
|
||||
let chosen = hover == Some(Hover::Drone(d.id));
|
||||
let name = if recon { format!("разведчик №{}", d.id) } else { format!("{} №{}", d.kind.spec().name, d.id) };
|
||||
add_lab(ui, labs, name, c, 7.0, alpha(YELLOW, 0.95), chosen);
|
||||
if chosen {
|
||||
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The hover card: beside the pointer, over the picture. A network track's card never claims its target or route;
|
||||
/// in the truth mode the true drone's card adds the route, the aim and the interception (#132).
|
||||
fn hover_card(sim: &Sim, ui: &mut MapUi, h: Hover, player: Option<DVec3>, out: &mut Vec<Shape>, taken: &mut Vec<[f32; 4]>) {
|
||||
let mut lines: Vec<(String, u32)> = Vec::new();
|
||||
let border;
|
||||
match h {
|
||||
Hover::Track(id) => {
|
||||
let pic = sim.picture();
|
||||
let Some(t) = pic.get(&id) else { return };
|
||||
border = RED;
|
||||
track_lines(sim, t, player, &mut lines);
|
||||
lines.push(("Цель и маршрут сети неизвестны".into(), GREY));
|
||||
if sim.truth && let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) {
|
||||
lines.push(("Истина (песочница):".into(), YELLOW));
|
||||
lines.push((format!("Тип: {} · {}", d.kind.spec().name, aim_text(sim, d)), YELLOW));
|
||||
}
|
||||
}
|
||||
Hover::Drone(id) => {
|
||||
let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) else { return };
|
||||
border = YELLOW;
|
||||
truth_lines(sim, d, player, &mut lines);
|
||||
lines.push(("Жёлтый пунктир — маршрут и цель; белые рамки — истина.".into(), GREY));
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (w, h) = ui.size;
|
||||
let card_w = 250.0f32.min(w - 16.0);
|
||||
let lines = wrap_lines(ui, lines, card_w);
|
||||
let lh = (11.0 * ui.u).round();
|
||||
let total = lines.len() as f32 * lh + 8.0;
|
||||
let mut x = ui.cursor.0 + 14.0;
|
||||
if x + card_w + 4.0 > w {
|
||||
x = ui.cursor.0 - card_w - 14.0;
|
||||
}
|
||||
let x = x.clamp(4.0, (w - card_w - 4.0).max(4.0));
|
||||
let y = (ui.cursor.1 - 10.0).clamp(4.0, (h - total - 4.0).max(4.0));
|
||||
out.push(fill(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 0xE8101814));
|
||||
out.extend(frame(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 1.0, border));
|
||||
let mut ty = y;
|
||||
for (l, c) in &lines {
|
||||
out.push(text(l.as_str(), x + 2.0, ty, *c));
|
||||
ty += lh;
|
||||
}
|
||||
taken.push([x - 3.0, y - 3.0, card_w + 6.0, total + 6.0]);
|
||||
}
|
||||
|
||||
/// Long lines broken at the card's width.
|
||||
fn wrap_lines(ui: &mut MapUi, lines: Vec<(String, u32)>, width: f32) -> Vec<(String, u32)> {
|
||||
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 ui.tw(&try_) > width - 8.0 && !cur.is_empty() {
|
||||
wrapped.push((std::mem::take(&mut cur), c));
|
||||
cur = word.to_string();
|
||||
} else {
|
||||
cur = try_;
|
||||
}
|
||||
}
|
||||
wrapped.push((cur, c));
|
||||
}
|
||||
wrapped
|
||||
}
|
||||
|
||||
impl AirDef {
|
||||
/// Opens the map (the key, or the menu).
|
||||
pub(crate) fn map_toggle(&mut self) {
|
||||
@@ -1120,7 +810,6 @@ impl AirDef {
|
||||
"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),
|
||||
"key.keyboard.t" => self.map_act(ui, Act::Truth),
|
||||
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() {
|
||||
@@ -1226,8 +915,6 @@ impl AirDef {
|
||||
ui.pick = Pick::None;
|
||||
ui.ed_sel = None;
|
||||
ui.trails.clear();
|
||||
ui.truth_trails.clear();
|
||||
ui.truth_seen.clear();
|
||||
ui.rims.clear();
|
||||
ui.note(tick, m);
|
||||
}
|
||||
@@ -1242,17 +929,6 @@ impl AirDef {
|
||||
}
|
||||
}
|
||||
Act::Filter(i) => ui.filters[i] = !ui.filters[i],
|
||||
Act::Truth => {
|
||||
self.sim.truth = !self.sim.truth;
|
||||
// The two pictures are kept apart: a mode switch starts its trails afresh (#132).
|
||||
ui.truth_trails.clear();
|
||||
ui.truth_seen.clear();
|
||||
ui.note(tick, if self.sim.truth {
|
||||
"Режим ИСТИНА (песочница): настоящие дроны, их цели и маршруты. Треки сети остаются на карте."
|
||||
} else {
|
||||
"Режим данных сети РЛС: только то, что засекли радары."
|
||||
});
|
||||
}
|
||||
Act::Close => {
|
||||
ui.close = true;
|
||||
}
|
||||
@@ -1439,7 +1115,7 @@ impl AirDef {
|
||||
let pic = self.sim.picture();
|
||||
let mut best: Option<(f32, u32)> = None;
|
||||
for (id, t) in &pic {
|
||||
if !tclass_shown(t, &ui.tclass) {
|
||||
if !ui.tclass[tgt_class(t)] {
|
||||
continue;
|
||||
}
|
||||
let e = t.est(now);
|
||||
@@ -1687,16 +1363,9 @@ impl AirDef {
|
||||
// The panels first: the labels keep clear of them. They are drawn last, over the picture.
|
||||
let mut panels: Vec<Shape> = Vec::with_capacity(400);
|
||||
self.map_panels(ui, &mut panels, &draft);
|
||||
// The hover card (#132): beside the pointer, over the picture; the labels keep clear of it too.
|
||||
let hover = if !editing && ui.drag.is_none() { hover_at(&self.sim, ui) } else { None };
|
||||
let mut hover_taken: Vec<[f32; 4]> = Vec::new();
|
||||
if let Some(h) = hover {
|
||||
hover_card(&self.sim, ui, h, crate::player().map(|p| DVec3::new(p.x, p.y, p.z)), &mut panels, &mut hover_taken);
|
||||
}
|
||||
let mut s: Vec<Shape> = Vec::with_capacity(2048);
|
||||
let mut labs: Vec<Lab> = Vec::new();
|
||||
let mut taken: Vec<[f32; 4]> = ui.blocked.clone();
|
||||
taken.extend(hover_taken);
|
||||
// Terrain.
|
||||
if ui.filters[F_TERRAIN] {
|
||||
self.map_terrain(ui, &mut s);
|
||||
@@ -1789,13 +1458,14 @@ impl AirDef {
|
||||
if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] {
|
||||
self.map_tracks(ui, &mut s, &mut labs, &mut taken);
|
||||
}
|
||||
// The optical posts and the contacts they watch (#136): a line to a contact last seen in clear sight.
|
||||
if ui.filters[F_SAMS] || ui.filters[F_TRACKS] {
|
||||
self.map_optical(ui, &mut s, &mut labs);
|
||||
}
|
||||
// The truth, when the sandbox shows it, marked as such: the real drones, their routes and aims.
|
||||
// The truth, when the sandbox shows it, marked as such.
|
||||
if self.sim.truth {
|
||||
map_truth(&self.sim, ui, hover, &mut s, &mut labs, &mut taken);
|
||||
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) {
|
||||
@@ -1917,51 +1587,6 @@ impl AirDef {
|
||||
}
|
||||
}
|
||||
|
||||
/// The optical posts (#136): a short status by each, and a line to the contact it has in clear
|
||||
/// sight (or last saw), never to a radar's measurement. At most a screenful, so a crowd stays cheap.
|
||||
fn map_optical(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>) {
|
||||
let now = self.sim.tick;
|
||||
let picture = self.sim.picture();
|
||||
let mut drawn = 0usize;
|
||||
for (i, sam) in self.sim.sams.iter().enumerate().filter(|(_, sam)| sam.kind == SamKind::Optical && sam.alive()) {
|
||||
if drawn >= 16 {
|
||||
break;
|
||||
}
|
||||
let c = ui.to_screen(sam.pos.x, sam.pos.z);
|
||||
if !ui.on_screen(c, 30.0) {
|
||||
continue;
|
||||
}
|
||||
drawn += 1;
|
||||
let Some(report) = self.sim.optical_report(sam.id) else { continue };
|
||||
let chosen = ui.sel == Some(Sel::Sam(sam.id));
|
||||
let color = match report.state {
|
||||
sim::OpticalState::Observing => GREEN,
|
||||
sim::OpticalState::Holding => CYAN,
|
||||
sim::OpticalState::NoSight => ORANGE,
|
||||
sim::OpticalState::Searching => GREY,
|
||||
};
|
||||
add_lab(ui, labs, format!("Опт. №{}: {}", i + 1, report.status()), c, 7.0, alpha(color, 0.95), chosen);
|
||||
if chosen {
|
||||
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
|
||||
}
|
||||
// The contact it watches: its own last clear sighting, else the network cue's forecast.
|
||||
let own = report.seen.is_some();
|
||||
let point = report
|
||||
.seen
|
||||
.or_else(|| report.target.and_then(|id| picture.get(&id).map(|t| t.est(now))));
|
||||
if let Some(p) = point {
|
||||
let pc = ui.to_screen(p.x, p.z);
|
||||
s.push(line(c, pc, 1.0, alpha(color, if chosen { 0.9 } else if own { 0.55 } else { 0.3 })));
|
||||
let label = match (own, report.observation) {
|
||||
(true, Some(o)) => format!("вероятно {} · {:.0}%", o.class.name(), (1.0 - o.uncertainty) * 100.0),
|
||||
(true, None) => "контакт в поле зрения".into(),
|
||||
(false, _) => "цель по подсказке".into(),
|
||||
};
|
||||
add_lab(ui, labs, label, pc, 5.0, alpha(color, 0.95), chosen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The radars' coverage edges. A radar's edge is where the land first hides a low flyer along each ray round it;
|
||||
/// each is worked out from the sim's own horizon (`low_rim`), a few a redraw, and kept a while. The selected
|
||||
/// one shows its dead zones filled.
|
||||
@@ -2297,21 +1922,21 @@ impl AirDef {
|
||||
fn map_tracks(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
|
||||
let now = self.sim.tick;
|
||||
let pic = self.sim.picture();
|
||||
// Only the classes asked for (the selected one and the unidentified always).
|
||||
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| tclass_shown(t, &ui.tclass) || ui.sel == Some(Sel::Track(**id))).collect();
|
||||
// Only the classes asked for (the selected one always).
|
||||
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| ui.tclass[tgt_class(t)] || ui.sel == Some(Sel::Track(**id))).collect();
|
||||
for (id, t) in &shown {
|
||||
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 { 1.0 } else { 0.7 });
|
||||
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, if chosen { 2.2 } else { 1.6 }, col));
|
||||
s.push(line(a, c, 1.0, col));
|
||||
}
|
||||
prev = Some(c);
|
||||
}
|
||||
@@ -2325,7 +1950,7 @@ impl AirDef {
|
||||
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.4, alpha(0xFFB0B0, 0.45)));
|
||||
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));
|
||||
}
|
||||
@@ -2333,7 +1958,7 @@ impl AirDef {
|
||||
// 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, 1.5, alpha(0xFF8080, 0.85));
|
||||
dashed(s, c, ahead, alpha(0xFF8080, 0.8));
|
||||
}
|
||||
}
|
||||
if !ui.filters[F_TRACKS] {
|
||||
@@ -2349,7 +1974,7 @@ impl AirDef {
|
||||
.collect();
|
||||
let pos: Vec<(f32, f32)> = vis.iter().map(|v| v.2).collect();
|
||||
let solo: Vec<bool> = vis.iter().map(|v| ui.sel == Some(Sel::Track(v.0))).collect();
|
||||
for grp in groups_of(&pos, &solo, TRACK_CLUSTER_R, true) {
|
||||
for grp in groups_of(&pos, &solo, CLUSTER_R * 0.8, true) {
|
||||
if grp.len() > 1 {
|
||||
let members: Vec<(f32, f32)> = grp.iter().map(|&k| vis[k].2).collect();
|
||||
draw_cluster(ui, s, taken, &members, RED);
|
||||
@@ -2359,36 +1984,16 @@ impl AirDef {
|
||||
let chosen = ui.sel == Some(Sel::Track(id));
|
||||
let forecast = t.forecast(now);
|
||||
let age = t.age(now);
|
||||
// A recon aircraft is a role of its own: a yellow hollow diamond and a named label, so
|
||||
// the player tells it from a strike drone the network tracks the same way (#135).
|
||||
let recon = sim::is_drone_id(id);
|
||||
let r = if recon { 5.0 } else { TRACK_R };
|
||||
let col = if recon { YELLOW } else if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
|
||||
s.push(diamond(c.0, c.1, r, col));
|
||||
if recon || !forecast {
|
||||
s.push(diamond(c.0, c.1, if recon { 2.0 } else { 3.0 }, 0xFF200808));
|
||||
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));
|
||||
}
|
||||
// Its measured course, a tick out of the marker.
|
||||
let v = t.vel.normalize_or_zero();
|
||||
if v != DVec3::ZERO {
|
||||
s.push(line(c, (c.0 + v.x as f32 * 10.0, c.1 + v.z as f32 * 10.0), 1.5, col));
|
||||
}
|
||||
taken.push([c.0 - r - 1.0, c.1 - r - 1.0, r * 2.0 + 2.0, r * 2.0 + 2.0]);
|
||||
let age_txt = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) };
|
||||
let txt = if recon {
|
||||
format!("разведчик {age_txt}")
|
||||
} else {
|
||||
let mark = t.class.mark();
|
||||
match (mark.is_empty(), forecast) {
|
||||
(true, true) => format!("~{age_txt}"),
|
||||
(true, false) => age_txt,
|
||||
(false, true) => format!("{mark} ~{age_txt}"),
|
||||
(false, false) => format!("{mark} {age_txt}"),
|
||||
}
|
||||
};
|
||||
add_lab(ui, labs, txt, c, r + 1.0, col, chosen);
|
||||
taken.push([c.0 - 5.0, c.1 - 5.0, 10.0, 10.0]);
|
||||
let txt = format!("{}{}", if forecast { "~" } else { "" }, if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) });
|
||||
add_lab(ui, labs, txt, c, 5.0, col, chosen);
|
||||
if chosen {
|
||||
s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN));
|
||||
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2413,7 +2018,7 @@ impl AirDef {
|
||||
};
|
||||
let tail_w = ui.tw(&tail);
|
||||
let heads: [&str; 2] = if self.sim.truth {
|
||||
["КАРТА · ИСТИНА (песочница): белые рамки — дроны, жёлтое — их цели и маршруты", "КАРТА · ИСТИНА (песочница)"]
|
||||
["КАРТА · ИСТИНА (песочница): красные рамки — настоящие дроны", "КАРТА · ИСТИНА"]
|
||||
} else {
|
||||
["КАРТА · режим: данные сети РЛС", "КАРТА · сеть РЛС"]
|
||||
};
|
||||
@@ -2464,14 +2069,9 @@ impl AirDef {
|
||||
for x in &self.sim.sams {
|
||||
sc[sys_class(x.kind)] += 1;
|
||||
}
|
||||
// By the estimated class; the unidentified are counted apart.
|
||||
let mut tc = [0usize; 5];
|
||||
let mut unknown = 0usize;
|
||||
for t in self.sim.picture().values() {
|
||||
match t.class.class() {
|
||||
Some(c) => tc[c as usize] += 1,
|
||||
None => unknown += 1,
|
||||
}
|
||||
tc[tgt_class(t)] += 1;
|
||||
}
|
||||
inner.push(text("Системы по классу", x0, y, GREY));
|
||||
y += lh;
|
||||
@@ -2486,7 +2086,7 @@ impl AirDef {
|
||||
x += draw_btn(ui, &mut inner, &label, Act::SysClass(i), ui.sclass[i], x, y, bh);
|
||||
}
|
||||
y += bh + 6.0;
|
||||
inner.push(text("Цели сети по классу", x0, y, GREY));
|
||||
inner.push(text("Цели сети по скорости", x0, y, GREY));
|
||||
y += lh;
|
||||
x = x0;
|
||||
for i in 0..TGT_CLASSES.len() {
|
||||
@@ -2498,16 +2098,11 @@ impl AirDef {
|
||||
}
|
||||
x += draw_btn(ui, &mut inner, &label, Act::TgtClass(i), ui.tclass[i], x, y, bh);
|
||||
}
|
||||
// The unidentified: a count, not a filter (they are always shown).
|
||||
inner.push(text(format!("? {unknown} (не опознано)"), x, y + 2.0, GREY));
|
||||
y += bh + 5.0;
|
||||
for l in ["ЗРК ракеты · ЗАК пушки · тыл", "Д дроны · Г реактивные · К крылатые", "С сверхзвук · Б баллистика"] {
|
||||
inner.push(text(l, x0, y, GREY));
|
||||
y += lh - 1.0;
|
||||
}
|
||||
let rn = self.sim.picture().values().filter(|t| sim::is_drone_id(t.id)).count();
|
||||
inner.push(text(format!("жёлтый ромб — разведчик ({rn})"), x0, y, GREY));
|
||||
y += lh - 1.0;
|
||||
}
|
||||
_ => {
|
||||
inner.push(text("Имя сценария", x0, y, GREY));
|
||||
@@ -2556,7 +2151,7 @@ impl AirDef {
|
||||
y += 6.0;
|
||||
// The mode buttons, in rows that wrap.
|
||||
let mut bx = x0 - 2.0;
|
||||
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Истина (T)", Act::Truth, self.sim.truth), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
|
||||
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
|
||||
let bw = ui.tw(label) + 10.0;
|
||||
if bx + bw > lw + 2.0 {
|
||||
bx = x0 - 2.0;
|
||||
@@ -2574,7 +2169,7 @@ impl AirDef {
|
||||
let helps: [&str; 3] = if editing {
|
||||
["ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc", "ЛКМ ставить · ПКМ убрать · Enter · Esc", "Enter · Esc"]
|
||||
} else {
|
||||
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · T: данные · Esc", "ЛКМ выбор · колесо масштаб · T данные · Esc", "Esc"]
|
||||
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · ПКМ: марш · Esc", "ЛКМ выбор · колесо масштаб · Esc", "Esc"]
|
||||
};
|
||||
for help in helps {
|
||||
let hw = ui.tw(help);
|
||||
@@ -2609,7 +2204,21 @@ impl AirDef {
|
||||
self.sel_card(ui, &mut lines, &mut btns);
|
||||
}
|
||||
// Long lines break at the card's width.
|
||||
let lines = wrap_lines(ui, lines, card_w);
|
||||
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 ui.tw(&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 = top;
|
||||
let ch = lines.len() as f32 * lh + 10.0;
|
||||
@@ -2702,14 +2311,7 @@ impl AirDef {
|
||||
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) => {
|
||||
let reach = if k == SamKind::Optical {
|
||||
format!("оптика {}", distance(sim::OPTICAL_RANGE))
|
||||
} else {
|
||||
format!("дальность {}", distance(k.range()))
|
||||
};
|
||||
lines.push((format!("В руке: {}, {reach}", k.name()), YELLOW));
|
||||
}
|
||||
Pick::Sam(k) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)),
|
||||
Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
|
||||
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
|
||||
}
|
||||
@@ -2728,11 +2330,7 @@ impl AirDef {
|
||||
let k = sam.kind;
|
||||
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
|
||||
if k == SamKind::Radar {
|
||||
let profile = sam.radar_profile();
|
||||
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
|
||||
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
|
||||
lines.push((format!("Ограничение: {}", profile.limit), GREY));
|
||||
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY));
|
||||
lines.push((format!("Роль РЛС: {}", crate::battery_view::radar_role_name(sam.radar_role)), WHITE));
|
||||
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
|
||||
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
|
||||
}
|
||||
@@ -2740,19 +2338,7 @@ impl AirDef {
|
||||
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
|
||||
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
|
||||
}
|
||||
lines.push((crate::battery_view::sam_status(sam), WHITE));
|
||||
if k == SamKind::Optical
|
||||
&& let Some(r) = self.sim.optical_report(sam.id)
|
||||
{
|
||||
lines.push((r.line(), WHITE));
|
||||
if let Some(o) = r.observation {
|
||||
lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE));
|
||||
}
|
||||
lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY));
|
||||
if r.target.is_some() {
|
||||
lines.push(("Выбранный контакт показан линией".into(), GREY));
|
||||
}
|
||||
}
|
||||
lines.push((sam.status(), WHITE));
|
||||
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
|
||||
if k == SamKind::Depot {
|
||||
lines.push((format!("Ударные RM48U: {} · снятые 48Н6: {}", sam.ground_stock, sam.air_48n6_stock), WHITE));
|
||||
@@ -2848,17 +2434,24 @@ impl AirDef {
|
||||
lines.push((format!("Трек №{id}: потерян сетью"), GREY));
|
||||
return;
|
||||
};
|
||||
if sim::is_drone_id(id) {
|
||||
lines.push((format!("Разведчик противника №{id}"), YELLOW));
|
||||
lines.push(("Роль: разведка (без оружия) — ищет технику вокруг объектов".into(), YELLOW));
|
||||
}
|
||||
let player = crate::player().map(|p| DVec3::new(p.x, p.y, p.z));
|
||||
track_lines(&self.sim, t, player, lines);
|
||||
lines.push(("Тонкая линия — пройденное по измерениям,".into(), GREY));
|
||||
lines.push(("пунктир — прогноз курса.".into(), GREY));
|
||||
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));
|
||||
}
|
||||
@@ -2867,24 +2460,18 @@ impl AirDef {
|
||||
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.sim.truth {
|
||||
lines.push(("Режим ИСТИНА: настоящие дроны, их цели и маршруты.".into(), YELLOW));
|
||||
lines.push(("Это песочница, не данные сети. T — обратно.".into(), YELLOW));
|
||||
}
|
||||
// The recon flight's phase, only while the network actually holds a recon aircraft:
|
||||
// what the visible aircraft are doing, not what the enemy learned (#135).
|
||||
if self.sim.picture().values().any(|t| sim::is_drone_id(t.id)) {
|
||||
let pic = self.sim.enemy_picture();
|
||||
if let Some(phase) = crate::recon_view::battle_phase(&pic) {
|
||||
lines.push((format!("Разведка противника: {phase} · разведчиков {}", pic.recon_sorties.len()), YELLOW));
|
||||
}
|
||||
}
|
||||
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) {
|
||||
@@ -2951,24 +2538,13 @@ fn ring(ui: &MapUi, s: &mut Vec<Shape>, c: (f32, f32), r: f32, w: f32, color: u3
|
||||
}
|
||||
}
|
||||
|
||||
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), w: f32, color: u32) {
|
||||
fn dashed(s: &mut Vec<Shape>, 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), w, color));
|
||||
}
|
||||
}
|
||||
|
||||
/// A coarser dash for the truth mode's routes: many drones at once, so fewer, longer dashes.
|
||||
fn route_dashed(s: &mut Vec<Shape>, 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 / 24.0) as usize).clamp(2, 24);
|
||||
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.2, color));
|
||||
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.0, color));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3026,90 +2602,4 @@ mod tests {
|
||||
let far: Vec<(f32, f32)> = (0..128).map(|i| (i as f32 * 30.0, 0.0)).collect();
|
||||
assert_eq!(groups_of(&far, &vec![false; 128], CLUSTER_R, true).len(), 128);
|
||||
}
|
||||
|
||||
/// A drone over the map's middle and a system that has not measured anything yet.
|
||||
fn hover_fixture() -> (Sim, u32, MapUi) {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.launch(sim::DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), DVec3::ZERO, DVec3::ZERO, &mut sim::Out::default());
|
||||
let id = sim.drones[0].id;
|
||||
let sid = sim.id();
|
||||
sim.sams.push(Sam::new(sid, SamKind::Buk, DVec3::new(0.0, 64.0, 500.0), 0.0));
|
||||
let ui = MapUi { size: (800.0, 600.0), centre: (0.0, 0.0), scale: 1.0, cursor: (400.0, 300.0), ..Default::default() };
|
||||
(sim, id, ui)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_reads_the_network_and_only_the_truth_mode_adds_drones() {
|
||||
let (mut sim, id, ui) = hover_fixture();
|
||||
// The system holds no track: the drone is not in the network's picture and is not hoverable.
|
||||
assert_eq!(hover_at(&sim, &ui), None);
|
||||
sim.truth = true;
|
||||
assert_eq!(hover_at(&sim, &ui), Some(Hover::Drone(id)));
|
||||
// A measured track is hoverable in the honest picture too.
|
||||
sim.truth = false;
|
||||
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false };
|
||||
sim.sams[0].tracks.push(t);
|
||||
assert_eq!(hover_at(&sim, &ui), Some(Hover::Track(id)));
|
||||
// Away from the marker there is nothing.
|
||||
let mut away = ui;
|
||||
away.cursor = (20.0, 20.0);
|
||||
assert_eq!(hover_at(&sim, &away), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_network_card_never_claims_a_target_and_lists_its_status_and_interception() {
|
||||
let (mut sim, id, _) = hover_fixture();
|
||||
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: true };
|
||||
sim.sams[0].tracks.push(t);
|
||||
let mut lines = Vec::new();
|
||||
track_lines(&sim, &t, Some(DVec3::ZERO), &mut lines);
|
||||
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
|
||||
for must in ["Трек №", "Статус:", "Источник: сеть", "Скорость:", "Дистанция:", "Огневой захват", "Перехват: ракет нет", "Держат: 1 комплексов"] {
|
||||
assert!(all.contains(must), "the track card lacks {must}: {all}");
|
||||
}
|
||||
assert!(!all.contains("Цель:"), "the network's card claims a target: {all}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_truth_card_names_the_type_aim_route_and_interception() {
|
||||
let (sim, _, ui) = hover_fixture();
|
||||
let mut lines = Vec::new();
|
||||
truth_lines(&sim, &sim.drones[0], Some(DVec3::ZERO), &mut lines);
|
||||
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
|
||||
for must in ["ИСТИНА", "Шахед", "вне картины сети", "Цель:", "Маршрут:", "До цели:", "Перехват:"] {
|
||||
assert!(all.contains(must), "the truth card lacks {must}: {all}");
|
||||
}
|
||||
assert_eq!(hover_at(&sim, &ui), None, "the truth-off map revealed the drone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_truth_layer_draws_white_frames_and_yellow_routes() {
|
||||
let (mut sim, id, mut ui) = hover_fixture();
|
||||
sim.truth = true;
|
||||
// The label's width is cached so the test needs no GUI host call.
|
||||
let label = format!("{} №{}", sim.drones[0].kind.spec().name, id);
|
||||
ui.widths.insert(label.clone(), 60.0);
|
||||
let mut shapes = Vec::new();
|
||||
let mut labs = Vec::new();
|
||||
let mut taken = Vec::new();
|
||||
map_truth(&sim, &mut ui, Some(Hover::Drone(id)), &mut shapes, &mut labs, &mut taken);
|
||||
assert!(shapes.iter().any(|s| matches!(s, Shape::Fill(f) if f.color == alpha(WHITE, 0.95))), "no white frame for the true drone");
|
||||
assert!(shapes.iter().any(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFFE070)), "no yellow route or aim");
|
||||
assert!(labs.iter().any(|l| l.text.contains("Шахед")), "the true drone has no label");
|
||||
assert!(!taken.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_truth_trail_never_mixes_into_the_network_trail() {
|
||||
let (mut sim, id, mut ui) = hover_fixture();
|
||||
sim.tick = SAMPLE;
|
||||
ui.sample(&sim);
|
||||
assert!(ui.trails.is_empty() && ui.seen.is_empty(), "the network got the truth's trail");
|
||||
sim.truth = true;
|
||||
sim.tick = SAMPLE * 2;
|
||||
ui.sample(&sim);
|
||||
assert_eq!(ui.truth_trails.get(&id).map(Vec::len), Some(1));
|
||||
assert!(ui.trails.is_empty(), "the truth's trail was filed as the network's");
|
||||
assert!(ui.truth_seen.contains_key(&id) && !ui.seen.contains_key(&id));
|
||||
}
|
||||
}
|
||||
|
||||
+23
-81
@@ -3,7 +3,7 @@
|
||||
//! renders it) locked on its target. K shows one system at a time, J all of
|
||||
//! them in a grid.
|
||||
use crate::panel::distance;
|
||||
use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text};
|
||||
use crate::sim::{Sam, SamState, Sim, heading_of, roles_text};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape};
|
||||
|
||||
@@ -91,23 +91,12 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
s.push(fill(x, y, w, h, 0xC0080C0A));
|
||||
s.push(fill(x, y, w, 12.0, 0xE0142018));
|
||||
let state = sam.state;
|
||||
let optical = sam.kind == SamKind::Optical;
|
||||
let lock = matches!(state, SamState::Lock | SamState::Launch | SamState::Fire);
|
||||
let blink = lock && (tick / 4) % 2 == 0;
|
||||
let label = if optical { sam.optical.state().name() } else { state.name() };
|
||||
let color = if optical {
|
||||
match sam.optical.state() {
|
||||
OpticalState::Observing => 0xFF60FF80,
|
||||
OpticalState::Holding => 0xFF9FE0FF,
|
||||
OpticalState::NoSight => 0xFFFFA040,
|
||||
OpticalState::Searching => 0xFFE0E0E0,
|
||||
}
|
||||
} else {
|
||||
state.color()
|
||||
};
|
||||
let label = state.name();
|
||||
let lw = render::text_width(label);
|
||||
s.push(text(fit(format!("№{} {}", index + 1, spec.name), w - lw - 12.0), x + 3.0, y + 2.0, 0xFF9FE0FF));
|
||||
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(color, if blink { 0x80 } else { 0xFF })));
|
||||
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(state.color(), if blink { 0x80 } else { 0xFF })));
|
||||
|
||||
// The radar, at the left: round the system, north up.
|
||||
let rr = ((h - 28.0) / 2.0).min(w * 0.2).max(10.0);
|
||||
@@ -125,13 +114,9 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
}
|
||||
// A system that only fires (no radar) has no reach: a radar's sensor
|
||||
// range stands in, and nothing is divided by zero.
|
||||
let reach = if optical {
|
||||
crate::sim::OPTICAL_RANGE
|
||||
} else {
|
||||
match sam.kind.range() {
|
||||
r if r > 0.0 => r,
|
||||
_ => spec.sensor,
|
||||
}
|
||||
let reach = match sam.kind.range() {
|
||||
r if r > 0.0 => r,
|
||||
_ => spec.sensor,
|
||||
};
|
||||
let scale = if reach > 0.0 { rr as f64 / (reach * 1.25) } else { 0.0 };
|
||||
// The beam is the radar's real one: targets are measured as it passes them.
|
||||
@@ -161,17 +146,13 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
seen += 1;
|
||||
let k = scale as f32;
|
||||
let (bx, by) = (rx + rel.x as f32 * k, ry + rel.z as f32 * k);
|
||||
// By the class the track was estimated (#133): the unknown are candidates too, shown in
|
||||
// their own colour — the explicit policy — never the target's own class. No roles means
|
||||
// holding fire, and that greys out the unknown as well.
|
||||
let allowed = sam.roles & d.kind.spec().class.bit() != 0;
|
||||
let color = if Some(d.id) == target.map(|t| t.id) {
|
||||
0xFFFFE040
|
||||
} else if !tr.class.in_roles(sam.roles) {
|
||||
0xFF808080
|
||||
} else if tr.class == ClassEst::Unknown {
|
||||
0xFFFFA040
|
||||
} else {
|
||||
} else if allowed {
|
||||
0xFFFF4040
|
||||
} else {
|
||||
0xFF808080
|
||||
};
|
||||
if tr.forecast(tick) {
|
||||
s.push(fill(bx - 1.5, by - 1.5, 3.0, 1.0, color));
|
||||
@@ -183,30 +164,14 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
}
|
||||
}
|
||||
s.push(fill(rx - 1.5, ry - 1.5, 3.0, 3.0, 0xFF40A0FF));
|
||||
let radar_text = if optical {
|
||||
format!("ОПТИКА · {}", sam.optical.state().name())
|
||||
} else if spec.sensor <= 0.0 {
|
||||
let radar_text = if spec.sensor <= 0.0 {
|
||||
format!("сеть · {seen}")
|
||||
} else if radar_up {
|
||||
let profile = sam.radar_profile();
|
||||
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) };
|
||||
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
|
||||
format!("РЛС {} · {}", distance(reach), seen)
|
||||
} else {
|
||||
"РЛС ОТКАЗ".to_string()
|
||||
};
|
||||
let radar_color = if optical {
|
||||
match sam.optical.state() {
|
||||
OpticalState::Observing => 0xFF60FF80,
|
||||
OpticalState::Holding => 0xFF9FE0FF,
|
||||
OpticalState::NoSight => 0xFFFFA040,
|
||||
OpticalState::Searching => 0xFFB0B0B0,
|
||||
}
|
||||
} else if spec.sensor > 0.0 && !radar_up {
|
||||
0xFFFF5040
|
||||
} else {
|
||||
0xFF80FF90
|
||||
};
|
||||
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, radar_color));
|
||||
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, if spec.sensor > 0.0 && !radar_up { 0xFFFF5040 } else { 0xFF80FF90 }));
|
||||
|
||||
// Its health under the radar: a bar, red when it is low.
|
||||
if sam.alive() && sam.health < 1.0 {
|
||||
@@ -244,7 +209,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
// Worn or failed parts, over the picture: orange, red when one has failed.
|
||||
if !sam.comps.whole() {
|
||||
let failed = crate::sim::Part::ALL.iter().any(|p| sam.part_state(*p) == crate::sim::PartState::Failed);
|
||||
s.push(text(fit(crate::why_view::parts(&sam.comps, sam.kind), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
|
||||
s.push(text(fit(sam.parts_text(), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
|
||||
}
|
||||
// Crosshair.
|
||||
s.push(fill(cx + cw / 2.0 - 0.5, cy + 3.0, 1.0, ch * 0.18, 0x90FFFFFF));
|
||||
@@ -252,21 +217,6 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
s.push(fill(cx + 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
|
||||
s.push(fill(cx + cw * 0.82 - 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
|
||||
match target {
|
||||
Some(_) if optical => {
|
||||
// The optical post's picture: its own class observation, never the true model name.
|
||||
let (color, info) = match sam.optical.state() {
|
||||
OpticalState::Observing => (0xFF60FF80, sam.optical.status_text()),
|
||||
OpticalState::Holding => (0xFF9FE0FF, sam.optical.status_text()),
|
||||
OpticalState::NoSight => (0xFFFFA040, sam.optical.status_text()),
|
||||
OpticalState::Searching => (0xFFB0B0B0, sam.optical.status_text()),
|
||||
};
|
||||
let (bw, bh) = (cw * 0.3, ch * 0.34);
|
||||
brackets(s, cx + cw / 2.0 - bw / 2.0, cy + ch / 2.0 - bh / 2.0, bw, bh, 6.0, color);
|
||||
if ch > 50.0 {
|
||||
s.push(text(fit(info.clone(), cw - 6.0), cx + 3.0, cy + ch - 20.0, color));
|
||||
}
|
||||
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
|
||||
}
|
||||
Some(t) => {
|
||||
let color = if lock { if blink { 0xFFFF3030 } else { 0xFFFF8080 } } else { 0xFFFFE060 };
|
||||
let (bw, bh) = (cw * 0.3, ch * 0.34);
|
||||
@@ -283,12 +233,9 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
let rel = at - sam.pos;
|
||||
let bearing = (heading_of(rel).to_degrees() + 180.0).rem_euclid(360.0);
|
||||
if ch > 50.0 {
|
||||
// What the system knows it by: the estimated class; the sandbox's truth names the model.
|
||||
let name = if sim.truth { t.kind.spec().name.to_string() } else { track.map_or_else(|| "тип не определён".into(), |tr| tr.class.name()) };
|
||||
s.push(text(fit(name, cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
|
||||
s.push(text(fit(t.kind.spec().name.into(), cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
|
||||
}
|
||||
// The speed its own measurements showed, never the target's own figures.
|
||||
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, track.map_or(0.0, |tr| tr.vel.length()) * 72.0);
|
||||
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, t.vel.length() * 72.0);
|
||||
if let Some(tr) = track {
|
||||
if tr.forecast(tick) {
|
||||
info += &format!(" прогноз {:.1}с", tr.age(tick) as f64 / 20.0);
|
||||
@@ -301,24 +248,19 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
||||
}
|
||||
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
|
||||
}
|
||||
None if optical => s.push(text(fit(sam.optical.status_text(), cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFB0B0B0)),
|
||||
None => s.push(text("ПОИСК", cx + 3.0, cy + ch - 10.0, 0xFF80FF90)),
|
||||
}
|
||||
|
||||
// What it carries and does.
|
||||
let mut line = String::new();
|
||||
if optical {
|
||||
line = sam.optical.status_text();
|
||||
} else {
|
||||
if !matches!(sam.kind, SamKind::Gepard) {
|
||||
line += &format!("Р{} ", sam.missiles);
|
||||
if sam.kind == SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
|
||||
}
|
||||
if crate::sim::catalog::unit(sam.kind).has_gun() {
|
||||
line += &format!("Оч{} ", sam.bursts);
|
||||
}
|
||||
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
|
||||
if !matches!(sam.kind, crate::sim::SamKind::Gepard) {
|
||||
line += &format!("Р{} ", sam.missiles);
|
||||
if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
|
||||
}
|
||||
if crate::sim::catalog::unit(sam.kind).has_gun() {
|
||||
line += &format!("Оч{} ", sam.bursts);
|
||||
}
|
||||
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
|
||||
s.push(text(fit(line, cw), cx, y + h - 10.0, 0xFF9FE0FF));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,311 +0,0 @@
|
||||
//! The world overlay (#132): while the player holds the overlay key, square markers over the
|
||||
//! targets they can see, each with a short line — the class the radars estimated (#133) and the
|
||||
//! distance. The picture is the network's, as the radar and the map read it; the sandbox's truth
|
||||
//! mode adds white markers of the real drones, labelled with their actual type, apart from the
|
||||
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
|
||||
//! Letting the key go hides everything. The markers are projected through the camera the last
|
||||
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
|
||||
use crate::panel::distance;
|
||||
use crate::sim::{ClassEst, Sim, Track};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
|
||||
|
||||
/// The most markers of one picture (the network's and the truth's each): a full raid still fits
|
||||
/// the HUD's 1024 shapes — a marker is four sides and a label.
|
||||
const MAX_MARKERS: usize = 64;
|
||||
/// A marker's side thickness, pixels.
|
||||
const LINE: f32 = 1.0;
|
||||
/// A label line's height (the HUD font with its shadow).
|
||||
const LH: f32 = 9.0;
|
||||
/// The half-size a marker clamps to, near and far.
|
||||
const HALF_MIN: f32 = 5.0;
|
||||
const HALF_MAX: f32 = 16.0;
|
||||
|
||||
const RED: u32 = 0xFF4040;
|
||||
const ORANGE: u32 = 0xFFB040;
|
||||
const WHITE: u32 = 0xFFFFFFFF;
|
||||
const GREEN: u32 = 0xFF80FF90;
|
||||
const YELLOW: u32 = 0xFFFFE070;
|
||||
/// The interceptors' own colour (the radar's missile dot).
|
||||
const MISSILE: u32 = 0xFFE060;
|
||||
/// An interceptor's marker half-size: small, it is not a target.
|
||||
const MISSILE_HALF: f32 = 3.0;
|
||||
|
||||
fn pt(x: f32, y: f32) -> Point {
|
||||
Point { x, y }
|
||||
}
|
||||
|
||||
fn text(t: String, x: f32, y: f32, color: u32, centered: bool) -> Shape {
|
||||
Shape::Text(TextShape { text: t, at: pt(x, y), color, centered, shadow: true })
|
||||
}
|
||||
|
||||
/// 0xAARRGGBB with this alpha (0..1).
|
||||
fn alpha(rgb: u32, a: f64) -> u32 {
|
||||
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
|
||||
}
|
||||
|
||||
/// A square outline around a screen point: four thin fills, the world's marker.
|
||||
fn square_outline(x: f32, y: f32, half: f32, color: u32) -> Vec<Shape> {
|
||||
let (w, h) = (half * 2.0, LINE);
|
||||
vec![
|
||||
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w, h }, color }),
|
||||
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y + half - LINE, w, h }, color }),
|
||||
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w: h, h: w }, color }),
|
||||
Shape::Fill(FillShape { rect: Rect { x: x + half - LINE, y: y - half, w: h, h: w }, color }),
|
||||
]
|
||||
}
|
||||
|
||||
/// A marker's half-size by the distance: near targets read bigger, far ones stay legible.
|
||||
fn half(dist: f64) -> f32 {
|
||||
(700.0 / dist.max(1.0)).clamp(HALF_MIN as f64, HALF_MAX as f64) as f32
|
||||
}
|
||||
|
||||
/// The short line under a network marker: the estimated class's mark (#133) and the distance to
|
||||
/// the forecast place; a forecast says how old it is. An unidentified track gets a `?`, never the
|
||||
/// target's type.
|
||||
fn track_label(t: &Track, now: u64, player: DVec3) -> String {
|
||||
let mark = match t.class {
|
||||
ClassEst::Unknown => "?",
|
||||
c => c.mark(),
|
||||
};
|
||||
let mut s = format!("{mark} {}", distance(t.est(now).distance(player)));
|
||||
if t.forecast(now) {
|
||||
s += &format!(" ~{}с", t.age(now) / 20);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Where a marker's label sits: under the square, or over it when the bottom edge is close.
|
||||
fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
|
||||
if above {
|
||||
if y - half - LH - 2.0 >= 0.0 { y - half - LH - 2.0 } else { y + half + 2.0 }
|
||||
} else if y + half + LH + 2.0 <= gui_h {
|
||||
y + half + 2.0
|
||||
} else {
|
||||
y - half - LH - 2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
|
||||
/// frame's camera); a point behind the camera projects to None, a point off the screen still
|
||||
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
|
||||
pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -> Option<Point>) -> Vec<Shape> {
|
||||
let mut s = Vec::new();
|
||||
if gui.0 <= 0.0 || gui.1 <= 0.0 {
|
||||
return s;
|
||||
}
|
||||
let pic = sim.air_picture();
|
||||
let now = pic.now;
|
||||
let truth = sim.truth && !pic.unaided;
|
||||
// The network's tracks, nearest first: a full raid keeps the closest markers.
|
||||
let mut tracks: Vec<&Track> = pic.tracks.iter().collect();
|
||||
tracks.sort_by(|a, b| a.est(now).distance(player).total_cmp(&b.est(now).distance(player)));
|
||||
let mut shown = 0usize;
|
||||
let mut hidden = tracks.len().saturating_sub(MAX_MARKERS);
|
||||
for t in tracks.into_iter().take(MAX_MARKERS) {
|
||||
let e = t.est(now);
|
||||
let dist = e.distance(player);
|
||||
let Some(p) = project(e) else { hidden += 1; continue };
|
||||
let h = half(dist);
|
||||
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||
hidden += 1;
|
||||
continue;
|
||||
}
|
||||
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
|
||||
let (color, a) = if pic.unaided {
|
||||
(RED, 1.0)
|
||||
} else if t.forecast(now) {
|
||||
(ORANGE, (1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3))
|
||||
} else {
|
||||
(RED, 1.0)
|
||||
};
|
||||
let color = alpha(color, a);
|
||||
s.extend(square_outline(p.x, p.y, h, color));
|
||||
s.push(text(track_label(t, now, player), p.x, label_y(p.y, h, gui.1, false), color, true));
|
||||
shown += 1;
|
||||
}
|
||||
// The truth's own markers: the real drones, even the ones no radar holds, white and labelled
|
||||
// with the actual type the network never shows. A tracked drone wears both: the network's
|
||||
// estimate under the square, the truth over it — the offset between them is the point.
|
||||
if truth {
|
||||
let mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect();
|
||||
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
||||
hidden += drones.len().saturating_sub(MAX_MARKERS);
|
||||
for d in drones.into_iter().take(MAX_MARKERS) {
|
||||
let Some(p) = project(d.pos) else { hidden += 1; continue };
|
||||
let h = half(d.pos.distance(player)) + 2.0;
|
||||
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||
hidden += 1;
|
||||
continue;
|
||||
}
|
||||
s.extend(square_outline(p.x, p.y, h, WHITE));
|
||||
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
|
||||
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
|
||||
shown += 1;
|
||||
}
|
||||
}
|
||||
// The player's own interceptors: small yellow squares, no label — they are not targets, and
|
||||
// the network never hid them (the radar has always shown them).
|
||||
let mut missiles: Vec<_> = sim.missiles.iter().collect();
|
||||
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
||||
for m in missiles.into_iter().take(MAX_MARKERS) {
|
||||
let Some(p) = project(m.pos) else { continue };
|
||||
let h = MISSILE_HALF;
|
||||
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||
continue;
|
||||
}
|
||||
s.extend(square_outline(p.x, p.y, h, MISSILE));
|
||||
}
|
||||
// The mode, named as the map names it: the network's data by default, the sandbox's truth
|
||||
// explicitly marked. The counts say what the frame holds and what stayed behind the camera
|
||||
// or past the edges.
|
||||
let head = if truth {
|
||||
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}")
|
||||
} else {
|
||||
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}")
|
||||
};
|
||||
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{DroneKind, Out, Sam, SamKind};
|
||||
|
||||
const GUI: (f32, f32) = (800.0, 600.0);
|
||||
|
||||
/// A projector as the game's: the world ahead lands on the screen, behind the camera None.
|
||||
/// Here: south (+z) is ahead, x spreads across the screen, the height lines up at 64.
|
||||
fn ahead(p: DVec3) -> Option<Point> {
|
||||
if p.z <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(pt(400.0 + p.x as f32, 300.0 - (p.y - 64.0) as f32))
|
||||
}
|
||||
|
||||
fn sim_with(kind: DroneKind, at: DVec3) -> Sim {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.launch(kind, at, DVec3::ZERO, DVec3::new(at.x, 64.0, 5000.0), &mut Out::default());
|
||||
sim
|
||||
}
|
||||
|
||||
fn fills(shapes: &[Shape], rgb: u32) -> usize {
|
||||
shapes.iter().filter(|s| matches!(s, Shape::Fill(f) if f.color & 0xFFFFFF == rgb & 0xFFFFFF)).count()
|
||||
}
|
||||
|
||||
fn texts(shapes: &[Shape]) -> Vec<&TextShape> {
|
||||
shapes.iter().filter_map(|s| match s {
|
||||
Shape::Text(t) => Some(t),
|
||||
_ => None,
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_target_gets_a_square_and_a_short_line() {
|
||||
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
||||
// One marker: four red sides, and a label with the firm class's mark and the distance.
|
||||
assert_eq!(fills(&shapes, RED), 4, "the marker is not one square outline");
|
||||
let label = texts(&shapes).into_iter().find(|t| t.text.contains("100 м")).expect("no distance label");
|
||||
assert!(label.text.starts_with("Д "), "the firm drone class is not marked: {}", label.text);
|
||||
assert!(label.centered && label.at.y > 300.0, "the label sits under the square");
|
||||
// The header names the network's data and the counts.
|
||||
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
|
||||
assert!(head.text.contains("данные сети РЛС") && head.text.contains("в кадре 1, за кадром 0"), "{}", head.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behind_the_camera_and_off_screen_are_counted_not_drawn() {
|
||||
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
assert_eq!(fills(&shapes, RED), 4, "the drone behind the camera drew a marker");
|
||||
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
|
||||
assert!(head.text.contains("в кадре 1, за кадром 1"), "{}", head.text);
|
||||
// Off the screen's edge: still a place, but no marker.
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, |_| Some(pt(-40.0, 300.0)));
|
||||
assert_eq!(fills(&shapes, RED), 0);
|
||||
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
|
||||
assert!(head.text.contains("в кадре 0, за кадром 2"), "{}", head.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_never_leaks_the_type_of_an_unidentified_track() {
|
||||
let t = Track { id: 1, class: ClassEst::Unknown, pos: DVec3::new(0.0, 64.0, 100.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 1, locked: false };
|
||||
let label = track_label(&t, 0, DVec3::ZERO);
|
||||
assert!(label.starts_with("? "), "{label}");
|
||||
assert!(!label.contains("дрон") && !label.contains("Шахед"), "{label}");
|
||||
// A probable class keeps its question mark; a firm one loses it.
|
||||
let t = Track { class: ClassEst::Probable(crate::sim::Class::Cruise), ..t };
|
||||
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К? "));
|
||||
let t = Track { class: ClassEst::Firm(crate::sim::Class::Cruise), hits: 3, ..t };
|
||||
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К "));
|
||||
// A forecast says its age.
|
||||
let label = track_label(&t, 100, DVec3::ZERO);
|
||||
assert!(label.contains("~5с"), "{label}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_truth_mode_marks_the_real_drones_apart_from_the_network() {
|
||||
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
|
||||
// Without the truth mode: no white markers, no actual type anywhere.
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
assert_eq!(fills(&shapes, WHITE), 0);
|
||||
assert!(!texts(&shapes).iter().any(|t| t.text.contains("Шахед")), "the network overlay leaked the type");
|
||||
// With it: a white square with the real type, and the header says whose picture it is.
|
||||
sim.truth = true;
|
||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
||||
assert_eq!(fills(&shapes, WHITE), 4, "the truth marker is not one white square");
|
||||
let label = texts(&shapes).into_iter().find(|t| t.text.contains("Шахед-136")).expect("no truth label");
|
||||
assert!(label.text.contains("100 м") && label.at.y < 300.0, "the truth label sits over the square: {label:?}");
|
||||
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
|
||||
assert!(head.text.contains("ИСТИНА (песочница)"), "{}", head.text);
|
||||
// The truth mode with no system deployed adds nothing: the sky as it is was already shown.
|
||||
sim.sams.clear();
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
assert_eq!(fills(&shapes, WHITE), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_raid_stays_inside_the_huds_shape_budget() {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.raid(DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), 80, 300.0, &mut Out::default());
|
||||
sim.truth = true;
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
assert!(shapes.len() <= 1024, "the overlay overflowed the HUD: {} shapes", shapes.len());
|
||||
// The nearest markers were kept, the rest counted.
|
||||
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
|
||||
assert!(head.text.contains("за кадром"), "{}", head.text);
|
||||
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interceptors_wear_small_yellow_squares_without_labels() {
|
||||
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||
sim.missiles.push(crate::sim::Missile::test_at(1, DVec3::new(10.0, 70.0, 120.0), 0));
|
||||
sim.missiles.push(crate::sim::Missile::test_at(2, DVec3::new(0.0, 64.0, -50.0), 0));
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
// The one ahead: four yellow sides; the one behind the camera: nothing.
|
||||
assert_eq!(fills(&shapes, MISSILE), 4);
|
||||
assert!(!texts(&shapes).iter().any(|t| t.text.contains("перехват")), "an interceptor is not a target");
|
||||
// The budget holds with a full salvo too.
|
||||
for id in 3..100 {
|
||||
sim.missiles.push(crate::sim::Missile::test_at(id, DVec3::new(id as f64, 64.0, 100.0), 0));
|
||||
}
|
||||
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
|
||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
||||
assert!(fills(&shapes, MISSILE) / 4 <= MAX_MARKERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_flip_over_the_square_near_the_edges() {
|
||||
// Near the bottom: the label goes over the square; near the top: under it.
|
||||
assert!(label_y(590.0, 10.0, 600.0, false) < 590.0);
|
||||
assert!(label_y(10.0, 10.0, 600.0, true) > 10.0);
|
||||
assert!(label_y(300.0, 10.0, 600.0, false) > 300.0);
|
||||
assert!(label_y(300.0, 10.0, 600.0, true) < 300.0);
|
||||
}
|
||||
}
|
||||
+12
-106
@@ -1,6 +1,6 @@
|
||||
//! The summary panel (top right): the alert, what is in the air, each
|
||||
//! air-defence system's state and the score.
|
||||
use crate::sim::{AirPicture, Class, ClassEst, Sim};
|
||||
use crate::sim::{AirPicture, DroneKind, Sim};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::hud::Line;
|
||||
|
||||
@@ -31,50 +31,28 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
} else {
|
||||
let blink = (sim.tick / 10) % 2 == 0;
|
||||
lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", pic.tracks.len()), if blink { RED } else { PINK }));
|
||||
// By the class the tracks were estimated (#133): probable and firm counted apart, the
|
||||
// unidentified named — the exact models stay in the sandbox's truth line.
|
||||
// By type, as the radars classed them.
|
||||
let mut by_type = String::new();
|
||||
for c in Class::ALL {
|
||||
let firm = pic.tracks.iter().filter(|t| t.class == ClassEst::Firm(c)).count();
|
||||
let prob = pic.tracks.iter().filter(|t| t.class == ClassEst::Probable(c)).count();
|
||||
for (n, pre) in [(firm, ""), (prob, "вер. ")] {
|
||||
if n > 0 {
|
||||
if !by_type.is_empty() {
|
||||
by_type += ", ";
|
||||
}
|
||||
by_type += &format!("{pre}{} ×{n}", c.name());
|
||||
for kind in DroneKind::ALL {
|
||||
let n = pic.tracks.iter().filter(|t| t.kind == kind).count();
|
||||
if n > 0 {
|
||||
if !by_type.is_empty() {
|
||||
by_type += ", ";
|
||||
}
|
||||
by_type += &format!("{} ×{n}", kind.spec().name);
|
||||
}
|
||||
}
|
||||
let unknown = pic.tracks.iter().filter(|t| t.class == ClassEst::Unknown).count();
|
||||
if unknown > 0 {
|
||||
if !by_type.is_empty() {
|
||||
by_type += ", ";
|
||||
}
|
||||
by_type += &format!("не опознано ×{unknown}");
|
||||
}
|
||||
lines.push(line(by_type, PINK));
|
||||
// The nearest track to the player: where it was last measured (a forecast says so, with its age).
|
||||
if let Some(t) = pic.nearest(player) {
|
||||
let e = t.est(now);
|
||||
let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() };
|
||||
lines.push(line(
|
||||
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч · {} кач.{}{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel), t.product.name(), t.quality),
|
||||
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
|
||||
PINK,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Recon aircraft the network tracks: their presence and the coarse phase of the flight. This is
|
||||
// what the visible aircraft are doing, not the enemy's knowledge — the marks and the reasons are
|
||||
// the debug command's and the after-action review's alone (#135).
|
||||
let recon_n = pic.tracks.iter().filter(|t| crate::sim::is_drone_id(t.id)).count();
|
||||
if recon_n > 0 {
|
||||
let mut text = format!("Разведка противника: разведчиков в воздухе {recon_n}");
|
||||
if let Some(phase) = crate::recon_view::battle_phase(&sim.enemy_picture()) {
|
||||
text += &format!(" · фаза: {phase}");
|
||||
}
|
||||
lines.push(line(text, YELLOW));
|
||||
}
|
||||
if sim.truth {
|
||||
let real = sim.drones.iter().filter(|d| d.alive()).count();
|
||||
let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count();
|
||||
@@ -83,12 +61,6 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
text += ", противник планирует налёт";
|
||||
}
|
||||
lines.push(line(text, YELLOW));
|
||||
// The recon phase, in the truth only: the aircraft out and the marks the enemy holds
|
||||
// are its knowledge, not the player's (#135).
|
||||
let (out, marks) = sim.recon_status();
|
||||
if out > 0 || marks > 0 {
|
||||
lines.push(line(format!("РАЗВЕДКА ПРОТИВНИКА: в воздухе {out}, отметок в картине {marks}"), YELLOW));
|
||||
}
|
||||
}
|
||||
// The launch sites found, and the strike missiles (#101).
|
||||
if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() {
|
||||
@@ -105,11 +77,6 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
let worst = sim.target_health.iter().copied().fold(100.0, f64::min);
|
||||
lines.push(line(format!("Объекты: {}", list.join(" ")), if worst < 50.0 { RED } else { GREEN }));
|
||||
}
|
||||
// The passive optical posts (#136): their own status and source, never a radar's emission.
|
||||
let optics = sim.optical_reports();
|
||||
if let Some(r) = optics.iter().find(|r| r.state == crate::sim::OpticalState::Observing).or_else(|| optics.first()) {
|
||||
lines.push(line(format!("Опт. №{}: {}", r.index, r.line()), CYAN));
|
||||
}
|
||||
let lost = sim.sams.iter().filter(|s| !s.alive()).count();
|
||||
if lost > 0 {
|
||||
lines.push(line(format!("Потеряно комплексов: {lost}"), RED));
|
||||
@@ -127,12 +94,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
}
|
||||
for sam in sim.sams.iter().take(shown) {
|
||||
let mut text = if sam.kind.armed() {
|
||||
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles))
|
||||
format!("{} [{}]", sam.status(), crate::sim::roles_text(sam.roles))
|
||||
} else {
|
||||
crate::battery_view::sam_status(sam)
|
||||
sam.status()
|
||||
};
|
||||
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
|
||||
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
|
||||
text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos)));
|
||||
}
|
||||
if sam.kills > 0 {
|
||||
text += &format!(" ({})", sam.kills);
|
||||
@@ -152,64 +119,3 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
));
|
||||
lines
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{Aim, AirPicture, Approach, DroneKind, Out, RaidOrder, Track};
|
||||
use glam::DVec3;
|
||||
|
||||
fn track(id: u32, class: ClassEst) -> Track {
|
||||
Track { id, class, pos: DVec3::new(0.0, 120.0, 300.0), vel: DVec3::new(0.0, 0.0, -0.5), tick: 100, own_tick: 100, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false }
|
||||
}
|
||||
|
||||
// A recon aircraft the network holds is named as such, with the flight's coarse phase; the line
|
||||
// carries no mark, area or priority — the enemy's knowledge is not the HUD's (#135).
|
||||
#[test]
|
||||
fn a_tracked_recon_aircraft_shows_presence_and_phase_not_marks() {
|
||||
let mut sim = Sim::new(135);
|
||||
let object = DVec3::new(0.0, 70.0, 0.0);
|
||||
sim.targets.push(object);
|
||||
sim.target_health.push(100.0);
|
||||
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart };
|
||||
sim.order_raid(&order, &[object], &mut Out::default());
|
||||
let pic = sim.air_picture();
|
||||
assert!(pic.tracks.iter().any(|t| crate::sim::is_drone_id(t.id)), "the smart wave sent no recon to track");
|
||||
let lines = summary(&sim, &pic, DVec3::ZERO);
|
||||
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
|
||||
assert!(recon.text.contains("разведчиков в воздухе"), "{}", recon.text);
|
||||
assert!(recon.text.contains("фаза:"), "the flight's phase was not shown: {}", recon.text);
|
||||
assert!(!recon.text.contains("приоритет") && !recon.text.contains("Отметка"), "the HUD leaked the enemy's marks: {}", recon.text);
|
||||
assert!(lines.iter().all(|l| !l.text.contains("Отметка") && !l.text.contains("приоритет")), "a mark reached the normal HUD");
|
||||
}
|
||||
|
||||
// An ordinary strike track is not a recon flight: no recon line appears.
|
||||
#[test]
|
||||
fn an_ordinary_track_is_not_called_recon() {
|
||||
let sim = Sim::new(1);
|
||||
let pic = AirPicture { now: 100, tracks: vec![track(1, ClassEst::Firm(Class::Drone))], unaided: false };
|
||||
let lines = summary(&sim, &pic, DVec3::ZERO);
|
||||
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
|
||||
}
|
||||
|
||||
// A recon id in the picture is enough for the presence line even without a live sortie (a flight
|
||||
// finishing its way home): the phase is then omitted, the presence stays.
|
||||
#[test]
|
||||
fn a_recon_track_without_a_sortie_still_names_the_presence() {
|
||||
let sim = Sim::new(1);
|
||||
let pic = AirPicture { now: 100, tracks: vec![track(0x3000_0001, ClassEst::Firm(Class::Drone))], unaided: false };
|
||||
let lines = summary(&sim, &pic, DVec3::ZERO);
|
||||
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
|
||||
assert!(recon.text.contains("разведчиков в воздухе 1"), "{}", recon.text);
|
||||
assert!(!recon.text.contains("фаза:"), "a phase was invented without a sortie: {}", recon.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_sky_has_no_recon_line() {
|
||||
let sim = Sim::new(1);
|
||||
let pic = AirPicture { now: 100, tracks: Vec::new(), unaided: false };
|
||||
let lines = summary(&sim, &pic, DVec3::ZERO);
|
||||
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-171
@@ -1,24 +1,15 @@
|
||||
//! The radar screen (bottom right): a round scope round the player, north up,
|
||||
//! with a sweeping beam; blips fade after the beam passes them. A track's blip is a shape by the
|
||||
//! class the radar measured (#132), big enough to read at a glance; close ones merge with a count.
|
||||
//! The radar screen (top left): a round scope round the player, north up,
|
||||
//! with a sweeping beam; blips fade after the beam passes them.
|
||||
use crate::panel::distance;
|
||||
use crate::sim::{Class, ClassEst, SamKind, Sim};
|
||||
use crate::sim::{SamKind, Sim};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::render::{FillShape, Point, QuadShape, Rect, Shape, TextShape};
|
||||
|
||||
/// The scope's side in GUI pixels.
|
||||
pub const SIZE: f32 = 112.0;
|
||||
/// The corner box's height: the scope and its range label, plus the truth mode's own line when it shows one.
|
||||
pub fn height(truth_label: bool) -> f32 {
|
||||
SIZE + if truth_label { 22.0 } else { 12.0 }
|
||||
}
|
||||
/// Blocks from the centre to the edge.
|
||||
const RANGE: f64 = 500.0;
|
||||
const SEGMENTS: usize = 48;
|
||||
/// A track blip's half-size: the icons span about six pixels, against the old dot's three and a half.
|
||||
const BLIP: f32 = 3.0;
|
||||
/// Tracks this close on the scope merge into one blip with their number.
|
||||
const MERGE_R: f32 = 4.5;
|
||||
|
||||
fn pt(x: f32, y: f32) -> Point {
|
||||
Point { x, y }
|
||||
@@ -41,34 +32,6 @@ fn alpha(rgb: u32, a: f64) -> u32 {
|
||||
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
|
||||
}
|
||||
|
||||
/// A track's blip: a shape by the estimated class, pointing along the measured course.
|
||||
/// Drones are triangles, jets darts, cruise squares, supersonic diamonds, ballistic octagons;
|
||||
/// an unidentified track gets a question mark instead of leaking the target's type (#133).
|
||||
fn blip(class: ClassEst, x: f32, y: f32, color: u32, vel: DVec3) -> Vec<Shape> {
|
||||
let h = DVec3::new(vel.x, 0.0, vel.z).normalize_or_zero();
|
||||
let (hx, hy) = if h == DVec3::ZERO { (0.0, -1.0) } else { (h.x as f32, h.z as f32) };
|
||||
let (px, py) = (-hy, hx);
|
||||
let r = BLIP;
|
||||
let at = |along: f32, side: f32| pt(x + hx * along + px * side, y + hy * along + py * side);
|
||||
match class.class() {
|
||||
Some(Class::Drone) => vec![quad(at(r * 1.2, 0.0), at(-r * 0.8, r * 0.9), at(-r * 0.8, -r * 0.9), at(-r * 0.8, -r * 0.9), color)],
|
||||
Some(Class::Jet) => vec![quad(at(r * 1.3, 0.0), at(-r * 0.9, r * 0.9), at(-r * 0.3, 0.0), at(-r * 0.9, -r * 0.9), color)],
|
||||
Some(Class::Cruise) => vec![square(x, y, 2.6, color)],
|
||||
Some(Class::Supersonic) => vec![quad(pt(x, y - 3.2), pt(x + 3.2, y), pt(x, y + 3.2), pt(x - 3.2, y), color)],
|
||||
Some(Class::Ballistic) => vec![square(x, y, 2.3, color), quad(pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y), color)],
|
||||
None => vec![square(x, y, 2.4, color), text("?".into(), x, y - 3.0, 0xFF200808, true)],
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a blip's centre far enough inside the disc that the whole icon stays on the scope: the longest point
|
||||
/// of any class's icon is 1.3 × a half-size out.
|
||||
fn inside(x: f32, y: f32, cx: f32, cy: f32, r: f32) -> (f32, f32) {
|
||||
let (dx, dy) = (x - cx, y - cy);
|
||||
let d = dx.hypot(dy);
|
||||
let max = r - BLIP * 1.4 - 0.5;
|
||||
if d > max && d > 0.0 { (cx + dx / d * max, cy + dy / d * max) } else { (x, y) }
|
||||
}
|
||||
|
||||
pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
|
||||
let mut s = Vec::new();
|
||||
let r = SIZE / 2.0 - 2.0;
|
||||
@@ -180,169 +143,49 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
|
||||
s.push(square(x, y, 1.5, 0xFFFFFFA0));
|
||||
}
|
||||
}
|
||||
// The player is below target blips: a close target must not disappear under the white arrow.
|
||||
// Minecraft's yaw 0 looks south (+z, down the scope).
|
||||
let face = yaw.to_radians();
|
||||
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
|
||||
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
|
||||
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, the sky as it is. Nothing else is read (#93).
|
||||
let pic = sim.air_picture();
|
||||
let now = pic.now;
|
||||
// (x, y, class, colour, brightness, velocity) of every track on the scope, its icon kept inside the disc.
|
||||
let mut marks: Vec<(f32, f32, ClassEst, u32, f64, DVec3)> = Vec::new();
|
||||
for t in &pic.tracks {
|
||||
let (pos, vel) = (t.est(now), t.vel);
|
||||
match scope(pos) {
|
||||
Some((x, y, bearing)) => {
|
||||
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
|
||||
// The product is visible: a coarse search plot is amber, a refinement yellow, a fire plot red.
|
||||
let fresh_color = match t.product {
|
||||
crate::sim::battery::Measure::Search => 0xFFB060,
|
||||
crate::sim::battery::Measure::Refine => 0xFFE070,
|
||||
crate::sim::battery::Measure::Fire => 0xFF4040,
|
||||
};
|
||||
let (a, color) = if pic.unaided {
|
||||
(fade(bearing), 0xFF4040)
|
||||
} else if t.forecast(now) {
|
||||
((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040)
|
||||
} else {
|
||||
(1.0, fresh_color)
|
||||
(1.0, 0xFF4040)
|
||||
};
|
||||
let (x, y) = inside(x, y, cx, cy, r);
|
||||
marks.push((x, y, t.class, color, a, vel));
|
||||
s.push(square(x, y, 1.8, alpha(color, a)));
|
||||
// Its heading, a short tail.
|
||||
let v = vel.normalize_or_zero();
|
||||
s.push(quad(pt(x, y), pt(x + 0.6, y), pt(x - v.x as f32 * 6.0 + 0.6, y - v.z as f32 * 6.0), pt(x - v.x as f32 * 6.0, y - v.z as f32 * 6.0), alpha(color, a * 0.6)));
|
||||
}
|
||||
None => far += 1,
|
||||
}
|
||||
}
|
||||
// A tight raid reads as one blip with its number, not a pile of icons.
|
||||
let pos: Vec<(f32, f32)> = marks.iter().map(|m| (m.0, m.1)).collect();
|
||||
for grp in crate::map::group(&pos, MERGE_R) {
|
||||
let (x, y, class, color, a, vel) = marks[grp[0]];
|
||||
s.extend(blip(class, x, y, alpha(color, a), vel));
|
||||
// Its heading, a short tail, kept on the disc too.
|
||||
let v = vel.normalize_or_zero();
|
||||
let (ex, ey) = inside(x - v.x as f32 * 7.0, y - v.z as f32 * 7.0, cx, cy, r);
|
||||
s.push(quad(pt(x, y), pt(x + 1.0, y), pt(ex + 1.0, ey), pt(ex, ey), alpha(color, a * 0.6)));
|
||||
if grp.len() > 1 {
|
||||
s.push(text(format!("×{}", grp.len()), x + 4.0, y - 9.0, alpha(color, a), false));
|
||||
}
|
||||
}
|
||||
// The true places, when the sandbox asks for them: a white dot beside the track, to see how far the picture is off.
|
||||
if sim.truth && !pic.unaided {
|
||||
for d in sim.drones.iter().filter(|d| d.alive()) {
|
||||
if let Some((x, y, _)) = scope(d.pos) {
|
||||
let (x, y) = inside(x, y, cx, cy, r);
|
||||
s.push(square(x, y, 1.3, 0xFFFFFFFF));
|
||||
s.push(square(x, y, 0.8, 0xFFFFFFFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The player: a white arrow the way they look.
|
||||
// Minecraft's yaw 0 looks south (+z, down the scope).
|
||||
let face = yaw.to_radians();
|
||||
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
|
||||
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
|
||||
// Labels.
|
||||
s.push(text(format!("РЛС · {}", distance(RANGE)), cx, SIZE + 2.0, 0xFF80FF90, true));
|
||||
if sim.truth && !pic.unaided {
|
||||
s.push(text("ИСТИНА · песочница".into(), cx, SIZE + 12.0, 0xFFFFE070, true));
|
||||
}
|
||||
s.push(text("С".into(), cx, 3.0, 0xFF80FF90, true));
|
||||
if far > 0 {
|
||||
s.push(text(format!("+{far} за пределом"), cx, SIZE - 14.0, 0xFFFF8080, true));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{DroneKind, Out, Sam};
|
||||
|
||||
#[test]
|
||||
fn target_blips_are_drawn_over_the_player_arrow() {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -10.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
let shapes = draw(&sim, DVec3::ZERO, 0.0);
|
||||
let arrow = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFFFFFF)).unwrap();
|
||||
// The Shahed's blip is a red triangle (a quad with a repeated corner), drawn after the arrow.
|
||||
let target = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFF4040)).unwrap();
|
||||
assert!(target > arrow, "the player arrow covers the target blip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_class_has_its_own_blip_shape() {
|
||||
let vel = DVec3::new(0.5, 0.0, 0.0);
|
||||
let shapes: Vec<Vec<Shape>> = Class::ALL.iter().map(|c| blip(ClassEst::Firm(*c), 50.0, 50.0, 0xFFFF4040, vel)).collect();
|
||||
for (i, a) in shapes.iter().enumerate() {
|
||||
assert!(!a.is_empty());
|
||||
for b in &shapes[i + 1..] {
|
||||
assert_ne!(format!("{a:?}"), format!("{b:?}"), "two classes share one icon");
|
||||
}
|
||||
}
|
||||
// A courseless track (a ballistic one straight overhead) still draws, pointing north.
|
||||
assert!(!blip(ClassEst::Firm(Class::Ballistic), 50.0, 50.0, 0xFFFF4040, DVec3::Y).is_empty());
|
||||
assert!(blip(ClassEst::Unknown, 50.0, 50.0, 0xFFFF4040, vel).iter().any(|s| matches!(s, Shape::Text(t) if t.text == "?")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blips_stay_inside_the_scope() {
|
||||
let mut sim = Sim::new(1);
|
||||
// One track near the rim on every bearing, one of each class among them, one just beyond it.
|
||||
for k in 0..8 {
|
||||
let a = k as f64 / 8.0 * std::f64::consts::TAU;
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(a.sin() * 495.0, 64.0, a.cos() * 495.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
}
|
||||
for (k, kind) in [DroneKind::Geran3, DroneKind::Kh101, DroneKind::Kh22, DroneKind::Kinzhal].into_iter().enumerate() {
|
||||
let a = (k as f64 + 0.5) / 4.0 * std::f64::consts::TAU;
|
||||
sim.launch(kind, DVec3::new(a.sin() * 490.0, 64.0, a.cos() * 490.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
}
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -700.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
let shapes = draw(&sim, DVec3::ZERO, 0.0);
|
||||
let (cx, cy, r) = (SIZE / 2.0, SIZE / 2.0, SIZE / 2.0 - 2.0);
|
||||
let mut blips = 0;
|
||||
for s in &shapes {
|
||||
let corners = match s {
|
||||
Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 => vec![q.corners.0, q.corners.1, q.corners.2, q.corners.3],
|
||||
Shape::Fill(f) if f.color & 0xFFFFFF == 0xFF4040 => vec![pt(f.rect.x, f.rect.y), pt(f.rect.x + f.rect.w, f.rect.y), pt(f.rect.x, f.rect.y + f.rect.h), pt(f.rect.x + f.rect.w, f.rect.y + f.rect.h)],
|
||||
_ => continue,
|
||||
};
|
||||
blips += 1;
|
||||
for p in corners {
|
||||
assert!((p.x - cx).hypot(p.y - cy) <= r + 0.01, "a blip corner leaves the disc: {p:?}");
|
||||
}
|
||||
}
|
||||
assert!(blips >= 8, "the rim tracks were not drawn");
|
||||
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("за пределом"))), "the track beyond the range is counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tight_raid_merges_into_one_blip_with_a_count() {
|
||||
let mut sim = Sim::new(1);
|
||||
for k in 0..3 {
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(100.0 + k as f64, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
}
|
||||
let shapes = draw(&sim, DVec3::ZERO, 0.0);
|
||||
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text == "×3")), "the merged blip has no count");
|
||||
let triangles = shapes
|
||||
.iter()
|
||||
.filter(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 && q.corners.2.x == q.corners.3.x && q.corners.2.y == q.corners.3.y))
|
||||
.count();
|
||||
assert_eq!(triangles, 1, "three close tracks drew three icons");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_truth_mode_is_labelled_on_the_scope() {
|
||||
let mut sim = Sim::new(1);
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
|
||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
|
||||
let plain = draw(&sim, DVec3::ZERO, 0.0);
|
||||
assert!(!plain.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("ИСТИНА"))));
|
||||
sim.truth = true;
|
||||
let shapes = draw(&sim, DVec3::ZERO, 0.0);
|
||||
let label = shapes.iter().find_map(|s| match s {
|
||||
Shape::Text(t) if t.text.contains("ИСТИНА") && t.text.contains("песочница") => Some(t),
|
||||
_ => None,
|
||||
}).expect("the truth mode is not marked");
|
||||
// The corner box is sized to hold the label: a line of the HUD font is 9 pixels with its shadow.
|
||||
assert!(label.at.y + 9.0 <= height(true), "the truth label falls outside the corner box");
|
||||
assert!(height(true) > height(false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
//! Text for the enemy's reconnaissance (#135): the readable phase of a recon flight and the
|
||||
//! reason a mark outranks another. It reads only the diagnostic report types (`EnemyPictureReport`,
|
||||
//! `ReconReport`, `ReconSortieReport`) — an area, a public category, a channel, an age and a quality,
|
||||
//! never a true place, `SamKind`, health, magazine, link or real id. The full picture is for the
|
||||
//! explicit debug command and the after-action review; the battle HUD takes only the coarse phase
|
||||
//! of aircraft the player's own network already tracks.
|
||||
use crate::sim::{Category, Confidence, EnemyPictureReport, Quality, ReconReport, ReconSortieReport, priority_parts};
|
||||
|
||||
/// The public category a look reported, in the panel's words.
|
||||
pub fn category_name(key: &str) -> &'static str {
|
||||
match key {
|
||||
"radar" => "РЛС",
|
||||
"launcher" => "пусковая",
|
||||
"gun" => "пушка",
|
||||
"ew" => "РЭБ",
|
||||
"support" => "тыл",
|
||||
_ => "не определено",
|
||||
}
|
||||
}
|
||||
|
||||
/// A radar's role, public only once a refined look told it.
|
||||
pub fn role_name(key: &str) -> &'static str {
|
||||
match key {
|
||||
"multi" => "многофункциональная",
|
||||
"search" => "обзорная",
|
||||
"engagement" => "наведения",
|
||||
"height" => "высотомер",
|
||||
_ => "не определена",
|
||||
}
|
||||
}
|
||||
|
||||
/// The channel that showed the unit.
|
||||
pub fn source_name(key: &str) -> &'static str {
|
||||
match key {
|
||||
"emission" => "излучение",
|
||||
"jamming" => "РЭБ",
|
||||
"launch" => "пуск",
|
||||
_ => "пролёт",
|
||||
}
|
||||
}
|
||||
|
||||
/// How well the area is known.
|
||||
pub fn quality_name(key: &str) -> &'static str {
|
||||
match key {
|
||||
"refined" => "уточнённая",
|
||||
_ => "грубая",
|
||||
}
|
||||
}
|
||||
|
||||
/// The trust the picture puts in a mark of this age.
|
||||
pub fn confidence_name(confidence: Confidence) -> &'static str {
|
||||
match confidence {
|
||||
Confidence::Confirmed => "подтверждена",
|
||||
Confidence::Probable => "вероятна",
|
||||
Confidence::Doubtful => "сомнительна",
|
||||
}
|
||||
}
|
||||
|
||||
/// The phase of a sortie, as the timeline and the battle UI read it.
|
||||
pub fn phase_name(phase: &str) -> &'static str {
|
||||
match phase {
|
||||
"reporting" => "донесение",
|
||||
"done" => "завершение",
|
||||
"looking" => "осмотр",
|
||||
_ => "разведка",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a smart drone's aim is what it is, in words.
|
||||
pub fn intent_name(intent: &str) -> &'static str {
|
||||
match intent {
|
||||
"sead" => "подавление ПВО",
|
||||
"react" => "реакция",
|
||||
"replace" => "замена",
|
||||
_ => "план",
|
||||
}
|
||||
}
|
||||
|
||||
/// One mark in a line: its area's category and role, the channel, the quality, the trust, the age
|
||||
/// and the priority the planner prices it at.
|
||||
pub fn mark_line(m: &ReconReport) -> String {
|
||||
let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default();
|
||||
format!(
|
||||
"Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}",
|
||||
m.id,
|
||||
category_name(m.category),
|
||||
role,
|
||||
source_name(m.source),
|
||||
quality_name(m.quality),
|
||||
confidence_name(m.confidence),
|
||||
m.age / 20,
|
||||
m.priority
|
||||
)
|
||||
}
|
||||
|
||||
/// Why the mark has the priority it does: the observed role, the freshness and the quality, each
|
||||
/// with the weight the planner gives it, summing to the priority. The unit's true importance is not
|
||||
/// in it — only what the look reported.
|
||||
pub fn mark_reason(m: &ReconReport) -> String {
|
||||
let category = Category::from_key(m.category).unwrap_or(Category::Unknown);
|
||||
let quality = Quality::from_key(m.quality).unwrap_or(Quality::Coarse);
|
||||
let role = m.role.and_then(crate::sim::battery::RadarRole::from_key);
|
||||
let (freshness, quality_w, role_w) = priority_parts(m.confidence, quality, category, role);
|
||||
let role_txt = match m.role {
|
||||
Some(key) => format!("роль «{}»", role_name(key)),
|
||||
None => format!("категория «{}»", category_name(m.category)),
|
||||
};
|
||||
format!(
|
||||
"приоритет {} = свежесть {}×4 + качество {}×3 + роль {}: {} {}, {}",
|
||||
m.priority,
|
||||
freshness,
|
||||
quality_w,
|
||||
role_w,
|
||||
confidence_name(m.confidence),
|
||||
quality_name(m.quality),
|
||||
role_txt
|
||||
)
|
||||
}
|
||||
|
||||
/// One sortie in a line: its phase, the zones left and when its pending report is due.
|
||||
pub fn sortie_line(s: &ReconSortieReport) -> String {
|
||||
let mut text = format!("Разведчик {}: {}", s.drone, phase_name(s.phase));
|
||||
if s.zones_left > 0 {
|
||||
text += &format!(" · зон осталось {}", s.zones_left);
|
||||
}
|
||||
if let Some(due) = s.report_in {
|
||||
text += &format!(" · донесение через {} с", due / 20);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The coarse phase of the recon flight for the battle UI: a report going home now, else aircraft
|
||||
/// still looking, else the flight finishing. `None` when no sortie is out. It says nothing of what
|
||||
/// the enemy learned — only what its visible aircraft are doing.
|
||||
pub fn battle_phase(pic: &EnemyPictureReport) -> Option<&'static str> {
|
||||
if pic.recon_sorties.iter().any(|s| s.phase == "reporting") {
|
||||
Some("донесение")
|
||||
} else if pic.recon_sorties.iter().any(|s| s.phase == "outbound" || s.phase == "looking") {
|
||||
Some("разведка")
|
||||
} else if !pic.recon_sorties.is_empty() {
|
||||
Some("завершение")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole picture for the debug command and the after-action review: the sorties and their
|
||||
/// phases, then the marks best-first with the reason each outranks the rest, then the drones aimed
|
||||
/// at a mark. Explicitly the enemy's belief, not the truth; never the normal HUD.
|
||||
pub fn picture_lines(pic: &EnemyPictureReport) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
if pic.recon.is_empty() && pic.recon_sorties.is_empty() {
|
||||
lines.push("Разведки не было: противник не высылал разведчиков и ничего не запомнил.".into());
|
||||
return lines;
|
||||
}
|
||||
lines.push(format!(
|
||||
"Картина противника (debug/разбор): отметок {}, разведчиков в воздухе {}",
|
||||
pic.recon.len(),
|
||||
pic.recon_sorties.len()
|
||||
));
|
||||
for s in &pic.recon_sorties {
|
||||
lines.push(sortie_line(s));
|
||||
}
|
||||
let mut marks: Vec<&ReconReport> = pic.recon.iter().collect();
|
||||
marks.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
|
||||
for m in marks {
|
||||
lines.push(mark_line(m));
|
||||
lines.push(format!(" ↳ {}", mark_reason(m)));
|
||||
}
|
||||
for a in pic.aims.iter().filter(|a| a.recon) {
|
||||
lines.push(format!(
|
||||
"Дрон {} целится в отметку {} (приоритет {}, {})",
|
||||
a.drone,
|
||||
a.unit,
|
||||
a.priority.unwrap_or(0),
|
||||
intent_name(a.intent)
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport};
|
||||
use glam::DVec3;
|
||||
|
||||
fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport {
|
||||
let cat = Category::from_key(category).unwrap();
|
||||
let qual = Quality::from_key(quality).unwrap();
|
||||
let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key);
|
||||
let (f, q, r) = priority_parts(confidence, qual, cat, role_enum);
|
||||
ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r }
|
||||
}
|
||||
|
||||
fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport {
|
||||
ReconSortieReport { drone, phase, zones_left, report_in }
|
||||
}
|
||||
|
||||
fn picture(recon: Vec<ReconReport>, recon_sorties: Vec<ReconSortieReport>, aims: Vec<AimReport>) -> EnemyPictureReport {
|
||||
EnemyPictureReport { now: 1000, contacts: Vec::new(), aims, pending: Vec::new(), work_per_tick: 4, recon, recon_sorties }
|
||||
}
|
||||
|
||||
// The reason names all three factors with the planner's own weights, and they sum to the priority.
|
||||
#[test]
|
||||
fn the_reason_is_the_observed_role_freshness_and_quality() {
|
||||
let m = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Confirmed, 100);
|
||||
let reason = mark_reason(&m);
|
||||
assert_eq!(m.priority, 4 * 4 + 2 * 3 + 3);
|
||||
assert!(reason.contains("приоритет 25 = свежесть 4×4 + качество 2×3 + роль 3"), "{reason}");
|
||||
assert!(reason.contains("подтверждена") && reason.contains("уточнённая") && reason.contains("роль «наведения»"), "{reason}");
|
||||
// A coarse, doubtful, unknown mark: every part is zero, and the reason says so.
|
||||
let weak = mark(0x1000_0002, "unknown", None, "coarse", Confidence::Doubtful, 5000);
|
||||
assert_eq!(weak.priority, 0);
|
||||
let weak_reason = mark_reason(&weak);
|
||||
assert!(weak_reason.contains("свежесть 0×4 + качество 0×3 + роль 0"), "{weak_reason}");
|
||||
assert!(weak_reason.contains("сомнительна") && weak_reason.contains("категория «не определено»"), "{weak_reason}");
|
||||
}
|
||||
|
||||
// A fresh modest mark can outrank a stale big one: the reason reflects the age, not the truth.
|
||||
#[test]
|
||||
fn a_fresh_modest_mark_outranks_a_stale_big_one() {
|
||||
let stale_big = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Doubtful, 5000);
|
||||
let fresh_modest = mark(0x1000_0002, "gun", None, "coarse", Confidence::Confirmed, 100);
|
||||
assert!(fresh_modest.priority > stale_big.priority, "{} vs {}", fresh_modest.priority, stale_big.priority);
|
||||
let fresh_id = fresh_modest.id;
|
||||
let lines = picture_lines(&picture(vec![stale_big, fresh_modest], Vec::new(), Vec::new()));
|
||||
let first = lines.iter().position(|l| l.starts_with("Отметка")).unwrap();
|
||||
assert!(lines[first].contains(&format!("Отметка {fresh_id}")), "the fresh modest mark did not lead: {lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_phase_reads_recon_report_and_done() {
|
||||
assert_eq!(phase_name("outbound"), "разведка");
|
||||
assert_eq!(phase_name("reporting"), "донесение");
|
||||
assert_eq!(phase_name("done"), "завершение");
|
||||
let reporting = picture(Vec::new(), vec![sortie(0x3000_0001, "reporting", 0, Some(40)), sortie(0x3000_0002, "outbound", 2, None)], Vec::new());
|
||||
assert_eq!(battle_phase(&reporting), Some("донесение"));
|
||||
let looking = picture(Vec::new(), vec![sortie(0x3000_0001, "outbound", 2, None)], Vec::new());
|
||||
assert_eq!(battle_phase(&looking), Some("разведка"));
|
||||
let done = picture(Vec::new(), vec![sortie(0x3000_0001, "done", 0, None)], Vec::new());
|
||||
assert_eq!(battle_phase(&done), Some("завершение"));
|
||||
assert_eq!(battle_phase(&picture(Vec::new(), Vec::new(), Vec::new())), None);
|
||||
assert!(sortie_line(&sortie(0x3000_0001, "reporting", 1, Some(40))).contains("донесение через 2 с"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_picture_says_there_was_no_recon() {
|
||||
let lines = picture_lines(&picture(Vec::new(), Vec::new(), Vec::new()));
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].contains("Разведки не было"), "{lines:?}");
|
||||
}
|
||||
|
||||
// The review shows the marks with their reasons and the drones aimed at them; the ids are the
|
||||
// synthetic ones, and nothing of the unit's truth (kind, health, exact place) is in the report.
|
||||
#[test]
|
||||
fn the_review_lists_marks_reasons_and_recon_aims() {
|
||||
let m = mark(0x1000_0001, "launcher", None, "coarse", Confidence::Probable, 1000);
|
||||
let mid = m.id;
|
||||
let aim = AimReport { drone: 7, unit: mid, intent: "sead", since: 900, switches: 0, confidence: Some(Confidence::Probable), recon: true, priority: Some(m.priority) };
|
||||
let unit_aim = AimReport { drone: 8, unit: 3, intent: "plan", since: 900, switches: 0, confidence: Some(Confidence::Confirmed), recon: false, priority: None };
|
||||
let lines = picture_lines(&picture(vec![m], vec![sortie(0x3000_0001, "outbound", 1, None)], vec![aim, unit_aim]));
|
||||
assert!(lines.iter().any(|l| l.contains(&format!("Отметка {mid}")) && l.contains("пусковая")), "{lines:?}");
|
||||
assert!(lines.iter().any(|l| l.contains("↳") && l.contains("приоритет")), "{lines:?}");
|
||||
assert!(lines.iter().any(|l| l.contains("Дрон 7 целится в отметку") && l.contains("подавление ПВО")), "{lines:?}");
|
||||
// A unit contact's aim is not a recon aim: it is not listed here.
|
||||
assert!(!lines.iter().any(|l| l.contains("Дрон 8")), "{lines:?}");
|
||||
// No true unit id leaks: the mark id is synthetic, far above any real unit's.
|
||||
assert!(mid >= 0x1000_0000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_public_name_is_translated() {
|
||||
for key in ["unknown", "radar", "launcher", "gun", "ew", "support"] {
|
||||
assert_ne!(category_name(key), key, "{key}");
|
||||
}
|
||||
for key in ["multi", "search", "engagement", "height"] {
|
||||
assert_ne!(role_name(key), key, "{key}");
|
||||
}
|
||||
for key in ["flyby", "emission", "jamming", "launch"] {
|
||||
assert_ne!(source_name(key), key, "{key}");
|
||||
}
|
||||
assert_ne!(quality_name("coarse"), "coarse");
|
||||
assert_ne!(quality_name("refined"), "refined");
|
||||
}
|
||||
}
|
||||
@@ -33,199 +33,8 @@ impl RadarRole {
|
||||
pub fn from_key(key: &str) -> Option<Self> {
|
||||
match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None }
|
||||
}
|
||||
pub fn profile(self) -> RadarProfile { RadarProfile::of(self) }
|
||||
pub fn authorizes(self) -> bool { self.profile().products & RadarProfile::FIRE_BIT != 0 }
|
||||
}
|
||||
|
||||
/// What a measurement is good for. A search plot is a warning, a refined
|
||||
/// plot fixes a matched contact, and a fire plot is a confirmed measurement
|
||||
/// a launcher may use. Quality (0..100) is separate from identification:
|
||||
/// a well-measured track can still be an unknown type (#133).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Measure {
|
||||
#[default]
|
||||
Search,
|
||||
Refine,
|
||||
Fire,
|
||||
}
|
||||
impl Measure {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self { Self::Search => "обзор", Self::Refine => "уточнение", Self::Fire => "пригоден для пуска" }
|
||||
}
|
||||
pub fn allows_fire(self) -> bool { self == Self::Fire }
|
||||
}
|
||||
|
||||
/// A radar profile: a stable catalog identity over the existing `SamKind::Radar`.
|
||||
/// The numbers are fictional game settings. The silhouette is shared with the
|
||||
/// existing radar model: this slice does not add art (a separate owner's zone).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RadarProfile {
|
||||
/// Stable content ID; old saves only have `RadarRole`, which maps here.
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
/// Allowed measurement products (`SEARCH_BIT`, `REFINE_BIT`, `FIRE_BIT`).
|
||||
pub products: u8,
|
||||
/// Ticks for the beam to go round.
|
||||
pub cycle: u32,
|
||||
/// Electronic revisit of held contacts between beam passes.
|
||||
pub agile: bool,
|
||||
/// Extra antenna height over the unit's spec mast (blocks).
|
||||
pub mast: f64,
|
||||
/// Search reach, a factor of the unit's sensor.
|
||||
pub reach: f64,
|
||||
/// Local search radius, a factor of the unit's sensor (1: the whole reach).
|
||||
pub local: f64,
|
||||
/// Simultaneous refined/fire channels; 0 means only search plots.
|
||||
pub channels: u8,
|
||||
/// Measurement error scale (blocks) and its growth per block of range.
|
||||
pub sigma: f64,
|
||||
pub spread: f64,
|
||||
/// Vertical error as a share of the horizontal one.
|
||||
pub vertical: f64,
|
||||
pub deployment: &'static str,
|
||||
/// The limit the profile deliberately keeps, shown in the UI.
|
||||
pub limit: &'static str,
|
||||
}
|
||||
|
||||
impl RadarProfile {
|
||||
pub const SEARCH_BIT: u8 = 1;
|
||||
pub const REFINE_BIT: u8 = 2;
|
||||
pub const FIRE_BIT: u8 = 4;
|
||||
|
||||
pub const MULTI: RadarProfile = RadarProfile {
|
||||
id: "radar_multi",
|
||||
name: "многофункциональная",
|
||||
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
|
||||
cycle: 140,
|
||||
agile: false,
|
||||
mast: 0.0,
|
||||
reach: 1.0,
|
||||
local: 0.55,
|
||||
channels: 3,
|
||||
sigma: 0.7,
|
||||
spread: 0.004,
|
||||
vertical: 0.75,
|
||||
deployment: "стационарная",
|
||||
limit: "универсальная: уступает специализированным по циклу, каналам и точности",
|
||||
};
|
||||
pub const SEARCH: RadarProfile = RadarProfile {
|
||||
id: "radar_search",
|
||||
name: "дальнего обзора",
|
||||
products: Self::SEARCH_BIT,
|
||||
cycle: 170,
|
||||
agile: false,
|
||||
mast: 0.0,
|
||||
reach: 1.15,
|
||||
local: 1.0,
|
||||
channels: 0,
|
||||
sigma: 1.0,
|
||||
spread: 0.008,
|
||||
vertical: 1.0,
|
||||
deployment: "крупная стационарная антенна",
|
||||
limit: "редкие грубые отметки; своего права на пуск не даёт",
|
||||
};
|
||||
pub const ENGAGEMENT: RadarProfile = RadarProfile {
|
||||
id: "radar_track",
|
||||
name: "сопровождения",
|
||||
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
|
||||
cycle: 70,
|
||||
agile: true,
|
||||
mast: 0.0,
|
||||
reach: 0.8,
|
||||
local: 0.12,
|
||||
channels: 2,
|
||||
sigma: 0.35,
|
||||
spread: 0.002,
|
||||
vertical: 0.6,
|
||||
deployment: "мобильная панель",
|
||||
limit: "локальный поиск и два канала; сеть лишь подсказывает, измеряет станция",
|
||||
};
|
||||
pub const HEIGHT: RadarProfile = RadarProfile {
|
||||
id: "radar_height",
|
||||
name: "мачта низких высот",
|
||||
products: Self::SEARCH_BIT | Self::REFINE_BIT,
|
||||
cycle: 140,
|
||||
agile: false,
|
||||
mast: 8.0,
|
||||
reach: 1.05,
|
||||
local: 0.15,
|
||||
channels: 3,
|
||||
sigma: 0.5,
|
||||
spread: 0.003,
|
||||
vertical: 0.35,
|
||||
deployment: "шасси с поднятой антенной",
|
||||
limit: "уточняет низкие контакты над рельефом; сквозь препятствия не видит и права на пуск не даёт",
|
||||
};
|
||||
/// A weapon's own radar: it measures for its own fire control. Kept out of
|
||||
/// the separate radar roles so embedded radars keep working as before.
|
||||
pub const EMBEDDED: RadarProfile = RadarProfile {
|
||||
id: "embedded",
|
||||
name: "РЛС комплекса",
|
||||
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
|
||||
cycle: 0,
|
||||
agile: false,
|
||||
mast: 0.0,
|
||||
reach: 1.0,
|
||||
local: 1.0,
|
||||
channels: 0,
|
||||
sigma: 0.8,
|
||||
spread: 0.004,
|
||||
// The old embedded scan drew its vertical error at half the horizontal one.
|
||||
vertical: 0.5,
|
||||
deployment: "встроенная",
|
||||
limit: "обслуживает только свой комплекс",
|
||||
};
|
||||
|
||||
pub fn of(role: RadarRole) -> Self {
|
||||
match role {
|
||||
RadarRole::Multifunction => Self::MULTI,
|
||||
RadarRole::Search => Self::SEARCH,
|
||||
RadarRole::Engagement => Self::ENGAGEMENT,
|
||||
RadarRole::Height => Self::HEIGHT,
|
||||
}
|
||||
}
|
||||
/// Old saves write the role key; new saves write the stable profile ID.
|
||||
/// Both read here, so a legacy `search` line maps to `radar_search`.
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
match id {
|
||||
"radar_multi" | "multi" => Some(Self::MULTI),
|
||||
"radar_search" | "search" => Some(Self::SEARCH),
|
||||
"radar_track" | "engagement" => Some(Self::ENGAGEMENT),
|
||||
"radar_height" | "height" => Some(Self::HEIGHT),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn role(self) -> RadarRole {
|
||||
match self.id {
|
||||
"radar_search" => RadarRole::Search,
|
||||
"radar_track" => RadarRole::Engagement,
|
||||
"radar_height" => RadarRole::Height,
|
||||
_ => RadarRole::Multifunction,
|
||||
}
|
||||
}
|
||||
pub fn allows(self, product: Measure) -> bool {
|
||||
match product {
|
||||
Measure::Search => self.products & Self::SEARCH_BIT != 0,
|
||||
Measure::Refine => self.products & Self::REFINE_BIT != 0,
|
||||
Measure::Fire => self.products & Self::FIRE_BIT != 0,
|
||||
}
|
||||
}
|
||||
pub fn products_text(self) -> &'static str {
|
||||
match self.products {
|
||||
p if p == Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT => "обзор, уточнение, пуск",
|
||||
p if p == Self::SEARCH_BIT | Self::REFINE_BIT => "обзор, уточнение",
|
||||
p if p == Self::SEARCH_BIT | Self::FIRE_BIT => "обзор, пуск",
|
||||
_ => "обзор",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sam {
|
||||
/// The profile this unit measures with. Embedded radars keep their kind's
|
||||
/// own scan and reach; only the separate radar uses a selectable profile.
|
||||
pub fn radar_profile(&self) -> RadarProfile {
|
||||
if self.kind == SamKind::Radar { RadarProfile::of(self.radar_role) } else { RadarProfile::EMBEDDED }
|
||||
}
|
||||
pub fn authorizes(self) -> bool { matches!(self, Self::Multifunction | Self::Engagement) }
|
||||
pub(super) fn reach_factor(self) -> f64 { match self { Self::Multifunction => 1.0, Self::Search => 1.15, Self::Engagement => 0.8, Self::Height => 1.05 } }
|
||||
}
|
||||
|
||||
impl Sam {
|
||||
@@ -304,22 +113,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn track(now: u64) -> Track {
|
||||
Track {
|
||||
id: 42,
|
||||
class: ClassEst::Firm(Class::Cruise),
|
||||
pos: DVec3::new(0.0, 100.0, -200.0),
|
||||
vel: DVec3::ZERO,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: 1,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 90,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 90,
|
||||
ttl: 400,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
}
|
||||
Track { id: 42, kind: DroneKind::Kh101, pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -457,24 +251,6 @@ mod tests {
|
||||
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_have_stable_ids_and_deliberately_different_limits() {
|
||||
let search = RadarRole::Search.profile();
|
||||
let height = RadarRole::Height.profile();
|
||||
let engagement = RadarRole::Engagement.profile();
|
||||
let multi = RadarRole::Multifunction.profile();
|
||||
assert_eq!((search.id, height.id, engagement.id, multi.id), ("radar_search", "radar_height", "radar_track", "radar_multi"));
|
||||
assert!(!RadarRole::Search.authorizes() && !RadarRole::Height.authorizes() && RadarRole::Engagement.authorizes());
|
||||
assert_eq!(search.products, RadarProfile::SEARCH_BIT);
|
||||
assert_eq!(height.products, RadarProfile::SEARCH_BIT | RadarProfile::REFINE_BIT);
|
||||
assert_ne!(search.cycle, engagement.cycle);
|
||||
assert!(height.mast > search.mast && height.mast > engagement.mast);
|
||||
assert!(engagement.channels < multi.channels && height.channels > 0 && search.channels == 0);
|
||||
assert!(search.local > height.local && height.local > engagement.local);
|
||||
assert_eq!(RadarProfile::from_id(search.id), Some(search));
|
||||
assert_eq!(RadarProfile::from_id("search"), Some(search), "legacy role keys map to profiles");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() {
|
||||
let mut sim = Sim::new(3);
|
||||
@@ -518,22 +294,7 @@ mod emission_tests {
|
||||
receiver.radar_on = false;
|
||||
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -100.0), DVec3::Z, DVec3::ZERO);
|
||||
let id = sim.drones[0].id;
|
||||
source.tracks.push(Track {
|
||||
id,
|
||||
class: ClassEst::Firm(Class::Cruise),
|
||||
pos: sim.drones[0].pos,
|
||||
vel: DVec3::ZERO,
|
||||
tick: 20,
|
||||
own_tick: 20,
|
||||
source: 1,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 90,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 90,
|
||||
ttl: 200,
|
||||
hits: 2,
|
||||
locked: false,
|
||||
});
|
||||
source.tracks.push(Track { id, kind: DroneKind::Kh101, pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false });
|
||||
sim.sams.extend([source, receiver]);
|
||||
let mut ground = Ground::default();
|
||||
sim.update_sight(&mut ground);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! Balance and rendering remain in `DroneSpec` and `SamSpec`: the catalog
|
||||
//! refers to those typed definitions instead of copying their values. The
|
||||
//! first eleven drone entries retain the historical positional wave-save order.
|
||||
use super::{battery::RadarProfile, battery::RadarRole, battery::SamMode, DroneKind, SamKind};
|
||||
use super::{DroneKind, SamKind};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Aircraft {
|
||||
@@ -19,28 +19,6 @@ impl Aircraft {
|
||||
pub fn id(self) -> &'static str { self.kind.spec().key }
|
||||
}
|
||||
|
||||
/// A variant of a complex: a configuration over an existing kind, deployed
|
||||
/// under its own command/menu id. Not new balance.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct UnitVariant {
|
||||
/// Existing command/menu key; changing it requires an explicit migration.
|
||||
pub id: &'static str,
|
||||
pub kind: SamKind,
|
||||
pub mode: SamMode,
|
||||
pub role: RadarRole,
|
||||
/// The deploy menu's row.
|
||||
pub label: &'static str,
|
||||
/// What the configuration is for (shown in the deploy menu).
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
impl UnitVariant {
|
||||
/// The typed radar profile behind a separate radar variant.
|
||||
pub fn radar_profile(self) -> Option<RadarProfile> {
|
||||
(self.kind == SamKind::Radar).then(|| RadarProfile::of(self.role))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GroundStrike {
|
||||
/// Game-only RM48U coordinate-strike profile for S-400. Evidence: official agency report,
|
||||
@@ -81,7 +59,6 @@ pub mod sound {
|
||||
|
||||
// Generated entries keep the historical raid and unit ordering.
|
||||
include!("catalog_entries.rs");
|
||||
include!("unit_variants_generated.rs");
|
||||
|
||||
/// Existing positional serialization makes the first entries' order part of the save format.
|
||||
const fn raid_count() -> usize {
|
||||
@@ -155,10 +132,6 @@ pub fn deploy_item(id: &str) -> Option<SamKind> {
|
||||
UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind)
|
||||
}
|
||||
|
||||
pub fn variant(id: &str) -> Option<&'static UnitVariant> {
|
||||
VARIANTS.iter().find(|variant| variant.id == id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -200,34 +173,6 @@ mod tests {
|
||||
assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]);
|
||||
}
|
||||
|
||||
/// A variant is a configuration of an existing kind, one row in the catalog,
|
||||
/// under an id that stays out of the other identities' keys; the battery-menu
|
||||
/// order is part of the UI's tested behaviour.
|
||||
#[test]
|
||||
fn variants_configure_existing_units_under_free_ids() {
|
||||
let ids: Vec<&str> = VARIANTS.iter().map(|v| v.id).collect();
|
||||
assert_eq!(ids, ["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]);
|
||||
for v in VARIANTS {
|
||||
assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id);
|
||||
assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id);
|
||||
assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
|
||||
assert!(!v.label.is_empty() && !v.description.is_empty());
|
||||
assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role)));
|
||||
if v.kind == SamKind::Radar {
|
||||
let profile = v.radar_profile().expect("a radar variant has a profile");
|
||||
assert_eq!(profile.id, v.id, "the stable profile ID is the variant ID");
|
||||
assert_eq!(profile.role(), v.role);
|
||||
assert!(profile.channels <= 3 && profile.cycle > 0);
|
||||
} else {
|
||||
assert!(v.radar_profile().is_none());
|
||||
}
|
||||
}
|
||||
let launcher = variant("s400_launcher").unwrap();
|
||||
assert_eq!((launcher.kind, launcher.mode, launcher.role), (SamKind::S400, SamMode::LauncherOnly, RadarRole::Multifunction));
|
||||
assert_eq!(VARIANTS[4].id, "radar_height");
|
||||
assert!(variant("miss").is_none() && variant("s400").is_none());
|
||||
}
|
||||
|
||||
/// The catalog is the only copy of the numbers: a kind without a row, or a row under
|
||||
/// another kind, would be a silent balance change.
|
||||
#[test]
|
||||
|
||||
@@ -31,5 +31,4 @@ pub const UNITS: &[Unit] = &[
|
||||
Unit { kind: SamKind::Tzm, deploy_item: "airdef:deploy_tzm" },
|
||||
Unit { kind: SamKind::Ew, deploy_item: "airdef:deploy_ew" },
|
||||
Unit { kind: SamKind::Light, deploy_item: "airdef:deploy_light" },
|
||||
Unit { kind: SamKind::Optical, deploy_item: "airdef:deploy_optical" },
|
||||
];
|
||||
|
||||
@@ -54,10 +54,6 @@ impl Part {
|
||||
Part::Comms => "Св",
|
||||
}
|
||||
}
|
||||
/// The short label as this kind of unit reads it: a passive post has optics, not a radar.
|
||||
pub fn short_on(self, kind: SamKind) -> &'static str {
|
||||
if self == Part::Sensor && kind == SamKind::Optical { "Опт" } else { self.short() }
|
||||
}
|
||||
fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
@@ -65,8 +61,7 @@ impl Part {
|
||||
pub fn on(self, kind: SamKind) -> bool {
|
||||
let spec = kind.spec();
|
||||
match self {
|
||||
// A passive optical post has a sensor without radar reach: it can be damaged and blinded too.
|
||||
Part::Sensor => spec.sensor > 0.0 || kind == SamKind::Optical,
|
||||
Part::Sensor => spec.sensor > 0.0,
|
||||
Part::Mount => kind.armed() && kind != SamKind::Light && (spec.missile.is_some() || spec.gun.is_some()),
|
||||
Part::Launcher => spec.missile.is_some(),
|
||||
Part::Gun => spec.gun.is_some(),
|
||||
@@ -117,6 +112,30 @@ impl Comps {
|
||||
pub fn whole(&self) -> bool {
|
||||
self.0.iter().all(|&v| v >= 1.0)
|
||||
}
|
||||
/// Parts of this kind that are not whole, as "РЛС 40%, ходовая отказ".
|
||||
pub fn describe(&self, kind: SamKind) -> String {
|
||||
Part::ALL
|
||||
.iter()
|
||||
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
|
||||
.map(|p| match self.state(*p) {
|
||||
PartState::Failed => format!("{} отказ", p.short()),
|
||||
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
/// The weakest part alone, for a one-line status (the full list is on the monitor).
|
||||
pub fn worst(&self, kind: SamKind) -> String {
|
||||
Part::ALL
|
||||
.iter()
|
||||
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
|
||||
.min_by(|a, b| self.get(**a).total_cmp(&self.get(**b)))
|
||||
.map(|p| match self.state(*p) {
|
||||
PartState::Failed => format!("{} отказ", p.short()),
|
||||
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Health points an object loses at the centre of a blast.
|
||||
@@ -424,6 +443,9 @@ impl Sam {
|
||||
pub fn part_state(&self, p: Part) -> PartState {
|
||||
if p.on(self.kind) { self.comps.state(p) } else { PartState::Ok }
|
||||
}
|
||||
pub fn parts_text(&self) -> String {
|
||||
self.comps.describe(self.kind)
|
||||
}
|
||||
/// The aiming drive's share of its speed: a failed one doesn't turn at all.
|
||||
pub(super) fn drive_fit(&self) -> f64 {
|
||||
let h = self.part(Part::Mount);
|
||||
@@ -439,7 +461,7 @@ impl Sam {
|
||||
0.5 + 0.5 * self.part(Part::Gun)
|
||||
}
|
||||
/// Its launcher's cells still good: a damaged one holds fewer missiles.
|
||||
pub fn cells(&self) -> u32 {
|
||||
pub(super) fn cells(&self) -> u32 {
|
||||
let Some(load) = &self.kind.spec().missile else { return 0 };
|
||||
let h = self.part(Part::Launcher);
|
||||
if h <= 0.0 { 0 } else { ((load.magazine as f64 * (0.4 + 0.6 * h)).ceil() as u32).clamp(1, load.magazine) }
|
||||
@@ -453,7 +475,7 @@ impl Sam {
|
||||
}
|
||||
}
|
||||
/// Ticks a reload takes: longer with a damaged launcher.
|
||||
pub fn reload_time(&self) -> u32 {
|
||||
pub(super) fn reload_time(&self) -> u32 {
|
||||
let r = self.kind.spec().reload.max(1);
|
||||
(r as f64 * (1.0 + 1.5 * (1.0 - self.part(Part::Launcher)))).round() as u32
|
||||
}
|
||||
|
||||
@@ -85,11 +85,6 @@ impl Doctrine {
|
||||
if near <= slack {
|
||||
return true;
|
||||
}
|
||||
// One blip carries no measured course (#133): nothing says the contact passes the
|
||||
// object by, so it is not ruled out as a threat on a velocity that is not there.
|
||||
if track.hits <= 1 {
|
||||
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.
|
||||
@@ -102,24 +97,23 @@ impl Doctrine {
|
||||
(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 (as the track's estimate
|
||||
/// classes it, an unidentified contact does not count), or anything about to hit.
|
||||
pub fn matters(d: &Drone, class: ClassEst) -> bool {
|
||||
class.class() == Some(Class::Ballistic) || why::arrival(d) < why::URGENT
|
||||
/// 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, class: ClassEst) -> u8 {
|
||||
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d, class) { RESERVE } else { 0 }
|
||||
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, class: ClassEst) -> u32 {
|
||||
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
|
||||
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, class),
|
||||
Salvo::Heavy => why::needed(d, class) + 1,
|
||||
Salvo::Normal => why::needed(d),
|
||||
Salvo::Heavy => why::needed(d) + 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,22 +162,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(pos: DVec3, vel: DVec3) -> Track {
|
||||
Track {
|
||||
id: 1,
|
||||
class: ClassEst::Unknown,
|
||||
pos,
|
||||
vel,
|
||||
tick: 0,
|
||||
own_tick: 0,
|
||||
source: 0,
|
||||
product: battery::Measure::Search,
|
||||
quality: 40,
|
||||
own_product: battery::Measure::Search,
|
||||
own_quality: 0,
|
||||
ttl: 100,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
}
|
||||
Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,11 +9,6 @@
|
||||
//! picture is mixed into a replay: a recording keeps trajectories, and this section is written and
|
||||
//! read for the live simulation only.
|
||||
//!
|
||||
//! Reconnaissance flights and the partial picture they radioed home are part of the same
|
||||
//! section (#135): their marks (an area, a category and an age, never a unit's truth), the
|
||||
//! sorties still out with their pending reports, and the zones already checked. A save keeps
|
||||
//! that memory across raids, and a restored flight finishes the same way.
|
||||
//!
|
||||
//! The format is its own versioned section of `state_text` (`air 1 ...`). A save without the section
|
||||
//! (every save made before #127) loads exactly as before: the layout, and an empty sky. Every value is
|
||||
//! checked before anything is restored, like [`layout`](crate::layout): a bad line refuses the whole
|
||||
@@ -30,9 +25,6 @@ const MAX_DRONES: usize = 512;
|
||||
/// Bytes the section may take before further drones are left out (the host allows 1 MiB a write;
|
||||
/// the layout and the headroom of the rest of the state stay clear of it).
|
||||
const MAX_BYTES: usize = 900_000;
|
||||
/// Bytes the recon block (marks, checked zones, sorties) may take. The drone loop keeps this much
|
||||
/// room free, so the recon memory never pushes the section past `MAX_BYTES` (#135).
|
||||
const MAX_RECON_BYTES: usize = 150_000;
|
||||
/// Route points one drone may have in a save.
|
||||
const MAX_ROUTE: usize = 512;
|
||||
/// Contacts (the picture, and a job's picture rebuilt from it) a save may hold.
|
||||
@@ -40,10 +32,6 @@ const MAX_CONTACTS: usize = 4096;
|
||||
/// Relief versions a save may hold, and the cells of each.
|
||||
const MAX_RELIEFS: usize = 8;
|
||||
const MAX_CELLS: usize = 40_000;
|
||||
/// Recon marks, checked zones and sorties a save may hold (#135).
|
||||
const MAX_RECON_MARKS: usize = recon::MAX_MARKS;
|
||||
const MAX_RECON_CHECKED: usize = recon::MAX_CHECKED;
|
||||
const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2;
|
||||
|
||||
/// What the air section of a save holds, checked as a whole before the scene is touched.
|
||||
pub struct AirSave {
|
||||
@@ -57,8 +45,6 @@ pub struct AirSave {
|
||||
jobs: Vec<JobRec>,
|
||||
/// The land new retarget jobs take as their version.
|
||||
known_relief: Option<std::sync::Arc<ew::KnownRelief>>,
|
||||
/// The enemy's recon flights and the partial picture they radioed home (#135).
|
||||
recon: recon::Recon,
|
||||
}
|
||||
|
||||
pub(crate) struct JobRec {
|
||||
@@ -212,7 +198,6 @@ impl Sim {
|
||||
^ (self.retargets.len() as u64) << 24
|
||||
^ (self.intel.contacts().len() as u64) << 36
|
||||
^ (self.job_next as u64) << 48
|
||||
^ self.recon.mark().rotate_left(12)
|
||||
}
|
||||
|
||||
/// The air section of the state text: `None` when there is nothing to keep (an empty sky and no
|
||||
@@ -288,7 +273,7 @@ impl Sim {
|
||||
// job with it (a job whose drone is not saved could never be restored).
|
||||
let mut body = String::new();
|
||||
let mut saved: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() + MAX_RECON_BYTES <= MAX_BYTES;
|
||||
let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= MAX_BYTES;
|
||||
let mut drone_count = 0usize;
|
||||
for d in &drones {
|
||||
let line = d.air_line("airdrone", "");
|
||||
@@ -311,15 +296,14 @@ impl Sim {
|
||||
saved.insert(d.id);
|
||||
queued_count += 1;
|
||||
}
|
||||
// A job's unit may be an exact contact or a recon mark's synthetic id (#135).
|
||||
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).chain(self.recon.marks.keys().copied()).collect();
|
||||
let units: std::collections::HashSet<u32> = contacts.iter().map(|c| c.id).collect();
|
||||
let jobs: Vec<(&ew::RouteJob, Option<usize>)> = self
|
||||
.retargets
|
||||
.iter()
|
||||
.zip(job_relief)
|
||||
.filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit)))
|
||||
.collect();
|
||||
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() {
|
||||
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let head = head.replacen(
|
||||
@@ -344,89 +328,6 @@ impl Sim {
|
||||
relief.map_or_else(|| "-".into(), |t| t.to_string())
|
||||
);
|
||||
}
|
||||
// Recon: the marks are memory (survive a new raid), the sorties are the aircraft still
|
||||
// out, and the zones already reported empty. Everything is bounded, and each line is
|
||||
// added only while the block stays inside its budget (#135).
|
||||
if !self.recon.is_empty() {
|
||||
let room = MAX_RECON_BYTES.min(MAX_BYTES.saturating_sub(text.len() + 96));
|
||||
let mut recon_body = String::new();
|
||||
let mut add = |line: &str| -> bool {
|
||||
if recon_body.len() + line.len() > room {
|
||||
return false;
|
||||
}
|
||||
recon_body.push_str(line);
|
||||
true
|
||||
};
|
||||
let mut marks = 0usize;
|
||||
for m in self.recon.marks.values().take(MAX_RECON_MARKS) {
|
||||
let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0);
|
||||
let line = format!(
|
||||
"airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
|
||||
m.id,
|
||||
truth,
|
||||
coord(m.area.x),
|
||||
coord(m.area.y),
|
||||
coord(m.area.z),
|
||||
coord(m.radius),
|
||||
m.category.name(),
|
||||
m.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
|
||||
m.source.name(),
|
||||
m.quality.name(),
|
||||
m.observed,
|
||||
m.reported,
|
||||
m.looks,
|
||||
);
|
||||
if !add(&line) {
|
||||
break;
|
||||
}
|
||||
marks += 1;
|
||||
}
|
||||
let mut checked = 0usize;
|
||||
for ((i, j), t) in self.recon.checked.iter().take(MAX_RECON_CHECKED) {
|
||||
if !add(&format!("airreconchecked {i} {j} {t}\n")) {
|
||||
break;
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
let mut sorties = 0usize;
|
||||
for s in self.recon.sorties.iter().filter(|s| saved.contains(&s.drone)).take(MAX_RECON_SORTIES) {
|
||||
// A sortie is written whole or not at all: its look and zone lines follow its header.
|
||||
let mut body = format!(
|
||||
"airrec {} {} {} {} {} {} {}\n",
|
||||
s.drone,
|
||||
s.launched,
|
||||
s.next,
|
||||
tick(s.report_at),
|
||||
s.report_zone.map_or_else(|| "-".into(), |z| z.to_string()),
|
||||
s.pending.len(),
|
||||
s.zones.len(),
|
||||
);
|
||||
for l in &s.pending {
|
||||
body += &format!(
|
||||
"airrecobs {} {} {} {} {} {} {} {} {} {}\n",
|
||||
l.truth,
|
||||
coord(l.area.x),
|
||||
coord(l.area.y),
|
||||
coord(l.area.z),
|
||||
coord(l.radius),
|
||||
l.category.name(),
|
||||
l.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()),
|
||||
l.quality.name(),
|
||||
l.source.name(),
|
||||
l.observed,
|
||||
);
|
||||
}
|
||||
for z in &s.zones {
|
||||
body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius));
|
||||
}
|
||||
if !add(&body) {
|
||||
break;
|
||||
}
|
||||
sorties += 1;
|
||||
}
|
||||
text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked);
|
||||
text += &recon_body;
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
|
||||
@@ -472,12 +373,6 @@ impl Sim {
|
||||
let mut drones: BTreeMap<u32, Drone> = BTreeMap::new();
|
||||
let mut queue: Vec<(u64, Drone)> = Vec::new();
|
||||
let mut jobs: Vec<JobRec> = Vec::new();
|
||||
// Recon (#135): a mark line carries the unit it is of (the observer's secret, never in
|
||||
// the planner's picture); a sortie's look and zone lines follow its header.
|
||||
let mut recon = recon::Recon::default();
|
||||
let mut recon_head: Option<(usize, usize, usize)> = None;
|
||||
let mut recon_sortie_at: Option<usize> = None;
|
||||
let mut recon_expect: Vec<(usize, usize)> = Vec::new();
|
||||
for (n, w) in &lines {
|
||||
if w.first() == Some(&"air") {
|
||||
continue;
|
||||
@@ -617,148 +512,6 @@ impl Sim {
|
||||
};
|
||||
jobs.push(JobRec { id, drone, aim, unit, version, intent, relief });
|
||||
}
|
||||
"airrecon" => {
|
||||
if w.len() != 6 {
|
||||
return Err(l.bad("разведка", "нужны счётчики отметок и дронов, отметки, разведчики и проверенные зоны"));
|
||||
}
|
||||
let next = l.int(1, "счётчик отметок", 0, i64::from(recon::MARK_TOP - recon::ID_BASE - 1))? as u32;
|
||||
let drone_next = l.int(2, "счётчик дронов", 0, i64::from(recon::DRONE_TOP - recon::DRONE_BASE - 1))? as u32;
|
||||
let marks = l.count(3, "отметки", MAX_RECON_MARKS)?;
|
||||
let sorties = l.count(4, "разведчики", MAX_RECON_SORTIES)?;
|
||||
let checked = l.count(5, "проверенные зоны", MAX_RECON_CHECKED)?;
|
||||
if recon_head.is_some() {
|
||||
return Err(l.bad("разведка", "заголовок записан дважды"));
|
||||
}
|
||||
recon_head = Some((marks, sorties, checked));
|
||||
recon.next = next;
|
||||
recon.drone_next = drone_next;
|
||||
}
|
||||
"airreconmark" => {
|
||||
if w.len() != 14 {
|
||||
return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена"));
|
||||
}
|
||||
let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32;
|
||||
if !recon::is_mark(id) {
|
||||
return Err(l.bad("id отметки", "не в диапазоне отметок"));
|
||||
}
|
||||
let truth = l.int(2, "юнит отметки", 0, 1 << 30)? as u32;
|
||||
let area = DVec3::new(l.num(3, "отметка X")?, l.num(4, "отметка Y")?, l.num(5, "отметка Z")?);
|
||||
let radius = l.num(6, "радиус отметки")?;
|
||||
if radius <= 0.0 {
|
||||
return Err(l.bad("радиус отметки", "должен быть больше нуля"));
|
||||
}
|
||||
let category = recon::Category::from_key(l.word(7, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
|
||||
let role = match l.word(8, "роль")? {
|
||||
"-" => None,
|
||||
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
|
||||
};
|
||||
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
|
||||
let quality = recon::Quality::from_key(l.word(10, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
|
||||
let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64;
|
||||
let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64;
|
||||
let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16;
|
||||
if recon.marks.contains_key(&id) {
|
||||
return Err(l.bad("id отметки", "отметка записана дважды"));
|
||||
}
|
||||
recon.truth.insert(id, truth);
|
||||
recon.marks.insert(id, recon::Mark {
|
||||
id,
|
||||
area,
|
||||
radius,
|
||||
category,
|
||||
role,
|
||||
source,
|
||||
observed,
|
||||
reported,
|
||||
quality,
|
||||
looks,
|
||||
});
|
||||
let slot = id.saturating_sub(recon::ID_BASE);
|
||||
recon.next = recon.next.max(slot);
|
||||
}
|
||||
"airreconchecked" => {
|
||||
if w.len() != 4 {
|
||||
return Err(l.bad("проверенная зона", "нужны X, Z и такт"));
|
||||
}
|
||||
let i = l.int(1, "зона X", -3_000_000, 3_000_000)?;
|
||||
let j = l.int(2, "зона Z", -3_000_000, 3_000_000)?;
|
||||
let t = l.int(3, "такт проверки", 0, tick as i64)? as u64;
|
||||
recon.checked.insert((i, j), t);
|
||||
}
|
||||
"airrec" => {
|
||||
if w.len() != 8 {
|
||||
return Err(l.bad("разведчик", "нужны дрон, вылет, зона, донесение и счётчики"));
|
||||
}
|
||||
let drone = l.int(1, "дрон разведчика", 1, 1 << 30)? as u32;
|
||||
let launched = l.int(2, "вылет", 0, tick as i64)? as u64;
|
||||
let next = l.count(3, "следующая зона", 1_000_000)?;
|
||||
let report_at = l.opt_tick(4, "такт донесения")?;
|
||||
let report_zone = match l.word(5, "зона донесения")? {
|
||||
"-" => None,
|
||||
v => Some(v.parse::<usize>().map_err(|_| l.bad("зона донесения", "не номер"))?),
|
||||
};
|
||||
let pending = l.count(6, "ожидающие наблюдения", recon::MAX_OBSERVED)?;
|
||||
let zones = l.count(7, "зоны разведчика", recon::ZONES_MAX)?;
|
||||
if recon.sorties.iter().any(|s| s.drone == drone) {
|
||||
return Err(l.bad("дрон разведчика", "разведчик записан дважды"));
|
||||
}
|
||||
recon.sorties.push(recon::Sortie {
|
||||
drone,
|
||||
zones: Vec::new(),
|
||||
next,
|
||||
launched,
|
||||
report_at,
|
||||
report_zone,
|
||||
pending: Vec::new(),
|
||||
});
|
||||
recon_sortie_at = Some(recon.sorties.len() - 1);
|
||||
recon_expect.push((pending, zones));
|
||||
}
|
||||
"airrecobs" => {
|
||||
if w.len() != 11 {
|
||||
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт"));
|
||||
}
|
||||
let Some(at) = recon_sortie_at else {
|
||||
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
|
||||
};
|
||||
let (want, _) = recon_expect[at];
|
||||
if recon.sorties[at].pending.len() >= want {
|
||||
return Err(l.bad("наблюдение разведки", "наблюдений больше объявленного"));
|
||||
}
|
||||
let truth = l.int(1, "юнит наблюдения", 0, 1 << 30)? as u32;
|
||||
let area = DVec3::new(l.num(2, "наблюдение X")?, l.num(3, "наблюдение Y")?, l.num(4, "наблюдение Z")?);
|
||||
let radius = l.num(5, "радиус наблюдения")?;
|
||||
if radius <= 0.0 {
|
||||
return Err(l.bad("радиус наблюдения", "должен быть больше нуля"));
|
||||
}
|
||||
let category = recon::Category::from_key(l.word(6, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?;
|
||||
let role = match l.word(7, "роль")? {
|
||||
"-" => None,
|
||||
key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?),
|
||||
};
|
||||
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
|
||||
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
|
||||
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
|
||||
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
|
||||
}
|
||||
"airreczone" => {
|
||||
if w.len() != 5 {
|
||||
return Err(l.bad("зона разведчика", "нужны X, Y, Z и радиус"));
|
||||
}
|
||||
let Some(at) = recon_sortie_at else {
|
||||
return Err(l.bad("зона разведчика", "строка без разведчика"));
|
||||
};
|
||||
let (_, want) = recon_expect[at];
|
||||
if recon.sorties[at].zones.len() >= want {
|
||||
return Err(l.bad("зона разведчика", "зон больше объявленного"));
|
||||
}
|
||||
let center = DVec3::new(l.num(1, "зона X")?, l.num(2, "зона Y")?, l.num(3, "зона Z")?);
|
||||
let radius = l.num(4, "радиус зоны")?;
|
||||
if radius <= 0.0 {
|
||||
return Err(l.bad("радиус зоны", "должен быть больше нуля"));
|
||||
}
|
||||
recon.sorties[at].zones.push(recon::Zone { center, radius });
|
||||
}
|
||||
other => return Err(l.bad("строка", &format!("неизвестная строка воздушной части «{other}»"))),
|
||||
}
|
||||
}
|
||||
@@ -787,32 +540,6 @@ impl Sim {
|
||||
if let Some(g) = global && reliefs[g].is_none() {
|
||||
return Err("воздушная часть: глобальный рельеф не записан".into());
|
||||
}
|
||||
if let Some((marks, sorties, checked)) = recon_head {
|
||||
if recon.marks.len() != marks {
|
||||
return Err(format!("воздушная часть: отметок разведки {} вместо {marks}", recon.marks.len()));
|
||||
}
|
||||
if recon.sorties.len() != sorties {
|
||||
return Err(format!("воздушная часть: разведчиков {} вместо {sorties}", recon.sorties.len()));
|
||||
}
|
||||
if recon.checked.len() != checked {
|
||||
return Err(format!("воздушная часть: проверенных зон {} вместо {checked}", recon.checked.len()));
|
||||
}
|
||||
} else if !recon.is_empty() {
|
||||
return Err("воздушная часть: разведка без заголовка airrecon".into());
|
||||
}
|
||||
for (i, (pending, zones)) in recon_expect.iter().enumerate() {
|
||||
if recon.sorties[i].pending.len() != *pending || recon.sorties[i].zones.len() != *zones {
|
||||
return Err(format!("воздушная часть: разведчик {i} записан не полностью"));
|
||||
}
|
||||
if recon.sorties[i].next > recon.sorties[i].zones.len() {
|
||||
return Err(format!("воздушная часть: разведчик {i} смотрит за пределами зон"));
|
||||
}
|
||||
if let Some(z) = recon.sorties[i].report_zone
|
||||
&& z >= recon.sorties[i].zones.len()
|
||||
{
|
||||
return Err(format!("воздушная часть: разведчик {i} доносит из несуществующей зоны"));
|
||||
}
|
||||
}
|
||||
let intel = intel.ok_or("воздушная часть: нет счётчиков секторов")?;
|
||||
let mut kills = [0u32; ew::SECTORS];
|
||||
let mut hits = [0u32; ew::SECTORS];
|
||||
@@ -828,7 +555,6 @@ impl Sim {
|
||||
queue,
|
||||
jobs,
|
||||
known_relief: global.and_then(|g| reliefs[g].clone()),
|
||||
recon,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -845,10 +571,6 @@ impl Sim {
|
||||
self.known_relief = save.known_relief;
|
||||
self.drones = save.drones;
|
||||
self.queue = save.queue;
|
||||
self.recon = save.recon;
|
||||
let alive: std::collections::HashSet<u32> = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect();
|
||||
self.recon.retain_drones(&alive);
|
||||
self.recon.expire(self.tick);
|
||||
self.retargets.clear();
|
||||
// A job's picture is its version's: the contacts observed no later than it, plus its own
|
||||
// target (whose last saved observation stands in for one made after the version).
|
||||
|
||||
+31
-198
@@ -19,12 +19,6 @@
|
||||
//! contact is a plain function of the contact's age, and its idea of a unit's
|
||||
//! capabilities is the type's published one — a contact says nothing about
|
||||
//! damage, roles, link health or magazine.
|
||||
//!
|
||||
//! A smart raid may also send a few recon aircraft ahead (#135). What they see is a
|
||||
//! different, coarser kind of knowledge: an area, a public category, the channel that
|
||||
//! showed it and its age, radioed home only after a delay and only while the aircraft
|
||||
//! lives. It is kept as a `recon::Mark`, separate from a disclosure `Contact`; its
|
||||
//! confidence is age alone and a duplicate report does not improve it.
|
||||
use super::*;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
@@ -329,15 +323,6 @@ pub(super) const CONTACT_TTL: u64 = 6000;
|
||||
const CONFIRMED_AGE: u64 = 600;
|
||||
const PROBABLE_AGE: u64 = 3000;
|
||||
|
||||
/// The one source of confidence: a contact's age, in the bands the picture trusts.
|
||||
pub(super) fn confidence_for_age(age: u64) -> Confidence {
|
||||
match age {
|
||||
0..=CONFIRMED_AGE => Confidence::Confirmed,
|
||||
..=PROBABLE_AGE => Confidence::Probable,
|
||||
_ => Confidence::Doubtful,
|
||||
}
|
||||
}
|
||||
|
||||
impl Contact {
|
||||
pub fn age(&self, now: u64) -> u64 {
|
||||
now.saturating_sub(self.tick)
|
||||
@@ -347,7 +332,11 @@ impl Contact {
|
||||
self.destroyed.is_none() && self.age(now) < CONTACT_TTL
|
||||
}
|
||||
pub fn confidence(&self, now: u64) -> Confidence {
|
||||
confidence_for_age(self.age(now))
|
||||
match self.age(now) {
|
||||
0..=CONFIRMED_AGE => Confidence::Confirmed,
|
||||
..=PROBABLE_AGE => Confidence::Probable,
|
||||
_ => Confidence::Doubtful,
|
||||
}
|
||||
}
|
||||
/// Whether the enemy believes this unit sees on its own radar (#127). A kind without a
|
||||
/// sensor never does. A kind with one does while an emission fix of this contact is
|
||||
@@ -567,9 +556,6 @@ impl Sim {
|
||||
/// Whether the picture holds a live contact for this unit: what the old revelation log
|
||||
/// answered at a scan, now one map lookup.
|
||||
pub(super) fn known_live(&self, id: u32) -> bool {
|
||||
if recon::is_mark(id) {
|
||||
return self.recon.live(id, self.tick);
|
||||
}
|
||||
self.intel.contacts.get(&id).is_some_and(|c| c.live(self.tick))
|
||||
}
|
||||
|
||||
@@ -592,10 +578,8 @@ impl Sim {
|
||||
/// the picture killed is a distinct, lower-priority decision.
|
||||
fn adapt_targets(&mut self) {
|
||||
self.intel.expire(self.tick);
|
||||
self.recon.expire(self.tick);
|
||||
let picture = Arc::new(self.picture_of_defences());
|
||||
let leads = self.recon.leads(self.tick);
|
||||
if picture.is_empty() && leads.is_empty() {
|
||||
if picture.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Every job of this adaptive tick plans over the same relief version, even if another smart
|
||||
@@ -617,17 +601,9 @@ impl Sim {
|
||||
if !eligible {
|
||||
continue;
|
||||
}
|
||||
// A recon mark is an area, not a unit: it is kept while the mark lives. A
|
||||
// hidden move does not move the aim; only a newer report can re-place it (#135).
|
||||
if recon::is_mark(d.aim.unit) {
|
||||
if self.recon.live(d.aim.unit, now) {
|
||||
continue;
|
||||
}
|
||||
// The mark aged out: the drone falls through to a fresh lead below.
|
||||
}
|
||||
// What it is aiming at in the picture now, if anything (a unit merely moved is still
|
||||
// aimed where it was seen: a contact is matched by its observed place).
|
||||
else if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
|
||||
if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) {
|
||||
// Already aiming at a unit: a fresh disclosure may be worth a switch, under the throttle.
|
||||
let Some(c) = Self::switch_candidate(&picture, current, d, now) else { continue };
|
||||
if per_contact.get(&c.id).copied().unwrap_or(0) >= ASSIGN_PER_CONTACT {
|
||||
@@ -651,30 +627,13 @@ impl Sim {
|
||||
if assigned >= ASSIGN_PER_TICK {
|
||||
continue;
|
||||
}
|
||||
let exact = Self::fresh_target(&picture, &per_contact, d.kind, n);
|
||||
// No disclosure contact to take: a recon mark whose observed role fits this drone,
|
||||
// best role and freshest first, bounded per mark as any assignment is. Where both
|
||||
// exist, the better observed role and fresher mark wins; a hidden unit is in neither.
|
||||
let mark = Self::fresh_recon_target(&leads, &per_contact);
|
||||
let (at, unit, confidence) = match (exact, mark) {
|
||||
(Some(c), Some(m)) => {
|
||||
let exact_rank = Self::exact_rank(&c, now);
|
||||
if m.priority(now) > exact_rank {
|
||||
(m.area, m.id, m.confidence(now))
|
||||
} else {
|
||||
(c.at, c.id, c.confidence(now))
|
||||
}
|
||||
}
|
||||
(Some(c), None) => (c.at, c.id, c.confidence(now)),
|
||||
(None, Some(m)) => (m.area, m.id, m.confidence(now)),
|
||||
(None, None) => continue,
|
||||
};
|
||||
*per_contact.entry(unit).or_insert(0) += 1;
|
||||
let Some(c) = Self::fresh_target(&picture, &per_contact, d.kind, n) else { continue };
|
||||
*per_contact.entry(c.id).or_insert(0) += 1;
|
||||
assigned += 1;
|
||||
d.target = at + d.err;
|
||||
d.target = c.at + d.err;
|
||||
d.intent = Intent::React;
|
||||
// A first assignment is not a switch: the aim's clock starts here, the count is kept.
|
||||
d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) };
|
||||
d.aim = Aim { unit: c.id, since: now, switches: d.aim.switches, confidence: Some(c.confidence(now)) };
|
||||
if Self::route_plannable(d) {
|
||||
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone()));
|
||||
job_next += 1;
|
||||
@@ -689,14 +648,11 @@ impl Sim {
|
||||
// moved is still aimed where seen.
|
||||
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) {
|
||||
let aim = d.target - d.err;
|
||||
let aim_gone = if recon::is_mark(d.aim.unit) {
|
||||
!self.recon.live(d.aim.unit, self.tick)
|
||||
} else {
|
||||
self.intel
|
||||
.contacts
|
||||
.values()
|
||||
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick))
|
||||
};
|
||||
let aim_gone = self
|
||||
.intel
|
||||
.contacts
|
||||
.values()
|
||||
.any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick));
|
||||
if !aim_gone {
|
||||
continue;
|
||||
}
|
||||
@@ -707,37 +663,17 @@ impl Sim {
|
||||
if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK {
|
||||
continue;
|
||||
}
|
||||
let exact = picture
|
||||
let next = picture
|
||||
.iter()
|
||||
.filter(|c| !plannable || Self::can_turn_to(d, c.at))
|
||||
.filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
|
||||
.map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now)))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mark = leads
|
||||
.iter()
|
||||
.filter(|m| !plannable || Self::can_turn_to(d, m.area))
|
||||
.filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
|
||||
.map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now)))
|
||||
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)));
|
||||
// A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal
|
||||
// freshness is preferred, because it is a fix rather than an area.
|
||||
let exact_rank = exact.map(|(_, _, _, c)| match c {
|
||||
Confidence::Confirmed => 30,
|
||||
Confidence::Probable => 15,
|
||||
Confidence::Doubtful => 0,
|
||||
});
|
||||
let next = match (exact, mark) {
|
||||
(Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)),
|
||||
(Some(e), _) => Some(e),
|
||||
(None, Some(m)) => Some((m.0, m.1, m.2, m.3)),
|
||||
(None, None) => None,
|
||||
};
|
||||
if let Some((_, unit, at, confidence)) = next {
|
||||
*per_contact.entry(unit).or_insert(0) += 1;
|
||||
.min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos)));
|
||||
if let Some(c) = next {
|
||||
*per_contact.entry(c.id).or_insert(0) += 1;
|
||||
assigned += 1;
|
||||
d.target = at + d.err;
|
||||
d.target = c.at + d.err;
|
||||
d.intent = Intent::Replace;
|
||||
d.aim = d.aim.replaced(unit, now, confidence);
|
||||
d.aim = d.aim.replaced(c.id, now, c.confidence(now));
|
||||
if plannable {
|
||||
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone()));
|
||||
job_next += 1;
|
||||
@@ -780,28 +716,6 @@ impl Sim {
|
||||
all.get(n % all.len().max(1)).map(|c| **c)
|
||||
}
|
||||
|
||||
/// The rank of an exact disclosure contact: its confidence, what its observed kind is
|
||||
/// worth, and a small premium for being a fix rather than an area.
|
||||
fn exact_rank(c: &Contact, now: u64) -> u8 {
|
||||
let seen = match c.confidence(now) {
|
||||
Confidence::Confirmed => 30,
|
||||
Confidence::Probable => 15,
|
||||
Confidence::Doubtful => 0,
|
||||
};
|
||||
seen + recon::Category::of(c.kind).weight() + 3
|
||||
}
|
||||
|
||||
/// The best recon mark a drone not yet sent at a unit may be given: observed role and
|
||||
/// freshness first (the list is sorted), bounded per mark. A mark's category must be one
|
||||
/// worth a strike; a support or unknown mark is only navigation interest.
|
||||
fn fresh_recon_target(leads: &[recon::Mark], per_contact: &HashMap<u32, usize>) -> Option<recon::Mark> {
|
||||
leads
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|m| m.category.weight() >= 2)
|
||||
.find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
|
||||
}
|
||||
|
||||
/// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the
|
||||
/// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the
|
||||
/// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new
|
||||
@@ -1095,7 +1009,7 @@ pub struct ContactReport {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AimReport {
|
||||
pub drone: u32,
|
||||
/// The unit aimed at (0: a marked object; a recon mark has a synthetic id).
|
||||
/// The unit aimed at (0: a marked object).
|
||||
pub unit: u32,
|
||||
/// "plan", "sead", "react" or "replace".
|
||||
pub intent: &'static str,
|
||||
@@ -1105,43 +1019,6 @@ pub struct AimReport {
|
||||
pub switches: u16,
|
||||
/// The confidence of the contact the aim rests on, when it is a unit.
|
||||
pub confidence: Option<Confidence>,
|
||||
/// Whether the aim is a recon mark's area rather than a unit contact.
|
||||
pub recon: bool,
|
||||
/// A recon mark's priority (observed role, freshness, quality); `None` for a unit contact.
|
||||
pub priority: Option<u8>,
|
||||
}
|
||||
|
||||
/// A recon mark as the diagnostic reports it (#135): an area, a coarse category, the channel,
|
||||
/// its age and quality. There is no true place, SamKind, health, magazine, link or real id here.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ReconReport {
|
||||
pub id: u32,
|
||||
pub area: DVec3,
|
||||
pub radius: f64,
|
||||
/// "unknown", "radar", "launcher", "gun", "ew" or "support".
|
||||
pub category: &'static str,
|
||||
/// A radar's role once a refined look told it.
|
||||
pub role: Option<&'static str>,
|
||||
/// "flyby", "emission", "jamming" or "launch".
|
||||
pub source: &'static str,
|
||||
pub age: u64,
|
||||
/// "coarse" or "refined".
|
||||
pub quality: &'static str,
|
||||
pub confidence: Confidence,
|
||||
pub live: bool,
|
||||
/// What the planner makes of it, in words: observed role and freshness only.
|
||||
pub priority: u8,
|
||||
}
|
||||
|
||||
/// One recon sortie as the diagnostic reports it (#135).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ReconSortieReport {
|
||||
pub drone: u32,
|
||||
/// "outbound", "looking", "reporting" or "done".
|
||||
pub phase: &'static str,
|
||||
pub zones_left: usize,
|
||||
/// The tick its pending report is due.
|
||||
pub report_in: Option<u64>,
|
||||
}
|
||||
|
||||
/// A route job the planner has not finished (#127): what it is for, why it is still waiting,
|
||||
@@ -1175,10 +1052,6 @@ pub struct EnemyPictureReport {
|
||||
pub pending: Vec<PendingReport>,
|
||||
/// The planner's work a tick, for the pending queue's budget.
|
||||
pub work_per_tick: usize,
|
||||
/// The partial picture recon flights radioed home (#135).
|
||||
pub recon: Vec<ReconReport>,
|
||||
/// The recon flights still out.
|
||||
pub recon_sorties: Vec<ReconSortieReport>,
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
@@ -1226,18 +1099,13 @@ impl Sim {
|
||||
.map(|(_, d)| d)
|
||||
.chain(self.drones.iter())
|
||||
.filter(|d| d.alive() && d.smart)
|
||||
.map(|d| {
|
||||
let mark = self.recon.marks.get(&d.aim.unit).filter(|m| m.live(now)).copied();
|
||||
AimReport {
|
||||
drone: d.id,
|
||||
unit: d.aim.unit,
|
||||
intent: d.intent.name(),
|
||||
since: d.aim.since,
|
||||
switches: d.aim.switches,
|
||||
confidence: d.aim.confidence,
|
||||
recon: mark.is_some(),
|
||||
priority: mark.map(|m| m.priority(now)),
|
||||
}
|
||||
.map(|d| AimReport {
|
||||
drone: d.id,
|
||||
unit: d.aim.unit,
|
||||
intent: d.intent.name(),
|
||||
since: d.aim.since,
|
||||
switches: d.aim.switches,
|
||||
confidence: d.aim.confidence,
|
||||
})
|
||||
.collect();
|
||||
let pending = self
|
||||
@@ -1261,42 +1129,7 @@ impl Sim {
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let recon = self
|
||||
.recon
|
||||
.marks
|
||||
.values()
|
||||
.map(|m| ReconReport {
|
||||
id: m.id,
|
||||
area: m.area,
|
||||
radius: m.radius,
|
||||
category: m.category.name(),
|
||||
role: m.role.map(|r| r.key()),
|
||||
source: m.source.name(),
|
||||
age: m.age(now),
|
||||
quality: m.quality.name(),
|
||||
confidence: m.confidence(now),
|
||||
live: m.live(now),
|
||||
priority: m.priority(now),
|
||||
})
|
||||
.collect();
|
||||
let recon_sorties = self
|
||||
.recon
|
||||
.sorties
|
||||
.iter()
|
||||
.map(|s| ReconSortieReport {
|
||||
drone: s.drone,
|
||||
phase: if s.report_at.is_some() {
|
||||
"reporting"
|
||||
} else if s.next < s.zones.len() {
|
||||
"outbound"
|
||||
} else {
|
||||
"done"
|
||||
},
|
||||
zones_left: s.zones.len().saturating_sub(s.next),
|
||||
report_in: s.report_at.map(|t| t.saturating_sub(now)),
|
||||
})
|
||||
.collect();
|
||||
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties }
|
||||
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK }
|
||||
}
|
||||
|
||||
/// What the planner makes of a contact, in words for the diagnostic (#127).
|
||||
|
||||
+60
-195
@@ -25,11 +25,8 @@ pub mod record;
|
||||
mod sight;
|
||||
mod terrain;
|
||||
mod ew;
|
||||
mod optical;
|
||||
mod recon;
|
||||
mod durable;
|
||||
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport, ReconReport, ReconSortieReport};
|
||||
pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts};
|
||||
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport};
|
||||
pub mod lights;
|
||||
mod logistics;
|
||||
mod orders;
|
||||
@@ -48,9 +45,6 @@ mod sensor_tests;
|
||||
pub use ew::EW_RADIUS;
|
||||
pub use damage::{Comps, Part, PartState};
|
||||
pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS};
|
||||
pub use optical::{Optical, OpticalClassEstimate, OpticalObservation, OpticalObservable, OpticalReport, OpticalState, SightBlock};
|
||||
/// The passive optical post's clear-day reach (the monitor's scale reads it).
|
||||
pub const OPTICAL_RANGE: f64 = optical::RANGE;
|
||||
use damage::dice;
|
||||
use outcome::{Impact, Outcome};
|
||||
pub use units::{Family, SamKind};
|
||||
@@ -177,11 +171,6 @@ impl Rng {
|
||||
pub fn state(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
/// Puts the generator back exactly where it was (a recon launch must not spend the
|
||||
/// strike's combat randomness).
|
||||
pub(super) fn set_state(&mut self, state: u64) {
|
||||
self.0 = state;
|
||||
}
|
||||
pub fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
@@ -585,135 +574,11 @@ impl Class {
|
||||
Class::Ballistic => "Б",
|
||||
}
|
||||
}
|
||||
/// The class as one object ("дрон", "крылатая ракета"): what a track's estimate reads as.
|
||||
pub fn singular(self) -> &'static str {
|
||||
match self {
|
||||
Class::Drone => "дрон",
|
||||
Class::Jet => "реакт. дрон",
|
||||
Class::Cruise => "крылатая ракета",
|
||||
Class::Supersonic => "сверхзвуковая ракета",
|
||||
Class::Ballistic => "баллистическая ракета",
|
||||
}
|
||||
}
|
||||
/// The class a measured speed (blocks a tick) says: the classifier's bands (#133), between the
|
||||
/// game's own speed clusters, so a slow propeller drone is never read as a jet. Contacts near a
|
||||
/// boundary can sit in the wrong class for a while, or stay undecided between measurements:
|
||||
/// there is no "three blips and the mark is known". A fast ballistic and a supersonic missile
|
||||
/// fly alike (their bands overlap): only speed cannot tell them apart, and the first version
|
||||
/// does not model the flight profile that would.
|
||||
pub fn of_speed(v: f64) -> Class {
|
||||
if v < 1.35 {
|
||||
Class::Drone
|
||||
} else if v < 1.9 {
|
||||
Class::Jet
|
||||
} else if v < 3.0 {
|
||||
Class::Cruise
|
||||
} else if v < 6.5 {
|
||||
Class::Supersonic
|
||||
} else {
|
||||
Class::Ballistic
|
||||
}
|
||||
}
|
||||
pub fn from_key(key: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.key() == key)
|
||||
}
|
||||
}
|
||||
|
||||
/// An optical observation this unsure (0 best, 1 worst) names no class for the network (#136):
|
||||
/// the post still shows its own look, but the shared estimate keeps what the radars made of it.
|
||||
pub const OPTICAL_CLASS_MAX_UNCERTAINTY: f64 = 0.5;
|
||||
|
||||
/// What the radars make of a track's class, from the measurements alone (#133): separate from
|
||||
/// the track's confirmation (`Track::ident`, how firmly it is held), its own state with its own
|
||||
/// rules. It travels with the measurement it grew from: a relay passes it as it was, ageing with
|
||||
/// the track, and it is gone when the track drops — a re-detected contact starts over.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum ClassEst {
|
||||
/// One measurement yet: something is there, its class is not.
|
||||
Unknown,
|
||||
/// Measured again: a class by how it flies; a new contrary measurement can still change it.
|
||||
Probable(Class),
|
||||
/// Several measurements agreed: high confidence.
|
||||
Firm(Class),
|
||||
}
|
||||
|
||||
impl ClassEst {
|
||||
/// The class it holds, if any.
|
||||
pub fn class(self) -> Option<Class> {
|
||||
match self {
|
||||
ClassEst::Unknown => None,
|
||||
ClassEst::Probable(c) | ClassEst::Firm(c) => Some(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// The estimate stepped by one more measurement that saw `speed`, `hits` of them so far (#133):
|
||||
/// the first says nothing; the second names a class by its speed; each further agreeing
|
||||
/// measurement firms it up, a contrary one replaces the hypothesis with the new guess.
|
||||
/// Pure arithmetic on the measurement: nothing random, nothing from the target itself.
|
||||
pub fn step(self, hits: u8, speed: f64) -> ClassEst {
|
||||
let seen = Class::of_speed(speed);
|
||||
match (self, hits) {
|
||||
(_, 1) => ClassEst::Unknown,
|
||||
(_, 2) => ClassEst::Probable(seen),
|
||||
(ClassEst::Firm(had), _) if had == seen => ClassEst::Firm(had),
|
||||
(ClassEst::Probable(had), _) if had == seen => ClassEst::Firm(had),
|
||||
_ => ClassEst::Probable(seen),
|
||||
}
|
||||
}
|
||||
|
||||
/// The estimate stepped by one passive optical observation (#136): an independent look at the
|
||||
/// same contact, never a radar measurement and never a relay. A look too unsure to name a
|
||||
/// class (uncertainty over [`OPTICAL_CLASS_MAX_UNCERTAINTY`]) changes nothing. A sure look
|
||||
/// names a class where none was, firms a probable one that agrees, and replaces a contrary
|
||||
/// hypothesis with the new guess — the same arithmetic as [`Self::step`], fed by the optics
|
||||
/// instead of the beam. It touches the class alone: no plot, no freshness and no fire right
|
||||
/// travels with it, and a relay of the refined track carries the class as it was.
|
||||
pub fn step_optical(self, class: Class, uncertainty: f64) -> ClassEst {
|
||||
if uncertainty > OPTICAL_CLASS_MAX_UNCERTAINTY {
|
||||
return self;
|
||||
}
|
||||
match self {
|
||||
ClassEst::Unknown => ClassEst::Probable(class),
|
||||
ClassEst::Probable(had) | ClassEst::Firm(had) if had == class => ClassEst::Firm(had),
|
||||
_ => ClassEst::Probable(class),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a system's roles cover the track's class. The explicit policy for the unknown
|
||||
/// (#133): an unidentified track is not blocked by the class filter — it stays a candidate
|
||||
/// under the general rules, and `why` says so. A system with no roles at all is holding its
|
||||
/// fire: nothing is a candidate for it. A probable or firm class out of the roles is a block,
|
||||
/// named in `why` too.
|
||||
pub fn in_roles(self, roles: u8) -> bool {
|
||||
match self {
|
||||
ClassEst::Unknown => roles != 0,
|
||||
ClassEst::Probable(c) | ClassEst::Firm(c) => roles & c.bit() != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// As the screens read it: «тип не определён», «вероятно крылатая ракета», «крылатая ракета».
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
ClassEst::Unknown => "тип не определён".into(),
|
||||
ClassEst::Probable(c) => format!("вероятно {}", c.singular()),
|
||||
ClassEst::Firm(c) => c.singular().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A short mark for the map's labels: the class letter, with `?` while the guess is only probable.
|
||||
pub fn mark(self) -> &'static str {
|
||||
match self {
|
||||
ClassEst::Unknown => "",
|
||||
ClassEst::Firm(c) => c.letter(),
|
||||
ClassEst::Probable(Class::Drone) => "Д?",
|
||||
ClassEst::Probable(Class::Jet) => "Г?",
|
||||
ClassEst::Probable(Class::Cruise) => "К?",
|
||||
ClassEst::Probable(Class::Supersonic) => "С?",
|
||||
ClassEst::Probable(Class::Ballistic) => "Б?",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Roles as a mask of [`Class::bit`]s, from `drone,jet,...` or `all`.
|
||||
pub fn parse_roles(text: &str) -> Option<u8> {
|
||||
if text == "all" {
|
||||
@@ -946,18 +811,6 @@ impl Drone {
|
||||
pub fn smart(&self) -> bool {
|
||||
self.smart
|
||||
}
|
||||
/// Where it is aimed, without this airframe's navigation error: only the sandbox's truth view reads it (#132).
|
||||
pub fn aim_pos(&self) -> DVec3 {
|
||||
self.target - self.err
|
||||
}
|
||||
/// The unit it is sent at (0: a marked object), as the aim bookkeeping holds it (#127).
|
||||
pub fn aim_unit(&self) -> u32 {
|
||||
self.aim.unit
|
||||
}
|
||||
/// The points it flies by on its way, the next first: the truth view draws the route ahead.
|
||||
pub fn route(&self) -> &[DVec3] {
|
||||
&self.route
|
||||
}
|
||||
/// How much a system wants to shoot it: fast and heavy first, decoys look real.
|
||||
fn threat(&self, from: DVec3) -> f64 {
|
||||
self.threat_at(from, self.pos)
|
||||
@@ -1103,10 +956,6 @@ impl MissileKind {
|
||||
}
|
||||
|
||||
impl Missile {
|
||||
/// The track it is intercepting: the map's hover says whether an interception is under way (#132).
|
||||
pub fn target(&self) -> u32 {
|
||||
self.target
|
||||
}
|
||||
/// Cold ejection and post-burn coast have no powered exhaust.
|
||||
pub fn engine_lit(&self) -> bool {
|
||||
let spec = self.kind.spec();
|
||||
@@ -1114,14 +963,6 @@ impl Missile {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-fixtures"))]
|
||||
impl Missile {
|
||||
/// A missile in flight for the screens' tests: command guidance, no seeker fix.
|
||||
pub fn test_at(id: u32, pos: DVec3, target: u32) -> Missile {
|
||||
Missile { id, kind: MissileKind::Pac3, pos, vel: DVec3::Z, target, sam: 0, age: 20, hold: 0, fix: None, seen: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl MissileKind {
|
||||
/// How far its own seeker holds a target of average size (blocks); 0: command guidance only.
|
||||
pub fn seeker(self) -> f64 {
|
||||
@@ -1281,8 +1122,6 @@ pub struct Sam {
|
||||
pub(super) terrain: HashMap<u32, (u64, u8)>,
|
||||
/// Targets whose land hasn't been answered yet, and since when it has been waited for.
|
||||
waits: HashMap<u32, u64>,
|
||||
/// A passive optical post's own state (#136): no radar, no track, one class observation at a time.
|
||||
pub optical: Optical,
|
||||
}
|
||||
|
||||
impl Sam {
|
||||
@@ -1356,7 +1195,6 @@ impl Sam {
|
||||
beam_cast: 0,
|
||||
terrain: HashMap::new(),
|
||||
waits: HashMap::new(),
|
||||
optical: Optical::default(),
|
||||
}
|
||||
}
|
||||
pub fn alive(&self) -> bool {
|
||||
@@ -1382,9 +1220,57 @@ impl Sam {
|
||||
self.yaw_vel = 0.0;
|
||||
self.pitch_vel = 0.0;
|
||||
}
|
||||
/// The TPK cell being opened, for the presentation adapter.
|
||||
pub fn preparing_cell(&self) -> Option<u32> {
|
||||
self.preparing.map(|p| p.cell)
|
||||
pub fn status(&self) -> String {
|
||||
let spec = self.kind.spec();
|
||||
let mut text = spec.name.to_string();
|
||||
if !self.alive() {
|
||||
return text + " УНИЧТОЖЕН";
|
||||
}
|
||||
if self.moving() {
|
||||
return text + " " + &self.state.name().to_lowercase();
|
||||
}
|
||||
match self.kind {
|
||||
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", self.cargo, self.ground_stock, self.air_48n6_stock),
|
||||
SamKind::Tzm => return format!("{text}: на борту {}/2, RM48U {}, снятых ПВО {}{}", self.cargo, self.ground_stock, self.air_48n6_stock, if self.return_cargo { ", везёт RM48U на склад" } else if self.job.is_some() { ", в пути" } else { "" }),
|
||||
SamKind::Ew => {
|
||||
let state = if self.ew_on { "ГЛУШИТ" } else if self.ew_lock { "остывает" } else { "готова" };
|
||||
return format!("{text}: {state}, нагрев {:.0}%", self.heat * 100.0);
|
||||
}
|
||||
SamKind::Radar => {
|
||||
let broken = if self.comps.whole() { String::new() } else { format!(" [{}]", self.comps.worst(self.kind)) };
|
||||
return format!("{text}: целей {}{broken}", self.own.len());
|
||||
}
|
||||
SamKind::Light => return format!("{text}{}", if self.target.is_some() { ": в луче цель" } else { "" }),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(p) = self.preparing {
|
||||
text += &format!(" · открытие ТПК №{}", p.cell + 1);
|
||||
}
|
||||
if self.empty && self.missiles == 0 {
|
||||
text += " ЖДЁТ БК";
|
||||
}
|
||||
if self.health < 1.0 {
|
||||
text += &format!(" ({:.0}%)", self.health * 100.0);
|
||||
}
|
||||
if !self.comps.whole() {
|
||||
text += &format!(" [{}]", self.comps.worst(self.kind));
|
||||
}
|
||||
if self.reloading > 0 {
|
||||
text += &format!(" перезарядка {}с", self.reloading.div_ceil(20));
|
||||
} else {
|
||||
if let Some(m) = &spec.missile {
|
||||
if self.kind == SamKind::S400 {
|
||||
text += &format!(" ПВО {} · RM48U {} / {} ячеек", self.missiles, self.ground_rounds, self.cells());
|
||||
if self.ground_return { text += " · ожидает вывоза RM48U"; }
|
||||
} else {
|
||||
text += &format!(" ракеты {}/{}", self.missiles, m.magazine);
|
||||
}
|
||||
}
|
||||
if spec.gun.is_some() {
|
||||
text += &format!(" очереди {}", self.bursts);
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1490,8 +1376,6 @@ pub struct Sim {
|
||||
pub tally: record::Tally,
|
||||
/// What the enemy has learned.
|
||||
intel: ew::Intel,
|
||||
/// Reconnaissance flights and the partial picture they radioed home (#135).
|
||||
recon: recon::Recon,
|
||||
/// Night: guns need light (the mod sets it from the game's clock).
|
||||
pub night: bool,
|
||||
/// The long fires at crash and impact points (#52).
|
||||
@@ -1568,7 +1452,6 @@ impl Sim {
|
||||
recordings: 0,
|
||||
tally: record::Tally::default(),
|
||||
intel: ew::Intel::default(),
|
||||
recon: recon::Recon::default(),
|
||||
night: false,
|
||||
fires: fires::Fires::default(),
|
||||
day_time: None,
|
||||
@@ -1599,12 +1482,6 @@ impl Sim {
|
||||
{
|
||||
return self.drones.iter().find(|d| d.id == id);
|
||||
}
|
||||
// An optical post has no track: its camera looks where it last saw the contact in clear
|
||||
// sight, and nowhere at all while it has not seen it (#136).
|
||||
if sam.kind == SamKind::Optical {
|
||||
let (id, _) = sam.optical.seen(self.tick)?;
|
||||
return self.drones.iter().find(|d| d.id == id);
|
||||
}
|
||||
let id = sam
|
||||
.gun_target
|
||||
.or(sam.target)
|
||||
@@ -1620,9 +1497,6 @@ impl Sim {
|
||||
{
|
||||
return Some(self.watched(sam).map_or(at, |d| d.pos));
|
||||
}
|
||||
if sam.kind == SamKind::Optical {
|
||||
return sam.optical.seen(self.tick).map(|(_, p)| p);
|
||||
}
|
||||
self.watched(sam).map(|d| d.pos)
|
||||
}
|
||||
|
||||
@@ -1681,7 +1555,6 @@ impl Sim {
|
||||
self.plan = None;
|
||||
self.retargets.clear();
|
||||
self.known_relief = None;
|
||||
self.recon.clear_sorties();
|
||||
self.wave = None;
|
||||
// Ammunition still to cook off, flares in the sky.
|
||||
self.later.clear();
|
||||
@@ -1729,7 +1602,6 @@ impl Sim {
|
||||
self.release_queue(ground, out);
|
||||
self.begin_recording_if_active();
|
||||
self.step_drones(ground, player, out);
|
||||
self.step_recon(out);
|
||||
self.step_later(ground, player, out);
|
||||
self.step_moves(ground, out);
|
||||
self.step_supply(out);
|
||||
@@ -2364,7 +2236,7 @@ impl Sim {
|
||||
|
||||
if self.hold {
|
||||
for i in 0..self.sams.len() {
|
||||
if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical {
|
||||
if self.sams[i].alive() && !self.sams[i].moving() {
|
||||
self.sams[i].state = SamState::Hold;
|
||||
}
|
||||
self.draw_sam(i, out);
|
||||
@@ -2420,10 +2292,7 @@ impl Sim {
|
||||
}
|
||||
if !self.sams[i].kind.armed() {
|
||||
let sam = &mut self.sams[i];
|
||||
// An optical post's state is its optics' (#136), not the armed systems' search line.
|
||||
if sam.kind != SamKind::Optical {
|
||||
sam.state = SamState::Search;
|
||||
}
|
||||
sam.state = SamState::Search;
|
||||
// A searchlight's target is its beam's (step_lights): kept for its spot of light.
|
||||
if sam.kind != SamKind::Light {
|
||||
retarget(&mut missile_on, sam.target.take(), None);
|
||||
@@ -2445,7 +2314,7 @@ impl Sim {
|
||||
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 doc = &me.doctrine;
|
||||
let needed = |tr: &Track, d: &Drone| doc.needed(d, tr.class);
|
||||
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.
|
||||
@@ -2463,7 +2332,7 @@ impl Sim {
|
||||
let stuck = me.held > why::HOLD_MAX;
|
||||
let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| tr.id == *t && basis(tr, 1.1, false).is_some()));
|
||||
keep.or_else(|| {
|
||||
let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d));
|
||||
let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(d));
|
||||
// Long shots only while nothing of the system's roles is in its normal reach.
|
||||
let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role));
|
||||
tracks
|
||||
@@ -2512,10 +2381,7 @@ impl Sim {
|
||||
}
|
||||
sam.target = target;
|
||||
}
|
||||
let gun_target = gun_target.flatten();
|
||||
if gun_target.is_some() || had_gun.is_some() {
|
||||
// A track that stopped being a candidate is let go (a class estimated out of the
|
||||
// roles since it was taken, #133, included): the gun must not keep firing at it.
|
||||
if let Some(gun_target) = gun_target {
|
||||
retarget(&mut guns_on, had_gun, gun_target);
|
||||
self.sams[i].gun_target = gun_target;
|
||||
}
|
||||
@@ -2551,14 +2417,13 @@ impl Sim {
|
||||
} else {
|
||||
SamState::Search
|
||||
};
|
||||
// Nothing to fire at: the mount watches the nearest track of its classes (by the class
|
||||
// the network estimates, the unknown among them: a reaction a turn shorter), else it
|
||||
// goes back to the rest position, under the drive's limits like any other turn.
|
||||
// Nothing to fire at: the mount watches the nearest track of its classes (a reaction a turn
|
||||
// shorter), else it goes back to the rest position, under the drive's limits like any other turn.
|
||||
let (mount, _) = sam.mount();
|
||||
let watch = sam
|
||||
.tracks
|
||||
.iter()
|
||||
.filter(|tr| tr.age(now) <= sight::MISSILE_AGE && tr.class.in_roles(roles) && drone_at.get(&tr.id).is_some_and(|&k| self.drones[k].alive()))
|
||||
.filter(|tr| tr.age(now) <= sight::MISSILE_AGE && drone_at.get(&tr.id).is_some_and(|&k| roles & self.drones[k].kind.spec().class.bit() != 0 && self.drones[k].alive()))
|
||||
.min_by(|a, b| a.est(now).distance(mount).total_cmp(&b.est(now).distance(mount)))
|
||||
.map(|tr| why::aim_wants(mount, tr.est(now), tr.vel, spec.gun.as_ref().map_or(5.0, |g| g.shell)));
|
||||
match (watch, spec.family) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,9 +18,9 @@ impl SamKind {
|
||||
Family::Truck => 10,
|
||||
}
|
||||
}
|
||||
/// A depot and a fixed optical post don't drive.
|
||||
/// A depot doesn't drive.
|
||||
pub fn mobile(self) -> bool {
|
||||
!matches!(self, SamKind::Depot | SamKind::Optical)
|
||||
self != SamKind::Depot
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -284,9 +284,6 @@ impl Sim {
|
||||
// read-only while the plan is built, and taking it per drone made a big second order
|
||||
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
|
||||
let picture = self.picture_of_defences();
|
||||
// The partial picture the recon flights have radioed home. It is memory, not the
|
||||
// force: a mark has an area, a category and an age, never a unit's exact place (#135).
|
||||
let leads = self.recon.leads(self.tick);
|
||||
// A smart enemy comes from where its raids got through best.
|
||||
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
|
||||
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
|
||||
@@ -315,7 +312,7 @@ impl Sim {
|
||||
index += 1;
|
||||
let (target, at_sam) = match job {
|
||||
Some((at, id)) => (at, Some(id)),
|
||||
None => self.choose_target(kind, object, order.aim, &picture, &leads),
|
||||
None => self.choose_target(kind, object, order.aim, &picture),
|
||||
};
|
||||
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
|
||||
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
|
||||
@@ -326,11 +323,7 @@ impl Sim {
|
||||
// The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit
|
||||
// chosen for the raid is the plan's objective, anything else is a marked object.
|
||||
if let Some(id) = at_sam {
|
||||
let confidence = picture
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map(|c| c.confidence(self.tick))
|
||||
.or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick)));
|
||||
let confidence = picture.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick));
|
||||
d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan };
|
||||
d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c));
|
||||
} else {
|
||||
@@ -370,11 +363,6 @@ impl Sim {
|
||||
waited: 0,
|
||||
mapped: !smart,
|
||||
});
|
||||
// The smart enemy may send a small recon flight ahead of the strike -- physically in
|
||||
// the air, not a pause: the strike is planned while they fly (#135).
|
||||
if smart {
|
||||
self.start_recon(objects, bearing, order.dist, out);
|
||||
}
|
||||
// A raid without routes is ready at once.
|
||||
self.plan_step(None, out);
|
||||
total
|
||||
@@ -592,25 +580,12 @@ impl Sim {
|
||||
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
|
||||
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
|
||||
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec<Option<(DVec3, u32)>> {
|
||||
// Exact disclosure contacts and recon marks of radars, best first. The order is the
|
||||
// observed role, freshness and quality -- never the id: a hidden station has no id,
|
||||
// and a big observed radar is worth more than a modest one (#135).
|
||||
let now = self.tick;
|
||||
let mut radars: Vec<(u8, u64, u32, DVec3)> = picture
|
||||
let mut radars: Vec<(u32, DVec3)> = picture
|
||||
.iter()
|
||||
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
|
||||
.map(|c| {
|
||||
let seen = match c.confidence(now) {
|
||||
ew::Confidence::Confirmed => 4,
|
||||
ew::Confidence::Probable => 2,
|
||||
ew::Confidence::Doubtful => 0,
|
||||
};
|
||||
(seen * 10 + 3, c.tick, c.id, c.at)
|
||||
})
|
||||
.chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area)))
|
||||
.filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable)
|
||||
.map(|c| (c.id, c.at))
|
||||
.collect();
|
||||
radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
|
||||
let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect();
|
||||
radars.sort_by_key(|(id, _)| *id);
|
||||
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
|
||||
let mut jobs = vec![None; flat.len()];
|
||||
if radars.is_empty() {
|
||||
@@ -634,8 +609,8 @@ impl Sim {
|
||||
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
|
||||
/// unit is the last observation — the place seen then, the type identified then — never where
|
||||
/// the unit actually is or what it has become since.
|
||||
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
|
||||
if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects {
|
||||
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option<u32>) {
|
||||
if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects {
|
||||
return (object, None);
|
||||
}
|
||||
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
|
||||
@@ -666,15 +641,7 @@ impl Sim {
|
||||
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((p, id)) = choice {
|
||||
return (p, Some(id));
|
||||
}
|
||||
// Nothing disclosed and nothing the kind's usual preference picked: a recon mark
|
||||
// whose observed role fits is the next best reason to turn a strike off the object.
|
||||
if let Some(m) = recon_pick(kind, leads, r) {
|
||||
return (m.area, Some(m.id));
|
||||
}
|
||||
(object, None)
|
||||
choice.map_or((object, None), |(p, id)| (p, Some(id)))
|
||||
}
|
||||
|
||||
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
|
||||
@@ -968,11 +935,6 @@ const AIR_START_WAIT: u32 = 120;
|
||||
if !why.is_empty() {
|
||||
out.messages.push(format!("Неудачи ПВО: {why}"));
|
||||
}
|
||||
// What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135).
|
||||
let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count();
|
||||
if marks > 0 {
|
||||
out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)"));
|
||||
}
|
||||
// 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 {
|
||||
@@ -994,21 +956,6 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
|
||||
len
|
||||
}
|
||||
|
||||
/// A recon mark whose observed category fits this kind. The list is already in priority
|
||||
/// order, so the first fit is the best reason.
|
||||
fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::Mark> {
|
||||
use recon::Category as C;
|
||||
let fits = |c: C| match kind {
|
||||
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
|
||||
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
|
||||
DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher),
|
||||
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
|
||||
_ => false,
|
||||
};
|
||||
let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect();
|
||||
fits.get((r * fits.len() as f64) as usize).copied().copied()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,8 @@
|
||||
//! Raids are recorded for their replays: every drone's and interceptor's
|
||||
//! track (a point every other tick, falling wrecks included) and what
|
||||
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
|
||||
//! A recording starts with the first strike drone in the sky and ends when the sky
|
||||
//! has been clear a while; the last few are kept. A recon aircraft is a role of its own
|
||||
//! and is not part of the strike's replay (#135).
|
||||
//! A recording starts with the first drone in the sky and ends when the sky
|
||||
//! has been clear a while; the last few are kept.
|
||||
use super::*;
|
||||
|
||||
/// A system's pose at a moment of a recording.
|
||||
@@ -156,8 +155,6 @@ impl Recording {
|
||||
objects: Vec::new(),
|
||||
sam_tracks: Vec::new(),
|
||||
sam_index: HashMap::new(),
|
||||
sam_keys: 0,
|
||||
sam_step: STEP,
|
||||
ticks: Vec::new(),
|
||||
times: Vec::new(),
|
||||
quiet: 0,
|
||||
@@ -188,8 +185,6 @@ pub const STEP: u32 = 2;
|
||||
/// The longest recording (10 minutes) and how many are kept.
|
||||
const LONGEST: u32 = 12_000;
|
||||
const KEPT: usize = 3;
|
||||
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
|
||||
const MAX_SAM_KEYS: usize = 32_768;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub enum What {
|
||||
@@ -386,8 +381,6 @@ pub struct Recording {
|
||||
/// it pointed, whether it was still whole).
|
||||
pub sam_tracks: Vec<SamTrack>,
|
||||
sam_index: HashMap<u32, usize>,
|
||||
sam_keys: usize,
|
||||
sam_step: u32,
|
||||
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
|
||||
/// shows the world's blocks as of this time.
|
||||
ticks: Vec<(u32, u64)>,
|
||||
@@ -596,38 +589,14 @@ impl Recording {
|
||||
objects: sim.targets.clone(),
|
||||
sam_tracks: Vec::new(),
|
||||
sam_index: HashMap::new(),
|
||||
sam_keys: 0,
|
||||
sam_step: STEP,
|
||||
ticks: Vec::new(),
|
||||
times: Vec::new(),
|
||||
quiet: 0,
|
||||
}
|
||||
}
|
||||
fn thin_sam_tracks(&mut self) {
|
||||
for track in &mut self.sam_tracks {
|
||||
let len = track.keys.len();
|
||||
let mut kept = 0;
|
||||
for read in (0..len).step_by(2) {
|
||||
track.keys[kept] = track.keys[read];
|
||||
kept += 1;
|
||||
}
|
||||
if len % 2 == 0 && len > 0 {
|
||||
track.keys[kept] = track.keys[len - 1];
|
||||
kept += 1;
|
||||
}
|
||||
track.keys.truncate(kept);
|
||||
track.keys.shrink_to_fit();
|
||||
}
|
||||
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||||
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
|
||||
}
|
||||
|
||||
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
|
||||
/// the pose it held marked before it so a replay doesn't glide through the stillness.
|
||||
fn note_sams(&mut self, sams: &[Sam], now: u32) {
|
||||
if now % self.sam_step != 0 {
|
||||
return;
|
||||
}
|
||||
for sam in sams {
|
||||
let key = SamKey::of(sam, self.origin, now);
|
||||
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
|
||||
@@ -635,21 +604,16 @@ impl Recording {
|
||||
self.sam_tracks.len() - 1
|
||||
});
|
||||
let track = &mut self.sam_tracks[i];
|
||||
let before = track.keys.len();
|
||||
match track.keys.last().copied() {
|
||||
None => track.keys.push(key),
|
||||
Some(last) if last.same(&key) => {}
|
||||
Some(last) => {
|
||||
if last.at + self.sam_step < now {
|
||||
track.keys.push(SamKey { at: now - self.sam_step, ..last });
|
||||
if last.at + STEP < now {
|
||||
track.keys.push(SamKey { at: now - STEP, ..last });
|
||||
}
|
||||
track.keys.push(key);
|
||||
}
|
||||
}
|
||||
self.sam_keys += track.keys.len() - before;
|
||||
}
|
||||
if self.sam_keys > MAX_SAM_KEYS {
|
||||
self.thin_sam_tracks();
|
||||
}
|
||||
}
|
||||
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
|
||||
@@ -835,11 +799,8 @@ impl Sim {
|
||||
}
|
||||
|
||||
/// Open before the combat update so transitions on the first active tick are not lost.
|
||||
/// A recon aircraft neither opens nor holds a strike's recording (#135).
|
||||
pub(super) fn begin_recording_if_active(&mut self) {
|
||||
if self.rec.is_none()
|
||||
&& (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty())
|
||||
{
|
||||
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
|
||||
self.recordings += 1;
|
||||
self.rec = Some(Recording::new(self.recordings, self));
|
||||
}
|
||||
@@ -857,13 +818,7 @@ impl Sim {
|
||||
pub(super) fn record(&mut self) {
|
||||
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
|
||||
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
|
||||
// A recon flight is not part of the strike's replay: it neither opens nor holds a
|
||||
// recording open. The strike's own drones and interceptors do (#135).
|
||||
let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id))
|
||||
|| !self.missiles.is_empty()
|
||||
|| !self.queue.is_empty()
|
||||
|| !self.strikes.flights.is_empty()
|
||||
|| !self.strikes.pending.is_empty();
|
||||
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty();
|
||||
self.begin_recording_if_active();
|
||||
let Some(r) = &mut self.rec else { return };
|
||||
r.note_tracks(&self.sams);
|
||||
@@ -877,7 +832,7 @@ impl Sim {
|
||||
if r.len % STEP == 0 {
|
||||
let now = r.len;
|
||||
r.note_sams(&self.sams, now);
|
||||
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
|
||||
for d in &self.drones {
|
||||
r.point(d.id, What::Drone(d.kind), d.pos);
|
||||
}
|
||||
for m in &self.missiles {
|
||||
@@ -1088,8 +1043,6 @@ mod tests {
|
||||
objects: Vec::new(),
|
||||
sam_tracks: Vec::new(),
|
||||
sam_index: HashMap::new(),
|
||||
sam_keys: 0,
|
||||
sam_step: STEP,
|
||||
ticks: Vec::new(),
|
||||
times: Vec::new(),
|
||||
quiet: 0,
|
||||
@@ -1109,19 +1062,6 @@ mod tests {
|
||||
assert!(r.sam_tracks[0].ghost(r.origin, 0.0, 1).unwrap().radar_on);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_preserves_a_separate_radars_profile() {
|
||||
let mut r = recording();
|
||||
for (at, role) in [(0, battery::RadarRole::Search), (10, battery::RadarRole::Height), (20, battery::RadarRole::Engagement)] {
|
||||
let mut sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
|
||||
sam.set_radar_role(role);
|
||||
r.note_sams(&[sam], at);
|
||||
}
|
||||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 1.0, 1).unwrap().radar_profile().id, "radar_search");
|
||||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 11.0, 1).unwrap().radar_profile().id, "radar_height");
|
||||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 21.0, 1).unwrap().radar_profile().id, "radar_track");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_preserves_launcher_configuration_and_individual_cover_poses() {
|
||||
let mut r = recording();
|
||||
@@ -1229,29 +1169,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_recording_bounds_sam_keys_without_freezing_their_poses() {
|
||||
let mut r = recording();
|
||||
let mut sams: Vec<_> = (0..64)
|
||||
.map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0))
|
||||
.collect();
|
||||
for now in (0..LONGEST).step_by(STEP as usize) {
|
||||
for sam in &mut sams {
|
||||
sam.dish = now as f64 * 0.01;
|
||||
}
|
||||
r.note_sams(&sams, now);
|
||||
}
|
||||
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||||
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
|
||||
assert_eq!(keys, r.sam_keys);
|
||||
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
|
||||
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
|
||||
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
|
||||
let last = r.sam_tracks[0].pose(LONGEST as f64).unwrap();
|
||||
assert!(last.at >= LONGEST - 64, "poses stopped at tick {}", last.at);
|
||||
assert!(last.dish > 100.0, "the final radar pose was not recorded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
|
||||
let mut r = recording();
|
||||
@@ -1313,22 +1230,7 @@ mod tests {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0));
|
||||
let mut r = Recording::new(1, &sim);
|
||||
let tr = sight::Track {
|
||||
id: 77,
|
||||
class: ClassEst::Firm(Class::Drone),
|
||||
pos: DVec3::Z * 100.0,
|
||||
vel: -DVec3::Z,
|
||||
tick: 1,
|
||||
own_tick: 1,
|
||||
source: 1,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 80,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 80,
|
||||
ttl: 10,
|
||||
hits: 1,
|
||||
locked: false,
|
||||
};
|
||||
let tr = sight::Track { id: 77, kind: DroneKind::Shahed, pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false };
|
||||
sim.sams[0].tracks.push(tr);
|
||||
r.note_tracks(&sim.sams);
|
||||
r.len = 1;
|
||||
@@ -1394,22 +1296,7 @@ mod tests {
|
||||
let id = sim.id();
|
||||
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||||
for target in 1..=4 {
|
||||
sam.tracks.push(sight::Track {
|
||||
id: target,
|
||||
class: ClassEst::Firm(Class::Drone),
|
||||
pos: DVec3::Z,
|
||||
vel: DVec3::ZERO,
|
||||
tick: 1,
|
||||
own_tick: 1,
|
||||
source: sam.id,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 80,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 80,
|
||||
ttl: 1,
|
||||
hits: 1,
|
||||
locked: false,
|
||||
});
|
||||
sam.tracks.push(sight::Track { id: target, kind: DroneKind::Shahed, pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false });
|
||||
}
|
||||
sim.sams.push(sam);
|
||||
}
|
||||
|
||||
@@ -990,7 +990,7 @@ fn fires_start_merge_and_are_limited() {
|
||||
// interceptors keep clear of it. A synthetic land (a height function) stands in for the game.
|
||||
|
||||
/// Land from a height function: blocks below it are solid, and the game's height map says the same.
|
||||
pub(super) struct Land<F: Fn(i32, i32) -> i32>(F);
|
||||
struct Land<F: Fn(i32, i32) -> i32>(F);
|
||||
impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
|
||||
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
||||
Some(y < (self.0)(x, z))
|
||||
@@ -998,7 +998,7 @@ impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
|
||||
}
|
||||
|
||||
/// What the game answers a tick after the sim asked: land heights, and the sections it needs.
|
||||
pub(super) fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
|
||||
fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
|
||||
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (land.0)(x, z))).collect();
|
||||
ground.answer(columns, now);
|
||||
let sections = ground.world.take_wanted(now);
|
||||
@@ -1010,7 +1010,7 @@ fn ridge(rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
|
||||
ridge_at(300, rise, half)
|
||||
}
|
||||
|
||||
pub(super) fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
|
||||
fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
|
||||
Land(move |x, _| 64 + (rise - (x - crest).abs() * rise / half).max(0))
|
||||
}
|
||||
|
||||
@@ -1103,23 +1103,9 @@ fn behind_ridge(land: &Land<impl Fn(i32, i32) -> i32>, crest: i32, kind: SamKind
|
||||
// It crawls along the far side of the ridge, 20 blocks over the land.
|
||||
let there = (land.0)(x as i32, 0) as f64;
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(x, there + 20.0, -100.0), DVec3::Z, DVec3::new(x, there, 3000.0));
|
||||
let id = sim.drones[0].id;
|
||||
for _ in 0..ticks {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
answer_land(&mut ground, land, sim.tick);
|
||||
// The scenario is about the interceptor's path over the ridge, not about
|
||||
// where the plot came from: give the system the crest radar's plot as its
|
||||
// own confirmed fire measurement (separate authority is tested in
|
||||
// `a_system_does_not_fire_at_a_target_masked_by_a_hill`).
|
||||
if let Some(t) = sim.sams[1].track(id).copied() {
|
||||
let mut own = t;
|
||||
own.source = sim.sams[0].id;
|
||||
own.own_tick = sim.tick;
|
||||
own.own_product = battery::Measure::Fire;
|
||||
own.own_quality = 90;
|
||||
sim.sams[0].tracks.retain(|o| o.id != id);
|
||||
sim.sams[0].tracks.push(own);
|
||||
}
|
||||
}
|
||||
sim
|
||||
}
|
||||
@@ -1145,25 +1131,27 @@ fn a_system_does_not_fire_at_a_target_masked_by_a_hill() {
|
||||
answer_land(&mut ground, land, sim.tick);
|
||||
}
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(200.0, 84.0, -60.0), DVec3::Z, DVec3::new(200.0, 64.0, 3000.0));
|
||||
let mut masked = 0u32;
|
||||
let mut seen = false;
|
||||
let mut told = false;
|
||||
for _ in 0..300 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
answer_land(&mut ground, land, sim.tick);
|
||||
seen |= sim.sams[0].seen.len() == 1;
|
||||
// The network shows the target, but the Tor has no own confirmed plot,
|
||||
// so `why` must say that no launch is authorized.
|
||||
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("право на пуск: нет"));
|
||||
masked += sim.sams[0].terrain.values().filter(|(_, b)| *b == terrain::MASKED).count() as u32;
|
||||
// `why` names the reason while the verdict stands.
|
||||
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("за рельефом"));
|
||||
}
|
||||
(sim, seen, told)
|
||||
(sim, seen, masked, told)
|
||||
};
|
||||
let (open, seen, _) = shot(&flat);
|
||||
let (open, seen, _, _) = shot(&flat);
|
||||
assert!(seen && open.sams[0].fired > 0, "control: with a clear line the Tor must fire (seen {seen}, fired {})", open.sams[0].fired);
|
||||
let (shut, seen, told) = shot(&hill);
|
||||
let (shut, seen, masked, told) = shot(&hill);
|
||||
assert!(seen, "the network must have shown the target to the Tor");
|
||||
assert_eq!(shut.sams[0].fired, 0, "the Tor fired at a target behind the hill");
|
||||
assert!(masked > 0, "no launch was judged and refused for the land");
|
||||
assert_eq!(shut.tally.blocked + shut.tally.scrubbed, 0);
|
||||
assert!(told, "`why` never named the missing own fire plot");
|
||||
assert!(told, "`why` never named the land as the reason");
|
||||
}
|
||||
|
||||
// A long-range system lofts over a low ridge (its interceptor does not hit it) but not over a mountain.
|
||||
@@ -2445,22 +2433,7 @@ fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() {
|
||||
// the test is about the launch stages, not about the scan's chance.
|
||||
let now = sim.tick;
|
||||
let tracks: Vec<sight::Track> = sim.drones.iter().filter(|d| d.alive())
|
||||
.map(|d| sight::Track {
|
||||
id: d.id,
|
||||
class: ClassEst::Firm(d.kind.spec().class),
|
||||
pos: d.pos,
|
||||
vel: d.vel,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: 1,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 90,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 90,
|
||||
ttl: 400,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
})
|
||||
.map(|d| sight::Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
|
||||
.collect();
|
||||
sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id));
|
||||
sim.sams[0].tracks.extend(tracks);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
|
||||
use super::battery::{Measure, RadarRole};
|
||||
use super::regress::{answer_land, ridge_at};
|
||||
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
|
||||
use super::sight::{swept, FORECAST_AGE};
|
||||
use super::*;
|
||||
|
||||
fn flat() -> (Ground, Out) {
|
||||
@@ -124,9 +122,6 @@ fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() {
|
||||
let early = radar_at(&mut sim, SamKind::Radar, 120.0);
|
||||
let id = drone_from(&mut sim, -150.0);
|
||||
sim.sams[p].comps.0[Part::Sensor as usize] = 0.0;
|
||||
// Hold fire: the fed track is now acted on (an unidentified contact is a candidate under the
|
||||
// general rules, #133), and this test is about the feed, not about the intercept.
|
||||
sim.sams[p].roles = 0;
|
||||
for _ in 0..500 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
@@ -259,526 +254,3 @@ fn the_same_seed_rolls_the_same_scan_and_damage() {
|
||||
};
|
||||
assert_eq!(run(), run());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- #133: the class estimate
|
||||
|
||||
#[test]
|
||||
fn the_classifier_steps_by_the_measurements_alone() {
|
||||
// The same observed speeds give the same estimate whatever the contact truly is, and a
|
||||
// contrary measurement replaces the hypothesis instead of being ignored.
|
||||
let mut est = ClassEst::Unknown;
|
||||
assert_eq!(est.step(1, 0.6), ClassEst::Unknown, "one blip says nothing of the class");
|
||||
est = est.step(2, 0.6);
|
||||
assert_eq!(est, ClassEst::Probable(Class::Drone));
|
||||
est = est.step(3, 0.62);
|
||||
assert_eq!(est, ClassEst::Firm(Class::Drone), "agreeing measurements firm the guess");
|
||||
// The contact proves much faster (or the first readings misled): the hypothesis gives way,
|
||||
// and one measurement is not enough to firm the new one.
|
||||
est = est.step(4, 5.0);
|
||||
assert_eq!(est, ClassEst::Probable(Class::Supersonic));
|
||||
est = est.step(5, 5.1);
|
||||
assert_eq!(est, ClassEst::Firm(Class::Supersonic));
|
||||
// Whatever the true kind, the same observations read the same: a Kinzhal measured as a slow
|
||||
// propeller is, to the network, a drone until its measurements say otherwise.
|
||||
assert_eq!(ClassEst::Unknown.step(2, 0.5), ClassEst::Probable(Class::Drone));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_speed_bands_read_the_games_own_kinds_right() {
|
||||
// The bands sit between the game's speed clusters: the measured speed of a kind reads as its
|
||||
// class, so a slow Lancet is no jet and a Shahed no cruise missile. A fast ballistic and a
|
||||
// supersonic missile fly alike (the Iskander and the Zircon): speed alone leaves that
|
||||
// ambiguity, documented on `Class::of_speed`.
|
||||
for kind in DroneKind::ALL {
|
||||
let spec = kind.spec();
|
||||
if spec.class == Class::Ballistic && spec.speed < 6.5 {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(Class::of_speed(spec.speed), spec.class, "{kind:?} at {} blocks a tick", spec.speed);
|
||||
}
|
||||
assert_eq!(Class::of_speed(5.0), Class::Supersonic, "a fast ballistic and a supersonic fly alike");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_blip_gives_no_class_and_no_speed() {
|
||||
let mut sim = Sim::new(5);
|
||||
let (mut ground, mut out) = flat();
|
||||
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
|
||||
let id = drone_from(&mut sim, -150.0);
|
||||
let mut first = None;
|
||||
for _ in 0..300 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if let Some(t) = sim.sams[r].track(id) {
|
||||
first = Some(*t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let t = first.expect("a track of the drone");
|
||||
assert_eq!(t.hits, 1);
|
||||
assert_eq!(t.class, ClassEst::Unknown, "the first measurement must not name a class");
|
||||
assert_eq!(t.vel, DVec3::ZERO, "the true velocity must not leak into the track");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_of_different_kinds_one_class_firm_the_same_estimate() {
|
||||
// A Shahed and a Gerbera are different machines of one class, flying alike; the picture both
|
||||
// networks end up holding is the same: a firm slow drone, never a model name. (Faster kinds
|
||||
// cross this little radar's reach between beam passes: too few measurements to firm anything.)
|
||||
let roles = SamKind::S400.spec().roles;
|
||||
let mut seen = Vec::new();
|
||||
for kind in [DroneKind::Shahed, DroneKind::Gerbera] {
|
||||
let mut sim = Sim::new(7);
|
||||
let (mut ground, mut out) = flat();
|
||||
// One radar: an uninterrupted chain of measurements (two early-warning radars do not
|
||||
// exchange tracks — a radar is fed only when it serves fire control — so the second one
|
||||
// would measure from a blank picture, its own chain apart).
|
||||
radar_at(&mut sim, SamKind::Radar, 0.0);
|
||||
let from = DVec3::new(-150.0, 95.0, 40.0);
|
||||
sim.add_drone(kind, from, DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
|
||||
let id = sim.drones.last().unwrap().id;
|
||||
let mut est = None;
|
||||
for _ in 0..700 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if let Some(t) = sim.picture().get(&id) {
|
||||
est = Some(t.class);
|
||||
}
|
||||
}
|
||||
assert_eq!(est, Some(ClassEst::Firm(Class::Drone)), "{kind:?}: {est:?}");
|
||||
// The wording and the class-dependent decisions come from the estimate, not the machine.
|
||||
let est = est.unwrap();
|
||||
seen.push((est, est.name(), est.mark(), est.in_roles(roles)));
|
||||
}
|
||||
assert_eq!(seen[0], seen[1], "the same observations read differently for two kinds: {seen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_role_policy_keeps_the_unidentified_and_holds_fire_with_no_roles() {
|
||||
let some = Class::Drone.bit() | Class::Jet.bit();
|
||||
// An unidentified contact is not a block: it stays a candidate under the general rules.
|
||||
assert!(ClassEst::Unknown.in_roles(some));
|
||||
// No roles at all is holding fire: nothing is a candidate, the unidentified included.
|
||||
assert!(!ClassEst::Unknown.in_roles(0), "hold fire must block the unidentified too");
|
||||
// A probable guess is a block when its class is out of the roles, and a pass when in them.
|
||||
assert!(ClassEst::Probable(Class::Drone).in_roles(some));
|
||||
assert!(!ClassEst::Probable(Class::Cruise).in_roles(some));
|
||||
assert!(ClassEst::Firm(Class::Jet).in_roles(some));
|
||||
assert!(!ClassEst::Firm(Class::Ballistic).in_roles(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() {
|
||||
// The Gepard's roles are drones, jets and cruise missiles: a supersonic missile is out of them.
|
||||
assert_eq!(SamKind::Gepard.spec().roles & Class::Supersonic.bit(), 0);
|
||||
let mut sim = Sim::new(11);
|
||||
let (mut ground, mut out) = flat();
|
||||
let p = radar_at(&mut sim, SamKind::Gepard, 0.0);
|
||||
sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 95.0, -60.0), DVec3::Z, DVec3::new(0.0, 70.0, -700.0));
|
||||
let id = sim.drones.last().unwrap().id;
|
||||
sim.tick = 10;
|
||||
let seed = |sim: &mut Sim, class| {
|
||||
let d = sim.drones[0].clone();
|
||||
sim.sams[p].tracks.retain(|t| t.id != d.id);
|
||||
let source = sim.sams[p].id;
|
||||
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
|
||||
};
|
||||
// Taken while the class was unknown: the general rules make it a candidate.
|
||||
seed(&mut sim, ClassEst::Unknown);
|
||||
sim.step_sams(&mut ground, &mut out);
|
||||
assert_eq!(sim.sams[p].gun_target, Some(id), "an unidentified track is not its gun target");
|
||||
// Classified: no longer a class the gun engages, and it is let go instead of being fired at.
|
||||
seed(&mut sim, ClassEst::Firm(Class::Supersonic));
|
||||
sim.step_sams(&mut ground, &mut out);
|
||||
assert_eq!(sim.sams[p].gun_target, None, "the gun kept a track its roles do not cover");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecasts_and_relays_add_no_confidence() {
|
||||
let mut sim = Sim::new(7);
|
||||
let (mut ground, mut out) = flat();
|
||||
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
|
||||
let _b = radar_at(&mut sim, SamKind::Radar, 500.0);
|
||||
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
|
||||
let id = drone_from(&mut sim, -50.0);
|
||||
// The source's own track: while no new measurement lands (the tick unchanged, the track only
|
||||
// forecast onwards) the estimate must not move — a forecast is not data.
|
||||
let mut prev: Option<(u64, ClassEst)> = None;
|
||||
let mut relayed = 0;
|
||||
for _ in 0..800 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if let Some(t) = sim.sams[a].track(id).copied() {
|
||||
if let Some((tick, class)) = prev {
|
||||
assert!(t.tick > tick || t.class == class, "a forecast or a re-read firmed the class: {tick}->{:?} {:?}->{:?}", t.tick, class, t.class);
|
||||
}
|
||||
prev = Some((t.tick, t.class));
|
||||
}
|
||||
// The network's copy carries the estimate as it was, with its measurement's age; passing
|
||||
// it on adds nothing (the receiver never measures: own_tick stays 0).
|
||||
if let Some(t) = sim.sams[n].track(id).copied() {
|
||||
relayed += 1;
|
||||
assert_eq!(t.own_tick, 0);
|
||||
let freshest = sim.sams.iter().filter(|s| s.id != sim.sams[n].id).filter_map(|s| s.track(id)).max_by_key(|t| t.tick);
|
||||
assert_eq!(Some(t.class), freshest.map(|f| f.class), "a relay altered the estimate");
|
||||
}
|
||||
}
|
||||
assert!(relayed > 100, "the network never passed the track ({relayed})");
|
||||
assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- separate radar profiles (#134)
|
||||
|
||||
fn radar_with_role(sim: &mut Sim, role: RadarRole, x: f64) -> usize {
|
||||
let id = sim.id();
|
||||
let mut sam = Sam::new(id, SamKind::Radar, DVec3::new(x, 70.0, 0.0), 0.0);
|
||||
sam.set_radar_role(role);
|
||||
sim.sams.push(sam);
|
||||
sim.sams.len() - 1
|
||||
}
|
||||
|
||||
fn bearing(from: DVec3, to: DVec3) -> f64 {
|
||||
(to.x - from.x).atan2(-(to.z - from.z))
|
||||
}
|
||||
|
||||
/// The beam of every radar is pointed at one of `targets` in turn, so a test
|
||||
/// does not depend on where the initial phase happened to be.
|
||||
fn sweep(sim: &mut Sim, ground: &mut Ground, radars: &[usize], targets: &[DVec3], tick: u64) {
|
||||
sim.tick = tick;
|
||||
for (k, &i) in radars.iter().enumerate() {
|
||||
let at = targets[(tick as usize + k) % targets.len()];
|
||||
sim.sams[i].beam = bearing(sim.sams[i].pos, at);
|
||||
}
|
||||
sim.update_sight(ground);
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
struct ProfileStats {
|
||||
first_high: Option<u64>,
|
||||
first_low_refined: Option<u64>,
|
||||
first_close_fire: Option<u64>,
|
||||
max_channels: usize,
|
||||
search_or_height_authorized: bool,
|
||||
}
|
||||
|
||||
/// A low contact at 330 blocks (above the search/engagement horizon but below
|
||||
/// the mast's), a high contact at 700/430 (inside the search reach but outside
|
||||
/// the mast's and engagement's local search), and two close contacts for the
|
||||
/// tracked-contact channels.
|
||||
fn profile_world(roles: &[RadarRole]) -> (Sim, Vec<usize>, Vec<u32>, Ground) {
|
||||
let mut sim = Sim::new(134);
|
||||
let radars: Vec<usize> = roles.iter().map(|role| radar_with_role(&mut sim, *role, 0.0)).collect();
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(330.0, 95.0, 0.0), DVec3::Z, DVec3::new(330.0, 95.0, 0.0));
|
||||
let low = sim.drones.last().unwrap().id;
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(700.0, 500.0, 0.0), DVec3::Z, DVec3::new(700.0, 500.0, 0.0));
|
||||
let high = sim.drones.last().unwrap().id;
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
|
||||
let close1 = sim.drones.last().unwrap().id;
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 130.0, 40.0), DVec3::Z, DVec3::new(180.0, 130.0, 40.0));
|
||||
let close2 = sim.drones.last().unwrap().id;
|
||||
(sim, radars, vec![low, high, close1, close2], Ground::default())
|
||||
}
|
||||
|
||||
fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec<usize>, Vec<u32>) {
|
||||
let (mut sim, radars, ids, mut ground) = profile_world(roles);
|
||||
let [low, high, close1, close2] = [ids[0], ids[1], ids[2], ids[3]];
|
||||
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
|
||||
let mut stats = ProfileStats::default();
|
||||
for tick in 1..=ticks {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
for &i in &radars {
|
||||
let sam = &sim.sams[i];
|
||||
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
|
||||
match t.id {
|
||||
id if id == high && stats.first_high.is_none() => stats.first_high = Some(tick),
|
||||
id if id == low && t.product == Measure::Refine && stats.first_low_refined.is_none() => stats.first_low_refined = Some(tick),
|
||||
id if (id == close1 || id == close2) && t.product == Measure::Fire && t.own_authorizes(sim.tick) && stats.first_close_fire.is_none() => stats.first_close_fire = Some(tick),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
|
||||
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
||||
}
|
||||
stats.max_channels = stats.max_channels.max(sam.own_channels_used());
|
||||
}
|
||||
}
|
||||
(stats, sim, radars, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_profile_is_useful_alone_and_the_full_set_covers_all_three_jobs() {
|
||||
let search = run_profile_world(&[RadarRole::Search], 500).0;
|
||||
assert!(search.first_high.is_some(), "the search radar gives no early high plot: {search:?}");
|
||||
assert!(search.first_low_refined.is_none(), "search refined a low contact it does not reach: {search:?}");
|
||||
assert!(search.first_close_fire.is_none(), "search authorized a launch: {search:?}");
|
||||
|
||||
let height = run_profile_world(&[RadarRole::Height], 500).0;
|
||||
assert!(height.first_high.is_none(), "the mast radar searched beyond its local patch: {height:?}");
|
||||
assert!(height.first_low_refined.is_some(), "the mast radar did not refine the low contact: {height:?}");
|
||||
assert!(height.first_close_fire.is_none(), "the mast radar authorized a launch: {height:?}");
|
||||
|
||||
let engagement = run_profile_world(&[RadarRole::Engagement], 500).0;
|
||||
assert!(engagement.first_high.is_none(), "the engagement radar searched beyond its local patch: {engagement:?}");
|
||||
assert!(engagement.first_low_refined.is_none(), "the engagement radar reached a low contact below the horizon: {engagement:?}");
|
||||
assert!(engagement.first_close_fire.is_some(), "the engagement radar gave no fire plot: {engagement:?}");
|
||||
assert!(engagement.max_channels <= 2, "more than two tracked contacts: {engagement:?}");
|
||||
|
||||
let search_height = run_profile_world(&[RadarRole::Search, RadarRole::Height], 500).0;
|
||||
assert!(search_height.first_high.is_some() && search_height.first_low_refined.is_some());
|
||||
assert!(search_height.first_close_fire.is_none(), "a search/height pair authorized a launch: {search_height:?}");
|
||||
|
||||
let search_engagement = run_profile_world(&[RadarRole::Search, RadarRole::Engagement], 500).0;
|
||||
assert!(search_engagement.first_high.is_some() && search_engagement.first_close_fire.is_some());
|
||||
assert!(search_engagement.first_low_refined.is_none(), "the pair covered the mast's low gap: {search_engagement:?}");
|
||||
|
||||
let height_engagement = run_profile_world(&[RadarRole::Height, RadarRole::Engagement], 500).0;
|
||||
assert!(height_engagement.first_low_refined.is_some() && height_engagement.first_close_fire.is_some());
|
||||
assert!(height_engagement.first_high.is_none(), "the pair covered the search's far picture: {height_engagement:?}");
|
||||
|
||||
let full = run_profile_world(&[RadarRole::Search, RadarRole::Height, RadarRole::Engagement], 500).0;
|
||||
assert!(full.first_high.is_some() && full.first_low_refined.is_some() && full.first_close_fire.is_some(), "{full:?}");
|
||||
assert!(!full.search_or_height_authorized, "a non-fire radar authorized a launch");
|
||||
// There is no set bonus in the profile table: a duplicated station adds no
|
||||
// function, and the full set's advantage is only the union of the three jobs.
|
||||
let duplicate = run_profile_world(&[RadarRole::Search, RadarRole::Search], 500).0;
|
||||
assert!(duplicate.first_low_refined.is_none() && duplicate.first_close_fire.is_none(), "two search radars invented another function: {duplicate:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
|
||||
let mut sim = Sim::new(1341);
|
||||
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
|
||||
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
|
||||
let receiver = {
|
||||
let id = sim.id();
|
||||
let mut s400 = Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0);
|
||||
// A blind receiver: only the network can give it a track.
|
||||
s400.comps.0[Part::Sensor as usize] = 0.0;
|
||||
s400.roles = 0xff;
|
||||
sim.sams.push(s400);
|
||||
sim.sams.len() - 1
|
||||
};
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(200.0, 120.0, 0.0), DVec3::Z, DVec3::new(200.0, 120.0, 0.0));
|
||||
let id = sim.drones[0].id;
|
||||
let mut ground = Ground::default();
|
||||
let targets = vec![sim.drones[0].pos];
|
||||
let radars = [search, engagement];
|
||||
for tick in 1..=120 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
let own = sim.sams[engagement].track(id).expect("the engagement radar measured the target");
|
||||
assert_eq!(own.source, sim.sams[engagement].id);
|
||||
assert_eq!(own.product, Measure::Fire);
|
||||
assert!(own.quality >= FIRE_QUALITY && own.own_authorizes(sim.tick));
|
||||
let relayed = sim.sams[receiver].track(id).expect("the network shared the plot");
|
||||
assert_eq!(relayed.own_tick, 0, "a relay became the receiver's own measurement");
|
||||
assert_eq!(relayed.tick, own.tick, "a relay refreshed the measurement's age");
|
||||
assert!(relayed.product == Measure::Fire && relayed.quality == own.quality, "relay lost product/quality");
|
||||
assert_eq!(relayed.source, sim.sams[engagement].id, "relay lost the measuring station");
|
||||
assert!(!relayed.own_authorizes(sim.tick));
|
||||
let opts = why::Opts { last_chance: false, far_shots: false };
|
||||
{
|
||||
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
|
||||
let drone = &sim.drones[0];
|
||||
assert!(why::basis(&sim.sams[receiver], load, relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_none(), "a relayed plot authorized a launch");
|
||||
}
|
||||
// A launcher without a radar may use the supporting radar's own confirmed plot.
|
||||
sim.sams[receiver].set_mode(battery::SamMode::LauncherOnly);
|
||||
for tick in 121..=122 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
let relayed = *sim.sams[receiver].track(id).expect("the launcher re-received the network plot");
|
||||
assert!(why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick));
|
||||
{
|
||||
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
|
||||
let drone = &sim.drones[0];
|
||||
assert!(why::basis(&sim.sams[receiver], load, &relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_some());
|
||||
}
|
||||
// The search radar's plot is coarse: it does not authorize even a launcher.
|
||||
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[search]], id, sim.tick));
|
||||
// A broken data link ends the cue even while the radar itself still measures.
|
||||
sim.sams[engagement].comps.0[Part::Comms as usize] = 0.0;
|
||||
assert_eq!(sim.sams[engagement].link_range(), 0.0);
|
||||
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_air_picture_prefers_the_better_plot_at_one_tick() {
|
||||
let mut sim = Sim::new(1345);
|
||||
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
|
||||
let track = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
|
||||
let id = sim.drones[0].id;
|
||||
let mut ground = Ground::default();
|
||||
let targets = vec![sim.drones[0].pos];
|
||||
for tick in 1..=5 {
|
||||
sweep(&mut sim, &mut ground, &[search, track], &targets, tick);
|
||||
}
|
||||
let pic = sim.air_picture();
|
||||
let t = pic.tracks.iter().find(|t| t.id == id).expect("the raid is on the picture");
|
||||
assert_eq!(t.source, sim.sams[track].id, "a coarse plot won over the better one at the same tick");
|
||||
assert_eq!(t.product, Measure::Fire);
|
||||
assert!(t.own_authorizes(sim.tick));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
|
||||
let mut sim = Sim::new(1344);
|
||||
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
|
||||
for x in [100.0, 140.0, 180.0, 220.0] {
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
|
||||
}
|
||||
let mut ground = Ground::default();
|
||||
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
|
||||
for tick in 1..=40 {
|
||||
sweep(&mut sim, &mut ground, &[engagement], &targets, tick);
|
||||
}
|
||||
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
|
||||
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
|
||||
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
|
||||
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
|
||||
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
|
||||
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
|
||||
let mut sim = Sim::new(1342);
|
||||
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
|
||||
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 20.0);
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
|
||||
let id = sim.drones[0].id;
|
||||
let mut ground = Ground::default();
|
||||
let targets = vec![sim.drones[0].pos];
|
||||
let radars = [search, engagement];
|
||||
for tick in 1..=80 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
assert!(sim.sams[engagement].track(id).is_some_and(|t| t.own_authorizes(sim.tick)));
|
||||
let healthy = sim.sams[engagement].track(id).unwrap().own_quality;
|
||||
// Off: the station emits nothing, its own plots stop, the neighbour still feeds the network.
|
||||
sim.sams[engagement].radar_on = false;
|
||||
let before = sim.sams[engagement].track(id).map(|t| t.own_tick);
|
||||
for tick in 81..=110 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
assert!(!sim.sams[engagement].radar_up());
|
||||
assert_eq!(sim.sams[engagement].track(id).map(|t| t.own_tick), before, "a silent radar renewed its own plot");
|
||||
assert!(sim.sams[search].track(id).is_some_and(|t| t.own_tick > 0));
|
||||
// Damage: a worn sensor still measures, with worse quality and no launch right.
|
||||
sim.sams[engagement].radar_on = true;
|
||||
sim.sams[engagement].comps.0[Part::Sensor as usize] = 0.2;
|
||||
for tick in 111..=180 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
let worn = sim.sams[engagement].track(id).expect("a worn radar still measures");
|
||||
assert!(worn.own_quality < healthy, "damage did not lower quality: {worn:?}");
|
||||
assert!(!worn.own_authorizes(sim.tick), "a worn sensor still authorized a launch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multifunction_and_embedded_radars_keep_their_fire_authority() {
|
||||
let mut sim = Sim::new(1343);
|
||||
let multi = radar_with_role(&mut sim, RadarRole::Multifunction, 0.0);
|
||||
let pantsir = radar_at(&mut sim, SamKind::Pantsir, 20.0);
|
||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
|
||||
let id = sim.drones[0].id;
|
||||
let mut ground = Ground::default();
|
||||
let targets = vec![sim.drones[0].pos];
|
||||
let radars = [multi, pantsir];
|
||||
for tick in 1..=100 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
}
|
||||
assert!(sim.sams[multi].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "the universal profile lost its own fire plot");
|
||||
assert!(sim.sams[pantsir].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "an embedded radar lost its own fire plot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
|
||||
// One seed and one ridge: the low contact hides behind it, the high one flies over it,
|
||||
// and two close contacts compete for the engagement channels on the far side.
|
||||
let targets = [
|
||||
DVec3::new(250.0, 84.0, 0.0),
|
||||
DVec3::new(700.0, 500.0, 0.0),
|
||||
DVec3::new(240.0, 90.0, 30.0),
|
||||
DVec3::new(260.0, 95.0, -20.0),
|
||||
];
|
||||
#[derive(Default, Debug)]
|
||||
struct RidgeStats {
|
||||
low_marked: bool,
|
||||
low_refined: bool,
|
||||
low_fire: bool,
|
||||
high_marked: bool,
|
||||
track_channels: usize,
|
||||
nonfire_authorized: bool,
|
||||
}
|
||||
let run = |stations: &[(RadarRole, DVec3)], land| -> RidgeStats {
|
||||
let mut sim = Sim::new(134);
|
||||
let radars: Vec<usize> = stations
|
||||
.iter()
|
||||
.map(|(role, pos)| {
|
||||
let id = sim.id();
|
||||
let mut sam = Sam::new(id, SamKind::Radar, *pos, 0.0);
|
||||
sam.set_radar_role(*role);
|
||||
sim.sams.push(sam);
|
||||
sim.sams.len() - 1
|
||||
})
|
||||
.collect();
|
||||
for (k, pos) in targets.iter().enumerate() {
|
||||
let kind = if k < 2 { DroneKind::Shahed } else { DroneKind::Gerbera };
|
||||
sim.add_drone(kind, *pos, DVec3::Z, *pos);
|
||||
}
|
||||
let ids: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
|
||||
let mut ground = Ground::default();
|
||||
// Unknown land hides nothing: let the heights answer before any measurement counts.
|
||||
for tick in 1..=60 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
answer_land(&mut ground, land, tick);
|
||||
}
|
||||
for i in &radars {
|
||||
sim.sams[*i].tracks.clear();
|
||||
}
|
||||
let mut stats = RidgeStats::default();
|
||||
for tick in 61..=560 {
|
||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
||||
answer_land(&mut ground, land, tick);
|
||||
for &i in &radars {
|
||||
let sam = &sim.sams[i];
|
||||
let profile = sam.radar_profile();
|
||||
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
|
||||
if t.id == ids[0] {
|
||||
stats.low_marked = true;
|
||||
stats.low_refined |= t.product == Measure::Refine;
|
||||
stats.low_fire |= t.own_authorizes(sim.tick);
|
||||
}
|
||||
stats.high_marked |= t.id == ids[1];
|
||||
}
|
||||
if profile.id == "radar_track" {
|
||||
stats.track_channels = stats.track_channels.max(sam.own_channels_used());
|
||||
}
|
||||
if profile.id == "radar_search" || profile.id == "radar_height" {
|
||||
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
||||
}
|
||||
}
|
||||
}
|
||||
stats
|
||||
};
|
||||
let near = DVec3::new(0.0, 64.0, 0.0);
|
||||
let far = DVec3::new(220.0, 64.0, 0.0);
|
||||
let ridge = ridge_at(150, 100, 60);
|
||||
let search = run(&[(RadarRole::Search, near)], &ridge);
|
||||
assert!(search.high_marked, "the search radar lost the high contact over the ridge: {search:?}");
|
||||
assert!(!search.low_marked, "the search radar saw through the ridge: {search:?}");
|
||||
// The same station on flat land does mark the low contact: the ridge is what hides it.
|
||||
let flat = ridge_at(150, 0, 60);
|
||||
let control = run(&[(RadarRole::Search, near)], &flat);
|
||||
assert!(control.low_marked, "the control lost the low contact on flat land: {control:?}");
|
||||
let height = run(&[(RadarRole::Height, far)], &ridge);
|
||||
assert!(height.low_refined, "the mast did not refine the low contact behind the ridge: {height:?}");
|
||||
assert!(!height.high_marked && !height.low_fire, "the mast left its patch or authorized a launch: {height:?}");
|
||||
let engagement = run(&[(RadarRole::Engagement, far)], &ridge);
|
||||
assert!(engagement.low_fire, "the engagement radar gave no fire plot on the low contact: {engagement:?}");
|
||||
assert!(!engagement.high_marked, "the engagement radar searched beyond its patch: {engagement:?}");
|
||||
assert!(engagement.track_channels <= 2, "more than two tracked contacts: {engagement:?}");
|
||||
let full = run(&[(RadarRole::Search, near), (RadarRole::Height, far), (RadarRole::Engagement, far)], &ridge);
|
||||
assert!(full.high_marked && full.low_refined && full.low_fire, "the full set lost a job on the ridge: {full:?}");
|
||||
assert!(!full.nonfire_authorized, "a non-fire radar authorized a launch: {full:?}");
|
||||
assert!(full.track_channels <= 2, "the engagement radar exceeded its channels: {full:?}");
|
||||
}
|
||||
|
||||
+33
-222
@@ -8,15 +8,12 @@
|
||||
//! (a period by the kind of radar; an electronic one also revisits what it holds
|
||||
//! more often), a target is measured when the beam passes it, with a chance that
|
||||
//! falls with range and size, and the measurement is kept as a *track*: where it
|
||||
//! was measured, how fast it then seemed to go (from the measured places, never
|
||||
//! the target's own figures), and when. Between measurements the track is
|
||||
//! was and how fast it went then, and when. Between measurements the track is
|
||||
//! carried on by that velocity (a forecast, shown as one), and after three missed
|
||||
//! scans it is dropped. A fire-control lock on a target the system is engaging is
|
||||
//! a dedicated channel: it measures every tick while the target is in reach and in
|
||||
//! sight. The track also carries what the measurements say of the contact's class,
|
||||
//! the estimate growing only on real measurements: a forecast, a relayed copy adds
|
||||
//! nothing to it. The network passes tracks with the age of their measurement;
|
||||
//! relaying makes none of them fresher.
|
||||
//! sight. The network passes tracks with the age of their measurement; relaying
|
||||
//! makes none of them fresher.
|
||||
use super::*;
|
||||
|
||||
/// Rays round a radar, and blocks between the land's samples along them.
|
||||
@@ -27,8 +24,6 @@ pub(super) const LINK: f64 = 2250.0;
|
||||
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
|
||||
pub(super) const MISSILE_AGE: u64 = 120;
|
||||
pub(super) const GUN_AGE: u64 = 3;
|
||||
/// A fire plot below this quality is not confirmed enough to authorize a launch.
|
||||
pub const FIRE_QUALITY: u8 = 50;
|
||||
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
|
||||
pub(super) const GUN_PICK_AGE: u64 = 40;
|
||||
/// A track older than this is shown as a forecast.
|
||||
@@ -92,7 +87,7 @@ pub(super) fn antenna(sam: &Sam) -> DVec3 {
|
||||
}
|
||||
|
||||
fn sensor_span(sam: &Sam) -> f64 {
|
||||
sam.kind.spec().sensor * sam.radar_profile().reach
|
||||
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
|
||||
}
|
||||
|
||||
/// How far a system's search radar reaches for this kind at `height` over the land:
|
||||
@@ -102,7 +97,7 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
|
||||
if spec.sensor <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25);
|
||||
let radar = spec.sensor * sam.radar_fit() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
|
||||
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
|
||||
radar.min(horizon).max(NEAR)
|
||||
}
|
||||
@@ -147,7 +142,7 @@ impl Sim {
|
||||
let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit());
|
||||
let height = LOW_KIND.spec().clearance;
|
||||
let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast());
|
||||
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach);
|
||||
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
|
||||
let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25);
|
||||
let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR);
|
||||
let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s)));
|
||||
@@ -248,31 +243,17 @@ impl Ident {
|
||||
}
|
||||
|
||||
/// What a system knows of one target: the last measurement, not the target itself.
|
||||
///
|
||||
/// The track never carries the target's type or its true velocity (#133): `class` is what the
|
||||
/// radars inferred from the measurements so far, `vel` the speed those measurements showed —
|
||||
/// none from the first blip, then the change of the measured places between real measurements,
|
||||
/// smoothed a little. The forecast and the guns live with that.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Track {
|
||||
pub id: u32,
|
||||
/// What the radars make of it from the measurements (never the target's own type).
|
||||
pub class: ClassEst,
|
||||
/// Where it was measured and how fast it seemed to go then (blocks, blocks a tick).
|
||||
/// What the radar made of it when it measured (the class the picture shows).
|
||||
pub kind: DroneKind,
|
||||
/// Where it was and how it went when last measured (blocks, blocks a tick).
|
||||
pub pos: DVec3,
|
||||
pub vel: DVec3,
|
||||
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
|
||||
pub tick: u64,
|
||||
pub own_tick: u64,
|
||||
/// The station that measured the latest plot, and what it is good for.
|
||||
pub source: u32,
|
||||
pub product: battery::Measure,
|
||||
/// Measurement quality (0..100), separate from identification (`hits`).
|
||||
pub quality: u8,
|
||||
/// This system's own measurement provenance. A fresher relay may replace
|
||||
/// the published plot without granting or erasing the station's own right.
|
||||
pub own_product: battery::Measure,
|
||||
pub own_quality: u8,
|
||||
/// Ticks the track lives without a new measurement.
|
||||
pub ttl: u32,
|
||||
pub hits: u8,
|
||||
@@ -313,25 +294,6 @@ impl Track {
|
||||
pub fn own_within(&self, now: u64, age: u64) -> bool {
|
||||
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
|
||||
}
|
||||
/// The station's own measurement was a confirmed fire plot, fresh enough.
|
||||
/// A relayed plot has `own_tick == 0` and never passes this test.
|
||||
pub fn own_fire_within(&self, now: u64, age: u64) -> bool {
|
||||
self.own_within(now, age) && self.own_product.allows_fire() && self.own_quality >= FIRE_QUALITY
|
||||
}
|
||||
/// Own plot good enough for a launcher's ordinary shot.
|
||||
pub fn own_authorizes(&self, now: u64) -> bool {
|
||||
self.own_fire_within(now, MISSILE_AGE)
|
||||
}
|
||||
/// Who measured the latest plot, as an ID (`0`: no station).
|
||||
pub fn measured_by(&self) -> Option<u32> {
|
||||
(self.source != 0).then_some(self.source)
|
||||
}
|
||||
/// One passive optical look at this contact (#136): refines the class alone. The plot, its
|
||||
/// age, source, quality and the station's own fire rights are untouched — optics never
|
||||
/// authorize a shot and never make a track fresher.
|
||||
pub fn refine_class_optical(&mut self, class: Class, uncertainty: f64) {
|
||||
self.class = self.class.step_optical(class, uncertainty);
|
||||
}
|
||||
pub fn ident(&self) -> Ident {
|
||||
match self.hits {
|
||||
0 | 1 => Ident::Unknown,
|
||||
@@ -348,12 +310,16 @@ impl Track {
|
||||
impl Sam {
|
||||
/// Fictional antenna height and scan characteristics for gameplay roles.
|
||||
pub(super) fn sensor_mast(&self) -> f64 {
|
||||
self.kind.spec().mast + self.radar_profile().mast
|
||||
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
|
||||
}
|
||||
pub(super) fn scan_profile(&self) -> Scan {
|
||||
if self.kind != SamKind::Radar { return self.kind.scan(); }
|
||||
let profile = self.radar_profile();
|
||||
Scan { period: profile.cycle, agile: profile.agile }
|
||||
match self.radar_role {
|
||||
battery::RadarRole::Multifunction => self.kind.scan(),
|
||||
battery::RadarRole::Search => Scan { period: 170, agile: false },
|
||||
battery::RadarRole::Engagement => Scan { period: 70, agile: true },
|
||||
battery::RadarRole::Height => Scan { period: 140, agile: false },
|
||||
}
|
||||
}
|
||||
/// Ticks for its beam to go round (longer when the radar is damaged).
|
||||
pub(super) fn scan_ticks(&self) -> f64 {
|
||||
@@ -366,10 +332,6 @@ impl Sam {
|
||||
pub fn track(&self, id: u32) -> Option<&Track> {
|
||||
self.tracks.iter().find(|t| t.id == id)
|
||||
}
|
||||
/// Refined/fire channels this station is currently using.
|
||||
pub fn own_channels_used(&self) -> usize {
|
||||
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
|
||||
@@ -383,18 +345,10 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
|
||||
match index.get(&t.id) {
|
||||
Some(&k) => {
|
||||
let mine = &mut tracks[k];
|
||||
// Prefer the fresher plot; at the same tick the better one (a fire plot
|
||||
// over a coarse search plot), without making anything newer.
|
||||
if t.tick > mine.tick || (t.tick == mine.tick && t.quality > mine.quality) {
|
||||
// A relayed plot is published with its source/quality, but it
|
||||
// neither refreshes nor erases this station's own measurement and its right.
|
||||
let (own_tick, own_product, own_quality, locked) = if t.own_tick > 0 {
|
||||
(t.own_tick, t.own_product, t.own_quality, t.locked)
|
||||
} else {
|
||||
(mine.own_tick, mine.own_product, mine.own_quality, mine.locked)
|
||||
};
|
||||
if t.tick > mine.tick {
|
||||
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
|
||||
let hits = mine.hits.max(t.hits);
|
||||
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t };
|
||||
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -404,23 +358,6 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A plot's quality (0..100). It uses only the measured geometry and the
|
||||
/// station's own fit, never the target's hidden state.
|
||||
fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 {
|
||||
let ratio = ratio.clamp(0.0, 1.0);
|
||||
let base = match profile.id {
|
||||
"radar_search" => 46.0 - 14.0 * ratio,
|
||||
"radar_height" => 74.0 - 12.0 * ratio + if height < 120.0 { 8.0 } else if height < 200.0 { 3.0 } else { 0.0 },
|
||||
"radar_track" => 88.0 - 12.0 * ratio,
|
||||
"radar_multi" => 72.0 - 14.0 * ratio,
|
||||
_ => 78.0 - 14.0 * ratio,
|
||||
};
|
||||
// A search plot is coarse whatever the profile; only a matched refinement or
|
||||
// a fire plot gets the profile's accuracy.
|
||||
let base = if product == battery::Measure::Search { base.min(48.0) } else { base };
|
||||
(base * sam.radar_fit()).round().clamp(5.0, 99.0) as u8
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
|
||||
/// into the tracks, old tracks out, and the network's tracks shared.
|
||||
@@ -464,7 +401,6 @@ impl Sim {
|
||||
index.clear();
|
||||
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
|
||||
let spec = sam.kind.spec();
|
||||
let profile = sam.radar_profile();
|
||||
let scan = sam.scan_profile();
|
||||
let period = sam.scan_ticks();
|
||||
let w = TAU / period;
|
||||
@@ -472,9 +408,6 @@ impl Sim {
|
||||
sam.beam = (b0 + w) % TAU;
|
||||
let at = antenna(sam);
|
||||
let horizon = self.horizons.get(&sam.id);
|
||||
let local = spec.sensor * profile.local;
|
||||
// Channels already refining or holding fire plots. Search plots do not use one.
|
||||
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count();
|
||||
let mut fresh: Vec<Track> = Vec::new();
|
||||
for (d, h) in self.drones.iter().zip(&heights) {
|
||||
if !d.alive() {
|
||||
@@ -482,7 +415,7 @@ impl Sim {
|
||||
}
|
||||
let rel = d.pos - at;
|
||||
let dist = rel.length();
|
||||
if dist > spec.sensor * profile.reach.max(1.0) * 1.2 {
|
||||
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
|
||||
continue;
|
||||
}
|
||||
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
|
||||
@@ -490,36 +423,13 @@ impl Sim {
|
||||
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
|
||||
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
|
||||
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
|
||||
// A network plot cues a fire-quality radar to look, but is never itself a
|
||||
// measurement: reach, terrain, probability and noise still apply.
|
||||
let cue = profile.allows(battery::Measure::Fire)
|
||||
// A search radar's network track cues this fictional tracking radar to look, but is
|
||||
// never itself a measurement: reach, terrain, probability and noise still apply.
|
||||
let cue = sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement
|
||||
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
|
||||
if !(in_beam || locked || revisit || cue) {
|
||||
continue;
|
||||
}
|
||||
// The separate stations search their own patch; a cue or an already held
|
||||
// contact may be followed beyond it, never an arbitrary target of the map.
|
||||
if profile.local < 1.0 && dist > local && !locked && !(cue || held.is_some_and(|t| t.own_tick > 0)) {
|
||||
continue;
|
||||
}
|
||||
// The tracked-contact channels are a hard limit: work per tick stays bounded
|
||||
// and a full station does not silently refine the whole sky. A station already
|
||||
// refining a contact keeps its channel; a new refinement needs a free one, and
|
||||
// without one the station still publishes its ordinary coarse search plot.
|
||||
let own_held = held.is_some_and(|t| t.own_tick > 0);
|
||||
let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
|
||||
let mut product = if profile.allows(battery::Measure::Fire) {
|
||||
battery::Measure::Fire
|
||||
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
|
||||
// Refinement only applies to a contact already matched, own or network.
|
||||
battery::Measure::Refine
|
||||
} else {
|
||||
battery::Measure::Search
|
||||
};
|
||||
let wants_channel = product != battery::Measure::Search && !holds_channel;
|
||||
if profile.channels > 0 && wants_channel && used >= profile.channels as usize {
|
||||
product = battery::Measure::Search;
|
||||
}
|
||||
let height = h.unwrap_or(d.pos.y - sam.pos.y);
|
||||
let reach = reach(sam, d.kind, height);
|
||||
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
|
||||
@@ -536,40 +446,17 @@ impl Sim {
|
||||
if dist > NEAR && dice(seed, now, key, 0) >= p {
|
||||
continue;
|
||||
}
|
||||
let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread };
|
||||
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
|
||||
let measured = d.pos + noise;
|
||||
let quality = plot_quality(sam, profile, product, dist / reach.max(1.0), height);
|
||||
if profile.channels > 0 && wants_channel && product != battery::Measure::Search {
|
||||
used += 1;
|
||||
}
|
||||
let hits = held.map_or(1, |t| t.hits.saturating_add(1));
|
||||
// What this measurement says of the contact's class and speed, from the measured
|
||||
// places alone: the first blip gives neither; a later one, the change of place over
|
||||
// the ticks since the last real measurement (not a forecast's), smoothed into what
|
||||
// the track held so the class does not flap on one noisy pair (#133).
|
||||
let (vel, class) = match held {
|
||||
Some(p) if p.tick < now => {
|
||||
let seen = (measured - p.pos) / (now - p.tick) as f64;
|
||||
let vel = if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) };
|
||||
(vel, p.class.step(hits, vel.length()))
|
||||
}
|
||||
_ => (DVec3::ZERO, ClassEst::Unknown),
|
||||
};
|
||||
let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 };
|
||||
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
|
||||
fresh.push(Track {
|
||||
id: d.id,
|
||||
class,
|
||||
pos: measured,
|
||||
vel,
|
||||
kind: d.kind,
|
||||
pos: d.pos + noise,
|
||||
vel: d.vel,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: sam.id,
|
||||
product,
|
||||
quality,
|
||||
own_product: product,
|
||||
own_quality: quality,
|
||||
ttl,
|
||||
hits,
|
||||
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
|
||||
locked,
|
||||
});
|
||||
}
|
||||
@@ -595,37 +482,7 @@ impl Sim {
|
||||
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick > 0 && t.own_tick == t.tick).copied().collect::<Vec<_>>()))
|
||||
.filter(|s| !s.3.is_empty())
|
||||
.collect();
|
||||
// One freshest track per radar is all a cue needs: the posts never walk every contact.
|
||||
let cues: Vec<(u32, DVec3, f64, Track)> = if self.sams.iter().any(|s| s.kind == SamKind::Optical) {
|
||||
shared
|
||||
.iter()
|
||||
.filter_map(|(id, at, range, tracks)| tracks.iter().max_by_key(|t| t.tick).map(|t| (*id, *at, *range, *t)))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for sam in &mut self.sams {
|
||||
if sam.kind == SamKind::Optical {
|
||||
// An optical post receives a cue, not a track: the freshest network measurement within
|
||||
// link range only points its head, and none of it enters `tracks`, `seen` or `own`.
|
||||
sam.seen.clear();
|
||||
sam.own.clear();
|
||||
if sam.alive() && !sam.moving() && sam.link_range() > 0.0 {
|
||||
let mine = sam.link_range();
|
||||
let mut best: Option<Track> = None;
|
||||
for (id, at, range, t) in &cues {
|
||||
if *id != sam.id && at.distance(sam.pos) <= range.min(mine)
|
||||
&& best.is_none_or(|b: Track| t.tick > b.tick)
|
||||
{
|
||||
best = Some(*t);
|
||||
}
|
||||
}
|
||||
if let Some(t) = best {
|
||||
sam.optical.offer_cue(t);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() {
|
||||
index.clear();
|
||||
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
|
||||
@@ -633,7 +490,7 @@ impl Sim {
|
||||
for (id, at, range, tracks) in &shared {
|
||||
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
|
||||
for t in tracks {
|
||||
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t });
|
||||
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -647,9 +504,6 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Passive optics (#136) look after the network has spoken: a cue is only a cue, and every
|
||||
// observation it makes is its own, never a track and never an emission.
|
||||
self.update_optics(ground);
|
||||
}
|
||||
|
||||
/// Whether any system's radar holds this drone (the player's radar shows only those).
|
||||
@@ -666,25 +520,8 @@ impl Sim {
|
||||
let mut tracks: Vec<Track> = if unaided {
|
||||
self.drones
|
||||
.iter()
|
||||
// No system is deployed: no estimation happens, the fallback is the sky as it is
|
||||
// (the screens have always had it), with the figures a system would show.
|
||||
.filter(|d| d.alive())
|
||||
.map(|d| Track {
|
||||
id: d.id,
|
||||
class: ClassEst::Firm(d.kind.spec().class),
|
||||
pos: d.pos,
|
||||
vel: d.vel,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: 0,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 100,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 100,
|
||||
ttl: 1,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
})
|
||||
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
|
||||
.collect()
|
||||
} else {
|
||||
self.picture().into_values().collect()
|
||||
@@ -693,12 +530,11 @@ impl Sim {
|
||||
AirPicture { now, tracks, unaided }
|
||||
}
|
||||
|
||||
/// The freshest track of each drone any system holds: the air picture. At one
|
||||
/// tick the better plot (quality, then product) is the one the player sees.
|
||||
/// The freshest track of each drone any system holds: the air picture.
|
||||
pub fn picture(&self) -> HashMap<u32, Track> {
|
||||
let mut best: HashMap<u32, Track> = HashMap::new();
|
||||
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
|
||||
if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) {
|
||||
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
|
||||
best.insert(t.id, *t);
|
||||
}
|
||||
}
|
||||
@@ -776,28 +612,3 @@ mod low_view_tests {
|
||||
assert!(seen > 0 && tint.as_millis() < 100, "{tint:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod relay_tests {
|
||||
use super::*;
|
||||
|
||||
/// A relayed measurement: its class and hits arrive as they were, the receiver's own age is
|
||||
/// kept, and passing the same message again adds nothing (#133).
|
||||
#[test]
|
||||
fn a_repeated_relay_adds_no_confidence_and_stays_foreign() {
|
||||
let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 400, hits: 1, locked: false };
|
||||
let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, source: 2, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 2, locked: false };
|
||||
let mut tracks = vec![ours];
|
||||
let mut index: HashMap<u32, usize> = HashMap::from([(7, 0)]);
|
||||
merge(&mut tracks, &mut index, relay);
|
||||
assert_eq!(tracks[0].own_tick, 90, "a relayed track is not the receiver's own measurement");
|
||||
for _ in 0..5 {
|
||||
merge(&mut tracks, &mut index, relay);
|
||||
}
|
||||
assert_eq!(tracks.len(), 1, "a relay of a held measurement is one track");
|
||||
assert_eq!(tracks[0].hits, 2, "a repeated relay added confidence");
|
||||
assert_eq!(tracks[0].class, ClassEst::Probable(Class::Drone), "a relay altered the estimate");
|
||||
assert_eq!(tracks[0].tick, 100, "a relay refreshed the measurement");
|
||||
assert_eq!(tracks[0].own_tick, 90, "a relay became the receiver's own");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1083,22 +1083,7 @@ mod tests {
|
||||
sim.drones.push(d);
|
||||
sim.tick = hidden_launch_tick;
|
||||
sim.scout_launch(drone, id, DroneKind::Shahed, DVec3::new(hidden_x, 70.0, 700.0));
|
||||
let track = sight::Track {
|
||||
id: drone,
|
||||
class: ClassEst::Firm(Class::Drone),
|
||||
pos: DVec3::new(0.0, 100.0, 1000.0),
|
||||
vel: -DVec3::Z * 5.0,
|
||||
tick: 100,
|
||||
own_tick: 100,
|
||||
source: 1,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 90,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 90,
|
||||
ttl: 100,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
};
|
||||
let track = sight::Track { id: drone, kind: DroneKind::Shahed, pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false };
|
||||
sim.sams[0].tracks.push(track);
|
||||
sim.tick = 100;
|
||||
sim.step_strikes(&mut ground, None, &mut out);
|
||||
@@ -1444,14 +1429,10 @@ mod tests {
|
||||
fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() {
|
||||
let mut sim = Sim::new(5);
|
||||
|
||||
// Two radars apart watch the start of an off-map site's drones. They hold fire: this test
|
||||
// is about the sighting and the strike, not about intercepting drones flown at 2 blocks a
|
||||
// tick (which measure as cruise missiles, #133, and would be engaged on the roles).
|
||||
// Two radars apart watch the start of an off-map site's drones.
|
||||
for x in [-150.0, 150.0] {
|
||||
let id = sim.id();
|
||||
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0);
|
||||
sam.roles = 0;
|
||||
sim.sams.push(sam);
|
||||
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,
|
||||
|
||||
@@ -380,31 +380,6 @@ const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
|
||||
mast: 1.5,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_OPTICAL: SamSpec = SamSpec {
|
||||
name: "Оптический пост",
|
||||
key: "optical",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.0,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts {
|
||||
body: "airdef:radar_truck",
|
||||
launcher: None,
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: Some(("airdef:radar_panel", 1.2, 0.0, 0.6, -0.2)),
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 2.5,
|
||||
};
|
||||
|
||||
impl SamKind {
|
||||
/// Its row of numbers from `catalog/specs.json`.
|
||||
pub fn spec(self) -> &'static SamSpec {
|
||||
@@ -424,14 +399,13 @@ impl SamKind {
|
||||
SamKind::Tzm => &UNIT_SPEC_TZM,
|
||||
SamKind::Ew => &UNIT_SPEC_EW,
|
||||
SamKind::Light => &UNIT_SPEC_LIGHT,
|
||||
SamKind::Optical => &UNIT_SPEC_OPTICAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Save keys by kind; a rename needs an explicit migration.
|
||||
#[cfg(test)]
|
||||
pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 16] = [
|
||||
pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 15] = [
|
||||
(SamKind::Patriot, "patriot"),
|
||||
(SamKind::Gepard, "gepard"),
|
||||
(SamKind::Pantsir, "pantsir"),
|
||||
@@ -447,5 +421,4 @@ pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 16] = [
|
||||
(SamKind::Tzm, "tzm"),
|
||||
(SamKind::Ew, "ew"),
|
||||
(SamKind::Light, "light"),
|
||||
(SamKind::Optical, "optical"),
|
||||
];
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
|
||||
pub const VARIANTS: &[UnitVariant] = &[
|
||||
UnitVariant { id: "s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая", description: "Пусковая С-400 без своей РЛС: работает по данным сети." },
|
||||
UnitVariant { id: "s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая", description: "Пусковая С-500 без своей РЛС: работает по данным сети." },
|
||||
UnitVariant { id: "radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора", description: "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт." },
|
||||
UnitVariant { id: "radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения", description: "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск." },
|
||||
UnitVariant { id: "radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
|
||||
];
|
||||
@@ -27,8 +27,6 @@ pub enum SamKind {
|
||||
Ew,
|
||||
/// A searchlight: lights up targets at night for the guns.
|
||||
Light,
|
||||
/// A passive optical observation post: no radar, no weapon, one class observation at a time (#136).
|
||||
Optical,
|
||||
}
|
||||
|
||||
/// How a vehicle is put together: how its launcher or turret moves and is drawn.
|
||||
@@ -181,14 +179,6 @@ impl SamKind {
|
||||
let s = self.spec();
|
||||
s.missile.is_some() || s.gun.is_some()
|
||||
}
|
||||
/// Missiles its launcher's magazine holds; `None` without a launcher.
|
||||
pub fn missile_magazine(self) -> Option<u32> {
|
||||
self.spec().missile.as_ref().map(|m| m.magazine)
|
||||
}
|
||||
/// Whether it has a gun (its bursts are read by the status line).
|
||||
pub fn has_gun(self) -> bool {
|
||||
self.spec().gun.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sam {
|
||||
@@ -335,7 +325,7 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
|
||||
part(out, model, sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s), base, s);
|
||||
}
|
||||
if let Some((model, h, back, size, tilt)) = parts.spinner {
|
||||
let extra = if sam.kind == SamKind::Radar { sam.radar_profile().mast } else { 0.0 };
|
||||
let extra = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
|
||||
let foot = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
|
||||
for segment in 0..(extra as u32 / 2) {
|
||||
part(out, "airdef:radar_mast", foot + DVec3::Y * (segment as f64 * 2.0 + 0.5), base, 1.0);
|
||||
|
||||
+47
-269
@@ -14,20 +14,14 @@ pub(super) const UNSEEN: u8 = 4;
|
||||
/// Its track is older than a launcher fires on.
|
||||
pub(super) const STALE: u8 = 8;
|
||||
|
||||
/// Why a drone is not a candidate for a system at all. The role is checked against the track's
|
||||
/// *estimated* class, never the target's own (#133): an unidentified track is not blocked — the
|
||||
/// explicit policy is that it stays a candidate under the general rules (a system with no roles
|
||||
/// is holding its fire: nothing is a candidate for it) — and a probable or firm class out of the
|
||||
/// roles is, with the reason named in `why`.
|
||||
pub(super) fn target_blocks(roles: u8, track: Option<&Track>, now: u64, d: &Drone) -> u8 {
|
||||
(if d.alive() { 0 } else { DEAD })
|
||||
| (if track.is_some_and(|t| t.class.in_roles(roles)) { 0 } else { ROLE })
|
||||
| (if roles & d.kind.spec().class.bit() != 0 { 0 } else { ROLE })
|
||||
| (if track.is_some() { 0 } else { UNSEEN })
|
||||
| (if track.is_some_and(|t| t.age(now) > sight::MISSILE_AGE) { STALE } else { 0 })
|
||||
}
|
||||
|
||||
/// Alive, of a class the system engages (or not yet classified), and on its picture (own radar
|
||||
/// or the network's), fresh enough.
|
||||
/// Alive, of a class the system engages, and on its picture (own radar or the network's), fresh enough.
|
||||
pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool {
|
||||
target_blocks(roles, Some(track), now, d) == 0
|
||||
}
|
||||
@@ -56,15 +50,14 @@ pub(super) fn arrival(d: &Drone) -> f64 {
|
||||
d.pos.distance(d.target) / d.vel.length().max(0.1)
|
||||
}
|
||||
|
||||
/// Shoot-look-shoot that grows with urgency: a ballistic missile gets a pair, anything else one; a target
|
||||
/// Shoot-look-shoot that grows with urgency: ballistic missiles get a pair, anything else one; a target
|
||||
/// this close to its aim (ticks) has one more interceptor allowed on it at once, closer still another, and in the last seconds a fourth.
|
||||
/// The class is the track's estimate (#133): an unidentified contact is treated as not ballistic.
|
||||
pub(super) const URGENT: f64 = 240.0;
|
||||
pub(super) const DESPERATE: f64 = 110.0;
|
||||
pub(super) const FINAL: f64 = 60.0;
|
||||
|
||||
pub(super) fn needed(d: &Drone, class: ClassEst) -> u32 {
|
||||
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
|
||||
pub(super) fn needed(d: &Drone) -> u32 {
|
||||
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
|
||||
let t = arrival(d);
|
||||
base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL)
|
||||
}
|
||||
@@ -75,14 +68,12 @@ pub(super) const SHY_TICKS: u64 = 120;
|
||||
|
||||
// ---------------------------------------------------------------- the grounds to launch on
|
||||
|
||||
/// Last chance (`/airdef lastchance`): a track of a *known* class the system does not engage that
|
||||
/// is about to hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire
|
||||
/// (no roles) keeps to it. An unidentified track is no last-chance case: it is already a candidate
|
||||
/// under the general rules (#133).
|
||||
/// Last chance (`/airdef lastchance`): a target of a class the system does not engage that is about to
|
||||
/// hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire (no roles) keeps to it.
|
||||
pub(super) const LAST_CHANCE_TICKS: f64 = 200.0;
|
||||
|
||||
pub(super) fn last_chance(on: bool, roles: u8, class: ClassEst, d: &Drone, claimed: u32) -> bool {
|
||||
on && roles != 0 && !class.in_roles(roles) && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS
|
||||
pub(super) fn last_chance(on: bool, roles: u8, d: &Drone, claimed: u32) -> bool {
|
||||
on && roles != 0 && roles & d.kind.spec().class.bit() == 0 && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS
|
||||
}
|
||||
|
||||
/// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds.
|
||||
@@ -101,17 +92,14 @@ impl SamKind {
|
||||
/// A live big radar in data-link reach of `sam` that measured `id` recently.
|
||||
pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool {
|
||||
radars.iter().any(|r| {
|
||||
r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
|
||||
r.radar_role.authorizes()
|
||||
&& r.link_range() > 0.0
|
||||
&& sam.link_range() > 0.0
|
||||
&& r.alive()
|
||||
&& !r.moving()
|
||||
&& r.radar_up()
|
||||
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())
|
||||
&& r.track(id).is_some_and(|t| {
|
||||
let age = if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE };
|
||||
t.own_fire_within(now, age)
|
||||
})
|
||||
&& r.track(id).is_some_and(|t| t.own_tick > 0 && now.saturating_sub(t.own_tick) <= if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -149,37 +137,25 @@ pub(super) struct Opts {
|
||||
/// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option<Basis> {
|
||||
// A launch rests on the battery's own confirmed fire plot. A launcher
|
||||
// without its own radar may use a supporting radar's own fire plot; a
|
||||
// relayed plot, a search plot or a height refinement never authorizes an
|
||||
// ordinary shot. A heavy system's *far* shot is the exception it already
|
||||
// had: it may use the cue radar's own confirmed fire plot beyond its reach.
|
||||
let own = track.own_authorizes(now);
|
||||
if sam.mode == battery::SamMode::LauncherOnly {
|
||||
if !cued { return None; }
|
||||
} else if !own && !cued {
|
||||
return None;
|
||||
}
|
||||
if sam.mode == battery::SamMode::LauncherOnly && !cued { return None; }
|
||||
let blocks = target_blocks(sam.roles, Some(track), now, d);
|
||||
if blocks & !ROLE != 0 {
|
||||
return None;
|
||||
}
|
||||
let est = track.class;
|
||||
let reach = reach_blocks(load.min, load.max, k, sam.pos, track.est(now));
|
||||
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, est) != 0 {
|
||||
if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d) != 0 {
|
||||
return None;
|
||||
}
|
||||
if reach == 0 {
|
||||
// A normal shot belongs to the battery's own confirmed measurement;
|
||||
// a launcher-only battery uses its supporting radar's (checked above).
|
||||
return (own || sam.mode == battery::SamMode::LauncherOnly).then_some(Basis::Role);
|
||||
return Some(Basis::Role);
|
||||
}
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0;
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
|
||||
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
|
||||
}
|
||||
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
|
||||
(reach == 0 && last_chance(opts.last_chance, sam.roles, d, claimed)).then_some(Basis::LastChance)
|
||||
}
|
||||
|
||||
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
|
||||
@@ -332,37 +308,6 @@ impl Sim {
|
||||
return v;
|
||||
}
|
||||
if !sam.kind.armed() {
|
||||
if sam.kind == SamKind::Radar {
|
||||
let profile = sam.radar_profile();
|
||||
v.push(check(true, format!(
|
||||
"профиль {} [{}]: {}, оборот {:.1} с, каналы {}, локальный поиск {}",
|
||||
profile.name,
|
||||
profile.id,
|
||||
profile.products_text(),
|
||||
profile.cycle as f64 / 20.0,
|
||||
profile.channels,
|
||||
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
|
||||
)));
|
||||
v.push(check(true, format!("ограничение: {}", profile.limit)));
|
||||
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(), profile.channels)));
|
||||
let now = self.tick;
|
||||
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
|
||||
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
|
||||
for t in tracks.into_iter().take(4) {
|
||||
v.push(check(
|
||||
t.own_authorizes(now),
|
||||
format!(
|
||||
"цель {}: {} ({}), качество {}, возраст {:.1} с{}",
|
||||
t.id,
|
||||
t.own_product.name(),
|
||||
if t.own_authorizes(now) { "право на пуск" } else { "пуск не разрешает" },
|
||||
t.own_quality,
|
||||
now.saturating_sub(t.own_tick) as f64 / 20.0,
|
||||
if t.own_authorizes(now) { "" } else { "; нужно подтверждённое измерение станции" },
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
|
||||
return v;
|
||||
}
|
||||
@@ -407,10 +352,7 @@ impl Sim {
|
||||
let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| {
|
||||
self.drones
|
||||
.iter()
|
||||
// Of what the system's picture holds: a track of its roles' classes (or not yet
|
||||
// classified), or a known out-of-role one about to hit (the last chance) — never
|
||||
// the target's own class (#133).
|
||||
.filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target))))
|
||||
.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| {
|
||||
// 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);
|
||||
@@ -418,61 +360,44 @@ impl Sim {
|
||||
})
|
||||
});
|
||||
let Some(t) = subject else {
|
||||
// Nothing to look at: either the sky holds nothing for this system, or it holds only
|
||||
// tracks whose estimated class is out of the roles — the reasons differ and are named (#133).
|
||||
let held = self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id));
|
||||
// No roles is holding fire: a reason of its own, not an empty class filter.
|
||||
let text = if sam.roles == 0 {
|
||||
"роль: система не ведёт огонь (роли не заданы) — ни одна цель не выбирается".to_string()
|
||||
} else if held {
|
||||
format!("цели на картине есть, но не в ролях [{}] (классы по оценке)", roles_text(sam.roles))
|
||||
} else {
|
||||
format!("нет целей классов [{}]", roles_text(sam.roles))
|
||||
};
|
||||
v.push(check(false, text));
|
||||
v.push(check(false, format!("нет целей классов [{}]", roles_text(sam.roles))));
|
||||
return v;
|
||||
};
|
||||
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
|
||||
let dist = sam.track(t.id).map_or(t.pos, |tr| tr.est(self.tick)).distance(sam.pos);
|
||||
let track = sam.track(t.id);
|
||||
v.push(check(
|
||||
true,
|
||||
format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
|
||||
format!("цель: {} {}, {}", t.kind.spec().name, if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
|
||||
));
|
||||
let est = track.map_or(ClassEst::Unknown, |tr| tr.class);
|
||||
let track = sam.track(t.id);
|
||||
let blocks = target_blocks(sam.roles, track, now, t);
|
||||
// Where the system believes the target is: its track's forecast (the true place only when it has no track).
|
||||
let est_at = track.map_or(t.pos, |tr| tr.est(now));
|
||||
let est = track.map_or(t.pos, |tr| tr.est(now));
|
||||
let evel = track.map_or(t.vel, |tr| tr.vel);
|
||||
let first_claim = claimed(t, &missile_on, sam.target);
|
||||
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, first_claim);
|
||||
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, t, first_claim);
|
||||
let role_text = if blocks & ROLE == 0 {
|
||||
match est {
|
||||
ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(),
|
||||
_ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)),
|
||||
}
|
||||
format!("роль: {} в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
|
||||
} else if chance {
|
||||
format!(
|
||||
"последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет",
|
||||
est.name(),
|
||||
t.kind.spec().class.name(),
|
||||
roles_text(sam.roles),
|
||||
arrival(t) / 20.0
|
||||
)
|
||||
} else if sam.roles == 0 {
|
||||
"роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string()
|
||||
} else {
|
||||
format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles))
|
||||
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, est) } else { 0 };
|
||||
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_at - sam.pos).to_degrees().rem_euclid(360.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())));
|
||||
@@ -493,15 +418,7 @@ impl Sim {
|
||||
let age = tr.age(now) as f64 / 20.0;
|
||||
let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" };
|
||||
let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() };
|
||||
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
|
||||
let authority = tr.own_authorizes(now) || (sam.mode == battery::SamMode::LauncherOnly && radar_cue(sam, &radars, t.id, now));
|
||||
format!(
|
||||
"трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}; право на пуск: {}",
|
||||
tr.ident().name(),
|
||||
tr.class.name(),
|
||||
if blocks & STALE != 0 { "устарел" } else { "годен" },
|
||||
if authority { "своё подтверждённое измерение" } else { "нет (сеть или обзор не дают права)" }
|
||||
)
|
||||
format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}", tr.ident().name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" })
|
||||
}
|
||||
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
|
||||
};
|
||||
@@ -539,19 +456,19 @@ impl Sim {
|
||||
v.push(check(sam.reloading == 0 && !sam.empty && (sam.missiles > 0 || sam.bursts > 0), format!("{rounds}— {supply}")));
|
||||
let mount = sam.mount().0;
|
||||
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
|
||||
let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, evel, lead_speed);
|
||||
let (_, want_yaw, want_pitch) = aim_wants(mount, est, evel, lead_speed);
|
||||
let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch);
|
||||
let vertical = spec.family == Family::Vertical;
|
||||
let mut fires = false;
|
||||
if let Some(load) = &spec.missile {
|
||||
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at);
|
||||
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est);
|
||||
// Beyond the normal reach, a heavy system may fire on a big radar's cue.
|
||||
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
|
||||
let cued = 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)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class))
|
||||
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_at) == 0;
|
||||
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));
|
||||
if far {
|
||||
let fb = far_blocks(self.far_shots, sam, load, cued, role_in_reach);
|
||||
@@ -570,7 +487,7 @@ impl Sim {
|
||||
v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", super::distance(dist), super::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) }));
|
||||
}
|
||||
let free = first_claim;
|
||||
let need = sam.doctrine.needed(t, est);
|
||||
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();
|
||||
@@ -587,7 +504,7 @@ impl Sim {
|
||||
why.push("пусковая отказала".to_string());
|
||||
}
|
||||
v.push(check(mb == 0, if mb == 0 { "пусковая готова".to_string() } else { format!("пусковая не готова: {}", why.join(", ")) }));
|
||||
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est_at), t.id, t.id, err);
|
||||
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est), t.id, t.id, err);
|
||||
let turn = if vertical { "вертикальный старт" } else { "доворот" };
|
||||
v.push(check(aligned, format!("{turn}: ошибка наведения {:.0}°{}", err.to_degrees(), if aligned { "" } else { " — ещё доворачивается" })));
|
||||
// The land: the verdict the launch decision gave this target (`terrain::launch_blocks`) a moment ago.
|
||||
@@ -603,9 +520,7 @@ impl Sim {
|
||||
));
|
||||
}
|
||||
let doc_ok = chance || area | held_back == 0;
|
||||
let own = track.is_some_and(|tr| tr.own_authorizes(now));
|
||||
let authorized = own || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok;
|
||||
let grounds = authorized && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
|
||||
let grounds = (sam.mode != battery::SamMode::LauncherOnly || cued) && 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 {
|
||||
@@ -620,7 +535,7 @@ impl Sim {
|
||||
if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" }
|
||||
),
|
||||
));
|
||||
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est_at), gun.range, now);
|
||||
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est), gun.range, now);
|
||||
let mut why = Vec::new();
|
||||
for (bit, name) in [
|
||||
(AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())),
|
||||
@@ -666,7 +581,7 @@ mod tests {
|
||||
}
|
||||
let w = sim.why(0);
|
||||
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("нет целей классов")));
|
||||
sim.sams[0].roles = 0xFF;
|
||||
assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль")));
|
||||
}
|
||||
@@ -697,45 +612,23 @@ mod tests {
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -80.0 - blocks), DVec3::Z, DVec3::new(0.0, 70.0, -80.0));
|
||||
}
|
||||
|
||||
/// The system's picture holds the drone as a contact whose class is already estimated — as if
|
||||
/// the network had passed enough measurements (#133). The sim's own radar then keeps the
|
||||
/// estimate up from its measurements alone.
|
||||
fn seed_classified(sim: &mut Sim, class: ClassEst) {
|
||||
let now = sim.tick;
|
||||
let d = sim.drones[0].clone();
|
||||
sim.sams[0].tracks.retain(|t| t.id != d.id);
|
||||
let source = sim.sams[0].id;
|
||||
sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_chance_fires_at_a_class_out_of_roles_only_when_it_is_about_to_hit() {
|
||||
// The S-400 does not engage drones by default.
|
||||
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0);
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
shahed_at(&mut sim, 60.0);
|
||||
// Classified as a drone by the picture: the roles block it, the last chance is what fires.
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
let at = until_fired(&mut sim, &mut ground, &land, &mut out, 140).expect("the S-400 never fired on a Shahed about to hit");
|
||||
assert!(at < LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go");
|
||||
// The diagnostic names why: first the role block, then the last chance.
|
||||
// The diagnostic names why: the last chance.
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
shahed_at(&mut sim, 100.0);
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
let mut saw_block = false;
|
||||
let mut saw_chance = false;
|
||||
for _ in 0..220 {
|
||||
for _ in 0..30 {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
let w = sim.why(0);
|
||||
saw_block |= w.iter().any(|c| c.legacy_text().contains("не в ролях"));
|
||||
saw_chance |= w.iter().any(|c| c.legacy_text().starts_with("последний шанс"));
|
||||
if saw_chance || sim.sams[0].fired > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(saw_block, "the role block was never named");
|
||||
assert!(saw_chance, "the last chance was never named");
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.ok && c.legacy_text().starts_with("последний шанс")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -743,12 +636,10 @@ mod tests {
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
// In plain view 120 blocks off, but flying away from its aim, 480 blocks (800 ticks) ahead.
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0));
|
||||
// Classified as a drone: out of the S-400's roles, and not about to hit: nothing fires.
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim");
|
||||
let w = sim.why(0);
|
||||
// Still named as what it was: a contact on the picture, out of the roles.
|
||||
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
// Still named as the role block it was: no target of its classes.
|
||||
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("нет целей классов")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
|
||||
}
|
||||
|
||||
@@ -759,7 +650,6 @@ mod tests {
|
||||
sim.last_chance = !off;
|
||||
sim.sams[0].roles = roles;
|
||||
shahed_at(&mut sim, 60.0);
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 140).is_none(), "fired with last chance off={off}, roles {roles}");
|
||||
}
|
||||
}
|
||||
@@ -768,109 +658,12 @@ mod tests {
|
||||
fn last_chance_leaves_a_target_that_already_has_an_interceptor_on_it() {
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
shahed_at(&mut sim, 60.0);
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
// Another system's interceptor is on it.
|
||||
let id = sim.drones[0].id;
|
||||
sim.drones[0].engaged = 1;
|
||||
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 40).is_none(), "fired at {id} that is claimed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_probable_class_out_of_roles_is_blocked_and_named() {
|
||||
// The S-400 does not engage drones. A track only *probably* a drone is already a block:
|
||||
// the guess is a class, not an unidentified contact.
|
||||
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0);
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0));
|
||||
seed_classified(&mut sim, ClassEst::Probable(Class::Drone));
|
||||
// A target taken before the class was estimated: the diagnostic names the probable class.
|
||||
sim.sams[0].target = Some(sim.drones[0].id);
|
||||
let want = format!("роль: вероятно дрон не в ролях [{}]", roles_text(SamKind::S400.spec().roles));
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.legacy_text() == want), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
|
||||
// And nothing fires at it while it is far from its aim.
|
||||
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a probable drone far from its aim");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hold_fire_blocks_an_unclassified_contact_and_says_so() {
|
||||
// No roles: nothing is a candidate, the unidentified included. Running the sim must not
|
||||
// turn it into a target.
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
sim.sams[0].roles = 0;
|
||||
shahed_at(&mut sim, 60.0);
|
||||
seed_classified(&mut sim, ClassEst::Unknown);
|
||||
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 200).is_none(), "fired while holding fire");
|
||||
let w = sim.why(0);
|
||||
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_unknown_target_on_a_system_holding_fire_is_explained_without_a_panic() {
|
||||
// The target was taken before the roles were emptied: the diagnostic must name the hold,
|
||||
// not unwrap a class the estimate does not have.
|
||||
let (mut sim, _, _, _) = setup(SamKind::S400);
|
||||
shahed_at(&mut sim, 60.0);
|
||||
seed_classified(&mut sim, ClassEst::Unknown);
|
||||
sim.sams[0].target = Some(sim.drones[0].id);
|
||||
sim.sams[0].roles = 0;
|
||||
let w = sim.why(0);
|
||||
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_read_the_estimate_an_unidentified_track_is_not_blocked() {
|
||||
// #133: the role filter reads the track's estimated class, never the target's own. While
|
||||
// the contact is unidentified the S-400 (its roles exclude drones) keeps it as a candidate
|
||||
// under the general rules — the explicit policy, named in why; once the estimate firms as
|
||||
// a drone, the block applies and why names that instead.
|
||||
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0, "the S-400 does not engage drones");
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
sim.last_chance = false;
|
||||
shahed_at(&mut sim, 60.0);
|
||||
let id = sim.drones[0].id;
|
||||
let roles = sim.sams[0].roles;
|
||||
let mut saw_open = false;
|
||||
for _ in 0..300 {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
let Some(t) = sim.sams[0].track(id).copied() else { continue };
|
||||
if t.class != ClassEst::Unknown {
|
||||
break;
|
||||
}
|
||||
saw_open = true;
|
||||
assert_eq!(why::target_blocks(roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "an unidentified contact must not be role-blocked");
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
break;
|
||||
}
|
||||
assert!(saw_open, "the contact was never seen unidentified");
|
||||
// Classified as a drone, out of the roles: blocked, and the diagnostic says so.
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
sim.last_chance = false;
|
||||
shahed_at(&mut sim, 60.0);
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
let id = sim.drones[0].id;
|
||||
for _ in 0..40 {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.sams[0].track(id).is_some_and(|t| t.class == ClassEst::Firm(Class::Drone)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let t = *sim.sams[0].track(id).expect("the track");
|
||||
assert_ne!(why::target_blocks(sim.sams[0].roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "a classified out-of-role contact must be blocked");
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
// Holding fire (no roles at all): nothing is a candidate, the unidentified either.
|
||||
let d = sim.drones[0].clone();
|
||||
let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: battery::Measure::Search, quality: 40, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 1, locked: false };
|
||||
assert_ne!(why::target_blocks(0, Some(&unknown), 0, &d) & why::ROLE, 0, "with no roles (hold fire) even the unknown is blocked");
|
||||
}
|
||||
|
||||
/// A Kh101 `dist` from the origin on the far side, at height, coming in along z; a radar beside the system.
|
||||
fn far_setup(radar: bool, dist: f64) -> (Sim, Ground, Land<fn(i32, i32) -> i32>, Out) {
|
||||
let (mut sim, ground, land, out) = setup(SamKind::S400);
|
||||
@@ -889,27 +682,12 @@ mod tests {
|
||||
.drones
|
||||
.iter()
|
||||
.filter(|d| d.alive())
|
||||
.map(|d| Track {
|
||||
id: d.id,
|
||||
class: ClassEst::Firm(d.kind.spec().class),
|
||||
pos: d.pos,
|
||||
vel: d.vel,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: 0,
|
||||
product: battery::Measure::Fire,
|
||||
quality: 90,
|
||||
own_product: battery::Measure::Fire,
|
||||
own_quality: 90,
|
||||
ttl: 400,
|
||||
hits: 3,
|
||||
locked: false,
|
||||
})
|
||||
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
|
||||
.collect();
|
||||
for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) {
|
||||
for t in &tracks {
|
||||
r.tracks.retain(|o| o.id != t.id);
|
||||
r.tracks.push(Track { source: r.id, ..*t });
|
||||
r.tracks.push(*t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-10
@@ -179,21 +179,14 @@ mod catalog_tests {
|
||||
}
|
||||
fn item_exists(item: &str) {
|
||||
let name = item.strip_prefix("airdef:").expect("item namespace");
|
||||
for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] {
|
||||
for path in [format!("items/{name}.json"), format!("models/item/{name}.json"), format!("textures/item/{name}.png")] {
|
||||
assert!(assets().join(&path).is_file(), "{item}: missing {path}");
|
||||
}
|
||||
let definition = std::fs::read_to_string(assets().join(format!("items/{name}.json"))).unwrap();
|
||||
assert!(definition.contains(&format!("airdef:item/{name}")), "{item}: wrong item model");
|
||||
let model = std::fs::read_to_string(assets().join(format!("models/item/{name}.json"))).unwrap();
|
||||
// The icon reference may be an alias of an existing texture (the optical post uses the
|
||||
// radar icon until its own asset lands, #136); what matters is that the PNG it names exists.
|
||||
let layer = model
|
||||
.split("\"layer0\": \"")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split('"').next())
|
||||
.unwrap_or_else(|| panic!("{item}: no icon reference"));
|
||||
let texture = layer.strip_prefix("airdef:item/").unwrap_or_else(|| panic!("{item}: bad icon reference {layer}"));
|
||||
let png = std::fs::read(assets().join(format!("textures/item/{texture}.png"))).unwrap();
|
||||
assert!(model.contains(&format!("airdef:item/{name}")), "{item}: wrong icon reference");
|
||||
let png = std::fs::read(assets().join(format!("textures/item/{name}.png"))).unwrap();
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature");
|
||||
}
|
||||
fn model_exists(model: &str) {
|
||||
|
||||
@@ -1,34 +1,13 @@
|
||||
//! Text for diagnostics produced by the simulation.
|
||||
use crate::sim::why::{CheckReason, PartEffect};
|
||||
use crate::sim::{Comps, Part, SamKind};
|
||||
|
||||
fn part_value(part: Part, value: f64) -> String {
|
||||
if value <= 0.0 { format!("{} отказ", part.short()) }
|
||||
else { format!("{} {:.0}%", part.short(), value * 100.0) }
|
||||
}
|
||||
|
||||
fn part_value_on(part: Part, value: f64, kind: SamKind) -> String {
|
||||
if value <= 0.0 { format!("{} отказ", part.short_on(kind)) }
|
||||
else { format!("{} {:.0}%", part.short_on(kind), value * 100.0) }
|
||||
}
|
||||
|
||||
/// Every worn or failed part of a system, as the monitor and the status line read it.
|
||||
pub fn parts(comps: &Comps, kind: SamKind) -> String {
|
||||
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
|
||||
.map(|p| part_value_on(*p, comps.get(*p), kind)).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The weakest worn or failed part alone, for a one-line status.
|
||||
pub fn worst(comps: &Comps, kind: SamKind) -> String {
|
||||
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
|
||||
.min_by(|a, b| comps.get(**a).total_cmp(&comps.get(**b)))
|
||||
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn reason(reason: &CheckReason) -> String {
|
||||
match reason {
|
||||
CheckReason::Text(text) => text.clone(),
|
||||
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
|
||||
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| {
|
||||
if *value <= 0.0 { format!("{} отказ", part.short()) }
|
||||
else { format!("{} {:.0}%", part.short(), value * 100.0) }
|
||||
}).collect::<Vec<_>>().join(", ")),
|
||||
CheckReason::PartEffect(effect) => match effect {
|
||||
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
|
||||
PartEffect::SensorDamaged { fit } => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", fit * 100.0),
|
||||
@@ -49,21 +28,7 @@ pub fn reason(reason: &CheckReason) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{Comps, Part, SamKind};
|
||||
|
||||
#[test]
|
||||
fn renders_worn_parts_without_the_reason_prefix() {
|
||||
let mut comps = Comps([1.0; 6]);
|
||||
comps.0[Part::Sensor as usize] = 0.4;
|
||||
comps.0[Part::Tracks as usize] = 0.0;
|
||||
assert_eq!(parts(&comps, SamKind::Pantsir), "РЛС 40%, Ход отказ");
|
||||
assert_eq!(worst(&comps, SamKind::Pantsir), "Ход отказ");
|
||||
// A passive post's sensor is optics; only its sensor is fitted.
|
||||
let mut optics = Comps([1.0; 6]);
|
||||
optics.0[Part::Sensor as usize] = 0.4;
|
||||
assert_eq!(parts(&optics, SamKind::Optical), "Опт 40%");
|
||||
}
|
||||
|
||||
use crate::sim::Part;
|
||||
#[test]
|
||||
fn damaged_simulation_produces_player_diagnostics_in_order() {
|
||||
use crate::sim::{Sam, SamKind, Sim};
|
||||
|
||||
@@ -50,14 +50,13 @@ expect.feedback = "№2 С-400: режим launcher"
|
||||
[[step]]
|
||||
command = "airdef deploy radar_track"
|
||||
|
||||
# A deployed radar keeps its equipment profile; only its emissions can be switched.
|
||||
[[step]]
|
||||
command = "airdef radar 4 search"
|
||||
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
|
||||
expect.feedback = "№4 РЛС: роль search"
|
||||
|
||||
[[step]]
|
||||
command = "airdef radar 4 engagement"
|
||||
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
|
||||
expect.feedback = "№4 РЛС: роль engagement"
|
||||
|
||||
[[step]]
|
||||
command = "airdef radar 4 off"
|
||||
|
||||
@@ -126,52 +126,6 @@
|
||||
{
|
||||
"kind": "Light",
|
||||
"item": "deploy_light"
|
||||
},
|
||||
{
|
||||
"kind": "Optical",
|
||||
"item": "deploy_optical"
|
||||
}
|
||||
],
|
||||
"variants": [
|
||||
{
|
||||
"id": "s400_launcher",
|
||||
"kind": "S400",
|
||||
"mode": "launcher",
|
||||
"role": "multi",
|
||||
"label": "С-400 — отдельная пусковая",
|
||||
"description": "Пусковая С-400 без своей РЛС: работает по данным сети."
|
||||
},
|
||||
{
|
||||
"id": "s500_launcher",
|
||||
"kind": "S500",
|
||||
"mode": "launcher",
|
||||
"role": "multi",
|
||||
"label": "С-500 — отдельная пусковая",
|
||||
"description": "Пусковая С-500 без своей РЛС: работает по данным сети."
|
||||
},
|
||||
{
|
||||
"id": "radar_search",
|
||||
"kind": "Radar",
|
||||
"mode": "integrated",
|
||||
"role": "search",
|
||||
"label": "РЛС обзора",
|
||||
"description": "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт."
|
||||
},
|
||||
{
|
||||
"id": "radar_track",
|
||||
"kind": "Radar",
|
||||
"mode": "integrated",
|
||||
"role": "engagement",
|
||||
"label": "РЛС сопровождения",
|
||||
"description": "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск."
|
||||
},
|
||||
{
|
||||
"id": "radar_height",
|
||||
"kind": "Radar",
|
||||
"mode": "integrated",
|
||||
"role": "height",
|
||||
"label": "Мачтовая РЛС",
|
||||
"description": "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт."
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
@@ -409,15 +363,6 @@
|
||||
52
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_optical",
|
||||
"title": "Развернуть оптический пост",
|
||||
"color": [
|
||||
70,
|
||||
110,
|
||||
90
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mover",
|
||||
"title": "Пульт перемещения",
|
||||
|
||||
@@ -668,31 +668,6 @@
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 0.0,
|
||||
"mast": 1.5
|
||||
},
|
||||
{
|
||||
"kind": "Optical",
|
||||
"key": "optical",
|
||||
"name": "Оптический пост",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.0,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 0,
|
||||
"family": "static",
|
||||
"parts": {
|
||||
"body": "airdef:radar_truck",
|
||||
"launcher": null,
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": ["airdef:radar_panel", 1.2, 0.0, 0.6, -0.2]
|
||||
},
|
||||
"mount": [0.0, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 0.0,
|
||||
"mast": 2.5
|
||||
}
|
||||
],
|
||||
"missiles": [
|
||||
|
||||
Vendored
-10
@@ -1,10 +0,0 @@
|
||||
@echo off
|
||||
rem Run AirDef with DLSS SR and GPU pass timing. Same game home and mod as play.bat.
|
||||
chcp 65001 >nul
|
||||
setlocal
|
||||
set "HORIZON_DLSS=1"
|
||||
rem Empty means the DLSS default of 2/3 render resolution.
|
||||
set "HORIZON_HD_SCALE="
|
||||
set "HORIZON_HD_DEBUG_MOTION="
|
||||
set "HORIZON_SHADER_PACK_TIMING=1"
|
||||
call "%~dp0play.bat" %*
|
||||
Vendored
-9
@@ -1,9 +0,0 @@
|
||||
@echo off
|
||||
rem Run the same scene with native TAAU at the same 2/3 render scale and timing.
|
||||
chcp 65001 >nul
|
||||
setlocal
|
||||
set "HORIZON_DLSS=0"
|
||||
set "HORIZON_HD_SCALE=0.67"
|
||||
set "HORIZON_HD_DEBUG_MOTION="
|
||||
set "HORIZON_SHADER_PACK_TIMING=1"
|
||||
call "%~dp0play.bat" %*
|
||||
@@ -42,36 +42,24 @@
|
||||
/airdef battery
|
||||
```
|
||||
|
||||
Нумерацию существующей техники показывает `/airdef battery`:
|
||||
Нумерацию существующей техники показывает `/airdef battery`. Чтобы переоборудовать её:
|
||||
|
||||
```text
|
||||
/airdef battery <номер С-400 или С-500> launcher
|
||||
/airdef battery <номер С-400 или С-500> integrated
|
||||
/airdef radar <номер РЛС> on|off
|
||||
/airdef radar <номер РЛС> search
|
||||
/airdef radar <номер другой РЛС> engagement
|
||||
```
|
||||
|
||||
Профиль РЛС задаётся при размещении (`radar_search`, `radar_track`, `radar_height`) и не
|
||||
переключается на ходу: `radar <номер> search|engagement|height` больше не меняет оборудование.
|
||||
Можно оставить одну многофункциональную РЛС (`multi`, старые сохранения) и несколько пусковых.
|
||||
|
||||
- **Обзорная** (`radar_search`): широкая дальность и ранние грубые отметки, медленный оборот,
|
||||
без каналов уточнения. Права на пуск не даёт.
|
||||
- **Мачтовая** (`radar_height`): поднятая антенна и лучшее вертикальное измерение уточняют низкие
|
||||
контакты в локальной зоне; рельеф по-прежнему скрывает цель. Права на пуск не даёт.
|
||||
- **Сопровождения** (`radar_track`): локальный поиск, электронный оборот, два канала точных
|
||||
треков. Сеть может подсказать, но станция должна **сама измерить** цель; только собственное
|
||||
подтверждённое измерение разрешает пуск.
|
||||
- **Многофункциональная** (`multi`): совместимый универсальный вариант, но не лучший во всём.
|
||||
|
||||
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
|
||||
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
|
||||
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
|
||||
Можно оставить одну многофункциональную РЛС (`multi`) и несколько пусковых.
|
||||
Поисковая/мачтовая РЛС даёт подсказку, но не разрешает огонь сама. РЛС сопровождения принимает
|
||||
подсказку и должна **сама измерить** цель в своей игровой досягаемости и с учётом рельефа.
|
||||
Чужой трек не превращается в собственное измерение. После этого связанные пусковые используют
|
||||
общую картину и существующее распределение целей. Если РЛС сопровождения уничтожена, свёрнута,
|
||||
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
|
||||
продолжают штатную игровую логику связи/памяти/самонаведения.
|
||||
|
||||
Старые миры и обычные `/airdef deploy s400` / `s500` сохраняют сборную конфигурацию `integrated`.
|
||||
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями; новые
|
||||
сохранения пишут устойчивый ID профиля, старые строки только с ролью читаются как те же профили.
|
||||
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями.
|
||||
У прежнего игрового С-500 был магазин на четыре ракеты при двух нарисованных ТПК;
|
||||
теперь он согласован с двумя физическими ячейками. При загрузке старой расстановки
|
||||
его загруженный остаток ограничивается новой вместимостью, как при обычном восстановлении боезапаса.
|
||||
@@ -108,9 +96,9 @@
|
||||
|
||||
## Ограничения
|
||||
|
||||
Все три профиля пока используют общий силуэт машины и антенны (отдельная художественная зона
|
||||
владельца): различаются поведение, цикл, точность, каналы и подпись. Точные модели 91Н6/92Н6/96Л6,
|
||||
машина КП, ручная принадлежность к батарее и кабельное снабжение не добавлены. Подробные режимы и параметры реальных
|
||||
Роли РЛС и мачта пока используют общую модель машины, с разным поведением/отображением антенны.
|
||||
Отдельные точные модели 91Н6/92Н6/96Л6, машина КП, ручная принадлежность к батарее, отдельные
|
||||
каналы сопровождения и кабельное снабжение пока не добавлены. Подробные режимы и параметры реальных
|
||||
комплексов не моделируются. В следующей серии добавлены конечная работа двигателя/coast (#120),
|
||||
доставка RM48U через ТЗМ (#118), переключение излучения (#121) и укрытия от непрямого blast (#119).
|
||||
Текущий объём и ограничения описаны в [техническом журнале](CODEX-HANDOFF.md).
|
||||
|
||||
@@ -4,27 +4,6 @@
|
||||
Рабочая ветка `kimi-work`; issues не закрывать, публиковать комментарии с коммитом и проверками.
|
||||
Движок — отдельный `chexit/horizon-airdef`, ветка `airdef`, подключён точным gitlink `horizon/`.
|
||||
|
||||
## #91: типизированные варианты комплексов — первый slice (20 ноября 2026)
|
||||
|
||||
Ветка `agent/91-variants` (worktree `/tmp/airdef-issue91`), база `60f1bf0fd`
|
||||
(рабочая ветка `kimi-work`), движок `ed751714e` не менялся. Минимальный вариант,
|
||||
который требует текущий код: развёртывание «элементов батареи» (`s400_launcher`,
|
||||
`s500_launcher`, `radar_search/track/height`) описывалось тремя разрозненными
|
||||
ручными списками — таблица меню `BATTERY_DEPLOY` и `match` конфигурации в `lib.rs`
|
||||
и цепочка ids в `commands.rs`. Они сведены в каталог: `catalog/content.json → variants`
|
||||
(ключи `mode`/`role` переиспользуют существовавшие ключи сохранений `SamMode`/`RadarRole`),
|
||||
`gen_catalog.py` генерирует `unit_variants_generated.rs` → `catalog::UnitVariant`
|
||||
(`id/kind/mode/role/label`), Python-валидация отвергает дубли, чужие kinds/modes,
|
||||
совпадение с ключами/предметами. Меню батареи, клик по строке и Tab-дополнение
|
||||
`deploy` читают таблицу; генерация порядка строк прежняя, тексты прежние. **Профили
|
||||
боезапаса по вариантам не заводились**: для «разных ракет/профилей по батареям» требуется
|
||||
согласованный профиль и явно подписанная игровая абстракция (замечание ревью по
|
||||
PAC-3 в комментарии #91) — следующий slice, не этот. Save/replay/тексты не менялись:
|
||||
вариант — только ключ развёртывания поверх тех же полей `sam`, сейв-формат, порядок
|
||||
и `durable mark` без изменений. То же видно и в `airdef-core` (общая симуляция).
|
||||
Остаток #91: профили боезапаса по вариантам, объединение Python-генераторов и других списков,
|
||||
игровая приёмка.
|
||||
|
||||
## Текущее состояние: 4 ноября 2026
|
||||
|
||||
Последнее продолжение пяти задач: [CONTINUATION-2026-11-04.md](CONTINUATION-2026-11-04.md).
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
# Проверка DLSS SR на Windows / RTX
|
||||
|
||||
Это тестовая, а не релизная сборка #124. Она включает native DLSS Super Resolution через Vulkan и сохраняет обычный TAAU как fallback. Frame generation здесь нет; RTX 3060 его и не поддерживает.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
1. Один раз запусти обычный Horizon Launcher, чтобы он подготовил ресурсы Minecraft 26.3.
|
||||
2. Распакуй `airdef-dlss-windows-x86_64.zip`. Не удаляй `nvngx_dlss.dll`: он должен остаться рядом с `horizon-client.exe`. Если Windows сообщает об отсутствии `MSVCP140.dll` или `VCRUNTIME140.dll`, поставь Microsoft Visual C++ Redistributable 2015–2022 x64.
|
||||
3. Запусти **`test-dlss.bat --world "Имя мира"**. Скрипт сам включит мод, `HORIZON_DLSS=1` и GPU pass timing.
|
||||
4. В игре выполни одну и ту же последовательность:
|
||||
|
||||
```text
|
||||
/airdef shader hd
|
||||
/airdef deploy radar_track
|
||||
/airdef deploy s400
|
||||
/airdef damage off
|
||||
/airdef wave shahed 8 300
|
||||
```
|
||||
|
||||
Подожди около 20 секунд, пока начнётся налёт. Для движущихся моделей подойдёт и `/airdef move 2`.
|
||||
5. Посмотри на ракеты/технику, сделай скриншот и запиши FPS/кадр. Не включай `HORIZON_HD_DEBUG_MOTION` при измерении качества или FPS.
|
||||
6. Выйди и запусти **`test-native.bat --world "Имя мира"`**. Он использует TAAU с тем же масштабом 2/3 и тем же GPU timing. Повтори ту же сцену, ракурс и скриншоты.
|
||||
|
||||
Для честного A/B используй один мир и одну позицию камеры. Если налёт уже закончился, запусти следующий `/airdef wave shahed 8 300`. Не меняй разрешение окна или HD-настройки между прогонами.
|
||||
|
||||
## Что подтверждает, что DLSS действительно включён
|
||||
|
||||
В `%APPDATA%\horizon\logs\latest.log` должна быть строка вроде:
|
||||
|
||||
```text
|
||||
DLSS Super Resolution: [1280, 720] -> [1920, 1080]
|
||||
```
|
||||
|
||||
Не должно быть `using native TAAU`, `FeatureNotSupported`, `no DLSS context` или `DLSS evaluation failed`. Само наличие повышенного FPS не считается подтверждением backend.
|
||||
|
||||
Скрипты включают `HORIZON_SHADER_PACK_TIMING=1`, поэтому в лог попадают GPU pass timings. Сравнивай не только средний FPS, но и микрофризы, дым, вспышки и движущиеся ракеты.
|
||||
|
||||
## Что прислать
|
||||
|
||||
- `%APPDATA%\horizon\logs\latest.log` после DLSS-прогона.
|
||||
- Скриншоты одного ракурса с DLSS и native TAAU, желательно с движущейся техникой/ракетой и отдельно с дымом.
|
||||
- Скриншот FPS/debug overlay обоих режимов или текстовые значения FPS.
|
||||
- Если есть артефакты: кратко, что именно не так и меняется ли оно при движении камеры.
|
||||
- Сохранения миров присылать не нужно.
|
||||
|
||||
## Если игра не запускается
|
||||
|
||||
- Сначала проверь, что `nvngx_dlss.dll` лежит рядом с `horizon-client.exe` и ресурсы подготовлены лаунчером.
|
||||
- При ошибке про Vulkan/NGX пришли `latest.log`: там должна быть конкретная причина. Не подменяй её догадкой про драйвер.
|
||||
- При `FeatureNotSupported` или другом сбое игра должна продолжить работу через native TAAU; это будет видно в логе. Такой запуск не является успешным тестом DLSS.
|
||||
- `test-native.bat` нужен только для сравнения; он не включает DLSS.
|
||||
|
||||
## Сборка самостоятельно вместо готового архива
|
||||
|
||||
Нужны Visual Studio Build Tools с C++, Rust, clang, Vulkan SDK и NVIDIA DLSS SDK v310.9.1. Ветка — `kimi-work`.
|
||||
|
||||
```powershell
|
||||
git clone --branch kimi-work https://gitea.maoniao.team/chexit/airdef.git
|
||||
cd airdef
|
||||
rustup target add x86_64-pc-windows-msvc wasm32-unknown-unknown
|
||||
$env:DLSS_SDK = "C:\path\to\DLSS"
|
||||
$env:VULKAN_SDK = "C:\path\to\VulkanSDK"
|
||||
cargo build --manifest-path horizon/Cargo.toml -p horizon-client --target x86_64-pc-windows-msvc --features "mods,dlss"
|
||||
py tools\airdef.py mod
|
||||
```
|
||||
|
||||
Скопируй `horizon/target/x86_64-pc-windows-msvc/debug/horizon-client.exe`, `airdef-mod/target/horizon-mod/airdef.hmod`, `dist/play.bat`, `dist/test-dlss.bat`, `dist/test-native.bat` и `$env:DLSS_SDK/lib/Windows_x86_64/rel/nvngx_dlss.dll` в одну папку. Для реальной игры нужен и `latest.log` с фактическим backend/кадрами.
|
||||
+2
-3
@@ -63,9 +63,8 @@ runtime закреплённого движка. Используется вре
|
||||
|
||||
## Акустика и владение захватом (API 27)
|
||||
|
||||
Текущий pin: `2bcce642362ab5d3f04de193e390d8293cd1bf30` (API 31; `render.project` — проекция
|
||||
мировых точек через камеру последнего отрисованного кадра, #132; ниже — staging, cascades,
|
||||
previous-frame motion и feature-gated DLSS SR backend #124, API 30). Акустические
|
||||
Текущий pin: `278f356aa604fa21c2d15d0081823bbe0f891df2` (API 30; поверх API29 — нормали моделей
|
||||
и очистка неудачного захвата). Акустические
|
||||
`render.acoustics-status` и `render.capture-owner-status` возвращают поколение,
|
||||
`available`, `enabled`, `request-accepted`, `prepared` и причину. В игре всё это показывает
|
||||
`/airdef capabilities`. Отсутствие запроса, выключение, ожидание backend и ошибка различаются.
|
||||
|
||||
+6
-49
@@ -58,12 +58,8 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
|
||||
возвращается. Рисуются секции террейна в коробке дальнего каскада (`hd_shadow_visible`) и сущности-тенеотбрасыватели
|
||||
(`shadow_casters`: без оверлеев 4/9/10/40 — 40 это светящиеся модели мода).
|
||||
2. **G-буфер** (свой depth): albedo `Rgba8Unorm` (a = эмиссия), нормаль `Rgba16Float` (мировая, из `dpdx/dpdy`),
|
||||
уровни света `Rgba8Unorm` (x = небо, y = блоки — сырые координаты лайтмапа /240), motion `Rg16Float`
|
||||
(current→previous в render-пикселях, обе проекции с jitter). Террейн + дальние LOD-тайлы + сущности.
|
||||
Terrain/ванильные сущности пишут camera/static motion; `motion_models_pass` перезаписывает mod-модели
|
||||
previous-frame transforms с read-only depth и тем же alpha cutout (`7a73e8d26`). Ветер остаётся camera-only.
|
||||
`HORIZON_HD_DEBUG_MOTION=1` показывает R/G displacement и validity вместо обычного TAA-кадра.
|
||||
Полупрозрачное в G-буфер **не** попадает (идёт ванильным путём); вода — отдельный путь, см. п. 3 и «Вода».
|
||||
уровни света `Rgba8Unorm` (x = небо, y = блоки — сырые координаты лайтмапа /240). Террейн + дальние LOD-тайлы +
|
||||
сущности. Полупрозрачное в G-буфер **не** попадает (идёт ванильным путём); вода — отдельный путь, см. п. 3 и «Вода».
|
||||
3. **Вода** (`water_pass`, только если на экране есть полупрозрачные секции, нет `frame.underwater` и не `HORIZON_HD_WATER=0`):
|
||||
те же секции ещё раз с `fs_water` (terrain.wgsl), который отбрасывает всё, кроме слоёв спрайтов `water_still`/`water_flow`
|
||||
(номера слоёв передаются в `Renderer::new` из `sprite_layers` и ставятся override-константами `WATER_STILL/WATER_FLOW`; стекло,
|
||||
@@ -90,9 +86,7 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
|
||||
5. **Пост-проход мода** `lit` → `fx` (`effects.wgsl`: взрывы, дым, вспышки, свечение; при HD его собственная
|
||||
«подсветка огнём» выключена — свет даёт HD).
|
||||
6. **TAA** — после пост-прохода мода (`fx`, либо `lit` без него), до bloom: история пинг-понгом, в альфе истории —
|
||||
дистанция для отбраковки дизокклюзии; телепорт > 64 блоков сбрасывает историю. Если world/G-buffer depth
|
||||
совпадают, history UV = current UV + motion/render_size; вода, прозрачность и небо используют прежний
|
||||
depth/camera fallback. Джиттер добавляется к
|
||||
дистанция для отбраковки дизокклюзии; телепорт > 64 блоков сбрасывает историю. Джиттер добавляется к
|
||||
`view_projection` только при HD (публичная матрица без джиттера); рука и HUD рисуются после tonemap и не дрожат.
|
||||
**TAAU**: если мир меньше окна (`HORIZON_HD_SCALE=0.67`), тот же проход (`fs_taau`, в таймингах `hd taau`) восстанавливает
|
||||
полное разрешение. История, bloom и tonemap — в разрешении окна. Для каждого пикселя выхода берётся 3×3 выборки мира
|
||||
@@ -231,7 +225,6 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
|
||||
| #36: ванильная вода не рисует цвет в HD (`fs_translucent` при `Globals.hd_flags.x`, глубину оставляет); прозрачное перед водой (`d` ближе `wd`) не отключает HD-воду: вода считается на освещённом дне и добавляется к сцене с весом 0.7; преломление не берёт тексели с таким прозрачным (`textureGather` по альфе) | готово (проверены стекло; частицы и scale 0.67 не проверялись) | в рабочем дереве форка |
|
||||
| #45: `gfx/hd.rs` разделён на модуль `gfx/hd/` (по файлу на проход: `shadows`, `gbuffer`, `ao`, `sky`, `volumes`, `lighting`+`tiles`, `water`, `taa`, `bloom`, `tonemap`, `frame`), WGSL вынесен в `.wgsl` (`include_str!`, общая прелюдия), у каждого прохода своя структура ресурсов/пайплайнов; контракты цвета, глубины, альф и времени записаны в `hd/mod.rs` и в начале файлов проходов; тесты привязок и размера `HdFrame`. Вид не менялся (сверка `tools/hd_bench.py`) | готово | в рабочем дереве форка |
|
||||
| #39: веер восхода `vanilla_sunrise_weight` отсекается до цикла по 16 треугольникам выше горизонта (знак x стороны солнца и наклон ≤ α/3; проверено перебором 200 тыс. лучей без пропусков); `hd lighting` на рассвете 5.3 → 3.3 мс (M-серия, 2560×1440) | готово | в рабочем дереве форка |
|
||||
| #126 (этап 1): retained-геометрия моделей мода — грани резолвятся против атласа раз в generation пака, кадр только трансформирует и освещает; motion #124 из тех же граней без второго bake; счётчики `mod_models` в `stats`; вершины бит-в-бит прежние (тест). `entity_geometry` CPU 5.71 → 1.57 мс avg, p95 8.7 → 2.2 (M5, raid-сцена Polygon) | готово; GPU-instancing — следующий этап | форк `a861c1ed2` (`kimi-work-124`), замеры `docs/measurements/issue-126-first-stage/` |
|
||||
|
||||
| Облака в воде, перистые, туман по рельефу, лучи, тень облаков при низком солнце, дальний дым (768 блоков) | готово, в рабочем дереве форка; тайминги не сняты чисто | не закоммичено |
|
||||
| Материалы и блики (план 5): G-буфер `levels.zw` = шероховатость, металличность; GGX-блик солнца с Френелем и отражение неба (`sky_along`/`atmosphere_sky`) в `shade_surface`; мокрые поверхности и лужи в дождь (`HdFrame.surface`); `HORIZON_HD_SPECULAR=0` — выкл. | готово | в рабочем дереве форка |
|
||||
@@ -252,14 +245,8 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
|
||||
TAA-проход восстанавливает полное разрешение: история в полном разрешении, текущий кадр семплируется с учётом
|
||||
джиттера (Catmull-Rom/Lanczos-веса по субпиксельной позиции), клиппинг окрестности как в TAA. Настройка
|
||||
масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно
|
||||
выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature
|
||||
и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit:
|
||||
world+linearize → NGX → delinearize; native TAAU остаётся fallback. По умолчанию DLSS рендерит world 2/3,
|
||||
`HORIZON_HD_SCALE` переопределяет это. Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и
|
||||
`--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build`
|
||||
на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен.
|
||||
A/B инструкция — `docs/DLSS-TESTING.md`.
|
||||
Ванильные сущности/ветер остаются camera-only. MetalFX — отдельный Metal backend, FG отдельно.
|
||||
выше. Альтернатива на Mac — MetalFX через wgpu-hal (нативный код, только Metal) — отдельной опцией потом. DLSS
|
||||
нереален для нашей цели (только NVIDIA через Streamline, нет в wgpu).
|
||||
2. **Вода** — СДЕЛАНО (патч 19, см. «Вода» ниже). Исходное ТЗ: отдельный G-буфер-путь для воды (маска + нормаль с анимированными волнами), SSR (трассировка по
|
||||
глубине, откат на небо/туман), преломление (смещение по нормали), затухание по глубине воды (цвет биома),
|
||||
блики солнца (GGX-подобный), френель. Подводный вид не ломать (`frame.underwater`).
|
||||
@@ -364,36 +351,6 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
|
||||
- Мод в повторе берёт взрывы из записи (`record::replay_blasts`, чистая функция времени), время идёт по часам повтора (`params[255].x` — доля частичного тика, которую эффекты не используют при паузе/замедлении).
|
||||
- #51: на перехвате слои звука (`cinema.rs`), свет-«удар» (белая вспышка в HD-освещении, радиус до 256), пик экспозиции/bloom (`set-lighting`), в `effects.wgsl` широкое гало, подсветка неба/облаков и яркое кольцо ударной волны на экране.
|
||||
|
||||
## Retained-геометрия моделей мода (#126, этап 1)
|
||||
|
||||
- **Что изменилось.** `game/mod_models.rs`: грани модели резолвятся против атласа один раз на
|
||||
generation пака (`MeshCache` по `BlockStateId`; generation — `Arc<RenderAssets>` текущего пака,
|
||||
сравнение `ptr_eq`, клон удерживает адрес от переиспользования): прямоугольник спрайта,
|
||||
model-space квад и нормаль (`block_model_normal`), emission и special-материал квада (40/41/42)
|
||||
по центру UV. Кадр только применяет трансформ инстанса: позиции — `m.transform_point3`,
|
||||
нормаль — один inverse-transpose на инстанс (не на грань), свет — мировой свет позиции + emission.
|
||||
Таблица special-материалов строится раз в generation, а не каждый кадр обходом всего атласа;
|
||||
линейный поиск материала по квадам убран из кадра. HD motion-проход (#124) берёт previous-позиции
|
||||
из тех же retained-граней с матрицей прошлого кадра — второй bake модели больше нет. Вершины
|
||||
бит-в-бит совпадают с прежним покадровым bake (тест `retained_emit_matches_the_per_frame_bake`,
|
||||
матрица трансформов × glow × свет × emission, включая motion).
|
||||
- **Инвалидация.** Resource reload (`apply_staged_pack`) и выход из мира (`clear_entities`,
|
||||
`leave_server`) сбрасывают кэш; generation-guard дополнительно ловит любую смену пака. Размер
|
||||
кэша ограничен числом состояний моделей в паке, не числом инстансов и не временем.
|
||||
- **Счётчики и span.** `stats`/`bench` control-сокета возвращают `mod_models`: frames, models,
|
||||
quads, motion_quads, vertex_bytes, motion_bytes, mesh_builds, atlas_scans с момента сброса
|
||||
(bench сбрасывает). Span `mod_models` внутри `entity_geometry` виден при `HORIZON_SPIKES`.
|
||||
- **Замеры.** M5, Metal, 2560×1440 offscreen, HD, in-frame, Polygon: 14 батарей + 3 волны
|
||||
(`shahed 40 900`, `kh101 16 1400`, `mix 24 700`), ~135 моделей/кадр, ~17.8 тыс. квадов/кадр.
|
||||
`entity_geometry` CPU 5.71 → 1.57 мс avg (p95 8.7 → 2.2, p99 10.6 → 2.7), фаза prepare
|
||||
23.5 → 7.05 мс; span `mod_models` 1.32 мс avg — чистые трансформы. Static-сцена (4 батареи,
|
||||
TAA/wind/clouds/volfog выключены, время заморожено): пиксели identical (0 px > 20/255 при
|
||||
сошедшемся LOD). Байты upload не менялись (~3.1 МБ/кадр вершин + ~4 МБ motion): этап убирает
|
||||
CPU-bake, не объём upload. Полная таблица и методика — `docs/measurements/issue-126-first-stage/`.
|
||||
- **Чем это не является.** Не GPU-instancing: вершины по-прежнему трансформируются на CPU и
|
||||
загружаются каждый кадр. Per-instance буферы, GPU-интерполяция и indirect draws — следующий
|
||||
этап направления A #126. Боевые правила, 20 Гц, API мода, DLSS/RT не тронуты; мод (WASM) тот же.
|
||||
|
||||
## Прожекторы: направленный свет и объёмный луч (#60)
|
||||
|
||||
- **API 16** `render.set-spot-lights(list<spot-light>) -> bool`: апекс, направление, цвет, интенсивность, `range` (до 1024), внутренний/внешний полуугол (рад), `beam` (видимость луча 0..1). До 32 от мода, рисуются ближайшие 16 (`MAX_SPOTS`). Возвращает, рисует ли HD (`HORIZON_HD_SPOTS=0` выключает), иначе мод держит свой запасной луч. Игра интерполирует по id между двумя вызовами (`mod_models.rs: mod_spots`) и переводит в `HdSpot` (`gfx/hd/frame.rs`): координаты камеры, косинусы углов.
|
||||
@@ -447,7 +404,7 @@ ffmpeg 9.0.1. `/airdef replay export` с записанного налёта (4
|
||||
|
||||
## Цветные тени, рябь, кино-пост: что знать преемнику
|
||||
|
||||
- **Цветные тени.** Ближний каскад (c = 0) рисуется `fs_shadow_near` (листва `MAT_LEAVES` отброшена), потом проход `hd shadow colour` (`Hd::shadow_tint_pass`, цель `Shadows::tint`, очистка в белое) рисует листву (`shadow_tint_leaves`, твёрдые квады, `SHADOW_SOLID`) и полупрозрачные квады секций (`shadow_tint_glass`, по отсортированным индексам; вода не рисуется) тем же `fs_shadow_tint`: rgb умножаются (blend `Dst*src`), альфа = `(расстояние от света − 320)/160` с blend Min — ближайший такой квад. Приёмник в `shadow_tint` (`light.wgsl`, привязка 22) окрашивается, если квад ближе к свету, чем он; 8 точек Vogel радиусом 0.4 блока размывают листву в «пятна». Дальний каскад по-прежнему рисует листву полностью; с `17382445a` near/far depth filters смешиваются на последних 6 блоках перед границей 36,8, а tint затухает по той же smoothstep — круглого шва нет. Цвет не доходит до лучей тумана, воды и дальнего каскада. Цена: `hd shadow colour` 0.25–0.35 мс (Mac, малая сцена).
|
||||
- **Цветные тени.** Ближний каскад (c = 0) рисуется `fs_shadow_near` (листва `MAT_LEAVES` отброшена), потом проход `hd shadow colour` (`Hd::shadow_tint_pass`, цель `Shadows::tint`, очистка в белое) рисует листву (`shadow_tint_leaves`, твёрдые квады, `SHADOW_SOLID`) и полупрозрачные квады секций (`shadow_tint_glass`, по отсортированным индексам; вода не рисуется) тем же `fs_shadow_tint`: rgb умножаются (blend `Dst*src`), альфа = `(расстояние от света − 320)/160` с blend Min — ближайший такой квад. Приёмник в `shadow_tint` (`light.wgsl`, привязка 22) окрашивается, если квад ближе к свету, чем он; 8 точек Vogel радиусом 0.4 блока размывают листву в «пятна». Дальний каскад по-прежнему рисует листву полностью (на границе 36 блоков шов: ближе листва светлее). Цвет не доходит до лучей тумана, воды и дальнего каскада. Цена: `hd shadow colour` 0.25–0.35 мс (Mac, малая сцена).
|
||||
- **Рябь.** `ripple_gradient` берёт часы воды (`water.y`, часы фильма): частоты — целые циклы на 600 с, сетка 160 клеток на 256 блоков, поэтому рисунок не прыгает на обороте. Гаснет по размеру пикселя, только под открытым небом (`nt.a`). Амплитуда 0.012 не подбиралась.
|
||||
- **Кино-пост.** `Hd::film` между `taa` и `finish` (`HdSource::Film`), только при `film_quality()`; цели создаются при первом фильме. Motion blur — только от движения камеры (глубина + `prev_view_proj`, затвор 180°, мёртвая зона 1–2.5 px из-за джиттера; движущиеся объекты не размываются; нет после склейки/телепорта: `taa.w`). DoF — диск 24 отсчёта, фокус авто (гармоническое среднее 9 глубин у центра) или `HORIZON_HD_DOF_FOCUS`. Детерминизм: единственное время в шейдере — `water.y` (часы фильма) для шума. Проверять на реальном фильме `/airdef replay film`; `HORIZON_HD_FILM_QUALITY=1` принудительно включает качество фильма для проб. DoF в игре был слишком сильным и дорогим; параметры уменьшены без повторного снимка. Motion blur на снимке (поворот 40° за 1.5 с) не разобран.
|
||||
- Из Photon (MIT) ничего нового не переносилось: THIRD_PARTY_PHOTON.md не менялся.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
для Rust и Python; #102: измеренный fuel, API29 light/source milestones, API30 camera-status
|
||||
и изоляция камер; #96: массовый deterministic offline capture; #115: authored Lancet/Х-101
|
||||
и кадры инстансов.
|
||||
Текущий engine pin — API31 (`render.project`, #132); старые номера/числа ниже описывают предыдущие этапы.
|
||||
Текущий engine pin — API30; старые номера/числа ниже описывают предыдущие этапы.
|
||||
Проблема нормалей модели #123 исправлена в engine `45b43f00d`; парные HD-кадры и ночная проверка Lancet записаны в галерее.
|
||||
|
||||
| Issue | Реализовано | Что остаётся для полной приёмки |
|
||||
@@ -17,7 +17,7 @@
|
||||
| #87 | Каноническое SDK-free ядро `airdef-core`, используется модом и сценариями | Дальнейшее отделение текстового/визуального вывода домена от адаптера |
|
||||
| #88 | Типизированный журнал измеренных переходов; read-only Snapshot для Smoke/Shown; записанные пожары, позы, пуски и зажигание | Перевести оставшиеся model/audio adapters и режиссёра на общий снимок; замер полной 10-минутной записи |
|
||||
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа; выход в заголовок завершает показ одним cleanup (хук `frame`, `Session::world_left`); движок освобождает temp/лог ошибки энкодера и не трогает готовый MP4 | Реальный короткий MP4 проверен 4 ноября (звук/видео, отмена, ошибка SDK и энкодера, повторный запуск, совпадение кадров и хвоста очереди, сохранность прежнего MP4). Остаётся: 10-минутный экспорт; приёмка Windows/Linux |
|
||||
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей; `catalog/specs.json` — единственный источник числовых строк, из него генерируются Rust-таблицы для мода и `airdef-core`, CI проверяет свежесть; первый типизированный slice вариантов комплексов: `catalog/content.json → variants` описывает существующие ключи развёртывания элементов батареи (`s400_launcher`…), вариант = `id/kind/mode/role/label` без нового баланса, таблица `catalog::VARIANTS` генерируется и потребляется меню/командами, ручные параллельные списки в `lib.rs`/`commands.rs` удалены | Профили боезапаса по вариантам (разные ракеты/боекомплекты по батареям) не заводились: обязательное условие — зафиксированный профиль и явная игровая абстракция (см. поправку ревью о PAC-3 в комментарии #91); далее полная игровая приёмка; каталог остаётся статичными данными, не динамическим ECS |
|
||||
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей; `catalog/specs.json` — единственный источник числовых строк, из него генерируются Rust-таблицы для мода и `airdef-core`, CI проверяет свежесть | Варианты комплексов (разные ракеты/профили по батареям) и игровая приёмка; каталог остаётся статичными данными, не динамическим ECS |
|
||||
| #92 | Authored overrides, проверка ссылок/PNG/границ, manifest, безопасная транзакционная генерация; registry/texture/icon modules | Дальнейшее ручное улучшение контента относится к #115 |
|
||||
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах; настоящий MP4 с акустикой: пары on/off, статусы ready, окклюзия/поглощение и диффузный wet-остаток в замкнутой геометрии | Прослушивание, игровой массовый звук/CPU, чистый хвост/RT60 в MP4; точность RT60 пока по допуску 35%, не 15% |
|
||||
| #102 | Pinned engine/API30, packer/build identity; smoke/acoustics/capture-owner/light/source/owner-scoped camera milestones; fallback/владение; WASM27 и flat stress271; измеренный callback fuel; JSON provenance/failure tests; Metal/no-audio smoke; URL/Git-регрессия; camera-ready по закодированному кадру с per-run/per-world сбросом; GPU-приёмка monitor/main-view на Metal/offscreen (Apple M5) | Старое69-шаговое утверждение о перекрытии отозвано; визуальная/Windows-GPU приёмка картинки камер, полные query/voice/peak budgets, GPU/готовый MP4 и Windows-приёмка остаются |
|
||||
@@ -31,7 +31,6 @@
|
||||
| #118 | Физический С-400/RM48U, четыре общие ячейки, конечные запасы; доставка и обратный вывоз ТЗМ, резерв/отмена, возврат снятой ПВО; обе фазы вывозного маршрута сохраняются; carrier/крышки/выброс/зажигание/разгон в записи; фантомное ПВО удалено | Визуальная приёмка пуска и маршрутов на сложном рельефе; другие носители не добавлены без подтверждённого профиля |
|
||||
| #128 | Невыполнимый возврат RM48U (ПУ движется/повреждена, маршрут недоступен, заявку уже везёт другая ТЗМ, у склада нет места) больше не блокирует ТЗМ: заявка сохраняется, свободная ТЗМ исполняет независимые заявки на доставку; выполнимый возврат снова в приоритете; консервация боеприпасов и save-restore посреди маршрута покрыты регрессиями | Игровая приёмка маршрутов на сложном рельефе остаётся за #118 |
|
||||
| #129 | Единые стадии пуска: выброс без мотора (`cold` 20/24 тика у С-400/С-500, 8 у IRIS-T/Тора), зажигание в текущей позиции, departure с плавным ростом тяги/темпа поворота, наведение только после `cold + boost`; рельсовые ракеты получили spool тяги без холодного выброса, P1-SUN — без струи; RM48U согласован на 20 тиков; live/replay/export читают записанное зажигание; `pk`, максимальные скорости и коллизии не менялись | Парные replay-MP4 до/после и кадры сняты на одном мире/seed/сценарии (Metal/offscreen); измеренный сдвиг первой вспышки 0,233 → 0,900 с. Остаётся человеческая визуальная оценка композиции, very-close план выброса; live-видео, Windows/Linux и живое прослушивание не проверялись |
|
||||
| #134 | Три самостоятельных игровых профиля отдельных РЛС (`radar_search`, `radar_track`, `radar_height`) с устойчивыми ID, циклом/каналами/локальным поиском и разрешёнными продуктами измерения; `on/off` сохраняется, переключение роли на ходу отклоняется; встроенные РЛС комплексов сохраняют своё право на пуск. Сеть передаёт измерившую станцию, возраст и качество, но повторная пересылка не освежает измерение и не даёт права на пуск. Пуск требует собственного подтверждённого огневого трека (или внешней огневой РЛС для отдельной пусковой и дальнего пуска). Карта/монитор/`why` показывают профиль, источник, продукт, качество, каналы и причину отказа; старые сейвы мигрируют по роли, replay хранит профиль. Тесты: сценарий профилей по отдельности/парами/втроём, дублирование, каналы, off/повреждение/связь, relay, миграция и replay | Общий силуэт машины у трёх профилей (различаются поведение, подписи и статусы); публикация наблюдаемой роли РЛС в картине противника (#127) не расширена; визуальная приёмка на Windows/Linux и живые замеры совокупной картины не проводились |
|
||||
|
||||
Для #118 RM48U — явно условный Minecraft-профиль. Существование сочетания опирается на сообщение ведомства,
|
||||
а игровые параметры не выдаются за реальные. `ground-stock` — команда подготовки sandbox-сценария,
|
||||
@@ -51,11 +50,8 @@
|
||||
| #119 | Три read-only луча в известной геометрии ослабляют непрямой blast для корпуса/узлов/объектов; проёмы дают частичное воздействие; прямой контакт сохранён | Unknown/stale: прежний урон без защиты, нулевое ожидание; partial blocks считаются занятыми кубами; GUI-проверка разрушения укрытия ещё нужна |
|
||||
| #120 | Конечное горение, powered/coast, сопротивление и снижение доступного манёвра, один остаточный pk по фактической скорости; swept-встреча; события burnout/energy loss; согласованное прекращение факела/дыма/звука | Игровой профиль, без аэродинамики и реальных параметров; сравнительная выборка 12 рейдов и расширенная сетка 48 рейдов (6 вариантов × 8 seed, батареи/дальности/классы) записаны в measurements; без подтверждённого дефекта параметры не менялись; прослушивание остаётся |
|
||||
| #121 | On/Off в команде и карте, save/replay; Off не создаёт own measurements и сохраняет сетевой приём; раскрытие работающего радара наблюдателем; SEAD использует last-known и возраст | Условный наблюдатель по расстоянию, без радиотехнической модели и ошибки пеленга; выбор на карте ещё не проверен в GUI |
|
||||
| #122 | Воспроизведены три класса: tick fuel exhaustion на двух максимальных составах, HD (полный обход height-cache на каждом взрыве заменён удалением нужных ключей; max135.3M/300M); остановка в UI event на втором крупном приказе (переснимок known_units на каждом дроне заменён одним снимком на приказ и O(журнал+группировка); max command 32.9M/1e9, `/stats` до/после совпал); OOM в `note_sams` (до: 384000 SamKey/27 MiB в одной полной записи 64 РЛС; после: бюджет 32768, адаптивное прореживание без остановки записи; WASM 24002 тика/64 РЛС/60 малых волн прошёл с прежним лимитом 64 MiB); нативные регрессии и callback diagnostics/profile | Требуется приёмка на Windows; без подтверждённого build identity нельзя утверждать ту же причину пользовательского сеанса; FPS/GPU не измерялись |
|
||||
| #124 | Motion + object transforms + feature-gated DLSS SR: engine `ed751714e`; NGX+HDR bootstrap, долгоживущий SDK/context, display↔linear conversion и ordered submit; native TAAU fallback. Полный `cargo xwin build` на MSVC и `v0.4.0-dlss-rc1` с PE32+, `airdef.hmod`, `nvngx_dlss.dll`, notices и A/B launchers опубликованы; 24 HD + layout, mods/no-mods, обычный Metal кадр проверены | Runtime/качество/FPS на RTX/Vulkan не подтверждены; нужна приёмка по `docs/DLSS-TESTING.md`. Ванильные сущности/ветер camera-only; reactive/transparency, FSR3/MetalFX и FG отдельно |
|
||||
| #130 | Первый небольшой backport: upstream `f7b77fbc8` перенесён как engine `94b572cd2`; oversized staging allocations округляются до степени двойки и переиспользуются, копируются только фактические байты; 3 upload/GPU readback-теста прошли на Metal | Полная миграция на Nightly не начата; VSync/pacing, дальний рельеф и другие кандидаты остаются; Windows/Vulkan и долгий игровой RSS-профиль не проверялись |
|
||||
| #122 | Воспроизведены два класса: tick fuel exhaustion на двух максимальных составах, HD (полный обход height-cache на каждом взрыве заменён удалением нужных ключей; max135.3M/300M) и остановка в UI event на втором крупном приказе (переснимок known_units на каждом дроне заменён одним снимком на приказ и O(журнал+группировка); max command 32.9M/1e9, `/stats` до/после совпал); нативные тесты эквивалентности и второго приказа; WASM fixture с 4 принятыми приказами; callback diagnostics/profile | Требуется приёмка на Windows; без подтверждённого build identity нельзя утверждать ту же причину пользовательского сеанса; FPS/GPU не измерялись |
|
||||
| #127 | Этапы 1–2. **Картина:** журнал раскрытий заменён картой контактов (`Intel.contacts`: последнее «пуск/излучение/глушение», место, время, метка эмиссии, наблюдённая гибель, счётчик увиденных пусков), уверенность — функция возраста (Confirmed/Probable/Doubtful, TTL 6000), угроза и цены читают только published-параметры и факты наблюдений (launcher-only без донора «слеп»), уничтожение учится только из BSA. **Structured intent:** `Intent` (Plan/Sead/React/Replace) и `Aim` (юнит, since, switches, confidence) отделены от random-выбора; throttle `SWITCH_HOLD=160`, `SWITCH_CAP=3`, `ASSIGN_PER_TICK=16`, `ASSIGN_PER_CONTACT=6`, цена смены `SWITCH_GAIN=120`; в полёте цель меняется только когда картинка её убила/забыла. **Durable queue:** автосейв пишет версионированную секцию `air 1` — дроны, очередь запуска, задания (id, дрон, цель, юнит, версия, приоритет, намерение, версия рельефа), контакты, RLE-рельеф; очередь ограничена 256, устаревшие/фантомные/дублирующие задания отменяются при загрузке (`JOB_TTL=1200`), картина задания восстанавливается на свою версию, старые saves читаются (пустое небо), сценарии воздух не несут, Live/Replay не смешиваются. **Неизвестная земля не бесплатна** (`Relief.unknown=6` у повторного плана). **Объяснимость:** `enemy_picture()` дополнен aims/pending reason/aimed_by/pending_jobs без русского текста в core. Метаморфные тесты скрытых изменений (включая нагрев/замок РЭБ), save/restore посреди незавершённой очереди, детерминизм seed, 40+ массовый ретаргет. Замеры: `docs/measurements/issue-127-intent-queue-{baseline,result}.json` | GUI поверх `enemy_picture()`, игровая приёмка сохранения налёта на Windows/Linux, оценка баланса ew-adaptive (kills 59→58/59→58/56→63, потери 3→3/3→4/4→2 — следствие throttle, параметры не менялись) |
|
||||
| #135 | **Core (`9d8f3da57`):** умная волна высылает ограниченный бюджет невооружённых разведчиков (Gerbera, собственные id `0x3000_0000`, не тратят combat RNG волны и не входят в её replay); они физически проходят игровые зоны вокруг отмеченных целей и через `REPORT_DELAY` передают только область, публичную категорию, канал (пролёт/излучение/РЭБ/пуск), возраст и качество — без точной точки, `SamKind`, HP, боезапаса, сети и реального id. Сбитый до донесения разведчик ничего не передаёт; уже переданное остаётся и переживает налёты. Планировщик читает отметки наравне с контактами раскрытия и назначает по наблюдаемой роли/свежести/качеству (`Mark::priority`), скрытая станция не становится целью, старая сомнительная отметка уступает свежей скромной; бюджет назначений и исходные цели волны сохранены. Save/load хранит отметки, вылеты, ожидающие донесения и проверенные зоны. **UI/диагностика (этот коммит):** на карте сети разведчик — узнаваемый жёлтый ромб с подписью «разведчик», роль в панели выбора и легенда фильтра; в боевом HUD и на карте — понятная фаза вылета (разведка/донесение/завершение) только пока сеть держит разведчика; в sandbox-режиме `truth` — янтарная метка и счётчик отметок. Причина выбора показана в `/airdef recon` и на странице меню «Разведка противника (разбор)» (из «Повторы…»): отметки best-first с разбором `приоритет = свежесть×4 + качество×3 + роль` (`recon::priority_parts`, сверен тестом с `Mark::priority`) и дроны, нацеленные на отметку. Всеведущая картина противника в обычный HUD не выводится — только явный debug/разбор. Механика, модели и текстуры не менялись. Тесты: `priority_parts`-кросс-чек, `recon_view`, панель, дерево команд | Игровая/визуальная приёмка значка и фазы на Windows/Linux; приёмка разбора в GUI; баланс приоритетов по серии seed остаётся за core-приёмкой |
|
||||
|
||||
По #127 реализованы карта контактов, структурированное намерение с throttle и durable-очередь:
|
||||
autosave хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому
|
||||
|
||||
+3
-24
@@ -7,31 +7,10 @@
|
||||
поэтому запись может сохраниться и без ручного копирования.
|
||||
Задача: [#122](https://gitea.maoniao.team/chexit/airdef/issues/122).
|
||||
|
||||
**Воспроизведены и исправлены три конкретные причины отключения в этом классе нагрузки.**
|
||||
**Воспроизведены и исправлены две конкретные причины отключения в этом классе нагрузки.**
|
||||
Первая — тик и кэш высот (`1f28f83`, ниже). Вторая — событие UI и второй приказ
|
||||
(`order_raid`, см. раздел «Второй налёт из UI: событие, не тик»). Третья — исчерпание
|
||||
64 MiB линейной памяти WASM полными ключами поз техники в реплеях. GPU/FPS отдельно не измерялись.
|
||||
|
||||
## OOM при записи поз техники
|
||||
|
||||
Точный лог Windows: `rust_oom` ← `RawVec<SamKey>::grow_one` ← `Recording::note_sams` ←
|
||||
`Sim::step` во время обычного `tick`, с оставшимся fuel. Это не повтор прежнего OutOfFuel.
|
||||
|
||||
До исправления нативная регрессия с 64 непрерывно вращающимися РЛС на полной записи 12000 тиков
|
||||
создавала 384000 `SamKey`: 27 MiB только в этих ключах, без учёта ёмкости `Vec`, траекторий и
|
||||
событий. Активная запись и три сохранённых реплея могли превысить лимит 64 MiB.
|
||||
|
||||
`Recording` теперь имеет общий бюджет 32768 ключей поз. При превышении старые ключи каждой
|
||||
трассы прореживаются вдвое без потери первой и последней позы, освобождённая ёмкость возвращается,
|
||||
а интервал следующих samples удваивается. Запись не обрывается: регрессия проверяет бюджет
|
||||
длины и реально выделенной ёмкости, а также наличие свежей позы в конце окна. Для обычных
|
||||
коротких записей частота не меняется; при нехватке памяти точность старого движения снижается.
|
||||
|
||||
Проверки: core release 233 + 8 сценариев (8 ignored), adapter 68 + 1 boundary + 5 сценариев;
|
||||
настоящий WASM contract 30 шагов. Дополнительный flat-world WASM-стресс: 64 РЛС, 60 волн по
|
||||
4 Shahed на 4000 блоках, 24002 тика и два полных окна записи, 185 шагов; max tick fuel
|
||||
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
|
||||
синтетический host без GPU и не приёмка Windows GUI.
|
||||
(`order_raid`, см. раздел «Второй налёт из UI: событие, не тик»). Без старого лога не
|
||||
утверждается, что Windows-сеанс имел именно их; GPU/FPS отдельно не измерялись.
|
||||
|
||||
## Второй налёт из UI: событие, не тик
|
||||
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
# Issue #126, этап 1: retained-геометрия моделей мода — замеры
|
||||
|
||||
Первый самостоятельный этап направления A #126: грани моделей мода резолвятся против атласа
|
||||
один раз на generation пака, кадр только трансформирует и освещает их. Это **не** GPU-instancing:
|
||||
вершины по-прежнему собираются на CPU и загружаются каждый кадр; объём upload не менялся.
|
||||
Изменение только в рендере (`game/mod_models.rs` + span/счётчики/инвалидация), боевая симуляция
|
||||
(WASM-мод) не тронута — тот же `airdef.hmod` в обоих прогонах A/B.
|
||||
|
||||
## Стенд
|
||||
|
||||
- Apple M5 (10 ядер, 16 ГБ), macOS, Metal. **Ryzen 5600X / RTX 3060 не профилировались** —
|
||||
приёмка на целевом железе pending (контракт #126).
|
||||
- Engine pin `ed751714e` (ветка форка `agent/126-engine-first-stage`), AirDef base `60f1bf0fd`.
|
||||
Baseline-бинарник — тот же pin без правки; after — с правкой. Оба `--profile fast --features mods`.
|
||||
- 2560×1440 offscreen (окно 1280×720 @2x), пресет HD, `HORIZON_HD_SCALE=1`, in-frame
|
||||
(`--in-frame`: фидбек мода читается `chat-log`, тик в кадре — одинаково в A/B),
|
||||
`HORIZON_NO_AUDIO=1`, `HORIZON_SPIKES=0` (span каждого кадра в логе),
|
||||
`HORIZON_SHADER_PACK_TIMING=1`. Одна игра за раз; чужих игр во время парных прогонов не было.
|
||||
- Мир `Polygon` (копия `run-home/saves/Polygon`), свежий `HORIZON_HOME` на прогон.
|
||||
Камера `tp @s 40 76 40 135 25`, `time set 6000`, `advance_time/advance_weather false`,
|
||||
`weather clear`, creative, HUD скрыт.
|
||||
|
||||
## Сцена и драйвер
|
||||
|
||||
Драйвер — scratch-скрипт `/tmp/airdef-issue126-run/profile.py` (в коммит не входит; команды и
|
||||
тайминги зафиксированы здесь и в `report.json`):
|
||||
|
||||
1. 14 батарей: `airdef deploy s400/patriot/pantsir/gepard/nasams/irist/tor` ×2.
|
||||
2. Raid: `airdef wave shahed 40 900`, `airdef wave kh101 16 1400`, `airdef wave mix 24 700`.
|
||||
Волна принимается не сразу: противник ищет площадки и ждёт terrain (~15–20 с), факт принятия
|
||||
проверялся по чату («ВОЗДУШНАЯ ТРЕВОГА», «В воздухе: N») и counters `mod_models.models`.
|
||||
3. `bench N` (сброс frame-stats и counters, ответ — p50/p95/p99/max frame/CPU/GPU + фазы),
|
||||
`stats` (counters `mod_models`), `sample` процесса на окно bench, скриншот.
|
||||
|
||||
Static-сцена: только батареи, `HORIZON_HD_TAA=0 HORIZON_HD_WIND=0 HORIZON_HD_CLOUDS=0
|
||||
HORIZON_HD_VOLFOG=0`, 3 кадра подряд; движущиеся пиксели (вода) маскируются по размаху >16/255
|
||||
между кадрами одного прогона (методика `tools/hd_bench.py`), сравнение A/B — по статичным.
|
||||
|
||||
## Результаты (парные прогоны, одна сцена)
|
||||
|
||||
Raid, develop 30 с + bench 12 с (`before-raid3` / `after-raid`), ~135 моделей/кадр:
|
||||
|
||||
| Метрика | before | after |
|
||||
|---|---|---|
|
||||
| `entity_geometry` CPU avg / p95 / p99, мс | 5.71 / 8.7 / 10.6 | 1.57 / 2.2 / 2.7 |
|
||||
| фаза `prepare` avg, мс | 23.49 | 7.05 |
|
||||
| frame CPU avg / p50 / p95 / p99, мс | 78.8 / 75.5 / 133.0 / 263.4 | 71.8 / 65.3 / 112.7 / 181.0 |
|
||||
| span `mod_models` CPU avg / p95 / p99, мс | — (внутри `entity_geometry`) | 1.32 / 2.0 / 2.3 |
|
||||
|
||||
Combat-плотный raid, develop 45 с + bench 15 с (`before-combat` / `after-combat`); фазы боя
|
||||
не синхронизированы по тикам (before: 28 в воздухе, 12 сбито; after: 40 в воздухе, 0 сбито):
|
||||
|
||||
| Метрика | before | after |
|
||||
|---|---|---|
|
||||
| `entity_geometry` CPU avg / p95 / p99, мс | 6.5 / 12.1 / 15.0 | 1.95 / 3.3 / 4.4 |
|
||||
| фаза `prepare` avg, мс | 20.13 | 7.78 |
|
||||
| frame CPU avg / p50 / p95 / p99, мс | 85.8 / 84.8 / 127.2 / 167.5 | 49.5 / 48.9 / 71.8 / 77.1 |
|
||||
|
||||
Counters `mod_models` (after-raid, окно bench, 155 кадров): models 21001 (~135/кадр),
|
||||
quads 2 760 334 (~17.8 тыс./кадр), vertex_bytes 485.8 МБ (~3.1 МБ/кадр, 44 Б/вершина),
|
||||
motion_bytes 618.3 МБ (~4 МБ/кадр, 56 Б/вершина), mesh_builds 0, atlas_scans 0 — в установившемся
|
||||
кадре bake нет, только трансформы. Байты upload до/после одинаковы (вершины те же).
|
||||
|
||||
Static (4 батареи, ~60 моделей/кадр): `prepare` 6.38 → 1.51 мс, frame CPU p50 15.1 → 10.9 мс,
|
||||
p95 42.7 → 15.5, p99 77.1 → 18.3 (settle 8 с). **Пиксели A/B при settle 25 с (LOD сошёлся):
|
||||
0 статичных пикселей с разницей >20/255 из 3.44 млн (93.2% кадра статичны), mean abs diff 0.128.**
|
||||
При settle 8 с разница 3991 px (0.116%) — вся в полосе горизонта y≤385 (дальний LOD не сошёлся,
|
||||
after-бинарник быстрее → другое состояние LOD к снимку); baseline↔baseline при том же settle — 14 px.
|
||||
|
||||
## Reload и world unload (lifecycle-smoke)
|
||||
|
||||
`lifecycle.py`: батареи → скриншот → F3+T (reload) → скриншот → Esc → «Save and Quit to Title» →
|
||||
`open Polygon` → батареи → скриншот. Counters after: atlas_scans 1 → 2 → 3, mesh_builds
|
||||
17 → 34 → 51 (17 состояний моделей перестроены после reload и после unload), модели рисуются
|
||||
в каждом этапе. Пиксели pre/post reload при 25 с ожидания: **before 0.3003%, after 0.2982%**
|
||||
статичных пикселей >20/255 — одинаковая у обоих бинарников остаточная разница самого reload
|
||||
(атлас/LOD после `clear_lod`), не регрессия правки; при 12 с ожидания разница больше у обоих
|
||||
(LOD не сошёлся), вся в полосе горизонта, на моделях — ноль.
|
||||
|
||||
## Тесты
|
||||
|
||||
```sh
|
||||
cd horizon && cargo test --profile fast -p horizon-client --bin horizon-client --features mods mod_models::tests
|
||||
```
|
||||
|
||||
- `retained_emit_matches_the_per_frame_bake` — вершины retained-пути бит-в-бит равны прежнему
|
||||
покадровому bake (`block_model_vertices` + material/post-pass) на матрице трансформов
|
||||
(scale × rotation × translation) × glow × light × emission, включая previous-позиции motion (#124).
|
||||
- `special_materials_match_names_and_centres` — таблица special-материалов и строгие границы
|
||||
прямоугольников (центр квада).
|
||||
|
||||
## Ограничения и что дальше
|
||||
|
||||
- Замеры только на M5/Metal; 5600X/3060 и M5-боевой p99-trace — pending acceptance #126.
|
||||
- In-frame режим замера (тик в кадре); server-thread путь проверен smoke-прогоном (HD, модели,
|
||||
reload работают), парные замеры в нём не снимались.
|
||||
- Фазы боя в A/B не синхронизированы по тикам (wall-clock waits); ordered combat trace harness
|
||||
не строился — правка только рендерная, sim/RNG не тронуты (diff scope).
|
||||
- Upload bytes/frame не уменьшены: GPU-instancing (per-instance буферы, GPU-интерполяция,
|
||||
indirect draws) — следующий этап A. HD smoke (направление B) не тронут.
|
||||
- Скрипты драйверов — scratch (`/tmp/airdef-issue126-run/`), в репозиторий не входят;
|
||||
воспроизведение — по командам выше и `report.json`.
|
||||
@@ -1,338 +0,0 @@
|
||||
{
|
||||
"issue": 126,
|
||||
"stage": "first: retained CPU-resolved model meshes (not GPU instancing)",
|
||||
"engine_pin": "ed751714e0d24d02062976ee615e994186284170",
|
||||
"airdef_base": "60f1bf0fd873d89a28b47bc7316b2fc02a79e669",
|
||||
"machine": "Apple M5, 10 cores, 16 GB, macOS, Metal backend",
|
||||
"render": "2560x1440 offscreen (window 1280x720 @2x), HD preset, HORIZON_HD_SCALE=1, in-frame mode, HORIZON_NO_AUDIO=1, HORIZON_SPIKES=0, HORIZON_SHADER_PACK_TIMING=1",
|
||||
"mod": "airdef.hmod built from airdef-mod @ base (unchanged between A/B), packer pinned ed751714",
|
||||
"scene": {
|
||||
"world": "Polygon (copy of run-home/saves/Polygon), fresh HORIZON_HOME per run",
|
||||
"camera": "tp @s 40 76 40 135 25, time set 6000, advance_time/advance_weather false, weather clear, gamemode creative, HUD hidden (f1)",
|
||||
"batteries": "deploy s400/patriot/pantsir/gepard/nasams/irist/tor twice (14 complexes)",
|
||||
"raid": "wave shahed 40 900; wave kh101 16 1400; wave mix 24 700",
|
||||
"static_env": "HORIZON_HD_TAA=0 HORIZON_HD_WIND=0 HORIZON_HD_CLOUDS=0 HORIZON_HD_VOLFOG=0",
|
||||
"driver": "/tmp/airdef-issue126-run/profile.py (scratch; commands and waits recorded here)"
|
||||
},
|
||||
"runs": {
|
||||
"before-raid3": {
|
||||
"frames": 130,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 78.76,
|
||||
"max_ms": 321.6,
|
||||
"p50_ms": 75.53,
|
||||
"p95_ms": 132.96,
|
||||
"p99_ms": 263.41
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 23.49,
|
||||
"render": 25.45,
|
||||
"tick": 28.1,
|
||||
"update": 1.73
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1355,
|
||||
"avg": 5.71,
|
||||
"p50": 6.0,
|
||||
"p95": 8.7,
|
||||
"p99": 10.6,
|
||||
"max": 29.1
|
||||
},
|
||||
"mod_models_span_cpu_ms": null,
|
||||
"mod_models_counters": null,
|
||||
"airborne_at_bench": "В воздухе: 19, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 4; удары по ПУ: пущено 0, уничтожено 0, подавле"
|
||||
},
|
||||
"after-raid": {
|
||||
"frames": 124,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 71.75,
|
||||
"max_ms": 427.98,
|
||||
"p50_ms": 65.26,
|
||||
"p95_ms": 112.68,
|
||||
"p99_ms": 181.0
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 7.05,
|
||||
"render": 30.29,
|
||||
"tick": 30.43,
|
||||
"update": 3.97
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1260,
|
||||
"avg": 1.57,
|
||||
"p50": 1.6,
|
||||
"p95": 2.2,
|
||||
"p99": 2.7,
|
||||
"max": 33.9
|
||||
},
|
||||
"mod_models_span_cpu_ms": {
|
||||
"n": 1065,
|
||||
"avg": 1.32,
|
||||
"p50": 1.3,
|
||||
"p95": 2.0,
|
||||
"p99": 2.3,
|
||||
"max": 2.7
|
||||
},
|
||||
"mod_models_counters": {
|
||||
"atlas_scans": 0,
|
||||
"frames": 155,
|
||||
"mesh_builds": 0,
|
||||
"models": 21001,
|
||||
"motion_bytes": 618314816,
|
||||
"motion_quads": 2760334,
|
||||
"quads": 2760334,
|
||||
"vertex_bytes": 485818784
|
||||
},
|
||||
"airborne_at_bench": "В воздухе: 24, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавле"
|
||||
},
|
||||
"before-combat": {
|
||||
"frames": 166,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 85.79,
|
||||
"max_ms": 185.08,
|
||||
"p50_ms": 84.82,
|
||||
"p95_ms": 127.19,
|
||||
"p99_ms": 167.54
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 20.13,
|
||||
"render": 35.38,
|
||||
"tick": 29.07,
|
||||
"update": 1.21
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1709,
|
||||
"avg": 6.5,
|
||||
"p50": 5.8,
|
||||
"p95": 12.1,
|
||||
"p99": 15.0,
|
||||
"max": 18.4
|
||||
},
|
||||
"mod_models_span_cpu_ms": null,
|
||||
"mod_models_counters": null,
|
||||
"airborne_at_bench": "В воздухе: 28, ракет: 0, ПВО: 14, сбито: 12, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавл"
|
||||
},
|
||||
"after-combat": {
|
||||
"frames": 275,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 49.47,
|
||||
"max_ms": 88.18,
|
||||
"p50_ms": 48.89,
|
||||
"p95_ms": 71.79,
|
||||
"p99_ms": 77.13
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 7.78,
|
||||
"render": 24.58,
|
||||
"tick": 16.23,
|
||||
"update": 0.88
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1861,
|
||||
"avg": 1.95,
|
||||
"p50": 1.8,
|
||||
"p95": 3.3,
|
||||
"p99": 4.4,
|
||||
"max": 19.5
|
||||
},
|
||||
"mod_models_span_cpu_ms": {
|
||||
"n": 1733,
|
||||
"avg": 1.63,
|
||||
"p50": 1.5,
|
||||
"p95": 2.8,
|
||||
"p99": 3.9,
|
||||
"max": 4.4
|
||||
},
|
||||
"mod_models_counters": {
|
||||
"atlas_scans": 0,
|
||||
"frames": 286,
|
||||
"mesh_builds": 3,
|
||||
"models": 44077,
|
||||
"motion_bytes": 1173606784,
|
||||
"motion_quads": 5239316,
|
||||
"quads": 5239316,
|
||||
"vertex_bytes": 922119616
|
||||
},
|
||||
"airborne_at_bench": "В воздухе: 40, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавле"
|
||||
},
|
||||
"before-static": {
|
||||
"frames": 174,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 17.92,
|
||||
"max_ms": 88.07,
|
||||
"p50_ms": 15.12,
|
||||
"p95_ms": 42.66,
|
||||
"p99_ms": 77.07
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 6.38,
|
||||
"render": 7.6,
|
||||
"tick": 3.9,
|
||||
"update": 0.04
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1094,
|
||||
"avg": 4.21,
|
||||
"p50": 4.6,
|
||||
"p95": 6.6,
|
||||
"p99": 7.1,
|
||||
"max": 27.1
|
||||
},
|
||||
"mod_models_span_cpu_ms": null,
|
||||
"mod_models_counters": null,
|
||||
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
|
||||
},
|
||||
"after-static": {
|
||||
"frames": 190,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 11.1,
|
||||
"max_ms": 20.46,
|
||||
"p50_ms": 10.92,
|
||||
"p95_ms": 15.54,
|
||||
"p99_ms": 18.3
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 1.51,
|
||||
"render": 6.47,
|
||||
"tick": 2.97,
|
||||
"update": 0.16
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1163,
|
||||
"avg": 1.29,
|
||||
"p50": 1.3,
|
||||
"p95": 1.9,
|
||||
"p99": 2.1,
|
||||
"max": 26.3
|
||||
},
|
||||
"mod_models_span_cpu_ms": {
|
||||
"n": 913,
|
||||
"avg": 1.04,
|
||||
"p50": 1.0,
|
||||
"p95": 1.4,
|
||||
"p99": 1.5,
|
||||
"max": 1.6
|
||||
},
|
||||
"mod_models_counters": {
|
||||
"atlas_scans": 0,
|
||||
"frames": 196,
|
||||
"mesh_builds": 0,
|
||||
"models": 11760,
|
||||
"motion_bytes": 322255360,
|
||||
"motion_quads": 1438640,
|
||||
"quads": 1438640,
|
||||
"vertex_bytes": 253200640
|
||||
},
|
||||
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
|
||||
},
|
||||
"before-static-long": {
|
||||
"frames": 237,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 9.68,
|
||||
"max_ms": 15.56,
|
||||
"p50_ms": 9.59,
|
||||
"p95_ms": 12.85,
|
||||
"p99_ms": 14.01
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 3.72,
|
||||
"render": 4.32,
|
||||
"tick": 1.51,
|
||||
"update": 0.12
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1951,
|
||||
"avg": 3.29,
|
||||
"p50": 3.5,
|
||||
"p95": 3.9,
|
||||
"p99": 4.1,
|
||||
"max": 13.8
|
||||
},
|
||||
"mod_models_span_cpu_ms": null,
|
||||
"mod_models_counters": null,
|
||||
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
|
||||
},
|
||||
"after-static-long": {
|
||||
"frames": 181,
|
||||
"cpu_ms": {
|
||||
"avg_ms": 14.21,
|
||||
"max_ms": 24.87,
|
||||
"p50_ms": 14.27,
|
||||
"p95_ms": 20.55,
|
||||
"p99_ms": 23.39
|
||||
},
|
||||
"phases_avg_ms": {
|
||||
"prepare": 1.92,
|
||||
"render": 8.27,
|
||||
"tick": 3.64,
|
||||
"update": 0.37
|
||||
},
|
||||
"entity_geometry_cpu_ms": {
|
||||
"n": 1506,
|
||||
"avg": 1.15,
|
||||
"p50": 1.0,
|
||||
"p95": 2.0,
|
||||
"p99": 2.2,
|
||||
"max": 14.9
|
||||
},
|
||||
"mod_models_span_cpu_ms": {
|
||||
"n": 1354,
|
||||
"avg": 0.88,
|
||||
"p50": 0.8,
|
||||
"p95": 1.6,
|
||||
"p99": 1.7,
|
||||
"max": 1.8
|
||||
},
|
||||
"mod_models_counters": {
|
||||
"atlas_scans": 0,
|
||||
"frames": 183,
|
||||
"mesh_builds": 0,
|
||||
"models": 10980,
|
||||
"motion_bytes": 300881280,
|
||||
"motion_quads": 1343220,
|
||||
"quads": 1343220,
|
||||
"vertex_bytes": 236406720
|
||||
},
|
||||
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
|
||||
}
|
||||
},
|
||||
"pixel_ab": {
|
||||
"static_settle25": {
|
||||
"static_pixels_pct": 93.2,
|
||||
"diff_gt20": 0,
|
||||
"diff_gt60": 0,
|
||||
"mean_abs_diff": 0.128
|
||||
},
|
||||
"static_settle8": {
|
||||
"static_pixels_pct": 93.1,
|
||||
"diff_gt20": 3991,
|
||||
"diff_gt60": 0,
|
||||
"note": "LOD not converged at 8 s; diffs all in horizon band y<=385, none on models; baseline-vs-baseline at same settle: 14 px"
|
||||
},
|
||||
"reload_lifecycle_settle25": {
|
||||
"before_diff_gt20_pct": 0.3003,
|
||||
"after_diff_gt20_pct": 0.2982,
|
||||
"note": "same residual in both binaries (atlas/LOD after clear_lod); at 12 s settle both larger, all in horizon band, zero on models"
|
||||
}
|
||||
},
|
||||
"tests": {
|
||||
"command": "cargo test --profile fast -p horizon-client --bin horizon-client --features mods mod_models::tests",
|
||||
"result": "2 passed (retained_emit_matches_the_per_frame_bake, special_materials_match_names_and_centres)"
|
||||
},
|
||||
"lifecycle_counters_after": {
|
||||
"pre_reload": {
|
||||
"atlas_scans": 1,
|
||||
"mesh_builds": 17
|
||||
},
|
||||
"post_reload": {
|
||||
"atlas_scans": 2,
|
||||
"mesh_builds": 34
|
||||
},
|
||||
"post_unload_reenter": {
|
||||
"atlas_scans": 3,
|
||||
"mesh_builds": 51
|
||||
}
|
||||
},
|
||||
"engine_commit": "a861c1ed2402fb13950a3c3049d16e9971489c24",
|
||||
"engine_branch": "kimi-work-124"
|
||||
}
|
||||
+1
-1
Submodule horizon updated: 2bcce64236...278f356aa6
@@ -13,10 +13,6 @@ MUZZLES = {"none", "patriot", "pantsir", "grid", "rails", "cells"}
|
||||
ENGINES = {"prop": {"type", "back", "size"}, "jet": {"type", "up", "back", "size"},
|
||||
"rocket": {"type", "back", "size"}}
|
||||
MODEL = r"airdef:[a-z0-9_]+"
|
||||
# The keys of the existing simulation enums, written once here so the generator and
|
||||
# Rust keep to one encoding. A new enum variant needs its key added here.
|
||||
CONFIG_MODES = {"integrated", "launcher"}
|
||||
CONFIG_ROLES = {"multi", "search", "engagement", "height"}
|
||||
|
||||
|
||||
def load():
|
||||
@@ -33,26 +29,6 @@ def load():
|
||||
referenced.extend(entry["item"] for entry in group if entry["item"] is not None)
|
||||
if len(referenced) != len(set(referenced)) or not set(referenced) <= set(ids):
|
||||
raise ValueError("duplicate or unregistered content item")
|
||||
unit_kinds = {entry["kind"] for entry in data["units"]}
|
||||
taken = set(referenced) | unit_kinds | set(ids)
|
||||
for variant in data["variants"]:
|
||||
where = f"variants[{variant['id']}]"
|
||||
if set(variant) != {"id", "kind", "mode", "role", "label", "description"}:
|
||||
raise ValueError(f"{where}: expected keys id, kind, mode, role, label, description, got {sorted(variant)}")
|
||||
if not re.fullmatch(r"[a-z0-9_]+", variant["id"]):
|
||||
raise ValueError(f"{where}: invalid variant id {variant['id']!r}")
|
||||
if variant["kind"] not in unit_kinds:
|
||||
raise ValueError(f"{where}: unknown unit kind {variant['kind']}")
|
||||
if variant["mode"] not in CONFIG_MODES or variant["role"] not in CONFIG_ROLES:
|
||||
raise ValueError(f"{where}: unknown configuration {variant['mode']}/{variant['role']}")
|
||||
if not isinstance(variant["label"], str) or not variant["label"]:
|
||||
raise ValueError(f"{where}: expected a menu label")
|
||||
if not isinstance(variant["description"], str) or not variant["description"]:
|
||||
raise ValueError(f"{where}: expected a description")
|
||||
if variant["id"] in taken:
|
||||
raise ValueError(f"{where}: variant id collides with an existing identity or kind")
|
||||
if len({v["id"] for v in data["variants"]}) != len(data["variants"]):
|
||||
raise ValueError("duplicate variant id in content catalog")
|
||||
for item in items:
|
||||
if len(item["color"]) != 3 or any(not isinstance(c, int) or not 0 <= c <= 255 for c in item["color"]):
|
||||
raise ValueError(f"invalid icon color for {item['id']}")
|
||||
|
||||
@@ -342,16 +342,10 @@ ICON_DRAW = {
|
||||
"mover": _mover, "remover": _remover, "flare_gun": _flare,
|
||||
}
|
||||
|
||||
# Items that borrow another item's icon until their own art lands (#136: the optical post uses the
|
||||
# radar icon). The alias is part of the generated model, so no duplicate texture is written.
|
||||
ICON_ALIAS = {
|
||||
"deploy_optical": "deploy_radar",
|
||||
}
|
||||
|
||||
|
||||
def render_icon(name, color, seed):
|
||||
c = _Icon(color, seed)
|
||||
ICON_DRAW[ICON_ALIAS.get(name, name)](c)
|
||||
ICON_DRAW[name](c)
|
||||
# Контур по краю силуэта: тёмные предметы — светлым, светлые — тёмным, чтобы читались на обоих фонах.
|
||||
# Альфа-маска не меняется: контур перекрашивает только уже нарисованные пиксели.
|
||||
lum = 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]
|
||||
|
||||
@@ -9,7 +9,7 @@ def write_json(path, obj):
|
||||
|
||||
|
||||
|
||||
def write_registry(out, namespace, models, items, camera_models, icon_aliases=None):
|
||||
def write_registry(out, namespace, models, items, camera_models):
|
||||
a = os.path.join(out, "assets", namespace)
|
||||
d = os.path.join(out, "data", namespace, "horizon")
|
||||
lang = {}
|
||||
@@ -19,11 +19,9 @@ def write_registry(out, namespace, models, items, camera_models, icon_aliases=No
|
||||
write_json(os.path.join(d, "block", name + ".json"),
|
||||
{"template": "minecraft:stone", "item": False})
|
||||
lang[f"block.{NS}.{name}"] = title
|
||||
icon_aliases = icon_aliases or {}
|
||||
for name, title, _ in items:
|
||||
icon = icon_aliases.get(name, name)
|
||||
write_json(os.path.join(a, "models", "item", name + ".json"),
|
||||
{"parent": "minecraft:item/generated", "textures": {"layer0": f"{NS}:item/{icon}"}})
|
||||
{"parent": "minecraft:item/generated", "textures": {"layer0": f"{NS}:item/{name}"}})
|
||||
write_json(os.path.join(a, "items", name + ".json"),
|
||||
{"model": {"type": "minecraft:model", "model": f"{NS}:item/{name}"}})
|
||||
write_json(os.path.join(d, "item", name + ".json"), {"template": "minecraft:stick", "max_stack_size": 1})
|
||||
|
||||
+1
-20
@@ -14,8 +14,6 @@ CLASSES = {"drone": "Drone", "jet": "Jet", "cruise": "Cruise", "supersonic": "Su
|
||||
"ballistic": "Ballistic"}
|
||||
FAMILIES = {"trainable": "Trainable", "gun": "Gun", "turret": "Turret", "vertical": "Vertical",
|
||||
"static": "Static", "truck": "Truck", "light": "Light"}
|
||||
MODES = {"integrated": "Integrated", "launcher": "LauncherOnly"}
|
||||
ROLES = {"multi": "Multifunction", "search": "Search", "engagement": "Engagement", "height": "Height"}
|
||||
SOUND_PREFIX = "sound::"
|
||||
|
||||
|
||||
@@ -306,33 +304,16 @@ def generate_unit_specs(data):
|
||||
return "\n".join(lines + ["];", ""])
|
||||
|
||||
|
||||
def generate_variants(data):
|
||||
"""A variant of a complex is one record: a deploy id over an existing unit's
|
||||
typed configuration (`battery::SamMode`, `battery::RadarRole`). No balance of
|
||||
its own — everything but the label comes from the unit rows it points at."""
|
||||
lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.",
|
||||
"pub const VARIANTS: &[UnitVariant] = &["]
|
||||
for entry in data["variants"]:
|
||||
mode = MODES[entry["mode"]]
|
||||
role = ROLES[entry["role"]]
|
||||
lines.append(f" UnitVariant {{ id: {text(entry['id'])}, kind: SamKind::{entry['kind']}, "
|
||||
f"mode: SamMode::{mode}, role: RadarRole::{role}, label: {text(entry['label'])}, "
|
||||
f"description: {text(entry['description'])} }},")
|
||||
return "\n".join(lines + ["];", ""])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
sound_output = OUTPUT.with_name("catalog_sound_ids.rs")
|
||||
variant_output = OUTPUT.with_name("unit_variants_generated.rs")
|
||||
specs = load_specs()
|
||||
outputs = ((OUTPUT, generate(load())),
|
||||
(sound_output, generate_sound_ids(load_sounds())),
|
||||
(SPEC_OUTPUT, generate_specs(specs)),
|
||||
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)),
|
||||
(variant_output, generate_variants(load())))
|
||||
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)))
|
||||
for path, generated in outputs:
|
||||
if args.check:
|
||||
if not path.exists() or path.read_text(encoding="utf-8") != generated:
|
||||
|
||||
+3
-4
@@ -27,7 +27,7 @@ from airdef_assets import pipeline
|
||||
from airdef_assets.bounds import write_rust_bounds
|
||||
from airdef_assets.registry import write_json, write_registry
|
||||
from airdef_assets.texture_catalog import RINGED, STRETCH_FN, TEXTURES
|
||||
from airdef_assets.icons import ICON_ALIAS, ITEMS, render_icon
|
||||
from airdef_assets.icons import ITEMS, render_icon
|
||||
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "airdef-mod"))
|
||||
NS = "airdef"
|
||||
|
||||
@@ -1090,9 +1090,8 @@ def generate(out):
|
||||
write_json(os.path.join(a, "models", "block", name + ".json"), model(fn(), name.endswith("_burnt")))
|
||||
GT.write_block_textures(a, TEXTURES, VARIANTS, STRETCH_FN)
|
||||
for name, _, color in ITEMS:
|
||||
if name not in ICON_ALIAS:
|
||||
GT.write_item_icon(a, name, render_icon(name, color, zlib.crc32(name.encode())))
|
||||
write_registry(out, NS, [(name, title) for name, (_, title) in MODELS.items()], ITEMS, CAM_MODELS, ICON_ALIAS)
|
||||
GT.write_item_icon(a, name, render_icon(name, color, zlib.crc32(name.encode())))
|
||||
write_registry(out, NS, [(name, title) for name, (_, title) in MODELS.items()], ITEMS, CAM_MODELS)
|
||||
return len(MODELS), len(ITEMS), len(TEXTURES)
|
||||
|
||||
|
||||
|
||||
Generated
-1238
File diff suppressed because it is too large
Load Diff
@@ -1,26 +0,0 @@
|
||||
[package]
|
||||
name = "airdef-rt-probe"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
# Same pin as the engine at the recorded gitlink (horizon/crates/horizon-client/Cargo.toml):
|
||||
# wgpu 30.0.1 plus the engine's vendored wgpu-hal patch. The probe is a capability test,
|
||||
# not a renderer; it never touches the game or the mod.
|
||||
[dependencies]
|
||||
wgpu = { version = "=30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "dx12", "gles", "wgsl", "naga-ir"] }
|
||||
pollster = "0.4"
|
||||
# Caret reqs would float the stack to 30.0.2; the engine lock pins 30.0.1.
|
||||
naga = { version = "=30.0.1", default-features = false }
|
||||
naga-types = { version = "=30.0.1", default-features = false }
|
||||
wgpu-core = { version = "=30.0.1", default-features = false }
|
||||
wgpu-types = { version = "=30.0.1", default-features = false }
|
||||
wgpu-naga-bridge = { version = "=30.0.1", default-features = false }
|
||||
wgpu-core-deps-apple = { version = "=30.0.1", default-features = false }
|
||||
wgpu-core-deps-emscripten = { version = "=30.0.1", default-features = false }
|
||||
wgpu-core-deps-windows-linux-android = { version = "=30.0.1", default-features = false }
|
||||
|
||||
[patch.crates-io]
|
||||
wgpu-hal = { path = "../../horizon/third_party/wgpu-hal" }
|
||||
|
||||
[workspace]
|
||||
@@ -1,443 +0,0 @@
|
||||
//! Native ray-tracing capability probe for AirDef issue #125, stage 1.
|
||||
//!
|
||||
//! Reports the real OS/backend/adapter/driver/features of the pinned wgpu
|
||||
//! (=30.0.1 plus the engine's vendored `third_party/wgpu-hal` patch), builds one
|
||||
//! BLAS/TLAS and traces a 16x16 ray-query frame, checking every ray against a
|
||||
//! CPU point-in-triangle expectation. GPU branding is never trusted: each stage
|
||||
//! is attempted and its real result printed, and an unsupported adapter or
|
||||
//! backend exits with the reason instead of a promise.
|
||||
//!
|
||||
//! Run from the repo root (needs the `horizon` submodule populated for the
|
||||
//! wgpu-hal patch): `cargo run --manifest-path tools/rt-probe/Cargo.toml`
|
||||
//! `RT_PROBE_BACKEND=gl|vulkan|dx12|metal` restricts the backend set, e.g. to
|
||||
//! exercise the unsupported fallback on a machine whose main backend has RT.
|
||||
//! `RT_PROBE_NO_OPTIN=1` requests the RT feature without the experimental
|
||||
//! opt-in, proving the device gate rejects it.
|
||||
//!
|
||||
//! Exit codes: 0 = ray query verified, 2 = unsupported at some stage (reason
|
||||
//! printed), 1 = wrong ray results or a GPU wait failure.
|
||||
|
||||
use std::{
|
||||
env,
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
const SIDE: u32 = 16;
|
||||
const TRI: [[f32; 3]; 3] = [[-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0]];
|
||||
const CUSTOM: u32 = 42;
|
||||
const WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
const SHADER: &str = r#"
|
||||
enable wgpu_ray_query;
|
||||
|
||||
@group(0) @binding(0) var scene: acceleration_structure;
|
||||
@group(0) @binding(1) var<storage, read_write> results: array<vec4<f32>>;
|
||||
|
||||
const SIDE: u32 = 16u;
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let idx = gid.y * SIDE + gid.x;
|
||||
if (idx >= SIDE * SIDE) { return; }
|
||||
let uv = (vec2<f32>(f32(gid.x) + 0.5, f32(gid.y) + 0.5) / f32(SIDE)) * 2.0 - 1.0;
|
||||
var rq: ray_query;
|
||||
let ray = RayDesc(
|
||||
RAY_FLAG_NONE, 0xFFu, 0.0, 100.0,
|
||||
vec3<f32>(uv.x, uv.y, -1.0),
|
||||
vec3<f32>(0.0, 0.0, 1.0),
|
||||
);
|
||||
rayQueryInitialize(&rq, scene, ray);
|
||||
loop {
|
||||
if (!rayQueryProceed(&rq)) { break; }
|
||||
}
|
||||
let hit = rayQueryGetCommittedIntersection(&rq);
|
||||
results[idx] = vec4<f32>(f32(hit.kind), hit.t, f32(hit.instance_custom_data), f32(hit.primitive_index));
|
||||
}
|
||||
"#;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ErrLog(Arc<Mutex<Vec<String>>>);
|
||||
|
||||
impl ErrLog {
|
||||
fn drain(&self) -> Vec<String> {
|
||||
std::mem::take(&mut self.0.lock().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
std::process::exit(run());
|
||||
}
|
||||
|
||||
fn unsupported(stage: &str, why: &str) -> i32 {
|
||||
println!("RESULT: UNSUPPORTED - {stage}: {why}");
|
||||
2
|
||||
}
|
||||
|
||||
fn run() -> i32 {
|
||||
println!(
|
||||
"airdef-rt-probe: issue #125 stage 1, wgpu =30.0.1 + engine third_party/wgpu-hal patch"
|
||||
);
|
||||
println!("os: {} {}", env::consts::OS, env::consts::ARCH);
|
||||
|
||||
// RT_PROBE_BACKEND restricts the backend set, e.g. `gl` to exercise the
|
||||
// unsupported-adapter fallback on a machine whose primary backend has RT.
|
||||
let backends = match env::var("RT_PROBE_BACKEND").as_deref() {
|
||||
Ok("metal") => wgpu::Backends::METAL,
|
||||
Ok("vulkan") => wgpu::Backends::VULKAN,
|
||||
Ok("dx12") => wgpu::Backends::DX12,
|
||||
Ok("gl") => wgpu::Backends::GL,
|
||||
_ => wgpu::Backends::all(),
|
||||
};
|
||||
println!("probing backends: {backends:?}");
|
||||
let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
instance_desc.backends = backends;
|
||||
instance_desc.flags =
|
||||
wgpu::InstanceFlags::from_build_config() | wgpu::InstanceFlags::VALIDATION;
|
||||
let instance = wgpu::Instance::new(instance_desc);
|
||||
let adapters = pollster::block_on(instance.enumerate_adapters(backends));
|
||||
if adapters.is_empty() {
|
||||
return unsupported("adapter", "no native adapter exposed on this OS");
|
||||
}
|
||||
let mut chosen = None;
|
||||
for (i, adapter) in adapters.iter().enumerate() {
|
||||
let info = adapter.get_info();
|
||||
let features = adapter.features();
|
||||
println!(
|
||||
"adapter[{i}]: backend={:?} name={:?} vendor={:#06x} device={:#06x} type={:?} driver={:?} driver_info={:?}",
|
||||
info.backend,
|
||||
info.name,
|
||||
info.vendor,
|
||||
info.device,
|
||||
info.device_type,
|
||||
info.driver,
|
||||
info.driver_info
|
||||
);
|
||||
println!(
|
||||
" EXPERIMENTAL_RAY_QUERY={} features={:?}",
|
||||
features.contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY),
|
||||
features
|
||||
);
|
||||
if chosen.is_none() && features.contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) {
|
||||
chosen = Some(i);
|
||||
}
|
||||
}
|
||||
let Some(idx) = chosen else {
|
||||
return unsupported(
|
||||
"adapter",
|
||||
"no adapter exposes Features::EXPERIMENTAL_RAY_QUERY on this OS/backend set",
|
||||
);
|
||||
};
|
||||
let adapter = &adapters[idx];
|
||||
let info = adapter.get_info();
|
||||
println!(
|
||||
"selected adapter[{idx}]: backend={:?} name={:?}",
|
||||
info.backend, info.name
|
||||
);
|
||||
|
||||
let (device, queue) =
|
||||
match pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("rt-probe"),
|
||||
required_features: wgpu::Features::EXPERIMENTAL_RAY_QUERY,
|
||||
// Default limits keep max_blas_geometry_count/max_tlas_instance_count at 0;
|
||||
// ask for the adapter's real limits so RT resources can be created.
|
||||
required_limits: adapter.limits(),
|
||||
// SAFETY: deliberate experimental opt-in, confined to this probe; the
|
||||
// game itself never requests experimental features (issue #125).
|
||||
// RT_PROBE_NO_OPTIN=1 keeps the opt-in disabled to prove a normal
|
||||
// launch cannot get RT even on a capable adapter.
|
||||
experimental_features: if env::var("RT_PROBE_NO_OPTIN").is_ok() {
|
||||
println!("experimental opt-in: disabled (RT_PROBE_NO_OPTIN)");
|
||||
wgpu::ExperimentalFeatures::disabled()
|
||||
} else {
|
||||
unsafe { wgpu::ExperimentalFeatures::enabled() }
|
||||
},
|
||||
..Default::default()
|
||||
})) {
|
||||
Ok(pair) => pair,
|
||||
Err(e) => {
|
||||
return unsupported(
|
||||
"device",
|
||||
&format!("request_device with EXPERIMENTAL_RAY_QUERY failed: {e}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
let errors = ErrLog::default();
|
||||
let sink = errors.clone();
|
||||
device.on_uncaptured_error(Arc::new(move |e| {
|
||||
eprintln!("uncaptured device error: {e}");
|
||||
sink.0.lock().unwrap().push(format!("{e}"));
|
||||
}));
|
||||
println!("device features: {:?}", device.features());
|
||||
println!(
|
||||
"allowed BLAS vertex formats: {:?}",
|
||||
device.features().allowed_vertex_formats_for_blas()
|
||||
);
|
||||
|
||||
let vertices: Vec<f32> = TRI.iter().flatten().copied().collect();
|
||||
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("probe-triangle"),
|
||||
contents: bytemuck_bytes(&vertices),
|
||||
usage: wgpu::BufferUsages::VERTEX
|
||||
| wgpu::BufferUsages::BLAS_INPUT
|
||||
| wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let size = wgpu::BlasTriangleGeometrySizeDescriptor {
|
||||
vertex_format: wgpu::VertexFormat::Float32x3,
|
||||
vertex_count: 3,
|
||||
index_format: None,
|
||||
index_count: None,
|
||||
flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
|
||||
};
|
||||
let blas = device.create_blas(
|
||||
&wgpu::CreateBlasDescriptor {
|
||||
label: Some("probe-blas"),
|
||||
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
|
||||
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
|
||||
},
|
||||
wgpu::BlasGeometrySizeDescriptors::Triangles {
|
||||
descriptors: vec![size.clone()],
|
||||
},
|
||||
);
|
||||
let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor {
|
||||
label: Some("probe-tlas"),
|
||||
max_instances: 1,
|
||||
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
|
||||
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
|
||||
});
|
||||
tlas[0] = Some(wgpu::TlasInstance::new(
|
||||
&blas,
|
||||
[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
|
||||
CUSTOM,
|
||||
0xFF,
|
||||
));
|
||||
let problems = errors.drain();
|
||||
if !problems.is_empty() {
|
||||
return unsupported("blas/tlas", &problems.join("; "));
|
||||
}
|
||||
println!("stage blas/tlas: created (1 triangle, 1 instance)");
|
||||
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
encoder.build_acceleration_structures(
|
||||
&[wgpu::BlasBuildEntry {
|
||||
blas: &blas,
|
||||
geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
|
||||
size: &size,
|
||||
vertex_buffer: &vertex_buffer,
|
||||
first_vertex: 0,
|
||||
vertex_stride: 12,
|
||||
index_buffer: None,
|
||||
first_index: None,
|
||||
transform_buffer: None,
|
||||
transform_buffer_offset: None,
|
||||
}]),
|
||||
}],
|
||||
[&tlas],
|
||||
);
|
||||
if let Err(code) = submit_checked(&device, &queue, encoder, &errors, "as-build") {
|
||||
return code;
|
||||
}
|
||||
println!("stage as-build: ok");
|
||||
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("probe-ray-query"),
|
||||
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
|
||||
});
|
||||
let compilation = pollster::block_on(shader.get_compilation_info());
|
||||
let shader_errors: Vec<String> = compilation
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|m| m.message_type == wgpu::CompilationMessageType::Error)
|
||||
.map(|m| m.message.clone())
|
||||
.collect();
|
||||
let mut stage_errors = errors.drain();
|
||||
stage_errors.extend(shader_errors);
|
||||
if !stage_errors.is_empty() {
|
||||
return unsupported("ray-query shader", &stage_errors.join("; "));
|
||||
}
|
||||
println!("stage ray-query shader: compiled");
|
||||
|
||||
let results = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("probe-results"),
|
||||
size: (SIDE * SIDE * 16) as u64,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("probe-bgl"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::AccelerationStructure {
|
||||
vertex_return: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("probe-bg"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: tlas.as_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: results.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("probe-pl"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("probe-pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let readback = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("probe-readback"),
|
||||
size: results.size(),
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
pass.set_pipeline(&pipeline);
|
||||
pass.set_bind_group(0, &bind_group, &[]);
|
||||
pass.dispatch_workgroups(SIDE / 8, SIDE / 8, 1);
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&results, 0, &readback, 0, results.size());
|
||||
if let Err(code) = submit_checked(&device, &queue, encoder, &errors, "ray-query frame") {
|
||||
return code;
|
||||
}
|
||||
|
||||
let slice = readback.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
if let Err(e) = device.poll(wgpu::PollType::Wait {
|
||||
submission_index: None,
|
||||
timeout: Some(WAIT),
|
||||
}) {
|
||||
println!("RESULT: FAIL - readback poll: {e}");
|
||||
return 1;
|
||||
}
|
||||
let data = match slice.get_mapped_range() {
|
||||
Ok(view) => view,
|
||||
Err(e) => {
|
||||
println!("RESULT: FAIL - readback map: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let ray = |i: usize| -> [f32; 4] {
|
||||
let b = &data[i * 16..i * 16 + 16];
|
||||
std::array::from_fn(|k| f32::from_le_bytes(b[k * 4..k * 4 + 4].try_into().unwrap()))
|
||||
};
|
||||
|
||||
let mut hits = 0u32;
|
||||
let mut misses = 0u32;
|
||||
let mut wrong = 0u32;
|
||||
let mut max_t_err = 0.0f32;
|
||||
println!("ray-query frame ({SIDE}x{SIDE}, '#'=hit, '.'=miss):");
|
||||
for y in 0..SIDE {
|
||||
let mut row = String::new();
|
||||
for x in 0..SIDE {
|
||||
let i = (y * SIDE + x) as usize;
|
||||
let [kind, t, custom, prim] = ray(i);
|
||||
let uv = [
|
||||
(x as f32 + 0.5) / SIDE as f32 * 2.0 - 1.0,
|
||||
(y as f32 + 0.5) / SIDE as f32 * 2.0 - 1.0,
|
||||
];
|
||||
let expect_hit = inside_triangle(uv);
|
||||
let ok = if expect_hit {
|
||||
hits += 1;
|
||||
max_t_err = max_t_err.max((t - 1.0).abs());
|
||||
kind == 1.0 && (t - 1.0).abs() <= 1e-3 && custom == CUSTOM as f32 && prim == 0.0
|
||||
} else {
|
||||
misses += 1;
|
||||
kind == 0.0
|
||||
};
|
||||
if !ok {
|
||||
wrong += 1;
|
||||
eprintln!(
|
||||
"ray {i} uv={uv:?}: got kind={kind} t={t} custom={custom} prim={prim}, expected hit={expect_hit}"
|
||||
);
|
||||
}
|
||||
row.push(if kind == 1.0 { '#' } else { '.' });
|
||||
}
|
||||
println!("{row}");
|
||||
}
|
||||
println!("hits={hits} misses={misses} wrong={wrong} max_t_err={max_t_err:.6}");
|
||||
if wrong != 0 {
|
||||
println!("RESULT: FAIL - ray results disagree with CPU expectation");
|
||||
return 1;
|
||||
}
|
||||
println!(
|
||||
"RESULT: OK - BLAS/TLAS build and ray query verified on backend={:?} name={:?} ({} hits, {} misses, all match CPU expectation)",
|
||||
info.backend, info.name, hits, misses
|
||||
);
|
||||
0
|
||||
}
|
||||
|
||||
fn submit_checked(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: wgpu::CommandEncoder,
|
||||
errors: &ErrLog,
|
||||
stage: &str,
|
||||
) -> Result<(), i32> {
|
||||
let guard = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let index = queue.submit([encoder.finish()]);
|
||||
let poll = device.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(index),
|
||||
timeout: Some(WAIT),
|
||||
});
|
||||
let scoped = pollster::block_on(guard.pop());
|
||||
let mut problems = errors.drain();
|
||||
problems.extend(scoped.map(|e| format!("{e}")));
|
||||
if !problems.is_empty() {
|
||||
return Err(unsupported(stage, &problems.join("; ")));
|
||||
}
|
||||
if let Err(e) = poll {
|
||||
println!("RESULT: FAIL - {stage} poll: {e}");
|
||||
return Err(1);
|
||||
}
|
||||
println!("stage {stage}: submitted and waited");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inside_triangle(p: [f32; 2]) -> bool {
|
||||
let cross = |o: [f32; 3], u: [f32; 3], v: [f32; 3]| {
|
||||
(u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])
|
||||
};
|
||||
let p3 = [p[0], p[1], 0.0];
|
||||
let d1 = cross(TRI[0], TRI[1], p3);
|
||||
let d2 = cross(TRI[1], TRI[2], p3);
|
||||
let d3 = cross(TRI[2], TRI[0], p3);
|
||||
let has_neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
||||
let has_pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
||||
!(has_neg && has_pos)
|
||||
}
|
||||
|
||||
fn bytemuck_bytes(values: &[f32]) -> &[u8] {
|
||||
unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), std::mem::size_of_val(values)) }
|
||||
}
|
||||
@@ -111,18 +111,6 @@ class ReproducibilityTests(unittest.TestCase):
|
||||
second = gen_tex.camo("nato_green", 1234, 32)
|
||||
self.assertEqual(first.tobytes(), second.tobytes())
|
||||
|
||||
def test_an_icon_alias_reuses_an_existing_texture_without_writing_a_duplicate(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "mod"
|
||||
root.mkdir()
|
||||
gen_models.regenerate(root, root / "source-assets", root / "generated-manifest.txt")
|
||||
model = json.loads((root / "assets/airdef/models/item/deploy_optical.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(model["textures"]["layer0"], "airdef:item/deploy_radar")
|
||||
self.assertTrue((root / "assets/airdef/textures/item/deploy_radar.png").is_file())
|
||||
self.assertFalse((root / "assets/airdef/textures/item/deploy_optical.png").exists())
|
||||
items = {item[0] for item in icons.ITEMS}
|
||||
self.assertLessEqual(set(icons.ICON_ALIAS.values()), items)
|
||||
|
||||
def test_authored_override_is_merged_without_changing_source(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
|
||||
Reference in New Issue
Block a user