Compare commits

...

4 Commits

Author SHA1 Message Date
chexit eea1b3692e Share aircraft and item catalog with asset generation
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit cb73cb7ccc Move world cache report to presentation adapter
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit 375fdf2d80 Separate battery status from player-facing text
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
chexit 63aefc7621 test: record measured callback fuel in budget reports
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 15:55:45 +03:00
19 changed files with 678 additions and 101 deletions
+1
View File
@@ -35,6 +35,7 @@ jobs:
- name: Проверка generated assets
run: |
python3 -m pip install --user -r tools/requirements.txt
python3 tools/gen_catalog.py --check
python3 tools/gen_models.py --check
python3 -m unittest discover -s tools -p test_model_bounds.py
- name: Тесты ядра без SDK
+3 -1
View File
@@ -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;
@@ -229,7 +231,7 @@ pub fn run(sc: &Scenario) -> Report {
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();
+42
View File
@@ -0,0 +1,42 @@
//! Player-facing labels for battery configuration snapshots.
use crate::sim::battery::{BatteryStatus, RadarRole, SamMode};
pub fn radar_role_name(role: RadarRole) -> &'static str {
match role {
RadarRole::Multifunction => "многофункциональная",
RadarRole::Search => "обзорная",
RadarRole::Engagement => "сопровождения",
RadarRole::Height => "мачтовая",
}
}
pub fn status(status: BatteryStatus) -> String {
match status {
BatteryStatus::Radar { index, role, emitting, operational } => format!(
"№{} РЛС: {}, излучение {}, {}", index + 1, radar_role_name(role),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
),
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
if mode == SamMode::LauncherOnly {
if linked { ", РЛС связана" } else { ", нет связанной РЛС сопровождения" }
} else { "" }
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::SamKind;
#[test]
fn renders_battery_status_in_existing_format() {
assert_eq!(status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }), "№1 РЛС: обзорная, излучение выкл, нет связи или РЛС не работает");
assert_eq!(status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }), "№2 РЛС: сопровождения, излучение вкл, работает");
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
}
}
+4 -2
View File
@@ -12,6 +12,7 @@ use horizon_mod_sdk::{
ui::{self, ButtonWidget, ItemWidget, ListWidget, Screen, Widget},
};
mod battery_view;
mod cinema;
mod capabilities;
mod engines;
@@ -29,6 +30,7 @@ mod smoke;
pub use airdef_core::sim;
mod scenario;
mod wave;
mod world_view;
use sim::{Class, DroneKind, Ground, Out, Sam, SamKind, Sim};
const ITEMS: [&str; sim::catalog::INVENTORY_COUNT] = sim::catalog::INVENTORY;
@@ -2301,7 +2303,7 @@ impl Mod for AirDef {
["deploy", kind] => Some(self.deploy_configured(kind)?),
["battery"] => {
let status = self.sim.battery_status();
for line in &status { say(line); }
for entry in status { say(&battery_view::status(entry)); }
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off|multi|search|engagement|height".into())
}
["battery", n, mode] => {
@@ -2545,7 +2547,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()),
};
+1 -1
View File
@@ -2330,7 +2330,7 @@ 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));
lines.push((format!("Роль РЛС: {}", crate::battery_view::radar_role_name(sam.radar_role)), WHITE));
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
}
+32 -7
View File
@@ -33,9 +33,6 @@ 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 name(self) -> &'static str {
match self { Self::Multifunction => "многофункциональная", Self::Search => "обзорная", Self::Engagement => "сопровождения", Self::Height => "мачтовая" }
}
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 } }
}
@@ -68,15 +65,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,6 +91,27 @@ 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 }
}
+2 -31
View File
@@ -52,37 +52,8 @@ 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 },
];
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");
/// Existing positional serialization makes the first entries' order part of the save format.
const fn raid_count() -> usize {
+34
View File
@@ -0,0 +1,34 @@
// 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" },
];
-21
View File
@@ -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]) {
+34
View File
@@ -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");
}
}
+394
View File
@@ -0,0 +1,394 @@
{
"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"
}
],
"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": "mover",
"title": "Пульт перемещения",
"color": [
60,
140,
220
]
},
{
"id": "flare_gun",
"title": "Осветительная ракета",
"color": [
255,
240,
180
]
},
{
"id": "remover",
"title": "Свернуть ПВО",
"color": [
200,
200,
200
]
}
]
}
+7 -1
View File
@@ -118,7 +118,13 @@ API/WIT/артефакт, проверку build identity, сценарий, Was
записываются как failed и дают ненулевой exit code.
Лимиты берутся из исходников: memory 64 MiB; fuel init/tick/frame/event — 2B/300M/10M/1B.
**Фактический расход fuel и peak memory не измеряются этим отчётом.** Сохранённый успешный прогон:
Начиная с продолжения 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; ошибок нет.
Исторический отчёт без измерения fuel:
[API27 budget report с поправкой покрытия](measurements/api27-wasm-budget.json).
Проверены реальный WASM guest с переходами состояний/владельца/мира, сборка клиента и два коротких
+2 -1
View File
@@ -34,6 +34,7 @@
Команды:
- `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow).
- `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.json`; `--check` проверяет актуальность.
- `python3 tools/gen_models.py` — перегенерировать.
- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях.
@@ -52,7 +53,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`.
+20 -2
View File
@@ -161,6 +161,16 @@ BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml"
BUDGET_ASSERTED_SHA256 = "bcc0359289ab20ab3de608bcc130f72d2cf88f9f6fbc470d7b6846e9db5d11df"
def fuel_measurements(output):
"""Read the pinned host's callback counters; never infer them from source caps."""
samples = []
for mod_id, callback, calls, maximum, budget, failures in re.findall(
r"(?m)^fuel (\S+) (\S+): calls=(\d+) max=(\d+) budget=(\d+) failures=(\d+)\s*$", output):
samples.append({"mod": mod_id, "callback": callback, "calls": int(calls),
"max_used": int(maximum), "budget": int(budget), "failures": int(failures)})
return samples
def test_budgets():
"""Run the opt-in heavy scenario and always write a machine-readable report."""
report_path = Path(os.environ.get("AIRDEF_BUDGET_REPORT") or
@@ -178,7 +188,9 @@ def test_budgets():
"accepted_raids_asserted": None, "snapshot_airborne_asserted": None,
"snapshot_tick": None, "peak_airborne_observed": None},
"runtime_limits": {"source": "horizon/crates/horizon-mods/src/runtime.rs",
"metering": "source_configured; measured_per_scenario: unavailable"},
"metering": "source_configured"},
"measured_fuel": {"available": False, "callbacks": [],
"scope": "guest callback fuel; excludes host CPU, memory and GPU time"},
}
def git(*args, text=True):
@@ -253,7 +265,8 @@ def test_budgets():
(isolated / "tests").mkdir()
(isolated / "tests" / "wasm_budget.toml").write_bytes(fixture_bytes)
command = [cargo(), "run", "--locked", "--manifest-path", FORK / "Cargo.toml",
"-p", "cargo-horizon-mod", "--", "horizon-mod", "test", "--hmod", artifact, "budget"]
"-p", "cargo-horizon-mod", "--", "horizon-mod", "test", "--hmod", artifact,
"--fuel-profile", "budget"]
print("+", " ".join(str(c) for c in command), flush=True)
result = subprocess.run([str(c) for c in command], cwd=isolated, env=build_env,
text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
@@ -261,6 +274,11 @@ def test_budgets():
report["exit_code"] = result.returncode
report["status"] = "passed" if result.returncode == 0 else "failed"
report["output"] = result.stdout[-12000:]
samples = fuel_measurements(result.stdout)
report["measured_fuel"].update({"available": bool(samples), "callbacks": samples})
if result.returncode == 0 and not samples:
report["status"] = "failed"
raise RuntimeError("pinned runtime did not return requested callback fuel counters")
# These assertions belong to this exact fixture, not to arbitrary edited scripts.
if result.returncode == 0 and report["scenario_sha256"] == BUDGET_ASSERTED_SHA256:
counts["accepted_raids_asserted"] = 2
+25
View File
@@ -0,0 +1,25 @@
"""Shared content identities and item presentation used by runtime and assets."""
import json
from pathlib import Path
PATH = Path(__file__).resolve().parents[2] / "catalog" / "content.json"
def load():
data = json.loads(PATH.read_text(encoding="utf-8"))
items = data["items"]
ids = [item["id"] for item in items]
if len(ids) != len(set(ids)):
raise ValueError("duplicate item ID in content catalog")
referenced = []
for group in (data["aircraft"], data["units"]):
kinds = [entry["kind"] for entry in group]
if len(kinds) != len(set(kinds)):
raise ValueError("duplicate kind in content catalog")
referenced.extend(entry["item"] for entry in group if entry["item"] is not None)
if len(referenced) != len(set(referenced)) or not set(referenced) <= set(ids):
raise ValueError("duplicate or unregistered content item")
for item in items:
if len(item["color"]) != 3 or any(not isinstance(c, int) or not 0 <= c <= 255 for c in item["color"]):
raise ValueError(f"invalid icon color for {item['id']}")
return data
+4 -32
View File
@@ -6,38 +6,10 @@ from PIL import Image
from .texture_catalog import clamp
# Предметы: (id, название, цвет иконки)
ITEMS = [
("designator", "Целеуказатель", (220, 50, 50)),
("launch_shahed", "Пуск: Шахед-136", (90, 92, 96)),
("launch_geran3", "Пуск: Герань-3", (30, 30, 34)),
("deploy_patriot", "Развернуть Patriot", (76, 86, 58)),
("deploy_gepard", "Развернуть Гепард", (104, 84, 54)),
("deploy_pantsir", "Развернуть Панцирь-С1", (82, 96, 60)),
("deploy_s400", "Развернуть С-400", (60, 80, 50)),
("deploy_s500", "Развернуть С-500", (108, 110, 80)),
("launch_lancet", "Пуск: Ланцет-3", (70, 78, 66)),
("launch_kh101", "Пуск: Х-101", (84, 88, 92)),
("launch_kalibr", "Пуск: Калибр", (150, 154, 156)),
("launch_kh22", "Пуск: Х-22", (226, 228, 222)),
("launch_zircon", "Пуск: Циркон", (52, 54, 52)),
("launch_iskander", "Пуск: Искандер-М", (108, 110, 80)),
("launch_kinzhal", "Пуск: Кинжал", (60, 62, 60)),
("launch_oreshnik", "Пуск: Орешник", (230, 120, 40)),
("deploy_irist", "Развернуть IRIS-T SLM", (76, 86, 58)),
("deploy_nasams", "Развернуть NASAMS", (76, 86, 58)),
("deploy_buk", "Развернуть Бук-М2", (82, 96, 60)),
("deploy_tor", "Развернуть Тор-М2", (108, 110, 80)),
("deploy_p1sun", "Развернуть P1-SUN", (52, 54, 52)),
("deploy_radar", "Развернуть РЛС дальнего обнаружения", (108, 110, 80)),
("deploy_depot", "Развернуть склад боеприпасов", (92, 78, 48)),
("deploy_tzm", "Развернуть ТЗМ", (82, 96, 60)),
("deploy_ew", "Развернуть станцию РЭБ", (108, 110, 80)),
("deploy_light", "Развернуть прожектор", (52, 54, 52)),
("mover", "Пульт перемещения", (60, 140, 220)),
("flare_gun", "Осветительная ракета", (255, 240, 180)),
("remover", "Свернуть ПВО", (200, 200, 200)),
]
# Presentation follows the shared content catalog; order keeps generated assets stable.
from .catalog import load as load_catalog
ITEMS = [(item["id"], item["title"], tuple(item["color"])) for item in load_catalog()["items"]]
# Иконки 16×16 без сглаживания. Каждый предмет рисуется своей функцией: категория задаёт основу
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Generate Rust content entries from the shared catalog; --check detects drift."""
import argparse
from pathlib import Path
import re
from airdef_assets.catalog import load
OUTPUT = Path(__file__).resolve().parents[1] / "airdef-mod/src/sim/catalog_entries.rs"
def generate(data):
lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.",
"pub const AIRCRAFT: &[Aircraft] = &["]
for entry in data["aircraft"]:
kind, item = entry["kind"], entry["item"]
if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", kind):
raise ValueError(f"invalid Rust kind {kind!r}")
if item is not None and not re.fullmatch(r"[a-z0-9_]+", item):
raise ValueError(f"invalid item ID {item!r}")
item_expr = f'Some("airdef:{item}")' if item is not None else "None"
lines.append(f' Aircraft {{ kind: {kind}, launch_item: {item_expr}, raid: {str(entry["raid"]).lower()} }},')
lines += ["];", "", "pub const UNITS: &[Unit] = &["]
for entry in data["units"]:
kind, item = entry["kind"], entry["item"]
if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", kind) or not re.fullmatch(r"[a-z0-9_]+", item):
raise ValueError(f"invalid unit {entry!r}")
lines.append(f' Unit {{ kind: SamKind::{kind}, deploy_item: "airdef:{item}" }},')
return "\n".join(lines + ["];", ""])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
generated = generate(load())
if args.check:
if not OUTPUT.exists() or OUTPUT.read_text(encoding="utf-8") != generated:
parser.exit(1, f"{OUTPUT} is stale; run python3 tools/gen_catalog.py\n")
else:
OUTPUT.write_text(generated, encoding="utf-8")
if __name__ == "__main__":
main()
+16 -2
View File
@@ -114,7 +114,9 @@ class BudgetReportFailureTests(unittest.TestCase):
(self.mod_root / airdef.BUDGET_SCENARIO).write_bytes(source.read_bytes())
def backend(command, cwd, **kwargs):
self.assertEqual((Path(cwd) / "tests/wasm_budget.toml").read_bytes(), source.read_bytes())
return CompletedProcess(args=command, returncode=0, stdout="test passed")
self.assertIn("--fuel-profile", command)
return CompletedProcess(args=command, returncode=0, stdout=(
"test passed\nfuel airdef tick: calls=2102 max=123456 budget=300000000 failures=0\n"))
with mock.patch.object(airdef, "mod"), mock.patch.object(airdef.subprocess, "run", side_effect=backend):
airdef.test_budgets()
report = self.read_report()
@@ -123,6 +125,16 @@ class BudgetReportFailureTests(unittest.TestCase):
counts = report["scenario_counts"]
self.assertEqual((counts["accepted_raids_asserted"], counts["snapshot_airborne_asserted"], counts["snapshot_tick"]), (2, 184, 2102))
self.assertIsNone(counts["peak_airborne_observed"])
self.assertEqual(report["measured_fuel"]["callbacks"], [{
"mod": "airdef", "callback": "tick", "calls": 2102,
"max_used": 123456, "budget": 300000000, "failures": 0}])
def test_success_without_requested_measurements_is_not_a_budget_proof(self):
backend = mock.Mock(return_value=CompletedProcess(args=[], returncode=0, stdout="test passed\n"))
with mock.patch.object(airdef, "mod"), mock.patch.object(airdef.subprocess, "run", backend):
report = self.invoke_and_require_failure()
self.assertFalse(report["measured_fuel"]["available"])
self.assertIn("did not return", report["error"])
def test_early_system_exit_writes_report_and_skips_backend(self):
backend = mock.Mock()
@@ -148,7 +160,8 @@ class BudgetReportFailureTests(unittest.TestCase):
def test_runtime_fuel_trap_persists_nonzero_exit_and_output(self):
backend = mock.Mock(return_value=CompletedProcess(
args=["cargo", "run"], returncode=137, stdout="error: all fuel consumed (fuel trap)\n"
args=["cargo", "run"], returncode=137, stdout=("error: all fuel consumed (fuel trap)\n"
"fuel airdef tick: calls=4 max=300000000 budget=300000000 failures=1\n")
))
with mock.patch.object(airdef, "mod"), \
mock.patch.object(airdef.subprocess, "run", backend):
@@ -157,6 +170,7 @@ class BudgetReportFailureTests(unittest.TestCase):
backend.assert_called_once()
self.assertEqual(report["exit_code"], 137)
self.assertIn("fuel trap", report["output"])
self.assertEqual(report["measured_fuel"]["callbacks"][0]["failures"], 1)
if __name__ == "__main__":
+12
View File
@@ -2,6 +2,8 @@
import hashlib
import importlib.util
import json
import subprocess
import os
import sys
import tempfile
@@ -22,6 +24,16 @@ gen_models = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(gen_models)
class ContentCatalogTests(unittest.TestCase):
def test_catalog_rust_entries_are_current_and_registered_items_match_assets(self):
root = TOOLS.parent
subprocess.run([sys.executable, str(TOOLS / "gen_catalog.py"), "--check"], check=True)
language = json.loads((root / "airdef-mod/assets/airdef/lang/ru_ru.json").read_text(encoding="utf-8"))
for name, title, _ in icons.ITEMS:
self.assertEqual(language[f"item.airdef.{name}"], title)
self.assertTrue((root / "airdef-mod/data/airdef/horizon/item" / (name + ".json")).is_file())
class ManifestTests(unittest.TestCase):
def test_manifest_rejects_traversal_and_duplicate_paths(self):
with tempfile.TemporaryDirectory() as tmp: