Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9370fd4ed4 | |||
| a983177d34 | |||
| 795b1b2fcf | |||
| c4e002ed8b | |||
| 12a706fb67 | |||
| 8550de16f8 | |||
| 245aceb434 | |||
| e5ee15a2ca | |||
| 53fbeced22 | |||
| e1b09f696f | |||
| 858735a4c6 | |||
| ac7521936d | |||
| 95739c95b1 | |||
| d302204649 | |||
| 1e2d5dd0c0 | |||
| 80d0cc9c43 | |||
| c59bfe9e54 | |||
| 306af49744 | |||
| 60f1bf0fd8 | |||
| e194971867 | |||
| 7ae0c5bbba | |||
| 217e3ac886 | |||
| f33b799551 | |||
| d8cb98a964 | |||
| e59c49e3bf | |||
| 9664783b17 | |||
| 3db1b73d64 | |||
| 367c7f4ac3 | |||
| e7934a1ebb | |||
| 8fc10c07a1 | |||
| 0b645d77e9 | |||
| 56093b3a55 | |||
| 1261c30724 | |||
| a592ece6e3 | |||
| a47812aadd | |||
| 6f7b041c8b | |||
| dc36d67eb7 | |||
| d45629ae29 | |||
| 61aaa0bf35 | |||
| 9217f9a5cc | |||
| 46d2274c8d | |||
| 325119b726 | |||
| 0937ac9e05 | |||
| ead87343d2 | |||
| abf3d76fdb | |||
| e6a7000440 | |||
| cec7257ea1 | |||
| 503e6e29af | |||
| 675967ce42 | |||
| 632061d2ad | |||
| 56339b076e | |||
| c1a595b773 | |||
| 914f723d1f | |||
| d45d59df9f | |||
| cfae0c1253 | |||
| 53669887dd | |||
| 4c7c887917 | |||
| daa9ed7cbc | |||
| 1553976484 | |||
| 0c870c10d5 | |||
| eea1b3692e | |||
| cb73cb7ccc | |||
| 375fdf2d80 | |||
| 63aefc7621 | |||
| d410e2c92d | |||
| ab737e7390 | |||
| 3b470ddc8a | |||
| cbd6067e8f | |||
| cc48302b36 | |||
| 1f28f8361f | |||
| 10f24b5df8 | |||
| 293236490b | |||
| bf8551e1a8 | |||
| 3afebae6bd | |||
| 326817db9a | |||
| 8f5603847e | |||
| bd091e60df | |||
| 296a64ffaa | |||
| a41a4d17cf | |||
| 692ae77af7 | |||
| 19c53fda4c |
@@ -35,6 +35,8 @@ jobs:
|
||||
- name: Проверка generated assets
|
||||
run: |
|
||||
python3 -m pip install --user -r tools/requirements.txt
|
||||
python3 tools/gen_catalog.py --check
|
||||
python3 -m unittest discover -s tools -p test_sound_catalog.py
|
||||
python3 tools/gen_models.py --check
|
||||
python3 -m unittest discover -s tools -p test_model_bounds.py
|
||||
- name: Тесты ядра без SDK
|
||||
|
||||
@@ -2,6 +2,7 @@ run-home/
|
||||
.horizon-cache/
|
||||
airdef-mod/target/
|
||||
airdef-core/target/
|
||||
tools/rt-probe/target/
|
||||
__pycache__/
|
||||
/out/
|
||||
.DS_Store
|
||||
|
||||
@@ -30,6 +30,14 @@ python3 tools/airdef.py all # получить закреплённый дв
|
||||
python3 tools/airdef.py play # запустить (аргументы игры — после: --world "Имя мира")
|
||||
```
|
||||
|
||||
`all` синхронизирует URL сабмодуля из `.gitmodules`, включая обновление со старого upstream.
|
||||
Продолжение 4 ноября: [модели, границы ядра, общий каталог, API29 и массовая акустика](docs/CONTINUATION-2026-11-04.md).
|
||||
|
||||
Диагностика в игре: `/airdef capabilities` показывает доступность API, принятие запроса и
|
||||
подготовку дыма, акустики и захвата именно этого мода. Подготовка не означает готовый GPU-кадр или MP4.
|
||||
Для разработчика: `python3 tools/airdef.py test-wasm` — лёгкий ABI-тест;
|
||||
`python3 tools/airdef.py test-budgets` — отдельный тяжёлый сценарий с JSON-отчётом.
|
||||
|
||||
Для разработки: `./install.sh` перегенерирует модели (`tools/gen_models.py`, нужен Pillow) и звуки
|
||||
(`tools/gen_sounds.py`, нужны numpy и ffmpeg), собирает и ставит мод. Сгенерированные файлы лежат в репозитории,
|
||||
так что для обычной сборки нужен только Rust.
|
||||
@@ -82,6 +90,9 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
|
||||
|
||||
**Сохранение.** Комплексы, объекты, их повреждения и настройки сохраняются отдельно для каждого мира (и для каждого
|
||||
сервера); уничтоженный комплекс остаётся остовом и после перезахода, пока его не отремонтируют.
|
||||
Налёт в воздухе тоже сохраняется: дроны, очередь их запуска и незавершённые задания на маршрут
|
||||
восстанавливаются, и перезаход не обрывает перенацеливание. Ракеты-перехватчики в воздухе и площадки
|
||||
запуска не сохраняются; сценарий — стартовое состояние и налёт не несёт.
|
||||
|
||||
**Сеть ПВО.** Единицы обмениваются измеренными треками в пределах игровой связи; повреждение связи
|
||||
сокращает её дальность. Можно поставить несколько С-400/С-500 без собственной РЛС и общие радары
|
||||
@@ -105,8 +116,12 @@ P1-SUN также использует чужие данные. Пушкам (Г
|
||||
с ракетами ПВО. `/airdef ground-stock <склад> <количество>` задаёт конечный начальный запас
|
||||
sandbox-сценария, `/airdef ground-load <С-400>` загружает одну ракету рядом со складом либо
|
||||
создаёт заявку на доставку ТЗМ. Груз едет физически; снятая ракета ПВО возвращается на склад.
|
||||
Заявка и груз сохраняются в пути. `/airdef ground-unload <С-400>` выгружает ракету у склада.
|
||||
Заявка и груз сохраняются в пути. `/airdef ground-unload <С-400>` выгружает ракету у склада,
|
||||
а вдали создаёт заявку на обратный вывоз ТЗМ. Одна ракета резервируется от пуска до забора;
|
||||
`/airdef ground-cancel <С-400>` отменяет ещё ожидающую доставку или вывоз.
|
||||
После забора ракета находится в машине и едет на склад. Отмена заявки не возвращает уже вывезенный груз в ПУ.
|
||||
Без склада этот ударный боеприпас сам не появляется. Бук и остальные комплексы такого профиля пока не имеют.
|
||||
Порядок подготовки, разведка и номера двух списков: [как ударить по ПУ](docs/GROUND-STRIKES.md).
|
||||
|
||||
**Перемещение.** **Пульт перемещения**: навестись на технику (выбрать), затем на точку на земле — она
|
||||
сворачивается (С-400 и другие с вертикальным пуском дольше, Гепард и Панцирь быстро), едет по рельефу и
|
||||
@@ -121,7 +136,9 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
|
||||
**Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий
|
||||
налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта
|
||||
перенацеливает ещё не взлетевшие Ланцеты и Шахеды на них; если цель-комплекс уничтожен, дроны идут к
|
||||
следующему известному. Дроны под обстрелом прижимаются к земле.
|
||||
следующему известному. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
|
||||
необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без
|
||||
маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле.
|
||||
|
||||
**Ночь.** Исправные пушки с собственным свежим радарным сопровождением не теряют точность из-за темноты.
|
||||
Цели освещают **прожекторы** (луч ведёт ближайшую
|
||||
@@ -137,6 +154,10 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
|
||||
тонмаппинг (ванильный диапазон не трогается, сжимается только то, что ярче). Источники передаются движку новым
|
||||
API мода `render.set-lights` (до 512, плавно интерполируются), режим — `render.set-lighting`.
|
||||
|
||||
В HD дымовые следы ракет немного уплотнены; число сегментов и время появления/выгорания сохранены.
|
||||
Это относится к ракетам ПВО, RM48U, крылатым, сверхзвуковым и баллистическим средствам;
|
||||
дым пожаров и слабая дымка винтовых дронов остались прежними.
|
||||
|
||||
**Сетка J** после сбития ещё 3,5 с держит камеру на сбитой цели, и комплекс в это время не пропадает из сетки.
|
||||
|
||||
**Повреждения.** Взрыв рядом с комплексом повреждает его: он хуже поворачивается, хуже видит и попадает,
|
||||
@@ -161,6 +182,20 @@ 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**:
|
||||
- **карта налёта** — вид сверху: комплексы и их зоны, объекты, треки целей (красные), ложных целей (серые) и
|
||||
@@ -179,7 +214,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт
|
||||
(48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт».
|
||||
|
||||
Клавиши N, K, J, R и U можно переназначить в «Настройки → Моды».
|
||||
Клавиши N, K, J, R, U и C (обзор целей, удержание) можно переназначить в «Настройки → Моды».
|
||||
|
||||
Команды:
|
||||
- `/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+ — «Орешник»);
|
||||
@@ -191,8 +226,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
- `/airdef lastchance <on|off>` — «последний шанс»: комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт (по умолчанию вкл; сохраняется);
|
||||
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
|
||||
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
|
||||
- `/airdef ground-stock <номер склада> <количество>` — задать начальный запас RM48U для sandbox-сценария (по умолчанию 0, сам не пополняется). `/airdef ground-load <номер С-400>` — у живого склада в пределах 60 блоков загрузить одну RM48U, сохранив снятую ракету ПВО на складе; `/airdef ground-unload <номер С-400>` — вернуть её и восстановить снятую ракету ПВО, если она осталась. Запас сохраняется с миром. Автоматическая доставка RM48U через ТЗМ пока не реализована. Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
|
||||
- `/airdef 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 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 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 блоках перед собой;
|
||||
@@ -202,10 +237,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
- `/airdef clear` — убрать дроны и ракеты;
|
||||
- `/airdef targets clear` — снять все цели;
|
||||
- `/airdef stats` — сводка.
|
||||
- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится.
|
||||
|
||||
Интерфейс:
|
||||
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт;
|
||||
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели (с хвостом по курсу), жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара.
|
||||
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение);
|
||||
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик».
|
||||
|
||||
**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет
|
||||
невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой
|
||||
только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип,
|
||||
прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит
|
||||
между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик —
|
||||
узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и
|
||||
счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник
|
||||
запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню
|
||||
N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и
|
||||
дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный
|
||||
HUD не выводится. Простые пресеты налёта фазу разведки не получают.
|
||||
|
||||
Комплексы ПВО и цели сохраняются между сессиями.
|
||||
|
||||
@@ -244,7 +292,9 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
|
||||
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
|
||||
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
|
||||
**станция РЭБ** (`ew`), **прожектор** (`light`). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
|
||||
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
|
||||
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
|
||||
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
|
||||
|
||||
**Согласование огня.** Комплексы делят цели между собой: на обычную цель идёт одна ракета, на баллистическую две; чем ближе цель к своей точке попадания,
|
||||
тем больше перехватчиков разрешено на неё сразу (за ~12 с до удара ещё один, за ~5 с — ещё один). Комплекс, у которого кончились ракеты
|
||||
@@ -252,10 +302,13 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
«Герберы» выглядят для них как настоящие. Геометрия встречи проверяется по движению обоих объектов
|
||||
за тик, а остаточный шанс учитывает фактическую скорость перехватчика.
|
||||
|
||||
**Энергетика перехватчика.** После холодного выброса ракета разгоняется, но двигатель работает
|
||||
конечное игровое время. После выгорания ракета летит по инерции, теряет скорость и манёвренность;
|
||||
при недостаточной скорости сопровождение срывается. Факел, звук двигателя и новый дым прекращаются
|
||||
при выгорании и в live, и в повторе; уже созданный дым продолжает рассеиваться.
|
||||
**Энергетика перехватчика.** Сначала ракета выходит из ТПК без двигателя: у С-400 это 1,0 с,
|
||||
у С-500 — 1,2 с; только потом в её текущей точке зажигается факел, и тяга плавно нарастает.
|
||||
После выброса ракета разгоняется, но двигатель работает конечное игровое время. После выгорания
|
||||
ракета летит по инерции, теряет скорость и манёвренность; при недостаточной скорости сопровождение
|
||||
срывается. Факел, звук двигателя и новый дым прекращаются при выгорании и в live, и в повторе;
|
||||
уже созданный дым продолжает рассеиваться. У ракет с горячим (рельсовым) пуском тяга тоже
|
||||
нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю.
|
||||
|
||||
**Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей
|
||||
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 10 с и на ней ещё нет
|
||||
@@ -343,6 +396,9 @@ run-home/ тестовая игровая папка (для пров
|
||||
|
||||
## Известные ограничения
|
||||
|
||||
- Для [#122](https://gitea.maoniao.team/chexit/airdef/issues/122) воспроизведено и исправлено исчерпание fuel при массовых взрывах:
|
||||
каждый взрыв больше не обходит всю карту высот. Проверка на конкретном Windows-компьютере ещё нужна;
|
||||
прирост FPS этим исправлением не обещается.
|
||||
- Мод клиентский: дроны и ПВО видит только тот, у кого он стоит. Мультиплеер не поддерживается.
|
||||
- Окно Horizon на macOS не рисует кадры, пока оно перекрыто другими окнами (это поведение движка).
|
||||
- Шейдер работает, только если не включён шейдер-пак Horizon (они взаимоисключающие).
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
//! The enemy-picture bench (#127) without building the Horizon SDK.
|
||||
extern crate airdef_core as airdef;
|
||||
#[path = "../../airdef-mod/examples/intel_bench.rs"]
|
||||
mod bench;
|
||||
|
||||
fn main() {
|
||||
bench::main();
|
||||
}
|
||||
@@ -35,3 +35,134 @@ fn same_seed_same_result() {
|
||||
let b = harness::run(&harness::logistics());
|
||||
assert_eq!((a.ticks_run, a.launched, a.kills, a.hits, a.fired, a.ground_queries), (b.ticks_run, b.launched, b.kills, b.hits, b.fired, b.ground_queries));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mass_strikes_on_flat_world() {
|
||||
use airdef::sim::{Aim, Approach, DroneKind as D, Ground, Out, RaidOrder, Sam, Sim};
|
||||
use glam::DVec3;
|
||||
let sc = harness::big_smart();
|
||||
let terrain = harness::Terrain::Flat(70);
|
||||
let mut sim = Sim::new(sc.seed);
|
||||
sim.damage = false;
|
||||
for unit in &sc.units {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, unit.kind, DVec3::new(unit.pos.x, 70.0, unit.pos.z), unit.heading));
|
||||
}
|
||||
sim.targets = vec![DVec3::new(0.0, 70.0, 0.0)];
|
||||
sim.target_health = vec![100.0];
|
||||
// Exact composition of the menu's "Массированный удар" preset.
|
||||
let order = RaidOrder { kinds: vec![(D::Gerbera, 8), (D::Shahed, 12), (D::Geran3, 4), (D::Kh101, 4), (D::Kalibr, 4), (D::Kh22, 2), (D::Iskander, 2)], approach: Approach::AllSides, aim: Aim::Smart, dist: 4000.0 };
|
||||
let mut ground = Ground::default();
|
||||
let mut pending = Vec::new();
|
||||
let mut out = Out::default();
|
||||
let targets = sim.targets.clone();
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), 36);
|
||||
let mut second = false;
|
||||
let mut peak = 0;
|
||||
for now in 1..=12000 {
|
||||
if !second && !sim.planning() {
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), 36);
|
||||
second = true;
|
||||
}
|
||||
ground.answer(std::mem::take(&mut pending), now);
|
||||
out = Out::default();
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
let wanted = ground.take_wanted();
|
||||
pending = wanted.into_iter().map(|(x, z)| (x, z, 70)).collect();
|
||||
let sections = ground.world.take_wanted(now);
|
||||
ground.world.serve(&terrain, sections, now);
|
||||
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
|
||||
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
|
||||
if sim.launched >= 72 && peak > 36 { break; }
|
||||
}
|
||||
eprintln!("overlapping mass strikes: launched {}, peak airborne {peak}", sim.launched);
|
||||
assert!(second && sim.launched >= 72, "second raid failed to launch; launched {}", sim.launched);
|
||||
assert!(peak > 36, "raids never overlapped; peak {peak}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_oreshnik_splits_are_recorded() {
|
||||
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sim};
|
||||
use glam::DVec3;
|
||||
let mut sim = Sim::new(1);
|
||||
sim.damage = false;
|
||||
let targets = vec![DVec3::new(0.0, 70.0, 0.0)];
|
||||
sim.targets = targets.clone();
|
||||
sim.target_health = vec![100.0];
|
||||
let order = RaidOrder { kinds: vec![(DroneKind::Oreshnik, 40)], approach: Approach::Sector, aim: Aim::Objects, dist: 2600.0 };
|
||||
let terrain = harness::Terrain::Flat(70);
|
||||
let mut ground = Ground::default();
|
||||
let mut pending = Vec::new();
|
||||
let mut out = Out::default();
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), 40);
|
||||
let mut second = false;
|
||||
let mut peak = 0;
|
||||
let mut peak_subs = 0;
|
||||
for now in 1..=10000 {
|
||||
if !second && !sim.planning() {
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), 40);
|
||||
second = true;
|
||||
}
|
||||
ground.answer(std::mem::take(&mut pending), now);
|
||||
out = Out::default();
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
pending = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 70)).collect();
|
||||
let sections = ground.world.take_wanted(now);
|
||||
ground.world.serve(&terrain, sections, now);
|
||||
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
|
||||
peak_subs = peak_subs.max(sim.drones.iter().filter(|d| d.alive() && d.kind == DroneKind::OreshnikSub).count());
|
||||
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
|
||||
if second && sim.launched >= 80 && !sim.replays.is_empty() { break; }
|
||||
}
|
||||
eprintln!("overlapping oreshnik: launched {}, peak airborne {peak}, peak submunitions {peak_subs}, replays {}", sim.launched, sim.replays.len());
|
||||
assert_eq!(sim.launched, 2880);
|
||||
assert!(peak_subs > 36, "expected many simultaneous submunitions");
|
||||
assert!(!sim.replays.is_empty(), "recording did not finish");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_maximum_menu_raids_with_answered_flat_terrain() {
|
||||
use airdef::sim::{Aim, Approach, Ground, Out, RaidOrder, Sam, Sim, catalog::RAID_KINDS};
|
||||
use glam::DVec3;
|
||||
let sc = harness::big_smart();
|
||||
let terrain = harness::Terrain::Flat(70);
|
||||
let mut sim = Sim::new(sc.seed);
|
||||
for unit in &sc.units {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, unit.kind, DVec3::new(unit.pos.x, 70.0, unit.pos.z), unit.heading));
|
||||
}
|
||||
let targets = vec![DVec3::new(0.0, 70.0, 0.0)];
|
||||
sim.targets = targets.clone();
|
||||
sim.target_health = vec![100.0];
|
||||
// The maximum selectable by the menu: 40 for each raid kind.
|
||||
let order = RaidOrder { kinds: RAID_KINDS.iter().copied().map(|kind| (kind, 40)).collect(), approach: Approach::AllSides, aim: Aim::Smart, dist: 300.0 };
|
||||
let expected = RAID_KINDS.len() as u32 * 40;
|
||||
let mut ground = Ground::default();
|
||||
let mut pending = Vec::new();
|
||||
let mut out = Out::default();
|
||||
assert_eq!(sim.order_raid(&order, &targets, &mut out), expected);
|
||||
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 {
|
||||
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);
|
||||
second = true;
|
||||
}
|
||||
ground.answer(std::mem::take(&mut pending), now);
|
||||
out = Out::default();
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
pending = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 70)).collect();
|
||||
let sections = ground.world.take_wanted(now);
|
||||
ground.world.serve(&terrain, sections, now);
|
||||
peak = peak.max(sim.drones.iter().filter(|d| d.alive()).count());
|
||||
assert!(sim.drones.iter().all(|d| d.pos.is_finite() && d.vel.is_finite()));
|
||||
if second && sim.launched >= expected * 2 && !sim.replays.is_empty() { break; }
|
||||
}
|
||||
eprintln!("max menu raids: requested {}, launched {}, peak {peak}, replays {}", expected * 2, sim.launched, sim.replays.len());
|
||||
assert!(second && overlap && sim.launched >= expected * 2 && peak > 40);
|
||||
assert!(!sim.replays.is_empty(), "raid recording did not finish");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"model": {
|
||||
"type": "minecraft:model",
|
||||
"model": "airdef:item/deploy_optical"
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,7 @@
|
||||
"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,6 +123,7 @@
|
||||
"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": "Свернуть ПВО",
|
||||
|
||||
@@ -741,8 +741,8 @@
|
||||
2.0
|
||||
],
|
||||
"to": [
|
||||
22.0,
|
||||
7.6,
|
||||
13.55,
|
||||
7.5,
|
||||
11.0
|
||||
],
|
||||
"faces": {
|
||||
@@ -750,8 +750,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
0.6999999999999993
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -759,8 +759,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
0.6999999999999993
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -769,7 +769,7 @@
|
||||
0,
|
||||
0,
|
||||
9.0,
|
||||
0.6999999999999993
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -778,7 +778,7 @@
|
||||
0,
|
||||
0,
|
||||
9.0,
|
||||
0.6999999999999993
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -786,7 +786,7 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
3.0500000000000007,
|
||||
9.0
|
||||
],
|
||||
"texture": "#kh101"
|
||||
@@ -795,7 +795,7 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
3.0500000000000007,
|
||||
9.0
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
@@ -804,13 +804,13 @@
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
-6.0,
|
||||
2.4499999999999993,
|
||||
6.9,
|
||||
2.0
|
||||
],
|
||||
"to": [
|
||||
5.5,
|
||||
7.6,
|
||||
7.5,
|
||||
11.0
|
||||
],
|
||||
"faces": {
|
||||
@@ -818,8 +818,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
0.6999999999999993
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -827,8 +827,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
0.6999999999999993
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -837,7 +837,7 @@
|
||||
0,
|
||||
0,
|
||||
9.0,
|
||||
0.6999999999999993
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -846,7 +846,7 @@
|
||||
0,
|
||||
0,
|
||||
9.0,
|
||||
0.6999999999999993
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -854,7 +854,7 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
3.0500000000000007,
|
||||
9.0
|
||||
],
|
||||
"texture": "#kh101"
|
||||
@@ -863,7 +863,7 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
11.5,
|
||||
3.0500000000000007,
|
||||
9.0
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
@@ -872,22 +872,22 @@
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
22.0,
|
||||
13.5,
|
||||
6.9,
|
||||
5.0
|
||||
2.65
|
||||
],
|
||||
"to": [
|
||||
28.5,
|
||||
7.4,
|
||||
11.0
|
||||
16.55,
|
||||
7.5,
|
||||
10.88
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
0.5
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -895,8 +895,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
0.5
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -904,8 +904,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.0,
|
||||
0.5
|
||||
8.23,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -913,8 +913,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.0,
|
||||
0.5
|
||||
8.23,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -922,8 +922,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
6.0
|
||||
3.0500000000000007,
|
||||
8.23
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -931,8 +931,552 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
6.0
|
||||
3.0500000000000007,
|
||||
8.23
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
-0.5500000000000007,
|
||||
6.9,
|
||||
2.65
|
||||
],
|
||||
"to": [
|
||||
2.5,
|
||||
7.5,
|
||||
10.88
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
8.23,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
8.23,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
8.23
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
8.23
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
16.5,
|
||||
6.9,
|
||||
3.3
|
||||
],
|
||||
"to": [
|
||||
19.55,
|
||||
7.5,
|
||||
10.76
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
7.46,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
7.46,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
7.46
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
7.46
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
-3.5500000000000007,
|
||||
6.9,
|
||||
3.3
|
||||
],
|
||||
"to": [
|
||||
-0.5,
|
||||
7.5,
|
||||
10.76
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
7.46,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
7.46,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
7.46
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
7.46
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
19.5,
|
||||
6.9,
|
||||
3.95
|
||||
],
|
||||
"to": [
|
||||
22.55,
|
||||
7.5,
|
||||
10.64
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.69,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.69,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
6.69
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
6.69
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
-6.550000000000001,
|
||||
6.9,
|
||||
3.95
|
||||
],
|
||||
"to": [
|
||||
-3.5,
|
||||
7.5,
|
||||
10.64
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.69,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.69,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
6.69
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
6.69
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
22.5,
|
||||
6.9,
|
||||
4.6
|
||||
],
|
||||
"to": [
|
||||
25.55,
|
||||
7.5,
|
||||
10.52
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.92,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.92,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
5.92
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
5.92
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
-9.55,
|
||||
6.9,
|
||||
4.6
|
||||
],
|
||||
"to": [
|
||||
-6.5,
|
||||
7.5,
|
||||
10.52
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.92,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.92,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
5.92
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0500000000000007,
|
||||
5.92
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [
|
||||
25.5,
|
||||
6.9,
|
||||
5.25
|
||||
],
|
||||
"to": [
|
||||
28.5,
|
||||
7.5,
|
||||
10.4
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"south": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"east": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.15,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"west": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
5.15,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"up": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0,
|
||||
5.15
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
"down": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
3.0,
|
||||
5.15
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
@@ -942,20 +1486,20 @@
|
||||
"from": [
|
||||
-12.5,
|
||||
6.9,
|
||||
5.0
|
||||
5.25
|
||||
],
|
||||
"to": [
|
||||
-6.0,
|
||||
7.4,
|
||||
11.0
|
||||
-9.5,
|
||||
7.5,
|
||||
10.4
|
||||
],
|
||||
"faces": {
|
||||
"north": {
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
0.5
|
||||
3.0,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -963,8 +1507,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
0.5
|
||||
3.0,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -972,8 +1516,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.0,
|
||||
0.5
|
||||
5.15,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -981,8 +1525,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.0,
|
||||
0.5
|
||||
5.15,
|
||||
0.5999999999999996
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -990,8 +1534,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
6.0
|
||||
3.0,
|
||||
5.15
|
||||
],
|
||||
"texture": "#kh101"
|
||||
},
|
||||
@@ -999,8 +1543,8 @@
|
||||
"uv": [
|
||||
0,
|
||||
0,
|
||||
6.5,
|
||||
6.0
|
||||
3.0,
|
||||
5.15
|
||||
],
|
||||
"texture": "#kh101_belly"
|
||||
}
|
||||
@@ -1551,4 +2095,4 @@
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"parent": "minecraft:item/generated",
|
||||
"textures": {
|
||||
"layer0": "airdef:item/deploy_radar"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"template": "minecraft:stick",
|
||||
"max_stack_size": 1
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Enemy-picture outcomes on fixed seeds (#127): what changed for the raids, measured.
|
||||
//!
|
||||
//! Runs the standard scenarios over a fixed seed set and prints one JSON object with the
|
||||
//! completion, losses and failure reasons of every run — the before/after comparison of the
|
||||
//! honest EnemyPicture is judged on these, not on "it got smarter".
|
||||
//!
|
||||
//! cargo run --release --example intel_bench
|
||||
#[path = "sim_run/harness.rs"]
|
||||
mod harness;
|
||||
|
||||
use harness::{big_smart, ew_adaptive, logistics, Scenario};
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.chars().flat_map(|c| match c {
|
||||
'"' => "\\\"".chars().collect::<Vec<_>>(),
|
||||
'\\' => "\\\\".chars().collect::<Vec<_>>(),
|
||||
c => vec![c],
|
||||
}).collect()
|
||||
}
|
||||
|
||||
fn run(sc: &Scenario) -> String {
|
||||
let r = harness::run(sc);
|
||||
format!(
|
||||
"{{\"scenario\":\"{}\",\"seed\":{},\"ticks_run\":{},\"raids_ordered\":{},\"raids_ended\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"crashes\":{},\"sams_lost\":{},\"fired\":{},\"retargets_max\":{},\"air_bytes\":{},\"switches_max\":{},\"intents\":\"{}\",\"failures\":\"{}\"}}",
|
||||
esc(&r.name),
|
||||
r.seed,
|
||||
r.ticks_run,
|
||||
r.raids_ordered,
|
||||
r.raids_ended,
|
||||
r.all_ended,
|
||||
r.launched,
|
||||
r.kills,
|
||||
r.hits,
|
||||
r.crashes,
|
||||
r.sams_lost,
|
||||
r.fired,
|
||||
r.retargets_max,
|
||||
r.air_bytes,
|
||||
r.switches_max,
|
||||
esc(&r.intents),
|
||||
esc(&r.failures),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
let scenarios: Vec<fn() -> Scenario> = vec![big_smart, logistics, ew_adaptive];
|
||||
let seeds = [1u64, 7, 42];
|
||||
let mut rows = Vec::new();
|
||||
for make in &scenarios {
|
||||
for &seed in &seeds {
|
||||
let mut sc = make();
|
||||
sc.seed = seed;
|
||||
rows.push(run(&sc));
|
||||
}
|
||||
}
|
||||
println!("[{}]", rows.join(",\n"));
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
//! Native timings say nothing about the WASM build or the GPU; use them to compare runs of the
|
||||
//! same machine.
|
||||
#![allow(dead_code)]
|
||||
#[path = "../../src/world_view.rs"]
|
||||
mod world_view;
|
||||
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sam, SamKind, Sim};
|
||||
use glam::DVec3;
|
||||
use std::collections::HashMap;
|
||||
@@ -126,6 +128,25 @@ pub struct Report {
|
||||
pub raids_ordered: usize,
|
||||
pub raids_ended: usize,
|
||||
pub all_ended: bool,
|
||||
/// Systems the defence lost (destroyed units at the end).
|
||||
pub sams_lost: u32,
|
||||
/// The most retarget route jobs waiting at once (#127).
|
||||
pub retargets_max: usize,
|
||||
/// The largest air section a save would have taken, in bytes (#127).
|
||||
pub air_bytes: usize,
|
||||
/// The aims every drone ended with, by intent: "plan:1,sead:2,react:3,replace:0".
|
||||
pub intents: String,
|
||||
/// The most aim switches one drone went through.
|
||||
pub switches_max: u16,
|
||||
}
|
||||
|
||||
/// The last intent every smart drone of the run was seen carrying, as `name:count`.
|
||||
fn intent_counts(seen: &HashMap<u32, &'static str>) -> String {
|
||||
let mut counts = std::collections::BTreeMap::new();
|
||||
for name in seen.values() {
|
||||
*counts.entry(*name).or_insert(0usize) += 1;
|
||||
}
|
||||
["plan", "sead", "react", "replace"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
fn finite(v: DVec3) -> bool {
|
||||
@@ -160,6 +181,8 @@ pub fn run(sc: &Scenario) -> Report {
|
||||
let mut ended = vec![false; sc.raids.len()];
|
||||
// truck id -> (last position, ticks standing while busy)
|
||||
let mut standing: HashMap<u32, (DVec3, u64)> = HashMap::new();
|
||||
// drone id -> the last structured intent it carried (#127).
|
||||
let mut intents_seen: HashMap<u32, &'static str> = HashMap::new();
|
||||
let mut out = Out::default();
|
||||
for now in 1..=sc.ticks {
|
||||
// Raids come in order: one is ordered once the previous one has been sent.
|
||||
@@ -192,6 +215,18 @@ pub fn run(sc: &Scenario) -> Report {
|
||||
pending = wanted.into_iter().map(|(x, z)| (x, z, sc.terrain.height(x, z))).collect();
|
||||
}
|
||||
r.ticks_run = now;
|
||||
r.retargets_max = r.retargets_max.max(sim.retargets_len());
|
||||
r.switches_max = sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)).map(|d| d.aim_switches()).max().unwrap_or(0).max(r.switches_max);
|
||||
for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) {
|
||||
if d.alive() && d.smart() {
|
||||
intents_seen.insert(d.id, d.intent().name());
|
||||
}
|
||||
}
|
||||
// The air section a save would take, sampled when the sky is fullest (writing it every tick
|
||||
// would distort the timings the bench measures).
|
||||
if sim.drones.len() > r.air_bytes {
|
||||
r.air_bytes = sim.air_text().map_or(0, |t| t.len());
|
||||
}
|
||||
// NaN check on everything with a position.
|
||||
let bad = sim.drones.iter().filter(|d| !finite(d.pos) || !finite(d.vel)).count()
|
||||
+ sim.missiles.iter().filter(|m| !finite(m.pos)).count()
|
||||
@@ -225,15 +260,17 @@ pub fn run(sc: &Scenario) -> Report {
|
||||
}
|
||||
}
|
||||
r.launched = sim.launched;
|
||||
r.sams_lost = sim.sams.iter().filter(|s| !s.alive()).count() as u32;
|
||||
r.kills = sim.kills;
|
||||
r.hits = sim.hits;
|
||||
r.fired = sim.sams.iter().map(|s| s.fired).sum();
|
||||
r.raids_ordered = ordered.iter().filter(|o| **o).count();
|
||||
r.world = ground.world.text();
|
||||
r.world = world_view::text(&ground.world);
|
||||
r.crashes = sim.crashes;
|
||||
r.failures = sim.tally.text();
|
||||
r.raids_ended = ended.iter().filter(|o| **o).count();
|
||||
r.all_ended = r.raids_ended == sc.raids.len();
|
||||
r.intents = intent_counts(&intents_seen);
|
||||
r.tick_total = times.iter().sum();
|
||||
times.sort();
|
||||
if !times.is_empty() {
|
||||
|
||||
@@ -114,6 +114,7 @@ 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
|
||||
@@ -136,8 +137,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
|
||||
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
|
||||
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
|
||||
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
|
||||
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/en_us.json
|
||||
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/ru_ru.json
|
||||
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/en_us.json
|
||||
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 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
|
||||
@@ -173,10 +174,10 @@ e6cb3f578b875d3683d2a027f1ac34226b56c4db410fecc6479e2683485b8c3e assets/airdef/
|
||||
449284669a58d71ae2de7e68cd7cf18ae21fec70ceb3124cd24fb4a09fc49909 assets/airdef/models/block/irist_tubes_burnt.json
|
||||
be87037b84cd45b2c53d7fde6653f51769e782eea1b8586383afcfababf19ab6 assets/airdef/models/block/iskander.json
|
||||
98d488ca797fb3d0193957b8a93a82f48376a89f8e091032e6365d1845016a90 assets/airdef/models/block/kalibr.json
|
||||
be9eb1389e169a76732f16e604499260b147b524b4c929d2a4e77b580a032fb7 assets/airdef/models/block/kh101.json
|
||||
20deb68dbba6eb64b7c51685497110ef7d1d3bf0aa7e7167c558e0a8e842e759 assets/airdef/models/block/kh101.json
|
||||
ea7c9af888f1285502b2ca51114f226573311be6fb90b8d449b9f75cfbb6b885 assets/airdef/models/block/kh22.json
|
||||
7b73015e33d85d4cef31660ef874ba8dcd6e07ae3a95416d0ead1d325bd0cb6c assets/airdef/models/block/kinzhal.json
|
||||
911e55de28058e1723a61d15de80676789e57ab15bfc09fd75757cc85095fbcb assets/airdef/models/block/lancet.json
|
||||
69135e90a1a7fb21d9f47b1854c5a3648e296136c2375acd9db5a48b0ad40887 assets/airdef/models/block/lancet.json
|
||||
15c9884ce51311cf4b9b9d106e142e33d72c5ba18dc9236c5b51da01232f8e44 assets/airdef/models/block/launch_ramp.json
|
||||
159fa5e3b6a096a1872dec2a550bfa30575d57519654a860607e20dab8f35f53 assets/airdef/models/block/launcher_truck.json
|
||||
2069198ba24a932816f504fb52f53dc4bc740cacaf45637698a17d9175da851c assets/airdef/models/block/m48n6.json
|
||||
@@ -254,6 +255,7 @@ 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
|
||||
@@ -567,6 +569,7 @@ 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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,213 @@
|
||||
//! Player-facing labels for battery configuration and status.
|
||||
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
|
||||
use crate::sim::{Sam, SamKind};
|
||||
|
||||
/// 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 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::Launcher { index, kind, mode, linked } => format!(
|
||||
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
|
||||
if mode == SamMode::LauncherOnly {
|
||||
if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" }
|
||||
} else { "" }
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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("уточнение"));
|
||||
}
|
||||
|
||||
#[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::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");
|
||||
}
|
||||
}
|
||||
@@ -59,10 +59,42 @@ fn line(
|
||||
format!("{name}: API={available}, включено={enabled}, запрос={accepted}, подготовлено={prepared}, поколение={generation}, {why}")
|
||||
}
|
||||
|
||||
fn camera_line(s: &render::CameraState) -> String {
|
||||
let cameras: Vec<String> = s
|
||||
.cameras
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let why = match c.reason {
|
||||
render::CameraReason::AwaitingFrame => "awaiting-frame",
|
||||
render::CameraReason::Ready => "ready",
|
||||
};
|
||||
format!("{}:{}", c.id, why)
|
||||
})
|
||||
.collect();
|
||||
let main = match s.main_view {
|
||||
Some(id) => id.to_string(),
|
||||
None => "нет".into(),
|
||||
};
|
||||
format!(
|
||||
"Камеры: API={}, включено={}, запрос={}, подготовлено={}, поколение={}, {}, main={}, [{}]",
|
||||
s.available,
|
||||
s.enabled,
|
||||
s.request_accepted,
|
||||
s.prepared,
|
||||
s.generation,
|
||||
reason(s.reason),
|
||||
main,
|
||||
cameras.join("; ")
|
||||
)
|
||||
}
|
||||
|
||||
pub fn diagnostics() -> String {
|
||||
let smoke = render::smoke_status();
|
||||
let acoustic = acoustics();
|
||||
let capture = render::capture_owner_status();
|
||||
let lights = render::point_lights_status();
|
||||
let sources = render::sound_sources_status();
|
||||
let cameras = render::camera_status();
|
||||
let smoke_reason = match smoke.reason {
|
||||
render::SmokeReason::AwaitingFrame => "awaiting-frame",
|
||||
render::SmokeReason::Disabled => "disabled",
|
||||
@@ -70,7 +102,7 @@ pub fn diagnostics() -> String {
|
||||
render::SmokeReason::Ready => "ready",
|
||||
};
|
||||
[
|
||||
"Возможности движка (API 27; подготовка не означает готовый GPU-кадр или файл):".into(),
|
||||
"Возможности движка (API 31; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
|
||||
line(
|
||||
"Дым",
|
||||
smoke.generation,
|
||||
@@ -89,6 +121,25 @@ pub fn diagnostics() -> String {
|
||||
acoustic.prepared,
|
||||
reason(acoustic.reason),
|
||||
),
|
||||
line(
|
||||
"Точечный свет",
|
||||
lights.generation,
|
||||
lights.available,
|
||||
lights.enabled,
|
||||
lights.request_accepted,
|
||||
lights.prepared,
|
||||
reason(lights.reason),
|
||||
),
|
||||
line(
|
||||
"Постоянные звуки",
|
||||
sources.generation,
|
||||
sources.available,
|
||||
sources.enabled,
|
||||
sources.request_accepted,
|
||||
sources.prepared,
|
||||
reason(sources.reason),
|
||||
),
|
||||
camera_line(&cameras),
|
||||
line(
|
||||
"Захват этого мода",
|
||||
capture.generation,
|
||||
@@ -144,4 +195,46 @@ mod tests {
|
||||
s.reason = CapabilityReason::Failed;
|
||||
assert!(capture_problem(&s).is_some());
|
||||
}
|
||||
fn camera(id: u32, prepared: bool) -> render::CameraReadiness {
|
||||
render::CameraReadiness {
|
||||
id,
|
||||
request_accepted: true,
|
||||
prepared,
|
||||
reason: if prepared {
|
||||
render::CameraReason::Ready
|
||||
} else {
|
||||
render::CameraReason::AwaitingFrame
|
||||
},
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn the_camera_line_separates_readiness_from_the_screens_selection() {
|
||||
let line = camera_line(&render::CameraState {
|
||||
generation: 5,
|
||||
available: true,
|
||||
enabled: true,
|
||||
request_accepted: true,
|
||||
prepared: true,
|
||||
reason: CapabilityReason::Ready,
|
||||
cameras: vec![camera(7, true), camera(8, false)],
|
||||
main_view: Some(7),
|
||||
});
|
||||
assert_eq!(
|
||||
line,
|
||||
"Камеры: API=true, включено=true, запрос=true, подготовлено=true, поколение=5, \
|
||||
ready, main=7, [7:ready; 8:awaiting-frame]"
|
||||
);
|
||||
// No accepted submission: no cameras, no main view, and the reason says so.
|
||||
let line = camera_line(&render::CameraState {
|
||||
generation: 5,
|
||||
available: true,
|
||||
enabled: false,
|
||||
request_accepted: false,
|
||||
prepared: false,
|
||||
reason: CapabilityReason::NotRequested,
|
||||
cameras: Vec::new(),
|
||||
main_view: None,
|
||||
});
|
||||
assert!(line.ends_with("not-requested, main=нет, []"), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-12
@@ -2,15 +2,17 @@
|
||||
//! tail; from afar the muffled report and a late boom), and the camera's reaction (a brief
|
||||
//! exposure and bloom punch). Everything is a function of the blast, its distance and its age, so
|
||||
//! a replay hears and sees the same as the live raid did, from the replay's camera.
|
||||
use crate::sim::catalog::sound;
|
||||
|
||||
|
||||
/// The power (0 air burst .. 4 ballistic) of a blast sound event, if it is one.
|
||||
pub fn blast_power(event: &str) -> Option<usize> {
|
||||
Some(match event {
|
||||
"airdef:blast.air" => 0,
|
||||
"airdef:blast.medium" => 1,
|
||||
"airdef:blast.big" => 2,
|
||||
"airdef:blast.heavy" => 3,
|
||||
"airdef:blast.huge" => 4,
|
||||
sound::BLAST_AIR => 0,
|
||||
sound::BLAST_MEDIUM => 1,
|
||||
sound::BLAST_BIG => 2,
|
||||
sound::BLAST_HEAVY => 3,
|
||||
sound::BLAST_HUGE => 4,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -34,7 +36,7 @@ pub const FULL: usize = 3;
|
||||
/// nearest of its tick.
|
||||
pub fn layers(power: usize, dist: f64, far: f64, gain: f32, pitch: f32, rank: usize) -> Vec<Layer> {
|
||||
let g = gain.clamp(0.3, 2.0);
|
||||
let own = ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][power.min(4)];
|
||||
let own = [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][power.min(4)];
|
||||
let layer = |name: &str, volume: f32, pitch: f32, delay: u64| Layer { name: name.to_string(), volume, pitch, delay };
|
||||
let far_away = dist > far;
|
||||
let suffix = if far_away { "_far" } else { "" };
|
||||
@@ -45,22 +47,22 @@ pub fn layers(power: usize, dist: f64, far: f64, gain: f32, pitch: f32, rank: us
|
||||
// The muffled report, then a deep boom that arrives late.
|
||||
return vec![
|
||||
layer(&format!("{own}_far"), g, pitch, 0),
|
||||
layer("airdef:blast.big_far", 0.7 * g, pitch * 0.6, 10 + 2 * power as u64),
|
||||
layer(sound::BLAST_BIG_FAR, 0.7 * g, pitch * 0.6, 10 + 2 * power as u64),
|
||||
];
|
||||
}
|
||||
let tail = (0.45 + 0.08 * power as f32) * g;
|
||||
if power == 0 {
|
||||
// An air burst has no body of its own: the crack, the thump, the roll.
|
||||
vec![
|
||||
layer("airdef:blast.air", g, pitch * 1.12, 0),
|
||||
layer("airdef:blast.big", 0.85 * g, pitch * 0.66, 2),
|
||||
layer("airdef:blast.huge", tail, pitch * 0.5, 7),
|
||||
layer(sound::BLAST_AIR, g, pitch * 1.12, 0),
|
||||
layer(sound::BLAST_BIG, 0.85 * g, pitch * 0.66, 2),
|
||||
layer(sound::BLAST_HUGE, tail, pitch * 0.5, 7),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
layer(own, g, pitch, 0),
|
||||
layer("airdef:blast.air", 0.7 * g, pitch * 1.15, 0),
|
||||
layer("airdef:blast.huge", tail, pitch * 0.5, 7),
|
||||
layer(sound::BLAST_AIR, 0.7 * g, pitch * 1.15, 0),
|
||||
layer(sound::BLAST_HUGE, tail, pitch * 0.5, 7),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]).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 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::choice(["on", "off", "multi", "search", "engagement", "height"])).runs())),
|
||||
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).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,6 +106,7 @@ 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(),
|
||||
])
|
||||
}
|
||||
@@ -162,7 +163,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", "roles",
|
||||
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "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",
|
||||
@@ -241,10 +242,10 @@ mod tests {
|
||||
fn completion_offers_the_next_word_only() {
|
||||
let top = complete("", &[]);
|
||||
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] {
|
||||
"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"] {
|
||||
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||
}
|
||||
assert_eq!(top.len(), 35);
|
||||
assert_eq!(top.len(), 36);
|
||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
||||
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
||||
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
||||
@@ -258,6 +259,18 @@ 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() {
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
//! for a tick or two (a step the simulation skipped) does not stop the sound; a *cut* (a replay
|
||||
//! seek, a new shot) stops every engine and starts them again under new ids, so nothing glides
|
||||
//! across the jump.
|
||||
use crate::sim::catalog::sound;
|
||||
|
||||
use glam::DVec3;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -52,12 +54,12 @@ pub enum Op {
|
||||
/// engine_sounds_has_no_hole` finds them (after the fade-in, before the sound begins to die).
|
||||
pub fn steady_part(event: &str) -> (f32, f32) {
|
||||
match event {
|
||||
"airdef:drone.shahed" => (0.2, 2.2),
|
||||
"airdef:drone.geran3" => (0.2, 2.0),
|
||||
"airdef:drone.lancet" => (0.2, 1.4),
|
||||
"airdef:drone.cruise" => (0.2, 2.6),
|
||||
"airdef:drone.rocket" => (0.2, 2.6),
|
||||
"airdef:missile.flight" => (0.2, 2.2),
|
||||
sound::DRONE_SHAHED => (0.2, 2.2),
|
||||
sound::DRONE_GERAN3 => (0.2, 2.0),
|
||||
sound::DRONE_LANCET => (0.2, 1.4),
|
||||
sound::DRONE_CRUISE => (0.2, 2.6),
|
||||
sound::DRONE_ROCKET => (0.2, 2.6),
|
||||
sound::MISSILE_FLIGHT => (0.2, 2.2),
|
||||
_ => (0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ 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,
|
||||
}
|
||||
@@ -147,10 +150,20 @@ 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"));
|
||||
}
|
||||
@@ -160,7 +173,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, 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, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo });
|
||||
}
|
||||
"target" => {
|
||||
if out.targets.len() >= MAX_UNITS {
|
||||
@@ -220,6 +233,7 @@ 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());
|
||||
@@ -230,6 +244,13 @@ 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() {
|
||||
@@ -258,6 +279,27 @@ 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() {
|
||||
|
||||
+323
-41
@@ -12,6 +12,7 @@ use horizon_mod_sdk::{
|
||||
ui::{self, ButtonWidget, ItemWidget, ListWidget, Screen, Widget},
|
||||
};
|
||||
|
||||
mod battery_view;
|
||||
mod cinema;
|
||||
mod capabilities;
|
||||
mod engines;
|
||||
@@ -20,15 +21,19 @@ 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;
|
||||
pub use airdef_core::sim;
|
||||
mod scenario;
|
||||
mod wave;
|
||||
mod world_view;
|
||||
mod why_view;
|
||||
use sim::{Class, DroneKind, Ground, Out, Sam, SamKind, Sim};
|
||||
|
||||
const ITEMS: [&str; sim::catalog::INVENTORY_COUNT] = sim::catalog::INVENTORY;
|
||||
@@ -93,6 +98,10 @@ 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.
|
||||
@@ -197,33 +206,27 @@ 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_DEPLOY: [(&str, &str); 5] = [
|
||||
("s400_launcher", "С-400 — отдельная пусковая"),
|
||||
("s500_launcher", "С-500 — отдельная пусковая"),
|
||||
("radar_search", "РЛС обзора"),
|
||||
("radar_track", "РЛС сопровождения"),
|
||||
("radar_height", "Мачтовая РЛС"),
|
||||
];
|
||||
const BATTERY_ROWS: u32 = sim::catalog::VARIANTS.len() as u32;
|
||||
|
||||
/// 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};
|
||||
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),
|
||||
})
|
||||
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)),
|
||||
}
|
||||
}
|
||||
|
||||
const BTN_HOLD: u32 = 10;
|
||||
const BTN_SHADER: u32 = 11;
|
||||
const BTN_DAMAGE: u32 = 12;
|
||||
@@ -240,7 +243,9 @@ 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;
|
||||
@@ -876,14 +881,37 @@ impl AirDef {
|
||||
}
|
||||
self.hud_shown = true;
|
||||
hud::set_panel(Corner::TopRight, &panel::summary(&self.sim, &pic, player));
|
||||
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::SIZE + 12.0, &radar::draw(&self.sim, player, yaw));
|
||||
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);
|
||||
}
|
||||
|
||||
// ------------------------------------------------ saving
|
||||
|
||||
/// The state as text, lines of words: the autosave's format, and the body of a scenario.
|
||||
/// `fresh`: every system and object whole, magazines full (a scenario to replay from the start).
|
||||
/// The air state (the raid's drones, launch queue, retarget jobs and the picture behind them,
|
||||
/// #127) belongs to the autosave only: a scenario is a start state, not a raid frozen mid-flight.
|
||||
fn state_text(&self, fresh: bool, view: bool) -> String {
|
||||
self.state_text_with(fresh, view, !fresh)
|
||||
}
|
||||
|
||||
fn state_text_with(&self, fresh: bool, view: bool, air: bool) -> String {
|
||||
let mut text = String::new();
|
||||
for s in &self.sim.sams {
|
||||
// Then its ammunition (missiles, bursts, out and waiting for a truck, reload ticks
|
||||
@@ -898,8 +926,9 @@ 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} {} {} {} {} {} {} {} {} {} {}\n",
|
||||
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}{profile}\n",
|
||||
s.kind.key(),
|
||||
s.pos.x,
|
||||
s.pos.y,
|
||||
@@ -936,11 +965,27 @@ impl AirDef {
|
||||
for (i, s) in self.sim.sams.iter().enumerate().filter(|(_, s)| !s.doctrine.is_default()) {
|
||||
text += &format!("doctrine {i} {}\n", s.doctrine.save_text());
|
||||
}
|
||||
// The enemy's air state, last: it names its own format version, so an older build (or an
|
||||
// older save) reads the layout and ignores it (#127).
|
||||
if air && let Some(a) = self.sim.air_text() {
|
||||
text += &a;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn save(&mut self) {
|
||||
let text = self.state_text(false, true);
|
||||
self.save_with(true);
|
||||
}
|
||||
|
||||
/// Writes the state. `air`: include the enemy's air state (#127). A raid still being *planned* has
|
||||
/// no durable form — its items, sites and routes are half made — so a periodic save waits for it
|
||||
/// to be launched (at most `sites::SEARCH_TICKS`), while a world change takes the layout alone.
|
||||
fn save_with(&mut self, air: bool) {
|
||||
if air && self.sim.planning() {
|
||||
self.next_save = self.sim.tick + 20;
|
||||
return;
|
||||
}
|
||||
let text = if air { self.state_text(false, true) } else { self.state_text_with(false, true, false) };
|
||||
// Clean only once written: a failed write is tried again after a pause.
|
||||
match storage::set(&self.state_key(), text.as_bytes()) {
|
||||
Ok(()) => {
|
||||
@@ -990,7 +1035,15 @@ impl AirDef {
|
||||
/// naming the line and field, and the scene stays as it was (#86).
|
||||
fn apply_state(&mut self, text: &str) -> Result<(), String> {
|
||||
let layout = layout::Layout::parse(text)?;
|
||||
// The air section is checked before anything is touched, like the layout (#127).
|
||||
let air = sim::Sim::parse_air(text)?;
|
||||
self.commit_layout(layout);
|
||||
if let Some(air) = air {
|
||||
let cancelled = self.sim.restore_air(air);
|
||||
if cancelled > 0 {
|
||||
say(&format!("Воздушная обстановка восстановлена: отменено устаревших заданий {cancelled}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1028,7 +1081,9 @@ impl AirDef {
|
||||
sam.air_48n6_stock = r.air_48n6_stock;
|
||||
sam.fit_cells();
|
||||
sam.set_mode(r.mode);
|
||||
sam.set_radar_role(r.radar_role);
|
||||
// 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.radar_on = r.radar_on;
|
||||
sam.spent_cells = r.spent_cells;
|
||||
sam.sync_tube_cells();
|
||||
@@ -1131,6 +1186,10 @@ fn durable_mark(sim: &Sim) -> u64 {
|
||||
.fold(sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(strikes)
|
||||
// The air state's shape (#127): a launch, a loss, a new or finished route job makes the
|
||||
// autosave take the raid as it stands, so a reload resumes it rather than an empty sky.
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(sim.air_mark())
|
||||
}
|
||||
|
||||
impl AirDef {
|
||||
@@ -1155,7 +1214,9 @@ impl AirDef {
|
||||
/// Another world opened: the last one's state saved, a clean simulation with this one's loaded.
|
||||
fn open_world(&mut self, world: Option<String>) {
|
||||
if self.world.is_some() && self.dirty {
|
||||
self.save();
|
||||
// Leaving the world: the layout is kept, a raid still being planned is not (it would have
|
||||
// no drones to resume and the world it belonged to is going).
|
||||
self.save_with(false);
|
||||
}
|
||||
self.end_session(presentation::ExitCause::WorldChange);
|
||||
let shader = self.sim.shader;
|
||||
@@ -1168,6 +1229,9 @@ 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.
|
||||
@@ -1464,13 +1528,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, and the radars; depots, trucks and lights have nothing to show.
|
||||
// Units that shoot, the radars and the passive optics; 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)
|
||||
.filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar || s.kind == SamKind::Optical)
|
||||
.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,
|
||||
@@ -1484,7 +1548,11 @@ impl AirDef {
|
||||
sim::SamState::Waiting => 35.0,
|
||||
sim::SamState::Packing | sim::SamState::Moving | sim::SamState::Deploying => 40.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 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 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 };
|
||||
@@ -1520,7 +1588,8 @@ impl AirDef {
|
||||
self.sim.sams.push(sam);
|
||||
self.sim.settle(id);
|
||||
self.dirty = true;
|
||||
Ok(format!("{} развёрнут ({}, {})", kind.name(), mode.key(), role.key()))
|
||||
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
|
||||
Ok(format!("{} развёрнут ({}, {}{profile})", kind.name(), mode.key(), role.key()))
|
||||
}
|
||||
|
||||
fn open_menu(&mut self, page: Page) {
|
||||
@@ -1547,11 +1616,16 @@ 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: BATTERY_DEPLOY.iter().map(|(_, name)| (*name).to_string()).collect(), selected: None }));
|
||||
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::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
||||
}
|
||||
Page::Replays => {
|
||||
@@ -1564,6 +1638,7 @@ 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();
|
||||
@@ -1572,10 +1647,17 @@ 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 {
|
||||
@@ -1814,8 +1896,12 @@ 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");
|
||||
@@ -1836,7 +1922,7 @@ impl Mod for AirDef {
|
||||
me.apply_far();
|
||||
// Subcommands, typed arguments and the saved scenarios' names for the chat box (#98).
|
||||
commands::register(&scenario::saved_names());
|
||||
Ok((me, Registration::new().command("airdef").on_tick()))
|
||||
Ok((me, Registration::new().command("airdef").on_tick().on_frame()))
|
||||
}
|
||||
|
||||
fn tick(&mut self, tick: u64) {
|
||||
@@ -1852,6 +1938,9 @@ 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() {
|
||||
@@ -2048,6 +2137,15 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2077,8 +2175,8 @@ impl Mod for AirDef {
|
||||
return;
|
||||
}
|
||||
(Page::BatteryDeploy, BATTERY_ROWS) => {
|
||||
if let Some((key, _)) = BATTERY_DEPLOY.get(row as usize) {
|
||||
match self.deploy_configured(key) {
|
||||
if let Some(v) = sim::catalog::VARIANTS.get(row as usize) {
|
||||
match self.deploy_configured(v.id) {
|
||||
Ok(message) => say(&message),
|
||||
Err(error) => say(&error),
|
||||
}
|
||||
@@ -2223,6 +2321,16 @@ 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;
|
||||
@@ -2277,6 +2385,23 @@ impl Mod for AirDef {
|
||||
self.menu = None;
|
||||
}
|
||||
|
||||
/// A frame runs outside a world too (the title screen), where no tick does: a film or an
|
||||
/// 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()) {
|
||||
cleanup.apply(self);
|
||||
}
|
||||
}
|
||||
|
||||
fn command(&mut self, _name: &str, args: &str) -> Result<Option<String>, String> {
|
||||
let w: Vec<&str> = args.split_whitespace().collect();
|
||||
let mut out = Out::default();
|
||||
@@ -2301,8 +2426,8 @@ impl Mod for AirDef {
|
||||
["deploy", kind] => Some(self.deploy_configured(kind)?),
|
||||
["battery"] => {
|
||||
let status = self.sim.battery_status();
|
||||
for line in &status { say(line); }
|
||||
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off|multi|search|engagement|height".into())
|
||||
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())
|
||||
}
|
||||
["battery", n, mode] => {
|
||||
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер комплекса")?;
|
||||
@@ -2320,13 +2445,12 @@ impl Mod for AirDef {
|
||||
self.dirty = true;
|
||||
Some(format!("№{} {}: излучение РЛС {}", i + 1, sam.kind.name(), state))
|
||||
}
|
||||
["radar", n, role] => {
|
||||
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер РЛС")?;
|
||||
["radar", _n, role] => {
|
||||
let role = sim::battery::RadarRole::from_key(role).ok_or("Роль: multi, search, engagement или height")?;
|
||||
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()))
|
||||
return Err(format!(
|
||||
"Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в {} не меняет оборудование. Доступно on/off.",
|
||||
role.key()
|
||||
));
|
||||
}
|
||||
["wave", kind, rest @ ..] => {
|
||||
let count = rest.first().and_then(|v| v.parse().ok()).unwrap_or(5u32).clamp(1, 80);
|
||||
@@ -2369,7 +2493,7 @@ impl Mod for AirDef {
|
||||
return Err("Нет такой техники".into());
|
||||
}
|
||||
for c in self.sim.why(i) {
|
||||
say(&format!("{} {}", if c.ok { "+" } else { "-" }, c.text));
|
||||
say(&format!("{} {}", if c.ok { "+" } else { "-" }, why_view::reason(&c.reason)));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -2377,6 +2501,12 @@ impl Mod for AirDef {
|
||||
self.launch_wave(&mut out)?;
|
||||
None
|
||||
}
|
||||
["preset", n] => {
|
||||
// The wave screen's preset button for scripts: the same apply() the UI cycles.
|
||||
let n = n.parse::<usize>().map_err(|_| "Номер готового состава: число".to_string())?;
|
||||
self.wave.apply(n);
|
||||
Some(format!("Готовый: {}", wave::PRESETS[self.wave.preset].name))
|
||||
}
|
||||
["sites"] => {
|
||||
// The launch sites the radars have found, and the strike missiles (#101).
|
||||
let p = player().ok_or("Нет игрока")?;
|
||||
@@ -2532,6 +2662,14 @@ 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(),
|
||||
@@ -2545,7 +2683,7 @@ impl Mod for AirDef {
|
||||
self.sim.strikes.stunned,
|
||||
self.sim.strikes.missed,
|
||||
self.sim.strikes.shot_down,
|
||||
self.ground.world.text()
|
||||
world_view::text(&self.ground.world)
|
||||
)),
|
||||
_ => return Err(help()),
|
||||
};
|
||||
@@ -2565,8 +2703,9 @@ 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 (key, _) in BATTERY_DEPLOY {
|
||||
assert!(deploy_configuration(key).is_some());
|
||||
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 kind in SamKind::ALL {
|
||||
let (actual, mode, role) = deploy_configuration(kind.key()).unwrap();
|
||||
@@ -2578,6 +2717,25 @@ 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),
|
||||
@@ -2612,6 +2770,8 @@ mod tests {
|
||||
model_generation: u32::MAX,
|
||||
by_id: Vec::new(),
|
||||
map: map::MapUi::default(),
|
||||
overlay_held: false,
|
||||
overlay_shown: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2722,6 +2882,75 @@ mod tests {
|
||||
assert_eq!((after.sim.sams[0].air_48n6_stock, after.sim.sams[2].ground_stock, after.sim.sams[2].air_48n6_stock), (1, 0, 0));
|
||||
}
|
||||
|
||||
/// #128 end to end: A declares a return and drives off, B waits for a round; the truck must
|
||||
/// serve B anyway (a save/load mid-flight included), and once A is back the actual return
|
||||
/// completes. Rounds are conserved throughout.
|
||||
#[test]
|
||||
fn a_moving_return_claim_drives_and_supplies_and_survives_a_state_round_trip() {
|
||||
struct Flat;
|
||||
impl sim::world::WorldSource for Flat {
|
||||
fn solid(&self, _: i32, y: i32, _: i32) -> Option<bool> { Some(y < 64) }
|
||||
}
|
||||
let mut game = test_mod();
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 120.0), (SamKind::S400, 240.0), (SamKind::Tzm, 0.0)] {
|
||||
let id = game.sim.id();
|
||||
game.sim.sams.push(Sam::new(id, kind, DVec3::new(x, 64.0, 0.0), 0.0));
|
||||
}
|
||||
game.sim.sams[0].ground_stock = 2;
|
||||
game.sim.sams[1].ground_rounds = 1;
|
||||
game.sim.sams[1].missiles = 3;
|
||||
game.sim.unload_ground_round(1).unwrap();
|
||||
assert!(game.sim.sams[1].ground_return);
|
||||
game.sim.sams[2].missiles = 3;
|
||||
// B is out of the depot's reach: the load becomes a pending delivery request.
|
||||
game.sim.load_ground_round(2).unwrap();
|
||||
assert!(game.sim.sams[2].ground_request);
|
||||
// A drives away: its return claim is impossible for a while.
|
||||
assert!(game.sim.order_move(1, DVec3::new(420.0, 64.0, 0.0)));
|
||||
let mut out = Out::default();
|
||||
let mut restored_mid_flight = false;
|
||||
let mut supplied = false;
|
||||
for _ in 0..12000 {
|
||||
let now = game.sim.tick;
|
||||
let cols = game.ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
|
||||
game.ground.answer(cols, now);
|
||||
let sections = game.ground.world.take_wanted(now);
|
||||
game.ground.world.serve(&Flat, sections, now);
|
||||
game.sim.step(&mut game.ground, None, &mut out);
|
||||
if !restored_mid_flight && game.sim.sams[3].ground_stock == 1 {
|
||||
// The truck took a round for B: save, reload, continue from the restored state.
|
||||
let saved = game.state_text(false, false);
|
||||
let mut restored = test_mod();
|
||||
restored.apply_state(&saved).unwrap();
|
||||
game = restored;
|
||||
restored_mid_flight = true;
|
||||
}
|
||||
if game.sim.sams[2].ground_rounds == 1 { supplied = true; break; }
|
||||
out = Out::default();
|
||||
}
|
||||
assert!(restored_mid_flight, "truck never picked up a round for B");
|
||||
assert!(supplied, "B starved while A's return was impossible");
|
||||
assert!(game.sim.sams[1].ground_return, "claim must survive the supply run");
|
||||
assert_eq!(game.sim.sams[0].ground_stock + game.sim.sams[3].ground_stock + game.sim.sams[1].ground_rounds + game.sim.sams[2].ground_rounds, 3);
|
||||
// A returns to its place; the waiting claim is then collected and driven to the depot.
|
||||
assert!(game.sim.order_move(1, DVec3::new(120.0, 64.0, 0.0)));
|
||||
let mut returned = false;
|
||||
for _ in 0..12000 {
|
||||
let now = game.sim.tick;
|
||||
let cols = game.ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
|
||||
game.ground.answer(cols, now);
|
||||
let sections = game.ground.world.take_wanted(now);
|
||||
game.ground.world.serve(&Flat, sections, now);
|
||||
game.sim.step(&mut game.ground, None, &mut out);
|
||||
if game.sim.sams[0].ground_stock == 2 && game.sim.sams[1].ground_rounds == 0 { returned = true; break; }
|
||||
out = Out::default();
|
||||
}
|
||||
assert!(returned);
|
||||
assert!(!game.sim.sams[1].ground_return);
|
||||
assert!(!game.sim.sams[3].return_cargo);
|
||||
assert_eq!(game.sim.sams[0].ground_stock + game.sim.sams[3].ground_stock + game.sim.sams[1].ground_rounds + game.sim.sams[2].ground_rounds, 3);
|
||||
}
|
||||
|
||||
/// #83: while an export records no other replay or film replaces it; after it, they may.
|
||||
#[test]
|
||||
fn typed_ammunition_changes_mark_the_state_dirty() {
|
||||
@@ -2862,4 +3091,57 @@ mod tests {
|
||||
sim.strikes.progress = sim::strike::TUNE.progress_save;
|
||||
assert_ne!(durable_mark(&sim), checkpoint, "a refill checkpoint is not saved");
|
||||
}
|
||||
|
||||
/// #127: the air section of a save is written and read by the adapter, and a save without it (an
|
||||
/// older one) still loads as before. The section itself is checked in the core's own tests; here
|
||||
/// the contract is that the text the game writes is the text the next load restores, and that a
|
||||
/// state with a sky replaces a state without one rather than merging into it.
|
||||
#[test]
|
||||
fn the_air_section_of_a_save_is_written_and_read_by_the_adapter() {
|
||||
let zeros = "0 ".repeat(24);
|
||||
let air = format!(
|
||||
"air 1 120 2 0 1 1 1 1\n\
|
||||
airintel {zeros}\n\
|
||||
airglobal -\n\
|
||||
airrelief 0 0 0 16 8 u64\n\
|
||||
aircontact 32 s400 0 70 0 100 emission - - 0\n\
|
||||
airqueue 200 48 shahed 0 90 -600 0 1 0 0 70 0 cruise react 32 120 0 confirmed 0 0 0 0 0 0 false false true 0 - 0 - -\n\
|
||||
airjob 1 48 0 70 0 32 120 1 react 0\n"
|
||||
);
|
||||
let saved = format!("sam {} 0 70 300 0\n{air}", SamKind::S400.key());
|
||||
let mut game = test_mod();
|
||||
game.apply_state(&saved).expect("a saved raid must load");
|
||||
assert_eq!(game.sim.tick, 120);
|
||||
assert_eq!(game.sim.queue.len(), 1, "the launch queue is not restored");
|
||||
assert_eq!(game.sim.queue[0].0, 200);
|
||||
assert_eq!(game.sim.drones.len(), 0);
|
||||
let report = game.sim.enemy_picture();
|
||||
assert_eq!(report.pending.len(), 1, "the pending route job is not restored");
|
||||
assert_eq!(report.pending[0].intent, "react");
|
||||
assert_eq!(report.pending[0].unit, 32);
|
||||
assert_eq!(report.contacts.len(), 1);
|
||||
|
||||
// The game writes the same section back: what it read is what it saves.
|
||||
let back = game.state_text(false, false);
|
||||
assert!(back.contains("\nair 1 120 2 0 1 1 1 1\n"), "{back}");
|
||||
assert!(back.contains("\nairjob 1 48 0.00 70.00 0.00 32 120 1 react 0\n"), "{back}");
|
||||
assert!(back.contains("\nairqueue 200 48 "), "{back}");
|
||||
|
||||
// The air state is replaced, not merged: a save of a quiet world clears the sky.
|
||||
let quiet = format!("sam {} 0 70 300 0\n", SamKind::S400.key());
|
||||
let quiet = format!("{quiet}air 1 300 2 0 0 0 0 0\nairintel {zeros}\nairglobal -\n");
|
||||
game.apply_state(&quiet).unwrap();
|
||||
assert!(game.sim.queue.is_empty() && game.sim.enemy_picture().pending.is_empty(), "an empty sky merged with the loaded one");
|
||||
|
||||
// An older save has no section at all: it loads its layout and leaves the sky as it was.
|
||||
let mut old = test_mod();
|
||||
old.apply_state(&format!("sam {} 0 70 0 0\n", SamKind::S400.key())).unwrap();
|
||||
assert_eq!(old.sim.sams.len(), 1);
|
||||
assert!(sim::Sim::parse_air("sam s400 0 70 0 0\n").unwrap().is_none());
|
||||
|
||||
// A scenario's body is a start state: it does not carry the sky.
|
||||
let scenario = game.scenario_text("t", false);
|
||||
assert!(!scenario.contains("\nair 1 "), "a scenario carries the air state");
|
||||
assert!(sim::Sim::parse_air(&scenario).unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+598
-81
@@ -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, LowSensor, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
|
||||
use crate::sim::{self, Class, Drone, 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,15 +27,23 @@ 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, by the speed of the track (the network doesn't know what a target is).
|
||||
/// 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.
|
||||
const TGT_CLASSES: [&str; 5] = ["Д", "Г", "К", "С", "Б"];
|
||||
/// 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];
|
||||
|
||||
/// 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])
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -121,6 +129,15 @@ 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.
|
||||
@@ -222,7 +239,11 @@ 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>,
|
||||
@@ -273,7 +294,9 @@ 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(),
|
||||
@@ -350,7 +373,9 @@ 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;
|
||||
@@ -371,10 +396,27 @@ 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) {
|
||||
@@ -423,7 +465,7 @@ impl MapUi {
|
||||
fn sys_class(k: SamKind) -> usize {
|
||||
if k.armed() {
|
||||
if k == SamKind::Gepard { 1 } else { 0 }
|
||||
} else if k.spec().sensor > 0.0 {
|
||||
} else if k == SamKind::Optical || k.spec().sensor > 0.0 {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
@@ -438,6 +480,7 @@ fn short_name(k: SamKind) -> &'static str {
|
||||
SamKind::Tzm => "ТЗМ",
|
||||
SamKind::Ew => "РЭБ",
|
||||
SamKind::Light => "Прож.",
|
||||
SamKind::Optical => "Опт.",
|
||||
SamKind::Pantsir => "Панцирь",
|
||||
SamKind::IrisT => "IRIS-T",
|
||||
SamKind::S400 => "С-400",
|
||||
@@ -449,14 +492,8 @@ 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`.
|
||||
fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
|
||||
pub(crate) 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() {
|
||||
@@ -567,6 +604,279 @@ 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) {
|
||||
@@ -810,6 +1120,7 @@ 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() {
|
||||
@@ -915,6 +1226,8 @@ 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);
|
||||
}
|
||||
@@ -929,6 +1242,17 @@ 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;
|
||||
}
|
||||
@@ -1115,7 +1439,7 @@ impl AirDef {
|
||||
let pic = self.sim.picture();
|
||||
let mut best: Option<(f32, u32)> = None;
|
||||
for (id, t) in &pic {
|
||||
if !ui.tclass[tgt_class(t)] {
|
||||
if !tclass_shown(t, &ui.tclass) {
|
||||
continue;
|
||||
}
|
||||
let e = t.est(now);
|
||||
@@ -1363,9 +1687,16 @@ 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);
|
||||
@@ -1458,14 +1789,13 @@ impl AirDef {
|
||||
if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] {
|
||||
self.map_tracks(ui, &mut s, &mut labs, &mut taken);
|
||||
}
|
||||
// The truth, when the sandbox shows it, marked as such.
|
||||
// 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.
|
||||
if self.sim.truth {
|
||||
for d in &self.sim.drones {
|
||||
let c = ui.to_screen(d.pos.x, d.pos.z);
|
||||
if ui.on_screen(c, 4.0) {
|
||||
s.extend(frame(c.0 - 3.0, c.1 - 3.0, 6.0, 6.0, 1.0, alpha(0xFF4040, 0.9)));
|
||||
}
|
||||
}
|
||||
map_truth(&self.sim, ui, hover, &mut s, &mut labs, &mut taken);
|
||||
}
|
||||
// The ghost under the pointer while placing.
|
||||
if editing && let Some(y) = self.ground_y(cur_world.0, cur_world.1) {
|
||||
@@ -1587,6 +1917,51 @@ 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.
|
||||
@@ -1922,21 +2297,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 always).
|
||||
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| ui.tclass[tgt_class(t)] || ui.sel == Some(Sel::Track(**id))).collect();
|
||||
// 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();
|
||||
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 { 0.95 } else { 0.5 });
|
||||
let col = alpha(0xFF6060, if chosen { 1.0 } else { 0.7 });
|
||||
let mut prev: Option<(f32, f32)> = None;
|
||||
for p in trail {
|
||||
let c = ui.to_screen(p.0 as f64, p.1 as f64);
|
||||
if let Some(a) = prev
|
||||
&& (ui.on_screen(a, 0.0) || ui.on_screen(c, 0.0))
|
||||
{
|
||||
s.push(line(a, c, 1.0, col));
|
||||
s.push(line(a, c, if chosen { 2.2 } else { 1.6 }, col));
|
||||
}
|
||||
prev = Some(c);
|
||||
}
|
||||
@@ -1950,7 +2325,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.0, alpha(0xFFB0B0, 0.4)));
|
||||
s.push(line(m, c, 1.4, alpha(0xFFB0B0, 0.45)));
|
||||
let r = (t.uncertainty(now) * ui.scale) as f32;
|
||||
ring(ui, s, c, r.min(300.0), 1.0, alpha(0xFFB0B0, 0.5));
|
||||
}
|
||||
@@ -1958,7 +2333,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, alpha(0xFF8080, 0.8));
|
||||
dashed(s, c, ahead, 1.5, alpha(0xFF8080, 0.85));
|
||||
}
|
||||
}
|
||||
if !ui.filters[F_TRACKS] {
|
||||
@@ -1974,7 +2349,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, CLUSTER_R * 0.8, true) {
|
||||
for grp in groups_of(&pos, &solo, TRACK_CLUSTER_R, 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);
|
||||
@@ -1984,16 +2359,36 @@ impl AirDef {
|
||||
let chosen = ui.sel == Some(Sel::Track(id));
|
||||
let forecast = t.forecast(now);
|
||||
let age = t.age(now);
|
||||
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));
|
||||
// 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));
|
||||
}
|
||||
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);
|
||||
// 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);
|
||||
if chosen {
|
||||
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
|
||||
s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2018,7 +2413,7 @@ impl AirDef {
|
||||
};
|
||||
let tail_w = ui.tw(&tail);
|
||||
let heads: [&str; 2] = if self.sim.truth {
|
||||
["КАРТА · ИСТИНА (песочница): красные рамки — настоящие дроны", "КАРТА · ИСТИНА"]
|
||||
["КАРТА · ИСТИНА (песочница): белые рамки — дроны, жёлтое — их цели и маршруты", "КАРТА · ИСТИНА (песочница)"]
|
||||
} else {
|
||||
["КАРТА · режим: данные сети РЛС", "КАРТА · сеть РЛС"]
|
||||
};
|
||||
@@ -2069,9 +2464,14 @@ 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() {
|
||||
tc[tgt_class(t)] += 1;
|
||||
match t.class.class() {
|
||||
Some(c) => tc[c as usize] += 1,
|
||||
None => unknown += 1,
|
||||
}
|
||||
}
|
||||
inner.push(text("Системы по классу", x0, y, GREY));
|
||||
y += lh;
|
||||
@@ -2086,7 +2486,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() {
|
||||
@@ -2098,11 +2498,16 @@ 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));
|
||||
@@ -2151,7 +2556,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), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
|
||||
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Истина (T)", Act::Truth, self.sim.truth), ("Игрок (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;
|
||||
@@ -2169,7 +2574,7 @@ impl AirDef {
|
||||
let helps: [&str; 3] = if editing {
|
||||
["ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc", "ЛКМ ставить · ПКМ убрать · Enter · Esc", "Enter · Esc"]
|
||||
} else {
|
||||
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · ПКМ: марш · Esc", "ЛКМ выбор · колесо масштаб · Esc", "Esc"]
|
||||
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · T: данные · Esc", "ЛКМ выбор · колесо масштаб · T данные · Esc", "Esc"]
|
||||
};
|
||||
for help in helps {
|
||||
let hw = ui.tw(help);
|
||||
@@ -2204,21 +2609,7 @@ impl AirDef {
|
||||
self.sel_card(ui, &mut lines, &mut btns);
|
||||
}
|
||||
// Long lines break at the card's width.
|
||||
let mut wrapped: Vec<(String, u32)> = Vec::new();
|
||||
for (l, c) in lines {
|
||||
let mut cur = String::new();
|
||||
for word in l.split(' ') {
|
||||
let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
|
||||
if 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;
|
||||
let lines = wrap_lines(ui, lines, card_w);
|
||||
if !lines.is_empty() || !btns.is_empty() {
|
||||
let mut y = top;
|
||||
let ch = lines.len() as f32 * lh + 10.0;
|
||||
@@ -2311,7 +2702,14 @@ 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) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)),
|
||||
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::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
|
||||
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
|
||||
}
|
||||
@@ -2330,7 +2728,11 @@ impl AirDef {
|
||||
let k = sam.kind;
|
||||
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
|
||||
if k == SamKind::Radar {
|
||||
lines.push((format!("Роль РЛС: {}", sam.radar_role.name()), WHITE));
|
||||
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));
|
||||
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
|
||||
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
|
||||
}
|
||||
@@ -2338,8 +2740,27 @@ 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((sam.status(), WHITE));
|
||||
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((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));
|
||||
lines.push((format!("Обычный БК ПВО: {} перезарядок", sam.cargo), WHITE));
|
||||
if sam.ground_stock == 0 { lines.push((format!("Начальный запас: /airdef ground-stock {} <число>", n + 1), GREY)); }
|
||||
} else if k == SamKind::Tzm {
|
||||
lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE));
|
||||
}
|
||||
if k.armed() {
|
||||
if sam.kind == SamKind::S400 { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); }
|
||||
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
|
||||
@@ -2427,24 +2848,17 @@ impl AirDef {
|
||||
lines.push((format!("Трек №{id}: потерян сетью"), GREY));
|
||||
return;
|
||||
};
|
||||
lines.push((format!("Трек сети №{id}"), 0xFFFF8080));
|
||||
lines.push((format!("Опознание: {}", t.ident().name()), WHITE));
|
||||
let age = t.age(now);
|
||||
lines.push((
|
||||
if t.forecast(now) { format!("ПРОГНОЗ: последнее измерение {} с назад", age / 20) } else { format!("Измерение {} с назад", age / 20) },
|
||||
if t.forecast(now) { YELLOW } else { GREEN },
|
||||
));
|
||||
lines.push((format!("Высота {:.0} м, скорость {:.0} км/ч", t.pos.y, t.vel.length() * 20.0 * 3.6), WHITE));
|
||||
lines.push((format!("Погрешность места до {}", distance(t.uncertainty(now))), GREY));
|
||||
lines.push(("Цель и маршрут неизвестны сети: тонкая линия —".into(), GREY));
|
||||
lines.push(("пройденное по измерениям, пунктир — прогноз курса.".into(), GREY));
|
||||
if 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));
|
||||
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));
|
||||
}
|
||||
@@ -2453,18 +2867,24 @@ 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) {
|
||||
@@ -2531,13 +2951,24 @@ 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), color: u32) {
|
||||
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), w: f32, color: u32) {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let len = dx.hypot(dy);
|
||||
let n = ((len / 8.0) as usize).min(200);
|
||||
for i in (0..n).step_by(2) {
|
||||
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
|
||||
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.0, color));
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2595,4 +3026,90 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
+82
-24
@@ -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::{Sam, SamState, Sim, heading_of, roles_text};
|
||||
use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape};
|
||||
|
||||
@@ -91,12 +91,23 @@ 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 = state.name();
|
||||
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 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(state.color(), if blink { 0x80 } else { 0xFF })));
|
||||
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(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);
|
||||
@@ -114,9 +125,13 @@ 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 = match sam.kind.range() {
|
||||
r if r > 0.0 => r,
|
||||
_ => spec.sensor,
|
||||
let reach = if optical {
|
||||
crate::sim::OPTICAL_RANGE
|
||||
} else {
|
||||
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.
|
||||
@@ -146,13 +161,17 @@ 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);
|
||||
let allowed = sam.roles & d.kind.spec().class.bit() != 0;
|
||||
// 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 color = if Some(d.id) == target.map(|t| t.id) {
|
||||
0xFFFFE040
|
||||
} else if allowed {
|
||||
0xFFFF4040
|
||||
} else {
|
||||
} else if !tr.class.in_roles(sam.roles) {
|
||||
0xFF808080
|
||||
} else if tr.class == ClassEst::Unknown {
|
||||
0xFFFFA040
|
||||
} else {
|
||||
0xFFFF4040
|
||||
};
|
||||
if tr.forecast(tick) {
|
||||
s.push(fill(bx - 1.5, by - 1.5, 3.0, 1.0, color));
|
||||
@@ -164,14 +183,30 @@ 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 spec.sensor <= 0.0 {
|
||||
let radar_text = if optical {
|
||||
format!("ОПТИКА · {}", sam.optical.state().name())
|
||||
} else if spec.sensor <= 0.0 {
|
||||
format!("сеть · {seen}")
|
||||
} else if radar_up {
|
||||
format!("РЛС {} · {}", distance(reach), seen)
|
||||
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)
|
||||
} else {
|
||||
"РЛС ОТКАЗ".to_string()
|
||||
};
|
||||
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 }));
|
||||
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));
|
||||
|
||||
// Its health under the radar: a bar, red when it is low.
|
||||
if sam.alive() && sam.health < 1.0 {
|
||||
@@ -209,7 +244,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(sam.parts_text(), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
|
||||
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 }));
|
||||
}
|
||||
// Crosshair.
|
||||
s.push(fill(cx + cw / 2.0 - 0.5, cy + 3.0, 1.0, ch * 0.18, 0x90FFFFFF));
|
||||
@@ -217,6 +252,21 @@ 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);
|
||||
@@ -233,9 +283,12 @@ 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 {
|
||||
s.push(text(fit(t.kind.spec().name.into(), cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
|
||||
// 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));
|
||||
}
|
||||
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, t.vel.length() * 72.0);
|
||||
// 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);
|
||||
if let Some(tr) = track {
|
||||
if tr.forecast(tick) {
|
||||
info += &format!(" прогноз {:.1}с", tr.age(tick) as f64 / 20.0);
|
||||
@@ -248,19 +301,24 @@ 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 !matches!(sam.kind, crate::sim::SamKind::Gepard) {
|
||||
line += &format!("Р{} ", sam.missiles);
|
||||
if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
|
||||
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 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));
|
||||
}
|
||||
|
||||
@@ -273,7 +331,7 @@ pub fn draw(sim: &Sim, index: usize) -> Vec<Shape> {
|
||||
s.push(fill(4.0, 156.0, 300.0, 4.0 + 10.0 * checks.len() as f32, 0xA0080C0A));
|
||||
for (k, c) in checks.iter().enumerate() {
|
||||
let color = if c.ok { 0xFF80FF90 } else { 0xFFFF9060 };
|
||||
s.push(text(fit(format!("{} {}", if c.ok { "+" } else { "-" }, c.text), 294.0), 7.0, 158.0 + 10.0 * k as f32, color));
|
||||
s.push(text(fit(format!("{} {}", if c.ok { "+" } else { "-" }, crate::why_view::reason(&c.reason)), 294.0), 7.0, 158.0 + 10.0 * k as f32, color));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
+106
-12
@@ -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, DroneKind, Sim};
|
||||
use crate::sim::{AirPicture, Class, ClassEst, Sim};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::hud::Line;
|
||||
|
||||
@@ -31,28 +31,50 @@ 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 type, as the radars classed them.
|
||||
// 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.
|
||||
let mut by_type = String::new();
|
||||
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 += ", ";
|
||||
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());
|
||||
}
|
||||
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.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
|
||||
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч · {} кач.{}{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel), t.product.name(), t.quality),
|
||||
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();
|
||||
@@ -61,6 +83,12 @@ 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() {
|
||||
@@ -77,6 +105,11 @@ 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));
|
||||
@@ -94,12 +127,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!("{} [{}]", sam.status(), crate::sim::roles_text(sam.roles))
|
||||
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles))
|
||||
} else {
|
||||
sam.status()
|
||||
crate::battery_view::sam_status(sam)
|
||||
};
|
||||
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
|
||||
text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos)));
|
||||
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
|
||||
}
|
||||
if sam.kills > 0 {
|
||||
text += &format!(" ({})", sam.kills);
|
||||
@@ -119,3 +152,64 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +286,16 @@ impl<P, E> Session<P, E> {
|
||||
Some(Cleanup { actions })
|
||||
}
|
||||
|
||||
/// The world is gone (the title screen): the game stops ticking there, so an active export
|
||||
/// would otherwise go on recording the title with its playback clock frozen. Nothing to do
|
||||
/// in Live, and a world still open is not a leave.
|
||||
pub fn world_left(&mut self, world: Option<&str>) -> Option<Cleanup> {
|
||||
if self.is_live() || world.is_some() {
|
||||
return None;
|
||||
}
|
||||
self.end(ExitCause::WorldChange)
|
||||
}
|
||||
|
||||
/// A world change invalidates live work too. Active playback uses the normal cleanup path,
|
||||
/// which advances generation exactly once; Live advances generation without host cleanup.
|
||||
pub fn world_changed(&mut self) -> Option<Cleanup> {
|
||||
@@ -466,6 +476,30 @@ mod tests {
|
||||
assert_ne!(session.generation(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gone_world_ends_an_active_export_once() {
|
||||
let mut session = Session::<(), ()>::default();
|
||||
assert!(session.world_left(None).is_none(), "Live has nothing to clean up");
|
||||
session.replay(());
|
||||
assert!(session.world_left(Some("world:w")).is_none(), "the world is still open");
|
||||
let State::Replay(playback) = session.take() else {
|
||||
panic!("replay state lost")
|
||||
};
|
||||
session.export(playback, ());
|
||||
let cleanup = session.world_left(None).expect("the title screen ends the export");
|
||||
assert!(cleanup.actions.contains(&CleanupAction::CancelCapture));
|
||||
|
||||
let mut host = HostFixture::default();
|
||||
host.apply(&cleanup);
|
||||
let count = host.actions.len();
|
||||
assert!(session.world_left(None).is_none(), "a second frame sees Live");
|
||||
assert_eq!(host.actions.len(), count, "cleanup is not repeated");
|
||||
assert_eq!(
|
||||
host.actions.iter().filter(|a| **a == CleanupAction::CancelCapture).count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_and_restart_emit_cleanup_once_for_stop_unload_failure_and_success() {
|
||||
for cause in [
|
||||
|
||||
+171
-14
@@ -1,15 +1,24 @@
|
||||
//! The radar screen (top left): a round scope round the player, north up,
|
||||
//! with a sweeping beam; blips fade after the beam passes them.
|
||||
//! 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.
|
||||
use crate::panel::distance;
|
||||
use crate::sim::{SamKind, Sim};
|
||||
use crate::sim::{Class, ClassEst, 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 }
|
||||
@@ -32,6 +41,34 @@ 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;
|
||||
@@ -143,49 +180,169 @@ 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, 0xFF4040)
|
||||
(1.0, fresh_color)
|
||||
};
|
||||
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)));
|
||||
let (x, y) = inside(x, y, cx, cy, r);
|
||||
marks.push((x, y, t.class, color, a, vel));
|
||||
}
|
||||
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) {
|
||||
s.push(square(x, y, 0.8, 0xFFFFFFFF));
|
||||
let (x, y) = inside(x, y, cx, cy, r);
|
||||
s.push(square(x, y, 1.3, 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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
//! world and a director's camera (a full-screen camera view) follows them —
|
||||
//! behind the drone, then behind the interceptor or from the side — slowing
|
||||
//! time round the moment itself.
|
||||
use crate::sim::catalog::sound;
|
||||
|
||||
use crate::film::{self, Film};
|
||||
use crate::panel::distance;
|
||||
use crate::sim::Ground;
|
||||
@@ -526,11 +528,11 @@ impl Player {
|
||||
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
|
||||
let event = match e.kind {
|
||||
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][(power as usize).min(4)],
|
||||
EventKind::SamLost { .. } => "airdef:blast.big",
|
||||
EventKind::Split { .. } => "airdef:boom.sonic",
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
||||
EventKind::SamLost { .. } => sound::BLAST_BIG,
|
||||
EventKind::Split { .. } => sound::BOOM_SONIC,
|
||||
EventKind::Strike { result: StrikeResult::Halted, .. } => continue,
|
||||
EventKind::Strike { result, .. } => ["airdef:blast.air", "airdef:blast.medium", "airdef:blast.big", "airdef:blast.heavy", "airdef:blast.huge"][match result {
|
||||
EventKind::Strike { result, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][match result {
|
||||
StrikeResult::Destroyed => 4,
|
||||
StrikeResult::Intercepted => 0,
|
||||
_ => 3,
|
||||
@@ -539,7 +541,7 @@ impl Player {
|
||||
let gain = if let EventKind::Kill { kind, outcome, .. } = e.kind { crate::sim::outcome::look(kind, outcome).2 } else { 1.0 };
|
||||
out.sound(event, heard(e.pos), gain, 1.0);
|
||||
if let EventKind::Kill { outcome: crate::sim::outcome::Outcome::AirDetonation, .. } = e.kind {
|
||||
out.sound("airdef:boom.sonic", heard(e.pos), 0.8, 1.2);
|
||||
out.sound(sound::BOOM_SONIC, heard(e.pos), 0.8, 1.2);
|
||||
}
|
||||
}
|
||||
// New recordings carry the exact launch and ignition sounds and their actual positions.
|
||||
@@ -570,7 +572,7 @@ impl Player {
|
||||
for tr in rec.tracks.iter().filter(|tr| matches!(tr.what, What::StrikeCarrier(_))) {
|
||||
let at = tr.first as f64 + crate::sim::strike::EJECT_TICKS as f64;
|
||||
if (self.heard..self.t).contains(&at) && let Some(p) = tr.at(rec.origin, at) {
|
||||
out.sound("airdef:launch.s400", heard(p), 1.0, 1.0);
|
||||
out.sound(sound::LAUNCH_S400, heard(p), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
self.heard = self.t;
|
||||
@@ -1208,7 +1210,7 @@ mod engine_tests {
|
||||
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400_eject"]);
|
||||
assert!(out.engines.is_empty());
|
||||
out = Out::default();
|
||||
p.t = 16.0;
|
||||
p.t = 10.0 + crate::sim::strike::EJECT_TICKS as f64 + 1.0;
|
||||
p.sounds(&rec, DVec3::ZERO, &mut out);
|
||||
p.engines(&rec, DVec3::ZERO, false, &mut out);
|
||||
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400"]);
|
||||
|
||||
@@ -36,9 +36,10 @@ fn names() -> Vec<String> {
|
||||
|
||||
impl AirDef {
|
||||
/// The scenario as text.
|
||||
fn scenario_text(&self, name: &str, fresh: bool) -> String {
|
||||
pub(crate) fn scenario_text(&self, name: &str, fresh: bool) -> String {
|
||||
let mut text = format!("scenario {VERSION}\nname {name}\nworld {}\n", self.state_key());
|
||||
text += &self.state_text(fresh, false);
|
||||
// A scenario is a start state: its body is the layout, not the raid a save happened to catch.
|
||||
text += &self.state_text_with(fresh, false, false);
|
||||
text += &format!("seed {}\nwave {}\n", self.sim.rng.state(), self.wave.text());
|
||||
text
|
||||
}
|
||||
|
||||
@@ -54,6 +54,12 @@ pub(super) struct Result {
|
||||
pub missed: u32,
|
||||
/// Missiles fired by the heavy systems (S-400, S-500, Patriot).
|
||||
pub heavy: u32,
|
||||
/// Interceptors whose fuse ran without a kill; whose life ran out; that lost their target on the way;
|
||||
/// and that fell below their guidance speed after motor burnout (#120's coast/energy tally).
|
||||
pub fuse_missed: u32,
|
||||
pub expired: u32,
|
||||
pub orphaned: u32,
|
||||
pub energy_lost: u32,
|
||||
pub by_kind: Vec<(DroneKind, u32, u32)>,
|
||||
pub tally: String,
|
||||
/// Drones that vanished short of their aim without being shot down: kind, where, how far from the aim.
|
||||
@@ -322,6 +328,10 @@ pub(super) fn fly(s: &Setup) -> Result {
|
||||
result.crashes = sim.crashes;
|
||||
result.blocked = sim.tally.blocked;
|
||||
result.scrubbed = sim.tally.scrubbed;
|
||||
result.fuse_missed = sim.tally.missed;
|
||||
result.expired = sim.tally.expired;
|
||||
result.orphaned = sim.tally.orphaned;
|
||||
result.energy_lost = sim.tally.energy_lost;
|
||||
result.leaked = sim.hits;
|
||||
let mut kinds: HashMap<DroneKind, (u32, u32)> = HashMap::new();
|
||||
for h in &gone_unkilled {
|
||||
@@ -514,6 +524,35 @@ fn one_raid() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #120's wider sampling: battery sizes, launch-range bounds and the target classes of a raid
|
||||
/// of 36, on the same seeds against the same cluster mix as `one_raid`. Prints CSV rows:
|
||||
/// `variant,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind`.
|
||||
/// `SEEDS=1-8 cargo test --release issue_120_grid -- --ignored --nocapture` (SEEDS overrides the seed range).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn issue_120_grid() {
|
||||
let seeds = match std::env::var("SEEDS") {
|
||||
Ok(v) => {
|
||||
let (a, b) = v.split_once('-').expect("SEEDS is a range like 1-8");
|
||||
let a: u64 = a.parse().expect("SEEDS start");
|
||||
let b: u64 = b.parse().expect("SEEDS end");
|
||||
a..=b
|
||||
}
|
||||
Err(_) => 1..=8,
|
||||
};
|
||||
for (variant, sams, dist) in [("batt10", 10usize, 500.0), ("batt20", 20, 500.0), ("batt50", 50, 500.0), ("near200", 20, 200.0), ("far1500", 20, 1500.0), ("hills20", 20, 500.0)] {
|
||||
for seed in seeds.clone() {
|
||||
let mut s = Setup::new(sams, false, seed);
|
||||
s.size = 36;
|
||||
s.dist = dist;
|
||||
s.hilly = variant == "hills20";
|
||||
let r = fly(&s);
|
||||
let kinds = r.by_kind.iter().map(|k| format!("{:?}:{}", k.0, k.1)).collect::<Vec<_>>().join(";");
|
||||
eprintln!("{variant},{seed},{sams},{dist},{},{},{},{},{},{},{},{},{},{},{},{},{},{}", r.launched, r.kills, r.leaked, r.missiles, r.heavy, r.ticks, r.blocked, r.scrubbed, r.crashes, r.fuse_missed, r.expired, r.orphaned, r.energy_lost, kinds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Far launches over mountains where only a disc round the player is known: who crashes, where and how often.
|
||||
/// `cargo test --release far_table -- --ignored --nocapture` (DISC=300 sets the radius, 0 for all known).
|
||||
#[test]
|
||||
|
||||
+288
-16
@@ -33,11 +33,199 @@ 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::Multifunction => "многофункциональная", Self::Search => "обзорная", Self::Engagement => "сопровождения", Self::Height => "мачтовая" }
|
||||
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 {
|
||||
@@ -68,15 +256,22 @@ impl Sam {
|
||||
}
|
||||
}
|
||||
|
||||
/// A snapshot of the relevant configuration, independent of its presentation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BatteryStatus {
|
||||
Radar { index: usize, role: RadarRole, emitting: bool, operational: bool },
|
||||
Launcher { index: usize, kind: SamKind, mode: SamMode, linked: bool },
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
/// Current configurations and whether a launcher has an operational radar link.
|
||||
pub fn battery_status(&self) -> Vec<String> {
|
||||
self.sams.iter().enumerate().filter_map(|(i, sam)| {
|
||||
pub fn battery_status(&self) -> Vec<BatteryStatus> {
|
||||
self.sams.iter().enumerate().filter_map(|(index, sam)| {
|
||||
if sam.kind == SamKind::Radar {
|
||||
Some(format!("№{} РЛС: {}, излучение {}, {}", i + 1, sam.radar_role.name(), if sam.radar_on { "вкл" } else { "выкл" }, if sam.radar_up() && sam.link_range() > 0.0 { "работает" } else { "нет связи или РЛС не работает" }))
|
||||
Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 })
|
||||
} else if matches!(sam.kind, SamKind::S400 | SamKind::S500) {
|
||||
let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()));
|
||||
Some(format!("№{} {}: {}{}", i + 1, sam.kind.name(), sam.mode.key(), if sam.mode == SamMode::LauncherOnly { if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" } } else { "" }))
|
||||
Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked })
|
||||
} else { None }
|
||||
}).collect()
|
||||
}
|
||||
@@ -87,8 +282,44 @@ mod tests {
|
||||
use super::*;
|
||||
use super::super::{sight, why};
|
||||
|
||||
#[test]
|
||||
fn status_reports_real_radar_links_and_preserves_indices() {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.sams.push(Sam::new(1, SamKind::Pantsir, DVec3::ZERO, 0.0));
|
||||
let mut radar = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0);
|
||||
radar.radar_role = RadarRole::Engagement;
|
||||
sim.sams.push(radar);
|
||||
let mut launcher = Sam::new(3, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0);
|
||||
launcher.set_mode(SamMode::LauncherOnly);
|
||||
sim.sams.push(launcher);
|
||||
assert_eq!(sim.battery_status(), vec![
|
||||
BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true },
|
||||
BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true },
|
||||
]);
|
||||
sim.sams[1].radar_on = false;
|
||||
assert_eq!(sim.battery_status(), vec![
|
||||
BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: false, operational: false },
|
||||
BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: false },
|
||||
]);
|
||||
}
|
||||
|
||||
fn track(now: u64) -> Track {
|
||||
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 }
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -226,6 +457,24 @@ 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);
|
||||
@@ -260,7 +509,7 @@ mod tests {
|
||||
mod emission_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn silence_accepts_network_without_inventing_own_measurements_and_contacts_age() {
|
||||
fn silence_discloses_nothing_and_contacts_age_and_channels_still_place_a_unit() {
|
||||
let mut sim = Sim::new(121);
|
||||
sim.tick = 20;
|
||||
let mut source = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
|
||||
@@ -269,29 +518,52 @@ 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, kind: DroneKind::Kh101, pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false });
|
||||
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,
|
||||
});
|
||||
sim.sams.extend([source, receiver]);
|
||||
let mut ground = Ground::default();
|
||||
sim.update_sight(&mut ground);
|
||||
assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0);
|
||||
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
|
||||
assert!(!sim.sams[1].radar_up());
|
||||
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
|
||||
// The emitting source is fixed by the drone; the silent receiver is not.
|
||||
let picture = sim.picture_of_defences();
|
||||
assert_eq!(picture.len(), 1);
|
||||
assert_eq!((picture[0].id, picture[0].at), (1, DVec3::ZERO));
|
||||
assert_eq!(picture[0].seen, ew::Seen::Emission);
|
||||
sim.sams[0].radar_on = false;
|
||||
// The truth moving is not an observation: the contact keeps the observed place.
|
||||
sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0);
|
||||
sim.tick = 40;
|
||||
sim.update_sight(&mut ground);
|
||||
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
|
||||
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
|
||||
let picture = sim.picture_of_defences();
|
||||
assert_eq!(picture.len(), 1);
|
||||
assert_eq!(picture[0].at, DVec3::ZERO, "a hidden move changed the picture");
|
||||
// A fresh emission fix re-places it where seen then.
|
||||
sim.sams[0].radar_on = true;
|
||||
sim.tick = 60;
|
||||
sim.update_sight(&mut ground);
|
||||
assert_eq!(sim.known_units(), vec![(1, DVec3::new(400.0, 0.0, 0.0))]);
|
||||
assert_eq!(sim.picture_of_defences()[0].at, DVec3::new(400.0, 0.0, 0.0));
|
||||
sim.sams[0].radar_on = false;
|
||||
// Other disclosure channels still reveal a silent unit.
|
||||
sim.intel.revealed.push((2, DVec3::ZERO, 60));
|
||||
assert!(Sim::enemy_knows(&sim.sams[1], &sim.known_units()));
|
||||
sim.intel.observe(&sim.sams[1], 60, ew::Seen::Launch);
|
||||
assert!(sim.known_live(2));
|
||||
sim.tick = 6060;
|
||||
assert!(sim.known_units().is_empty());
|
||||
assert!(sim.picture_of_defences().is_empty(), "an unrefreshed contact never ages out");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::{DroneKind, SamKind};
|
||||
use super::{battery::RadarProfile, battery::RadarRole, battery::SamMode, DroneKind, SamKind};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Aircraft {
|
||||
@@ -19,6 +19,28 @@ 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,
|
||||
@@ -52,37 +74,14 @@ impl Unit {
|
||||
}
|
||||
|
||||
use DroneKind::*;
|
||||
/// The raid entries come first, in the order stored by existing scenario files.
|
||||
pub const AIRCRAFT: &[Aircraft] = &[
|
||||
Aircraft { kind: Gerbera, launch_item: None, raid: true },
|
||||
Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true },
|
||||
Aircraft { kind: Geran3, launch_item: Some("airdef:launch_geran3"), raid: true },
|
||||
Aircraft { kind: Lancet, launch_item: Some("airdef:launch_lancet"), raid: true },
|
||||
Aircraft { kind: Kh101, launch_item: Some("airdef:launch_kh101"), raid: true },
|
||||
Aircraft { kind: Kalibr, launch_item: Some("airdef:launch_kalibr"), raid: true },
|
||||
Aircraft { kind: Kh22, launch_item: Some("airdef:launch_kh22"), raid: true },
|
||||
Aircraft { kind: Zircon, launch_item: Some("airdef:launch_zircon"), raid: true },
|
||||
Aircraft { kind: Iskander, launch_item: Some("airdef:launch_iskander"), raid: true },
|
||||
Aircraft { kind: Kinzhal, launch_item: Some("airdef:launch_kinzhal"), raid: true },
|
||||
Aircraft { kind: Oreshnik, launch_item: Some("airdef:launch_oreshnik"), raid: true },
|
||||
Aircraft { kind: OreshnikBlock, launch_item: None, raid: false },
|
||||
Aircraft { kind: OreshnikSub, launch_item: None, raid: false },
|
||||
];
|
||||
/// Stable sound IDs shared with the audio resource generator.
|
||||
pub mod sound {
|
||||
include!("catalog_sound_ids.rs");
|
||||
}
|
||||
|
||||
macro_rules! units {
|
||||
($( $kind:ident => $item:literal ),+ $(,)?) => {
|
||||
pub const UNITS: &[Unit] = &[$(Unit { kind: SamKind::$kind, deploy_item: $item }),+];
|
||||
};
|
||||
}
|
||||
units! {
|
||||
Patriot => "airdef:deploy_patriot", Gepard => "airdef:deploy_gepard",
|
||||
Pantsir => "airdef:deploy_pantsir", S400 => "airdef:deploy_s400",
|
||||
S500 => "airdef:deploy_s500", IrisT => "airdef:deploy_irist",
|
||||
Nasams => "airdef:deploy_nasams", Buk => "airdef:deploy_buk",
|
||||
Tor => "airdef:deploy_tor", P1sun => "airdef:deploy_p1sun",
|
||||
Radar => "airdef:deploy_radar", Depot => "airdef:deploy_depot",
|
||||
Tzm => "airdef:deploy_tzm", Ew => "airdef:deploy_ew", Light => "airdef:deploy_light",
|
||||
}
|
||||
// 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 {
|
||||
@@ -156,6 +155,10 @@ 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::*;
|
||||
@@ -196,4 +199,60 @@ mod tests {
|
||||
assert_eq!(kinds, SamKind::ALL.into_iter().collect());
|
||||
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]
|
||||
fn generated_specs_cover_every_kind_and_keep_their_keys() {
|
||||
let mut drones = HashSet::new();
|
||||
let mut drone_keys = HashSet::new();
|
||||
for (kind, key) in super::super::DRONE_SPEC_KEYS {
|
||||
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
|
||||
assert!(drones.insert(kind), "duplicate drone profile {kind:?}");
|
||||
assert!(drone_keys.insert(key), "duplicate drone save key {key}");
|
||||
assert!(kind.spec().rcs > 0.0 && kind.spec().launch_sound.starts_with("airdef:"));
|
||||
}
|
||||
assert_eq!(drones, DroneKind::ALL.into_iter().collect());
|
||||
let mut missiles = HashSet::new();
|
||||
for (kind, model) in super::super::MISSILE_SPEC_MODELS {
|
||||
assert_eq!(kind.spec().model, model, "profile/model mismatch for {kind:?}");
|
||||
assert!(missiles.insert(kind), "duplicate missile profile {kind:?}");
|
||||
}
|
||||
let mut units = HashSet::new();
|
||||
let mut unit_keys = HashSet::new();
|
||||
for (kind, key) in super::super::units::UNIT_SPEC_KEYS {
|
||||
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
|
||||
assert!(units.insert(kind), "duplicate unit profile {kind:?}");
|
||||
assert!(unit_keys.insert(key), "duplicate unit save key {key}");
|
||||
}
|
||||
assert_eq!(units, SamKind::ALL.into_iter().collect());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
|
||||
pub const AIRCRAFT: &[Aircraft] = &[
|
||||
Aircraft { kind: Gerbera, launch_item: None, raid: true },
|
||||
Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true },
|
||||
Aircraft { kind: Geran3, launch_item: Some("airdef:launch_geran3"), raid: true },
|
||||
Aircraft { kind: Lancet, launch_item: Some("airdef:launch_lancet"), raid: true },
|
||||
Aircraft { kind: Kh101, launch_item: Some("airdef:launch_kh101"), raid: true },
|
||||
Aircraft { kind: Kalibr, launch_item: Some("airdef:launch_kalibr"), raid: true },
|
||||
Aircraft { kind: Kh22, launch_item: Some("airdef:launch_kh22"), raid: true },
|
||||
Aircraft { kind: Zircon, launch_item: Some("airdef:launch_zircon"), raid: true },
|
||||
Aircraft { kind: Iskander, launch_item: Some("airdef:launch_iskander"), raid: true },
|
||||
Aircraft { kind: Kinzhal, launch_item: Some("airdef:launch_kinzhal"), raid: true },
|
||||
Aircraft { kind: Oreshnik, launch_item: Some("airdef:launch_oreshnik"), raid: true },
|
||||
Aircraft { kind: OreshnikBlock, launch_item: None, raid: false },
|
||||
Aircraft { kind: OreshnikSub, launch_item: None, raid: false },
|
||||
];
|
||||
|
||||
pub const UNITS: &[Unit] = &[
|
||||
Unit { kind: SamKind::Patriot, deploy_item: "airdef:deploy_patriot" },
|
||||
Unit { kind: SamKind::Gepard, deploy_item: "airdef:deploy_gepard" },
|
||||
Unit { kind: SamKind::Pantsir, deploy_item: "airdef:deploy_pantsir" },
|
||||
Unit { kind: SamKind::S400, deploy_item: "airdef:deploy_s400" },
|
||||
Unit { kind: SamKind::S500, deploy_item: "airdef:deploy_s500" },
|
||||
Unit { kind: SamKind::IrisT, deploy_item: "airdef:deploy_irist" },
|
||||
Unit { kind: SamKind::Nasams, deploy_item: "airdef:deploy_nasams" },
|
||||
Unit { kind: SamKind::Buk, deploy_item: "airdef:deploy_buk" },
|
||||
Unit { kind: SamKind::Tor, deploy_item: "airdef:deploy_tor" },
|
||||
Unit { kind: SamKind::P1sun, deploy_item: "airdef:deploy_p1sun" },
|
||||
Unit { kind: SamKind::Radar, deploy_item: "airdef:deploy_radar" },
|
||||
Unit { kind: SamKind::Depot, deploy_item: "airdef:deploy_depot" },
|
||||
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" },
|
||||
];
|
||||
@@ -0,0 +1,36 @@
|
||||
// Generated by tools/gen_catalog.py from catalog/sounds.json. Do not edit.
|
||||
pub const DRONE_SHAHED: &str = "airdef:drone.shahed";
|
||||
pub const DRONE_GERAN3: &str = "airdef:drone.geran3";
|
||||
pub const DRONE_LANCET: &str = "airdef:drone.lancet";
|
||||
pub const DRONE_CRUISE: &str = "airdef:drone.cruise";
|
||||
pub const DRONE_ROCKET: &str = "airdef:drone.rocket";
|
||||
pub const MISSILE_FLIGHT: &str = "airdef:missile.flight";
|
||||
pub const DRONE_BALLISTIC: &str = "airdef:drone.ballistic";
|
||||
pub const BOOM_SONIC: &str = "airdef:boom.sonic";
|
||||
pub const BOOM_SONIC_FAR: &str = "airdef:boom.sonic_far";
|
||||
pub const LAUNCH_PATRIOT: &str = "airdef:launch.patriot";
|
||||
pub const LAUNCH_PATRIOT_FAR: &str = "airdef:launch.patriot_far";
|
||||
pub const LAUNCH_S400_EJECT: &str = "airdef:launch.s400_eject";
|
||||
pub const LAUNCH_S400_EJECT_FAR: &str = "airdef:launch.s400_eject_far";
|
||||
pub const LAUNCH_S400: &str = "airdef:launch.s400";
|
||||
pub const LAUNCH_S400_FAR: &str = "airdef:launch.s400_far";
|
||||
pub const LAUNCH_S500_EJECT: &str = "airdef:launch.s500_eject";
|
||||
pub const LAUNCH_S500_EJECT_FAR: &str = "airdef:launch.s500_eject_far";
|
||||
pub const LAUNCH_S500: &str = "airdef:launch.s500";
|
||||
pub const LAUNCH_S500_FAR: &str = "airdef:launch.s500_far";
|
||||
pub const LAUNCH_PANTSIR: &str = "airdef:launch.pantsir";
|
||||
pub const LAUNCH_PANTSIR_FAR: &str = "airdef:launch.pantsir_far";
|
||||
pub const GUN_GEPARD: &str = "airdef:gun.gepard";
|
||||
pub const GUN_GEPARD_FAR: &str = "airdef:gun.gepard_far";
|
||||
pub const GUN_PANTSIR: &str = "airdef:gun.pantsir";
|
||||
pub const GUN_PANTSIR_FAR: &str = "airdef:gun.pantsir_far";
|
||||
pub const BLAST_BIG: &str = "airdef:blast.big";
|
||||
pub const BLAST_BIG_FAR: &str = "airdef:blast.big_far";
|
||||
pub const BLAST_HEAVY: &str = "airdef:blast.heavy";
|
||||
pub const BLAST_HEAVY_FAR: &str = "airdef:blast.heavy_far";
|
||||
pub const BLAST_HUGE: &str = "airdef:blast.huge";
|
||||
pub const BLAST_HUGE_FAR: &str = "airdef:blast.huge_far";
|
||||
pub const BLAST_MEDIUM: &str = "airdef:blast.medium";
|
||||
pub const BLAST_MEDIUM_FAR: &str = "airdef:blast.medium_far";
|
||||
pub const BLAST_AIR: &str = "airdef:blast.air";
|
||||
pub const BLAST_AIR_FAR: &str = "airdef:blast.air_far";
|
||||
@@ -54,6 +54,10 @@ 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
|
||||
}
|
||||
@@ -61,7 +65,8 @@ impl Part {
|
||||
pub fn on(self, kind: SamKind) -> bool {
|
||||
let spec = kind.spec();
|
||||
match self {
|
||||
Part::Sensor => spec.sensor > 0.0,
|
||||
// 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::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(),
|
||||
@@ -112,30 +117,6 @@ 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.
|
||||
@@ -443,9 +424,6 @@ 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);
|
||||
@@ -461,7 +439,7 @@ impl Sam {
|
||||
0.5 + 0.5 * self.part(Part::Gun)
|
||||
}
|
||||
/// Its launcher's cells still good: a damaged one holds fewer missiles.
|
||||
pub(super) fn cells(&self) -> u32 {
|
||||
pub 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) }
|
||||
@@ -475,7 +453,7 @@ impl Sam {
|
||||
}
|
||||
}
|
||||
/// Ticks a reload takes: longer with a damaged launcher.
|
||||
pub(super) fn reload_time(&self) -> u32 {
|
||||
pub 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,6 +85,11 @@ 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.
|
||||
@@ -97,23 +102,24 @@ 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, or anything about to hit.
|
||||
pub fn matters(d: &Drone) -> bool {
|
||||
d.kind.spec().class == Class::Ballistic || why::arrival(d) < why::URGENT
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// The reserve holds the launch back: the magazine is at the reserve and the target doesn't matter.
|
||||
pub fn reserve_blocks(&self, missiles: u32, d: &Drone) -> u8 {
|
||||
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d) { RESERVE } else { 0 }
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Interceptors this doctrine asks for on `d`: `why::needed` by default, the base only when economical, one more when heavy.
|
||||
pub fn needed(&self, d: &Drone) -> u32 {
|
||||
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
|
||||
pub fn needed(&self, d: &Drone, class: ClassEst) -> u32 {
|
||||
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
|
||||
match self.salvo {
|
||||
Salvo::Economy => base,
|
||||
Salvo::Normal => why::needed(d),
|
||||
Salvo::Heavy => why::needed(d) + 1,
|
||||
Salvo::Normal => why::needed(d, class),
|
||||
Salvo::Heavy => why::needed(d, class) + 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +168,22 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(pos: DVec3, vel: DVec3) -> Track {
|
||||
Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -219,7 +240,7 @@ mod tests {
|
||||
}
|
||||
// The explanation while the target is in the sky: all the lines it gave then.
|
||||
if sim.tick % 10 == 0 {
|
||||
lines.extend(sim.why(0).into_iter().map(|c| c.text));
|
||||
lines.extend(sim.why(0).into_iter().map(|c| c.legacy_text().to_owned()));
|
||||
}
|
||||
}
|
||||
(sim.sams[0].fired, first, lines)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1717
-76
File diff suppressed because it is too large
Load Diff
+234
-37
@@ -4,14 +4,6 @@
|
||||
//! reloads to the systems that wait, nearest first, and back.
|
||||
use super::*;
|
||||
|
||||
/// How near a depot a system reloads straight from it.
|
||||
const DEPOT_REACH: f64 = 60.0;
|
||||
/// How near a truck must come to hand a reload over, or to load up at a depot.
|
||||
const HANDOVER: f64 = 10.0;
|
||||
/// What a truck carries.
|
||||
const TRUCK_LOAD: u32 = 2;
|
||||
const STOCK_LIMIT: u32 = 1_000_000;
|
||||
|
||||
impl Sim {
|
||||
/// Whether ammunition is counted: a depot was set up (without one, magazines refill as
|
||||
/// before). A destroyed depot still counts: losing the last one leaves the systems short,
|
||||
@@ -35,6 +27,9 @@ impl Sim {
|
||||
let Some(depot) = depot else {
|
||||
if s.ground_request { return Err("Заявка RM48U уже ожидает ТЗМ".into()); }
|
||||
if !self.sams.iter().any(|d| d.alive() && ((d.kind == SamKind::Depot && d.ground_stock > 0) || (d.kind == SamKind::Tzm && d.ground_stock > 0))) {
|
||||
if let Some((j, _)) = self.sams.iter().enumerate().find(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH) {
|
||||
return Err(format!("Склад №{} рядом, но RM48U: 0. Задайте запас: /airdef ground-stock {} <количество>", j + 1, j + 1));
|
||||
}
|
||||
return Err("Нет живого склада с RM48U рядом (60 блоков)".into());
|
||||
}
|
||||
if !self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive()) { return Err("Для доставки RM48U нужна исправная ТЗМ".into()); }
|
||||
@@ -124,41 +119,59 @@ impl Sim {
|
||||
let at = truck.pos;
|
||||
let truck_id = truck.id;
|
||||
// A return is picked up physically; its cargo remains marked until a depot accepts it.
|
||||
// The return keeps its priority only while it can actually proceed (#128): a carrier
|
||||
// holding a reserved round needs a depot with room in reach, an empty one a system
|
||||
// ready to hand a round over (whole, deployed, not claimed by another truck, a
|
||||
// reachable route). A return that is merely claimed but impossible used to clear the
|
||||
// job and stop the truck, starving independent supply requests; the claim now stays
|
||||
// untouched and only real RM48U demand pulls the truck away from its watch.
|
||||
let return_cargo = truck.return_cargo && truck.ground_stock > 0;
|
||||
let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD;
|
||||
let return_work = truck.return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return));
|
||||
if return_work {
|
||||
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
|
||||
let target = if truck.return_cargo {
|
||||
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
} else {
|
||||
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
}.map(|s| (s.id, s.pos));
|
||||
self.sams[t].job = target.map(|x| x.0);
|
||||
if let Some((id, to)) = target {
|
||||
if at.distance(to) > HANDOVER {
|
||||
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
|
||||
self.order_move_near(t, to + side, 3.5);
|
||||
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
|
||||
if self.sams[t].return_cargo {
|
||||
self.sams[j].ground_stock += 1;
|
||||
self.sams[t].ground_stock -= 1;
|
||||
self.sams[t].return_cargo = false;
|
||||
} else {
|
||||
self.sams[j].ground_rounds -= 1;
|
||||
self.sams[j].ground_return = false;
|
||||
self.sams[t].ground_stock += 1;
|
||||
self.sams[t].return_cargo = true;
|
||||
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
|
||||
self.sams[t].air_48n6_stock -= 1;
|
||||
self.sams[j].missiles += 1;
|
||||
}
|
||||
let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return));
|
||||
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
|
||||
let target = if return_cargo {
|
||||
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
} else if can_pick {
|
||||
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
|
||||
} else {
|
||||
None
|
||||
}.map(|s| (s.id, s.pos));
|
||||
if let Some((id, to)) = target {
|
||||
self.sams[t].job = Some(id);
|
||||
if at.distance(to) > HANDOVER {
|
||||
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
|
||||
self.order_move_near(t, to + side, 3.5);
|
||||
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
|
||||
if self.sams[t].return_cargo {
|
||||
self.sams[j].ground_stock += 1;
|
||||
self.sams[t].ground_stock -= 1;
|
||||
self.sams[t].return_cargo = false;
|
||||
} else {
|
||||
self.sams[j].ground_rounds -= 1;
|
||||
self.sams[j].ground_return = false;
|
||||
self.sams[t].ground_stock += 1;
|
||||
self.sams[t].return_cargo = true;
|
||||
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
|
||||
self.sams[t].air_48n6_stock -= 1;
|
||||
self.sams[j].missiles += 1;
|
||||
}
|
||||
self.sams[t].job = None;
|
||||
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
|
||||
}
|
||||
self.sams[t].job = None;
|
||||
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if claim_pending {
|
||||
// The impossible return still outranks a mere stock run: without RM48U demand
|
||||
// the truck holds its watch (and drops a stale job) exactly as before.
|
||||
let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request))
|
||||
|| (self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request)
|
||||
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
|
||||
if !supply_demand {
|
||||
self.sams[t].job = None;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed
|
||||
// after loading a save; the request and physical cargo survive independently.
|
||||
let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 ||
|
||||
@@ -181,6 +194,8 @@ impl Sim {
|
||||
let take = self.sams[t].ground_stock.min(STOCK_LIMIT - self.sams[j].ground_stock);
|
||||
self.sams[j].ground_stock += take;
|
||||
self.sams[t].ground_stock -= take;
|
||||
// The last reserved round left the truck: nothing marks as return cargo any more.
|
||||
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
|
||||
}
|
||||
if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) {
|
||||
self.sams[j].ground_stock -= 1;
|
||||
@@ -193,6 +208,9 @@ impl Sim {
|
||||
if self.sams[j].ground_rounds >= self.sams[j].cells() && self.sams[j].kind.spec().gun.is_none() { self.sams[j].empty = false; }
|
||||
self.sams[j].ground_request = false;
|
||||
self.sams[t].ground_stock -= 1;
|
||||
// A round reserved for return redirected to a waiting request is no
|
||||
// longer return cargo once the last one leaves the truck (#128).
|
||||
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
|
||||
self.sams[t].air_48n6_stock += displaced;
|
||||
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
|
||||
}
|
||||
@@ -288,6 +306,19 @@ impl Sim {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn an_empty_nearby_depot_explains_the_missing_typed_stock() {
|
||||
let mut sim = Sim::new(1);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 1.0)] {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
let error = sim.load_ground_round(1).unwrap_err();
|
||||
assert!(error.contains("RM48U: 0"));
|
||||
assert!(error.contains("/airdef ground-stock 1"));
|
||||
assert_eq!((sim.sams[0].ground_stock, sim.sams[1].ground_rounds, sim.sams[1].missiles), (0, 0, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_waits_for_capacity_and_ready_carrier_and_can_be_cancelled() {
|
||||
let mut sim = Sim::new(3);
|
||||
@@ -400,4 +431,170 @@ mod tests {
|
||||
assert!(!sim.sams[1].ground_request);
|
||||
}
|
||||
|
||||
/// Runs `step_supply`, jumping the truck beside its current job each tick so handovers
|
||||
/// resolve without a full drive (movement itself is covered by the lib round-trip tests).
|
||||
/// Fails after 200 ticks if `done` never holds.
|
||||
fn serve_until(sim: &mut Sim, truck: usize, mut done: impl FnMut(&Sim) -> bool) {
|
||||
let mut ok = false;
|
||||
for _ in 0..200 {
|
||||
if done(sim) { ok = true; break; }
|
||||
if let Some(id) = sim.sams[truck].job()
|
||||
&& let Some(j) = sim.sams.iter().position(|s| s.id == id)
|
||||
{
|
||||
sim.sams[truck].pos = sim.sams[j].pos;
|
||||
}
|
||||
sim.sams[truck].state = SamState::Search;
|
||||
sim.tick += 1;
|
||||
sim.step_supply(&mut Out::default());
|
||||
}
|
||||
assert!(ok, "condition not reached within 200 step_supply calls");
|
||||
}
|
||||
|
||||
/// #128: a return that is claimed but cannot proceed (here: the returning system is on the
|
||||
/// move) must not stop the free truck with job=None; an independent typed request is served.
|
||||
/// The claim stays, the rounds are conserved, and once the system stops the return completes.
|
||||
#[test]
|
||||
fn a_moving_return_claim_does_not_starve_an_independent_supply_request() {
|
||||
let mut sim = Sim::new(5);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
|
||||
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
|
||||
let b_id = sim.sams[b].id;
|
||||
sim.sams[depot].ground_stock = 2;
|
||||
sim.sams[a].ground_rounds = 1;
|
||||
sim.sams[a].missiles = 3;
|
||||
sim.sams[a].ground_return = true;
|
||||
sim.sams[b].ground_request = true;
|
||||
assert!(sim.order_move(a, DVec3::new(400.0, 70.0, 0.0)));
|
||||
// The free truck loads one RM48U at the depot and starts driving to B within 100 ticks;
|
||||
// before the fix it entered the return branch, found the moving A impossible and idled.
|
||||
let mut started = false;
|
||||
for _ in 0..100 {
|
||||
sim.tick += 1;
|
||||
sim.step_supply(&mut Out::default());
|
||||
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
|
||||
}
|
||||
assert!(started, "truck never started the delivery to B");
|
||||
// The claim and the rounds are untouched by the fallback.
|
||||
assert!(sim.sams[a].ground_return);
|
||||
assert_eq!(sim.sams[a].ground_rounds, 1);
|
||||
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock), (1, 1));
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
// Hand the round over to B; the full drive is exercised in the lib round-trip test.
|
||||
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
|
||||
assert!(!sim.sams[b].ground_request);
|
||||
assert_eq!((sim.sams[b].missiles, sim.sams[truck].air_48n6_stock), (3, 1));
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
// No request is left, so the truck holds its watch (a stock run aside): the pending
|
||||
// return still outranks it and the claim survives.
|
||||
for _ in 0..20 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
|
||||
assert!(sim.sams[a].ground_return);
|
||||
assert_eq!(sim.sams[a].ground_rounds, 1);
|
||||
// A stops: the actual return is picked up and driven back to the depot.
|
||||
sim.sams[a].state = SamState::Search;
|
||||
sim.sams[a].dest = None;
|
||||
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
|
||||
assert!(!sim.sams[a].ground_return);
|
||||
assert_eq!((sim.sams[a].ground_rounds, sim.sams[a].missiles), (0, 4));
|
||||
assert_eq!((sim.sams[truck].ground_stock, sim.sams[truck].air_48n6_stock), (1, 0));
|
||||
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
|
||||
assert!(!sim.sams[truck].return_cargo);
|
||||
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
}
|
||||
|
||||
/// #128 variant: the pickup is already claimed by another truck, so for this one the return
|
||||
/// is impossible; it must turn to the waiting request instead of idling with job=None. A
|
||||
/// dropped job (as after loading a save) is rebuilt, damaged trucks wait, and the repaired
|
||||
/// claiming truck keeps the priority of the now executable return over the request.
|
||||
#[test]
|
||||
fn a_return_claimed_by_another_truck_leaves_the_supply_to_the_second_one() {
|
||||
let mut sim = Sim::new(7);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 0.0), (SamKind::Tzm, 150.0)] {
|
||||
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
let (depot, a, b, t2, t1) = (0usize, 1usize, 2usize, 3usize, 4usize);
|
||||
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
|
||||
sim.sams[depot].ground_stock = 2;
|
||||
sim.sams[a].ground_rounds = 1;
|
||||
sim.sams[a].missiles = 3;
|
||||
sim.sams[a].ground_return = true;
|
||||
sim.sams[b].ground_request = true;
|
||||
// The first truck claimed A's pickup earlier; both trucks start damaged: nothing
|
||||
// moves, no round is lost, the claim waits.
|
||||
sim.sams[t1].job = Some(a_id);
|
||||
sim.sams[t1].comps.0[Part::Tracks as usize] = 0.0;
|
||||
sim.sams[t2].comps.0[Part::Tracks as usize] = 0.0;
|
||||
for _ in 0..30 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
|
||||
assert_eq!(sim.sams[t2].job(), None);
|
||||
assert_eq!((sim.sams[depot].ground_stock, sim.sams[b].ground_rounds), (2, 0));
|
||||
assert!(sim.sams[a].ground_return);
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
// Repaired, the second truck must not idle on the claimed return: depot first, then B.
|
||||
sim.sams[t2].comps.0[Part::Tracks as usize] = 1.0;
|
||||
let mut started = false;
|
||||
for _ in 0..100 {
|
||||
sim.tick += 1;
|
||||
sim.step_supply(&mut Out::default());
|
||||
if sim.sams[t2].job() == Some(b_id) { started = true; break; }
|
||||
}
|
||||
assert!(started, "second truck never started the delivery to B");
|
||||
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t2].ground_stock), (1, 1));
|
||||
assert!(sim.sams[a].ground_return, "claimed return must survive the fallback");
|
||||
// A save/load drops the job; the request and the cargo survive and the job is rebuilt.
|
||||
sim.sams[t2].job = None;
|
||||
serve_until(&mut sim, t2, |s| s.sams[t2].job() == Some(b_id));
|
||||
// The claiming truck is repaired: the executable return has priority over the request,
|
||||
// and the still-hauling second truck is not diverted from B.
|
||||
sim.sams[t1].comps.0[Part::Tracks as usize] = 1.0;
|
||||
serve_until(&mut sim, t1, |s| s.sams[t1].return_cargo);
|
||||
assert!(!sim.sams[a].ground_return);
|
||||
assert_eq!(sim.sams[a].ground_rounds, 0);
|
||||
assert_eq!(sim.sams[t2].job(), Some(b_id), "hauling truck must keep its supply job");
|
||||
// B gets its round; the displaced air round rides along.
|
||||
serve_until(&mut sim, t2, |s| s.sams[b].ground_rounds == 1);
|
||||
assert_eq!((sim.sams[b].missiles, sim.sams[t2].air_48n6_stock), (3, 1));
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
// And the picked-up return reaches the depot: everything is back except B's new round.
|
||||
serve_until(&mut sim, t1, |s| s.sams[depot].ground_stock == 2);
|
||||
assert!(!sim.sams[t1].return_cargo);
|
||||
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t1].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
|
||||
}
|
||||
|
||||
/// #128 variant: the route to the returning system is marked unreachable, so the return is
|
||||
/// impossible for now; the truck serves the request, and the return completes once the
|
||||
/// route is passable again and the system is still waiting with its claim.
|
||||
#[test]
|
||||
fn an_unreachable_route_falls_back_to_supply_until_it_expires() {
|
||||
let mut sim = Sim::new(9);
|
||||
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
|
||||
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
|
||||
}
|
||||
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
|
||||
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
|
||||
sim.sams[depot].ground_stock = 2;
|
||||
sim.sams[a].ground_rounds = 1;
|
||||
sim.sams[a].missiles = 3;
|
||||
sim.sams[a].ground_return = true;
|
||||
sim.sams[b].ground_request = true;
|
||||
sim.routes.unreachable.insert((sim.sams[truck].id, a_id), u64::MAX);
|
||||
let mut started = false;
|
||||
for _ in 0..100 {
|
||||
sim.tick += 1;
|
||||
sim.step_supply(&mut Out::default());
|
||||
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
|
||||
}
|
||||
assert!(started, "truck never started the delivery to B");
|
||||
assert!(sim.sams[a].ground_return, "claim must survive the blocked route");
|
||||
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
|
||||
// The route is passable again: the waiting claim is picked up and returned.
|
||||
sim.routes.unreachable.clear();
|
||||
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
|
||||
assert!(!sim.sams[a].ground_return);
|
||||
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
|
||||
assert!(!sim.sams[truck].return_cargo);
|
||||
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+339
-506
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -18,9 +18,9 @@ impl SamKind {
|
||||
Family::Truck => 10,
|
||||
}
|
||||
}
|
||||
/// A depot doesn't drive.
|
||||
/// A depot and a fixed optical post don't drive.
|
||||
pub fn mobile(self) -> bool {
|
||||
self != SamKind::Depot
|
||||
!matches!(self, SamKind::Depot | SamKind::Optical)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -123,9 +123,9 @@ pub fn look(kind: DroneKind, outcome: Outcome) -> (f32, u32, f32, &'static str)
|
||||
let life = (8 + (w as u32) / 2) * 9;
|
||||
let gain = 1.0 + 0.06 * w;
|
||||
match outcome {
|
||||
Outcome::DisabledFalling => (size, life, gain, "airdef:blast.air"),
|
||||
Outcome::Breakup => (size * 0.9, life, gain * 0.9, "airdef:blast.medium"),
|
||||
Outcome::AirDetonation => (size * 1.9, life * 8 / 5, gain * 1.5, "airdef:blast.big"),
|
||||
Outcome::DisabledFalling => (size, life, gain, super::catalog::sound::BLAST_AIR),
|
||||
Outcome::Breakup => (size * 0.9, life, gain * 0.9, super::catalog::sound::BLAST_MEDIUM),
|
||||
Outcome::AirDetonation => (size * 1.9, life * 8 / 5, gain * 1.5, super::catalog::sound::BLAST_BIG),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+263
-76
@@ -146,6 +146,7 @@ const LONGEST_WAIT: f64 = 12_000.0;
|
||||
pub(super) const WORK_PER_TICK: usize = 40_000;
|
||||
|
||||
/// The planner's grid over a raid: its corner, its cells' size and how many a side.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Grid {
|
||||
pub(super) min: DVec3,
|
||||
pub(super) cell: f64,
|
||||
@@ -157,22 +158,20 @@ impl Grid {
|
||||
let n = self.size;
|
||||
((((p.x - self.min.x) / self.cell) as i32).clamp(0, n - 1), (((p.z - self.min.z) / self.cell) as i32).clamp(0, n - 1))
|
||||
}
|
||||
fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
|
||||
pub(super) fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
|
||||
DVec3::new(self.min.x + (i as f64 + 0.5) * self.cell, y, self.min.z + (j as f64 + 0.5) * self.cell)
|
||||
}
|
||||
}
|
||||
|
||||
/// The cheapest way over `grid` from `from` to `to` by its prices (A*): points along it, `to` last.
|
||||
pub(super) fn plan_route(grid: &Grid, prices: &[f32], from: DVec3, to: DVec3) -> (Vec<DVec3>, usize) {
|
||||
plan_route_on(grid, prices, None, from, to)
|
||||
}
|
||||
|
||||
/// The land a route crosses: its height under each cell (NaN unknown), the climb a kind holds for long
|
||||
/// (rise a block), and the height above which the land forces a drone up from its low altitude.
|
||||
/// (rise a block), and the height above which the land forces a drone up from its low altitude. Unknown
|
||||
/// land costs `unknown` per cell on top of the open ground: zero for a plan routed over land it is still
|
||||
/// mapping, more than free for a replanned retarget (#127).
|
||||
pub(super) struct Relief<'a> {
|
||||
pub heights: &'a [f32],
|
||||
pub slope: f32,
|
||||
pub floor: f32,
|
||||
pub unknown: f32,
|
||||
}
|
||||
|
||||
/// [`plan_route`] over relief: a climb steeper than the kind holds is dear (a cliff or a ridge it would have to
|
||||
@@ -219,6 +218,9 @@ pub(super) fn plan_route_on(grid: &Grid, prices: &[f32], relief: Option<&Relief>
|
||||
price += (slope - r.slope) * 20.0 * len;
|
||||
}
|
||||
}
|
||||
} else if r.unknown > 0.0 {
|
||||
// Unmapped land is not free: the route prefers what the plan actually knew.
|
||||
price += len * r.unknown;
|
||||
}
|
||||
}
|
||||
let ng = g + price;
|
||||
@@ -278,6 +280,13 @@ impl Sim {
|
||||
return 0;
|
||||
}
|
||||
let smart = order.aim == Aim::Smart;
|
||||
// The planner's picture of the layout: one snapshot for the whole order. It is
|
||||
// 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).
|
||||
@@ -290,7 +299,7 @@ impl Sim {
|
||||
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
|
||||
let mut items = Vec::new();
|
||||
// A smart raid goes for the radars too (a few strikers each); the others pick as they always did.
|
||||
let radar_jobs = if smart { self.radar_strikes(&order.kinds) } else { Vec::new() };
|
||||
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &picture) } else { Vec::new() };
|
||||
let mut index = 0usize;
|
||||
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
|
||||
let spec = kind.spec();
|
||||
@@ -306,7 +315,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),
|
||||
None => self.choose_target(kind, object, order.aim, &picture, &leads),
|
||||
};
|
||||
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;
|
||||
@@ -314,6 +323,20 @@ impl Sim {
|
||||
// Where it starts is provisional: the site's pad, once the site is placed.
|
||||
let from = centre + DVec3::new(a.sin() * dist, height + self.rng.s() * 6.0, a.cos() * dist);
|
||||
let mut d = self.make_drone(kind, from, horizontal(aim - from), aim);
|
||||
// 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)));
|
||||
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 {
|
||||
d.intent = ew::Intent::Plan;
|
||||
d.aim = ew::Aim::point(self.tick);
|
||||
}
|
||||
let range = spec.ballistic.map_or(order.dist, |far| far.max(order.dist));
|
||||
let want = sites::want_index(&mut wants, centre, side, a, sites::SiteClass::of(kind), range, order.dist.max(120.0));
|
||||
let pad = wants[want].jobs;
|
||||
@@ -347,6 +370,11 @@ 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
|
||||
@@ -445,6 +473,7 @@ impl Sim {
|
||||
heights: &plan.heights,
|
||||
slope: (kind.climb_pitch().tan() * 0.5) as f32,
|
||||
floor: (aim.y + spec.clearance) as f32,
|
||||
unknown: 0.0,
|
||||
});
|
||||
let (r, cost) = plan_route_on(&plan.grid, &plan.prices[&kind], relief.as_ref(), from, aim);
|
||||
work += cost;
|
||||
@@ -480,6 +509,11 @@ impl Sim {
|
||||
}
|
||||
self.queue.push((now + wait.clamp(0.0, LONGEST_WAIT) as u64, d));
|
||||
}
|
||||
// Keep the land this plan was worked out over (#127): a retarget later is planned over the same
|
||||
// known relief, not over ground mapped since.
|
||||
if plan.smart && !plan.heights.is_empty() {
|
||||
self.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(plan.grid, std::mem::take(&mut plan.heights))));
|
||||
}
|
||||
self.wave = Some(WaveStats {
|
||||
kills: self.kills,
|
||||
hits: self.hits,
|
||||
@@ -500,6 +534,18 @@ impl Sim {
|
||||
self.plan.is_some()
|
||||
}
|
||||
|
||||
/// The plan's drones and the structured intent each was given (#127; tests and diagnostics).
|
||||
#[cfg(test)]
|
||||
pub(super) fn planned_intents(&self) -> Vec<(u32, ew::Intent)> {
|
||||
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.id, i.d.intent)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The plan's unit aims and their intent: the same list, keyed by what the drone goes for.
|
||||
#[cfg(test)]
|
||||
pub(super) fn planned_aims(&self) -> Vec<(u32, ew::Intent)> {
|
||||
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A drone ready to fly from `from`, not yet in the sky.
|
||||
pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone {
|
||||
let id = self.id();
|
||||
@@ -534,6 +580,8 @@ impl Sim {
|
||||
smart: false,
|
||||
nav: Nav::default(),
|
||||
err,
|
||||
intent: ew::Intent::Plan,
|
||||
aim: ew::Aim::point(0),
|
||||
hold: 0,
|
||||
pace: Pace::default(),
|
||||
}
|
||||
@@ -542,11 +590,27 @@ impl Sim {
|
||||
/// The strikes a smart raid sends at observed radars: for drones of `kinds` in order,
|
||||
/// the last observed place and id for those that go for one. Each radar
|
||||
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
|
||||
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)]) -> Vec<Option<(DVec3, u32)>> {
|
||||
let mut radars: Vec<(u32, DVec3)> = self.known_units().into_iter()
|
||||
.filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.alive() && s.kind == SamKind::Radar))
|
||||
/// 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
|
||||
.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)))
|
||||
.collect();
|
||||
radars.sort_by_key(|(id, _)| *id);
|
||||
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();
|
||||
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() {
|
||||
@@ -566,101 +630,108 @@ impl Sim {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
|
||||
/// point and the system's id.
|
||||
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim) -> (DVec3, Option<u32>) {
|
||||
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
|
||||
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
|
||||
/// What a drone goes for: an object, or (by its kind and the raid's aim) a unit. Returns the
|
||||
/// 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 {
|
||||
return (object, None);
|
||||
}
|
||||
let pick = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
|
||||
(!list.is_empty()).then(|| {
|
||||
let s = list[(r * list.len() as f64) as usize % list.len()];
|
||||
(s.pos, s.id)
|
||||
})
|
||||
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
|
||||
let c = list.get((r * list.len() as f64) as usize)?;
|
||||
Some((c.at, c.id))
|
||||
};
|
||||
let r = self.rng.f();
|
||||
let roll = self.rng.f();
|
||||
if aim == Aim::ObjectsAndSams {
|
||||
return if roll < 0.33 { pick(&alive, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
|
||||
return if roll < 0.33 { pick(picture, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
|
||||
}
|
||||
// Smart: each kind at what it is good against; what gave itself away first (a jamming
|
||||
// station, a radar, a system that fired).
|
||||
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
|
||||
// themselves away; the rest of the player's layout is not in its hands.
|
||||
let known = self.known_units();
|
||||
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, &known)).collect();
|
||||
let pick_known = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
|
||||
let s = *list.get((r * list.len() as f64) as usize)?;
|
||||
known.iter().find(|(id, _)| *id == s.id).map(|(_, pos)| (*pos, s.id))
|
||||
};
|
||||
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind == SamKind::Ew).collect();
|
||||
let known_ew: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect();
|
||||
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 {
|
||||
let s = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
|
||||
return (known.iter().find(|(id, _)| *id == s.id).unwrap().1, Some(s.id));
|
||||
let c = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
|
||||
return (c.at, Some(c.id));
|
||||
}
|
||||
// Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars
|
||||
// that feed them for the fast missiles.
|
||||
let guns: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind.armed() && s.kind.range() <= 300.0).collect();
|
||||
let long: Vec<&Sam> =
|
||||
alive.iter().copied().filter(|s| s.kind.range() >= 450.0 || s.kind == SamKind::Radar).collect();
|
||||
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 300.0).collect();
|
||||
let long: Vec<ew::Contact> =
|
||||
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
|
||||
let choice = match kind {
|
||||
DroneKind::Lancet if roll < 0.75 => pick_known(&guns, r).or_else(|| pick_known(&alive, r)),
|
||||
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_known(&long, r),
|
||||
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_known(&long, r),
|
||||
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_known(&alive, r),
|
||||
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)),
|
||||
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
|
||||
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
|
||||
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
|
||||
_ => None,
|
||||
};
|
||||
choice.map_or((object, None), |(p, id)| (p, Some(id)))
|
||||
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)
|
||||
}
|
||||
|
||||
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
|
||||
/// system sees it there (its radar's reach for it, the land) and can shoot it.
|
||||
#[cfg(test)]
|
||||
pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec<f32>, usize) {
|
||||
self.price_grid_on(grid, kind, None)
|
||||
}
|
||||
|
||||
/// The same over known land: a cell's drone flies `height` over the land there, not over the system's feet,
|
||||
/// so what a radar sees and what a hill hides follow the relief.
|
||||
/// The same over the picture this moment holds: a smart plan's own prices are priced on the
|
||||
/// picture the plan was ordered with (#127). Later observations change nothing here.
|
||||
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec<f32>, usize) {
|
||||
self.price_grid_known(grid, kind, land, &self.picture_of_defences())
|
||||
}
|
||||
|
||||
/// The same over a picture of the defences: a retarget is priced on the picture its target was
|
||||
/// chosen from, so the jobs of one adaptive tick do not each see a different world (#127). Every
|
||||
/// capability read here is the contact's published kind and the contact's own observations —
|
||||
/// never the unit's actual switch settings, damage, roles, link health or magazine.
|
||||
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, picture: &[ew::Contact]) -> (Vec<f32>, usize) {
|
||||
let mut cost = 0;
|
||||
let spec = kind.spec();
|
||||
let height = spec.clearance.max(6.0);
|
||||
let known_now = self.known_units();
|
||||
let n = grid.size;
|
||||
let now = self.tick;
|
||||
let mut prices = vec![1.0f32; (n * n) as usize];
|
||||
// Known jamming stations: drones that navigate by satellite keep away.
|
||||
if kind.jammable() {
|
||||
let known = self.known_units();
|
||||
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known.iter().any(|k| k.0 == s.id)) {
|
||||
let pos = known.iter().find(|(id, _)| *id == s.id).unwrap().1;
|
||||
let (ci, cj) = grid.index(pos);
|
||||
let r = (EW_RADIUS / grid.cell).ceil() as i32;
|
||||
for c in picture.iter().filter(|c| c.kind == SamKind::Ew) {
|
||||
let (ci, cj) = grid.index(c.at);
|
||||
let r = (ew::EW_RADIUS / grid.cell).ceil() as i32;
|
||||
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
|
||||
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
|
||||
if horizontal(grid.centre((i, j), pos.y) - pos).length() < EW_RADIUS {
|
||||
if horizontal(grid.centre((i, j), c.at.y) - c.at).length() < ew::EW_RADIUS {
|
||||
prices[(i * n + j) as usize] += 12.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only the systems the enemy knows of are priced in (#93): a hidden one is flown into.
|
||||
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0 && Self::enemy_knows(s, &known_now)) {
|
||||
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
|
||||
let sp = s.kind.spec();
|
||||
// Only the systems the picture holds are priced in (#93): a hidden one is flown into.
|
||||
for c in picture.iter().filter(|c| c.kind.spec().roles & spec.class.bit() != 0) {
|
||||
let pos = c.at;
|
||||
let sp = c.kind.spec();
|
||||
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
|
||||
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
|
||||
// A gun needs its own radar; a missile also flies on the tracks of any radar within data-link range.
|
||||
let own = sight::reach(s, kind, height);
|
||||
let net = self.sams.iter().filter_map(|r| {
|
||||
let at = known_now.iter().find(|(id, _)| *id == r.id)?.1;
|
||||
(r.id != s.id && at.distance(pos) <= sight::LINK).then(|| sight::reach(r, kind, height))
|
||||
}).fold(0.0, f64::max);
|
||||
// A gun needs its own radar; a missile also flies on the tracks of any radar the picture
|
||||
// holds within data-link range of the unit's observed place. What those radars are set to
|
||||
// (role, switch, damage) is not observable: a live contact of one is assumed to feed.
|
||||
let own = if c.believes_own_sensor(now) { ew::published_reach(c.kind, kind, height) } else { 0.0 };
|
||||
let net = picture
|
||||
.iter()
|
||||
.filter(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(pos) <= sight::LINK)
|
||||
.map(|d| ew::published_reach(d.kind, kind, height))
|
||||
.fold(0.0, f64::max);
|
||||
let (hi, gun) = (hi.min(own.max(net)), gun.min(own));
|
||||
let far = hi.max(gun);
|
||||
let at = pos + (sight::antenna(s) - s.pos);
|
||||
let horizon = (pos == s.pos).then(|| self.horizons.get(&s.id)).flatten();
|
||||
// Only the cells round it.
|
||||
let (ci, cj) = grid.index(pos);
|
||||
let r = (far / grid.cell).ceil() as i32 + 1;
|
||||
@@ -677,9 +748,6 @@ impl Sim {
|
||||
if !(missile || d < gun) {
|
||||
continue;
|
||||
}
|
||||
if horizon.is_some_and(|h| h.hides(at, p)) {
|
||||
continue;
|
||||
}
|
||||
prices[(i * n + j) as usize] += if missile { 30.0 } else { 18.0 };
|
||||
}
|
||||
}
|
||||
@@ -900,6 +968,11 @@ 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 {
|
||||
@@ -921,6 +994,21 @@ 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::*;
|
||||
@@ -975,20 +1063,27 @@ mod tests {
|
||||
fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
|
||||
let mut sim = Sim::new(121);
|
||||
let old = DVec3::new(100.0, 70.0, 200.0);
|
||||
let mut radar = Sam::new(1, SamKind::Radar, old, 0.0);
|
||||
radar.radar_on = false;
|
||||
let radar = Sam::new(1, SamKind::Radar, old, 0.0);
|
||||
sim.sams.push(radar);
|
||||
let kinds = [(DroneKind::Kh22, 8)];
|
||||
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
|
||||
let none = Vec::new();
|
||||
assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none));
|
||||
sim.tick = 20;
|
||||
sim.intel.revealed.push((1, old, sim.tick));
|
||||
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
|
||||
// The truth moving after the fix is not an observation: the strike goes to the seen place.
|
||||
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
|
||||
sim.tick = 40;
|
||||
let jobs = sim.radar_strikes(&kinds);
|
||||
let picture = sim.picture_of_defences();
|
||||
let jobs = sim.radar_strikes(&kinds, &picture);
|
||||
assert_eq!(jobs.iter().flatten().count(), 2);
|
||||
assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
|
||||
// An old contact is not worth a strike either.
|
||||
sim.tick = 3021;
|
||||
let picture = sim.picture_of_defences();
|
||||
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none), "a doubtful contact was struck");
|
||||
sim.tick = 6020;
|
||||
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
|
||||
let picture = sim.picture_of_defences();
|
||||
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -998,9 +1093,10 @@ mod tests {
|
||||
for (i, at) in [(-300.0, -200.0), (250.0, -250.0), (50.0, 300.0)].into_iter().enumerate() {
|
||||
let id = sim.id();
|
||||
let p = DVec3::new(at.0, 70.0, at.1);
|
||||
sim.sams.push(Sam::new(id, SamKind::Radar, p, i as f64));
|
||||
let sam = Sam::new(id, SamKind::Radar, p, i as f64);
|
||||
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
|
||||
sim.sams.push(sam);
|
||||
radars.push((id, p));
|
||||
sim.intel.revealed.push((id, p, sim.tick));
|
||||
}
|
||||
let ew = sim.id();
|
||||
sim.sams.push(Sam::new(ew, SamKind::Ew, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
||||
@@ -1036,7 +1132,7 @@ mod tests {
|
||||
// The first strikers are the fast ones.
|
||||
assert!(radars.iter().any(|(_, p)| aimed_at(&sim, *p).iter().any(|k| matches!(k, DroneKind::Kh22 | DroneKind::Zircon | DroneKind::Iskander | DroneKind::Kinzhal))));
|
||||
// The enemy has learnt of the jamming station and re-aims what it can: not these.
|
||||
sim.intel.revealed.push((ew, DVec3::new(0.0, 70.0, 0.0), sim.tick));
|
||||
sim.intel.observe(&sim.sams.iter().find(|s| s.id == ew).unwrap(), sim.tick, ew::Seen::Jamming);
|
||||
for _ in 0..160 {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
@@ -1044,6 +1140,97 @@ mod tests {
|
||||
check(&sim, "after adapting");
|
||||
}
|
||||
|
||||
/// The picture the planner works from: one contact per unit, the newest observation
|
||||
/// winning, the forgotten and the watched-dead out, the order deterministic — and it
|
||||
/// never reads the force itself, so a contact of a unit that no longer exists stays
|
||||
/// until its observations age out.
|
||||
#[test]
|
||||
fn picture_is_newest_per_unit_and_reads_no_truth() {
|
||||
let mut sim = Sim::new(9);
|
||||
let mut ids = Vec::new();
|
||||
for (i, kind) in [SamKind::S400, SamKind::Ew, SamKind::Radar, SamKind::Tor, SamKind::Patriot].into_iter().enumerate() {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0));
|
||||
ids.push(id);
|
||||
}
|
||||
sim.tick = 7000;
|
||||
let (a, b, c, d, e) = (ids[0], ids[1], ids[2], ids[3], ids[4]);
|
||||
// A long fight: repeated observations (newest wins), one unit watched dying, one
|
||||
// never seen, one id the force does not have, and one observation that aged out.
|
||||
for t in 0..200u64 {
|
||||
sim.intel.observe(&sim.sams[0], 1000 + t, ew::Seen::Launch);
|
||||
sim.intel.observe(&sim.sams[2], 1000 + t, ew::Seen::Emission);
|
||||
if t % 7 == 0 { sim.intel.observe(&sim.sams[1], 1000 + t, ew::Seen::Jamming); }
|
||||
if t % 11 == 0 { sim.intel.observe(&sim.sams[3], 1000 + t, ew::Seen::Launch); }
|
||||
if t % 13 == 0 {
|
||||
sim.intel.note(999_999, SamKind::Radar, DVec3::new(1.0, 70.0, 0.0), true, 1000 + t, ew::Seen::Emission);
|
||||
}
|
||||
}
|
||||
sim.intel.note(e, SamKind::Patriot, DVec3::new(15.0, 70.0, 0.0), true, 2, ew::Seen::Launch); // aged out at tick 7000
|
||||
// The EW station is watched dying by a strike: observed, and so out of the targets.
|
||||
sim.intel.outcome(b, false, sim.sams[1].pos, 1349);
|
||||
let picture = sim.picture_of_defences();
|
||||
let got: Vec<u32> = picture.iter().map(|c| c.id).collect();
|
||||
// a and c were both seen last at tick 1199 (tie: the newer id first); d at 1198; the
|
||||
// fake at 1195. The watched-dead b, the never-seen e and the aged-out are out.
|
||||
assert_eq!(got, vec![c, a, d, 999_999]);
|
||||
assert_eq!(picture[0].at, DVec3::new(200.0, 70.0, -50.0), "the observed place is the unit's own");
|
||||
assert_eq!(picture[0].seen, ew::Seen::Emission);
|
||||
assert_eq!(picture[1].kind, SamKind::S400);
|
||||
assert!(picture.iter().all(|c| c.id != b && c.id != e));
|
||||
assert_eq!(sim.picture_of_defences(), picture, "the picture is not deterministic");
|
||||
}
|
||||
|
||||
/// The reported Windows stop (#122): the second big order from the UI path, with a fat
|
||||
/// intel log and a large surviving force, must be accepted and launched like the first.
|
||||
/// (The old per-drone planner snapshot was correct but quadratic; its cost is pinned by
|
||||
/// the actual-WASM fuel measurements in docs/measurements/issue-122-ui-fuel.)
|
||||
#[test]
|
||||
fn a_second_smart_order_with_a_fat_intel_log_is_accepted_and_launched() {
|
||||
let mut sim = Sim::new(31);
|
||||
let mut ids = Vec::new();
|
||||
for i in 0..48 {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, [SamKind::S400, SamKind::Patriot, SamKind::Nasams, SamKind::Pantsir][i % 4], DVec3::new((i % 8 * 40) as f64, 70.0, (i / 8 * 40) as f64), 0.0));
|
||||
ids.push(id);
|
||||
}
|
||||
// A fought-off first raid leaves a long observation history: launches, emitting
|
||||
// radars, stations. Its entries sit in the past of the sim clock, like real ones.
|
||||
sim.tick = 4000;
|
||||
for t in 0..3000u64 {
|
||||
let sam = &sim.sams[(t as usize) % ids.len()];
|
||||
sim.intel.observe(sam, 1001 + t, if t % 3 == 0 { ew::Seen::Emission } else { ew::Seen::Launch });
|
||||
}
|
||||
sim.targets.push(DVec3::new(160.0, 70.0, 160.0));
|
||||
sim.target_health.push(100.0);
|
||||
let mut ground = Ground::default();
|
||||
let land = Land(|_, _| 64);
|
||||
let mut out = Out::default();
|
||||
for _ in 0..20 {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
let mut order = RaidOrder::mix(36, 300.0);
|
||||
order.aim = Aim::Smart;
|
||||
order.approach = Approach::AllSides;
|
||||
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
|
||||
let first = sim.order_raid(&order, &sim.targets.clone(), &mut out);
|
||||
assert_eq!(first, total);
|
||||
while sim.planning() {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
assert!(sim.queue.len() + sim.launched as usize >= total as usize, "the first order queued or launched every drone (queue {}, launched {})", sim.queue.len(), sim.launched);
|
||||
// The second order — the path that stopped the mod on Windows — is accepted too.
|
||||
let second = sim.order_raid(&order, &sim.targets.clone(), &mut out);
|
||||
assert_eq!(second, total);
|
||||
while sim.planning() {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
assert!(sim.queue.len() + sim.launched as usize >= 2 * total as usize, "both orders queued or launched their drones (queue {}, launched {})", sim.queue.len(), sim.launched);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systems_ready_together_send_one_missile_at_a_drone() {
|
||||
let mut sim = Sim::new(3);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,9 @@
|
||||
//! Raids are recorded for their replays: every drone's and interceptor's
|
||||
//! track (a point every other tick, falling wrecks included) and what
|
||||
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
|
||||
//! A recording starts with the first drone in the sky and ends when the sky
|
||||
//! has been clear a while; the last few are kept.
|
||||
//! 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).
|
||||
use super::*;
|
||||
|
||||
/// A system's pose at a moment of a recording.
|
||||
@@ -155,6 +156,8 @@ 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,
|
||||
@@ -185,6 +188,8 @@ 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 {
|
||||
@@ -381,6 +386,8 @@ 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)>,
|
||||
@@ -589,14 +596,38 @@ 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(|| {
|
||||
@@ -604,16 +635,21 @@ 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 + STEP < now {
|
||||
track.keys.push(SamKey { at: now - STEP, ..last });
|
||||
if last.at + self.sam_step < now {
|
||||
track.keys.push(SamKey { at: now - self.sam_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:
|
||||
@@ -799,8 +835,11 @@ 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()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
|
||||
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())
|
||||
{
|
||||
self.recordings += 1;
|
||||
self.rec = Some(Recording::new(self.recordings, self));
|
||||
}
|
||||
@@ -818,7 +857,13 @@ 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.
|
||||
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();
|
||||
// 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();
|
||||
self.begin_recording_if_active();
|
||||
let Some(r) = &mut self.rec else { return };
|
||||
r.note_tracks(&self.sams);
|
||||
@@ -832,7 +877,7 @@ impl Sim {
|
||||
if r.len % STEP == 0 {
|
||||
let now = r.len;
|
||||
r.note_sams(&self.sams, now);
|
||||
for d in &self.drones {
|
||||
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
|
||||
r.point(d.id, What::Drone(d.kind), d.pos);
|
||||
}
|
||||
for m in &self.missiles {
|
||||
@@ -1043,6 +1088,8 @@ 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,
|
||||
@@ -1062,6 +1109,19 @@ 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();
|
||||
@@ -1169,6 +1229,29 @@ 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();
|
||||
@@ -1230,7 +1313,22 @@ 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, kind: DroneKind::Shahed, pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false };
|
||||
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,
|
||||
};
|
||||
sim.sams[0].tracks.push(tr);
|
||||
r.note_tracks(&sim.sams);
|
||||
r.len = 1;
|
||||
@@ -1296,7 +1394,22 @@ 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, kind: DroneKind::Shahed, pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false });
|
||||
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,
|
||||
});
|
||||
}
|
||||
sim.sams.push(sam);
|
||||
}
|
||||
|
||||
+601
-22
@@ -54,9 +54,9 @@ fn network_launcher_must_contribute_to_route_risk() {
|
||||
// The planner prices only observed units; neither unit is known initially.
|
||||
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
|
||||
assert!(prices.iter().all(|p|*p==1.),"an unknown launcher must not be priced");
|
||||
sim.intel.revealed.push((sim.sams[0].id,DVec3::new(0.,70.,0.),0));
|
||||
// Both the launcher and its supporting radar have been observed.
|
||||
sim.intel.revealed.push((sim.sams[1].id,DVec3::new(0.,70.,0.),0));
|
||||
// The launcher is seen firing without a sensor of its own; the radar is fixed emitting.
|
||||
sim.intel.observe(&sim.sams[0],0,ew::Seen::Launch);
|
||||
sim.intel.observe(&sim.sams[1],0,ew::Seen::Emission);
|
||||
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
|
||||
assert!(prices.iter().any(|p|*p>1.),"armed launcher with a network radar is invisible to route risk");
|
||||
}
|
||||
@@ -131,11 +131,14 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
|
||||
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
||||
let goal = sim.id();
|
||||
sim.sams.push(Sam::new(goal, SamKind::Ew, DVec3::new(0.0, 70.0, 1000.0), 0.0));
|
||||
sim.intel.revealed.push((goal, DVec3::new(0.0, 70.0, 1000.0), 0));
|
||||
// Its first target, a system that is destroyed by now.
|
||||
sim.intel.observe(&sim.sams[2], 0, ew::Seen::Jamming);
|
||||
// Its first target: a system the picture watched die — seen firing, then the enemy's
|
||||
// munition watched the wreck. A unit destroyed unobserved would keep the drone coming.
|
||||
let id = sim.id();
|
||||
let mut wreck = Sam::new(id, SamKind::Patriot, DVec3::new(3000.0, 70.0, -1000.0), 0.0);
|
||||
sim.intel.observe(&wreck, 0, ew::Seen::Launch);
|
||||
wreck.health = 0.0;
|
||||
sim.intel.outcome(wreck.id, false, wreck.pos, 0);
|
||||
sim.sams.push(wreck);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 100.0, -1000.0), DVec3::Z, DVec3::new(3000.0, 70.0, -1000.0));
|
||||
sim.drones[0].pos = DVec3::new(0.0, 100.0, -1000.0);
|
||||
@@ -147,6 +150,276 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
|
||||
assert!(d.route.len() > 1, "no route after the new target: it flies straight through the defences");
|
||||
}
|
||||
|
||||
// #127: a mass retarget works its route jobs out over the following ticks. No drone is left without a
|
||||
// route by the budget, old safe routes are kept until their replacements are ready, and the queue never
|
||||
// grows or repeats a drone.
|
||||
#[cfg(test)]
|
||||
fn mass_retarget_sim(seed: u64) -> (Sim, HashMap<u32, Vec<DVec3>>, u32) {
|
||||
let mut sim = Sim::new(seed);
|
||||
for i in 0..8 {
|
||||
for j in 0..5 {
|
||||
let at = DVec3::new(-560.0 + i as f64 * 160.0, 70.0, -320.0 + j as f64 * 160.0);
|
||||
let id = sim.id();
|
||||
let sam = Sam::new(id, SamKind::S400, at, 0.0);
|
||||
// Every system is on the picture, its radar fixed emitting once.
|
||||
sim.intel.observe(&sam, 0, ew::Seen::Emission);
|
||||
sim.sams.push(sam);
|
||||
}
|
||||
}
|
||||
let mut old = HashMap::new();
|
||||
let mut empty = 0;
|
||||
for i in 0..40 {
|
||||
let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0);
|
||||
let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0));
|
||||
d.smart = true;
|
||||
d.route = vec![from, DVec3::new(1800.0, 70.0, 1800.0)];
|
||||
// The last drone starts with no route at all (a drone whose route was lost): its job must wait its
|
||||
// budget, not be dropped, and must give it a route in the end.
|
||||
if i == 39 {
|
||||
d.route.clear();
|
||||
empty = d.id;
|
||||
}
|
||||
old.insert(d.id, d.route.clone());
|
||||
sim.queue.push((0, d));
|
||||
}
|
||||
(sim, old, empty)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn flight_state(sim: &Sim) -> Vec<(u32, u64, u64, u64, Vec<(u64, u64, u64)>)> {
|
||||
sim.queue
|
||||
.iter()
|
||||
.map(|(_, d)| {
|
||||
let route = d.route.iter().map(|p| (p.x.to_bits(), p.y.to_bits(), p.z.to_bits())).collect();
|
||||
(d.id, d.target.x.to_bits(), d.target.y.to_bits(), d.target.z.to_bits(), route)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mass_retarget_finishes_its_route_jobs_over_the_budget() {
|
||||
let (mut sim, old, empty) = mass_retarget_sim(7);
|
||||
sim.tick = 40;
|
||||
sim.adapt();
|
||||
|
||||
let pending = sim.retarget_ids();
|
||||
assert!(!pending.is_empty(), "the budget planned all 40 routes: the test no longer covers the queue");
|
||||
assert_eq!(pending.len(), pending.iter().collect::<std::collections::HashSet<_>>().len(), "duplicate jobs");
|
||||
// Assignments are throttled too: one adaptive tick hands out a bounded number of new aims,
|
||||
// and the rest of the force is sent on the following adaptive ticks (#127).
|
||||
assert!(pending.len() <= super::ew::ASSIGN_PER_TICK, "one adaptive tick assigned {} drones", pending.len());
|
||||
for id in &pending {
|
||||
let d = &sim.queue.iter().find(|(_, d)| d.id == *id).unwrap().1;
|
||||
assert_eq!(&d.route, old.get(id).unwrap(), "an old safe route was replaced before the new one was ready");
|
||||
}
|
||||
|
||||
let mut left = pending.len();
|
||||
for _ in 0..400 {
|
||||
sim.tick += 1;
|
||||
sim.adapt();
|
||||
if sim.tick % 40 == 0 {
|
||||
// A new adaptive tick: more drones may be sent, still within the throttle.
|
||||
let now = sim.retarget_ids().len();
|
||||
assert!(now <= left + super::ew::ASSIGN_PER_TICK, "an adaptive tick assigned more than {} drones", super::ew::ASSIGN_PER_TICK);
|
||||
left = now;
|
||||
} else if left > 0 {
|
||||
assert!(sim.retargets.len() < left, "a budget tick made no progress: {left} jobs left");
|
||||
left = sim.retargets.len();
|
||||
}
|
||||
let still = sim.retarget_ids();
|
||||
assert!(
|
||||
// A drone the throttle has not sent yet is still on its own plan's route or has none to lose;
|
||||
// one already sent at a unit whose route is empty must have a job that will fill it.
|
||||
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || still.contains(&d.id) || d.aim.unit == 0),
|
||||
"a route is still empty with no job left to fill it"
|
||||
);
|
||||
}
|
||||
assert_eq!(sim.retargets.len(), 0, "route jobs were never finished");
|
||||
// No drone is left with an empty route for ever, and every new route ends at its aim. The drone
|
||||
// that started with no route at all got one too: its job waited for the budget, not for ever.
|
||||
for (_, d) in &sim.queue {
|
||||
assert!(!d.route.is_empty(), "a drone was left with no route");
|
||||
assert!(d.route.last().is_some_and(|p| p.distance(d.target) < 1e-6), "the new route does not end at the new aim");
|
||||
assert!(d.aim.unit != 0, "a drone was never sent at a unit");
|
||||
}
|
||||
let empty = sim.queue.iter().find(|(_, d)| d.id == empty).unwrap().1.clone();
|
||||
assert!(!empty.route.is_empty(), "the drone that started with no route never got one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mass_retarget_is_deterministic_and_never_duplicates_a_drone() {
|
||||
let (mut a, _, _) = mass_retarget_sim(11);
|
||||
let (mut b, _, _) = mass_retarget_sim(11);
|
||||
a.tick = 40;
|
||||
b.tick = 40;
|
||||
a.adapt();
|
||||
b.adapt();
|
||||
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the same seed left a different queue");
|
||||
assert_eq!(flight_state(&a), flight_state(&b), "the same seed planned different routes");
|
||||
for _ in 0..80 {
|
||||
a.adapt();
|
||||
b.adapt();
|
||||
let ids = a.retarget_ids();
|
||||
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a drone has two jobs");
|
||||
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the queues drifted apart");
|
||||
assert_eq!(flight_state(&a), flight_state(&b), "the routes drifted apart");
|
||||
if ids.is_empty() {
|
||||
break;
|
||||
}
|
||||
a.tick += 1;
|
||||
b.tick += 1;
|
||||
// Another adaptive tick while the queue is still being worked: a known aim must not enqueue again.
|
||||
if a.tick % 40 == 0 {
|
||||
a.adapt();
|
||||
b.adapt();
|
||||
let ids = a.retarget_ids();
|
||||
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a repeat adapt duplicated a job");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn relief_grid() -> Grid {
|
||||
Grid { min: DVec3::new(-2560.0, 0.0, -2560.0), cell: 32.0, size: 160 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn flat_relief() -> std::sync::Arc<super::ew::KnownRelief> {
|
||||
let g = relief_grid();
|
||||
std::sync::Arc::new(super::ew::KnownRelief::new(g, vec![70.0; (g.size * g.size) as usize]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn wall_relief() -> std::sync::Arc<super::ew::KnownRelief> {
|
||||
let g = relief_grid();
|
||||
let mut h = vec![70.0; (g.size * g.size) as usize];
|
||||
for i in 0..g.size {
|
||||
for j in 0..g.size {
|
||||
let x = g.min.x + (f64::from(i) + 0.5) * g.cell;
|
||||
let z = g.min.z + (f64::from(j) + 0.5) * g.cell;
|
||||
if (x + 1000.0).abs() < 80.0 && z.abs() < 420.0 {
|
||||
h[(i * g.size + j) as usize] = 1000.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sync::Arc::new(super::ew::KnownRelief::new(g, h))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn finish_retargets(sim: &mut Sim) {
|
||||
for _ in 0..200 {
|
||||
if sim.retargets.is_empty() {
|
||||
return;
|
||||
}
|
||||
sim.tick += 1;
|
||||
sim.adapt();
|
||||
}
|
||||
panic!("the retarget queue did not finish");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn retarget_route(sim: &Sim, id: u32) -> Vec<DVec3> {
|
||||
sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_retarget_keeps_its_relief_version_after_a_new_plan() {
|
||||
let flat = flat_relief();
|
||||
let wall = wall_relief();
|
||||
let outside = Grid { min: DVec3::new(3000.0, 0.0, 3000.0), cell: 32.0, size: 8 };
|
||||
assert!(flat.sampled_on(&outside).is_none(), "land outside the plan must be Unknown");
|
||||
let edge = Grid { min: DVec3::new(2500.0, 0.0, 2500.0), cell: 32.0, size: 8 };
|
||||
let edge_flat = flat.sampled_on(&edge).unwrap();
|
||||
assert!(edge_flat.iter().any(|h| h.is_nan()) && edge_flat.iter().any(|h| *h == 70.0));
|
||||
|
||||
let prepare = |relief| {
|
||||
let (mut sim, _, _) = mass_retarget_sim(7);
|
||||
sim.known_relief = Some(relief);
|
||||
sim.tick = 40;
|
||||
sim.adapt();
|
||||
sim
|
||||
};
|
||||
let mut control = prepare(flat.clone());
|
||||
let mut test = prepare(flat.clone());
|
||||
let id = *test.retarget_ids().last().unwrap();
|
||||
assert!(test.pending_relief(id).is_some(), "the chosen job is not waiting");
|
||||
// Another smart plan finishes while the job waits: the global snapshot is the wall now.
|
||||
test.known_relief = Some(wall.clone());
|
||||
let bits = |v: Option<Vec<f32>>| v.map(|x| x.into_iter().map(f32::to_bits).collect::<Vec<_>>());
|
||||
assert_eq!(
|
||||
bits(test.pending_relief(id).unwrap().sampled_on(&edge)),
|
||||
bits(flat.sampled_on(&edge)),
|
||||
"a pending job's relief changed with the global snapshot"
|
||||
);
|
||||
|
||||
finish_retargets(&mut control);
|
||||
finish_retargets(&mut test);
|
||||
assert_eq!(retarget_route(&control, id), retarget_route(&test, id), "the pending route used the newer relief");
|
||||
|
||||
let mut walled = prepare(wall);
|
||||
finish_retargets(&mut walled);
|
||||
assert_ne!(retarget_route(&control, id), retarget_route(&walled, id), "the test does not distinguish the relief versions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
|
||||
let flat = flat_relief();
|
||||
let mut sim = Sim::new(3);
|
||||
let start = DVec3::new(-1000.0, 100.0, 0.0);
|
||||
let aim = DVec3::new(1000.0, 70.0, 0.0);
|
||||
let threat = sim.id();
|
||||
let threat_at = DVec3::new(0.0, 70.0, 0.0);
|
||||
sim.sams.push(Sam::new(threat, SamKind::S400, threat_at, 0.0));
|
||||
let target = sim.id();
|
||||
sim.sams.push(Sam::new(target, SamKind::S400, aim, 0.0));
|
||||
let contact = |id: u32, at: DVec3| super::ew::Contact {
|
||||
id,
|
||||
kind: SamKind::S400,
|
||||
at,
|
||||
tick: 0,
|
||||
seen: super::ew::Seen::Emission,
|
||||
emission: Some(0),
|
||||
destroyed: None,
|
||||
launches: 0,
|
||||
};
|
||||
let known_all = std::sync::Arc::new(vec![contact(threat, threat_at), contact(target, aim)]);
|
||||
let known_target = std::sync::Arc::new(vec![contact(target, aim)]);
|
||||
// The picture holds both units: a job's unit is alive only while the picture believes in it.
|
||||
for c in known_all.iter() {
|
||||
sim.intel.note(c.id, c.kind, c.at, true, 0, super::ew::Seen::Emission);
|
||||
}
|
||||
|
||||
let mut add = |known: std::sync::Arc<Vec<super::ew::Contact>>, version: u64| -> u32 {
|
||||
let mut d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim);
|
||||
d.smart = true;
|
||||
d.err = DVec3::ZERO;
|
||||
d.target = aim;
|
||||
d.route = vec![start, aim];
|
||||
let id = d.id;
|
||||
sim.queue.push((0, d));
|
||||
sim.retargets.push_back(super::ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone())));
|
||||
id
|
||||
};
|
||||
// Same relief, same start and aim. Version 1 knows the threat on the direct line; version 2 does not.
|
||||
let first = add(known_all.clone(), 1);
|
||||
let other = add(known_target, 2);
|
||||
// A second job of version 1: it may reuse the first one's price grid and route.
|
||||
let same = add(known_all, 1);
|
||||
sim.tick = 1;
|
||||
for _ in 0..10 {
|
||||
if sim.retargets.is_empty() {
|
||||
break;
|
||||
}
|
||||
sim.adapt();
|
||||
sim.tick += 1;
|
||||
}
|
||||
assert!(sim.retargets.is_empty(), "the jobs were not finished");
|
||||
let route = |id| sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone();
|
||||
let (r1, r2, r3) = (route(first), route(other), route(same));
|
||||
assert_ne!(r1, r2, "jobs with different known snapshots shared a route");
|
||||
assert_eq!(r1, r3, "jobs of one knowledge version did not reuse their route cache");
|
||||
}
|
||||
|
||||
// #31: a big cache of fresh columns is not scanned on every answer
|
||||
#[test]
|
||||
fn big_ground_cache_is_swept_rarely() {
|
||||
@@ -717,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.
|
||||
struct Land<F: Fn(i32, i32) -> i32>(F);
|
||||
pub(super) 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))
|
||||
@@ -725,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.
|
||||
fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
|
||||
pub(super) 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);
|
||||
@@ -737,7 +1010,7 @@ fn ridge(rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
|
||||
ridge_at(300, rise, half)
|
||||
}
|
||||
|
||||
fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
|
||||
pub(super) 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))
|
||||
}
|
||||
|
||||
@@ -830,9 +1103,23 @@ 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
|
||||
}
|
||||
@@ -858,27 +1145,25 @@ 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;
|
||||
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.text.contains("за рельефом"));
|
||||
// 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("право на пуск: нет"));
|
||||
}
|
||||
(sim, seen, masked, told)
|
||||
(sim, seen, 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, masked, told) = shot(&hill);
|
||||
let (shut, seen, 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 land as the reason");
|
||||
assert!(told, "`why` never named the missing own fire plot");
|
||||
}
|
||||
|
||||
// A long-range system lofts over a low ridge (its interceptor does not hit it) but not over a mountain.
|
||||
@@ -895,7 +1180,7 @@ fn a_long_range_system_lofts_over_a_ridge_or_waits() {
|
||||
let sim = behind_ridge(&tall, 150, SamKind::IrisT, 230.0, ticks);
|
||||
assert_eq!(sim.sams[0].fired, 0, "no missile can climb a 400-block mountain at this range");
|
||||
assert_eq!(sim.tally.blocked + sim.tally.scrubbed, 0);
|
||||
told |= sim.why(0).iter().any(|c| !c.ok && c.text.contains("рельеф"));
|
||||
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("рельеф"));
|
||||
}
|
||||
assert!(told, "`why` never named the land as the reason");
|
||||
}
|
||||
@@ -1316,7 +1601,7 @@ fn raids_have_the_same_strike_accuracy_as_manual_launches() {
|
||||
let mut sim = Sim::new(3);
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Ew, DVec3::new(0.0, 70.0, 900.0), 0.0));
|
||||
sim.intel.revealed.push((id, DVec3::new(0.0, 70.0, 900.0), 0));
|
||||
sim.intel.observe(&sim.sams[0], 0, ew::Seen::Jamming);
|
||||
let order = RaidOrder { kinds: vec![(DroneKind::Zircon, 20)], approach: Approach::Sector, dist: 400.0, aim: Aim::Objects };
|
||||
sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut Out::default());
|
||||
// (The raid's launch sites need land the game has told of: a flat one is served.)
|
||||
@@ -1969,6 +2254,8 @@ fn spent_motor_has_less_maneuver_at_low_speed() {
|
||||
assert!(powered.x > coast.x && coast.x > 0.0, "{powered:?} {coast:?}");
|
||||
}
|
||||
|
||||
// #129: the staged launch's exact speed rules: gas-drag ejection with a floor, a spooled
|
||||
// departure that grows into full acceleration, full power at guidance, the coast drag after.
|
||||
#[test]
|
||||
fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
|
||||
let kind = MissileKind::M48n6;
|
||||
@@ -1984,8 +2271,300 @@ fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
|
||||
sim.step_missiles(&mut Ground::default(), &mut Out::default());
|
||||
sim.missiles[0].vel.length()
|
||||
};
|
||||
assert!((fly(0, 2.0) - 2.0 * 0.97).abs() < 1e-9, "cold ejection drag");
|
||||
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
|
||||
assert!((fly(0, spec.eject) - (spec.eject - spec.eject_drag)).abs() < 1e-9, "cold ejection drag");
|
||||
assert!((fly(spec.cold - 1, 0.1) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor near ignition");
|
||||
assert!((fly(0, 0.2) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor");
|
||||
let spool0 = 0.45 + 0.55 / f64::from(spec.boost);
|
||||
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel * spool0)).abs() < 1e-9, "ignition spool-up");
|
||||
assert!((fly(spec.cold + spec.boost - 1, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
|
||||
assert!((fly(spec.cold + kind.burn_ticks(), 2.0) - 2.0 * 0.995).abs() < 1e-9, "coast drag");
|
||||
assert!((fly(0, 0.2) - 0.4).abs() < 1e-9, "cold ejection minimum");
|
||||
}
|
||||
|
||||
// ---- #129: the staged cold launch. Ejection (unlit gas throw) → ignition where the round has
|
||||
// reached → departure (spool-up and course capture at a growing rate) → guidance at cold + boost.
|
||||
|
||||
/// Every cold-launched kind walks its stages in order; before ignition there is no motor voice,
|
||||
/// no flame and no steering, the speed is continuous across ignition, and the turn each tick
|
||||
/// never exceeds what the stage allows.
|
||||
#[test]
|
||||
fn cold_launch_stages_run_in_order_and_guidance_follows_ignition() {
|
||||
for &kind in &[MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT, MissileKind::M9m338] {
|
||||
let spec = kind.spec();
|
||||
let mut sim = Sim::new(120);
|
||||
// A still target well off the vertical: the tip-over has somewhere to turn.
|
||||
let target_pos = DVec3::new(300.0, 120.0, 300.0);
|
||||
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
|
||||
let (target, id) = (sim.drones[0].id, sim.id());
|
||||
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * spec.eject, target, sam: 999, age: 0, hold: 0,
|
||||
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
|
||||
sim.begin_recording_if_active();
|
||||
let mut previous_speed = spec.eject;
|
||||
let mut previous_dir = DVec3::Y;
|
||||
let mut saw_ignition = false;
|
||||
for age in 1..=(spec.cold + spec.boost + 2) {
|
||||
sim.tick += 1;
|
||||
let mut out = Out::default();
|
||||
sim.step_missiles(&mut Ground::default(), &mut out);
|
||||
let m = sim.missiles.iter().find(|m| m.id == id).unwrap_or_else(|| panic!("{kind:?} age {age}"));
|
||||
let speed = m.vel.length();
|
||||
let dir = m.vel.normalize_or(DVec3::Y);
|
||||
let voice = out.engines.iter().any(|e| e.key == (0x4000_0000 | id));
|
||||
let flame = out.particles.iter().any(|p| p.kind == "minecraft:flame");
|
||||
assert_eq!(voice, m.engine_lit(), "{kind:?} age {age}: the motor voice runs only when lit");
|
||||
if !m.engine_lit() {
|
||||
assert!(!voice && !flame, "{kind:?} age {age}: powered effects before ignition");
|
||||
assert!((speed - (previous_speed - spec.eject_drag)).abs() < 1e-9, "{kind:?} age {age}: ejection drag");
|
||||
assert!(dir.angle_between(DVec3::Y) < 1e-9, "{kind:?} age {age}: steering before ignition");
|
||||
} else if !saw_ignition {
|
||||
saw_ignition = true;
|
||||
assert_eq!(m.age, spec.cold + 1, "{kind:?}: ignition one tick after the ejection ends");
|
||||
assert!(speed > previous_speed - 1e-9, "{kind:?}: speed jumps down across ignition ({previous_speed} -> {speed})");
|
||||
assert!(out.sounds.iter().any(|s| s.0 == sound::LAUNCH_S400 || s.0 == sound::LAUNCH_S500), "{kind:?}: ignition sound");
|
||||
let events = sim.rec.as_ref().unwrap().scene.as_ref().unwrap().events();
|
||||
assert!(events.iter().any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { missile, .. } if missile == id)), "{kind:?}: ignition recorded");
|
||||
}
|
||||
let allowed = if spec.guided(m.age) {
|
||||
spec.turn
|
||||
} else if m.engine_lit() {
|
||||
// Departure: the rate grows into the full one; no snap at the boundary.
|
||||
spec.turn * (0.2 + 0.8 * spec.departure_ramp(m.age))
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
assert!(previous_dir.angle_between(dir) <= allowed + 1e-9, "{kind:?} age {age}: turned past the stage's rate");
|
||||
previous_speed = speed;
|
||||
previous_dir = dir;
|
||||
}
|
||||
assert!(saw_ignition, "{kind:?}: never lit");
|
||||
let m = sim.missiles.iter().find(|m| m.id == id).unwrap();
|
||||
assert!(m.vel.normalize().angle_between(DVec3::Y) > 0.3, "{kind:?}: still vertical after guidance started");
|
||||
}
|
||||
}
|
||||
|
||||
/// The invariant the issue is about: with a longer ignition delay the old `age >= boost` guidance
|
||||
/// would have switched on before the motor existed. Now guidance implies ignition, for every
|
||||
/// profile and every age, and the seeker opens with guidance, not with the raw boost counter.
|
||||
#[test]
|
||||
fn guidance_never_starts_before_ignition_for_any_profile() {
|
||||
for kind in [
|
||||
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
|
||||
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
|
||||
] {
|
||||
let spec = kind.spec();
|
||||
for age in 0..=spec.life.min(2000) {
|
||||
assert!(!spec.guided(age) || age > spec.cold, "{kind:?} age {age}: guidance before ignition (cold {})", spec.cold);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Across the whole staging the speed changes smoothly (no jumps beyond the stage's own drag or
|
||||
/// full acceleration) and the per-tick turn never exceeds the profile's rate, for every kind.
|
||||
/// A rocket's first powered tick is a throttled one for rail and cold launches alike (#129).
|
||||
#[test]
|
||||
fn launch_accel_and_turn_stay_continuous_for_every_interceptor() {
|
||||
for kind in [
|
||||
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
|
||||
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
|
||||
] {
|
||||
let spec = kind.spec();
|
||||
let mut sim = Sim::new(120);
|
||||
let target_pos = DVec3::new(400.0, 140.0, 400.0);
|
||||
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
|
||||
let (target, id) = (sim.drones[0].id, sim.id());
|
||||
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
|
||||
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * v0, target, sam: 999, age: 0, hold: 0,
|
||||
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
|
||||
let mut previous_speed = v0;
|
||||
let mut previous_dir = DVec3::Y;
|
||||
let mut first_power: Option<f64> = None;
|
||||
for _ in 0..120 {
|
||||
sim.tick += 1;
|
||||
sim.step_missiles(&mut Ground::default(), &mut Out::default());
|
||||
let Some(m) = sim.missiles.iter().find(|m| m.id == id) else { break };
|
||||
let speed = m.vel.length();
|
||||
let dir = m.vel.normalize_or(DVec3::Y);
|
||||
assert!(speed - previous_speed <= spec.accel + 1e-9, "{kind:?}: speed jumped up {previous_speed} -> {speed}");
|
||||
let allowed_down = spec.eject_drag + previous_speed * 0.005;
|
||||
assert!(speed >= previous_speed - allowed_down - 1e-9, "{kind:?}: speed jumped down {previous_speed} -> {speed}");
|
||||
assert!(previous_dir.angle_between(dir) <= spec.turn + 1e-9, "{kind:?}: turned past the profile's rate");
|
||||
if m.engine_lit() && first_power.is_none() {
|
||||
first_power = Some(speed - previous_speed);
|
||||
}
|
||||
previous_speed = speed;
|
||||
previous_dir = dir;
|
||||
}
|
||||
if spec.flame > 0.0 {
|
||||
let gain = first_power.unwrap_or_else(|| panic!("{kind:?}: the motor never lit"));
|
||||
let spooled = spec.accel * (0.45 + 0.55 / f64::from(spec.boost.max(1)));
|
||||
assert!(gain > 0.0 && gain <= spooled + 1e-9, "{kind:?}: the motor reached full thrust at once ({gain} > {spooled})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The electric P1-SUN is not a rocket: it keeps no flame, no powered smoke and its own voice.
|
||||
#[test]
|
||||
fn p1sun_stays_a_ramming_drone_without_a_plume() {
|
||||
let kind = MissileKind::P1sun;
|
||||
let spec = kind.spec();
|
||||
assert_eq!(spec.flame, 0.0);
|
||||
assert_eq!(spec.cold, 0);
|
||||
let mut sim = Sim::new(120);
|
||||
let target_pos = DVec3::new(200.0, 64.0, 0.0);
|
||||
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
|
||||
let (target, id) = (sim.drones[0].id, sim.id());
|
||||
sim.missiles.push(Missile { id, kind, pos: DVec3::ZERO, vel: DVec3::X * 0.8, target, sam: 999, age: 0, hold: 0,
|
||||
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
|
||||
for _ in 0..40 {
|
||||
sim.tick += 1;
|
||||
let mut out = Out::default();
|
||||
sim.step_missiles(&mut Ground::default(), &mut out);
|
||||
assert!(!out.particles.iter().any(|p| p.kind == "minecraft:flame"), "P1-SUN grew a rocket plume");
|
||||
if let Some(m) = sim.missiles.iter().find(|m| m.id == id) {
|
||||
assert!(m.engine_lit(), "the electric interceptor's motor state is wrong");
|
||||
let (event, _, _) = kind.engine_voice();
|
||||
assert!(out.engines.iter().any(|e| e.key == (0x4000_0000 | id) && e.event == event));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A real S-400 launch records the ejection and the ignition `cold` ticks apart; the replay's lit
|
||||
/// state follows the recorded ignition, so a seek across it shows one flame and one voice sequence.
|
||||
#[test]
|
||||
fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() {
|
||||
let mut sim = Sim::new(0x129);
|
||||
let sam = sim.id();
|
||||
sim.sams.push(Sam::new(sam, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0));
|
||||
sim.sams[0].cooldown = 0;
|
||||
let mut out = Out::default();
|
||||
sim.launch(DroneKind::Kh101, DVec3::new(0.0, 160.0, -600.0), DVec3::Z, DVec3::new(0.0, 64.0, 0.0), &mut out);
|
||||
let mut ground = Ground::default();
|
||||
for _ in 0..200 {
|
||||
// The firing system's own measurement, fresh this tick (as `why::radar_sees` feeds 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,
|
||||
})
|
||||
.collect();
|
||||
sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id));
|
||||
sim.sams[0].tracks.extend(tracks);
|
||||
let wanted = ground.take_wanted();
|
||||
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 64)).collect(), sim.tick);
|
||||
out = Out::default();
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.replays.iter().chain(sim.rec.iter()).flat_map(|r| r.scene.iter().flat_map(|s| s.events())).any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let rec = sim.rec.as_ref().or_else(|| sim.replays.last()).expect("a recording");
|
||||
let scene = rec.scene.as_ref().unwrap();
|
||||
let launch = scene.events().iter().find(|e| matches!(e.kind, record::SceneKind::MissileLaunch { .. })).expect("the ejection is recorded");
|
||||
let missile = match launch.kind { record::SceneKind::MissileLaunch { missile, .. } => missile, _ => unreachable!() };
|
||||
let spec = MissileKind::M48n6.spec();
|
||||
let ignition = rec.missile_ignition(missile).expect("the ignition is recorded");
|
||||
assert_eq!(ignition.at - launch.at, spec.cold, "ignition {} ticks after the ejection", spec.cold);
|
||||
let track = rec.track(missile).expect("the interceptor's track");
|
||||
for t in [ignition.at as f64 - 1.0, ignition.at as f64 - 0.1] {
|
||||
assert!(!rec.missile_is_lit(track, t, spec.cold), "lit before the recorded ignition at {t}");
|
||||
}
|
||||
for t in [ignition.at as f64, ignition.at as f64 + 5.0] {
|
||||
assert!(rec.missile_is_lit(track, t, spec.cold), "not lit at the recorded ignition ({t})");
|
||||
}
|
||||
assert!(!rec.missile_is_lit(track, ignition.at as f64 + spec.cold as f64 + f64::from(MissileKind::M48n6.burn_ticks()) + 2.0, spec.cold), "lit past the recorded burnout");
|
||||
}
|
||||
|
||||
/// The physical RM48U strike ejects unlit and slow, then lights at `EJECT_TICKS` where it has
|
||||
/// reached: no motor voice or flame before, one ignition sound at the hand-over.
|
||||
#[test]
|
||||
fn rm48u_strike_ejects_before_ignition_on_its_own_path() {
|
||||
use super::sites::testland::{Land, serve};
|
||||
use super::sites::{LaunchSite, SiteClass};
|
||||
use super::strike::{Estimate, Known, SiteState};
|
||||
use glam::DVec2;
|
||||
let land = Land(|_, _| 64);
|
||||
let mut sim = Sim::new(11);
|
||||
// A fixed site the strike needs no scouting for; its launches are queued far ahead, so a wave
|
||||
// boundary does not retire it while the test runs.
|
||||
let id = sim.sites.add(LaunchSite {
|
||||
id: 0, side: 0, sector: 0, bearing: 0.0, class: SiteClass::Ramp,
|
||||
pos: DVec3::new(0.0, 64.0, 400.0), range: 400.0, water: false,
|
||||
stock: 4, planned: 4, alive: true, next_free: 0, offmap: false,
|
||||
});
|
||||
for i in 0..4 {
|
||||
let site = sim.sites.get(id).unwrap().clone();
|
||||
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
||||
sim.sites.job(d.id, id);
|
||||
sim.queue.push((20_000 + u64::from(i), d));
|
||||
}
|
||||
sim.strikes.known.push(Known {
|
||||
site: id, class: SiteClass::Ramp, obs: Vec::new(),
|
||||
est: Some(Estimate { pos: DVec2::new(0.0, 400.0), radius: 5.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
|
||||
launches: 1, last: 0, state: SiteState::Active, aimed: false,
|
||||
});
|
||||
let carrier = sim.id();
|
||||
let mut sam = Sam::new(carrier, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0);
|
||||
sam.missiles = 2;
|
||||
sam.ground_rounds = 2;
|
||||
sam.cooldown = 0;
|
||||
sim.sams.push(sam);
|
||||
let mut out = Out::default();
|
||||
sim.order_strike(id, DVec3::ZERO, &mut out).unwrap();
|
||||
let (mut ground, mut heard_ignition) = (Ground::default(), 0);
|
||||
let mut saw_voice_before = false;
|
||||
let mut saw_flame_before = false;
|
||||
let mut rise = 0.0f64;
|
||||
let mut all_messages = Vec::new();
|
||||
for _ in 0..(launch::OPEN_TICKS as usize + strike::EJECT_TICKS as usize + 6) {
|
||||
serve(&mut ground, &land, sim.tick);
|
||||
out = Out::default();
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
all_messages.append(&mut out.messages);
|
||||
if let Some(f) = sim.strikes.flights.first() {
|
||||
let age = sim.tick - f.start;
|
||||
if age < strike::EJECT_TICKS {
|
||||
saw_voice_before |= out.engines.iter().any(|e| e.key == 0x7500_0000 + f.id * PARTS);
|
||||
saw_flame_before |= out.models.iter().any(|m| m.name == "airdef:flame" && m.id == 0x7500_0000 + f.id * PARTS + 1);
|
||||
rise = rise.max(f.pos.y - f.from.y);
|
||||
}
|
||||
if age == strike::EJECT_TICKS {
|
||||
heard_ignition = out.sounds.iter().filter(|s| s.0 == sound::LAUNCH_S400).count();
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(rise > 10.0, "the ejection rose only {rise} blocks");
|
||||
assert!(!saw_voice_before && !saw_flame_before, "powered effects during the unlit ejection");
|
||||
assert_eq!(heard_ignition, 1, "exactly one ignition sound at the hand-over: {all_messages:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blast_forget_removes_only_columns_in_the_same_square() {
|
||||
let mut ground = Ground::default();
|
||||
for x in -25..=25 {
|
||||
for z in -25..=25 {
|
||||
ground.known.insert((x, z), (x * 100 + z, 123));
|
||||
}
|
||||
}
|
||||
let before = ground.known.clone();
|
||||
let at = DVec3::new(-3.2, 70.0, 4.9);
|
||||
ground.forget(at, 8);
|
||||
let expected: std::collections::HashMap<_, _> = before.into_iter()
|
||||
.filter(|&((x, z), _)| (x + 4_i32).abs() > 8 || (z - 4_i32).abs() > 8)
|
||||
.collect();
|
||||
assert_eq!(ground.known, expected);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
|
||||
use super::sight::{swept, FORECAST_AGE};
|
||||
use super::battery::{Measure, RadarRole};
|
||||
use super::regress::{answer_land, ridge_at};
|
||||
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
|
||||
use super::*;
|
||||
|
||||
fn flat() -> (Ground, Out) {
|
||||
@@ -122,6 +124,9 @@ 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);
|
||||
}
|
||||
@@ -173,7 +178,7 @@ fn a_close_blast_can_leave_a_firing_but_immobile_system() {
|
||||
if s.alive() && s.part(Part::Tracks) <= 0.0 && s.part(Part::Launcher) > 0.0 && s.part(Part::Gun) > 0.0 {
|
||||
assert!(!sim.order_move(0, DVec3::new(300.0, 70.0, 0.0)), "failed running gear must refuse a march");
|
||||
assert!(why::missile_blocks(&sim.sams[0]) & why::LAUNCHER_DOWN == 0);
|
||||
assert!(sim.why(0).iter().any(|c| c.text.contains("ходовая отказала")), "{:?}", sim.why(0).iter().map(|c| &c.text).collect::<Vec<_>>());
|
||||
assert!(sim.why(0).iter().any(|c| matches!(c.reason, why::CheckReason::PartEffect(why::PartEffect::TracksFailed))), "{:?}", sim.why(0));
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
@@ -254,3 +259,526 @@ 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:?}");
|
||||
}
|
||||
|
||||
+225
-36
@@ -8,12 +8,15 @@
|
||||
//! (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 and how fast it went then, and when. Between measurements the track is
|
||||
//! 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
|
||||
//! 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 network passes tracks with the age of their measurement; relaying
|
||||
//! makes none of them fresher.
|
||||
//! 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.
|
||||
use super::*;
|
||||
|
||||
/// Rays round a radar, and blocks between the land's samples along them.
|
||||
@@ -24,14 +27,16 @@ 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.
|
||||
pub const FORECAST_AGE: u64 = 20;
|
||||
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
|
||||
const HORIZON: f64 = 35.0;
|
||||
pub(super) const HORIZON: f64 = 35.0;
|
||||
/// Anything this near is seen (and heard), whatever hides it.
|
||||
const NEAR: f64 = 24.0;
|
||||
pub(super) const NEAR: f64 = 24.0;
|
||||
|
||||
pub(super) struct Horizon {
|
||||
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
|
||||
@@ -87,7 +92,7 @@ pub(super) fn antenna(sam: &Sam) -> DVec3 {
|
||||
}
|
||||
|
||||
fn sensor_span(sam: &Sam) -> f64 {
|
||||
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
|
||||
sam.kind.spec().sensor * sam.radar_profile().reach
|
||||
}
|
||||
|
||||
/// How far a system's search radar reaches for this kind at `height` over the land:
|
||||
@@ -97,7 +102,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() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
|
||||
let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25);
|
||||
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
|
||||
radar.min(horizon).max(NEAR)
|
||||
}
|
||||
@@ -142,7 +147,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)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
|
||||
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach);
|
||||
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)));
|
||||
@@ -243,17 +248,31 @@ 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 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).
|
||||
/// 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).
|
||||
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,
|
||||
@@ -294,6 +313,25 @@ 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,
|
||||
@@ -310,16 +348,12 @@ impl Track {
|
||||
impl Sam {
|
||||
/// Fictional antenna height and scan characteristics for gameplay roles.
|
||||
pub(super) fn sensor_mast(&self) -> f64 {
|
||||
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
|
||||
self.kind.spec().mast + self.radar_profile().mast
|
||||
}
|
||||
pub(super) fn scan_profile(&self) -> Scan {
|
||||
if self.kind != SamKind::Radar { return self.kind.scan(); }
|
||||
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 },
|
||||
}
|
||||
let profile = self.radar_profile();
|
||||
Scan { period: profile.cycle, agile: profile.agile }
|
||||
}
|
||||
/// Ticks for its beam to go round (longer when the radar is damaged).
|
||||
pub(super) fn scan_ticks(&self) -> f64 {
|
||||
@@ -332,6 +366,10 @@ 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π,
|
||||
@@ -345,10 +383,18 @@ 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];
|
||||
if t.tick > mine.tick {
|
||||
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
|
||||
// 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)
|
||||
};
|
||||
let hits = mine.hits.max(t.hits);
|
||||
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
|
||||
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -358,6 +404,23 @@ 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.
|
||||
@@ -401,6 +464,7 @@ 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;
|
||||
@@ -408,6 +472,9 @@ 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() {
|
||||
@@ -415,7 +482,7 @@ impl Sim {
|
||||
}
|
||||
let rel = d.pos - at;
|
||||
let dist = rel.length();
|
||||
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
|
||||
if dist > spec.sensor * profile.reach.max(1.0) * 1.2 {
|
||||
continue;
|
||||
}
|
||||
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
|
||||
@@ -423,13 +490,36 @@ 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 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
|
||||
// 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)
|
||||
&& 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))) {
|
||||
@@ -446,17 +536,40 @@ impl Sim {
|
||||
if dist > NEAR && dice(seed, now, key, 0) >= p {
|
||||
continue;
|
||||
}
|
||||
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;
|
||||
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),
|
||||
};
|
||||
fresh.push(Track {
|
||||
id: d.id,
|
||||
kind: d.kind,
|
||||
pos: d.pos + noise,
|
||||
vel: d.vel,
|
||||
class,
|
||||
pos: measured,
|
||||
vel,
|
||||
tick: now,
|
||||
own_tick: now,
|
||||
source: sam.id,
|
||||
product,
|
||||
quality,
|
||||
own_product: product,
|
||||
own_quality: quality,
|
||||
ttl,
|
||||
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
|
||||
hits,
|
||||
locked,
|
||||
});
|
||||
}
|
||||
@@ -471,7 +584,7 @@ impl Sim {
|
||||
if now % 20 == 0 {
|
||||
for s in self.sams.iter().filter(|s| s.radar_up()) {
|
||||
if self.drones.iter().any(|d| d.alive() && d.pos.distance(s.pos) <= 1600.0) {
|
||||
self.intel.revealed.push((s.id, s.pos, now));
|
||||
self.intel.observe(s, now, ew::Seen::Emission);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,7 +595,37 @@ 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)));
|
||||
@@ -490,7 +633,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, ..*t });
|
||||
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -504,6 +647,9 @@ 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).
|
||||
@@ -520,8 +666,25 @@ 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, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
|
||||
.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,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
self.picture().into_values().collect()
|
||||
@@ -530,11 +693,12 @@ impl Sim {
|
||||
AirPicture { now, tracks, unaided }
|
||||
}
|
||||
|
||||
/// The freshest track of each drone any system holds: the air picture.
|
||||
/// 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.
|
||||
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 > b.tick) {
|
||||
if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) {
|
||||
best.insert(t.id, *t);
|
||||
}
|
||||
}
|
||||
@@ -612,3 +776,28 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
|
||||
// Game-scale values, not real weapon data; the catalog is the only copy.
|
||||
|
||||
/// Share of the old slew speed a launcher keeps when it has no rate of its own.
|
||||
const DRIVE_SCALE: f64 = 0.4;
|
||||
/// Ticks a drive takes to reach its top speed (and to stop from it).
|
||||
const DRIVE_RAMP: f64 = 8.0;
|
||||
const DRIVE_TRAINABLE: (f64, f64) = (0.12, 0.0);
|
||||
const DRIVE_VERTICAL: (f64, f64) = (0.15, 0.0);
|
||||
const DRIVE_OTHER: (f64, f64) = (0.05, 0.05);
|
||||
/// Ballistic flight's gravity, blocks a tick².
|
||||
const GRAVITY: f64 = 0.05;
|
||||
/// Height over the target where the Oreshnik's blocks release their submunitions.
|
||||
const BLOCK_SPLIT: f64 = 300.0;
|
||||
/// How near a depot a system reloads straight from it.
|
||||
const DEPOT_REACH: f64 = 60.0;
|
||||
/// How near a truck must come to hand a reload over, or to load up at a depot.
|
||||
const HANDOVER: f64 = 10.0;
|
||||
/// What a truck carries.
|
||||
const TRUCK_LOAD: u32 = 2;
|
||||
const STOCK_LIMIT: u32 = 1000000;
|
||||
|
||||
const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec {
|
||||
name: "Шахед-136",
|
||||
key: "shahed",
|
||||
model: "airdef:shahed",
|
||||
speed: 0.6,
|
||||
turn: 0.035,
|
||||
cruise: 45.0,
|
||||
clearance: 18.0,
|
||||
dive: 32.0,
|
||||
warhead: 3,
|
||||
scale: 1.3,
|
||||
engine: Engine::Prop(1.34, 1.0),
|
||||
decoy: false,
|
||||
stealth: 1.0,
|
||||
rcs: 0.3,
|
||||
sound: (sound::DRONE_SHAHED, 1.0, 48),
|
||||
class: Class::Drone,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_GERAN3: DroneSpec = DroneSpec {
|
||||
name: "Герань-3",
|
||||
key: "geran3",
|
||||
model: "airdef:geran3",
|
||||
speed: 1.6,
|
||||
turn: 0.03,
|
||||
cruise: 60.0,
|
||||
clearance: 18.0,
|
||||
dive: 50.0,
|
||||
warhead: 2,
|
||||
scale: 1.15,
|
||||
engine: Engine::Jet(0.34, 1.55, 1.0),
|
||||
decoy: false,
|
||||
stealth: 1.1,
|
||||
rcs: 0.4,
|
||||
sound: (sound::DRONE_GERAN3, 1.0, 40),
|
||||
class: Class::Jet,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_LANCET: DroneSpec = DroneSpec {
|
||||
name: "Ланцет-3",
|
||||
key: "lancet",
|
||||
model: "airdef:lancet",
|
||||
speed: 1.1,
|
||||
turn: 0.07,
|
||||
cruise: 25.0,
|
||||
clearance: 10.0,
|
||||
dive: 38.0,
|
||||
warhead: 1,
|
||||
scale: 0.9,
|
||||
engine: Engine::Prop(0.93, 0.55),
|
||||
decoy: false,
|
||||
stealth: 1.4,
|
||||
rcs: 0.08,
|
||||
sound: (sound::DRONE_LANCET, 1.0, 32),
|
||||
class: Class::Drone,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_GERBERA: DroneSpec = DroneSpec {
|
||||
name: "Гербера",
|
||||
key: "gerbera",
|
||||
model: "airdef:gerbera",
|
||||
speed: 0.5,
|
||||
turn: 0.04,
|
||||
cruise: 40.0,
|
||||
clearance: 15.0,
|
||||
dive: 30.0,
|
||||
warhead: 0,
|
||||
scale: 1.1,
|
||||
engine: Engine::Prop(1.03, 0.9),
|
||||
decoy: true,
|
||||
stealth: 0.9,
|
||||
rcs: 0.4,
|
||||
sound: (sound::DRONE_SHAHED, 1.3, 40),
|
||||
class: Class::Drone,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_KH101: DroneSpec = DroneSpec {
|
||||
name: "Х-101",
|
||||
key: "kh101",
|
||||
model: "airdef:kh101",
|
||||
speed: 2.4,
|
||||
turn: 0.025,
|
||||
cruise: 0.0,
|
||||
clearance: 12.0,
|
||||
dive: 26.0,
|
||||
warhead: 6,
|
||||
scale: 1.6,
|
||||
engine: Engine::Jet(-0.27, 1.4, 0.6),
|
||||
decoy: false,
|
||||
stealth: 1.5,
|
||||
rcs: 0.05,
|
||||
sound: (sound::DRONE_CRUISE, 1.0, 50),
|
||||
class: Class::Cruise,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_KALIBR: DroneSpec = DroneSpec {
|
||||
name: "Калибр",
|
||||
key: "kalibr",
|
||||
model: "airdef:kalibr",
|
||||
speed: 2.1,
|
||||
turn: 0.025,
|
||||
cruise: 0.0,
|
||||
clearance: 15.0,
|
||||
dive: 26.0,
|
||||
warhead: 5,
|
||||
scale: 1.5,
|
||||
engine: Engine::Jet(-0.2, 1.5, 0.6),
|
||||
decoy: false,
|
||||
stealth: 1.3,
|
||||
rcs: 0.15,
|
||||
sound: (sound::DRONE_CRUISE, 1.2, 50),
|
||||
class: Class::Cruise,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_KH22: DroneSpec = DroneSpec {
|
||||
name: "Х-22",
|
||||
key: "kh22",
|
||||
model: "airdef:kh22",
|
||||
speed: 4.0,
|
||||
turn: 0.03,
|
||||
cruise: 140.0,
|
||||
clearance: 40.0,
|
||||
dive: 150.0,
|
||||
warhead: 7,
|
||||
scale: 1.8,
|
||||
engine: Engine::Rocket(1.5, 1.3),
|
||||
decoy: false,
|
||||
stealth: 1.4,
|
||||
rcs: 1.0,
|
||||
sound: (sound::DRONE_ROCKET, 0.8, 46),
|
||||
class: Class::Supersonic,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_ZIRCON: DroneSpec = DroneSpec {
|
||||
name: "Циркон",
|
||||
key: "zircon",
|
||||
model: "airdef:zircon",
|
||||
speed: 5.5,
|
||||
turn: 0.025,
|
||||
cruise: 90.0,
|
||||
clearance: 30.0,
|
||||
dive: 110.0,
|
||||
warhead: 6,
|
||||
scale: 1.4,
|
||||
engine: Engine::Rocket(1.5, 1.1),
|
||||
decoy: false,
|
||||
stealth: 2.0,
|
||||
rcs: 0.4,
|
||||
sound: (sound::DRONE_ROCKET, 1.35, 46),
|
||||
class: Class::Supersonic,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S400,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_ISKANDER: DroneSpec = DroneSpec {
|
||||
name: "Искандер-М",
|
||||
key: "iskander",
|
||||
model: "airdef:iskander",
|
||||
speed: 5.0,
|
||||
turn: 0.04,
|
||||
cruise: 0.0,
|
||||
clearance: 0.0,
|
||||
dive: 0.0,
|
||||
warhead: 8,
|
||||
scale: 1.8,
|
||||
engine: Engine::Rocket(1.5, 1.6),
|
||||
decoy: false,
|
||||
stealth: 1.6,
|
||||
rcs: 0.6,
|
||||
sound: (sound::DRONE_ROCKET, 0.7, 46),
|
||||
class: Class::Ballistic,
|
||||
ballistic: Some(1000.0),
|
||||
launch_sound: sound::LAUNCH_S500,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_KINZHAL: DroneSpec = DroneSpec {
|
||||
name: "Кинжал",
|
||||
key: "kinzhal",
|
||||
model: "airdef:kinzhal",
|
||||
speed: 7.5,
|
||||
turn: 0.03,
|
||||
cruise: 0.0,
|
||||
clearance: 0.0,
|
||||
dive: 0.0,
|
||||
warhead: 8,
|
||||
scale: 1.7,
|
||||
engine: Engine::Rocket(1.5, 1.5),
|
||||
decoy: false,
|
||||
stealth: 2.2,
|
||||
rcs: 0.5,
|
||||
sound: (sound::DRONE_ROCKET, 0.6, 46),
|
||||
class: Class::Ballistic,
|
||||
ballistic: Some(1500.0),
|
||||
launch_sound: sound::LAUNCH_S500,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_ORESHNIK: DroneSpec = DroneSpec {
|
||||
name: "Орешник",
|
||||
key: "oreshnik",
|
||||
model: "airdef:iskander",
|
||||
speed: 9.0,
|
||||
turn: 0.0,
|
||||
cruise: 0.0,
|
||||
clearance: 0.0,
|
||||
dive: 0.0,
|
||||
warhead: 0,
|
||||
scale: 2.6,
|
||||
engine: Engine::Rocket(1.5, 2.4),
|
||||
decoy: false,
|
||||
stealth: 3.0,
|
||||
rcs: 2.0,
|
||||
sound: (sound::DRONE_ROCKET, 0.5, 46),
|
||||
class: Class::Ballistic,
|
||||
ballistic: Some(2600.0),
|
||||
launch_sound: sound::LAUNCH_S500,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_ORESHNIKBLOCK: DroneSpec = DroneSpec {
|
||||
name: "Орешник: блок",
|
||||
key: "oreshnik_block",
|
||||
model: "airdef:reentry",
|
||||
speed: 9.0,
|
||||
turn: 0.0,
|
||||
cruise: 0.0,
|
||||
clearance: 0.0,
|
||||
dive: 0.0,
|
||||
warhead: 4,
|
||||
scale: 1.6,
|
||||
engine: Engine::Rocket(1.0, 1.0),
|
||||
decoy: false,
|
||||
stealth: 3.5,
|
||||
rcs: 0.4,
|
||||
sound: (sound::DRONE_BALLISTIC, 0.8, 9999),
|
||||
class: Class::Ballistic,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S500,
|
||||
};
|
||||
|
||||
const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec {
|
||||
name: "Орешник: суббоеприпас",
|
||||
key: "oreshnik_sub",
|
||||
model: "airdef:reentry",
|
||||
speed: 9.0,
|
||||
turn: 0.05,
|
||||
cruise: 0.0,
|
||||
clearance: 0.0,
|
||||
dive: 0.0,
|
||||
warhead: 3,
|
||||
scale: 1.1,
|
||||
engine: Engine::Rocket(1.0, 1.0),
|
||||
decoy: false,
|
||||
stealth: 4.0,
|
||||
rcs: 0.08,
|
||||
sound: (sound::DRONE_BALLISTIC, 1.0, 9999),
|
||||
class: Class::Ballistic,
|
||||
ballistic: None,
|
||||
launch_sound: sound::LAUNCH_S500,
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
|
||||
model: "airdef:pac3",
|
||||
speed: 5.5,
|
||||
accel: 0.35,
|
||||
turn: 0.3,
|
||||
boost: 8,
|
||||
cold: 0,
|
||||
eject: 0.0,
|
||||
eject_drag: 0.0,
|
||||
pk: 0.9,
|
||||
fuse: 4.0,
|
||||
life: 240,
|
||||
scale: 1.0,
|
||||
flame: 1.0,
|
||||
rear: 28.0,
|
||||
seeker: 110.0,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 1.0),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec {
|
||||
model: "airdef:m57e6",
|
||||
speed: 5.0,
|
||||
accel: 0.5,
|
||||
turn: 0.32,
|
||||
boost: 5,
|
||||
cold: 0,
|
||||
eject: 0.0,
|
||||
eject_drag: 0.0,
|
||||
pk: 0.82,
|
||||
fuse: 3.0,
|
||||
life: 160,
|
||||
scale: 0.85,
|
||||
flame: 0.65,
|
||||
rear: 28.0,
|
||||
seeker: 0.0,
|
||||
launch_sound: sound::LAUNCH_PANTSIR,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 1.12),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
|
||||
model: "airdef:m48n6",
|
||||
speed: 7.0,
|
||||
accel: 0.5,
|
||||
turn: 0.22,
|
||||
boost: 8,
|
||||
cold: 20,
|
||||
eject: 2.4,
|
||||
eject_drag: 0.07,
|
||||
pk: 0.9,
|
||||
fuse: 5.0,
|
||||
life: 300,
|
||||
scale: 1.5,
|
||||
flame: 1.4,
|
||||
rear: 30.0,
|
||||
seeker: 120.0,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 0.88),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
|
||||
model: "airdef:m77n6",
|
||||
speed: 9.0,
|
||||
accel: 0.6,
|
||||
turn: 0.22,
|
||||
boost: 8,
|
||||
cold: 24,
|
||||
eject: 2.6,
|
||||
eject_drag: 0.07,
|
||||
pk: 0.95,
|
||||
fuse: 6.0,
|
||||
life: 320,
|
||||
scale: 1.7,
|
||||
flame: 1.6,
|
||||
rear: 32.0,
|
||||
seeker: 120.0,
|
||||
launch_sound: sound::LAUNCH_S500_EJECT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 0.8),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec {
|
||||
model: "airdef:irist_missile",
|
||||
speed: 7.0,
|
||||
accel: 0.5,
|
||||
turn: 0.35,
|
||||
boost: 6,
|
||||
cold: 8,
|
||||
eject: 1.8,
|
||||
eject_drag: 0.1,
|
||||
pk: 0.9,
|
||||
fuse: 4.0,
|
||||
life: 260,
|
||||
scale: 0.95,
|
||||
flame: 0.9,
|
||||
rear: 28.0,
|
||||
seeker: 90.0,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec {
|
||||
model: "airdef:amraam_missile",
|
||||
speed: 6.0,
|
||||
accel: 0.45,
|
||||
turn: 0.3,
|
||||
boost: 6,
|
||||
cold: 0,
|
||||
eject: 0.0,
|
||||
eject_drag: 0.0,
|
||||
pk: 0.85,
|
||||
fuse: 4.0,
|
||||
life: 260,
|
||||
scale: 0.9,
|
||||
flame: 0.9,
|
||||
rear: 28.0,
|
||||
seeker: 130.0,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec {
|
||||
model: "airdef:m48n6",
|
||||
speed: 6.5,
|
||||
accel: 0.5,
|
||||
turn: 0.25,
|
||||
boost: 8,
|
||||
cold: 0,
|
||||
eject: 0.0,
|
||||
eject_drag: 0.0,
|
||||
pk: 0.85,
|
||||
fuse: 5.0,
|
||||
life: 300,
|
||||
scale: 1.1,
|
||||
flame: 1.2,
|
||||
rear: 32.0,
|
||||
seeker: 90.0,
|
||||
launch_sound: sound::LAUNCH_PATRIOT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 0.9),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec {
|
||||
model: "airdef:m57e6",
|
||||
speed: 5.5,
|
||||
accel: 0.6,
|
||||
turn: 0.4,
|
||||
boost: 4,
|
||||
cold: 8,
|
||||
eject: 1.6,
|
||||
eject_drag: 0.1,
|
||||
pk: 0.9,
|
||||
fuse: 3.0,
|
||||
life: 160,
|
||||
scale: 1.0,
|
||||
flame: 0.8,
|
||||
rear: 28.0,
|
||||
seeker: 70.0,
|
||||
launch_sound: sound::LAUNCH_S400_EJECT,
|
||||
voice: (sound::MISSILE_FLIGHT, 1.0, 1.15),
|
||||
};
|
||||
|
||||
const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec {
|
||||
model: "airdef:p1sun",
|
||||
speed: 2.8,
|
||||
accel: 0.12,
|
||||
turn: 0.3,
|
||||
boost: 4,
|
||||
cold: 0,
|
||||
eject: 0.0,
|
||||
eject_drag: 0.0,
|
||||
pk: 0.8,
|
||||
fuse: 3.0,
|
||||
life: 900,
|
||||
scale: 0.8,
|
||||
flame: 0.0,
|
||||
rear: 10.0,
|
||||
seeker: 60.0,
|
||||
launch_sound: sound::DRONE_LANCET,
|
||||
voice: (sound::DRONE_LANCET, 0.8, 1.6),
|
||||
};
|
||||
|
||||
impl DroneKind {
|
||||
/// Its row of numbers from `catalog/specs.json`.
|
||||
pub fn spec(self) -> &'static DroneSpec {
|
||||
match self {
|
||||
DroneKind::Shahed => &DRONE_SPEC_SHAHED,
|
||||
DroneKind::Geran3 => &DRONE_SPEC_GERAN3,
|
||||
DroneKind::Lancet => &DRONE_SPEC_LANCET,
|
||||
DroneKind::Gerbera => &DRONE_SPEC_GERBERA,
|
||||
DroneKind::Kh101 => &DRONE_SPEC_KH101,
|
||||
DroneKind::Kalibr => &DRONE_SPEC_KALIBR,
|
||||
DroneKind::Kh22 => &DRONE_SPEC_KH22,
|
||||
DroneKind::Zircon => &DRONE_SPEC_ZIRCON,
|
||||
DroneKind::Iskander => &DRONE_SPEC_ISKANDER,
|
||||
DroneKind::Kinzhal => &DRONE_SPEC_KINZHAL,
|
||||
DroneKind::Oreshnik => &DRONE_SPEC_ORESHNIK,
|
||||
DroneKind::OreshnikBlock => &DRONE_SPEC_ORESHNIKBLOCK,
|
||||
DroneKind::OreshnikSub => &DRONE_SPEC_ORESHNIKSUB,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MissileKind {
|
||||
fn spec(self) -> &'static MissileSpec {
|
||||
match self {
|
||||
MissileKind::Pac3 => &MISSILE_SPEC_PAC3,
|
||||
MissileKind::M57e6 => &MISSILE_SPEC_M57E6,
|
||||
MissileKind::M48n6 => &MISSILE_SPEC_M48N6,
|
||||
MissileKind::M77n6 => &MISSILE_SPEC_M77N6,
|
||||
MissileKind::IrisT => &MISSILE_SPEC_IRIST,
|
||||
MissileKind::Amraam => &MISSILE_SPEC_AMRAAM,
|
||||
MissileKind::M9m317 => &MISSILE_SPEC_M9M317,
|
||||
MissileKind::M9m338 => &MISSILE_SPEC_M9M338,
|
||||
MissileKind::P1sun => &MISSILE_SPEC_P1SUN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Save keys by kind; a rename needs an explicit migration.
|
||||
#[cfg(test)]
|
||||
pub(super) const DRONE_SPEC_KEYS: [(DroneKind, &str); 13] = [
|
||||
(DroneKind::Shahed, "shahed"),
|
||||
(DroneKind::Geran3, "geran3"),
|
||||
(DroneKind::Lancet, "lancet"),
|
||||
(DroneKind::Gerbera, "gerbera"),
|
||||
(DroneKind::Kh101, "kh101"),
|
||||
(DroneKind::Kalibr, "kalibr"),
|
||||
(DroneKind::Kh22, "kh22"),
|
||||
(DroneKind::Zircon, "zircon"),
|
||||
(DroneKind::Iskander, "iskander"),
|
||||
(DroneKind::Kinzhal, "kinzhal"),
|
||||
(DroneKind::Oreshnik, "oreshnik"),
|
||||
(DroneKind::OreshnikBlock, "oreshnik_block"),
|
||||
(DroneKind::OreshnikSub, "oreshnik_sub"),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const MISSILE_SPEC_MODELS: [(MissileKind, &str); 9] = [
|
||||
(MissileKind::Pac3, "airdef:pac3"),
|
||||
(MissileKind::M57e6, "airdef:m57e6"),
|
||||
(MissileKind::M48n6, "airdef:m48n6"),
|
||||
(MissileKind::M77n6, "airdef:m77n6"),
|
||||
(MissileKind::IrisT, "airdef:irist_missile"),
|
||||
(MissileKind::Amraam, "airdef:amraam_missile"),
|
||||
(MissileKind::M9m317, "airdef:m48n6"),
|
||||
(MissileKind::M9m338, "airdef:m57e6"),
|
||||
(MissileKind::P1sun, "airdef:p1sun"),
|
||||
];
|
||||
@@ -25,7 +25,16 @@ use glam::DVec2;
|
||||
/// Minecraft presentation profile; neither dimensions nor timing reproduce a real weapon.
|
||||
pub const ROUND_MODEL: &str = "airdef:rm48u";
|
||||
pub const ROUND_SCALE: f64 = 1.5;
|
||||
pub const EJECT_TICKS: u64 = 5;
|
||||
/// Ticks the gas throw takes before the motor lights: the same staged cold launch as the
|
||||
/// interceptor's `cold` (#129), so a physical strike shows the unlit ejection too.
|
||||
pub const EJECT_TICKS: u64 = 20;
|
||||
|
||||
/// The unlit ejection's height at flight age `age`: a gas throw of 2.2 blocks a tick with a
|
||||
/// linear drag of 0.09 a tick², integrated (game scale, like the interceptor's `eject`).
|
||||
fn eject_rise(age: u64) -> f64 {
|
||||
let a = age as f64;
|
||||
(2.2 * a - 0.045 * a * a).max(0.0)
|
||||
}
|
||||
|
||||
/// Shared live/replay appearance, including the unlit cold-ejection phase.
|
||||
pub(super) fn round_visual(out: &mut Out, id: u32, pos: DVec3, rot: DQuat, lit: bool) {
|
||||
@@ -581,10 +590,18 @@ impl Sim {
|
||||
let end = DVec3::new(f.land.x, below.unwrap_or(f.from.y), f.land.y);
|
||||
let t = ((now - f.start) as f64 / (f.arrive - f.start).max(1) as f64).clamp(0.0, 1.0);
|
||||
let age = now.saturating_sub(f.start);
|
||||
let arc = |t: f64| TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt();
|
||||
let planned = if f.carrier.is_some() && age < EJECT_TICKS {
|
||||
f.from + DVec3::Y * (age as f64 * 0.7)
|
||||
// The unlit gas throw: it rises and slows, no motor yet (#129).
|
||||
f.from + DVec3::Y * eject_rise(age)
|
||||
} else if f.carrier.is_some() {
|
||||
// From where the ejection reached, onto the cruise arc: the plan is continuous
|
||||
// at ignition, and the flight time counted at the order includes the ejection.
|
||||
let top = f.from + DVec3::Y * eject_rise(EJECT_TICKS);
|
||||
let t = ((age - EJECT_TICKS) as f64 / (f.arrive - f.start).saturating_sub(EJECT_TICKS).max(1) as f64).clamp(0.0, 1.0);
|
||||
top.lerp(end, t) + DVec3::Y * arc(t)
|
||||
} else {
|
||||
f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt())
|
||||
f.from.lerp(end, t) + DVec3::Y * arc(t)
|
||||
};
|
||||
let from = f.pos;
|
||||
// Time spent waiting for world data must not accumulate into a faster step.
|
||||
@@ -660,7 +677,7 @@ impl Sim {
|
||||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
|
||||
}
|
||||
if f.carrier.is_some() {
|
||||
if age == EJECT_TICKS { out.sound("airdef:launch.s400", pos, 1.0, 1.0); }
|
||||
if age == EJECT_TICKS { out.sound(super::catalog::sound::LAUNCH_S400, pos, 1.0, 1.0); }
|
||||
if age >= EJECT_TICKS {
|
||||
let (event, gain, pitch) = MissileKind::M48n6.engine_voice();
|
||||
out.engine(id, event, pos, pos - from, gain, pitch, false);
|
||||
@@ -694,7 +711,7 @@ impl Sim {
|
||||
/// Reserve a physical carrier and its cell; ammunition is spent only on ejection.
|
||||
pub fn order_strike(&mut self, id: u32, _from: DVec3, _out: &mut Out) -> Result<String, String> {
|
||||
let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена"))?;
|
||||
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: нужна разведка")?;
|
||||
let est = k.est.filter(|e| e.fix).ok_or("Место ПУ неизвестно: РЛС должна увидеть сам пуск. /airdef sites — состояние разведки")?;
|
||||
if matches!(k.state, SiteState::Destroyed(_)) { return Err("ПУ уже уничтожена".into()); }
|
||||
if self.strikes.flights.iter().any(|f| f.site == id) || self.strikes.pending.iter().any(|p| p.site == id) {
|
||||
return Err("По этой ПУ ракета уже готовится или в полёте".into());
|
||||
@@ -750,16 +767,19 @@ impl Sim {
|
||||
sam.launched = 12;
|
||||
sam.fired += 1;
|
||||
let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length();
|
||||
self.intel.revealed.push((p.carrier, sam.pos, self.tick));
|
||||
// The launch betrays the carrier: the enemy saw it fire, no more than that.
|
||||
self.intel.observe(&self.sams[i], self.tick, ew::Seen::Launch);
|
||||
self.strikes.fired += 1;
|
||||
self.strikes.next += 1;
|
||||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
|
||||
// The counted flight includes the unlit ejection: the missile is honest about
|
||||
// arriving a second later (#129).
|
||||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
|
||||
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, p.site as u64, 7), gauss(self.seed, self.strikes.next as u64, p.site as u64, 8));
|
||||
self.strikes.flights.push(Flight { id: self.strikes.next, site: p.site, carrier: Some(p.carrier), from: start, pos: start, aim: p.aim,
|
||||
land: p.aim + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == p.site) { k.aimed = true; }
|
||||
self.record_strike_launch(self.strikes.next, p.carrier, start);
|
||||
out.sound("airdef:launch.s400_eject", start, 1.0, 1.0);
|
||||
out.sound(super::catalog::sound::LAUNCH_S400_EJECT, start, 1.0, 1.0);
|
||||
out.particles("minecraft:cloud", start, 0.6, DVec3::Y * 0.05, 0.05, 30);
|
||||
}
|
||||
}
|
||||
@@ -790,7 +810,8 @@ impl Sim {
|
||||
self.strikes.stock -= 1;
|
||||
self.strikes.fired += 1;
|
||||
self.strikes.next += 1;
|
||||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
|
||||
// The counted flight includes the unlit ejection (#129).
|
||||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
|
||||
let start = from + DVec3::Y * 1.5;
|
||||
// Its own scatter at the aim, rolled once here: the flight and its outcome name one point.
|
||||
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
|
||||
@@ -954,9 +975,9 @@ impl Sim {
|
||||
s
|
||||
}).collect();
|
||||
if v.is_empty() {
|
||||
v.push("Известных ПУ нет: их находят РЛС по пускам и трекам вылетевших целей".into());
|
||||
v.push("Известных ПУ нет: РЛС должна заметить пуск или вылетевшую цель; для удара нужно определить место пуска".into());
|
||||
}
|
||||
v.push("Удар: /airdef strike <ПУ>; подготовка RM48U: /airdef ground-load <номер С-400> у склада".into());
|
||||
v.push("Удар: /airdef strike <вражеская ПУ>; RM48U: /airdef ground-stock <склад> <число>, затем ground-load <С-400>".into());
|
||||
v
|
||||
}
|
||||
}
|
||||
@@ -1062,7 +1083,22 @@ 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, 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 };
|
||||
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,
|
||||
};
|
||||
sim.sams[0].tracks.push(track);
|
||||
sim.tick = 100;
|
||||
sim.step_strikes(&mut ground, None, &mut out);
|
||||
@@ -1408,10 +1444,14 @@ 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.
|
||||
// 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).
|
||||
for x in [-150.0, 150.0] {
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0));
|
||||
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0);
|
||||
sam.roles = 0;
|
||||
sim.sams.push(sam);
|
||||
}
|
||||
let id = sim.sites.add(LaunchSite {
|
||||
id: 0,
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
|
||||
// Game-scale values, not real weapon data; the catalog is the only copy.
|
||||
|
||||
const NAMED_BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
|
||||
const NAMED_BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
|
||||
const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
|
||||
|
||||
const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
|
||||
name: "Patriot",
|
||||
key: "patriot",
|
||||
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
|
||||
gun: None,
|
||||
reload: 220,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.66,
|
||||
roles: 30,
|
||||
family: Family::Trainable,
|
||||
parts: Parts {
|
||||
body: "airdef:patriot_trailer",
|
||||
launcher: Some("airdef:patriot_launcher"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.69, 1.2),
|
||||
pivot: DVec3::new(0.0, -0.5, 1.375),
|
||||
muzzle: Muzzle::Patriot,
|
||||
sensor: 585.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
|
||||
name: "Гепард",
|
||||
key: "gepard",
|
||||
missile: None,
|
||||
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
|
||||
reload: 160,
|
||||
scale: 1.25,
|
||||
rest_pitch: 0.0,
|
||||
roles: 7,
|
||||
family: Family::Gun,
|
||||
parts: Parts {
|
||||
body: "airdef:gepard_hull",
|
||||
launcher: Some("airdef:gepard_turret"),
|
||||
pack: Some("airdef:gepard_guns"),
|
||||
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (1.55, 0.25),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 255.0,
|
||||
mast: 3.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
|
||||
name: "Панцирь-С1",
|
||||
key: "pantsir",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
|
||||
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
|
||||
reload: 280,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 15,
|
||||
family: Family::Turret,
|
||||
parts: Parts {
|
||||
body: "airdef:pantsir_truck",
|
||||
launcher: Some("airdef:pantsir_turret"),
|
||||
pack: Some("airdef:pantsir_pack"),
|
||||
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (1.35, 0.69),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Pantsir,
|
||||
sensor: 292.0,
|
||||
mast: 4.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_S400: SamSpec = SamSpec {
|
||||
name: "С-400",
|
||||
key: "s400",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
|
||||
gun: None,
|
||||
reload: 420,
|
||||
scale: 1.5,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 30,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:s400_chassis",
|
||||
launcher: Some("airdef:s400_tubes"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: NAMED_BATTERY_RADAR,
|
||||
spinner: NAMED_BATTERY_SPINNER,
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: NAMED_TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(2, 2, 7.0),
|
||||
sensor: 936.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_S500: SamSpec = SamSpec {
|
||||
name: "С-500",
|
||||
key: "s500",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
|
||||
gun: None,
|
||||
reload: 520,
|
||||
scale: 1.6,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 24,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:s500_chassis",
|
||||
launcher: Some("airdef:s500_tubes"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: NAMED_BATTERY_RADAR,
|
||||
spinner: NAMED_BATTERY_SPINNER,
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: NAMED_TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(2, 1, 9.5),
|
||||
sensor: 1365.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_IRIST: SamSpec = SamSpec {
|
||||
name: "IRIS-T SLM",
|
||||
key: "irist",
|
||||
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
|
||||
gun: None,
|
||||
reload: 300,
|
||||
scale: 1.4,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 15,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:irist_chassis",
|
||||
launcher: Some("airdef:irist_tubes"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: NAMED_BATTERY_RADAR,
|
||||
spinner: NAMED_BATTERY_SPINNER,
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: NAMED_TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(4, 2, 4.0),
|
||||
sensor: 780.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_NASAMS: SamSpec = SamSpec {
|
||||
name: "NASAMS",
|
||||
key: "nasams",
|
||||
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
|
||||
gun: None,
|
||||
reload: 260,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.5,
|
||||
roles: 14,
|
||||
family: Family::Trainable,
|
||||
parts: Parts {
|
||||
body: "airdef:nasams_trailer",
|
||||
launcher: Some("airdef:nasams_launcher"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
|
||||
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
|
||||
},
|
||||
mount: (0.62, 0.4),
|
||||
pivot: NAMED_TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(3, 2, 4.0),
|
||||
sensor: 585.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_BUK: SamSpec = SamSpec {
|
||||
name: "Бук-М2",
|
||||
key: "buk",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
|
||||
gun: None,
|
||||
reload: 400,
|
||||
scale: 1.4,
|
||||
rest_pitch: 0.0,
|
||||
roles: 14,
|
||||
family: Family::Turret,
|
||||
parts: Parts {
|
||||
body: "airdef:buk_chassis",
|
||||
launcher: Some("airdef:buk_turret"),
|
||||
pack: Some("airdef:buk_rails"),
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (1.55, 0.2),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
|
||||
sensor: 878.0,
|
||||
mast: 4.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_TOR: SamSpec = SamSpec {
|
||||
name: "Тор-М2",
|
||||
key: "tor",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
|
||||
gun: None,
|
||||
reload: 300,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 15,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:tor_chassis",
|
||||
launcher: Some("airdef:tor_turret"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (1.5, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Cells,
|
||||
sensor: 315.0,
|
||||
mast: 3.5,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_P1SUN: SamSpec = SamSpec {
|
||||
name: "P1-SUN",
|
||||
key: "p1sun",
|
||||
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
|
||||
gun: None,
|
||||
reload: 240,
|
||||
scale: 1.1,
|
||||
rest_pitch: 0.35,
|
||||
roles: 1,
|
||||
family: Family::Trainable,
|
||||
parts: Parts {
|
||||
body: "airdef:nasams_trailer",
|
||||
launcher: Some("airdef:p1sun_launcher"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.6, 0.3),
|
||||
pivot: NAMED_TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(4, 2, 3.0),
|
||||
sensor: 0.0,
|
||||
mast: 2.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_RADAR: SamSpec = SamSpec {
|
||||
name: "РЛС дальнего обнаружения",
|
||||
key: "radar",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.5,
|
||||
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, 1.2, 1.5, -0.25)),
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 2550.0,
|
||||
mast: 16.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_DEPOT: SamSpec = SamSpec {
|
||||
name: "Склад боеприпасов",
|
||||
key: "depot",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.5,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts {
|
||||
body: "airdef:depot",
|
||||
launcher: None,
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 1.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_TZM: SamSpec = SamSpec {
|
||||
name: "ТЗМ",
|
||||
key: "tzm",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Truck,
|
||||
parts: Parts {
|
||||
body: "airdef:tzm_truck",
|
||||
launcher: None,
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 2.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_EW: SamSpec = SamSpec {
|
||||
name: "Станция РЭБ",
|
||||
key: "ew",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts {
|
||||
body: "airdef:ew_truck",
|
||||
launcher: None,
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 3.0,
|
||||
};
|
||||
|
||||
const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
|
||||
name: "Прожектор",
|
||||
key: "light",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.2,
|
||||
rest_pitch: 0.6,
|
||||
roles: 0,
|
||||
family: Family::Light,
|
||||
parts: Parts {
|
||||
body: "airdef:searchlight",
|
||||
launcher: Some("airdef:searchlight_head"),
|
||||
pack: None,
|
||||
dish: None,
|
||||
fixed: &[],
|
||||
spinner: None,
|
||||
},
|
||||
mount: (0.85, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
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 {
|
||||
match self {
|
||||
SamKind::Patriot => &UNIT_SPEC_PATRIOT,
|
||||
SamKind::Gepard => &UNIT_SPEC_GEPARD,
|
||||
SamKind::Pantsir => &UNIT_SPEC_PANTSIR,
|
||||
SamKind::S400 => &UNIT_SPEC_S400,
|
||||
SamKind::S500 => &UNIT_SPEC_S500,
|
||||
SamKind::IrisT => &UNIT_SPEC_IRIST,
|
||||
SamKind::Nasams => &UNIT_SPEC_NASAMS,
|
||||
SamKind::Buk => &UNIT_SPEC_BUK,
|
||||
SamKind::Tor => &UNIT_SPEC_TOR,
|
||||
SamKind::P1sun => &UNIT_SPEC_P1SUN,
|
||||
SamKind::Radar => &UNIT_SPEC_RADAR,
|
||||
SamKind::Depot => &UNIT_SPEC_DEPOT,
|
||||
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] = [
|
||||
(SamKind::Patriot, "patriot"),
|
||||
(SamKind::Gepard, "gepard"),
|
||||
(SamKind::Pantsir, "pantsir"),
|
||||
(SamKind::S400, "s400"),
|
||||
(SamKind::S500, "s500"),
|
||||
(SamKind::IrisT, "irist"),
|
||||
(SamKind::Nasams, "nasams"),
|
||||
(SamKind::Buk, "buk"),
|
||||
(SamKind::Tor, "tor"),
|
||||
(SamKind::P1sun, "p1sun"),
|
||||
(SamKind::Radar, "radar"),
|
||||
(SamKind::Depot, "depot"),
|
||||
(SamKind::Tzm, "tzm"),
|
||||
(SamKind::Ew, "ew"),
|
||||
(SamKind::Light, "light"),
|
||||
(SamKind::Optical, "optical"),
|
||||
];
|
||||
@@ -0,0 +1,8 @@
|
||||
// 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: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
|
||||
];
|
||||
+15
-369
@@ -27,6 +27,8 @@ 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.
|
||||
@@ -107,11 +109,6 @@ pub(super) struct Drive {
|
||||
pub pitch: (f64, f64),
|
||||
}
|
||||
|
||||
/// The drives are this share of the speeds they had before they had a speed of their own.
|
||||
const DRIVE_SCALE: f64 = 0.4;
|
||||
/// Ticks a drive takes to reach its top speed (and to stop from it).
|
||||
const DRIVE_RAMP: f64 = 8.0;
|
||||
|
||||
pub struct SamSpec {
|
||||
pub name: &'static str,
|
||||
pub key: &'static str,
|
||||
@@ -140,20 +137,16 @@ impl SamSpec {
|
||||
pub(super) fn drive(&self) -> Drive {
|
||||
let (yaw, pitch) = match (&self.gun, self.family) {
|
||||
(Some(g), _) => g.slew,
|
||||
(None, Family::Trainable) => (0.12, 0.0),
|
||||
(None, Family::Vertical) => (0.15, 0.0),
|
||||
(None, _) => (0.05, 0.05),
|
||||
(None, Family::Trainable) => DRIVE_TRAINABLE,
|
||||
(None, Family::Vertical) => DRIVE_VERTICAL,
|
||||
(None, _) => DRIVE_OTHER,
|
||||
};
|
||||
let axis = |speed: f64| (speed * DRIVE_SCALE, speed * DRIVE_SCALE / DRIVE_RAMP);
|
||||
Drive { yaw: axis(yaw), pitch: axis(pitch) }
|
||||
}
|
||||
}
|
||||
|
||||
const NO_PARTS: Parts = Parts { body: "", launcher: None, pack: None, dish: None, fixed: &[], spinner: None };
|
||||
/// The battery radar trailer behind a vertical launcher.
|
||||
const BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
|
||||
const BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
|
||||
const TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
|
||||
include!("unit_specs_generated.rs");
|
||||
|
||||
impl SamKind {
|
||||
pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS;
|
||||
@@ -170,361 +163,6 @@ impl SamKind {
|
||||
SamKind::Tor,
|
||||
SamKind::P1sun,
|
||||
];
|
||||
pub fn spec(self) -> &'static SamSpec {
|
||||
match self {
|
||||
SamKind::Patriot => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Patriot",
|
||||
key: "patriot",
|
||||
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
|
||||
gun: None,
|
||||
reload: 220,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.66,
|
||||
roles: 30,
|
||||
family: Family::Trainable,
|
||||
parts: Parts {
|
||||
body: "airdef:patriot_trailer",
|
||||
launcher: Some("airdef:patriot_launcher"),
|
||||
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.69, 1.2),
|
||||
pivot: DVec3::new(0.0, -0.5, 1.375),
|
||||
muzzle: Muzzle::Patriot,
|
||||
sensor: 585.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Gepard => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Гепард",
|
||||
key: "gepard",
|
||||
missile: None,
|
||||
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
|
||||
reload: 160,
|
||||
scale: 1.25,
|
||||
rest_pitch: 0.0,
|
||||
roles: 7,
|
||||
family: Family::Gun,
|
||||
parts: Parts {
|
||||
body: "airdef:gepard_hull",
|
||||
launcher: Some("airdef:gepard_turret"),
|
||||
pack: Some("airdef:gepard_guns"),
|
||||
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (1.55, 0.25),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 255.0,
|
||||
mast: 3.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Pantsir => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Панцирь-С1",
|
||||
key: "pantsir",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
|
||||
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
|
||||
reload: 280,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 15,
|
||||
family: Family::Turret,
|
||||
parts: Parts {
|
||||
body: "airdef:pantsir_truck",
|
||||
launcher: Some("airdef:pantsir_turret"),
|
||||
pack: Some("airdef:pantsir_pack"),
|
||||
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (1.35, 0.69),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Pantsir,
|
||||
sensor: 292.0,
|
||||
mast: 4.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::S400 => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "С-400",
|
||||
key: "s400",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
|
||||
gun: None,
|
||||
reload: 420,
|
||||
scale: 1.5,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 30,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:s400_chassis",
|
||||
launcher: Some("airdef:s400_tubes"),
|
||||
fixed: BATTERY_RADAR,
|
||||
spinner: BATTERY_SPINNER,
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(2, 2, 7.0),
|
||||
sensor: 936.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::S500 => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "С-500",
|
||||
key: "s500",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
|
||||
gun: None,
|
||||
reload: 520,
|
||||
scale: 1.6,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 24,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:s500_chassis",
|
||||
launcher: Some("airdef:s500_tubes"),
|
||||
fixed: BATTERY_RADAR,
|
||||
spinner: BATTERY_SPINNER,
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(2, 1, 9.5),
|
||||
sensor: 1365.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::IrisT => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "IRIS-T SLM",
|
||||
key: "irist",
|
||||
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
|
||||
gun: None,
|
||||
reload: 300,
|
||||
scale: 1.4,
|
||||
rest_pitch: HALF_PI - 0.02,
|
||||
roles: 15,
|
||||
family: Family::Vertical,
|
||||
parts: Parts {
|
||||
body: "airdef:irist_chassis",
|
||||
launcher: Some("airdef:irist_tubes"),
|
||||
fixed: BATTERY_RADAR,
|
||||
spinner: BATTERY_SPINNER,
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.7, 1.45),
|
||||
pivot: TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(4, 2, 4.0),
|
||||
sensor: 780.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Nasams => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "NASAMS",
|
||||
key: "nasams",
|
||||
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
|
||||
gun: None,
|
||||
reload: 260,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.5,
|
||||
roles: 14,
|
||||
family: Family::Trainable,
|
||||
parts: Parts {
|
||||
body: "airdef:nasams_trailer",
|
||||
launcher: Some("airdef:nasams_launcher"),
|
||||
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
|
||||
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.62, 0.4),
|
||||
pivot: TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(3, 2, 4.0),
|
||||
sensor: 585.0,
|
||||
mast: 5.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Buk => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Бук-М2",
|
||||
key: "buk",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
|
||||
gun: None,
|
||||
reload: 400,
|
||||
scale: 1.4,
|
||||
rest_pitch: 0.0,
|
||||
roles: 14,
|
||||
family: Family::Turret,
|
||||
parts: Parts {
|
||||
body: "airdef:buk_chassis",
|
||||
launcher: Some("airdef:buk_turret"),
|
||||
pack: Some("airdef:buk_rails"),
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (1.55, 0.2),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
|
||||
sensor: 878.0,
|
||||
mast: 4.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Tor => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Тор-М2",
|
||||
key: "tor",
|
||||
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
|
||||
gun: None,
|
||||
reload: 300,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 15,
|
||||
family: Family::Vertical,
|
||||
parts: Parts { body: "airdef:tor_chassis", launcher: Some("airdef:tor_turret"), ..NO_PARTS },
|
||||
mount: (1.5, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::Cells,
|
||||
sensor: 315.0,
|
||||
mast: 3.5,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::P1sun => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "P1-SUN",
|
||||
key: "p1sun",
|
||||
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
|
||||
gun: None,
|
||||
reload: 240,
|
||||
scale: 1.1,
|
||||
rest_pitch: 0.35,
|
||||
roles: 1,
|
||||
family: Family::Trainable,
|
||||
parts: Parts { body: "airdef:nasams_trailer", launcher: Some("airdef:p1sun_launcher"), ..NO_PARTS },
|
||||
mount: (0.6, 0.3),
|
||||
pivot: TUBE_PIVOT,
|
||||
muzzle: Muzzle::Grid(4, 2, 3.0),
|
||||
// No radar of its own: it fires on the network's tracks.
|
||||
sensor: 0.0,
|
||||
mast: 2.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Radar => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "РЛС дальнего обнаружения",
|
||||
key: "radar",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.5,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts {
|
||||
body: "airdef:radar_truck",
|
||||
spinner: Some(("airdef:radar_panel", 1.2, 1.2, 1.5, -0.25)),
|
||||
..NO_PARTS
|
||||
},
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 2550.0,
|
||||
mast: 16.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Depot => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Склад боеприпасов",
|
||||
key: "depot",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.5,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts { body: "airdef:depot", ..NO_PARTS },
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 1.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Tzm => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "ТЗМ",
|
||||
key: "tzm",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Truck,
|
||||
parts: Parts { body: "airdef:tzm_truck", ..NO_PARTS },
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 2.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Ew => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Станция РЭБ",
|
||||
key: "ew",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.3,
|
||||
rest_pitch: 0.0,
|
||||
roles: 0,
|
||||
family: Family::Static,
|
||||
parts: Parts { body: "airdef:ew_truck", ..NO_PARTS },
|
||||
mount: (0.0, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 3.0,
|
||||
};
|
||||
&S
|
||||
}
|
||||
SamKind::Light => {
|
||||
const S: SamSpec = SamSpec {
|
||||
name: "Прожектор",
|
||||
key: "light",
|
||||
missile: None,
|
||||
gun: None,
|
||||
reload: 0,
|
||||
scale: 1.2,
|
||||
rest_pitch: 0.6,
|
||||
roles: 0,
|
||||
family: Family::Light,
|
||||
parts: Parts { body: "airdef:searchlight", launcher: Some("airdef:searchlight_head"), ..NO_PARTS },
|
||||
mount: (0.85, 0.0),
|
||||
pivot: DVec3::ZERO,
|
||||
muzzle: Muzzle::None,
|
||||
sensor: 0.0,
|
||||
mast: 1.5,
|
||||
};
|
||||
&S
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
self.spec().name
|
||||
}
|
||||
@@ -543,6 +181,14 @@ 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 {
|
||||
@@ -689,7 +335,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_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
|
||||
let extra = if sam.kind == SamKind::Radar { sam.radar_profile().mast } 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);
|
||||
|
||||
@@ -18,23 +18,24 @@ impl MissileKind {
|
||||
/// The sound of its motor, its gain and its pitch: a rocket's roar, or the electric whine of
|
||||
/// a motor without a flame.
|
||||
pub fn engine_voice(self) -> (&'static str, f32, f32) {
|
||||
if self.spec().flame == 0.0 {
|
||||
return ("airdef:drone.lancet", 0.8, 1.6);
|
||||
}
|
||||
let pitch = match self {
|
||||
MissileKind::Pac3 => 1.0,
|
||||
MissileKind::M57e6 => 1.12,
|
||||
MissileKind::M48n6 => 0.88,
|
||||
MissileKind::M77n6 => 0.8,
|
||||
MissileKind::IrisT | MissileKind::Amraam => 1.05,
|
||||
MissileKind::M9m317 => 0.9,
|
||||
MissileKind::M9m338 => 1.15,
|
||||
MissileKind::P1sun => 1.7,
|
||||
};
|
||||
("airdef:missile.flight", 1.0, pitch)
|
||||
self.spec().voice
|
||||
}
|
||||
/// Ticks from the launch until the motor lights (a cold launch throws it out of the tube first).
|
||||
pub fn lit_after(self) -> u32 {
|
||||
self.spec().cold
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::super::catalog::sound;
|
||||
|
||||
/// The catalog holds the voice that is actually played. P1-SUN has no flame, so it uses the
|
||||
/// Lancet voice at 1.6; its old `P1sun => 1.7` match arm was unreachable behind `flame == 0`.
|
||||
#[test]
|
||||
fn missile_engine_voices_keep_their_played_values() {
|
||||
assert_eq!(MissileKind::P1sun.engine_voice(), (sound::DRONE_LANCET, 0.8, 1.6));
|
||||
assert_eq!(MissileKind::M48n6.engine_voice(), (sound::MISSILE_FLIGHT, 1.0, 0.88));
|
||||
}
|
||||
}
|
||||
|
||||
+319
-68
@@ -14,14 +14,20 @@ 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 roles & d.kind.spec().class.bit() != 0 { 0 } else { ROLE })
|
||||
| (if track.is_some_and(|t| t.class.in_roles(roles)) { 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, and on its picture (own radar or the network's), fresh enough.
|
||||
/// Alive, of a class the system engages (or not yet classified), 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
|
||||
}
|
||||
@@ -50,14 +56,15 @@ 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: ballistic missiles get a pair, anything else one; a target
|
||||
/// Shoot-look-shoot that grows with urgency: a ballistic missile gets 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) -> u32 {
|
||||
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
|
||||
pub(super) fn needed(d: &Drone, class: ClassEst) -> u32 {
|
||||
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
|
||||
let t = arrival(d);
|
||||
base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL)
|
||||
}
|
||||
@@ -68,12 +75,14 @@ pub(super) const SHY_TICKS: u64 = 120;
|
||||
|
||||
// ---------------------------------------------------------------- the grounds to launch on
|
||||
|
||||
/// 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.
|
||||
/// 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).
|
||||
pub(super) const LAST_CHANCE_TICKS: f64 = 200.0;
|
||||
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
/// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds.
|
||||
@@ -92,14 +101,17 @@ 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_role.authorizes()
|
||||
r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
|
||||
&& 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| t.own_tick > 0 && now.saturating_sub(t.own_tick) <= if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE })
|
||||
&& 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -137,25 +149,37 @@ 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> {
|
||||
if sam.mode == battery::SamMode::LauncherOnly && !cued { return None; }
|
||||
// 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;
|
||||
}
|
||||
let blocks = target_blocks(sam.roles, Some(track), now, d);
|
||||
if blocks & !ROLE != 0 {
|
||||
return None;
|
||||
}
|
||||
let est = track.est(now);
|
||||
let reach = reach_blocks(load.min, load.max, k, sam.pos, est);
|
||||
let est = track.class;
|
||||
let reach = reach_blocks(load.min, load.max, k, sam.pos, track.est(now));
|
||||
if blocks & ROLE == 0 {
|
||||
// The doctrine (sector, protected objects, reserve) rules over the role's shots and the long ones; the last chance is past it.
|
||||
if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d) != 0 {
|
||||
if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 {
|
||||
return None;
|
||||
}
|
||||
if reach == 0 {
|
||||
return Some(Basis::Role);
|
||||
// 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);
|
||||
}
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0;
|
||||
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
|
||||
}
|
||||
(reach == 0 && last_chance(opts.last_chance, sam.roles, d, claimed)).then_some(Basis::LastChance)
|
||||
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
|
||||
}
|
||||
|
||||
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
|
||||
@@ -250,15 +274,42 @@ pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f6
|
||||
|
||||
// ---------------------------------------------------------------- the diagnostic
|
||||
|
||||
/// One condition and whether it holds.
|
||||
/// A diagnostic condition and its structured or legacy reason.
|
||||
#[derive(Debug)]
|
||||
pub struct Check {
|
||||
pub ok: bool,
|
||||
pub text: String,
|
||||
pub reason: CheckReason,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CheckReason {
|
||||
/// Diagnostics not yet migrated to typed reasons.
|
||||
Text(String),
|
||||
Parts(Vec<(Part, f64)>),
|
||||
PartEffect(PartEffect),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum PartEffect {
|
||||
SensorFailed, SensorDamaged { fit: f64 },
|
||||
MountFailed { yaw_degrees: f64 }, MountDamaged { fit: f64 },
|
||||
LauncherFailed, LauncherDamaged { cells: u32, capacity: u32, reload_seconds: f64 },
|
||||
GunFailed, GunDamaged { fit: f64 },
|
||||
TracksFailed, TracksDamaged { speed: f64 },
|
||||
CommsFailed, CommsDamaged { range: f64 },
|
||||
}
|
||||
|
||||
impl Check {
|
||||
#[cfg(test)]
|
||||
pub(super) fn legacy_text(&self) -> &str {
|
||||
match &self.reason { CheckReason::Text(text) => text, _ => "" }
|
||||
}
|
||||
}
|
||||
|
||||
fn check(ok: bool, text: impl Into<String>) -> Check {
|
||||
Check { ok, text: text.into() }
|
||||
Check { ok, reason: CheckReason::Text(text.into()) }
|
||||
}
|
||||
fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } }
|
||||
|
||||
impl Sim {
|
||||
/// Why system `index` fires or doesn't, at its current target or at the most threatening
|
||||
@@ -281,6 +332,37 @@ 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;
|
||||
}
|
||||
@@ -293,7 +375,9 @@ impl Sim {
|
||||
v.push(check(alive > 0, format!("в небе {alive}, на картине {seen} (своя РЛС {own}, остальные по сети)")));
|
||||
// The parts: what is worn or failed and what it costs.
|
||||
if !sam.comps.whole() {
|
||||
v.push(check(false, format!("узлы: {}", sam.parts_text())));
|
||||
let parts = Part::ALL.into_iter().filter(|p| p.on(sam.kind) && sam.comps.get(*p) < 1.0)
|
||||
.map(|p| (p, sam.comps.get(p))).collect();
|
||||
v.push(part_check(CheckReason::Parts(parts)));
|
||||
}
|
||||
for p in Part::ALL {
|
||||
if !p.on(sam.kind) || sam.part_state(p) == PartState::Ok {
|
||||
@@ -301,20 +385,20 @@ impl Sim {
|
||||
}
|
||||
let failed = sam.part_state(p) == PartState::Failed;
|
||||
let effect = match (p, failed) {
|
||||
(Part::Sensor, true) => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".to_string(),
|
||||
(Part::Sensor, false) => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", sam.radar_fit() * 100.0),
|
||||
(Part::Mount, true) => format!("привод наведения заклинил: стоит на {:.0}°, не доворачивается", sam.yaw.to_degrees().rem_euclid(360.0)),
|
||||
(Part::Mount, false) => format!("привод наведения повреждён: поворот {:.0}% от нормы", sam.drive_fit() * 100.0),
|
||||
(Part::Launcher, true) => "пусковая отказала: пуски невозможны".to_string(),
|
||||
(Part::Launcher, false) => format!("пусковая повреждена: {} ячеек из {}, перезарядка {:.0} с", sam.cells(), spec.missile.as_ref().map_or(0, |m| m.magazine), sam.reload_time() as f64 / 20.0),
|
||||
(Part::Gun, true) => "орудие заклинило: не стреляет".to_string(),
|
||||
(Part::Gun, false) => format!("орудие повреждено: меткость {:.0}%, заклинивает", sam.gun_fit() * 100.0),
|
||||
(Part::Tracks, true) => "ходовая отказала: на марш не выйдет".to_string(),
|
||||
(Part::Tracks, false) => format!("ходовая повреждена: скорость марша {:.0}%", sam.drive_speed() * 100.0),
|
||||
(Part::Comms, true) => "связь отказала: сети нет, цели только свои".to_string(),
|
||||
(Part::Comms, false) => format!("связь повреждена: линия {:.0} м", sam.link_range()),
|
||||
(Part::Sensor, true) => PartEffect::SensorFailed,
|
||||
(Part::Sensor, false) => PartEffect::SensorDamaged { fit: sam.radar_fit() },
|
||||
(Part::Mount, true) => PartEffect::MountFailed { yaw_degrees: sam.yaw.to_degrees().rem_euclid(360.0) },
|
||||
(Part::Mount, false) => PartEffect::MountDamaged { fit: sam.drive_fit() },
|
||||
(Part::Launcher, true) => PartEffect::LauncherFailed,
|
||||
(Part::Launcher, false) => PartEffect::LauncherDamaged { cells: sam.cells(), capacity: spec.missile.as_ref().map_or(0, |m| m.magazine), reload_seconds: sam.reload_time() as f64 / 20.0 },
|
||||
(Part::Gun, true) => PartEffect::GunFailed,
|
||||
(Part::Gun, false) => PartEffect::GunDamaged { fit: sam.gun_fit() },
|
||||
(Part::Tracks, true) => PartEffect::TracksFailed,
|
||||
(Part::Tracks, false) => PartEffect::TracksDamaged { speed: sam.drive_speed() },
|
||||
(Part::Comms, true) => PartEffect::CommsFailed,
|
||||
(Part::Comms, false) => PartEffect::CommsDamaged { range: sam.link_range() },
|
||||
};
|
||||
v.push(check(false, effect));
|
||||
v.push(part_check(CheckReason::PartEffect(effect)));
|
||||
}
|
||||
if sam.jam > 0 {
|
||||
v.push(check(false, format!("орудие заклинило, ещё {:.1} с", sam.jam as f64 / 20.0)));
|
||||
@@ -323,7 +407,10 @@ impl Sim {
|
||||
let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| {
|
||||
self.drones
|
||||
.iter()
|
||||
.filter(|d| d.alive() && (sam.roles & d.kind.spec().class.bit() != 0 || last_chance(self.last_chance, sam.roles, d, claimed(d, &missile_on, sam.target))))
|
||||
// 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))))
|
||||
.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);
|
||||
@@ -331,44 +418,61 @@ impl Sim {
|
||||
})
|
||||
});
|
||||
let Some(t) = subject else {
|
||||
v.push(check(false, format!("нет целей классов [{}]", roles_text(sam.roles))));
|
||||
// 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));
|
||||
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!("цель: {} {}, {}", t.kind.spec().name, if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
|
||||
format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
|
||||
));
|
||||
let track = sam.track(t.id);
|
||||
let est = track.map_or(ClassEst::Unknown, |tr| tr.class);
|
||||
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 = track.map_or(t.pos, |tr| tr.est(now));
|
||||
let est_at = 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, t, first_claim);
|
||||
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, first_claim);
|
||||
let role_text = if blocks & ROLE == 0 {
|
||||
format!("роль: {} в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
|
||||
match est {
|
||||
ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(),
|
||||
_ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)),
|
||||
}
|
||||
} else if chance {
|
||||
format!(
|
||||
"последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет",
|
||||
t.kind.spec().class.name(),
|
||||
est.name(),
|
||||
roles_text(sam.roles),
|
||||
arrival(t) / 20.0
|
||||
)
|
||||
} else if sam.roles == 0 {
|
||||
"роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string()
|
||||
} else {
|
||||
format!("роль: {} не в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
|
||||
format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles))
|
||||
};
|
||||
v.push(check(blocks & ROLE == 0 || chance, role_text));
|
||||
// The doctrine: which of its settings let the shot through or stopped it. The last chance is past them.
|
||||
let doc = &sam.doctrine;
|
||||
let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now));
|
||||
let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t) } else { 0 };
|
||||
let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t, est) } else { 0 };
|
||||
if !doc.is_default() {
|
||||
v.push(check(true, format!("доктрина: {}", doc.text(&self.targets))));
|
||||
}
|
||||
if area & doctrine::OUT_SECTOR != 0 {
|
||||
let bearing = heading_of(est - sam.pos).to_degrees().rem_euclid(360.0);
|
||||
let bearing = heading_of(est_at - 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())));
|
||||
@@ -389,7 +493,15 @@ 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() };
|
||||
format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}", tr.ident().name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" })
|
||||
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 { "нет (сеть или обзор не дают права)" }
|
||||
)
|
||||
}
|
||||
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
|
||||
};
|
||||
@@ -427,19 +539,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, evel, lead_speed);
|
||||
let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, 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);
|
||||
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at);
|
||||
// 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) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o))
|
||||
sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class))
|
||||
});
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
|
||||
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 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);
|
||||
@@ -458,7 +570,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);
|
||||
let need = sam.doctrine.needed(t, est);
|
||||
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();
|
||||
@@ -475,7 +587,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), t.id, t.id, err);
|
||||
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est_at), 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.
|
||||
@@ -491,7 +603,9 @@ impl Sim {
|
||||
));
|
||||
}
|
||||
let doc_ok = chance || area | held_back == 0;
|
||||
let grounds = (sam.mode != battery::SamMode::LauncherOnly || cued) && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
|
||||
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);
|
||||
fires |= grounds && free < need && mb == 0 && aligned && land == 0;
|
||||
}
|
||||
if let Some(gun) = &spec.gun {
|
||||
@@ -506,7 +620,7 @@ impl Sim {
|
||||
if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" }
|
||||
),
|
||||
));
|
||||
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est), gun.range, now);
|
||||
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est_at), gun.range, now);
|
||||
let mut why = Vec::new();
|
||||
for (bit, name) in [
|
||||
(AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())),
|
||||
@@ -551,10 +665,10 @@ mod tests {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
let w = sim.why(0);
|
||||
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.text.contains("нет целей классов")));
|
||||
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<_>>());
|
||||
sim.sams[0].roles = 0xFF;
|
||||
assert!(sim.why(0).iter().any(|c| c.text.starts_with("роль")));
|
||||
assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль")));
|
||||
}
|
||||
|
||||
use super::sites::testland::{Land, serve};
|
||||
@@ -583,23 +697,45 @@ 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: the last chance.
|
||||
// The diagnostic names why: first the role block, then the last chance.
|
||||
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
|
||||
shahed_at(&mut sim, 100.0);
|
||||
for _ in 0..30 {
|
||||
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
|
||||
let mut saw_block = false;
|
||||
let mut saw_chance = false;
|
||||
for _ in 0..220 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.ok && c.text.starts_with("последний шанс")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
|
||||
assert!(saw_block, "the role block was never named");
|
||||
assert!(saw_chance, "the last chance was never named");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -607,11 +743,13 @@ 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 the role block it was: no target of its classes.
|
||||
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.text.contains("нет целей классов")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
|
||||
assert!(!w.iter().any(|c| c.text.starts_with("последний шанс")));
|
||||
// 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<_>>());
|
||||
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -621,6 +759,7 @@ 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}");
|
||||
}
|
||||
}
|
||||
@@ -629,12 +768,109 @@ 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);
|
||||
@@ -653,12 +889,27 @@ mod tests {
|
||||
.drones
|
||||
.iter()
|
||||
.filter(|d| d.alive())
|
||||
.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 })
|
||||
.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,
|
||||
})
|
||||
.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(*t);
|
||||
r.tracks.push(Track { source: r.id, ..*t });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -678,7 +929,7 @@ mod tests {
|
||||
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
|
||||
assert!(fire_far(&mut sim, &mut ground, &land, &mut out, 80) >= 1, "no long shot at 1.4 x max with a radar");
|
||||
let w = sim.why(0);
|
||||
assert!(w.iter().any(|c| c.text.starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
|
||||
assert!(w.iter().any(|c| c.legacy_text().starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
|
||||
// No radar, no shot (the system's own radar may well see it: that is not a cue).
|
||||
let (mut sim, mut ground, land, mut out) = far_setup(false, max * 1.4);
|
||||
assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with no radar");
|
||||
|
||||
@@ -238,27 +238,6 @@ impl WorldCache {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.secs.is_empty()
|
||||
}
|
||||
/// One line for the report.
|
||||
pub fn text(&self) -> String {
|
||||
let s = &self.stats;
|
||||
format!(
|
||||
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}; взрывы в блоках: {} (подтверждено {}, без перемен {}, нет чанка {}), чужих ответов {}",
|
||||
self.len(),
|
||||
self.bytes() / 1024,
|
||||
s.sections_asked,
|
||||
s.sections_unknown,
|
||||
s.sweeps,
|
||||
s.hits,
|
||||
s.unknown_sweeps,
|
||||
s.cells,
|
||||
s.blasts_asked,
|
||||
s.blasts_confirmed,
|
||||
s.blasts_unchanged,
|
||||
s.blasts_unloaded,
|
||||
s.late_dropped
|
||||
)
|
||||
}
|
||||
|
||||
/// The game's note of changes: another world voids everything; changed
|
||||
/// sections (or too many to say) are read again when next used.
|
||||
pub fn changed(&mut self, epoch: u32, overflow: bool, sections: &[Sec]) {
|
||||
|
||||
+12
-8
@@ -13,6 +13,8 @@ use std::collections::HashMap;
|
||||
|
||||
const MAX_TRAIL: usize = 2400;
|
||||
const MAX_TOTAL: usize = 4000;
|
||||
// A small optical-density lift for powered missile trails. Keep geometry and budgets unchanged.
|
||||
const MISSILE_TRAIL_DENSITY: f32 = 1.12;
|
||||
|
||||
struct Trail {
|
||||
seg: SmokeSegment,
|
||||
@@ -135,7 +137,7 @@ fn rocket(scale: f32, density: f32, life: f32) -> Look {
|
||||
Look {
|
||||
r0: 0.25 * scale,
|
||||
r1: 1.2 + 1.6 * scale,
|
||||
density,
|
||||
density: density * MISSILE_TRAIL_DENSITY,
|
||||
soot: 0.02,
|
||||
clear: 0.8 + 1.2 * scale,
|
||||
life: life + 250.0 * scale,
|
||||
@@ -163,7 +165,7 @@ fn drone_look(class: Class, scale: f32) -> Look {
|
||||
Class::Cruise => Look {
|
||||
r0: 0.6,
|
||||
r1: 3.0,
|
||||
density: 0.6,
|
||||
density: 0.6 * MISSILE_TRAIL_DENSITY,
|
||||
soot: 0.3,
|
||||
clear: 2.0,
|
||||
life: 600.0,
|
||||
@@ -606,13 +608,15 @@ mod tests {
|
||||
#[test]
|
||||
fn recorded_physical_strike_trail_starts_at_ignition_not_at_the_muzzle() {
|
||||
use crate::sim::record::{Recording, What};
|
||||
let mut rec = Recording::blank(40);
|
||||
rec.straight(1, What::StrikeCarrier(77), 10, 30, DVec3::ZERO, DVec3::Z * 20.0);
|
||||
let ignite = 10.0 + crate::sim::strike::EJECT_TICKS as f64;
|
||||
let mut rec = Recording::blank(120);
|
||||
rec.straight(1, What::StrikeCarrier(77), 10, 90, DVec3::ZERO, DVec3::Z * 80.0);
|
||||
assert!(replay_smoke(&rec, 14.0).is_empty());
|
||||
let segments = replay_smoke(&rec, 18.0);
|
||||
assert_eq!(segments.len(), 1);
|
||||
assert!((segments[0].az - 5.0).abs() < 1e-6);
|
||||
assert!((segments[0].bz - 8.0).abs() < 1e-6);
|
||||
assert!(replay_smoke(&rec, (ignite - 2.0).max(30.0)).is_empty(), "no trail before the ignition");
|
||||
let segments = replay_smoke(&rec, ignite + 12.0);
|
||||
assert_eq!(segments.len(), 2);
|
||||
assert!((segments[0].az - 20.0).abs() < 1e-6 && (segments[0].bz - 24.0).abs() < 1e-6, "the trail begins at the recorded ignition");
|
||||
assert!((segments[1].az - 24.0).abs() < 1e-6 && (segments[1].bz - 32.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+10
-3
@@ -179,14 +179,21 @@ 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"), format!("textures/item/{name}.png")] {
|
||||
for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] {
|
||||
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();
|
||||
assert!(model.contains(&format!("airdef:item/{name}")), "{item}: wrong icon reference");
|
||||
let png = std::fs::read(assets().join(format!("textures/item/{name}.png"))).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!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature");
|
||||
}
|
||||
fn model_exists(model: &str) {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! 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::PartEffect(effect) => match effect {
|
||||
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
|
||||
PartEffect::SensorDamaged { fit } => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", fit * 100.0),
|
||||
PartEffect::MountFailed { yaw_degrees } => format!("привод наведения заклинил: стоит на {yaw_degrees:.0}°, не доворачивается"),
|
||||
PartEffect::MountDamaged { fit } => format!("привод наведения повреждён: поворот {:.0}% от нормы", fit * 100.0),
|
||||
PartEffect::LauncherFailed => "пусковая отказала: пуски невозможны".into(),
|
||||
PartEffect::LauncherDamaged { cells, capacity, reload_seconds } => format!("пусковая повреждена: {cells} ячеек из {capacity}, перезарядка {reload_seconds:.0} с"),
|
||||
PartEffect::GunFailed => "орудие заклинило: не стреляет".into(),
|
||||
PartEffect::GunDamaged { fit } => format!("орудие повреждено: меткость {:.0}%, заклинивает", fit * 100.0),
|
||||
PartEffect::TracksFailed => "ходовая отказала: на марш не выйдет".into(),
|
||||
PartEffect::TracksDamaged { speed } => format!("ходовая повреждена: скорость марша {:.0}%", speed * 100.0),
|
||||
PartEffect::CommsFailed => "связь отказала: сети нет, цели только свои".into(),
|
||||
PartEffect::CommsDamaged { range } => format!("связь повреждена: линия {range:.0} м"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[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%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_simulation_produces_player_diagnostics_in_order() {
|
||||
use crate::sim::{Sam, SamKind, Sim};
|
||||
let mut sim = Sim::new(1);
|
||||
let mut sam = Sam::new(1, SamKind::Pantsir, glam::DVec3::ZERO, 0.0);
|
||||
sam.comps.0[Part::Sensor as usize] = 0.4;
|
||||
sam.comps.0[Part::Tracks as usize] = 0.0;
|
||||
sim.sams.push(sam);
|
||||
let lines: Vec<String> = sim.why(0).iter().map(|c| reason(&c.reason)).collect();
|
||||
let summary = lines.iter().position(|s| s == "узлы: РЛС 40%, Ход отказ").unwrap();
|
||||
let sensor = lines.iter().position(|s| s.starts_with("РЛС повреждена: дальность ")).unwrap();
|
||||
let tracks = lines.iter().position(|s| s == "ходовая отказала: на марш не выйдет").unwrap();
|
||||
assert!(summary < sensor && sensor < tracks, "{lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_damage_diagnostics() {
|
||||
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
|
||||
let cases = [
|
||||
(PartEffect::SensorFailed, "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети"),
|
||||
(PartEffect::SensorDamaged { fit: 0.4 }, "РЛС повреждена: дальность 40%, обзор вдвое реже при худшем"),
|
||||
(PartEffect::MountFailed { yaw_degrees: 42.0 }, "привод наведения заклинил: стоит на 42°, не доворачивается"),
|
||||
(PartEffect::MountDamaged { fit: 0.3 }, "привод наведения повреждён: поворот 30% от нормы"),
|
||||
(PartEffect::LauncherFailed, "пусковая отказала: пуски невозможны"),
|
||||
(PartEffect::LauncherDamaged { cells: 2, capacity: 4, reload_seconds: 12.0 }, "пусковая повреждена: 2 ячеек из 4, перезарядка 12 с"),
|
||||
(PartEffect::GunFailed, "орудие заклинило: не стреляет"),
|
||||
(PartEffect::GunDamaged { fit: 0.5 }, "орудие повреждено: меткость 50%, заклинивает"),
|
||||
(PartEffect::TracksFailed, "ходовая отказала: на марш не выйдет"),
|
||||
(PartEffect::TracksDamaged { speed: 0.2 }, "ходовая повреждена: скорость марша 20%"),
|
||||
(PartEffect::CommsFailed, "связь отказала: сети нет, цели только свои"),
|
||||
(PartEffect::CommsDamaged { range: 123.0 }, "связь повреждена: линия 123 м"),
|
||||
];
|
||||
for (effect, expected) in cases { assert_eq!(reason(&CheckReason::PartEffect(effect)), expected); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Player-facing world-cache report, also used by the headless scenario driver.
|
||||
use airdef_core::sim::world::WorldCache;
|
||||
|
||||
pub fn text(world: &WorldCache) -> String {
|
||||
let s = &world.stats;
|
||||
format!(
|
||||
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}; взрывы в блоках: {} (подтверждено {}, без перемен {}, нет чанка {}), чужих ответов {}",
|
||||
world.len(), world.bytes() / 1024, s.sections_asked, s.sections_unknown,
|
||||
s.sweeps, s.hits, s.unknown_sweeps, s.cells, s.blasts_asked,
|
||||
s.blasts_confirmed, s.blasts_unchanged, s.blasts_unloaded, s.late_dropped
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reports_cache_counts_in_existing_format() {
|
||||
let mut world = WorldCache::default();
|
||||
world.stats.sections_asked = 1;
|
||||
world.stats.sections_unknown = 2;
|
||||
world.stats.sweeps = 3;
|
||||
world.stats.hits = 4;
|
||||
world.stats.unknown_sweeps = 5;
|
||||
world.stats.cells = 6;
|
||||
world.stats.blasts_asked = 7;
|
||||
world.stats.blasts_confirmed = 8;
|
||||
world.stats.blasts_unchanged = 9;
|
||||
world.stats.blasts_unloaded = 10;
|
||||
world.stats.late_dropped = 11;
|
||||
assert_eq!(text(&world), "мир: 0 секций (0 КБ), запросов 1, неизвестно 2, лучей 3 (ударов 4, неизв. 5), клеток 6; взрывы в блоках: 7 (подтверждено 8, без перемен 9, нет чанка 10), чужих ответов 11");
|
||||
}
|
||||
}
|
||||
@@ -262,17 +262,31 @@ expect.feedback = "Тор-М2 развёрнут (integrated, multi)"
|
||||
command = "airdef deploy s400"
|
||||
expect.feedback = "С-400 развёрнут (integrated, multi)"
|
||||
|
||||
# Two maximum supported waves are issued before simulation advances, so
|
||||
# their 160 airborne units overlap while 64 defensive systems track them.
|
||||
[[step]]
|
||||
command = "airdef wave mix 80 4000"
|
||||
|
||||
# The next raid can only be ordered after the first plan is complete.
|
||||
[[step]]
|
||||
command = "airdef wave kh101 80 4000"
|
||||
|
||||
[[step]]
|
||||
ticks = 450
|
||||
frames = 225
|
||||
expect.chat = ["Противник готовит налёт: ищет площадки, местность подгружается", "Площадок за пределами загруженной карты: 1: оттуда пуск без площадки, с высоты полёта", "ВОЗДУШНАЯ ТРЕВОГА: налёт, 80 целей (один сектор)"]
|
||||
|
||||
[[step]]
|
||||
command = "airdef wave kh101 80 4000"
|
||||
expect.chat = []
|
||||
|
||||
[[step]]
|
||||
ticks = 600
|
||||
frames = 300
|
||||
expect.chat = ["Противник готовит налёт: ищет площадки, местность подгружается", "Площадок за пределами загруженной карты: 1: оттуда пуск без площадки, с высоты полёта", "ВОЗДУШНАЯ ТРЕВОГА: налёт, 80 целей (один сектор)"]
|
||||
|
||||
[[step]]
|
||||
command = "airdef stats"
|
||||
expect.feedback = "В воздухе: 12, ракет: 0, ПВО: 64, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 0 секций (0 КБ), запросов 652, неизвестно 0, лучей 5642 (ударов 0, неизв. 5642), клеток 5642; взрывы в блоках: 0 (подтверждено 0, без перемен 0, нет чанка 0), чужих ответов 0"
|
||||
|
||||
[[step]]
|
||||
ticks = 400
|
||||
frames = 200
|
||||
|
||||
[[step]]
|
||||
command = "airdef clear"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,10 @@ expect.error = "Нет живого склада с RM48U рядом (60 бло
|
||||
[[step]]
|
||||
command = "airdef deploy depot"
|
||||
|
||||
[[step]]
|
||||
command = "airdef ground-load 2"
|
||||
expect.error = "Склад №3 рядом, но RM48U: 0. Задайте запас: /airdef ground-stock 3 <количество>"
|
||||
|
||||
[[step]]
|
||||
command = "airdef ground-stock 3 2"
|
||||
expect.feedback = "Sandbox: задан начальный запас склада №3: RM48U 2"
|
||||
@@ -46,13 +50,14 @@ 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.feedback = "№4 РЛС: роль search"
|
||||
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
|
||||
|
||||
[[step]]
|
||||
command = "airdef radar 4 engagement"
|
||||
expect.feedback = "№4 РЛС: роль engagement"
|
||||
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
|
||||
|
||||
[[step]]
|
||||
command = "airdef radar 4 off"
|
||||
@@ -69,6 +74,19 @@ expect.error = "У комплекса нет активной РЛС"
|
||||
[[step]]
|
||||
command = "airdef deploy s500_launcher"
|
||||
|
||||
# The wave screen's preset button through the command boundary; an empty wave cannot launch.
|
||||
[[step]]
|
||||
command = "airdef preset 0"
|
||||
expect.feedback = "Готовый: Рой Шахедов"
|
||||
|
||||
[[step]]
|
||||
command = "airdef preset 6"
|
||||
expect.feedback = "Готовый: Пусто"
|
||||
|
||||
[[step]]
|
||||
command = "airdef raid"
|
||||
expect.error = "Налёт пуст: выберите типы и число"
|
||||
|
||||
[[step]]
|
||||
command = "airdef wave mix 40 1500"
|
||||
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
{
|
||||
"aircraft": [
|
||||
{
|
||||
"kind": "Gerbera",
|
||||
"item": null,
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Shahed",
|
||||
"item": "launch_shahed",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Geran3",
|
||||
"item": "launch_geran3",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Lancet",
|
||||
"item": "launch_lancet",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Kh101",
|
||||
"item": "launch_kh101",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Kalibr",
|
||||
"item": "launch_kalibr",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Kh22",
|
||||
"item": "launch_kh22",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Zircon",
|
||||
"item": "launch_zircon",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Iskander",
|
||||
"item": "launch_iskander",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Kinzhal",
|
||||
"item": "launch_kinzhal",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "Oreshnik",
|
||||
"item": "launch_oreshnik",
|
||||
"raid": true
|
||||
},
|
||||
{
|
||||
"kind": "OreshnikBlock",
|
||||
"item": null,
|
||||
"raid": false
|
||||
},
|
||||
{
|
||||
"kind": "OreshnikSub",
|
||||
"item": null,
|
||||
"raid": false
|
||||
}
|
||||
],
|
||||
"units": [
|
||||
{
|
||||
"kind": "Patriot",
|
||||
"item": "deploy_patriot"
|
||||
},
|
||||
{
|
||||
"kind": "Gepard",
|
||||
"item": "deploy_gepard"
|
||||
},
|
||||
{
|
||||
"kind": "Pantsir",
|
||||
"item": "deploy_pantsir"
|
||||
},
|
||||
{
|
||||
"kind": "S400",
|
||||
"item": "deploy_s400"
|
||||
},
|
||||
{
|
||||
"kind": "S500",
|
||||
"item": "deploy_s500"
|
||||
},
|
||||
{
|
||||
"kind": "IrisT",
|
||||
"item": "deploy_irist"
|
||||
},
|
||||
{
|
||||
"kind": "Nasams",
|
||||
"item": "deploy_nasams"
|
||||
},
|
||||
{
|
||||
"kind": "Buk",
|
||||
"item": "deploy_buk"
|
||||
},
|
||||
{
|
||||
"kind": "Tor",
|
||||
"item": "deploy_tor"
|
||||
},
|
||||
{
|
||||
"kind": "P1sun",
|
||||
"item": "deploy_p1sun"
|
||||
},
|
||||
{
|
||||
"kind": "Radar",
|
||||
"item": "deploy_radar"
|
||||
},
|
||||
{
|
||||
"kind": "Depot",
|
||||
"item": "deploy_depot"
|
||||
},
|
||||
{
|
||||
"kind": "Tzm",
|
||||
"item": "deploy_tzm"
|
||||
},
|
||||
{
|
||||
"kind": "Ew",
|
||||
"item": "deploy_ew"
|
||||
},
|
||||
{
|
||||
"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": [
|
||||
{
|
||||
"id": "designator",
|
||||
"title": "Целеуказатель",
|
||||
"color": [
|
||||
220,
|
||||
50,
|
||||
50
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_shahed",
|
||||
"title": "Пуск: Шахед-136",
|
||||
"color": [
|
||||
90,
|
||||
92,
|
||||
96
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_geran3",
|
||||
"title": "Пуск: Герань-3",
|
||||
"color": [
|
||||
30,
|
||||
30,
|
||||
34
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_patriot",
|
||||
"title": "Развернуть Patriot",
|
||||
"color": [
|
||||
76,
|
||||
86,
|
||||
58
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_gepard",
|
||||
"title": "Развернуть Гепард",
|
||||
"color": [
|
||||
104,
|
||||
84,
|
||||
54
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_pantsir",
|
||||
"title": "Развернуть Панцирь-С1",
|
||||
"color": [
|
||||
82,
|
||||
96,
|
||||
60
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_s400",
|
||||
"title": "Развернуть С-400",
|
||||
"color": [
|
||||
60,
|
||||
80,
|
||||
50
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_s500",
|
||||
"title": "Развернуть С-500",
|
||||
"color": [
|
||||
108,
|
||||
110,
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_lancet",
|
||||
"title": "Пуск: Ланцет-3",
|
||||
"color": [
|
||||
70,
|
||||
78,
|
||||
66
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_kh101",
|
||||
"title": "Пуск: Х-101",
|
||||
"color": [
|
||||
84,
|
||||
88,
|
||||
92
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_kalibr",
|
||||
"title": "Пуск: Калибр",
|
||||
"color": [
|
||||
150,
|
||||
154,
|
||||
156
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_kh22",
|
||||
"title": "Пуск: Х-22",
|
||||
"color": [
|
||||
226,
|
||||
228,
|
||||
222
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_zircon",
|
||||
"title": "Пуск: Циркон",
|
||||
"color": [
|
||||
52,
|
||||
54,
|
||||
52
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_iskander",
|
||||
"title": "Пуск: Искандер-М",
|
||||
"color": [
|
||||
108,
|
||||
110,
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_kinzhal",
|
||||
"title": "Пуск: Кинжал",
|
||||
"color": [
|
||||
60,
|
||||
62,
|
||||
60
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "launch_oreshnik",
|
||||
"title": "Пуск: Орешник",
|
||||
"color": [
|
||||
230,
|
||||
120,
|
||||
40
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_irist",
|
||||
"title": "Развернуть IRIS-T SLM",
|
||||
"color": [
|
||||
76,
|
||||
86,
|
||||
58
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_nasams",
|
||||
"title": "Развернуть NASAMS",
|
||||
"color": [
|
||||
76,
|
||||
86,
|
||||
58
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_buk",
|
||||
"title": "Развернуть Бук-М2",
|
||||
"color": [
|
||||
82,
|
||||
96,
|
||||
60
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_tor",
|
||||
"title": "Развернуть Тор-М2",
|
||||
"color": [
|
||||
108,
|
||||
110,
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_p1sun",
|
||||
"title": "Развернуть P1-SUN",
|
||||
"color": [
|
||||
52,
|
||||
54,
|
||||
52
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_radar",
|
||||
"title": "Развернуть РЛС дальнего обнаружения",
|
||||
"color": [
|
||||
108,
|
||||
110,
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_depot",
|
||||
"title": "Развернуть склад боеприпасов",
|
||||
"color": [
|
||||
92,
|
||||
78,
|
||||
48
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_tzm",
|
||||
"title": "Развернуть ТЗМ",
|
||||
"color": [
|
||||
82,
|
||||
96,
|
||||
60
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_ew",
|
||||
"title": "Развернуть станцию РЭБ",
|
||||
"color": [
|
||||
108,
|
||||
110,
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_light",
|
||||
"title": "Развернуть прожектор",
|
||||
"color": [
|
||||
52,
|
||||
54,
|
||||
52
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "deploy_optical",
|
||||
"title": "Развернуть оптический пост",
|
||||
"color": [
|
||||
70,
|
||||
110,
|
||||
90
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mover",
|
||||
"title": "Пульт перемещения",
|
||||
"color": [
|
||||
60,
|
||||
140,
|
||||
220
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "flare_gun",
|
||||
"title": "Осветительная ракета",
|
||||
"color": [
|
||||
255,
|
||||
240,
|
||||
180
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "remover",
|
||||
"title": "Свернуть ПВО",
|
||||
"color": [
|
||||
200,
|
||||
200,
|
||||
200
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
[
|
||||
{
|
||||
"event": "drone.shahed",
|
||||
"distance": 220,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "drone.geran3",
|
||||
"distance": 260,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "drone.lancet",
|
||||
"distance": 120,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "drone.cruise",
|
||||
"distance": 320,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "drone.rocket",
|
||||
"distance": 450,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "missile.flight",
|
||||
"distance": 380,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "drone.ballistic",
|
||||
"distance": 700,
|
||||
"far": false
|
||||
},
|
||||
{
|
||||
"event": "boom.sonic",
|
||||
"distance": 900,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.patriot",
|
||||
"distance": 650,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.s400_eject",
|
||||
"distance": 400,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.s400",
|
||||
"distance": 900,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.s500_eject",
|
||||
"distance": 500,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.s500",
|
||||
"distance": 1100,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "launch.pantsir",
|
||||
"distance": 500,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "gun.gepard",
|
||||
"distance": 400,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "gun.pantsir",
|
||||
"distance": 380,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "blast.big",
|
||||
"distance": 1000,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "blast.heavy",
|
||||
"distance": 1300,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "blast.huge",
|
||||
"distance": 1700,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "blast.medium",
|
||||
"distance": 700,
|
||||
"far": true
|
||||
},
|
||||
{
|
||||
"event": "blast.air",
|
||||
"distance": 800,
|
||||
"far": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,894 @@
|
||||
{
|
||||
"shared": {
|
||||
"mobility": {
|
||||
"drive_scale": 0.4,
|
||||
"drive_ramp": 8.0,
|
||||
"trainable": [0.12, 0.0],
|
||||
"vertical": [0.15, 0.0],
|
||||
"other": [0.05, 0.05]
|
||||
},
|
||||
"flight": {
|
||||
"gravity": 0.05,
|
||||
"block_split": 300.0
|
||||
},
|
||||
"logistics": {
|
||||
"depot_reach": 60.0,
|
||||
"handover": 10.0,
|
||||
"truck_load": 2,
|
||||
"stock_limit": 1000000
|
||||
}
|
||||
},
|
||||
"drones": [
|
||||
{
|
||||
"kind": "Shahed",
|
||||
"key": "shahed",
|
||||
"name": "Шахед-136",
|
||||
"model": "airdef:shahed",
|
||||
"speed": 0.6,
|
||||
"turn": 0.035,
|
||||
"cruise": 45.0,
|
||||
"clearance": 18.0,
|
||||
"dive": 32.0,
|
||||
"warhead": 3,
|
||||
"scale": 1.3,
|
||||
"engine": {"type": "prop", "back": 1.34, "size": 1.0},
|
||||
"decoy": false,
|
||||
"stealth": 1.0,
|
||||
"sound": {"event": "drone.shahed", "pitch": 1.0, "interval": 48},
|
||||
"class": "drone",
|
||||
"ballistic": null,
|
||||
"rcs": 0.3,
|
||||
"launch_sound": "launch.s400_eject"
|
||||
},
|
||||
{
|
||||
"kind": "Geran3",
|
||||
"key": "geran3",
|
||||
"name": "Герань-3",
|
||||
"model": "airdef:geran3",
|
||||
"speed": 1.6,
|
||||
"turn": 0.03,
|
||||
"cruise": 60.0,
|
||||
"clearance": 18.0,
|
||||
"dive": 50.0,
|
||||
"warhead": 2,
|
||||
"scale": 1.15,
|
||||
"engine": {"type": "jet", "up": 0.34, "back": 1.55, "size": 1.0},
|
||||
"decoy": false,
|
||||
"stealth": 1.1,
|
||||
"sound": {"event": "drone.geran3", "pitch": 1.0, "interval": 40},
|
||||
"class": "jet",
|
||||
"ballistic": null,
|
||||
"rcs": 0.4,
|
||||
"launch_sound": "launch.s400_eject"
|
||||
},
|
||||
{
|
||||
"kind": "Lancet",
|
||||
"key": "lancet",
|
||||
"name": "Ланцет-3",
|
||||
"model": "airdef:lancet",
|
||||
"speed": 1.1,
|
||||
"turn": 0.07,
|
||||
"cruise": 25.0,
|
||||
"clearance": 10.0,
|
||||
"dive": 38.0,
|
||||
"warhead": 1,
|
||||
"scale": 0.9,
|
||||
"engine": {"type": "prop", "back": 0.93, "size": 0.55},
|
||||
"decoy": false,
|
||||
"stealth": 1.4,
|
||||
"sound": {"event": "drone.lancet", "pitch": 1.0, "interval": 32},
|
||||
"class": "drone",
|
||||
"ballistic": null,
|
||||
"rcs": 0.08,
|
||||
"launch_sound": "launch.s400_eject"
|
||||
},
|
||||
{
|
||||
"kind": "Gerbera",
|
||||
"key": "gerbera",
|
||||
"name": "Гербера",
|
||||
"model": "airdef:gerbera",
|
||||
"speed": 0.5,
|
||||
"turn": 0.04,
|
||||
"cruise": 40.0,
|
||||
"clearance": 15.0,
|
||||
"dive": 30.0,
|
||||
"warhead": 0,
|
||||
"scale": 1.1,
|
||||
"engine": {"type": "prop", "back": 1.03, "size": 0.9},
|
||||
"decoy": true,
|
||||
"stealth": 0.9,
|
||||
"sound": {"event": "drone.shahed", "pitch": 1.3, "interval": 40},
|
||||
"class": "drone",
|
||||
"ballistic": null,
|
||||
"rcs": 0.4,
|
||||
"launch_sound": "launch.s400_eject"
|
||||
},
|
||||
{
|
||||
"kind": "Kh101",
|
||||
"key": "kh101",
|
||||
"name": "Х-101",
|
||||
"model": "airdef:kh101",
|
||||
"speed": 2.4,
|
||||
"turn": 0.025,
|
||||
"cruise": 0.0,
|
||||
"clearance": 12.0,
|
||||
"dive": 26.0,
|
||||
"warhead": 6,
|
||||
"scale": 1.6,
|
||||
"engine": {"type": "jet", "up": -0.27, "back": 1.4, "size": 0.6},
|
||||
"decoy": false,
|
||||
"stealth": 1.5,
|
||||
"sound": {"event": "drone.cruise", "pitch": 1.0, "interval": 50},
|
||||
"class": "cruise",
|
||||
"ballistic": null,
|
||||
"rcs": 0.05,
|
||||
"launch_sound": "launch.patriot"
|
||||
},
|
||||
{
|
||||
"kind": "Kalibr",
|
||||
"key": "kalibr",
|
||||
"name": "Калибр",
|
||||
"model": "airdef:kalibr",
|
||||
"speed": 2.1,
|
||||
"turn": 0.025,
|
||||
"cruise": 0.0,
|
||||
"clearance": 15.0,
|
||||
"dive": 26.0,
|
||||
"warhead": 5,
|
||||
"scale": 1.5,
|
||||
"engine": {"type": "jet", "up": -0.2, "back": 1.5, "size": 0.6},
|
||||
"decoy": false,
|
||||
"stealth": 1.3,
|
||||
"sound": {"event": "drone.cruise", "pitch": 1.2, "interval": 50},
|
||||
"class": "cruise",
|
||||
"ballistic": null,
|
||||
"rcs": 0.15,
|
||||
"launch_sound": "launch.patriot"
|
||||
},
|
||||
{
|
||||
"kind": "Kh22",
|
||||
"key": "kh22",
|
||||
"name": "Х-22",
|
||||
"model": "airdef:kh22",
|
||||
"speed": 4.0,
|
||||
"turn": 0.03,
|
||||
"cruise": 140.0,
|
||||
"clearance": 40.0,
|
||||
"dive": 150.0,
|
||||
"warhead": 7,
|
||||
"scale": 1.8,
|
||||
"engine": {"type": "rocket", "back": 1.5, "size": 1.3},
|
||||
"decoy": false,
|
||||
"stealth": 1.4,
|
||||
"sound": {"event": "drone.rocket", "pitch": 0.8, "interval": 46},
|
||||
"class": "supersonic",
|
||||
"ballistic": null,
|
||||
"rcs": 1.0,
|
||||
"launch_sound": "launch.patriot"
|
||||
},
|
||||
{
|
||||
"kind": "Zircon",
|
||||
"key": "zircon",
|
||||
"name": "Циркон",
|
||||
"model": "airdef:zircon",
|
||||
"speed": 5.5,
|
||||
"turn": 0.025,
|
||||
"cruise": 90.0,
|
||||
"clearance": 30.0,
|
||||
"dive": 110.0,
|
||||
"warhead": 6,
|
||||
"scale": 1.4,
|
||||
"engine": {"type": "rocket", "back": 1.5, "size": 1.1},
|
||||
"decoy": false,
|
||||
"stealth": 2.0,
|
||||
"sound": {"event": "drone.rocket", "pitch": 1.35, "interval": 46},
|
||||
"class": "supersonic",
|
||||
"ballistic": null,
|
||||
"rcs": 0.4,
|
||||
"launch_sound": "launch.s400"
|
||||
},
|
||||
{
|
||||
"kind": "Iskander",
|
||||
"key": "iskander",
|
||||
"name": "Искандер-М",
|
||||
"model": "airdef:iskander",
|
||||
"speed": 5.0,
|
||||
"turn": 0.04,
|
||||
"cruise": 0.0,
|
||||
"clearance": 0.0,
|
||||
"dive": 0.0,
|
||||
"warhead": 8,
|
||||
"scale": 1.8,
|
||||
"engine": {"type": "rocket", "back": 1.5, "size": 1.6},
|
||||
"decoy": false,
|
||||
"stealth": 1.6,
|
||||
"sound": {"event": "drone.rocket", "pitch": 0.7, "interval": 46},
|
||||
"class": "ballistic",
|
||||
"ballistic": 1000.0,
|
||||
"rcs": 0.6,
|
||||
"launch_sound": "launch.s500"
|
||||
},
|
||||
{
|
||||
"kind": "Kinzhal",
|
||||
"key": "kinzhal",
|
||||
"name": "Кинжал",
|
||||
"model": "airdef:kinzhal",
|
||||
"speed": 7.5,
|
||||
"turn": 0.03,
|
||||
"cruise": 0.0,
|
||||
"clearance": 0.0,
|
||||
"dive": 0.0,
|
||||
"warhead": 8,
|
||||
"scale": 1.7,
|
||||
"engine": {"type": "rocket", "back": 1.5, "size": 1.5},
|
||||
"decoy": false,
|
||||
"stealth": 2.2,
|
||||
"sound": {"event": "drone.rocket", "pitch": 0.6, "interval": 46},
|
||||
"class": "ballistic",
|
||||
"ballistic": 1500.0,
|
||||
"rcs": 0.5,
|
||||
"launch_sound": "launch.s500"
|
||||
},
|
||||
{
|
||||
"kind": "Oreshnik",
|
||||
"key": "oreshnik",
|
||||
"name": "Орешник",
|
||||
"model": "airdef:iskander",
|
||||
"speed": 9.0,
|
||||
"turn": 0.0,
|
||||
"cruise": 0.0,
|
||||
"clearance": 0.0,
|
||||
"dive": 0.0,
|
||||
"warhead": 0,
|
||||
"scale": 2.6,
|
||||
"engine": {"type": "rocket", "back": 1.5, "size": 2.4},
|
||||
"decoy": false,
|
||||
"stealth": 3.0,
|
||||
"sound": {"event": "drone.rocket", "pitch": 0.5, "interval": 46},
|
||||
"class": "ballistic",
|
||||
"ballistic": 2600.0,
|
||||
"rcs": 2.0,
|
||||
"launch_sound": "launch.s500"
|
||||
},
|
||||
{
|
||||
"kind": "OreshnikBlock",
|
||||
"key": "oreshnik_block",
|
||||
"name": "Орешник: блок",
|
||||
"model": "airdef:reentry",
|
||||
"speed": 9.0,
|
||||
"turn": 0.0,
|
||||
"cruise": 0.0,
|
||||
"clearance": 0.0,
|
||||
"dive": 0.0,
|
||||
"warhead": 4,
|
||||
"scale": 1.6,
|
||||
"engine": {"type": "rocket", "back": 1.0, "size": 1.0},
|
||||
"decoy": false,
|
||||
"stealth": 3.5,
|
||||
"sound": {"event": "drone.ballistic", "pitch": 0.8, "interval": 9999},
|
||||
"class": "ballistic",
|
||||
"ballistic": null,
|
||||
"rcs": 0.4,
|
||||
"launch_sound": "launch.s500"
|
||||
},
|
||||
{
|
||||
"kind": "OreshnikSub",
|
||||
"key": "oreshnik_sub",
|
||||
"name": "Орешник: суббоеприпас",
|
||||
"model": "airdef:reentry",
|
||||
"speed": 9.0,
|
||||
"turn": 0.05,
|
||||
"cruise": 0.0,
|
||||
"clearance": 0.0,
|
||||
"dive": 0.0,
|
||||
"warhead": 3,
|
||||
"scale": 1.1,
|
||||
"engine": {"type": "rocket", "back": 1.0, "size": 1.0},
|
||||
"decoy": false,
|
||||
"stealth": 4.0,
|
||||
"sound": {"event": "drone.ballistic", "pitch": 1.0, "interval": 9999},
|
||||
"class": "ballistic",
|
||||
"ballistic": null,
|
||||
"rcs": 0.08,
|
||||
"launch_sound": "launch.s500"
|
||||
}
|
||||
],
|
||||
"units": [
|
||||
{
|
||||
"kind": "Patriot",
|
||||
"key": "patriot",
|
||||
"name": "Patriot",
|
||||
"missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 450.0, "interval": 16},
|
||||
"gun": null,
|
||||
"reload": 220,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.66,
|
||||
"roles": 30,
|
||||
"family": "trainable",
|
||||
"parts": {
|
||||
"body": "airdef:patriot_trailer",
|
||||
"launcher": "airdef:patriot_launcher",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [["airdef:patriot_truck", 0.0, -3.0], ["airdef:patriot_radar", 0.0, 3.6]],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.69, 1.2],
|
||||
"pivot": [0.0, -0.5, 1.375],
|
||||
"muzzle": {"type": "patriot"},
|
||||
"sensor": 585.0,
|
||||
"mast": 5.0
|
||||
},
|
||||
{
|
||||
"kind": "Gepard",
|
||||
"key": "gepard",
|
||||
"name": "Гепард",
|
||||
"missile": null,
|
||||
"gun": {"range": 135.0, "track": 195.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]},
|
||||
"reload": 160,
|
||||
"scale": 1.25,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 7,
|
||||
"family": "gun",
|
||||
"parts": {
|
||||
"body": "airdef:gepard_hull",
|
||||
"launcher": "airdef:gepard_turret",
|
||||
"pack": "airdef:gepard_guns",
|
||||
"dish": ["airdef:gepard_dish", 0.95, 0.6, 0.0],
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [1.55, 0.25],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 255.0,
|
||||
"mast": 3.0
|
||||
},
|
||||
{
|
||||
"kind": "Pantsir",
|
||||
"key": "pantsir",
|
||||
"name": "Панцирь-С1",
|
||||
"missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 225.0, "interval": 14},
|
||||
"gun": {"range": 90.0, "track": 135.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]},
|
||||
"reload": 280,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 15,
|
||||
"family": "turret",
|
||||
"parts": {
|
||||
"body": "airdef:pantsir_truck",
|
||||
"launcher": "airdef:pantsir_turret",
|
||||
"pack": "airdef:pantsir_pack",
|
||||
"dish": ["airdef:pantsir_dish", 0.85, 0.3, 0.3],
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [1.35, 0.69],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "pantsir"},
|
||||
"sensor": 292.0,
|
||||
"mast": 4.0
|
||||
},
|
||||
{
|
||||
"kind": "S400",
|
||||
"key": "s400",
|
||||
"name": "С-400",
|
||||
"missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 720.0, "interval": 20},
|
||||
"gun": null,
|
||||
"reload": 420,
|
||||
"scale": 1.5,
|
||||
"rest_pitch": {"half_pi": -0.02},
|
||||
"roles": 30,
|
||||
"family": "vertical",
|
||||
"parts": {
|
||||
"body": "airdef:s400_chassis",
|
||||
"launcher": "airdef:s400_tubes",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": {"ref": "battery_radar"},
|
||||
"spinner": {"ref": "battery_spinner"}
|
||||
},
|
||||
"mount": [0.7, 1.45],
|
||||
"pivot": {"ref": "tube_pivot"},
|
||||
"muzzle": {"type": "grid", "cols": 2, "rows": 2, "size": 7.0},
|
||||
"sensor": 936.0,
|
||||
"mast": 5.0
|
||||
},
|
||||
{
|
||||
"kind": "S500",
|
||||
"key": "s500",
|
||||
"name": "С-500",
|
||||
"missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1050.0, "interval": 20},
|
||||
"gun": null,
|
||||
"reload": 520,
|
||||
"scale": 1.6,
|
||||
"rest_pitch": {"half_pi": -0.02},
|
||||
"roles": 24,
|
||||
"family": "vertical",
|
||||
"parts": {
|
||||
"body": "airdef:s500_chassis",
|
||||
"launcher": "airdef:s500_tubes",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": {"ref": "battery_radar"},
|
||||
"spinner": {"ref": "battery_spinner"}
|
||||
},
|
||||
"mount": [0.7, 1.45],
|
||||
"pivot": {"ref": "tube_pivot"},
|
||||
"muzzle": {"type": "grid", "cols": 2, "rows": 1, "size": 9.5},
|
||||
"sensor": 1365.0,
|
||||
"mast": 5.0
|
||||
},
|
||||
{
|
||||
"kind": "IrisT",
|
||||
"key": "irist",
|
||||
"name": "IRIS-T SLM",
|
||||
"missile": {"kind": "IrisT", "magazine": 8, "min": 15.0, "max": 600.0, "interval": 10},
|
||||
"gun": null,
|
||||
"reload": 300,
|
||||
"scale": 1.4,
|
||||
"rest_pitch": {"half_pi": -0.02},
|
||||
"roles": 15,
|
||||
"family": "vertical",
|
||||
"parts": {
|
||||
"body": "airdef:irist_chassis",
|
||||
"launcher": "airdef:irist_tubes",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": {"ref": "battery_radar"},
|
||||
"spinner": {"ref": "battery_spinner"}
|
||||
},
|
||||
"mount": [0.7, 1.45],
|
||||
"pivot": {"ref": "tube_pivot"},
|
||||
"muzzle": {"type": "grid", "cols": 4, "rows": 2, "size": 4.0},
|
||||
"sensor": 780.0,
|
||||
"mast": 5.0
|
||||
},
|
||||
{
|
||||
"kind": "Nasams",
|
||||
"key": "nasams",
|
||||
"name": "NASAMS",
|
||||
"missile": {"kind": "Amraam", "magazine": 6, "min": 10.0, "max": 450.0, "interval": 14},
|
||||
"gun": null,
|
||||
"reload": 260,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.5,
|
||||
"roles": 14,
|
||||
"family": "trainable",
|
||||
"parts": {
|
||||
"body": "airdef:nasams_trailer",
|
||||
"launcher": "airdef:nasams_launcher",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [["airdef:radar_trailer", 0.0, 3.4]],
|
||||
"spinner": ["airdef:radar_panel", 0.9, 3.4, 0.6, -0.3]
|
||||
},
|
||||
"mount": [0.62, 0.4],
|
||||
"pivot": {"ref": "tube_pivot"},
|
||||
"muzzle": {"type": "grid", "cols": 3, "rows": 2, "size": 4.0},
|
||||
"sensor": 585.0,
|
||||
"mast": 5.0
|
||||
},
|
||||
{
|
||||
"kind": "Buk",
|
||||
"key": "buk",
|
||||
"name": "Бук-М2",
|
||||
"missile": {"kind": "M9m317", "magazine": 4, "min": 20.0, "max": 675.0, "interval": 18},
|
||||
"gun": null,
|
||||
"reload": 400,
|
||||
"scale": 1.4,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 14,
|
||||
"family": "turret",
|
||||
"parts": {
|
||||
"body": "airdef:buk_chassis",
|
||||
"launcher": "airdef:buk_turret",
|
||||
"pack": "airdef:buk_rails",
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [1.55, 0.2],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "rails", "xs": [-9.0, -3.0, 13.0, 19.0]},
|
||||
"sensor": 878.0,
|
||||
"mast": 4.0
|
||||
},
|
||||
{
|
||||
"kind": "Tor",
|
||||
"key": "tor",
|
||||
"name": "Тор-М2",
|
||||
"missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 240.0, "interval": 8},
|
||||
"gun": null,
|
||||
"reload": 300,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 15,
|
||||
"family": "vertical",
|
||||
"parts": {
|
||||
"body": "airdef:tor_chassis",
|
||||
"launcher": "airdef:tor_turret",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [1.5, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "cells"},
|
||||
"sensor": 315.0,
|
||||
"mast": 3.5
|
||||
},
|
||||
{
|
||||
"kind": "P1sun",
|
||||
"key": "p1sun",
|
||||
"name": "P1-SUN",
|
||||
"missile": {"kind": "P1sun", "magazine": 8, "min": 5.0, "max": 675.0, "interval": 12},
|
||||
"gun": null,
|
||||
"reload": 240,
|
||||
"scale": 1.1,
|
||||
"rest_pitch": 0.35,
|
||||
"roles": 1,
|
||||
"family": "trainable",
|
||||
"parts": {
|
||||
"body": "airdef:nasams_trailer",
|
||||
"launcher": "airdef:p1sun_launcher",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.6, 0.3],
|
||||
"pivot": {"ref": "tube_pivot"},
|
||||
"muzzle": {"type": "grid", "cols": 4, "rows": 2, "size": 3.0},
|
||||
"sensor": 0.0,
|
||||
"mast": 2.0
|
||||
},
|
||||
{
|
||||
"kind": "Radar",
|
||||
"key": "radar",
|
||||
"name": "РЛС дальнего обнаружения",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.5,
|
||||
"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, 1.2, 1.5, -0.25]
|
||||
},
|
||||
"mount": [0.0, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 2550.0,
|
||||
"mast": 16.0
|
||||
},
|
||||
{
|
||||
"kind": "Depot",
|
||||
"key": "depot",
|
||||
"name": "Склад боеприпасов",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.5,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 0,
|
||||
"family": "static",
|
||||
"parts": {
|
||||
"body": "airdef:depot",
|
||||
"launcher": null,
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.0, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 0.0,
|
||||
"mast": 1.0
|
||||
},
|
||||
{
|
||||
"kind": "Tzm",
|
||||
"key": "tzm",
|
||||
"name": "ТЗМ",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 0,
|
||||
"family": "truck",
|
||||
"parts": {
|
||||
"body": "airdef:tzm_truck",
|
||||
"launcher": null,
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.0, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 0.0,
|
||||
"mast": 2.0
|
||||
},
|
||||
{
|
||||
"kind": "Ew",
|
||||
"key": "ew",
|
||||
"name": "Станция РЭБ",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.3,
|
||||
"rest_pitch": 0.0,
|
||||
"roles": 0,
|
||||
"family": "static",
|
||||
"parts": {
|
||||
"body": "airdef:ew_truck",
|
||||
"launcher": null,
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.0, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"muzzle": {"type": "none"},
|
||||
"sensor": 0.0,
|
||||
"mast": 3.0
|
||||
},
|
||||
{
|
||||
"kind": "Light",
|
||||
"key": "light",
|
||||
"name": "Прожектор",
|
||||
"missile": null,
|
||||
"gun": null,
|
||||
"reload": 0,
|
||||
"scale": 1.2,
|
||||
"rest_pitch": 0.6,
|
||||
"roles": 0,
|
||||
"family": "light",
|
||||
"parts": {
|
||||
"body": "airdef:searchlight",
|
||||
"launcher": "airdef:searchlight_head",
|
||||
"pack": null,
|
||||
"dish": null,
|
||||
"fixed": [],
|
||||
"spinner": null
|
||||
},
|
||||
"mount": [0.85, 0.0],
|
||||
"pivot": [0.0, 0.0, 0.0],
|
||||
"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": [
|
||||
{
|
||||
"kind": "Pac3",
|
||||
"model": "airdef:pac3",
|
||||
"speed": 5.5,
|
||||
"accel": 0.35,
|
||||
"turn": 0.3,
|
||||
"boost": 8,
|
||||
"cold": 0,
|
||||
"eject": 0.0,
|
||||
"eject_drag": 0.0,
|
||||
"pk": 0.9,
|
||||
"fuse": 4.0,
|
||||
"life": 240,
|
||||
"scale": 1.0,
|
||||
"flame": 1.0,
|
||||
"rear": 28.0,
|
||||
"seeker": 110.0,
|
||||
"launch_sound": "launch.patriot",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.0}
|
||||
},
|
||||
{
|
||||
"kind": "M57e6",
|
||||
"model": "airdef:m57e6",
|
||||
"speed": 5.0,
|
||||
"accel": 0.5,
|
||||
"turn": 0.32,
|
||||
"boost": 5,
|
||||
"cold": 0,
|
||||
"eject": 0.0,
|
||||
"eject_drag": 0.0,
|
||||
"pk": 0.82,
|
||||
"fuse": 3.0,
|
||||
"life": 160,
|
||||
"scale": 0.85,
|
||||
"flame": 0.65,
|
||||
"rear": 28.0,
|
||||
"seeker": 0.0,
|
||||
"launch_sound": "launch.pantsir",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.12}
|
||||
},
|
||||
{
|
||||
"kind": "M48n6",
|
||||
"model": "airdef:m48n6",
|
||||
"speed": 7.0,
|
||||
"accel": 0.5,
|
||||
"turn": 0.22,
|
||||
"boost": 8,
|
||||
"cold": 20,
|
||||
"eject": 2.4,
|
||||
"eject_drag": 0.07,
|
||||
"pk": 0.9,
|
||||
"fuse": 5.0,
|
||||
"life": 300,
|
||||
"scale": 1.5,
|
||||
"flame": 1.4,
|
||||
"rear": 30.0,
|
||||
"seeker": 120.0,
|
||||
"launch_sound": "launch.s400_eject",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.88}
|
||||
},
|
||||
{
|
||||
"kind": "M77n6",
|
||||
"model": "airdef:m77n6",
|
||||
"speed": 9.0,
|
||||
"accel": 0.6,
|
||||
"turn": 0.22,
|
||||
"boost": 8,
|
||||
"cold": 24,
|
||||
"eject": 2.6,
|
||||
"eject_drag": 0.07,
|
||||
"pk": 0.95,
|
||||
"fuse": 6.0,
|
||||
"life": 320,
|
||||
"scale": 1.7,
|
||||
"flame": 1.6,
|
||||
"rear": 32.0,
|
||||
"seeker": 120.0,
|
||||
"launch_sound": "launch.s500_eject",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.8}
|
||||
},
|
||||
{
|
||||
"kind": "IrisT",
|
||||
"model": "airdef:irist_missile",
|
||||
"speed": 7.0,
|
||||
"accel": 0.5,
|
||||
"turn": 0.35,
|
||||
"boost": 6,
|
||||
"cold": 8,
|
||||
"eject": 1.8,
|
||||
"eject_drag": 0.1,
|
||||
"pk": 0.9,
|
||||
"fuse": 4.0,
|
||||
"life": 260,
|
||||
"scale": 0.95,
|
||||
"flame": 0.9,
|
||||
"rear": 28.0,
|
||||
"seeker": 90.0,
|
||||
"launch_sound": "launch.s400_eject",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.05}
|
||||
},
|
||||
{
|
||||
"kind": "Amraam",
|
||||
"model": "airdef:amraam_missile",
|
||||
"speed": 6.0,
|
||||
"accel": 0.45,
|
||||
"turn": 0.3,
|
||||
"boost": 6,
|
||||
"cold": 0,
|
||||
"eject": 0.0,
|
||||
"eject_drag": 0.0,
|
||||
"pk": 0.85,
|
||||
"fuse": 4.0,
|
||||
"life": 260,
|
||||
"scale": 0.9,
|
||||
"flame": 0.9,
|
||||
"rear": 28.0,
|
||||
"seeker": 130.0,
|
||||
"launch_sound": "launch.patriot",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.05}
|
||||
},
|
||||
{
|
||||
"kind": "M9m317",
|
||||
"model": "airdef:m48n6",
|
||||
"speed": 6.5,
|
||||
"accel": 0.5,
|
||||
"turn": 0.25,
|
||||
"boost": 8,
|
||||
"cold": 0,
|
||||
"eject": 0.0,
|
||||
"eject_drag": 0.0,
|
||||
"pk": 0.85,
|
||||
"fuse": 5.0,
|
||||
"life": 300,
|
||||
"scale": 1.1,
|
||||
"flame": 1.2,
|
||||
"rear": 32.0,
|
||||
"seeker": 90.0,
|
||||
"launch_sound": "launch.patriot",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.9}
|
||||
},
|
||||
{
|
||||
"kind": "M9m338",
|
||||
"model": "airdef:m57e6",
|
||||
"speed": 5.5,
|
||||
"accel": 0.6,
|
||||
"turn": 0.4,
|
||||
"boost": 4,
|
||||
"cold": 8,
|
||||
"eject": 1.6,
|
||||
"eject_drag": 0.1,
|
||||
"pk": 0.9,
|
||||
"fuse": 3.0,
|
||||
"life": 160,
|
||||
"scale": 1.0,
|
||||
"flame": 0.8,
|
||||
"rear": 28.0,
|
||||
"seeker": 70.0,
|
||||
"launch_sound": "launch.s400_eject",
|
||||
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.15}
|
||||
},
|
||||
{
|
||||
"kind": "P1sun",
|
||||
"model": "airdef:p1sun",
|
||||
"speed": 2.8,
|
||||
"accel": 0.12,
|
||||
"turn": 0.3,
|
||||
"boost": 4,
|
||||
"cold": 0,
|
||||
"eject": 0.0,
|
||||
"eject_drag": 0.0,
|
||||
"pk": 0.8,
|
||||
"fuse": 3.0,
|
||||
"life": 900,
|
||||
"scale": 0.8,
|
||||
"flame": 0.0,
|
||||
"rear": 10.0,
|
||||
"seeker": 60.0,
|
||||
"launch_sound": "drone.lancet",
|
||||
"voice": {"event": "drone.lancet", "gain": 0.8, "pitch": 1.6}
|
||||
}
|
||||
],
|
||||
"named": {
|
||||
"battery_radar": {
|
||||
"kind": "fixed",
|
||||
"value": [["airdef:radar_trailer", 0.0, 4.2]]
|
||||
},
|
||||
"battery_spinner": {
|
||||
"kind": "spinner",
|
||||
"value": ["airdef:radar_panel", 0.9, 4.2, 0.9, -0.3]
|
||||
},
|
||||
"tube_pivot": {
|
||||
"kind": "pivot",
|
||||
"value": [0.0, -0.5, 1.5]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
@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
@@ -0,0 +1,9 @@
|
||||
@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" %*
|
||||
@@ -1,5 +1,12 @@
|
||||
# Акустика AirDef: реализация, проверки и разбор Sound Physics Remastered (#96)
|
||||
|
||||
4 ноября добавлен opt-in массовый offline capture fixture: 100 движущихся двигателей и до
|
||||
16 импульсных источников, настоящие `Audio::tick_acoustics`/`film_mix`, две одинаковые дорожки,
|
||||
сброс хвоста при новом capture. Release на Apple M5: p50 3.55 мс, p95 4.30 мс, max 5.57 мс
|
||||
на 50 мс аудио. Геометрия и сэмплы синтетические; это не полный игровой CPU/GPU/FPS и не MP4.
|
||||
[Команда, результат и оставшаяся приёмка](CONTINUATION-2026-11-04.md),
|
||||
[JSON и SHA дорожки](measurements/mass-acoustics-2026-11-04.json).
|
||||
|
||||
Сначала приведён текущий статус реализации. Разбор SPR и первоначальный план ниже сохранены как
|
||||
история решений; формулировки будущего времени в плане не заменяют текущий статус. При расхождении прав код.
|
||||
|
||||
@@ -48,6 +55,43 @@ GPL-файлы три: `acoustics/spr_occlusion.rs`, (стадия 2) `acoustics
|
||||
выстрел 1.5 с на 60 блоках, стена камня в 2 блока: ниже 300 Гц -5.2 дБ (SPR: gain 0.55), 300-1500 -7.4, 1500-5000 -19.7, выше 5000 -40.0 дБ.
|
||||
Тесты: `cargo test -p horizon-client --lib acoustics` (формулы, неизвестное, щель, кеш, инвалидация, детерминизм, рабочий поток) и `audio`.
|
||||
|
||||
### Настоящий MP4 с включённой акустикой (4 ноября, pin `73b9d3070`, API 29)
|
||||
|
||||
Пары настоящих экспортов одного и того же повтора, с акустикой и без: кнопка мода «Акустика
|
||||
(преграды, эхо)», затем тот же `/airdef replay export` (640×360, 30 fps, crf 20), offscreen Metal,
|
||||
ffmpeg 9.0.1, scratch `HORIZON_HOME`/мир (не сохранения игрока). `HORIZON_ACOUSTICS=1` без
|
||||
`HORIZON_NO_AUDIO`. В сохранённом мире значение акустики хранится в состоянии мода, поэтому env
|
||||
задаёт только начальное значение: в проверке её включали и выключали кнопкой.
|
||||
|
||||
Статусы в игре во время и после экспорта: `Акустика: API=true, включено=true, запрос=true,
|
||||
подготовлено=true, ready`; `Захват этого мода: запрос=true, подготовлено=true, ready`. Контроль
|
||||
`HORIZON_ACOUSTICS=1` + `HORIZON_NO_AUDIO=1`: `включено=true, запрос=true, подготовлено=false,
|
||||
awaiting-backend` — ожидаемое отсутствие offline-микшера, не замена звуковому MP4.
|
||||
|
||||
| Сцена | ON: кадры/с | OFF: кадры/с | RMS ON/OFF | пик ON/OFF | L/R corr ON/OFF | centroid ON/OFF | HF>4k ON/OFF |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| поле, 3 события, `sec=4` | 123/4.100 | 124/4.133 | −23.53/−23.26 | −7.18/−5.60 | 0.675/0.627 | 1089/1382 Гц | 0.071/0.095 |
|
||||
| поле, 1 событие, весь фильм | 351/11.700 | 352/11.733 | −32.18/−16.19 | −12.41/−2.65 | 0.829/0.963 | 1157/1862 Гц | 0.075/0.138 |
|
||||
| каменный двор 80×100×30 (стены), весь фильм | 430/14.333 | 430/14.333 | −22.06/−20.09 | −5.97/−5.76 | 0.915/0.985 | 232/652 Гц | 0.005/0.039 |
|
||||
|
||||
Все пары — `h264` + AAC 48 кГц stereo, без обрезки звука; файлы `airdef-films/{ac,one,court}_{on,off}.mp4`
|
||||
в scratch. Уже это показывает, что акустика реально обрабатывает дорожку фильма: в каменном дворе
|
||||
OFF почти моно (L/R 0.985–1.000), ON декоррелирован (0.915); centroid и доля >4 кГц падают, как и
|
||||
ожидается от окклюзии/воздушного поглощения; в поле ON тише OFF до 16 дБ по RMS за рельефом.
|
||||
|
||||
Реверб/эхо: в каменном дворе отрезок 9–14 с (после склейки) описывается ON ≈ g·OFF, g = −2.03 дБ
|
||||
(лучшее совмещение −32 сэмпла = 0.67 мс). Остаток −25.18 dBFS при сигнале −17.61 dBFS (на 7.6 дБ
|
||||
ниже), centroid 546 Гц, доля >4 кГц 0.009, L/R corr 0.495: низкочастотный диффузный
|
||||
декоррелированный компонент — это wet-путь (реверб/эхо), а не масштаб сухого сигнала. В открытом
|
||||
поле send реверба равен нулю по построению (`acoustics/room.rs`: `a field has no send`), поэтому
|
||||
поле показывает только окклюзию/поглощение, а реверб — только в замкнутой геометрии.
|
||||
|
||||
Ограничения: чистый хвост/RT60 в настоящем MP4 не выделен — в замкнутом зале ON-дорожка была на
|
||||
30–40 дБ тише (сильная окклюзия), а в открытом дворе длинный сэмпл взрыва (`blast_big`, 15 с; его
|
||||
21 Гц тон виден в дорожке) маскирует хвост; камеру в комнате с источником и тишиной после него в
|
||||
этом проходе получить не удалось. Ранние отражения отдельно не измерены. Субъективного
|
||||
прослушивания не было; 10-минутный экспорт, Windows/Linux и полный бой не проверялись.
|
||||
|
||||
### Стадия 2: эхо (сделано)
|
||||
|
||||
Что игрок получает: взрыв в ущелье или между домами отвечает настоящим эхо от тех стен, что там есть, с задержкой по
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Модели летательных аппаратов (#115)
|
||||
|
||||
Это промежуточные игровые стилизации. У «Ланцета» две пары Х-образных крыльев получили ступенчатые стреловидные кромки, переработан нос и добавлены детали корпуса. У Х-101 изменена стреловидность развёрнутых крыльев; корпус, хвост и подфюзеляжный элемент сохранены. Идентификаторы, положение винта и состав частей не изменены. Число элементов: «Ланцет» 17 → 49, Х-101 22 → 30. Влияние на производительность не измерено.
|
||||
|
||||
| Модель | До | После |
|
||||
|---|---|---|
|
||||
| Ланцет |  |  |
|
||||
| Х-101 |  |  |
|
||||
|
||||
Дополнительные ракурсы: [Ланцет до](media/aircraft-pass/lancet-before-nose.png), [Ланцет после](media/aircraft-pass/lancet-after-nose.png), [Х-101 до](media/aircraft-pass/kh101-before-nose.png), [Х-101 после](media/aircraft-pass/kh101-after-nose.png).
|
||||
|
||||
## Проверка игрового инстанса
|
||||
|
||||
| До | После |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
[Ракурс сверху до](media/aircraft-pass/lancet-instance-before-top.png) · [ракурс сверху после](media/aircraft-pass/lancet-instance-after-top.png).
|
||||
|
||||
Проверочный мод `tools/model-preview` выставляет модель через игровой `render.set-models` с `glow=false` и HD-освещением в открытом воздухе. На этих кадрах видны цвет, крылья и нос; это статичный инстанс, полёт и анимация не проверены. Различия яркости наклонных сегментов на старых кадрах исправлены в #123.
|
||||
|
||||
## Исправление нормалей (#123)
|
||||
|
||||
| До | После |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
[Сверху после исправления](media/aircraft-pass/lancet-instance-normal-fix-top.png) · [ночь после исправления](media/aircraft-pass/lancet-instance-normal-fix-night.png).
|
||||
|
||||
Пара «до/после» снята в одном scratch-мире, с одинаковыми координатами камеры, временем и погодой на Apple M5/Metal. Динамический block-model путь теперь вычисляет нормаль из неколлинеарных вершин квада и использует прежний осевой fallback только для вырожденной геометрии. Unit-тест покрывает оба знака наклона 45°, другие углы, осевые и вырожденные квады. Массовая производительность и полёт этой проверкой не измерялись.
|
||||
|
||||
Остальные снимки выше показывают модели как установленные блоки в изолированных мирах Horizon, offscreen, без звука, при времени 6000 и ясной погоде, со светящейся платформой и одинаковыми координатами камеры. В пакетах одинаковы код и остальные ресурсы; для варианта «до» заменены два JSON модели на версии d410e2c. Оба блока после установки проверены через `block`. Ландшафт и состояние подгрузки различаются; снимки не ретушированы. Непрозрачный установленный блок местами выглядит почти чёрным, поэтому его снимки нельзя использовать для оценки освещения игровых инстансов. В исходной серии ночное освещение не проверялось; ночной кадр Lancet после #123 представлен выше. Массовая производительность не проверена; художественная приёмка остаётся открытой.
|
||||
|
||||
Редактируемые источники — `airdef-mod/source-assets/assets/airdef/models/block/{lancet,kh101}.json`. Для переэкспорта запустите `python3 tools/aircraft_models.py`, затем `python3 tools/gen_models.py` для установки ресурсов и пересчёта габаритов.
|
||||
@@ -42,24 +42,36 @@
|
||||
/airdef battery
|
||||
```
|
||||
|
||||
Нумерацию существующей техники показывает `/airdef battery`. Чтобы переоборудовать её:
|
||||
Нумерацию существующей техники показывает `/airdef battery`:
|
||||
|
||||
```text
|
||||
/airdef battery <номер С-400 или С-500> launcher
|
||||
/airdef radar <номер РЛС> search
|
||||
/airdef radar <номер другой РЛС> engagement
|
||||
/airdef battery <номер С-400 или С-500> integrated
|
||||
/airdef radar <номер РЛС> on|off
|
||||
```
|
||||
|
||||
Можно оставить одну многофункциональную РЛС (`multi`) и несколько пусковых.
|
||||
Поисковая/мачтовая РЛС даёт подсказку, но не разрешает огонь сама. РЛС сопровождения принимает
|
||||
подсказку и должна **сама измерить** цель в своей игровой досягаемости и с учётом рельефа.
|
||||
Чужой трек не превращается в собственное измерение. После этого связанные пусковые используют
|
||||
общую картину и существующее распределение целей. Если РЛС сопровождения уничтожена, свёрнута,
|
||||
Профиль РЛС задаётся при размещении (`radar_search`, `radar_track`, `radar_height`) и не
|
||||
переключается на ходу: `radar <номер> search|engagement|height` больше не меняет оборудование.
|
||||
Можно оставить одну многофункциональную РЛС (`multi`, старые сохранения) и несколько пусковых.
|
||||
|
||||
- **Обзорная** (`radar_search`): широкая дальность и ранние грубые отметки, медленный оборот,
|
||||
без каналов уточнения. Права на пуск не даёт.
|
||||
- **Мачтовая** (`radar_height`): поднятая антенна и лучшее вертикальное измерение уточняют низкие
|
||||
контакты в локальной зоне; рельеф по-прежнему скрывает цель. Права на пуск не даёт.
|
||||
- **Сопровождения** (`radar_track`): локальный поиск, электронный оборот, два канала точных
|
||||
треков. Сеть может подсказать, но станция должна **сама измерить** цель; только собственное
|
||||
подтверждённое измерение разрешает пуск.
|
||||
- **Многофункциональная** (`multi`): совместимый универсальный вариант, но не лучший во всём.
|
||||
|
||||
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
|
||||
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
|
||||
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
|
||||
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
|
||||
продолжают штатную игровую логику связи/памяти/самонаведения.
|
||||
|
||||
Старые миры и обычные `/airdef deploy s400` / `s500` сохраняют сборную конфигурацию `integrated`.
|
||||
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями.
|
||||
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями; новые
|
||||
сохранения пишут устойчивый ID профиля, старые строки только с ролью читаются как те же профили.
|
||||
У прежнего игрового С-500 был магазин на четыре ракеты при двух нарисованных ТПК;
|
||||
теперь он согласован с двумя физическими ячейками. При загрузке старой расстановки
|
||||
его загруженный остаток ограничивается новой вместимостью, как при обычном восстановлении боезапаса.
|
||||
@@ -69,13 +81,26 @@
|
||||
1. Подготовка резервирует конкретную ячейку. Отдельная крышка ТПК открывается; ракета ещё не расходуется.
|
||||
2. При потере цели или неисправности/сворачивании носителя до выброса подготовка отменяется.
|
||||
3. Ракета выбрасывается из фактического muzzle. Боекомплект уменьшается один раз; использованный ТПК остаётся открытым.
|
||||
4. В фазе выброса отсутствуют факел, непрерывный звук двигателя и его дымовой след.
|
||||
5. После зажигания включаются эффекты, ракета разгоняется и начинает поворот по существующей игровой логике.
|
||||
4. Выброс идёт без двигателя: ракета поднимается и линейно теряет скорость под газовым сопротивлением.
|
||||
Длительность считается от выброса, а не от открытия крышки: у С-400 (`M48n6`) 20 тиков — 1,00 с,
|
||||
у С-500 (`M77n6`) 24 тика — 1,20 с, у IRIS-T и Тора (`IrisT`/`M9m338`) 8 тиков — 0,40 с.
|
||||
В этой фазе нет факела, непрерывного звука двигателя, моторного света и powered smoke; остаётся
|
||||
только отдельный газовый хлопок/клуб.
|
||||
5. Зажигание — отдельное событие в текущей точке ракеты, а не у оставленной ПУ: там же появляются
|
||||
вспышка, факел, звук и запись `MotorIgnition`. Оно наступает после `cold` тиков выброса.
|
||||
6. После зажигания начинается departure: тяга плавно нарастает от 45% к 100%, а допустимый темп
|
||||
поворота — от 20% к полному за `boost` тиков. Полное наведение (включая самонаведение и облёт
|
||||
рельефа) включается только при `age >= cold + boost`; при увеличении `cold` оно не может
|
||||
включиться раньше мотора. Максимальная скорость, `pk`, `turn` и правила столкновений не менялись.
|
||||
|
||||
Это действует для зенитных С-400/С-500 и подготовленного ударного RM48U у С-400.
|
||||
У ручного удара носитель и ячейка резервируются до пуска; изменение состояния отменяет подготовку
|
||||
без расхода. Для RM48U добавлен плавный разгон после выброса. Задержанный ручной приказ
|
||||
не возобновляется после загрузки мира: незапущенный боеприпас остаётся в носителе.
|
||||
без расхода. RM48U использует ту же 20-тиковую хореографию: неосвещённый выброс, зажигание в текущей
|
||||
точке, затем разгон; насчитанное время полёта включает выброс, а записанный дым начинается у точки
|
||||
зажигания. Задержанный ручной приказ не возобновляется после загрузки мира: незапущенный боеприпас
|
||||
остаётся в носителе. Ракеты с рельсовым (горячим) пуском тоже получили плавное нарастание тяги за
|
||||
свой `boost`, но не холодный выброс; электрический P1-SUN сохраняет постоянный разгон и не получает
|
||||
ракетную струю.
|
||||
|
||||
В записи сохраняются конфигурация машины, использованные ячейки и положение крышки;
|
||||
повтор восстанавливает их по своей временной шкале. Записанный дым начинается у точки зажигания,
|
||||
@@ -83,26 +108,39 @@
|
||||
|
||||
## Ограничения
|
||||
|
||||
Роли РЛС и мачта пока используют общую модель машины, с разным поведением/отображением антенны.
|
||||
Отдельные точные модели 91Н6/92Н6/96Л6, машина КП, ручная принадлежность к батарее, отдельные
|
||||
каналы сопровождения и кабельное снабжение пока не добавлены. Подробные режимы и параметры реальных
|
||||
Все три профиля пока используют общий силуэт машины и антенны (отдельная художественная зона
|
||||
владельца): различаются поведение, цикл, точность, каналы и подпись. Точные модели 91Н6/92Н6/96Л6,
|
||||
машина КП, ручная принадлежность к батарее и кабельное снабжение не добавлены. Подробные режимы и параметры реальных
|
||||
комплексов не моделируются. В следующей серии добавлены конечная работа двигателя/coast (#120),
|
||||
доставка RM48U через ТЗМ (#118), переключение излучения (#121) и укрытия от непрямого blast (#119).
|
||||
Текущий объём и ограничения описаны в [техническом журнале](CODEX-HANDOFF.md).
|
||||
|
||||
## Проверка в игре и тестами
|
||||
|
||||
Исходный код батареи и команды опубликованы в `966b52f`. Для этой контрольной точки прошли
|
||||
169 тестов ядра и 4 сценария (7 отдельных тестов помечены ignored), а также 53 теста адаптера,
|
||||
проверка границы с ядром и ещё 4 сценария. Настоящий собранный WASM-пакет прошёл 21 шаг
|
||||
`wasm_contract.toml`, включая конфигурацию батареи и развёртывание новых пресетов.
|
||||
Генератор моделей не обнаружил различий с исходниками.
|
||||
Историческая контрольная точка батареи и команд — `966b52f`: 169 тестов ядра и 4 сценария
|
||||
(7 ignored), 53 теста адаптера, проверка границы с ядром и ещё 4 сценария; настоящий WASM-пакет
|
||||
прошёл 21 шаг `wasm_contract.toml`, генератор моделей не нашёл различий.
|
||||
|
||||
Отдельный тест симуляции проверяет открытие до расхода, отмену при повреждении,
|
||||
однократное списание при выбросе, отсутствие голоса двигателя до зажигания и последующий рост скорости.
|
||||
Тест повтора проверяет перемотку состояния крышек и конфигурации пусковой туда и обратно.
|
||||
Контрольная точка #129 — `4b013fb7f30dbaa87a266b27a31911937fc523b4` (ветка
|
||||
`agent/issue-129-cold-launch`): core release **206 + 8 сценариев** (8 ignored), адаптер
|
||||
**67 + 1 boundary + 5 сценариев**, настоящий WASM **30 шагов**, `gen_catalog.py --check` без
|
||||
расхождений, `gen_models.py --check` без различий, `test_gen_assets.py` — 10 тестов.
|
||||
|
||||
Ниже — исходные кадры из изолированного тестового мира Horizon, Metal, 2560×1440.
|
||||
Отдельные тесты проверяют открытие до расхода, отмену при повреждении, однократное списание при
|
||||
выбросе, отсутствие голоса/факела до зажигания, записанное зажигание через `cold` тиков после
|
||||
выброса, плавные ограничения скорости и поворота для всех профилей, а также RM48U без powered
|
||||
эффектов до зажигания. Тест повтора проверяет перемотку состояния крышек и конфигурации ПУ туда и
|
||||
обратно и отсутствие дыма до записанного зажигания.
|
||||
|
||||
Сравнительная выборка #129 (те же seed, что у сетки #120; 6 вариантов × 8 seed, 2208 целей на
|
||||
сторону): сбито 1988 → 1939, прорывов 216 → 258, ракет 3461 → 3467; `energy_lost` 0 → 0,
|
||||
`expired` 1 → 0, сорванных о рельеф 2 → 4. Близкие (`near200`) 318 → 311 сбитых, дальние
|
||||
(`far1500`) 338 → 334, холмы (`hills20`) 334 → 319. Отдельные 12 seed `SAMS=20 SIZE=12`:
|
||||
203 → 201 сбитых, 1 → 3 прорыва, 355 → 360 ракет. Это ожидаемое следствие более длинного старта,
|
||||
а не скрытая компенсация: `pk`, максимальные скорости и столкновения не менялись. Данные:
|
||||
[сетка](measurements/issue-129-grid.csv), [рейды](measurements/issue-129-balance.csv).
|
||||
|
||||
Ниже — исходные кадры крышек из изолированного тестового мира Horizon, Metal, 2560×1440.
|
||||
На первом четыре малые крышки ТПК закрыты; на втором одна поднята, остальные закрыты.
|
||||
Большая прямоугольная панель позади труб — навесная РЛС конфигурации `integrated`.
|
||||
|
||||
@@ -114,5 +152,59 @@
|
||||
`3fae616902563b01e6463a32687c062d5983c4e94bd357f8f8129744d859f4d7`;
|
||||
геометрия крышек и их преобразования совпадают с опубликованной версией.
|
||||
Сохранение после пуска содержит 3 оставшиеся ракеты С-400 и маску использованной ячейки `1`.
|
||||
Эти кадры подтверждают положение крышек, но не являются видеопроверкой всех стадий полёта:
|
||||
сам выброс и момент зажигания крупным планом снять не удалось.
|
||||
|
||||
### Парная съёмка #129: до и после
|
||||
|
||||
Оба ролика сняты на одном и том же scratch-мире `ColdLaunch129` (плоский тестовый рельеф,
|
||||
`--creative`), одном сохранении мира, одном сценарии `pair129` и одном seed
|
||||
`965460218386186365`. Сценарий: С-400 в точке `1.5 72 8.5`, роли `31`, один Х-22, налёт с 900.
|
||||
Оба прогона — один и тот же клиент/движок `278f356aa` (API30), одни ресурсы, Metal/offscreen,
|
||||
`HORIZON_NO_AUDIO=1`, одна команда режиссёра
|
||||
`/airdef replay export <имя> best fps=30 size=1280x720 crf=16 sec=24`.
|
||||
|
||||
| | До (`dc36d67`) | После (`4b013fb`; hmod `00f0209`) |
|
||||
|---|---|---|
|
||||
| `.hmod` SHA-256 | `2d828aa8…` | `ca3bdd30…` |
|
||||
| исходный MP4 | 17 268 968 Б, 403 кадра | 17 832 718 Б, 412 кадров |
|
||||
| длительность | 13,433 с | 13,733 с |
|
||||
| поток | h264 1280×720 30 fps + AAC 48 кГц | то же |
|
||||
| план «Пуск» | кадры 94–151 | кадры 94–160 |
|
||||
| первое освещение центра | кадр 101 = 0,233 с | кадр 121 = 0,900 с |
|
||||
| `cold` профиля | 5 тиков = 0,25 с | 20 тиков = 1,00 с |
|
||||
|
||||
«Первое освещение» — прокси зажигания/факела: первый кадр, где средняя яркость центрального
|
||||
окна 100×120 px (`x 590..689`, `y 300..419`) превышает 100/255. До (`dc36d67`) это кадр 101, через 7 кадров
|
||||
после начала плана «Пуск» (кадр 94) — 0,233 с при `cold=5` (0,25 с). После — кадр 121, через
|
||||
27 кадров — 0,900 с при `cold=20` (1,00 с); к кадру 124 окно выходит на устойчивую яркость
|
||||
≈198. Разница 0,667 с совпадает с разницей `cold` 15 тиков = 0,75 с в пределах 2–3 кадров
|
||||
(30 fps). Аудиодорожка даёт тот же сдвиг: RMS (окно 50 мс) впервые превышает 0,03 на 3,45 с
|
||||
до и 4,15 с после при старте плана 3,10 с, то есть через 0,35 и 1,05 с; это атака звука, а не
|
||||
кадр зажигания. Полные числа и хэши:
|
||||
[issue-129-pair.json](measurements/issue-129-pair.json).
|
||||
|
||||
Оба MP4 лежат в `docs/media/cold-launch`: [до](media/cold-launch/cold-launch-129-before.mp4) и
|
||||
[после](media/cold-launch/cold-launch-129-after.mp4), в перекодировке h264 CRF26 для хранения;
|
||||
число кадров, 30 fps, длительность и AAC сохранены. Исходные файлы с CRF16 и их SHA-256
|
||||
записаны в JSON.
|
||||
Это **replay/export**, не live-видео: живые кадры в MP4 не писались (`--offscreen` не даёт окна
|
||||
для сторонней записи, встроенной live-записи у мода нет). Звук сведён офлайн, живое
|
||||
прослушивание не выполнялось.
|
||||
|
||||
Парные кадры (слева — до, справа — после), один и тот же кадр фильма:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
**Ограничение приёмки.** Агент, выполнивший прогон, не имеет ввода изображений и не может сам
|
||||
оценить композицию, читаемость и красоту кадров. Проверены факт и параметры съёмки, одинаковый
|
||||
старт плана «Пуск» (кадр 94), яркость центра и её сдвиг по времени; парные кадры приложены для
|
||||
человеческого просмотра. Кадры до/после не пиксельно идентичны: это два отдельных живых прогона,
|
||||
камера общего плана движется, листва/трава анимированы, поэтому в предпусковых кадрах остаётся
|
||||
разница в несколько уровней яркости. Совпадают мир, сохранение, сценарий, seed, метод камеры и
|
||||
команда экспорта, а не каждый пиксель. Отдельный очень крупный статичный план выброса у самой ПУ
|
||||
не снят; план «Пуск» — боковой с 46 блоков. Это не полная визуальная приёмка #129.
|
||||
|
||||
+434
-6
@@ -4,9 +4,135 @@
|
||||
Рабочая ветка `kimi-work`; issues не закрывать, публиковать комментарии с коммитом и проверками.
|
||||
Движок — отдельный `chexit/horizon-airdef`, ветка `airdef`, подключён точным gitlink `horizon/`.
|
||||
|
||||
## Текущее состояние: 3 ноября 2026
|
||||
## #91: типизированные варианты комплексов — первый slice (20 ноября 2026)
|
||||
|
||||
Код четырёх задач интегрирован и опубликован до `6e2d661`. Движок в этой серии не менялся.
|
||||
Ветка `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).
|
||||
Движок `57f8b2853c4443f7e3ff5701600cbb262b53118f`, API29. В этом файле ниже сохранён
|
||||
исторический журнал предыдущих серий; старые SHA и числа тестов не заменяют новую контрольную точку.
|
||||
|
||||
След #91 продолжен: `catalog/specs.json` — единственная копия числовых строк дронов, ракет и
|
||||
комплексов; `python3 tools/gen_catalog.py` генерирует `specs_generated.rs` и
|
||||
`unit_specs_generated.rs`, `--check` (CI) валит расхождение. Числа не менялись; сверка с литералами
|
||||
подтвердила 1.6 как фактический голос P1-SUN (недостижимый `P1sun => 1.7` в старом match не в счёт);
|
||||
на это добавлена Rust-регрессия. Остаток: варианты комплексов и игровая приёмка.
|
||||
|
||||
### Продолжение #129: стадии холодного пуска и разгон (6 ноября 2026)
|
||||
|
||||
Ветка `agent/issue-129-cold-launch`, кодовый коммит `4b013fb7f30dbaa87a266b27a31911937fc523b4`
|
||||
(документация, измерения и кадры — следующим коммитом этой же ветки).
|
||||
Игра/движок не менялись: pin `278f356aa604fa21c2d15d0081823bbe0f891df2`, API30. Push не выполнялся,
|
||||
issues не закрывались.
|
||||
|
||||
**Контракт стадий.** У `MissileSpec` появились `eject` и `eject_drag`; `cold` — тики физического
|
||||
выброса, `boost` — тики departure. `guided(age) = age >= cold + boost`; основная ветка наведения,
|
||||
самонаведение и облёт рельефа больше не могут включиться до зажигания (раньше было `age >= boost`,
|
||||
что при большом `cold` включало наведение до мотора). Зажигание — по-прежнему `age > cold`;
|
||||
событие `MotorIgnition`, звук, факел и голос используют текущую позицию ракеты. `departure_ramp`
|
||||
растёт 0→1 за `boost`; темп поворота в departure — `turn·(0.2 + 0.8·ramp)`. Тяга ракетных
|
||||
профилей — `accel·(0.45 + 0.55·ramp)`, на guidance — полная. P1-SUN (`flame=0`) сохраняет
|
||||
полный разгон без ракетной струи.
|
||||
|
||||
**Профили.** `M48n6`: `cold=20`, `eject=2.4`, `eject_drag=0.07` — 1,00 с; `M77n6`: `cold=24`,
|
||||
`eject=2.6`, `eject_drag=0.07` — 1,20 с; `IrisT`/`M9m338`: `cold=8`, `eject=1.8/1.6`,
|
||||
`eject_drag=0.1` — 0,40 с. Рельсовые профили (`cold=0`) получили только spool тяги; ранний
|
||||
поворот на рельсовом пуске был проверен и отменён: он уводил Pac3 в землю на холмах и валил
|
||||
`an_interceptor_over_rolling_land_does_not_hit_the_ground`. `speed`, `accel`, `turn`, `pk`,
|
||||
`fuse` и правила столкновений не менялись.
|
||||
|
||||
**RM48U.** `EJECT_TICKS` 5 → 20. Выброс неосвещённый и замедляется; зажигание на `EJECT_TICKS`,
|
||||
факел/звук/голос с этого момента; насчитанное время полёта включает выброс; дым в записи
|
||||
начинается от точки зажигания, а не от горловины. Live, repeat и export читают одно и то же
|
||||
состояние `lit`/записанное `MotorIgnition`.
|
||||
|
||||
**Проверки.** core release **206 + 8 сценариев**, 8 ignored; адаптер **67 + 1 boundary +
|
||||
5 сценариев**; настоящий `.hmod` — **30 шагов** `wasm_contract.toml`; `gen_catalog.py --check` и
|
||||
`gen_models.py --check` без расхождений; `test_gen_assets.py` — 10 тестов; `git diff --check` чист.
|
||||
Новые регрессии: стадии по порядку и отсутствие powered-эффектов до зажигания; `guided` не раньше
|
||||
`cold` для всех профилей; непрерывность скорости/поворота и throttled первый powered тик; P1-SUN
|
||||
без факела; записанное зажигание через `cold` тиков и `missile_is_lit` по нему; RM48U без
|
||||
голоса/факела до зажигания и ровно один звук зажигания.
|
||||
|
||||
**Баланс.** Сетка #120 (6 вариантов × 8 seed, 2208 целей на сторону, baseline `dc36d67`):
|
||||
сбито 1988 → 1939, прорывов 216 → 258, ракет 3461 → 3467; `near200` 318 → 311, `far1500`
|
||||
338 → 334, `hills20` 334 → 319; `energy_lost` 0 → 0, `expired` 1 → 0, scrub 2 → 4.
|
||||
`SAMS=20 SIZE=12`, 12 seed: 203 → 201 сбитых, 1 → 3 прорыва, 355 → 360 ракет. Отдельные CSV:
|
||||
[сетка](measurements/issue-129-grid.csv), [рейды](measurements/issue-129-balance.csv).
|
||||
Это намеренное следствие более длинного старта; скрытого повышения `pk` или максимальной скорости нет.
|
||||
|
||||
**Парная съёмка.** Один scratch-мир `ColdLaunch129`, одно сохранение, сценарий `pair129`,
|
||||
seed `965460218386186365`, один клиент/движок API30, один режиссёр
|
||||
(`/airdef replay export … best fps=30 size=1280x720 crf=16 sec=24`), Metal/offscreen.
|
||||
Сценарий: С-400 `1.5 72 8.5`, роли `31`, один Х-22 с 900; мод до — `dc36d67`, после — `4b013fb`.
|
||||
Оба MP4: h264 1280×720 30 fps + AAC 48 кГц; до — 403 кадра/13,433 с, после — 412/13,733 с.
|
||||
План «Пуск» стартует на кадре 94 в обоих; первое освещение центра (окно 100×120, порог 100)
|
||||
до — кадр 101 (0,233 с после старта, `cold=5` = 0,25 с), после — кадр 121 (0,900 с,
|
||||
`cold=20` = 1,00 с); к 124 кадру устойчиво ≈198. Это подтверждает сдвиг холодной паузы на
|
||||
≈0,67 с между сборками. MP4 в `docs/media/cold-launch` перекодированы в CRF26 для хранения;
|
||||
исходные файлы, их SHA-256, ffprobe и логика измерения — в
|
||||
[issue-129-pair.json](measurements/issue-129-pair.json). **Ограничение:** у агента нет ввода
|
||||
изображений; проверены параметры, старт плана, яркость центра и парные кадры, но композицию и
|
||||
красоту кадров человеком ещё нужно оценить. Предпусковые кадры не пиксельно идентичны (живой
|
||||
прогон, движение камеры, анимация листвы); совпадают мир/сейв/сценарий/seed/метод камеры.
|
||||
Отдельный very-close статичный план и live-MP4 не сняты (`--offscreen` без окна). Это не полная
|
||||
визуальная приёмка.
|
||||
|
||||
### Продолжение #122 (второй налёт из UI)
|
||||
|
||||
Точный лог Windows: `stopped in UI event (fuel budget 1000000000, remaining Some(0))`,
|
||||
backtrace `known_units ← order_raid ← launch_wave ← ui_select` — другой класс, чем тик
|
||||
`1f28f83`. Причина: `order_raid` пересчитывал снимок известных комплексов на каждом дроне,
|
||||
а сам снимок был квадратичен по журналу и группировке. Исправление: один снимок на приказ
|
||||
(+ O(журнал+группировка) через множества, `price_grid_on` переиспользует свой снимок);
|
||||
семантика целеуказания и выбора носителей не менялась, сверка с прежним предикатом в
|
||||
нативном тесте, `/stats` в WASM совпал побайтово. Лимиты не трогали, HD/запись не отключали,
|
||||
размер волны не ограничивали.
|
||||
|
||||
Воспроизведение в настоящем WASM (измеренный fuel): до — второй приказ 111 дронов исчерпывает
|
||||
ровно 1e9 в событии (failures=1), тот же приказ 11 дронов — 247805865; после — тот же сценарий
|
||||
целиком: max command 32946177/1e9, tick 236581288/300M, ошибок 0. Диагностический гость
|
||||
(`trigger.patch` вызывает обработчик `ui_select(BTN_LAUNCH)`) и точный сценарий:
|
||||
[issue-122-ui-fuel](measurements/issue-122-ui-fuel/summary.json). Воспроизвести удалось только
|
||||
с разнесённой группировкой: стек в одной точке гибнет от одной боеголовки (`known=0`, приказ
|
||||
дёшев) — у пользователя силы дожили до второго приказа.
|
||||
|
||||
Закреплённые регрессии: нативные «эквивалентность снимка» и «второй умный приказ с толстым
|
||||
журналом принят и запущен»; тяжёлый WASM fixture расширен двумя умными приказами через
|
||||
`airdef preset` + `airdef raid` (функция кнопки ПУСК) — 4 принятых приказа, SHA fixture
|
||||
обновлён; лёгкий контракт 30 шагов с `preset` и отказом пустой волны. Новая команда
|
||||
`airdef preset <n>` — script-эквивалент кнопки готового состава.
|
||||
|
||||
Последний общий прогон: core release **195 + 8 сценариев** / 7 ignored; адаптер **65 + 1
|
||||
boundary + 5 сценариев**; лёгкий WASM **30 шагов**; тяжёлый WASM **283 шага** (tick max
|
||||
182413686/300M, command max 6939810/1e9, failures=0), отчёт
|
||||
[flat-wasm-raid-budget](measurements/flat-wasm-raid-budget.json); 6 тестов отчёта budget
|
||||
и build-тест прошли. Ни одно issue не закрыто; пуш не выполнялся.
|
||||
|
||||
### Контрольная точка 3 ноября
|
||||
|
||||
Код предыдущих четырёх задач интегрирован до `6e2d661`. Продолжение #102/обратного вывоза
|
||||
опубликовано до `aab3e78`; последнее продолжение расследования налётов — `2932364`.
|
||||
Текущий движок — `f95f03c08ec2916a0e5bd3b2d4a2a790e7937b47`, API 27.
|
||||
README описывает доступное поведение; `IMPLEMENTATION-STATUS.md` отделяет реализацию от приёмки.
|
||||
Ни одно issue не закрыто. Участники: Codex (интеграция, #119, ревью, документация) и три
|
||||
GPT-6.1 Terra (энергетика, типизированная доставка, излучение). Новые числа — только игровые.
|
||||
@@ -23,6 +149,82 @@ GPT-6.1 Terra (энергетика, типизированная доставк
|
||||
`python3 tools/airdef.py all`, `python3 tools/airdef.py play`. `all` обновляет точный сабмодуль,
|
||||
собирает игру/мод и устанавливает пакет. На Windows обычно используется `python` вместо `python3`.
|
||||
|
||||
### Продолжение #102 и обратного вывоза RM48U
|
||||
|
||||
- `d3378b3`: `fork()` синхронизирует URL из `.gitmodules` даже на fast path совпавшего pin.
|
||||
Реальная Git-регрессия воспроизводит старый upstream URL и новый коммит, отсутствующий в локальном clone.
|
||||
Это исправляет наблюдавшееся на Windows `upload-pack: not our ref 86b1014…`; пользователь подтвердил
|
||||
ручное исправление через `git submodule sync --recursive` до публикации автоматизации.
|
||||
- `bb931ab`, `e9fbaba`, `b0085cb`: `ground-unload` вдали от склада резервирует одну RM48U и вызывает
|
||||
ТЗМ. `ground-cancel` отменяет ещё ожидающий вывоз/доставку; после забора груз продолжает путь на склад.
|
||||
Проверены физическое движение и полный save/restore до забора и после забора, без телепортации запаса.
|
||||
- `910f02c`: потеря зарезервированной ракеты вместе с ячейками сбрасывает заявку на вывоз.
|
||||
Иначе можно было создать сохранение, которое loader сам отвергал как несовместимое состояние.
|
||||
- Двигатель: `f4c1131d3`, затем `c89c78c47` опубликованы в `horizon-airdef:airdef` до обновления gitlink.
|
||||
API27 добавляет acoustics-status и capture-owner-status, scoped к запуску мода и поколению мира.
|
||||
Остановка capture проверяет владельца; смена мира снимает незапущенный запрос или посылает cancel.
|
||||
- `910f02c`: команда `/airdef capabilities`; дальний звуковой fallback сохраняется до подготовки
|
||||
акустического пути, экспорт принимает только своё подтверждённое состояние; Arming ждёт до 600 тиков.
|
||||
`prepared` — milestone хоста, не GPU fence, не результат каждой акустической трассы и не готовый MP4.
|
||||
- `4dddea2`, `8d5d0d1`: opt-in `test-budgets`, отдельный ручной workflow и JSON provenance;
|
||||
тесты ошибок сборки, stale identity и ненулевого runtime exit. Native success не заменяет actual WASM.
|
||||
- `aab3e78`: repo-local packer использует target-cache закреплённого движка; `CARGO_TARGET_DIR`
|
||||
не переопределяется для сборки самого мода и не уводит `.hmod` в чужое дерево.
|
||||
|
||||
Проверки объединённого состояния: core release **190 + 4 сценария**, 7 ignored;
|
||||
адаптер **60 + 1 boundary + 4 сценария**; лёгкий WASM **26 шагов**, тяжёлый **69 шагов**;
|
||||
Git-регрессия и три теста failure report прошли. Исходный профиль запрашивал 64 ПВО + 160 целей,
|
||||
602 tick / 300 frame; JSON фиксирует clean `aab3e78`, pin API27 и совпадающий build identity.
|
||||
Полные данные: [budget report](measurements/api27-wasm-budget.json).
|
||||
**Исправление оценки покрытия:** второй запрос исходного 69-шагового сценария отклонялся во время
|
||||
подготовки первого. Его успешный exit не подтверждает 160 запущенных или одновременно летящих целей.
|
||||
В архивный JSON добавлена поправка; исправленный сценарий проверяет ответы. Для настоящего stress
|
||||
также нужны ответы render-world: прежний sandbox их не давал и часто проверял лишь ожидание земли.
|
||||
|
||||
Дополнительно два свежих профиля игры на Metal/no-audio: smoke off не ready, HD smoke ready;
|
||||
при HORIZON_ACOUSTICS=1 + HORIZON_NO_AUDIO=1 акустика enabled/request=true, prepared=false,
|
||||
awaiting-backend. Выход через quit подтверждён. Это не прослушивание, не benchmark и не новый MP4.
|
||||
Правила API, пределы проверок и команды: [ENGINE.md](ENGINE.md).
|
||||
|
||||
## Двойные налёты и плотность следов
|
||||
|
||||
Перед продолжением читать [RAID-STABILITY.md](RAID-STABILITY.md): два соответствующих класса
|
||||
отключения теперь воспроизведены и исправлены — тик (`1f28f83`) и событие UI на втором
|
||||
приказе (#122, `order_raid`/known_units); приёмка конкретного Windows-сеанса остаётся.
|
||||
Текущий исправленный WASM stress проверяет две принятые волны, обслуживаемую плоскую геометрию
|
||||
и 184 воздушные цели в конкретный момент; новый [JSON](measurements/flat-wasm-raid-budget.json)
|
||||
заменяет прежнее недостаточное доказательство покрытия. Лимиты fuel/memory не увеличивались.
|
||||
`86e1d272e` в движке улучшает callback/fuel/error-chain diagnostics; `ed7615d36` добавляет только
|
||||
необязательную flat-world среду тестов и отказывает неожиданным ошибкам команд в Script.
|
||||
Основная клиентская логика сцены этим test helper не заменяется.
|
||||
|
||||
`692ae77`: HD-треки ракет оптически плотнее на 12% через общий `rocket()` и cruise style.
|
||||
SAM/RM48U, крылатые/сверхзвуковые/баллистические треки покрыты; сегментов, радиусов и времени не добавлено.
|
||||
Пожары и дымка винтовых дронов не менялись. Обычные ванильные fallback-частицы этим множителем не меняются.
|
||||
Пять существующих smoke-тестов прошли; прирост FPS и приёмка новой плотности на Windows не заявлены.
|
||||
|
||||
Последний общий прогон: core release190 + 6 сценариев, 7 ignored;
|
||||
адаптер60 + 1 boundary + 4 сценария; лёгкий WASM26; тяжёлый WASM271; 5 тестов отчёта.
|
||||
Нативные overlap-тесты — `airdef-core/tests/scenarios.rs`:
|
||||
два стандартных массовых пресета и два налёта с разделением «Орешников», оба со встроенной записью.
|
||||
|
||||
Продолжение по пользовательскому HD-отключению: `1f28f83` заменяет полный `known.retain` при
|
||||
каждом взрыве на удаление прежнего квадрата; семантическая эквивалентность проверена.
|
||||
В диагностическом WASM max-menu ×2 раньше был trap tick1835 на 300M; после фикса полный
|
||||
3602-tick прогон прошёл, max135273690. Гость отличается от baseline только временным trigger hook
|
||||
состава меню и исправлением. Это измерение fuel, не прирост FPS. Артефакты/ограничения — в RAID-STABILITY.
|
||||
`cc48302` добавляет публичный native max-menu regression; `3b470dd` закрепляет опциональный
|
||||
engine `test --fuel-profile` (не новый SDK API и не увеличение лимитов).
|
||||
|
||||
`cbd6067` исправляет сообщение о пустом соседнем складе, показывает типизированные запасы на M,
|
||||
уточняет подсказку разведки и убирает устаревшую строку README о якобы отсутствующей доставке.
|
||||
[GROUND-STRIKES.md](GROUND-STRIKES.md) — инструкция с различием номеров своего С-400/склада и вражеской ПУ.
|
||||
Default RM48U=0; `ground-stock` задаёт остаток, `ground-load` грузит одну; поздний трек не даёт fix.
|
||||
`ab737e7`: actual WASM теперь 27 шагов с проверкой ошибки пустого соседнего склада.
|
||||
|
||||
После фикса полный core: 192 passed + 6 сценариев / 7 ignored; новый max-menu сценарий отдельно
|
||||
прошёл седьмым. Адаптер60 + 1 boundary + 4 сценария; light WASM27; engine /spin fuel-profile test прошёл.
|
||||
|
||||
## Исходная контрольная точка этой серии
|
||||
|
||||
Исходное состояние этой серии: `2689d93`; движок закреплён на
|
||||
@@ -137,6 +339,30 @@ baseline — 202 сбитых, 2 прорыва, 367 ракет; новое —
|
||||
Это небольшой регрессионный ориентир, не доказательство баланса всех типов/дальностей.
|
||||
Данные каждого seed: [CSV](measurements/issue-120-balance.csv).
|
||||
|
||||
Расширенная сетка остатка #120 (ветка `agent/issue-120-balance`, коммит см. в git):
|
||||
baseline `2689d93` против текущего `e6a7000` (то есть с #118/#119/#121 и сменами движка, не только #120),
|
||||
6 вариантов × 8 одинаковых seed, рейд `SIZE=36` (46 целей: Gerbera 10, Shahed 13, Geran3 5, Х-101 5,
|
||||
«Калибр» 4, Х-22 2, «Циркон» 1, «Искандер» 4, «Кинжаль» 2; «Орешник» harness исключает, как в `one_raid`):
|
||||
`batt10/20/50` (10/20/50 ЗРК, дистанция 500), `near200` (20 ЗРК, пуск в 200), `far1500` (20 ЗРК, пуск в 1500),
|
||||
`hills20` (20 ЗРК, холмы, 500). Кластер тот же `MIX` из 10 систем: `SAMS=10` — по одному комплексу каждого типа.
|
||||
Итого 2208 целей на сторону, 96 строк: [CSV](measurements/issue-120-grid.csv). Команда (игнорируемый тест
|
||||
`sim::balance::issue_120_grid`, только harness-поля в `Result`, поведение симуляции не менялось):
|
||||
|
||||
```sh
|
||||
SEEDS=1-8 cargo test --release --manifest-path airdef-core/Cargo.toml issue_120_grid -- --ignored --nocapture
|
||||
```
|
||||
|
||||
Факты сетки (суммы по 8 seed каждого варианта, baseline → текущий): сбитые 297→301 (batt10), 331→334 (batt20),
|
||||
357→363 (batt50), 313→318 (near200), 328→338 (far1500), 328→334 (hills20); прорывы 70→66, 37→34, 11→5,
|
||||
53→48, 40→30, 39→33. Промахов по взрывателю заметно меньше (например far1500: 70→38). Расход ракет близок
|
||||
(516→504 … 597→583). На холмах потери у рельефа: разбито 14 и 14, самоуничтожений у хребта 6→2.
|
||||
Прорывы во всех вариантах — преимущественно баллистические и быстрые классы («Искандер», «Кинжаль», Х-22,
|
||||
«Циркон»); у медленных Shahed/Gerbera прорывов почти нет (0–2 на вариант), у ложных Gerbera — ноль ни разу.
|
||||
`MotorEnergyLost` не сработал ни в одном из 48 сценариев текущего кода, `expired` ≤ 1 на вариант: coast
|
||||
существует, но бои на этих дистанциях заканчиваются раньше, чем сопротивление 0.995/тик опустит скорость
|
||||
ниже порога 25% (и раньше выработки ресурса). Это измеренное свойство профиля, не подтверждённый дефект,
|
||||
поэтому параметры не менялись. Путь потери энергии покрыт юнит-тестом регресса (`regress.rs`), а не этой сеткой.
|
||||
|
||||
```sh
|
||||
SAMS=20 SIZE=12 cargo test --release --manifest-path airdef-core/Cargo.toml sim::balance::one_raid -- --ignored --nocapture
|
||||
```
|
||||
@@ -158,8 +384,11 @@ SAMS=20 SIZE=12 cargo test --release --manifest-path airdef-core/Cargo.toml sim:
|
||||
с продолжением маршрута. GUI-доставка на сложном рельефе ещё не проверена.
|
||||
|
||||
Новых носителей вроде Бука не добавляли: один публичный игровой профиль не даёт основания
|
||||
приписывать его всем ЗРК. Обратный вывоз RM48U из удалённого носителя пока не автоматизирован:
|
||||
`ground-unload` требует склад рядом. Отдельной отмены ожидающей заявки в UI пока нет.
|
||||
приписывать его всем ЗРК. Обратный вывоз из удалённого носителя автоматизирован в продолжении выше.
|
||||
Новая команда `ground-cancel` отменяет ожидающую заявку, но не возвращает уже забранный груз в ПУ.
|
||||
ТЗМ вмещает два типизированных места RM48U/48Н6; прежние абстрактные generic reload-пакеты учитываются отдельно.
|
||||
Вывезенная ракета возвращается в конечный запас; ПВО восстанавливается при заборе только из реально
|
||||
имеющейся у ТЗМ ракеты 48Н6 и свободной ячейки. Резерв одной RM48U учитывается при выборе носителя удара.
|
||||
|
||||
### #121: излучение отдельно от сети
|
||||
|
||||
@@ -190,6 +419,8 @@ SAMS=20 SIZE=12 cargo test --release --manifest-path airdef-core/Cargo.toml sim:
|
||||
| 25–27 | mode, radar_role, spent_cells |
|
||||
| 28 | ground_request: 0/1, только С-400 |
|
||||
| 29 | radar_on: true/false, отсутствие означает true |
|
||||
| 30 | ground_return: true/false, резерв вывоза одной RM48U из С-400 |
|
||||
| 31 | return_cargo: true/false, возвращаемая RM48U на ТЗМ |
|
||||
|
||||
Две агентские ветки сначала заняли поле 28 одновременно; при интеграции излучение перенесено
|
||||
в 29, опубликованная совместимость заявки сохранена. Проверка полного roundtrip одновременно
|
||||
@@ -216,17 +447,214 @@ Unknown, stale и слишком старые секции считаются **
|
||||
Unknown и поздний ответ без повторного урона/запросов; прямое попадание; устаревшая геометрия;
|
||||
пропуск исходного блока. Все четыре прошли в объединённом наборе.
|
||||
|
||||
### #127: устойчивая очередь маршрутов после массового перенацеливания
|
||||
|
||||
Реализована только узкая часть issue: `sim::ew::RouteJob` — задание с ID дрона, новой целью,
|
||||
ID цели-юнита, версией знаний и общим для тика снимком `known_units` (`Arc`). `adapt` по-прежнему
|
||||
выбирает новые цели раз в 40 тиков, но маршруты теперь достраивает `replan_retargets` **каждый
|
||||
тик**: одно задание или несколько, пока не исчерпан `WORK_PER_TICK`. Незавершённое задание
|
||||
остаётся в `Sim::retargets` (FIFO) и не теряется; повторный выбор того же дрона заменяет задание
|
||||
на месте, поэтому очередь не растёт.
|
||||
|
||||
Старый маршрут не очищается при перенацеливании: дрон следует готовому безопасному участку,
|
||||
пока новое задание не получит маршрут. Если задание отменяется (дрон погиб, цель изменена снова,
|
||||
юнит уничтожен), маршрут очищается как fallback — дрон летит прямо до следующего адаптивного тика.
|
||||
Lancet, баллистика и decoy, как и раньше, летят прямо: для них задание не создаётся. В полёте
|
||||
следующая известная цель берётся только если до неё есть разворот; цель сзади внутри радиуса
|
||||
разворота пропускается, и дрон завершает текущий заход, а не получает невыполнимый маршрут.
|
||||
Повторный план использует снимок разведки исходного выбора цели и известный рельеф **той же версии
|
||||
задания**: `KnownRelief` (сетка и высоты) лежит в `Arc` внутри `RouteJob`, `Sim::known_relief` хранит
|
||||
тот же `Arc` только для новых заданий. Завершение другой умной волны заменяет глобальный указатель,
|
||||
но не снимок ожидающего job. Выборка рельефа, цены и кэш маршрутов в `replan_retargets` ключуются
|
||||
версией знаний целиком — adapt tick плюс указатели на снимки known units и рельефа, — а не только
|
||||
рельефом: два job с одинаковым рельефом, но разными known units, не делят price/route grid. За
|
||||
пределами известной сетки — Unknown, новая карта не раскрывается.
|
||||
|
||||
Очередь этапа 1 была рантайм-состоянием планировщика: дроны и очередь запуска в `state_text` не
|
||||
входили, поэтому durable-очередью она не была. Этап 2 (ниже) сохраняет её вместе с дронами, очередью
|
||||
запуска, картиной и версиями рельефа. Регрессии этапа 1 остаются: `mass_retarget_finishes_its_route_jobs_over_the_budget`
|
||||
(40+ ретаргетов, прогресс каждый бюджетный тик, старый маршрут до нового, нет пустых маршрутов)
|
||||
и `mass_retarget_is_deterministic_and_never_duplicates_a_drone` (тот же seed — те же цели и
|
||||
маршруты; повторный `adapt` не создаёт дублей).
|
||||
|
||||
### #127, этап 1: честная EnemyPicture
|
||||
|
||||
Журнал `intel.revealed: Vec<(id, место, тик)>` заменён картой контактов: `Intel.contacts: BTreeMap<u32, Contact>`,
|
||||
одна запись на юнита, последнее наблюдение побеждает. Контакт пишется только в момент раскрытия и
|
||||
читает истину только тогда: пуск (mod.rs/strike.rs) → `Seen::Launch`; фиксация излучения
|
||||
радаром рядом с чужим аппаратом (sight.rs, каждые 20 тиков, 1600 блоков) → `Seen::Emission`
|
||||
(отдельно помечается `emission` — вера в собственный сенсор опирается только на неё); работающая
|
||||
РЭБ (ew.rs) → `Seen::Jamming`; четвёртый канал — BSA: падение собственной боеголовки рядом с
|
||||
известным юнитом (`Sim::observe_outcomes`, радиус 16) фиксирует `destroyed` либо обновляет «жив»
|
||||
и место. Пока юнит незамечен, его перемещения, выключение радара, смена ролей/режима, расход БК,
|
||||
урон и гибель картину не меняют — это метаморфные тесты `sim::ew::picture_tests`.
|
||||
|
||||
Из контактов решается всё: снимок `picture_of_defences()` на приказ и на адаптивный тик (newest first,
|
||||
при равном тике — больший id, как у старого reversed-журнала), цели `choose_target` и SEAD
|
||||
(`radar_strikes` — только Probable и свежее), ретаргет в полёте (цель «мертва» лишь по контакту с
|
||||
`destroyed`; забытого контакта дрон не замечает), живость задания очереди (`job_live` — по картине,
|
||||
не по истине). Уверенность — функция одного возраста: Confirmed ≤ 600, Probable ≤ 3000, Doubtful до
|
||||
TTL 6000 тиков (`Confidence`, диагностика и SEAD её используют, цены — нет: консервативно считаются
|
||||
все живые контакты).
|
||||
|
||||
Модель возможностей в `price_grid_known` читает только картину: роли — published `kind.spec().roles`
|
||||
(смена `/airdef roles` невидима), дальности — `ew::published_reach` (без урона, фактора роли и
|
||||
мачт истины), донор — любой живой контакт вида Radar в link range от наблюдённого места (роль
|
||||
донора не наблюдаема: рабочий контакт РЛС предполагается кормящим сеть — это допущение, а не
|
||||
знание; разрыв связи/гибель донора незамеченными картину не меняют). Собственный сенсор верится,
|
||||
пока жива фиксация эмиссии; пуск при нуля эмиссионных фиксаций у С-400/С-500 читается как
|
||||
launcher-only: без донорского контакта такая ПУ в ценовой сетке «слепа», с ним бьёт на дальность
|
||||
донора. Горизонт РЛС игрока (`self.horizons`) из чужого планировщика убран: маскировка рельефа —
|
||||
тайна обороны, цены по ней консервативнее и объяснимее.
|
||||
|
||||
Диагностика без GUI: `Sim::enemy_picture() -> EnemyPictureReport` (англ.): по каждому контакту —
|
||||
наблюдение (канал, место, возраст), уверенность, живость, наблюдённое уничтожение, вера в сенсор,
|
||||
наличие донора и текстовое «что планировщик из этого делает». Адаптация по-прежнему ограничена
|
||||
статистикой секторов (`best_bearing` по kills/hits): новых всеведущих данных и усиления
|
||||
характеристик нет.
|
||||
|
||||
Форматы этапа 1 не менялись: intel оставался рантаймом (save хранил Layout, replay — траектории);
|
||||
durable-очередь появилась на этапе 2, ниже. Измерения до/после на одних seed: `docs/measurements/issue-127-enemy-picture-baseline.json`
|
||||
(0b645d77e) и `issue-127-enemy-picture-result.json` (эта ветка), bench — `cargo run --release --example intel_bench`.
|
||||
big-smart и logistics побайтово совпали с базой; ew-adaptive изменился (kills 62→59/61→59/61→56,
|
||||
hits 3→7/5→7/7→8, потери ЗРК 1→3/4→3/4→4) — фиксируется как факт перехода на честную картину,
|
||||
балансные параметры не трогали. Регрессии: метаморфные `hidden_changes_do_not_move_the_picture_or_its_decisions`,
|
||||
`a_new_observation_is_what_updates_the_picture`, `launcher_only_is_blind_in_the_picture_without_a_donor`
|
||||
(донор любой роли; разрыв связи наблюдённый/нет), `destruction_moves_the_picture_only_when_watched`,
|
||||
`confidence_is_a_function_of_age_alone`, `enemy_picture_report_describes_observation_and_belief`,
|
||||
`an_impact_watches_the_kill_and_updates_only_the_picture` (BSA end-to-end), обновлённые SEAD/#4/#21/#122
|
||||
и обе регрессии очереди. Остаток #127 после этапа 1: durable save queue, structured intent, GUI.
|
||||
|
||||
### #127, этап 2: structured intent, durable queue и объяснимость
|
||||
|
||||
**Намерение отделено от цели.** У дрона теперь два поля: `ew::Intent` — почему он летит туда — и
|
||||
`ew::Aim` — юнит, когда цель выбрана, сколько раз менялась и уверенность контакта. `Intent`:
|
||||
`Plan` (собственная цель плана: объект или юнит, выбранный при заказе), `Sead` (плановый удар по РЛС
|
||||
из `radar_strikes`), `React` (реакция на раскрытие: станция показала себя уже в воздухе) и `Replace`
|
||||
(картинка увидела гибель/забвение прежней цели). Случайный выбор цели (`choose_target`) больше не
|
||||
смешивается с реакцией: при заказе налёта intent фиксируется, а `adapt` помечает свои решения явно.
|
||||
Приоритет очереди — из намерения: Plan 3, Sead 2, React 1, Replace 0.
|
||||
|
||||
**Throttle.** `SWITCH_HOLD = 160` тиков (8 с): свежее раскрытие может сменить цель только после
|
||||
выдержки; `SWITCH_CAP = 3` смены на дрон за жизнь; `ASSIGN_PER_TICK = 16` новых целей за адаптивный
|
||||
тик и `ASSIGN_PER_CONTACT = 6` на один контакт за тик — массовый ретаргет растягивается на следующие
|
||||
адаптивные тики, а не переписывает все маршруты сразу. Смена возможна, только если контакт показался
|
||||
позже текущей цели (`tick > aim.since`), он не Doubtful, и он либо достовернее текущего, либо ближе
|
||||
на `SWITCH_GAIN = 120` блоков: смена выбрасывает готовый маршрут и стоит планировщику нового, поэтому
|
||||
маргинальная не делается. Замена убитой цели выдержку не ждёт (цели уже нет), но упирается в тот же
|
||||
cap. В полёте, как и раньше, цель меняется только когда картинка её убила или забыла.
|
||||
|
||||
**Явные игровые реакции без скрытых данных.** Реакции читают только поля контакта, записанные каналом
|
||||
наблюдения: выключенный радар остаётся в картине таким, каким его видели (эмиссия не фиксировалась —
|
||||
собственный сенсор не верится), разделённая батарея читается как пуск без эмиссии (launcher-only,
|
||||
без донора «слепа»), конечный БК наблюдается только как пуски (`Contact.launches`: счётчик увиденных
|
||||
пусков; остаток магазина в картину не входит никогда), энергия/нагрев РЭБ — своё состояние станции,
|
||||
а не раскрытие. Метаморфный тест `hidden_changes_do_not_move_the_picture_or_its_decisions` расширен:
|
||||
скрытые перемещение, off, роли, режим, БК, урон, гибель и нагрев/замок/выключение РЭБ не двигают ни
|
||||
картинку, ни цены, ни намерения/aims/очередь заданий. Повторное наблюдение двигает всё — как и должно.
|
||||
|
||||
**Неизвестная земля не бесплатна.** `raid::Relief` получил поле `unknown`; у плана умной волны оно
|
||||
0 (поведение этапа 1 сохранено), у повторного планирования задания — `UNKNOWN_LAND = 6` сверх базовой
|
||||
цены клетки 1. Задание, чья версия рельефа ничего не знает, планируется по полностью неизвестной
|
||||
земле с той же ценой, а не «как по свободной»: маршрут держится размеченной части, если она есть.
|
||||
Тест `unknown_land_is_not_free_in_a_replanned_route` сравнивает маршрут с ценой 0 и с ценой 6 на одной
|
||||
сетке: бесплатный срезает через неразмеченное, платный идёт по размеченному.
|
||||
|
||||
**Durable queue: формат save.** `state_text` (автосейв) дописывает версионированную секцию
|
||||
(`sim::durable`, формат `air 1`):
|
||||
|
||||
```
|
||||
air 1 <такт> <номер следующего задания> <дронов> <в очереди> <заданий> <контактов> <версий рельефа>
|
||||
airintel <12 kills> <12 hits>
|
||||
airglobal <версия рельефа|->
|
||||
airrelief <номер> <minX> <minZ> <клетка> <сторона> <RLE: u<n> | <высота>x<n> ...>
|
||||
aircontact <id> <тип> <x> <y> <z> <такт наблюдения> <канал> <эмиссия|-> <гибель|-> <пусков>
|
||||
airdrone <id> <тип> ... <полёт> <намерение> <юнит> <since> <смены> <уверенность> ... <маршрут: n x y z ...|->
|
||||
airqueue <такт запуска> <то же тело дрона>
|
||||
airjob <id> <дрон> <x> <y> <z> <юнит> <версия> <приоритет> <намерение> <рельеф|->
|
||||
```
|
||||
|
||||
Секция пишется только автосейвом: сценарий — это стартовое состояние, его тело её не несёт
|
||||
(`scenario_text` → `state_text_with(..., air = false)`). Старые saves без секции читаются как прежде
|
||||
(пустое небо); старые сборки новые saves читают как Layout, игнорируя `air*` (Layout пропускает
|
||||
неизвестные строки). Всё проверяется до применения: битая строка отказывает save целиком с номером
|
||||
строки и полем, счётчики в заголовке сверяются с числом строк (обрезанный файл отвергается), чужая
|
||||
строка внутри секции — тоже. Границы: 512 дронов, 512 точек маршрута, 4096 контактов, 8 версий
|
||||
рельефа, 40 000 клеток; координаты пишутся до 0.01 блока (полёт этого не замечает), рельеф — RLE
|
||||
целых высот. Секция дополнительно ограничена 900 КБ (хост разрешает 1 МиБ на одну запись): дрон,
|
||||
который не влез, не пишется, и его задание тоже (восстановить его было бы нельзя). Измеренный размер секции в bench: 4.0–8.8 КБ для logistics/ew-adaptive и 61–62 КБ для
|
||||
big-smart (38 дронов в воздухе).
|
||||
|
||||
**Что именно восстанавливается.** Дроны в воздухе (живые; падающие обломки — эффект, их нет),
|
||||
очередь запуска с тактами, задания (`id`, дрон, цель, юнит, версия, приоритет, намерение, версия
|
||||
рельефа), контакты картины (счётчики секторов, пуски), глобальный снимок рельефа и `job_next`.
|
||||
Картина задания восстанавливается «на свою версию»: контакты, наблюдённые не позже версии, плюс
|
||||
собственная цель задания (её последнее сохранённое наблюдение заменяет более позднее — иначе цель
|
||||
исчезла бы из своей же картины). Устаревшие задания отменяются при загрузке (`prune_air`): дрон
|
||||
исчез/погиб, цель уже другая, юнит наблюдённо уничтожен или забыт, дубль по дрону, версия старше
|
||||
`JOB_TTL = 1200` тиков (60 с). Маршрут отменённого «по устареванию/дублю» задания сохраняется (он
|
||||
ведёт к той же цели), отменённого из-за смены цели — очищается.
|
||||
|
||||
`apply_state` сначала проверяет Layout и секцию, затем применяет обе; секция заменяет воздушное
|
||||
состояние, а не сливается с ним. `durable_mark` включает `air_mark` (число дронов/очереди/заданий/
|
||||
контактов и `job_next`): автосейв берётся на запуске, потере, новом/завершённом задании и новом/забытом
|
||||
контакте, а не каждый тик полёта. Пока налёт *планируется*, периодический save откладывается (план не
|
||||
имеет durable-формы; поиск площадок ограничен `sites::SEARCH_TICKS = 400`); при смене мира пишется
|
||||
только Layout. Replay по-прежнему хранит траектории: секция пишется и читается только для живого
|
||||
`Sim`, записи не смешиваются с ней.
|
||||
|
||||
Остаток и ограничения: ракеты-перехватчики в воздухе, пусковые площадки (`sites`), промежуточный
|
||||
план, статистика волны и состояние RNG не сохраняются — после загрузки перехваты начнутся заново,
|
||||
очередь стартует без площадки (свободный слот), отчёт волны не придёт, а случайные броски идут от
|
||||
нового генератора мира; сама воздушная обстановка (дроны, цели, задания, картина) восстанавливается
|
||||
точно. GUI поверх отчёта не делался.
|
||||
|
||||
**Объяснимость.** `EnemyPictureReport` расширен без русского текста в core: у контакта — `launches`,
|
||||
`aimed_by` (сколько дронов на него нацелено) и `pending_jobs`; добавлены `aims` (дрон, юнит, intent,
|
||||
since, switches, confidence) и `pending` (id задания, дрон, юнит, точка, версия, приоритет, intent,
|
||||
`relief_known`, `reason` словами: ждёт бюджета / ждёт бюджета, земля неизвестна и стоит дороже /
|
||||
устарело), плюс `work_per_tick`. Тест `the_report_explains_aims_and_pending_jobs_in_english`
|
||||
проверяет и ASCII-only диагностику.
|
||||
|
||||
**Измерения (baseline 8fc10c07a → эта ветка, `cargo run --release --example intel_bench`, seeds 1/7/42):**
|
||||
`docs/measurements/issue-127-intent-queue-baseline.json` и `issue-127-intent-queue-result.json`.
|
||||
big-smart: завершение у всех, launched 38, kills 38, hits 0, потери 0 — как в базе; ticks 1716→1676
|
||||
(seed 1) и 1542/1433 без изменений, fired 49→60, 48→68, 49→71 (больше пусков ПВО). logistics: все
|
||||
поля совпали (27 запусков, 11/12/12 сбито, 8/7/8 прорвалось, 18 ракет, 0 потерь). ew-adaptive:
|
||||
kills 59→58, 59→58, 56→63; hits 7→7, 7→9, 8→3; потери ЗРК 3→3, 3→4, 4→2; ticks 8084→7146, 8193→7650,
|
||||
7916→7243; fired 69→76, 81→98, 69→82. Это следствие throttle назначений и приоритетной очереди, а не
|
||||
подкрутки баланса: параметры ПВО/дронов не менялись, числа фиксируются как факт. В result-файле есть
|
||||
новые поля (`retargets_max`, `air_bytes`, `switches_max`, `intents`), у baseline их нет.
|
||||
|
||||
**Регрессии этапа 2.** Core: `the_plan_records_sead_separately_from_its_objective`,
|
||||
`assignments_are_throttled_per_tick_and_per_contact`, `a_fresh_disclosure_switches_an_aim_only_after_the_hold`,
|
||||
`a_watched_kill_replaces_the_aim_and_queues_a_lower_priority_route`,
|
||||
`launched_rounds_are_observed_but_the_magazine_is_not`, `unknown_land_is_not_free_in_a_replanned_route`,
|
||||
`the_route_queue_is_bounded_and_refuses_a_worthless_job`, `the_same_seed_chose_the_same_intents_and_jobs`,
|
||||
`the_report_explains_aims_and_pending_jobs_in_english`, `the_air_state_round_trips_every_job_field`,
|
||||
`a_pending_route_continues_after_a_save_and_a_load` (save/load посреди незавершённой очереди: та же
|
||||
очередь, те же маршруты, обе кампании доводят задания, пустых маршрутов нет),
|
||||
`stale_ghost_and_duplicate_jobs_are_cancelled`, `a_job_for_a_unit_the_picture_lost_is_cancelled_on_load`,
|
||||
`a_damaged_air_section_is_refused_with_its_line_and_field`, `the_section_stays_inside_its_byte_bound`
|
||||
(600 дронов с длинными маршрутами: секция ≤ 900 КБ, записанные задания принадлежат записанным дронам),
|
||||
обновлённые массовые ретаргеты (40+ дронов:
|
||||
прогресс на бюджетном тике, throttle назначений, у дрона, стартовавшего без маршрута, маршрут
|
||||
появляется). Adapter: `the_air_section_of_a_save_is_written_and_read_by_the_adapter` (запись/чтение
|
||||
секции, замена не слияние, старый save без секции, сценарий без воздуха).
|
||||
|
||||
## Что следующему агенту проверить в первую очередь
|
||||
|
||||
1. На Windows: обновление сабмодуля через `all`, сохранение/перезаход, рабочий цикл игры.
|
||||
2. В GUI: полный холодный пуск крупным планом; карточка On/Off; маршрут ТЗМ по сложной местности;
|
||||
разрушение стены одним взрывом и защита от того же взрыва по исходной геометрии.
|
||||
3. Прослушать прекращение голоса двигателя при burnout и seek/экспорт вокруг этой границы.
|
||||
4. Расширить баланс #120 на разные батареи, пределы дальности и классы целей; исходная CSV — ориентир.
|
||||
4. Расширенная балансировка #120 (батареи/дальности/классы) записана в `measurements/issue-120-grid.csv`;
|
||||
остаются прослушивание голоса мотора и платформенная приёмка.
|
||||
5. Продолжить оставшиеся архитектурные #87/#88/#89/#91/#102 и художественный #115 по статусной таблице.
|
||||
|
||||
Это незавершённая платформенная/визуальная приёмка, а не отсутствие перечисленного выше кода.
|
||||
Текущий прогон не запускал GUI или новый MP4, не прослушивал звук и не проверял Windows/Linux.
|
||||
Прогон четырёх задач не запускал GUI/MP4. В продолжении API27 есть два коротких игровых smoke,
|
||||
но новый MP4, прослушивание и платформенная приёмка Windows/Linux по-прежнему не выполнены.
|
||||
|
||||
## Правила продолжения
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# Продолжение 4 ноября: #115, #87, #91, #102, #96
|
||||
|
||||
Рабочая ветка `kimi-work`. Все issues оставлены открытыми. Работа выполнена Codex с GPT-6.1 Terra.
|
||||
Движок опубликован в `horizon-airdef:airdef`, текущий pin
|
||||
`57f8b2853c4443f7e3ff5701600cbb262b53118f`, API **29**.
|
||||
|
||||
## Изменения
|
||||
|
||||
- **#115:** authored-модели «Ланцета» и Х-101: сегментные стреловидные крылья,
|
||||
детали носа/корпуса. Элементы 17→49 и 22→30 соответственно; игровые параметры не менялись.
|
||||
`5366988`, `cfae0c1`, `914f723`. [Кадры и ограничения](AIRCRAFT-MODELS.md).
|
||||
`tools/model-preview` воспроизводит реальный `set-models`, `glow=false`; установленный
|
||||
stone-template блок не подходит для оценки света динамической модели. Полосы яркости
|
||||
на наклонных сегментах вынесены в [#123](https://gitea.maoniao.team/chexit/airdef/issues/123).
|
||||
- **#87:** `375fdf2`, `cb73cb7`, `0c870c1`: типизированный `BatteryStatus`, отчёт кэша мира
|
||||
и причины повреждений отделены от русского форматирования. Команда/карта/монитор используют
|
||||
адаптеры `battery_view`, `world_view`, `why_view`. Порядок и тексты сохранены.
|
||||
Это постепенное разделение: `CheckReason::Text`, сообщения `Out` и часть представления в ядре остаются.
|
||||
- **#91:** `eea1b36`, `1553976`, `daa9ed7`: `catalog/content.json` — идентичности техники,
|
||||
предметы и метаданные иконок; `catalog/sounds.json` — звуковые события, дальности и far-варианты.
|
||||
`gen_catalog.py` создаёт Rust-константы, Python-регистрации читают тот же источник;
|
||||
CI проверяет актуальность. Сохранены порядок позиционных сейвов, все 35 звуковых событий,
|
||||
OGG и порядок общего RNG синтезатора. Числовые `DroneSpec`/`SamSpec` остаются типизированным
|
||||
источником в Rust; полного переноса всех характеристик в JSON не было.
|
||||
Продолжение переноса чисел — ниже.
|
||||
- **#102:** `63aefc7`: `test-budgets` включает настоящий `--fuel-profile` и сохраняет
|
||||
`measured_fuel.callbacks`, включая ошибки. Отсутствие запрошенных счётчиков запрещает success.
|
||||
В движке `6230ec703`/`d8fa77b00` добавлены API28 point-lights-status и API29 sound-sources-status.
|
||||
Свет: заявка → cache → обработка main-view HD списка; звук: заявка → фактический apply
|
||||
source manager при live/offline output. Отдельные run/world/source epochs, clear/reload и
|
||||
отсутствие output проверены настоящими Wasmtime-гостями. Это не обещание пикселя/слышимости.
|
||||
`/airdef capabilities` показывает оба состояния (`c1a595b`).
|
||||
`57f8b2853` также устраняет коллизию камер: texture targets, scheduler, HUD/canvas/corner и
|
||||
main-view адресуются `(run_serial, local_id)`. Проверены два настоящих гостя с одинаковым ID,
|
||||
поиск target и scheduler, компиляция клиента.
|
||||
`efe017ffb`/`278f356aa` добавляют API30 `camera-status`: `prepared` — закодированный в target
|
||||
кадр камеры или кадр мира с её main-view, причём milestone получает только тот запуск, чей выбор
|
||||
экран реально использовал (чужой тот же local ID и чужая картинка его не готовят). `enabled` —
|
||||
последний отмеченный кадр был кадром мира, не заголовком. Пустая `set-views` и смена мира
|
||||
очищают заявку/выбор/готовность, reload начинает заново; главный вид теряет picture target до
|
||||
нового кадра. Проверено настоящими Wasmtime-гостями. Итоговый engine `278f356aa` с AirDef API30
|
||||
проверен и в запущенной игре на Metal/offscreen (Apple M5, чистый `HORIZON_HOME`, копии тестовых
|
||||
миров): monitor даёт `ready` с нарисованной картинкой (по снимкам), film-main-view — `ready` с
|
||||
main-view (на экране карточка подготовки фильма), пустая заявка
|
||||
и смена мира — `not-requested` с новым поколением, после deploy+monitor камера снова готова;
|
||||
команды и ограничения — в [ENGINE.md](ENGINE.md#gpu-приёмка-картинки-камер-metaloffscreen).
|
||||
- **#96:** engine `e44ad82a9`: opt-in `audio::tests::export_moving_mass_raid` проводит
|
||||
100 движущихся двигателей и 16 импульсных источников через настоящие `Audio::tick_acoustics`
|
||||
и `film_mix`: эхо/реверб, камера, инвалидация и смена epoch, новый capture без старого хвоста.
|
||||
Два 6-секундных прогона дают одинаковые float-сэмплы; ненулевая дорожка, finite/peak и reset
|
||||
проверяются assertions. Сэмплы и геометрия синтетические, устройство звука не открывается.
|
||||
Release на Apple M5: step+mix на 50 мс аудио — p50 **3.55 мс**, p95 **4.30 мс**, max **5.57 мс**.
|
||||
[Отчёт и SHA дорожки](measurements/mass-acoustics-2026-11-04.json).
|
||||
Это не замер полного игрового CPU/GPU, не Windows FPS и не готовый MP4.
|
||||
|
||||
## Продолжение #91: один источник чисел
|
||||
|
||||
`catalog/specs.json` теперь единственная копия числовых строк симуляции: 13 дронов
|
||||
(`DroneKind::spec`), 9 ракет (включая `seeker`, звук пуска и голос мотора), 15 комплексов
|
||||
(`SamKind::spec`, включая части моделей и именованные наборы), общие константы гравитации,
|
||||
высоты раскрытия «Орешника», приводов и логистики. `tools/gen_catalog.py` генерирует
|
||||
`airdef-mod/src/sim/specs_generated.rs` и `unit_specs_generated.rs`; `include!` встраивает их в
|
||||
`mod.rs` и `units.rs`, поэтому мод и `airdef-core` компилируют одни и те же строки. Прежние
|
||||
`match`-литералы удалены; `DroneKind::spec`, `MissileKind::spec`, `SamKind::spec` и их производные
|
||||
(RCS, seeker, звуки, голос) читают сгенерированные константы.
|
||||
|
||||
`load_specs` проверяет схему, звуковые ссылки, совпадение набора kinds с `content.json`, ссылки на
|
||||
именованные части и то, что каждая строка кем-то используется; `gen_catalog.py --check` уже в
|
||||
CI-шаге «Проверка generated assets», поэтому расхождение JSON и Rust валит сборку.
|
||||
|
||||
Сверка перед переносом: JSON сравнивался с литералами `632061d` по всем полям. Голос P1-SUN —
|
||||
тонкое место: фактически играет ранний возврат `flame == 0` в старом `voices.rs`
|
||||
(`(DRONE_LANCET, 0.8, 1.6)`), а `P1sun => 1.7` в `match` недостижим. Первая версия сверки ошибочно
|
||||
приняла недостижимую ветку за факт и поставила в JSON 1.7 — это меняло звук перехватчика; fixup
|
||||
вернул 1.6 и добавил регрессию `missile_engine_voices_keep_their_played_values` (P1-SUN и M48N6).
|
||||
После генерации строки сверены с прежними литералами поле-в-поле (включая части моделей и
|
||||
именованные refs) — расхождений нет. Порядок raid/save, ключи `sam`/дронов, RNG и тексты не менялись.
|
||||
|
||||
Проверки этого этапа: `cargo test --release` ядра — **194 passed, 7 ignored** + **8 сценариев**;
|
||||
адаптер — **64 unit**, **1 boundary**, **5 сценариев**; `gen_catalog.py --check`, `gen_models.py --check`,
|
||||
тесты генераторов/звука/границ моделей; настоящий WASM `test-wasm` — **27 шагов**, 1 скрипт.
|
||||
GUI/MP4 и варианты комплексов (разные ракеты/профили по батареям) в этот этап не входили.
|
||||
|
||||
## Проверки и продолжение
|
||||
|
||||
Объединённый core release: **193 unit**, 7 ignored, **8 сценариев**; адаптер: **64 unit**,
|
||||
**1 boundary**, **5 сценариев**. Генераторы catalog/models, asset pipeline, sound references,
|
||||
границы моделей и 6 тестов provenance/failure отчёта проверяются отдельно. Лёгкий WASM — 27 шагов.
|
||||
Тяжёлый default fixture — 271 шаг с двумя принятыми налётами; его текущий отчёт пишет
|
||||
`python tools/airdef.py test-budgets` в `.horizon-cache/wasm-budget-report.json`.
|
||||
Чистый финальный прогон `56339b0` с API29 сохранён в
|
||||
[api29-wasm-budget.json](measurements/api29-wasm-budget.json): tick max 106132646/300000000,
|
||||
command max 1013387/1000000000, ошибок 0, build identity совпал.
|
||||
|
||||
Не завершены: субъективное прослушивание, настоящий MP4 с акустикой, полный 10-минутный
|
||||
replay/export, расширенная модельная/ночная/FPS приёмка, визуальная/Windows-GPU приёмка
|
||||
camera-ready картинки и полные query/voice/peak-memory бюджеты.
|
||||
Старый допуск broadband RT60 35% не ужесточался до 15%.
|
||||
Попытка живого MP4 в этом проходе не дала проверенного файла и за приёмку не считается;
|
||||
изолированные процессы закрыты. Продолжать с текущего pin, не с временных пакетов агентов.
|
||||
|
||||
Обновление Windows прежнее: `git switch kimi-work`, `git pull --ff-only`,
|
||||
`python tools/airdef.py all`, `python tools/airdef.py play`.
|
||||
|
||||
## Обновление #89 (4 ноября, после этого прохода)
|
||||
|
||||
Живой короткий MP4 получен и проверен на pin `57f8b2853` (API 29) на scratch `HORIZON_HOME`/мире:
|
||||
h264 + AAC, отчёт мода совпадает с `ffprobe nb_frames`, отмена/ошибка SDK/ошибка энкодера/повторный
|
||||
запуск проходят. Найден и исправлен дефект: выход в заголовок во время экспорта оставлял захват
|
||||
записывать заголовок (запрос `sec=10` дал 3898 кадров); теперь показ завершается по кадровому хуку.
|
||||
Подробности и проверенные ограничения — [HD-RENDERER](HD-RENDERER.md) (раздел про кинорежиссёра)
|
||||
и [ENGINE](ENGINE.md) (раздел про захват). Очистка временных файлов при ошибке энкодера
|
||||
исправлена в движке `73b9d3070`: лог удаляется, его последние строки входят в текст ошибки, а
|
||||
готовый MP4 прежнего экспорта с тем же именем сохраняется. Акустика проверена отдельно в настоящем
|
||||
MP4 (пары on/off одного повтора, статусы ready, диффузный wet-остаток в каменном дворе); чистый
|
||||
хвост/RT60 и прослушивание остаются — [ACOUSTICS](ACOUSTICS.md). 10-минутный экспорт и Windows/Linux
|
||||
по-прежнему не проверены.
|
||||
|
||||
## Обновление #123
|
||||
|
||||
Engine `45b43f00d`: dynamic block models используют геометрическую нормаль квада вместо осевого
|
||||
`facing`; для вырожденных вершин сохранён прежний fallback. Unit-тест покрывает `±45°`, другие
|
||||
наклоны, осевые и вырожденные квады. На реальном Lancet-инстансе через `set-models`, `glow=false`
|
||||
и HD получены парные кадры до/после в одном мире и ракурсе, а также вид сверху и ночью; полосы
|
||||
осевого освещения устранены. [Кадры и ограничения](AIRCRAFT-MODELS.md). Массовый FPS и полёт не
|
||||
измерялись.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Проверка 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/кадрами.
|
||||
+196
-1
@@ -59,4 +59,199 @@ runtime закреплённого движка. Используется вре
|
||||
и причина (`awaiting-frame`, `disabled`, `path-unavailable`, `ready`). AirDef убирает обычный дым
|
||||
только когда выполнены все четыре условия; после смены мира старые сегменты и часы очищаются.
|
||||
Это подтверждение выбранного пути рендера, а не завершения GPU или видимости каждого сегмента.
|
||||
Для акустики и capture аналогичное подтверждение этим API не реализовано.
|
||||
Сам `smoke-status` не подтверждает акустику и capture; их отдельные статусы добавлены в API 27 ниже.
|
||||
|
||||
## Акустика и владение захватом (API 27)
|
||||
|
||||
Текущий pin: `2bcce642362ab5d3f04de193e390d8293cd1bf30` (API 31; `render.project` — проекция
|
||||
мировых точек через камеру последнего отрисованного кадра, #132; ниже — staging, cascades,
|
||||
previous-frame motion и feature-gated DLSS SR backend #124, API 30). Акустические
|
||||
`render.acoustics-status` и `render.capture-owner-status` возвращают поколение,
|
||||
`available`, `enabled`, `request-accepted`, `prepared` и причину. В игре всё это показывает
|
||||
`/airdef capabilities`. Отсутствие запроса, выключение, ожидание backend и ошибка различаются.
|
||||
|
||||
Для акустики `prepared` означает выполненный шаг обработки с геометрией при доступном live/offline
|
||||
микшере. Шаг может поставить worker job или принять результаты; это **не** подтверждение результата
|
||||
для каждого источника, завершения worker, слышимого звука или точного отражения. В режиме no-audio
|
||||
без offline-микшера готовность не наступает. AirDef подтверждает текущее глобальное предпочтение,
|
||||
не меняя его, и сохраняет собственные дальние варианты звука до подтверждённой подготовки.
|
||||
|
||||
Для capture запрос принадлежит конкретному запуску мода и поколению мира. `prepared` соответствует
|
||||
его стадиям Recording/Encoding/Done; состояние файла и ошибка по-прежнему читаются из `capture-status`.
|
||||
AirDef не принимает чужие Recording/Done за свой экспорт. Ожидание первоначальной подготовки
|
||||
ограничено 600 тиками. Остановка проверяет владельца; смена мира отменяет модовый захват и
|
||||
сбрасывает готовность. Уже переданный writer файл на Encoding может всё же завершиться:
|
||||
это запрос отмены, не гарантия удаления файла.
|
||||
|
||||
Проверено на реальном экспорте 4 ноября (pin `57f8b2853`; очистка ошибки в `73b9d3070`):
|
||||
|
||||
- Смена мира доходит до движка только через снимок мода (`set_snapshot`). На экране заголовка тики
|
||||
не вызываются, поэтому мод без хука `frame` не сообщает о закрытии мира, и захват продолжает
|
||||
писать заголовок. AirDef теперь просит `frame` и завершает показ по `game.world-id = none`.
|
||||
- При ошибке энкодера временные файлы этого захвата (`<имя>.video.mp4`, `<имя>.audio.raw`,
|
||||
`<имя>.ffmpeg.log`) удаляются, а последние строки лога переносятся в текст ошибки: ссылки на
|
||||
уже удалённый лог больше нет. Кодировщик всегда пишет `<имя>.video.mp4`, а `<имя>.mp4`
|
||||
появляется только после успешного mux или переименования, поэтому неудачный, отменённый или
|
||||
беззвучный захват не перезаписывает и не удаляет готовый фильм прежнего экспорта с тем же
|
||||
именем. Исправлено в `73b9d307048fc44d7f21fa3c829fc5a855d144a6` (`game/film.rs`), проверено
|
||||
реальной ошибкой ffmpeg и контрольным MP4.
|
||||
|
||||
## Отдельный тяжёлый WASM tier
|
||||
|
||||
```sh
|
||||
python3 tools/airdef.py test-budgets
|
||||
python3 tools/test_budget_report.py
|
||||
python3 tools/test_airdef_build.py
|
||||
```
|
||||
|
||||
Сценарий `airdef-mod/tests/budgets/wasm_flat_budget.toml` запускается в изолированном временном `tests/`,
|
||||
поскольку CLI читает только непосредственные `tests/*.toml`. Обычный `test-wasm` остаётся лёгким.
|
||||
Ручной workflow `.gitea/workflows/wasm-budget.yml` не добавляет нагрузку на каждый push.
|
||||
|
||||
Исходный профиль запрашивал 64 комплекса и две волны по 80 целей на 4000 блоках,
|
||||
602 вызова tick и 300 frame, 69 шагов. Позднее обнаружено: второй заказ во время подготовки
|
||||
первого отклонялся, а fixture не проверял ответ. Поэтому тот прогон **не доказывает перекрытие
|
||||
160 целей**; сохранённый JSON помечен `coverage_correction`. Новый сценарий проверяет принятие
|
||||
обоих заказов и отличает requested counts от неизвестного пика в воздухе.
|
||||
Это не полный лимит расстановки (2000) и не нагрузочный
|
||||
тест GPU, mixer voices или всех физических world replies: sandbox не выполняет настоящий рендер/звук.
|
||||
|
||||
Текущий default заменён на flat render-world: ground/sections/rays отвечают для плоскости y=64,
|
||||
GPU не имитируется. Проверяются два принятых налёта по 40 «Орешников» и 64 ПВО; в середине
|
||||
включаются HD и grid. На тике 2102 assertion подтверждает **184 цели в воздухе**, а не пик за всё время.
|
||||
Прогон `2932364` прошёл: 271 шаг, 2102 tick и 2052 вызова frame стенда. У AirDef нет собственного
|
||||
frame hook; эти вызовы не являются нагрузкой на GPU или измерением 10M frame fuel мода.
|
||||
Точный отчёт: [flat-world budget](measurements/flat-wasm-raid-budget.json).
|
||||
|
||||
С 4 ноября (#122) fixture расширен хвостом умных приказов через UI-путь: 4 РЭБ, `airdef preset 1`
|
||||
(та же `apply()`, что у кнопки готового состава) и два `airdef raid` — это та же функция
|
||||
`launch_wave`, что у кнопки ПУСК (`ui_select`), с боевым журналом разведки и EW; оба приказа
|
||||
приняты (`expect.chat = []`), итого 4 принятых приказа, финальный `/stats` закреплён строкой.
|
||||
Прогон исправления #122: 283 шага, 3302 tick; max fuel tick 182413686/300M, command 6939810/1e9,
|
||||
ошибок 0. Отчёт: [flat-world budget](measurements/flat-wasm-raid-budget.json).
|
||||
|
||||
Fixture копируется из тех же байтов, чей SHA записан до сборки. Проверенные 2 принятия и точка
|
||||
184/2102 заносятся только после success и совпадения `BUDGET_ASSERTED_SHA256` с точной версией файла.
|
||||
После изменения fixture нужно повторно проверить её и обновить SHA/метаданные; простой список
|
||||
запрошенных целей не заменяет assertions. Пик остаётся null, если он не измерен.
|
||||
Отчёт `.horizon-cache/wasm-budget-report.json` содержит SHA/dirty/diff AirDef, pin/identity движка,
|
||||
API/WIT/артефакт, проверку build identity, сценарий, Wasmtime и исходные memory/fuel limits.
|
||||
`AIRDEF_BUDGET_REPORT` меняет путь отчёта. Stale identity запрещает запуск, ошибки сборки/тестов
|
||||
записываются как failed и дают ненулевой exit code.
|
||||
|
||||
Лимиты берутся из исходников: memory 64 MiB; fuel init/tick/frame/event — 2B/300M/10M/1B.
|
||||
Начиная с продолжения 4 ноября `test-budgets` включает `--fuel-profile` и сохраняет
|
||||
`measured_fuel.callbacks`: число вызовов, максимум guest fuel, бюджет и ошибки отдельно по callback.
|
||||
Отсутствие запрошенных счётчиков делает проверку неуспешной, даже если сценарий завершился.
|
||||
Это не время host/GPU и не peak memory; невызывавшиеся callbacks, включая init до включения профиля,
|
||||
не получают выдуманного нуля. Первый прогон: tick 2102 вызова, max 106132646/300000000;
|
||||
command 69 вызовов, max 1013370/1000000000; ошибок нет. Прогон исправления #122 (283 шага,
|
||||
включая два умных UI-приказа): tick 3302 вызова, max 182413686/300M; command 79 вызовов,
|
||||
max 6939810/1e9; ошибок нет.
|
||||
Исторический отчёт без измерения fuel:
|
||||
[API27 budget report с поправкой покрытия](measurements/api27-wasm-budget.json).
|
||||
Актуальный чистый API29-прогон с измерением:
|
||||
[271 шаг, fuel и build identity](measurements/api29-wasm-budget.json).
|
||||
Актуальный прогон с умными UI-приказами #122 и build identity:
|
||||
[flat-world budget](measurements/flat-wasm-raid-budget.json).
|
||||
|
||||
Проверены реальный WASM guest с переходами состояний/владельца/мира, сборка клиента и два коротких
|
||||
offscreen-профиля Metal. При `HORIZON_ACOUSTICS=1` + `HORIZON_NO_AUDIO=1` в игре получено
|
||||
enabled/request=true, prepared=false, awaiting-backend; HD smoke переходит в ready после подготовки
|
||||
основного кадра. Это не замер производительности и не прослушивание.
|
||||
|
||||
API28/29 добавляют отдельные `point-lights-status` и `sound-sources-status`: свет подтверждается
|
||||
после cache/main-view HD обработки, звук — после source-manager apply с live/offline output.
|
||||
Заявки привязаны к запуску мода и поколению мира; звук также к source epoch. Clear/reload/выход
|
||||
снимают подтверждение. Это не GPU fence, загрузка сэмпла, наличие голоса или слышимость.
|
||||
Камеры и их targets изолированы по `(run_serial, local_id)` вместо глобального ID.
|
||||
|
||||
API30 добавляет `camera-status` для камер `set-views` вызывающего запуска: доступность API,
|
||||
включение пути картинок в последнем отмеченном кадре, принятие заявки поколения и поштучная
|
||||
готовность каждой камеры. `prepared` означает, что рендерер закодировал кадр камеры в её
|
||||
texture target, либо кадр мира отрендерен с неё как main-view **этого** запуска: если одинаковый
|
||||
local ID выбрали два мода, экран использует выбор первого, и milestone получает только он; чужая
|
||||
картинка с тем же ID чужую камеру не готовит. `enabled` — последний отмеченный кадр был кадром
|
||||
мира (не заголовок/загрузка). Это не регистрация target и не GPU fence: видимый пиксель,
|
||||
представление кадра и обход ротации per-frame бюджета не гарантируются. Пустая `set-views`
|
||||
снимает заявку и готовность; смена мира очищает заявку, выбор main-view и готовность (камеры
|
||||
другого мира не рисуются), перезагрузка мода начинает заново, а повторная отправка и камера,
|
||||
отданная в main-view, ждут нового кадра (у такой камеры нет своего picture target).
|
||||
Проверено двумя настоящими Wasmtime-гостями с одинаковым local ID, пустой заявкой, сменой мира
|
||||
и reload. `/airdef capabilities` показывает строку камер.
|
||||
|
||||
### GPU-приёмка картинки камер (Metal/offscreen)
|
||||
|
||||
Итоговый engine `278f356aa` с AirDef API30 проверен в запущенной игре, а не только в песочнице:
|
||||
macOS, Apple M5 (Metal, IntegratedGpu), `--offscreen`, `HORIZON_NO_AUDIO=1`, чистый
|
||||
`HORIZON_HOME=/tmp/airdef-camera-accept` и копии тестовых миров из scratch-папки прежних прогонов
|
||||
(`AirDefenseLab`, `Polygon`), ресурсы лаунчера v0.2.91. `.hmod` — из этого дерева
|
||||
(`python3 tools/airdef.py mod`, API30), не из основного дерева.
|
||||
|
||||
```
|
||||
tools/airdef.py install # HORIZON_HOME=<scratch>
|
||||
horizon-ctl --socket $H/ctl.sock launch --game horizon/target/fast/horizon-client \
|
||||
--world AirDefenseLab --creative --offscreen --wait --resources <26.3>
|
||||
# мод-команды клиентские: ctl command/chat уходят в консоль сервера, поэтому — через поле чата
|
||||
horizon-ctl key t tap; horizon-ctl type "/airdef capabilities"; horizon-ctl key enter tap
|
||||
horizon-ctl screenshot <png>
|
||||
```
|
||||
|
||||
Наблюдения (строки `/airdef capabilities`, `поколение` = generation):
|
||||
|
||||
| Когда | Камеры |
|
||||
| --- | --- |
|
||||
| камер нет | `API=true, включено=true, запрос=false, подготовлено=false, поколение=1, not-requested, main=нет, []` |
|
||||
| `/airdef deploy s400` + `/airdef monitor` | `... запрос=true, подготовлено=true, поколение=1, ready, main=нет, [32:ready]` |
|
||||
| `/airdef monitor` (пустая заявка) | `... запрос=false, ... not-requested, main=нет, []` |
|
||||
| `/airdef replay film best` | `... main=1996488705, [1996488705:ready]`, затем `main=1996488707` на следующем плане |
|
||||
| другой мир (AirDefenseLab → Polygon) | `поколение=2, запрос=false, ... not-requested, main=нет, []` |
|
||||
| там же deploy+monitor | `поколение=2, запрос=true, подготовлено=true, ready, [32:ready]` |
|
||||
|
||||
Снимки подтверждают, что `prepared` — нарисованная картинка, а не регистрация (число различных
|
||||
цветов, выборка каждого 6-го пикселя): при взгляде в небо (кадр однородный) включение монитора
|
||||
добавляло панель и picture-область — 477→4867 цветов на кадре; в том же мире A/B
|
||||
«монитор выключен/включён» в области панели: 199→2080 цветов,
|
||||
доля тёмной панели 1.2%→48.7%, а в области картинки 110→1771 цветов с доминирующим небом (рисуется
|
||||
сцена с камеры С-400, а не плоская заглушка «НЕТ СВЯЗИ»). В film-режиме экран показывал карточку
|
||||
«Готовлю кадры…» (фильм готовит планы), при этом main-view milestone был `ready` — это API-отметка
|
||||
и отрисовка кадров рендерером, не проверка пикселей фильма.
|
||||
|
||||
`title → тот же мир` не меняет поколение: заявка и milestone сохраняются (смена поколения — это
|
||||
смена мира), а `enabled` сбрасывается кадром заголовка (note с `world=false`), поэтому `ready`
|
||||
требует нового кадра мира после возврата; он и наступает (наблюдалось). 8 из 8 запросов при
|
||||
работающем мониторе дали `ready`. `set_views`/`set_main_view` вызываются модом каждый tick, то есть каждый
|
||||
tick начинает ожидание нового кадра: выборка между tick и note может честно показать
|
||||
`awaiting-frame` по порядку вызовов — это не flicker, а порядок tick → render → note.
|
||||
|
||||
Остаток этой приёмки: визуальная оценка человеком, Windows/другие GPU, два запуска с одинаковым
|
||||
local ID на GPU (покрыто Wasmtime-гостями), reload мода на GPU (покрыт host-тестом), fence/представление
|
||||
кадров не проверялись.
|
||||
|
||||
Остаток #102: полные query/voice/peak budgets,
|
||||
GPU/готовый MP4 и платформенная приёмка. Эти результаты текущими тестами не объявляются выполненными.
|
||||
|
||||
## Измеренный fuel и массовые взрывы
|
||||
|
||||
В runtime добавлен выключенный по умолчанию профиль вызовов. У тестового CLI флаг
|
||||
`test --fuel-profile` выводит mod/callback, число вызовов, максимальный израсходованный guest fuel,
|
||||
бюджет и число ошибок; результат печатается и при неуспехе сценария. Init до включения профиля
|
||||
и предыдущие поколения после reload в эти значения не входят. Это гостевые инструкции,
|
||||
не время CPU, не heap peak и не работа GPU/host. Обычный `test-budgets` без этого флага по-прежнему
|
||||
не выдаёт свои исходные caps за измеренный расход.
|
||||
|
||||
С профилем воспроизведён остановившийся tick на двух максимальных составах меню и HD:
|
||||
полный обход height-cache при каждом взрыве доводил его до 300M. `1f28f83` заменяет обход
|
||||
удалением только затронутого квадрата. В контрольном диагностическом WASM-прогоне после исправления
|
||||
3602 тика прошли, max tick fuel = 135273690/300M, failures=0. Лимиты не менялись.
|
||||
Диагностический гость содержит только временный способ запуска точного меню-состава;
|
||||
это не исходный пользовательский Windows-сеанс. [Данные и воспроизведение](RAID-STABILITY.md).
|
||||
|
||||
С профилем воспроизведён и второй класс — остановка в **событии UI** (не тике) на втором
|
||||
крупном приказе: переснимок `known_units` на каждом дроне приказа давал `дроны × журнал ×
|
||||
группировка` за одно событие, 1e9 исчерпаны ровно (max command fuel 1000000000/1e9,
|
||||
failures=1; состояние: 13172 записей журнала, 144 известных живых комплекса). Исправление
|
||||
(#122, одним снимком на приказ и O(журнал+группировка) за проход) доводит тот же сценарий
|
||||
до max command fuel 32946177/1e9, failures=0, `/stats` на тике 2602 совпал побайтово.
|
||||
Это гостевые инструкции, не прирост FPS; приёмка Windows-сеанса внешняя.
|
||||
[Данные и воспроизведение](RAID-STABILITY.md).
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Как подготовить удар по вражеской ПУ
|
||||
|
||||
Номера своей техники и вражеских ПУ — разные списки. На карте **M** щёлкните по своей машине:
|
||||
заголовок карточки показывает её номер. `/airdef sites` выводит номера разведанных вражеских площадок.
|
||||
|
||||
## Боеприпас
|
||||
|
||||
У обычного склада по умолчанию **0 RM48U**. Его обычные перезарядки ПВО — другой запас.
|
||||
Профиль наземного удара пока есть только у С-400; другие ЗРК таким способом не заряжаются.
|
||||
|
||||
Пример: склад №3, С-400 №2:
|
||||
|
||||
```text
|
||||
/airdef ground-stock 3 4
|
||||
/airdef ground-load 2
|
||||
```
|
||||
|
||||
Первая команда **задаёт остаток** склада равным четырём RM48U, а не прибавляет четыре.
|
||||
Это подготовка sandbox-сценария; производства этих ракет пока нет.
|
||||
Вторая загружает одну ракету. Каждый повтор загружает ещё одну, пока хватает запаса и ячеек.
|
||||
Четыре ТПК общие: например, после первой загрузки будет 3 ракеты ПВО + 1 RM48U.
|
||||
Вытесненная ракета ПВО остаётся на складе либо возвращается туда грузом ТЗМ.
|
||||
|
||||
Рядом с исправным развёрнутым С-400 и наполненным складом (менее 60 блоков) передача прямая.
|
||||
Вдали тот же приказ создаёт заявку, если есть запас и живая ТЗМ. Погрузка запрещена во время
|
||||
движения, перезарядки, подготовки пуска или при отказе пусковой. Нулевой запас не исправляется
|
||||
перестановкой склада ближе. Карточка склада показывает RM48U отдельно от обычного БК.
|
||||
|
||||
## Откуда берётся разведка
|
||||
|
||||
Она автоматическая. Поставьте и включите РЛС **до налёта**. Рабочая включённая РЛС может заметить **сам пуск** с наземной площадки,
|
||||
если он попадает в её игровой обзор и не закрыт рельефом. Это даёт оценку позиции; несколько
|
||||
наблюдений могут её уточнить. Обнаруженная позже летящая цель даёт лишь слабое предположение
|
||||
о направлении старта — оно не превращается в координаты от ожидания или от количества радаров.
|
||||
|
||||
Команда `/airdef sites` должна показать, что место ПУ определено. Если там только направление
|
||||
или «место неизвестно», удар не разрешён. Специальной команды, выдающей скрытые координаты,
|
||||
и отдельного ручного режима разведки сейчас нет. У запусков «за картой» сам пуск не наблюдается.
|
||||
Чтобы попробовать механику, используйте близкий наземный налёт и открытую местность; далёкая
|
||||
траектория сама по себе не гарантирует обнаружения площадки.
|
||||
|
||||
## Приказ на удар
|
||||
|
||||
После определения места, например вражеской ПУ №7:
|
||||
|
||||
```text
|
||||
/airdef sites
|
||||
/airdef strike 7
|
||||
```
|
||||
|
||||
Или **M → карточка вражеской ПУ → «Нанести удар»**. Кнопка появляется после определения позиции.
|
||||
Указывать номер своего С-400 в `strike` не надо: мод сам выбирает готовый совместимый носитель
|
||||
с RM48U в игровой дальности. Сначала проверяется разведка, поэтому её ошибка может появиться
|
||||
раньше сообщения о незагруженной ракете.
|
||||
|
||||
На носителе резервируется ячейка, открывается крышка, ракета выбрасывается; боеприпас списывается
|
||||
при выбросе. Пуск остаётся игровой стилизацией, а не моделью реального регламента.
|
||||
|
||||
## Возврат и отмена
|
||||
|
||||
```text
|
||||
/airdef ground-unload 2
|
||||
/airdef ground-cancel 2
|
||||
```
|
||||
|
||||
`ground-unload` у склада выгружает одну RM48U сразу; вдали резервирует её и вызывает ТЗМ для
|
||||
вывоза. `ground-cancel` отменяет ещё ожидающую доставку/вывоз. Уже забранная ракета находится
|
||||
в ТЗМ и продолжает путь на склад; команда не телепортирует её обратно в ПУ.
|
||||
|
||||
Возврат имеет приоритет, только пока он выполним: ПУ исправна и развёрнута, маршрут доступен,
|
||||
ракету ещё не забирает другая ТЗМ, а у склада есть место. Заявка при этом сохраняется, но
|
||||
невыполнимый вывоз не блокирует ТЗМ: свободная машина исполняет независимые заявки на доставку
|
||||
RM48U, а как только вывоз снова становится выполнимым, он встаёт в приоритет. Проверено
|
||||
регрессиями #128, включая консервацию боеприпасов и save-restore посреди маршрута.
|
||||
+83
-6
@@ -58,8 +58,12 @@ 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). Террейн + дальние LOD-тайлы +
|
||||
сущности. Полупрозрачное в G-буфер **не** попадает (идёт ванильным путём); вода — отдельный путь, см. п. 3 и «Вода».
|
||||
уровни света `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 и «Вода».
|
||||
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`; стекло,
|
||||
@@ -86,7 +90,9 @@ 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 блоков сбрасывает историю. Джиттер добавляется к
|
||||
дистанция для отбраковки дизокклюзии; телепорт > 64 блоков сбрасывает историю. Если world/G-buffer depth
|
||||
совпадают, history UV = current UV + motion/render_size; вода, прозрачность и небо используют прежний
|
||||
depth/camera fallback. Джиттер добавляется к
|
||||
`view_projection` только при HD (публичная матрица без джиттера); рука и HUD рисуются после tonemap и не дрожат.
|
||||
**TAAU**: если мир меньше окна (`HORIZON_HD_SCALE=0.67`), тот же проход (`fs_taau`, в таймингах `hd taau`) восстанавливает
|
||||
полное разрешение. История, bloom и tonemap — в разрешении окна. Для каждого пикселя выхода берётся 3×3 выборки мира
|
||||
@@ -225,6 +231,7 @@ 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` — выкл. | готово | в рабочем дереве форка |
|
||||
@@ -245,8 +252,14 @@ 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 заметно
|
||||
выше. Альтернатива на Mac — MetalFX через wgpu-hal (нативный код, только Metal) — отдельной опцией потом. DLSS
|
||||
нереален для нашей цели (только NVIDIA через Streamline, нет в wgpu).
|
||||
выше. #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 отдельно.
|
||||
2. **Вода** — СДЕЛАНО (патч 19, см. «Вода» ниже). Исходное ТЗ: отдельный G-буфер-путь для воды (маска + нормаль с анимированными волнами), SSR (трассировка по
|
||||
глубине, откат на небо/туман), преломление (смещение по нормали), затухание по глубине воды (цвет биома),
|
||||
блики солнца (GGX-подобный), френель. Подводный вид не ломать (`frame.underwater`).
|
||||
@@ -351,6 +364,36 @@ 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`): координаты камеры, косинусы углов.
|
||||
@@ -368,9 +411,43 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
|
||||
- Мод-HUD (`set-hud`) теперь рисуется и при `set-main-view` (титры, леттербокс фильма); ванильный HUD по-прежнему скрыт.
|
||||
- Режиссура: `airdef-mod/src/film.rs` (план по записи, варианты ракурсов, проверка рельефа по высотам `Ground::land_state`, ускорение/замедление времени).
|
||||
|
||||
### Проверенный жизненный цикл MP4 (4 ноября, pin `57f8b2853`, очистка ошибки энкодера — `73b9d3070`, API 29)
|
||||
|
||||
Реальный короткий экспорт на scratch `HORIZON_HOME`/мире (не на сохранениях игрока), Apple M5, Metal,
|
||||
ffmpeg 9.0.1. `/airdef replay export` с записанного налёта (4 цели, 4 перехвата), 640×360:
|
||||
|
||||
- готовый файл: h264 + AAC 48 кГц stereo, длительность видео = длительность звука; звук не пустой
|
||||
(mean −29.4 dB, max −18.0 dB); 2 с при 30 fps — 62 кадра, `sec=1` — 32, `noaudio` — 33 кадра без
|
||||
звуковой дорожки, `sec=0.01` — 3 кадра; 1920×1080 `sec=1` — 32 кадра. Число кадров в отчёте мода
|
||||
всегда совпадает с `ffprobe nb_frames`: очередь не теряет кадры на остановке.
|
||||
- 2–3 кадра сверх `sec` — это кадры, уже находившиеся в полёте на момент остановки (движок их
|
||||
дописывает); это не потеря хвоста. Отчёт и файл сходятся.
|
||||
- отмена во время записи (`/airdef replay stop`): сообщение «Экспорт отменён», файла и процессов
|
||||
ffmpeg не остаётся; сразу после отмены новый экспорт проходит.
|
||||
- отказ SDK (`size=10000x10000`): сообщение об ошибке, захват не остаётся, следующий экспорт проходит.
|
||||
- ошибка энкодера (подставной `HORIZON_FFMPEG`, отвечающий на `-encoders`, но падающий при записи):
|
||||
«Экспорт не удался: … Broken pipe …: fake encoder failed: no such codec»; временных файлов и
|
||||
процесса нет, а последние строки лога теперь в самом тексте ошибки (сам лог удалён). Готовый
|
||||
`keep.mp4` прежнего экспорта с тем же именем остался байт-в-байт (sha256), как и беззвучный
|
||||
`keepnone.mp4` после неудачного `noaudio`-экспорта с тем же именем. Движок `73b9d3070` всегда
|
||||
пишет `<имя>.video.mp4`; `<имя>.mp4` появляется только после успешного mux/переименования.
|
||||
Контрольный `ctrl` на итоговой сборке `73b9d3070` — h264 + AAC, 33 кадра, временных файлов нет;
|
||||
`keep` (h264 + AAC, 32 кадра) и `keepnone` (только h264, 32 кадра) проверялись на той же правке.
|
||||
- акустика в MP4: пары on/off одного повтора (кнопка мода) со статусами `Акустика … ready` и
|
||||
`Захват … ready`; в открытом поле send реверба нулевой по построению, в каменном дворе ON тише и
|
||||
глуше, а остаток после вычитания масштабированного сухого сигнала низкочастотный и
|
||||
декоррелированный (wet-путь). Цифры, статусы и ограничения — [ACOUSTICS.md](ACOUSTICS.md).
|
||||
- **выход в заголовок во время экспорта** (до исправления): игра перестаёт тикать на экране
|
||||
заголовка, но продолжает кадры, поэтому захват писал заголовок; запрос `sec=10` дал 3898 кадров
|
||||
(129.9 с), временные `video.mp4`/`audio.raw` и ffmpeg оставались, а после возврата в тот же мир
|
||||
экспорт продолжался. Мод получает кадры и вне мира (`Mod::frame`), поэтому `Session::world_left`
|
||||
завершает показ с `ExitCause::WorldChange` и одним `CancelCapture`: после исправления при выходе
|
||||
в заголовок ffmpeg и временные файлы исчезают, повторный вход и следующий экспорт проходят.
|
||||
Пропуск мира виден по `game.world-id = none`; тик мода вне мира не вызывается.
|
||||
|
||||
## Цветные тени, рябь, кино-пост: что знать преемнику
|
||||
|
||||
- **Цветные тени.** Ближний каскад (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, малая сцена).
|
||||
- **Цветные тени.** Ближний каскад (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, малая сцена).
|
||||
- **Рябь.** `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 не менялся.
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
# Состояние исходных 16 задач
|
||||
|
||||
Ветка `kimi-work`, 3 ноября 2026. Issues остаются открытыми по просьбе владельца.
|
||||
Ветка `kimi-work`, 6 ноября 2026. Issues остаются открытыми по просьбе владельца.
|
||||
«Реализовано» ниже означает проверенный объём кода, а не закрытие issue и не подтверждение всех платформ.
|
||||
|
||||
Новый проверенный объём: [продолжение пяти задач 4 ноября](CONTINUATION-2026-11-04.md).
|
||||
#87: typed battery/world/damage diagnostics и адаптеры текста; #91: общий content/sound catalog
|
||||
для 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); старые номера/числа ниже описывают предыдущие этапы.
|
||||
Проблема нормалей модели #123 исправлена в engine `45b43f00d`; парные HD-кадры и ночная проверка Lancet записаны в галерее.
|
||||
|
||||
| Issue | Реализовано | Что остаётся для полной приёмки |
|
||||
|---|---|---|
|
||||
| #72 | Upstream Horizon 0.2.97 объединён с форком; сохранена история; локальные тесты и Metal-полигон | Windows/Linux, native HDR, сравнительная производительность |
|
||||
| #87 | Каноническое SDK-free ядро `airdef-core`, используется модом и сценариями | Дальнейшее отделение текстового/визуального вывода домена от адаптера |
|
||||
| #88 | Типизированный журнал измеренных переходов; read-only Snapshot для Smoke/Shown; записанные пожары, позы, пуски и зажигание | Перевести оставшиеся model/audio adapters и режиссёра на общий снимок; замер полной 10-минутной записи |
|
||||
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа | Полный игровой цикл MP4 с отменой/ошибкой энкодера и проверкой хвоста очереди |
|
||||
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей | Единый источник всех чисел, звуков и Python-регистраций; проверка вариантов комплексов |
|
||||
| #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 |
|
||||
| #92 | Authored overrides, проверка ссылок/PNG/границ, manifest, безопасная транзакционная генерация; registry/texture/icon modules | Дальнейшее ручное улучшение контента относится к #115 |
|
||||
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах | Прослушивание, игровой массовый звук/CPU, акустика реального MP4; точность RT60 пока по допуску 35%, не 15% |
|
||||
| #102 | Отдельный pinned engine, repo-local packer, build identity, настоящий WASM tier; API26 handshake дыма | Аналогичный статус для других возможностей, максимальные бюджеты и GPU/export tier |
|
||||
| #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-приёмка остаются |
|
||||
| #104 | Движок вынесен в `chexit/horizon-airdef`, ветка `airdef`; AirDef использует точный gitlink | Отдельная Windows-проверка миграции старого standalone checkout |
|
||||
| #107 | ПУ оценивается по наблюдениям: обратный курс не выдаёт точную ПУ | Повторная игровая проверка сценариев с маневрирующими целями |
|
||||
| #110 | Изменения чанков инвалидируют акустические снимки/кэш; включено в pin и проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
|
||||
@@ -20,7 +28,10 @@
|
||||
| #114 | Навигация учитывает footprint и окончательную authored-геометрию; остановка перед unread frontier; угловые пересечения | Массовая игровая проверка всех новых шасси на сложном рельефе |
|
||||
| #115 | Три пилота с кадрами до/после, спокойные материалы; authored-проход по боевым и вспомогательным машинам | Крупные планы и точность прототипов ещё промежуточные; остальные летательные аппараты/ракеты, анимации, дальние виды и FPS |
|
||||
| #116 | Streaming не освобождает busy-guard работающего acoustic worker; проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
|
||||
| #118 | Ручной пуск из физического С-400 с отдельным RM48U; четыре общие ячейки; конечный склад; доставка ТЗМ и возврат снятой ракеты ПВО; сохранение груза/заявки и продолжение реального маршрута; carrier, крышки, выброс, зажигание и разгон в записи; фантомное ПВО удалено | Визуальная приёмка всего пуска и доставки на сложном рельефе; другие носители не добавлены без подтверждённого профиля |
|
||||
| #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-сценария,
|
||||
@@ -38,8 +49,20 @@
|
||||
| Issue | Реализовано | Границы и оставшаяся приёмка |
|
||||
|---|---|---|
|
||||
| #119 | Три read-only луча в известной геометрии ослабляют непрямой blast для корпуса/узлов/объектов; проёмы дают частичное воздействие; прямой контакт сохранён | Unknown/stale: прежний урон без защиты, нулевое ожидание; partial blocks считаются занятыми кубами; GUI-проверка разрушения укрытия ещё нужна |
|
||||
| #120 | Конечное горение, powered/coast, сопротивление и снижение доступного манёвра, один остаточный pk по фактической скорости; swept-встреча; события burnout/energy loss; согласованное прекращение факела/дыма/звука | Игровой профиль, без аэродинамики и реальных параметров; сравнительная выборка 12 рейдов, расширенная балансировка и прослушивание остаются |
|
||||
| #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-профиль не проверялись |
|
||||
| #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 хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому
|
||||
незавершённый ретаргет продолжается после перезахода. Старые saves без секции `air` читаются как
|
||||
прежде (пустое небо), сценарии воздушное состояние не несут, replay по-прежнему хранит траектории.
|
||||
Ракеты-перехватчики, площадки запуска, промежуточный план, статистика волны и RNG не сохраняются —
|
||||
это ограничение записано в handoff.
|
||||
|
||||
Точные коммиты, формат сохранения, тесты и порядок продолжения:
|
||||
[CODEX-HANDOFF.md](CODEX-HANDOFF.md). Формальный open-статус не меняется после реализации.
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# Два крупных налёта: проверка стабильности
|
||||
|
||||
Пользовательский отчёт: AirDef часто перестаёт работать при двух больших налётах,
|
||||
резкого обвала FPS перед этим не замечено. RTX 3060 + Ryzen 5600X — около 50 FPS во время налёта.
|
||||
Пользователь уточнил: игра продолжает работать, отключается только AirDef; режим эффектов — HD.
|
||||
Точный build и старый лог не предоставлены. Horizon архивирует предыдущие логи в `logs/YYYY-MM-DD-N.log.gz`,
|
||||
поэтому запись может сохраниться и без ручного копирования.
|
||||
Задача: [#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.
|
||||
|
||||
## Второй налёт из UI: событие, не тик
|
||||
|
||||
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,
|
||||
remaining Some(0))`; backtrace: `ew::Sim::known_units` ← `raid::Sim::order_raid` ←
|
||||
`airdef::AirDef::launch_wave` ← `ui_select`. Прежний fix `1f28f83` — другой класс: тогда
|
||||
мод останавливался в **тике** на 300M.
|
||||
|
||||
**Причина.** `order_raid` для каждого дрона заново вычислял снимок известных комплексов
|
||||
`known_units()` (`choose_target`), а сам `known_units()` на каждую запись журнала разведки
|
||||
пересканировал весь список комплексов и список уже принятых. Журнал держит каждый пуск,
|
||||
каждое раскрытие РЭБ и каждую emitting-РЛС за последние 6000 тиков. Стоимость второго
|
||||
большого приказа росла как `дроны × журнал × размер группировки` внутри одного UI-события.
|
||||
|
||||
**Воспроизведение** (настоящий WASM, измеренный fuel по callback, диагностический гость —
|
||||
`trigger.patch` гоняет тот же обработчик `ui_select(BTN_LAUNCH)` → `launch_wave` →
|
||||
`order_raid` с максимальным составом меню; метка callback — `command`, бюджет тот же 1e9):
|
||||
разнесённая группировка 172 комплекса (40 кластеров × 4 тяжёлых + 12 РЭБ, игрок двигается
|
||||
шагами сценария — стек в одной точке умирает от одной боеголовки и не воспроизводит),
|
||||
первый налёт 111 дронов отбит, второй приказ на тике ~2600 при `revealed=13172`,
|
||||
`known=144` живых. До fix: второй приказ исчерпывает ровно 1e9 и останавливает мод
|
||||
(`before-trap.txt`); тот же приказ из 11 дронов в том же состоянии — 247805865
|
||||
(`before-scaling.txt`). После fix тот же сценарий проходит целиком: max command fuel
|
||||
32946177/1e9, max tick 236581288/300M, ошибок 0; `/stats` на тике 2602 совпал побайтово
|
||||
до/после, включая счётчики мира.
|
||||
|
||||
**Фикс.** Один снимок `known_units` на весь приказ, передаётся в `radar_strikes` и
|
||||
`choose_target`; сам `known_units` — один проход O(журнал + группировка) через множества;
|
||||
`price_grid_on` переиспользует свой снимок. Семантика планирования не изменилась:
|
||||
нативный тест сверяет новый снимок с прежним предикатом (дубликаты, погибшие, устаревшие,
|
||||
чужие id, порядок «новые первыми»). Лимиты не менялись, HD/запись не отключались,
|
||||
размер волны не ограничивался.
|
||||
|
||||
**Регрессии.** Нативные: эквивалентность снимка и «второй умный приказ с толстым журналом
|
||||
принят и запущен». Закреплённые WASM: тяжёлый fixture расширен — два умных приказа через
|
||||
функцию кнопки ПУСК (`airdef preset 1` + `airdef raid` — тот же `launch_wave`, что и у
|
||||
`ui_select`) с РЭБ и боевым журналом, оба приняты (`expect.chat = []`), 4 принятых приказа
|
||||
в отчёте; лёгкий контракт проверяет `preset` и отказ пустой волны. Данные и точный
|
||||
сценарий: [summary.json](measurements/issue-122-ui-fuel/summary.json),
|
||||
[trigger.patch](measurements/issue-122-ui-fuel/trigger.patch),
|
||||
[до](measurements/issue-122-ui-fuel/scenario-before.toml),
|
||||
[после](measurements/issue-122-ui-fuel/scenario-after.toml). Patch — только для
|
||||
диагностического гостя, в мод не входит.
|
||||
|
||||
Приёмка конкретного Windows-сеанса остаётся внешней: нужны build identity и строки
|
||||
`latest.log` вокруг остановки. Измерение fuel — не прирост FPS.
|
||||
|
||||
## Первая причина и фикс (тик, `1f28f83`)
|
||||
|
||||
Два максимальных состава меню (11 видов × 40, два принятых приказа), 64 ПВО, расстояние 300,
|
||||
HD и grid, обслуживаемый плоский мир: tick 1835 исчерпал ровно 300M fuel и мод остановился.
|
||||
Grid, запись и обновление дыма не были необходимы для этого spike: исследовательские абляции
|
||||
не убирали остановку. В производственном исправлении эти функции не отключаются.
|
||||
|
||||
`Ground::forget` при каждом взрыве делал `retain` по всему кэшу известных высот. Тот же полный
|
||||
обход выполнялся при обработке просроченных blast replies. Когда приходило много взрывов,
|
||||
затраты росли как произведение количества взрывов и размера/ёмкости таблицы высот.
|
||||
|
||||
`1f28f83` удаляет непосредственно координаты прежнего квадрата: при радиусе 8 это 17×17 ключей,
|
||||
а не просмотр всей таблицы. Вызов `world.touched` сохранён. Тест сравнивает весь результат со
|
||||
старым predicate, включая отрицательные координаты и границы; правила урона и лимиты не менялись.
|
||||
|
||||
Контрольный диагностический гость с полными записью, дымом, HD и grid, без phase markers:
|
||||
421 шаг, 3602 тика — PASS; max tick fuel 135273690/300M, command 92658271/1B, failures=0.
|
||||
Финальные показатели: 0 в воздухе, 209 сбито, 3435 поражений, 15 столкновений.
|
||||
На тике 1834 до прежней остановки вывод `/stats` до/после совпал побайтово,
|
||||
включая счётчики мира. Это не утверждение о равенстве каждого скрытого поля симуляции.
|
||||
|
||||
Для воспроизведения огромного меню-состава использован временный hook команды mix,
|
||||
вызывающий тот же `WaveConfig/order_raid`; сам hook **не входит в мод**.
|
||||
Исходник — `10f24b5`, после фикса добавлен только новый `forget`. Данные, hook и точный
|
||||
сценарий: [summary.json](measurements/max-raid-fuel/summary.json),
|
||||
[trigger.patch](measurements/max-raid-fuel/trigger.patch),
|
||||
[scenario.toml](measurements/max-raid-fuel/scenario.toml),
|
||||
[до](measurements/max-raid-fuel/before.txt), [после](measurements/max-raid-fuel/after.txt).
|
||||
Patch предназначен для отдельного диагностического worktree, а не для обычной игры.
|
||||
Два checkpoint-лога намеренно заканчиваются несовпадением с `probe`, чтобы получить `/stats`;
|
||||
это не реальные traps. Успешный полный прогон отдельно в `after.txt`.
|
||||
|
||||
Публичный native-тест `two_maximum_menu_raids_with_answered_flat_terrain` использует настоящий
|
||||
максимальный `RaidOrder` без hook, terrain replies и запись. Он также прошёл.
|
||||
|
||||
## Найденные пробелы старых тестов
|
||||
|
||||
В первом `wasm_budget.toml` два приказа отправлялись без тика между ними. `order_raid` отклоняет
|
||||
второй во время подготовки первого; ответ не проверялся. Кроме того, TestGame не отвечал на
|
||||
render ground/sections/rays: пуски могли ждать неизвестную землю вместо полноценного полёта.
|
||||
69 успешных шагов не подтверждали 160 одновременно летящих целей. Старый отчёт сохранён с поправкой.
|
||||
|
||||
## Что проверено теперь
|
||||
|
||||
- Native: точный состав двух меню-пресетов «Массированный удар», 61 комплекс, плоский мир с
|
||||
ответами геометрии и встроенной записью. Оба приказа приняты, все 72 цели запущены,
|
||||
перекрытие проверено по числу одновременно живых целей.
|
||||
- Native: два приказа 40+40 «Орешников» с разделением, многими суббоеприпасами и окончанием записи.
|
||||
- Actual WASM: 64 комплекса, два принятых приказа 40+40 «Орешников», плоскость y=64 с ответами
|
||||
ground/sections/rays. В середине включаются shader hd и grid. 271 шаг прошёл;
|
||||
на тике 2102 проверено **184 цели в воздухе**. Пик за весь прогон не измеряется.
|
||||
- Кадры чередуются с тиками. 2052 вызова frame стенда не означают GPU-рендер:
|
||||
у AirDef нет собственной реализации frame hook, основная работа идёт в tick и событиях.
|
||||
|
||||
Отчёт clean `2932364`, engine `ed7615d36`:
|
||||
[flat-wasm-raid-budget.json](measurements/flat-wasm-raid-budget.json).
|
||||
Memory 64 MiB и fuel init/tick/frame/event 2B/300M/10M/1B не увеличивались.
|
||||
Отчёт фиксирует исходные лимиты, не измеренный расход fuel/peak memory.
|
||||
|
||||
```sh
|
||||
python3 tools/airdef.py test-budgets
|
||||
cargo test --release --manifest-path airdef-core/Cargo.toml --test scenarios overlapping_
|
||||
```
|
||||
|
||||
Это проверка гостевого кода и контрактов с синтетическим host-миром. Она не воспроизводит
|
||||
RTX-драйвер, реальный рельеф/чанки, звук и стоимость HDR, shadow/light/smoke на GPU пользователя.
|
||||
Включение HD в fixture проверяет путь подготовки модовых данных, а не графическую производительность.
|
||||
|
||||
## Диагностика следующего воспроизведения
|
||||
|
||||
В `latest.log` после остановки теперь записываются mod ID, callback, заданный и оставшийся fuel,
|
||||
полная цепочка ошибки. Сообщение OutOfFuel больше не объявляет тяжёлую работу бесконечным циклом.
|
||||
Проверка настоящим WASM `/spin` подтверждает, что при fuel trap останавливается только нарушивший мод.
|
||||
Это не доказывает, что пользовательский случай имеет ту же причину.
|
||||
|
||||
Нужны build identity и строки Windows `latest.log` вокруг остановки, состав двух налётов,
|
||||
HD/обычный профиль, открытые grid/monitor/replay и ответ: закрылась ли игра целиком.
|
||||
До этих данных не подменять диагноз увеличением fuel, отключением записи или обрезанием целей.
|
||||
Измерение FPS вести отдельно от поиска trap: стабильный FPS не исключает лимит WASM, а прошедший
|
||||
WASM-тест не исключает ошибку GPU или native host.
|
||||
+5
-2
@@ -34,10 +34,13 @@
|
||||
Команды:
|
||||
|
||||
- `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow).
|
||||
- `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.json`, `catalog/specs.json` или `catalog/sounds.json`; `--check` проверяет актуальность.
|
||||
- `python3 tools/gen_models.py` — перегенерировать.
|
||||
- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях.
|
||||
|
||||
`tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`.
|
||||
`catalog/specs.json` — единственный источник числовых профилей симуляции: строки `DroneSpec`, `MissileSpec`/`MissileKind` (включая RCS, seeker, звук пуска и голос мотора), `SamSpec` (оружие, части моделей, приводы, датчик), общие константы (гравитация, высота раскрытия «Орешника», логистика) и именованные наборы частей. `tools/gen_catalog.py` создаёт из него `airdef-mod/src/sim/specs_generated.rs` (включается в `mod.rs`; тот же файл компилирует `airdef-core`) и `airdef-mod/src/sim/unit_specs_generated.rs` (включается в `units.rs`). Эти два файла не редактировать вручную. `tools/airdef_assets/catalog.py::load_specs` проверяет схему, звуковые ссылки, наборы kinds против `content.json`, ссылки на именованные части и заполненность всех строк; `gen_catalog.py --check` в CI ловит расхождение. Значения — игровой масштаб, не реальные характеристики техники.
|
||||
|
||||
`catalog/sounds.json` хранит звуковые ID, дальности и наличие дальнего варианта; `tools/gen_catalog.py` экспортирует ID для Rust, а `tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`.
|
||||
|
||||
## Архив: `legacy/`
|
||||
|
||||
@@ -52,7 +55,7 @@
|
||||
- `tools/airdef_assets/bounds.py` экспортирует габариты итоговых моделей для headless-навигации; authored overrides входят в расчёт.
|
||||
- `tools/gen_tex.py` отвечает за вывод процедурных текстур и иконок; переиспользуемые примитивы палитры также находятся здесь.
|
||||
- `tools/airdef_assets/texture_catalog.py` связывает стабильную палитру и процедурные функции с текстурами моделей, не смешивая каталог с геометрией.
|
||||
- `tools/airdef_assets/icons.py` содержит каталог предметов и чистую функцию рендера иконки с явными параметрами `(name, color, seed)`.
|
||||
- `catalog/content.json` задаёт идентичности техники и предметов и оформление предметов; `tools/airdef_assets/icons.py` читает его и содержит чистую функцию рендера иконки с явными параметрами `(name, color, seed)`.
|
||||
- `tools/airdef_assets/pipeline.py` проверяет manifest, рассчитывает безопасный план обновления и откатывает записи при исключении.
|
||||
- `airdef-mod/source-assets/assets/airdef/` — источник авторских переопределений. Генератор объединяет его с процедурными ресурсами во временном дереве, проверяет ссылки/JSON/PNG, затем устанавливает runtime-файлы.
|
||||
- `airdef-mod/assets/` и `airdef-mod/data/` — упакованные generated output. Не редактируйте их вручную; добавляйте авторские исходники в `source-assets`.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"airdef": {
|
||||
"diff_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"dirty": false,
|
||||
"sha": "aab3e784b8a87d3af0741b8c47d3351cd68dc152"
|
||||
},
|
||||
"api_level": 27,
|
||||
"artifact_sha256": "faecb18f25210e694fb53a1f6f99afe4abc3060a68a0376555e8b1dc9114d612",
|
||||
"build_identity": {
|
||||
"checks": {
|
||||
"airdef_diff_sha256": true,
|
||||
"airdef_dirty": true,
|
||||
"airdef_sha": true,
|
||||
"artifact_sha256": true,
|
||||
"engine_identity": true,
|
||||
"engine_pin": true,
|
||||
"wit_sha256": true
|
||||
},
|
||||
"matches": true,
|
||||
"path": "airdef-mod/target/horizon-mod/build-identity.json"
|
||||
},
|
||||
"command": "test-budgets",
|
||||
"coverage_correction": {
|
||||
"confirmed_peak_airborne": null,
|
||||
"reason": "Second raid was requested during planning and not accepted; original fixture did not assert feedback. The runtime pass does not confirm 160 active or launched units.",
|
||||
"second_raid_accepted": false,
|
||||
"valid_double_raid_proof": false
|
||||
},
|
||||
"engine": {
|
||||
"identity": "c89c78c47047fcfc0dfb0b8968600c650bf12d2b",
|
||||
"pin": "c89c78c47047fcfc0dfb0b8968600c650bf12d2b"
|
||||
},
|
||||
"exit_code": 0,
|
||||
"output": " Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.34s\n Running `<checkout>/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod <checkout>/airdef-mod/target/horizon-mod/airdef.hmod budget`\nrunning 1 scripts against <checkout>/airdef-mod/target/horizon-mod/airdef.hmod\ntest tests/wasm_budget.toml ... ok (69 steps)\ntest result: ok. 1 passed\n",
|
||||
"runtime_limits": {
|
||||
"fuel_per_call": {
|
||||
"event": 1000000000,
|
||||
"frame": 10000000,
|
||||
"init": 2000000000,
|
||||
"tick": 300000000
|
||||
},
|
||||
"memory_bytes": 67108864,
|
||||
"metering": "source_configured; measured_per_scenario: unavailable",
|
||||
"source": "horizon/crates/horizon-mods/src/runtime.rs",
|
||||
"wasmtime_component_model": true,
|
||||
"wasmtime_fuel_metering": true
|
||||
},
|
||||
"scenario": "tests/budgets/wasm_budget.toml",
|
||||
"scenario_counts": {
|
||||
"air_defense_units": 64,
|
||||
"frames": 300,
|
||||
"layout_unit_limit": 2000,
|
||||
"max_units_per_raid": 80,
|
||||
"raids": 2,
|
||||
"requested_raid_units": 160,
|
||||
"scripts": 1,
|
||||
"steps": 69,
|
||||
"ticks": 602
|
||||
},
|
||||
"scenario_sha256": "58490798d6e70910e188ffe8fd282fbf975fec5548287561b227fc53e06bf7e6",
|
||||
"schema": 1,
|
||||
"status": "passed",
|
||||
"wasmtime_version": "48.0.7",
|
||||
"wit_sha256": "14c57b73f144888e04e27b77a6dfa29098c6b0c27c0383bb96aedaccb4c0a1d4"
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"airdef": {
|
||||
"diff_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"dirty": false,
|
||||
"sha": "56339b076e3dad9c6825ddbc73fdfe6b9a2727bc"
|
||||
},
|
||||
"api_level": 29,
|
||||
"artifact_sha256": "f3720d58e18210b2e962ae924306a18cbf12c28e033c2bf862ad6a1a0db462b6",
|
||||
"build_identity": {
|
||||
"checks": {
|
||||
"airdef_diff_sha256": true,
|
||||
"airdef_dirty": true,
|
||||
"airdef_sha": true,
|
||||
"artifact_sha256": true,
|
||||
"engine_identity": true,
|
||||
"engine_pin": true,
|
||||
"wit_sha256": true
|
||||
},
|
||||
"matches": true,
|
||||
"path": "/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/build-identity.json"
|
||||
},
|
||||
"command": "test-budgets",
|
||||
"engine": {
|
||||
"identity": "57f8b2853c4443f7e3ff5701600cbb262b53118f",
|
||||
"pin": "57f8b2853c4443f7e3ff5701600cbb262b53118f"
|
||||
},
|
||||
"exit_code": 0,
|
||||
"measured_fuel": {
|
||||
"available": true,
|
||||
"callbacks": [
|
||||
{
|
||||
"budget": 1000000000,
|
||||
"callback": "command",
|
||||
"calls": 69,
|
||||
"failures": 0,
|
||||
"max_used": 1013387,
|
||||
"mod": "airdef"
|
||||
},
|
||||
{
|
||||
"budget": 300000000,
|
||||
"callback": "tick",
|
||||
"calls": 2102,
|
||||
"failures": 0,
|
||||
"max_used": 106132646,
|
||||
"mod": "airdef"
|
||||
}
|
||||
],
|
||||
"scope": "guest callback fuel; excludes host CPU, memory and GPU time"
|
||||
},
|
||||
"output": " Compiling horizon-mods v0.1.0 (/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/crates/horizon-mods)\n Compiling cargo-horizon-mod v0.1.0 (/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/crates/cargo-horizon-mod)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.70s\n Running `/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod /Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/airdef.hmod --fuel-profile budget`\nrunning 1 scripts against /Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/airdef.hmod\nfuel airdef command: calls=69 max=1013387 budget=1000000000 failures=0\nfuel airdef tick: calls=2102 max=106132646 budget=300000000 failures=0\ntest tests/wasm_budget.toml ... ok (271 steps)\ntest result: ok. 1 passed\n",
|
||||
"runtime_limits": {
|
||||
"fuel_per_call": {
|
||||
"event": 1000000000,
|
||||
"frame": 10000000,
|
||||
"init": 2000000000,
|
||||
"tick": 300000000
|
||||
},
|
||||
"memory_bytes": 67108864,
|
||||
"metering": "source_configured",
|
||||
"source": "horizon/crates/horizon-mods/src/runtime.rs",
|
||||
"wasmtime_component_model": true,
|
||||
"wasmtime_fuel_metering": true
|
||||
},
|
||||
"scenario": "tests/budgets/wasm_flat_budget.toml",
|
||||
"scenario_counts": {
|
||||
"accepted_raids_asserted": 2,
|
||||
"air_defense_units": 64,
|
||||
"frames": 2052,
|
||||
"layout_unit_limit": 2000,
|
||||
"peak_airborne_observed": null,
|
||||
"raid_requests": 2,
|
||||
"raid_units_requested": 80,
|
||||
"scripts": 1,
|
||||
"snapshot_airborne_asserted": 184,
|
||||
"snapshot_tick": 2102,
|
||||
"steps": 271,
|
||||
"ticks": 2102
|
||||
},
|
||||
"scenario_render_world": "flat at y=64",
|
||||
"scenario_sha256": "bcc0359289ab20ab3de608bcc130f72d2cf88f9f6fbc470d7b6846e9db5d11df",
|
||||
"schema": 1,
|
||||
"status": "passed",
|
||||
"wasmtime_version": "48.0.7",
|
||||
"wit_sha256": "dded023a150a5f916bc5d935b7f891806728e0118eb7107ad0551d2aad8c70a5"
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"airdef": {
|
||||
"diff_sha256": "143fbab5f1fd60981df9ef8ef3081b08a4102507f2588c6942924a7325b5139b",
|
||||
"dirty": true,
|
||||
"sha": "e6a70004406b34ea17884875ce236a5fb4b849e4"
|
||||
},
|
||||
"api_level": 29,
|
||||
"artifact_sha256": "c4ef7d759524eb053ccd55f0eccdcb49c91954201eb4e0ad923ee9b2828efc4e",
|
||||
"build_identity": {
|
||||
"checks": {
|
||||
"airdef_diff_sha256": true,
|
||||
"airdef_dirty": true,
|
||||
"airdef_sha": true,
|
||||
"artifact_sha256": true,
|
||||
"engine_identity": true,
|
||||
"engine_pin": true,
|
||||
"wit_sha256": true
|
||||
},
|
||||
"matches": true,
|
||||
"path": "/private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/build-identity.json"
|
||||
},
|
||||
"command": "test-budgets",
|
||||
"engine": {
|
||||
"identity": "73b9d307048fc44d7f21fa3c829fc5a855d144a6",
|
||||
"pin": "73b9d307048fc44d7f21fa3c829fc5a855d144a6"
|
||||
},
|
||||
"exit_code": 0,
|
||||
"measured_fuel": {
|
||||
"available": true,
|
||||
"callbacks": [
|
||||
{
|
||||
"budget": 1000000000,
|
||||
"callback": "command",
|
||||
"calls": 79,
|
||||
"failures": 0,
|
||||
"max_used": 6939810,
|
||||
"mod": "airdef"
|
||||
},
|
||||
{
|
||||
"budget": 10000000,
|
||||
"callback": "frame",
|
||||
"calls": 2202,
|
||||
"failures": 0,
|
||||
"max_used": 77,
|
||||
"mod": "airdef"
|
||||
},
|
||||
{
|
||||
"budget": 300000000,
|
||||
"callback": "tick",
|
||||
"calls": 3302,
|
||||
"failures": 0,
|
||||
"max_used": 182413686,
|
||||
"mod": "airdef"
|
||||
}
|
||||
],
|
||||
"scope": "guest callback fuel; excludes host CPU, memory and GPU time"
|
||||
},
|
||||
"output": " Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.35s\n Running `/private/tmp/issue-122-raid/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod /private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod --fuel-profile budget`\nrunning 1 scripts against /private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod\nfuel airdef command: calls=79 max=6939810 budget=1000000000 failures=0\nfuel airdef frame: calls=2202 max=77 budget=10000000 failures=0\nfuel airdef tick: calls=3302 max=182413686 budget=300000000 failures=0\ntest tests/wasm_budget.toml ... ok (283 steps)\ntest result: ok. 1 passed\n",
|
||||
"runtime_limits": {
|
||||
"fuel_per_call": {
|
||||
"event": 1000000000,
|
||||
"frame": 10000000,
|
||||
"init": 2000000000,
|
||||
"tick": 300000000
|
||||
},
|
||||
"memory_bytes": 67108864,
|
||||
"metering": "source_configured",
|
||||
"source": "horizon/crates/horizon-mods/src/runtime.rs",
|
||||
"wasmtime_component_model": true,
|
||||
"wasmtime_fuel_metering": true
|
||||
},
|
||||
"scenario": "tests/budgets/wasm_flat_budget.toml",
|
||||
"scenario_counts": {
|
||||
"accepted_raids_asserted": 4,
|
||||
"air_defense_units": 68,
|
||||
"frames": 2202,
|
||||
"layout_unit_limit": 2000,
|
||||
"peak_airborne_observed": null,
|
||||
"raid_requests": 2,
|
||||
"raid_units_requested": 80,
|
||||
"scripts": 1,
|
||||
"snapshot_airborne_asserted": 184,
|
||||
"snapshot_tick": 2102,
|
||||
"steps": 283,
|
||||
"ticks": 3302
|
||||
},
|
||||
"scenario_render_world": "flat at y=64",
|
||||
"scenario_sha256": "134cb4667691cf9faa639ed37120941d829cfc13ce45e9638582c409d9e0dd29",
|
||||
"schema": 1,
|
||||
"status": "passed",
|
||||
"wasmtime_version": "48.0.7",
|
||||
"wit_sha256": "dded023a150a5f916bc5d935b7f891806728e0118eb7107ad0551d2aad8c70a5"
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
variant,commit,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,10,500,46,35,11,61,9,781,0,0,0,9,0,21,0,Geran3:3;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,1,10,500,46,37,9,62,9,812,0,0,0,4,1,23,0,Geran3:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,10,500,46,40,6,62,10,875,0,0,0,7,0,16,0,Shahed:1;Kh101:2;Kalibr:2;Iskander:1
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,2,10,500,46,41,5,65,11,883,0,0,0,6,0,20,0,Shahed:1;Kh101:2;Kalibr:1;Iskander:1
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,10,500,46,39,7,56,6,740,0,0,0,4,0,18,0,Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,3,10,500,46,39,7,56,6,740,0,0,0,4,0,18,0,Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,10,500,46,38,8,75,9,919,0,0,0,13,0,24,0,Geran3:1;Kh101:1;Kh22:1;Iskander:3;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,4,10,500,46,34,11,57,8,854,0,0,0,4,0,20,0,Geran3:2;Kh101:3;Kalibr:2;Kh22:1;Iskander:2;Kinzhal:1
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,10,500,46,34,11,66,8,871,0,0,0,12,0,26,0,Geran3:1;Kh101:2;Kh22:2;Zircon:1;Iskander:4;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,5,10,500,46,39,7,67,6,914,0,0,0,7,0,26,0,Kh101:2;Kh22:1;Iskander:3;Kinzhal:1
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,10,500,46,36,10,72,11,986,0,0,0,6,0,30,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,6,10,500,46,36,10,73,11,977,0,0,0,7,0,30,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,10,500,46,35,11,62,6,802,0,0,0,6,0,23,0,Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,7,10,500,46,35,11,63,6,802,0,0,0,7,0,23,0,Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,10,500,46,40,6,62,8,979,0,0,0,6,0,20,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
|
||||
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,8,10,500,46,40,6,61,8,979,0,0,0,3,0,21,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,500,46,41,5,72,13,580,0,0,0,11,0,22,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,500,46,42,4,75,13,578,0,0,0,10,1,22,0,Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,500,46,40,6,81,14,629,0,0,0,10,0,36,0,Kh101:2;Kalibr:1;Zircon:1;Kinzhal:2
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,500,46,41,5,71,15,612,0,0,0,4,0,26,0,Kh101:2;Kalibr:1;Kinzhal:2
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,500,46,42,4,64,13,513,0,0,0,9,0,17,0,Zircon:1;Iskander:3
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,500,46,44,2,68,13,541,0,0,0,6,0,23,0,Zircon:1;Iskander:1
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,500,46,42,4,81,15,581,0,0,0,14,0,28,0,Kh22:1;Iskander:2;Kinzhal:1
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,500,46,42,4,76,15,614,0,0,0,8,0,27,0,Kh22:1;Iskander:2;Kinzhal:1
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,500,46,42,4,71,15,730,0,0,0,7,0,23,0,Kh101:1;Iskander:2;Kinzhal:1
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,500,46,42,4,73,15,748,0,0,0,6,0,25,0,Kh101:1;Iskander:2;Kinzhal:1
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,500,46,41,5,77,14,696,0,0,0,7,0,29,0,Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,500,46,41,5,80,13,681,0,0,0,5,0,34,0,Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,500,46,40,6,68,13,619,0,0,0,6,0,23,0,Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,500,46,40,6,68,13,619,0,0,0,6,0,23,0,Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
|
||||
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,500,46,43,3,70,15,632,0,0,0,10,0,23,0,Zircon:1;Iskander:1;Kinzhal:1
|
||||
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,500,46,42,4,67,14,669,0,0,0,8,0,23,0,Kh101:1;Iskander:2;Kinzhal:1
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,50,500,46,45,1,84,30,394,0,0,0,9,0,31,0,Kh22:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,1,50,500,46,45,1,83,28,418,0,0,0,7,0,32,0,Kh22:1
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,50,500,46,46,0,83,26,575,0,0,0,10,0,31,0,
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,2,50,500,46,46,0,82,28,514,0,0,0,6,0,35,0,
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,50,500,46,46,0,81,27,499,0,0,0,10,0,35,0,
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,3,50,500,46,46,0,77,27,523,0,0,0,3,0,35,0,
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,50,500,46,45,1,84,31,581,0,0,0,14,0,26,0,Iskander:1;Kinzhal:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,4,50,500,46,46,0,82,31,607,0,0,0,7,0,32,0,
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,50,500,46,44,2,82,32,586,0,0,0,8,0,36,0,Zircon:1;Kinzhal:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,5,50,500,46,46,0,87,29,707,0,0,0,10,0,40,0,
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,50,500,46,45,1,82,26,629,0,0,0,9,0,29,0,Kinzhal:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,6,50,500,46,46,0,94,29,584,0,0,0,11,0,39,0,
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,50,500,46,41,5,91,29,573,0,0,0,17,0,34,0,Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,7,50,500,46,42,4,82,31,523,0,0,0,4,0,37,0,Kh101:1;Kh22:1;Zircon:1;Kinzhal:1
|
||||
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,50,500,46,45,1,74,26,677,0,0,0,6,0,30,0,Kinzhal:1
|
||||
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,8,50,500,46,46,0,75,26,695,0,0,0,4,0,33,0,
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,200,46,41,5,75,16,350,0,0,0,2,0,32,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,200,46,41,5,75,16,350,0,0,0,2,0,32,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,200,46,40,5,69,14,383,0,0,1,5,0,25,0,Shahed:1;Kh101:2;Iskander:1;Kinzhal:2
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,200,46,40,5,71,14,401,0,0,1,4,0,29,0,Kh101:2;Iskander:2;Kinzhal:1
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,200,46,39,6,61,14,375,0,0,1,3,0,26,0,Shahed:1;Kh101:2;Iskander:2;Kinzhal:1
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,200,46,39,6,60,12,344,0,0,1,2,0,22,0,Shahed:1;Kh101:2;Iskander:3
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,200,46,40,6,83,15,459,0,0,0,15,0,30,0,Geran3:1;Kh22:2;Zircon:1;Iskander:1;Kinzhal:1
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,200,46,40,6,73,13,495,0,0,0,7,0,26,0,Geran3:1;Kh22:2;Iskander:2;Kinzhal:1
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,200,46,37,9,76,16,406,0,0,0,14,0,33,0,Kh101:1;Kh22:2;Zircon:1;Iskander:3;Kinzhal:2
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,200,46,41,5,71,17,455,0,0,0,2,0,34,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,200,46,39,7,71,13,450,0,0,0,4,0,29,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,200,46,39,7,71,13,450,0,0,0,4,0,29,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,200,46,39,7,77,14,448,0,0,0,9,0,31,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,200,46,40,6,84,14,465,0,0,0,11,0,33,0,Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
|
||||
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,200,46,38,8,70,14,524,0,0,0,10,0,28,0,Kh101:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
|
||||
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,200,46,38,8,67,15,563,0,0,0,4,0,31,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,1500,46,42,4,75,15,2181,0,0,0,9,0,27,0,Kh101:1;Iskander:1;Kinzhal:2
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,1500,46,44,2,68,14,2218,0,0,0,4,0,24,0,Iskander:1;Kinzhal:1
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,1500,46,41,5,72,17,2342,0,0,0,8,0,23,0,Kh101:1;Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,1500,46,43,3,70,20,2342,0,0,0,7,0,20,0,Kh101:1;Kalibr:1;Iskander:1
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,1500,46,43,3,68,19,2385,0,0,0,8,0,19,0,Iskander:2;Kinzhal:1
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,1500,46,44,2,70,20,2363,0,0,0,5,0,21,0,Iskander:2
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,1500,46,41,5,73,16,2388,0,0,0,14,0,22,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,1500,46,42,4,68,16,2387,0,0,0,5,0,25,0,Kh101:1;Kh22:1;Iskander:1;Kinzhal:1
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,1500,46,42,4,75,18,2550,0,0,0,12,0,24,0,Kh101:2;Iskander:1;Kinzhal:1
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,1500,46,42,4,69,19,2635,0,0,0,5,0,23,0,Kh101:2;Iskander:1;Kinzhal:1
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,1500,46,36,10,75,18,2575,0,0,0,3,0,37,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,1500,46,38,8,76,18,2575,0,0,0,2,0,36,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,1500,46,42,4,78,20,2361,0,0,0,10,0,27,0,Kh101:1;Iskander:1;Kinzhal:2
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,1500,46,43,3,73,18,2361,0,0,0,6,0,25,0,Kh101:1;Kalibr:1;Kinzhal:1
|
||||
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,1500,46,41,5,66,19,2544,0,0,0,6,0,23,0,Kh101:1;Iskander:2;Kinzhal:2
|
||||
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,1500,46,42,4,68,20,2544,0,0,0,4,0,26,0,Kh101:1;Iskander:2;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,500,46,41,5,79,14,606,0,0,0,12,0,27,0,Kalibr:1;Kh22:1;Zircon:1;Iskander:2
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,500,46,40,6,73,12,551,0,0,0,8,0,25,0,Geran3:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,500,46,38,8,77,15,651,8,0,0,2,0,30,0,Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,500,46,38,8,81,14,681,7,0,0,3,0,33,0,Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,500,46,44,1,79,12,640,0,1,1,10,0,28,0,Kh101:1;Zircon:1;Iskander:1
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,500,46,44,1,78,13,675,0,0,1,7,0,29,0,Kh101:1;Zircon:1;Iskander:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,500,46,40,6,82,15,492,3,3,0,13,0,25,0,Kh22:1;Iskander:4;Kinzhal:1
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,500,46,42,4,77,15,515,3,2,0,8,0,24,0,Kh22:1;Iskander:3
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,500,46,39,7,69,18,514,0,1,0,8,0,23,0,Kh22:1;Iskander:4;Kinzhal:2
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,500,46,42,4,65,15,469,1,0,0,4,0,22,0,Kh22:1;Iskander:2;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,500,46,43,3,68,13,612,0,0,0,3,0,22,0,Zircon:1;Iskander:1;Kinzhal:1
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,500,46,43,3,68,13,612,0,0,0,3,0,22,0,Zircon:1;Iskander:1;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,500,46,41,5,66,13,554,0,0,0,6,0,19,0,Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,500,46,43,3,64,15,546,0,0,0,5,0,16,0,Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
|
||||
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,500,46,42,4,77,14,712,3,0,0,14,0,20,0,Iskander:2;Kinzhal:2
|
||||
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,500,46,42,4,77,14,712,3,0,0,13,0,20,0,Iskander:2;Kinzhal:2
|
||||
|
@@ -0,0 +1,6 @@
|
||||
running 1 scripts against /tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod
|
||||
fuel airdef command: calls=179 max=32946177 budget=1000000000 failures=0
|
||||
fuel airdef frame: calls=377 max=77 budget=10000000 failures=0
|
||||
fuel airdef tick: calls=3802 max=236581288 budget=300000000 failures=0
|
||||
test tests/wasm_budget.toml ... ok (255 steps)
|
||||
test result: ok. 1 passed
|
||||
@@ -0,0 +1,10 @@
|
||||
=== BEFORE: scaling witness — an 11-drone second order at the same state ===
|
||||
running 1 scripts against /tmp/issue-122-run/airdef-diag-before.hmod
|
||||
fuel airdef command: calls=177 max=247805865 budget=1000000000 failures=0
|
||||
fuel airdef frame: calls=257 max=77 budget=10000000 failures=0
|
||||
fuel airdef tick: calls=2602 max=241372671 budget=300000000 failures=0
|
||||
test tests/wasm_budget.toml ... FAILED
|
||||
step 229 (/airdef wave mix 1 300): feedback
|
||||
expected: Some("PROBE")
|
||||
got: Some("DIAG revealed=13172 known=144 sams=172 alive=144 planning=true queue=0")
|
||||
error: 1 failed, 0 passed
|
||||
@@ -0,0 +1,7 @@
|
||||
=== BEFORE: second order (UI path) traps at the 1e9 event budget ===
|
||||
running 1 scripts against /tmp/issue-122-run/airdef-diag-before.hmod
|
||||
fuel airdef command: calls=177 max=1000000000 budget=1000000000 failures=1
|
||||
fuel airdef frame: calls=257 max=77 budget=10000000 failures=0
|
||||
fuel airdef tick: calls=2602 max=241372671 budget=300000000 failures=0
|
||||
test tests/wasm_budget.toml ... ok (229 steps)
|
||||
test result: ok. 1 passed
|
||||
@@ -0,0 +1,762 @@
|
||||
[[step]]
|
||||
render-ground-y = 64
|
||||
ticks = 2
|
||||
frames = 2
|
||||
expect.commands = ["airdef"]
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
command = "airdef wave mix 10 300"
|
||||
[[step]]
|
||||
ticks = 100
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef stats"
|
||||
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 308, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8156 секций (382 КБ), запросов 16075, неизвестно 0, лучей 87524 (ударов 1830, неизв. 1567), клеток 1318224; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
|
||||
[[step]]
|
||||
command = "airdef wave mix 10 300"
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef stats"
|
||||
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 309, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8557 секций (401 КБ), запросов 16511, неизвестно 0, лучей 89230 (ударов 2855, неизв. 2039), клеток 1326528; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
|
||||
@@ -0,0 +1,688 @@
|
||||
[[step]]
|
||||
render-ground-y = 64
|
||||
ticks = 2
|
||||
frames = 2
|
||||
expect.commands = ["airdef"]
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 0.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 40.0 }
|
||||
command = "airdef deploy ew"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 40.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 80.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 120.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 0.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 40.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 80.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 120.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 160.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 200.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 240.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy s400"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy patriot"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy nasams"
|
||||
[[step]]
|
||||
player = { x = 280.0, z = 160.0 }
|
||||
command = "airdef deploy pantsir"
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
command = "airdef wave mix 10 300"
|
||||
[[step]]
|
||||
ticks = 100
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef ew on"
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
ticks = 50
|
||||
frames = 5
|
||||
[[step]]
|
||||
command = "airdef stats"
|
||||
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 308, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8156 секций (382 КБ), запросов 16075, неизвестно 0, лучей 87524 (ударов 1830, неизв. 1567), клеток 1318224; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
|
||||
[[step]]
|
||||
command = "airdef wave mix 10 300"
|
||||
expect.stopped = "exceeded its execution limit"
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"issue": 122,
|
||||
"kind": "diagnostic_guest_ui_path_comparison_not_exact_user_session",
|
||||
"user_report": {
|
||||
"log": "Horizon: mod airdef stopped in UI event (fuel budget 1000000000, remaining Some(0))",
|
||||
"backtrace": "airdef_core::sim::ew::Sim::known_units <- sim::raid::Sim::order_raid <- airdef::AirDef::launch_wave <- horizon_mod_sdk::Mod::ui_select <- ui-events select",
|
||||
"windows_session_confirmed_same_cause": false
|
||||
},
|
||||
"root_cause": {
|
||||
"what": "order_raid recomputed the planner snapshot known_units() for every drone (choose_target), and known_units() itself rescanned the whole force and the dedup list per intel entry",
|
||||
"growth": "drones x intel_log x force_size per UI event; the intel log holds every launch, EW disclosure, and radar disclosure of the last 6000 ticks",
|
||||
"state_at_trap": {
|
||||
"revealed_entries": 13172,
|
||||
"known_alive_units": 144,
|
||||
"sams_total": 172
|
||||
}
|
||||
},
|
||||
"fix": {
|
||||
"description": "one known_units snapshot per order_raid passed to radar_strikes and choose_target; known_units is a single O(R+S) set pass; price_grid_on reuses its snapshot",
|
||||
"semantics": "identical planner results; native equivalence test against the former predicate; WASM checkpoint /airdef stats byte-identical before/after at tick 2602",
|
||||
"limits_unchanged": true,
|
||||
"wave_size_unrestricted": true,
|
||||
"hd_record_untouched": true
|
||||
},
|
||||
"setup": {
|
||||
"defenses": "40 spread clusters x 4 heavy SAMs + 12 EW = 172, player moved per deploy step",
|
||||
"first_raid": "airdef wave mix 10 (111 drones, Smart, AllSides) via the diagnostic UI-path trigger",
|
||||
"second_raid": "same, at tick ~2600 after the first raid is fought off",
|
||||
"note": "stacked single-point layouts die to one warhead (known=0, cheap order); the trap needs a surviving force, like the user's session"
|
||||
},
|
||||
"before": {
|
||||
"source": "e6a7000 + trigger.patch (diagnostic guest only)",
|
||||
"second_order_111_drones": {
|
||||
"callback": "command (the diagnostic trigger invokes the exact ui_select(BTN_LAUNCH) handler; the UI event and the command share the same 1e9 event budget)",
|
||||
"max_used": 1000000000,
|
||||
"budget": 1000000000,
|
||||
"failures": 1,
|
||||
"mod_stopped": true,
|
||||
"log": "before-trap.txt"
|
||||
},
|
||||
"scaling_witness_11_drones_same_state": {
|
||||
"max_used": 247805865,
|
||||
"budget": 1000000000,
|
||||
"failures": 0,
|
||||
"log": "before-scaling.txt"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"same_scenario_passed": true,
|
||||
"steps": 255,
|
||||
"max_command_fuel": 32946177,
|
||||
"max_tick_fuel": 236581288,
|
||||
"failures": 0,
|
||||
"checkpoint_stats_equal_before_after": true,
|
||||
"log": "after.txt"
|
||||
},
|
||||
"artifacts": {
|
||||
"trigger_patch": "trigger.patch",
|
||||
"scenario_before": "scenario-before.toml",
|
||||
"scenario_after": "scenario-after.toml",
|
||||
"before_guest_sha256": "6d4525cd7aaa61dbf344593f9819be1b61e06654126e9e9088e57967dc657365",
|
||||
"after_guest_sha256": "c4ef7d759524eb053ccd55f0eccdcb49c91954201eb4e0ad923ee9b2828efc4e",
|
||||
"scenario_before_sha256": "398d099275e396deab269601e5adbcf325ab5e0ea6b540c1d03a477d6b0963d1",
|
||||
"scenario_after_sha256": "3bc27338d2e6fb433f027a0cf1afc39ff9a94e1af5840454082af6d8d15aad7c"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs
|
||||
index dc6585eb3..73864e41e 100644
|
||||
--- a/airdef-mod/src/lib.rs
|
||||
+++ b/airdef-mod/src/lib.rs
|
||||
@@ -2351,8 +2351,16 @@ impl Mod for AirDef {
|
||||
.nearest_target(DVec3::new(p.x, p.y, p.z))
|
||||
.unwrap_or(DVec3::new(p.x, p.y, p.z));
|
||||
if *kind == "mix" {
|
||||
- let objects = self.objects(DVec3::new(p.x, p.y, p.z));
|
||||
- self.sim.order_raid(&wave::WaveConfig::mix(count, dist), &objects, &mut out);
|
||||
+ // DIAGNOSTIC ONLY (issue #122): drive the exact UI launch path
|
||||
+ // (Page::WaveGo, BTN_LAUNCH) with the maximum menu composition.
|
||||
+ let mut wave = wave::WaveConfig::default();
|
||||
+ wave.counts = [40; wave::KINDS.len()];
|
||||
+ wave.dist = dist;
|
||||
+ wave.approach = sim::Approach::AllSides;
|
||||
+ wave.aim = sim::Aim::Smart;
|
||||
+ self.wave = wave;
|
||||
+ self.menu = Some(Page::WaveGo);
|
||||
+ self.ui_select(BTN_LAUNCH, 0);
|
||||
} else {
|
||||
let kind = DroneKind::from_key(kind).ok_or(
|
||||
"Тип: shahed, geran3, lancet, gerbera, kh101, kalibr, kh22, zircon, iskander, kinzhal, oreshnik или mix",
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,338 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"world": "EnemyPicture127",
|
||||
"branch": "kimi-work (baseline, before #127 stage 1)",
|
||||
"code_commit": "0b645d77e",
|
||||
"bench": "cargo run --release --example intel_bench (airdef-core, SDK-free)",
|
||||
"scenarios": [
|
||||
"big-smart",
|
||||
"logistics",
|
||||
"ew-adaptive"
|
||||
],
|
||||
"seeds": [
|
||||
1,
|
||||
7,
|
||||
42
|
||||
],
|
||||
"metrics": "completion: raids_ended/raids_ordered, all_ended; losses: sams_lost; exchange: launched/kills/hits/crashes/fired; failure reasons: sim.tally text (Russian, as the tally words them)",
|
||||
"runs": [
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 1,
|
||||
"ticks_run": 1642,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 50,
|
||||
"failures": "5 промахов по взрывателю, 30 ракет остались без цели, 4 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 7,
|
||||
"ticks_run": 1514,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 49,
|
||||
"failures": "2 промахов по взрывателю, 22 ракет остались без цели, 6 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 42,
|
||||
"ticks_run": 1490,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 56,
|
||||
"failures": "5 промахов по взрывателю, 35 ракет остались без цели, 9 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 1,
|
||||
"ticks_run": 1009,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 11,
|
||||
"hits": 8,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 7,
|
||||
"ticks_run": 970,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 12,
|
||||
"hits": 7,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 42,
|
||||
"ticks_run": 1003,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 12,
|
||||
"hits": 8,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 1,
|
||||
"ticks_run": 8661,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 62,
|
||||
"hits": 3,
|
||||
"crashes": 4,
|
||||
"sams_lost": 1,
|
||||
"fired": 82,
|
||||
"failures": "8 промахов по взрывателю, 1 ракет выработали ресурс, 24 ракет остались без цели, 14 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 7,
|
||||
"ticks_run": 8809,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 61,
|
||||
"hits": 5,
|
||||
"crashes": 3,
|
||||
"sams_lost": 4,
|
||||
"fired": 78,
|
||||
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 10 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 42,
|
||||
"ticks_run": 6976,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 61,
|
||||
"hits": 7,
|
||||
"crashes": 1,
|
||||
"sams_lost": 4,
|
||||
"fired": 75,
|
||||
"failures": "8 промахов по взрывателю, 1 ракет выработали ресурс, 25 ракет остались без цели, 10 потерь трека"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"world": "EnemyPicture127",
|
||||
"branch": "agent/issue-127-enemy-picture",
|
||||
"code_commit": "agent/issue-127-enemy-picture (see git log for the exact SHA)",
|
||||
"bench": "cargo run --release --example intel_bench (airdef-core, SDK-free)",
|
||||
"scenarios": [
|
||||
"big-smart",
|
||||
"logistics",
|
||||
"ew-adaptive"
|
||||
],
|
||||
"seeds": [
|
||||
1,
|
||||
7,
|
||||
42
|
||||
],
|
||||
"metrics": "completion: raids_ended/raids_ordered, all_ended; losses: sams_lost; exchange: launched/kills/hits/crashes/fired; failure reasons: sim.tally text (Russian, as the tally words them)",
|
||||
"runs": [
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 1,
|
||||
"ticks_run": 1716,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 49,
|
||||
"failures": "3 промахов по взрывателю, 27 ракет остались без цели, 3 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 7,
|
||||
"ticks_run": 1542,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 48,
|
||||
"failures": "2 промахов по взрывателю, 22 ракет остались без цели, 5 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "big-smart",
|
||||
"seed": 42,
|
||||
"ticks_run": 1433,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 38,
|
||||
"kills": 38,
|
||||
"hits": 0,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 49,
|
||||
"failures": "2 промахов по взрывателю, 27 ракет остались без цели, 7 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 1,
|
||||
"ticks_run": 1009,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 11,
|
||||
"hits": 8,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 7,
|
||||
"ticks_run": 970,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 12,
|
||||
"hits": 7,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "logistics",
|
||||
"seed": 42,
|
||||
"ticks_run": 1003,
|
||||
"raids_ordered": 1,
|
||||
"raids_ended": 1,
|
||||
"all_ended": true,
|
||||
"launched": 27,
|
||||
"kills": 12,
|
||||
"hits": 8,
|
||||
"crashes": 0,
|
||||
"sams_lost": 0,
|
||||
"fired": 18,
|
||||
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 1,
|
||||
"ticks_run": 8084,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 59,
|
||||
"hits": 7,
|
||||
"crashes": 3,
|
||||
"sams_lost": 3,
|
||||
"fired": 69,
|
||||
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 11 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 7,
|
||||
"ticks_run": 8193,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 59,
|
||||
"hits": 7,
|
||||
"crashes": 3,
|
||||
"sams_lost": 3,
|
||||
"fired": 81,
|
||||
"failures": "4 промахов по взрывателю, 3 ракет выработали ресурс, 26 ракет остались без цели, 8 потерь трека"
|
||||
},
|
||||
{
|
||||
"scenario": "ew-adaptive",
|
||||
"seed": 42,
|
||||
"ticks_run": 7916,
|
||||
"raids_ordered": 3,
|
||||
"raids_ended": 3,
|
||||
"all_ended": true,
|
||||
"launched": 69,
|
||||
"kills": 56,
|
||||
"hits": 8,
|
||||
"crashes": 5,
|
||||
"sams_lost": 4,
|
||||
"fired": 69,
|
||||
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 12 потерь трека"
|
||||
}
|
||||
]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user