Finish AirDef catalog, route, stock and observation fixes
build / mod (push) Successful in 30m46s

Refs #91, #114, #118, #135. Show the latest recorded unit decision in the native card (#153).
This commit is contained in:
2026-12-02 18:22:22 +03:00
parent 9e0cec13f2
commit 7612d15963
38 changed files with 942 additions and 737 deletions
+1 -1
View File
@@ -715,7 +715,7 @@ def test_wasm():
BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml"
BUDGET_ASSERTED_SHA256 = "9122cdac879f7db79fe10de3d0bef4646e3d7391e3716f6f46c0c19c07564634"
BUDGET_ASSERTED_SHA256 = "adc10637892159e450458e33b036ccf210ebbf9b7fb05bb3d428d41df5569a8e"
def fuel_measurements(output):
+52 -23
View File
@@ -13,15 +13,38 @@ MUZZLES = {"none", "patriot", "pantsir", "grid", "rails", "cells"}
ENGINES = {"prop": {"type", "back", "size"}, "jet": {"type", "up", "back", "size"},
"rocket": {"type", "back", "size"}}
MODEL = r"airdef:[a-z0-9_]+"
GROUND_STRIKES = {"rm48u_game": ("Rm48uGame", "M48n6")}
# The keys of the existing simulation enums, written once here so the generator and
# Rust keep to one encoding. A new enum variant needs its key added here.
CONFIG_MODES = {"integrated", "launcher"}
CONFIG_ROLES = {"multi", "search", "engagement", "height"}
def load():
def load(specs=None):
"""Project items and deployment identities from their simulation rows."""
data = json.loads(PATH.read_text(encoding="utf-8"))
items = data["items"]
_exact(data, {"items", "variants"}, "content.json")
if specs is None:
specs = json.loads(SPECS.read_text(encoding="utf-8"))
drones = specs["drones"]
slots = sorted(_integer(row["raid_slot"], f"{row['kind']}.raid_slot") for row in drones if row["raid_slot"] is not None)
if slots != list(range(len(slots))):
raise ValueError("raid slots must be unique and contiguous")
ordered = sorted(drones, key=lambda row: row["raid_slot"] if row["raid_slot"] is not None else len(slots))
items = list(data["items"])
for row in [*ordered, *specs["units"]]:
if row["item"] is not None:
items.append(row["item"])
for item in items:
_exact(item, {"id", "title", "color"}, "item")
_text(item["id"], "item.id", r"[a-z0-9_]+")
_text(item["title"], "item.title")
if not isinstance(item["color"], list) or len(item["color"]) != 3 or any(type(c) is not int or not 0 <= c <= 255 for c in item["color"]):
raise ValueError(f"invalid icon color for {item['id']}")
data["items"] = items
data["aircraft"] = [{"kind": row["kind"], "item": row["item"]["id"] if row["item"] else None,
"raid": row["raid_slot"] is not None} for row in ordered]
data["units"] = [{"kind": row["kind"], "item": row["item"]["id"]} for row in specs["units"]]
ids = [item["id"] for item in items]
if len(ids) != len(set(ids)):
raise ValueError("duplicate item ID in content catalog")
@@ -53,9 +76,6 @@ def load():
raise ValueError(f"{where}: variant id collides with an existing identity or kind")
if len({v["id"] for v in data["variants"]}) != len(data["variants"]):
raise ValueError("duplicate variant id in content catalog")
for item in items:
if len(item["color"]) != 3 or any(not isinstance(c, int) or not 0 <= c <= 255 for c in item["color"]):
raise ValueError(f"invalid icon color for {item['id']}")
return data
@@ -189,12 +209,13 @@ def _rest_pitch(entry, where):
def load_specs():
"""Load the numeric profiles shared by Rust and Python, validating every reference."""
return validate_specs(json.loads(SPECS.read_text(encoding="utf-8")), load(),
{entry["event"] for entry in load_sounds()})
data = validate_specs(json.loads(SPECS.read_text(encoding="utf-8")), {entry["event"] for entry in load_sounds()})
load(data)
return data
def validate_specs(data, content, events):
"""Check a specs document against the content identities and registered sound events.
def validate_specs(data, events):
"""Check profile rows and their registered sound events.
Nothing here names a unit or aircraft kind: a new type only needs its catalog entry.
"""
@@ -255,13 +276,13 @@ def validate_specs(data, content, events):
for i, entry in enumerate(data["missiles"]):
where = f"missiles[{i}]"
_exact(entry, {"kind", "model", "speed", "accel", "turn", "boost", "cold", "eject", "eject_drag",
"pk", "fuse", "life", "scale", "flame", "rear", "seeker", "launch_sound", "voice"}, where)
"pk", "fuse", "life", "scale", "flame", "rear", "seeker", "launch_sound", "voice", "launcher_blast"}, where)
kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*")
if kind in missile_kinds:
raise ValueError(f"{where}: duplicate missile kind {kind}")
missile_kinds.add(kind)
_text(entry["model"], f"{where}.model", MODEL)
for field in ("speed", "accel", "turn", "pk", "fuse", "scale", "flame", "rear", "seeker"):
for field in ("speed", "accel", "turn", "pk", "fuse", "scale", "flame", "rear", "seeker", "launcher_blast"):
_number(entry[field], f"{where}.{field}", 0)
_integer(entry["boost"], f"{where}.boost")
_integer(entry["cold"], f"{where}.cold")
@@ -278,8 +299,8 @@ def validate_specs(data, content, events):
keys = set()
for i, entry in enumerate(data["drones"]):
where = f"drones[{i}]"
_exact(entry, {"kind", "key", "name", "model", "speed", "turn", "cruise", "clearance", "dive",
"warhead", "scale", "engine", "decoy", "stealth", "sound", "class", "ballistic",
_exact(entry, {"kind", "key", "name", "item", "raid_slot", "model", "speed", "turn", "cruise", "clearance", "dive",
"warhead", "accuracy", "scale", "engine", "decoy", "stealth", "sound", "class", "ballistic",
"rcs", "launch_sound"}, where)
kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*")
drone_kinds.append(kind)
@@ -292,6 +313,12 @@ def validate_specs(data, content, events):
for field in ("speed", "turn", "cruise", "clearance", "dive", "scale", "stealth", "rcs"):
_number(entry[field], f"{where}.{field}", 0)
_integer(entry["warhead"], f"{where}.warhead")
accuracy = entry["accuracy"]
if not isinstance(accuracy, list) or len(accuracy) != 2:
raise ValueError(f"{where}.accuracy: expected [scatter, large miss probability]")
_number(accuracy[0], f"{where}.accuracy[0]", 0)
if _number(accuracy[1], f"{where}.accuracy[1]", 0) > 1:
raise ValueError(f"{where}.accuracy[1]: probability exceeds one")
if not isinstance(entry["decoy"], bool):
raise ValueError(f"{where}.decoy: expected a boolean")
engine = entry["engine"]
@@ -314,9 +341,12 @@ def validate_specs(data, content, events):
used_missiles = set()
for i, entry in enumerate(data["units"]):
where = f"units[{i}]"
_exact(entry, {"kind", "key", "name", "missile", "gun", "reload", "scale", "rest_pitch",
"roles", "family", "parts", "mount", "pivot", "muzzle", "sensor", "mast"}, where)
profile = {"ground_strike"} if isinstance(entry, dict) and "ground_strike" in entry else set()
_exact(entry, {"kind", "key", "name", "item", "missile", "gun", "reload", "scale", "rest_pitch",
"roles", "family", "parts", "mount", "pivot", "muzzle", "sensor", "mast", "village_cost"} | profile, where)
kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*")
if entry["item"] is None:
raise ValueError(f"{where}.item: deployed units need an item")
unit_kinds.append(kind)
key = _text(entry["key"], f"{where}.key", r"[a-z0-9_]+")
if key in keys:
@@ -324,6 +354,7 @@ def validate_specs(data, content, events):
keys.add(key)
_text(entry["name"], f"{where}.name")
_integer(entry["reload"], f"{where}.reload")
_integer(entry["village_cost"], f"{where}.village_cost", 1)
_number(entry["scale"], f"{where}.scale", 0)
_rest_pitch(entry["rest_pitch"], f"{where}.rest_pitch")
_integer(entry["roles"], f"{where}.roles")
@@ -355,6 +386,10 @@ def validate_specs(data, content, events):
_number(missile["min"], f"{where}.missile.min", 0)
_number(missile["max"], f"{where}.missile.max", 0)
_integer(missile["interval"], f"{where}.missile.interval", 1)
if profile:
name = _text(entry["ground_strike"], f"{where}.ground_strike")
if name not in GROUND_STRIKES or missile is None or missile["kind"] != GROUND_STRIKES[name][1]:
raise ValueError(f"{where}.ground_strike: incompatible shared magazine")
gun = entry["gun"]
if gun is not None:
_exact(gun, {"range", "track", "p", "bursts", "shell", "slew"}, f"{where}.gun")
@@ -366,14 +401,8 @@ def validate_specs(data, content, events):
for j, v in enumerate(gun["slew"]):
_number(v, f"{where}.gun.slew[{j}]", 0)
if set(drone_kinds) != {entry["kind"] for entry in content["aircraft"]}:
raise ValueError("specs.json drones and content.json aircraft disagree")
if len(drone_kinds) != len(content["aircraft"]):
raise ValueError("specs.json drones and content.json aircraft differ in count")
if set(unit_kinds) != {entry["kind"] for entry in content["units"]}:
raise ValueError("specs.json units and content.json units disagree")
if len(unit_kinds) != len(content["units"]):
raise ValueError("specs.json units and content.json units differ in count")
if len(set(drone_kinds)) != len(drone_kinds) or len(set(unit_kinds)) != len(unit_kinds):
raise ValueError("duplicate kind in specs.json")
missing = used_missiles - missile_kinds
if missing:
raise ValueError(f"units reference missiles without a profile: {sorted(missing)}")
+26 -8
View File
@@ -4,7 +4,7 @@ import argparse
from pathlib import Path
import re
from airdef_assets.catalog import load, load_specs, load_sounds
from airdef_assets.catalog import GROUND_STRIKES, load, load_specs, load_sounds
OUTPUT = Path(__file__).resolve().parents[1] / "airdef-mod/src/sim/catalog_entries.rs"
SPEC_OUTPUT = OUTPUT.with_name("specs_generated.rs")
@@ -20,7 +20,7 @@ SOUND_PREFIX = "sound::"
def generate(data):
lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.",
lines = ["// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.",
"pub const AIRCRAFT: &[Aircraft] = &["]
for entry in data["aircraft"]:
kind, item = entry["kind"], entry["item"]
@@ -147,6 +147,7 @@ def drone_profile(entry):
f" clearance: {num(entry['clearance'])},",
f" dive: {num(entry['dive'])},",
f" warhead: {integer(entry['warhead'])},",
f" accuracy: ({num(entry['accuracy'][0])}, {num(entry['accuracy'][1])}),",
f" scale: {num(entry['scale'])},",
f" engine: {motor},",
f" decoy: {str(entry['decoy']).lower()},",
@@ -164,6 +165,7 @@ def missile_profile(entry):
voice = entry["voice"]
lines = [f"const MISSILE_SPEC_{entry['kind'].upper()}: MissileSpec = MissileSpec {{",
f" model: {text(entry['model'])},",
f" launcher_blast: {num(entry['launcher_blast'])},",
f" speed: {num(entry['speed'])},",
f" accel: {num(entry['accel'])},",
f" turn: {num(entry['turn'])},",
@@ -198,10 +200,14 @@ def unit_profile(entry):
gun_expr = (f"Some(GunSpec {{ range: {num(gun['range'])}, track: {num(gun['track'])}, p: {num(gun['p'])}, "
f"bursts: {integer(gun['bursts'])}, shell: {num(gun['shell'])}, "
f"slew: ({num(gun['slew'][0])}, {num(gun['slew'][1])}) }})")
ground = entry.get("ground_strike")
ground_expr = f"Some(catalog::GroundStrike::{GROUND_STRIKES[ground][0]})" if ground is not None else "None"
lines = [f"const UNIT_SPEC_{entry['kind'].upper()}: SamSpec = SamSpec {{",
f" name: {text(entry['name'])},",
f" key: {text(entry['key'])},",
f" village_cost: {integer(entry['village_cost'])},",
f" missile: {missile_expr},",
f" ground_strike: {ground_expr},",
f" gun: {gun_expr},",
f" reload: {integer(entry['reload'])},",
f" scale: {num(entry['scale'])},",
@@ -218,6 +224,11 @@ def unit_profile(entry):
return "\n".join(lines)
def kind_enum(name, entries):
return ["#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]", f"pub enum {name} {{",
*(f" {entry['kind']}," for entry in entries), "}", ""]
def generate_specs(data):
"""The simulation's numeric rows, generated for both the mod and airdef-core."""
shared = data["shared"]
@@ -243,12 +254,15 @@ def generate_specs(data):
f"const TRUCK_LOAD: u32 = {integer(shared['logistics']['truck_load'])};",
f"const STOCK_LIMIT: u32 = {integer(shared['logistics']['stock_limit'])};",
""]
lines += kind_enum("DroneKind", data["drones"])
lines += kind_enum("MissileKind", data["missiles"])
for entry in data["drones"]:
lines += [drone_profile(entry), ""]
for entry in data["missiles"]:
lines += [missile_profile(entry), ""]
lines += ["impl DroneKind {",
" /// Its row of numbers from `catalog/specs.json`.",
lines += ["impl DroneKind {", f" pub const ALL: [DroneKind; {len(data['drones'])}] = ["]
lines += [f" DroneKind::{entry['kind']}," for entry in data["drones"]]
lines += [" ];", "", " /// Its row of numbers from `catalog/specs.json`.",
" pub fn spec(self) -> &'static DroneSpec {",
" match self {"]
for entry in data["drones"]:
@@ -289,10 +303,13 @@ def generate_unit_specs(data):
else:
lines.append(f"const NAMED_{name.upper()}: DVec3 = DVec3::new({', '.join(num(v) for v in value)});")
lines.append("")
lines += kind_enum("SamKind", data["units"])
for entry in data["units"]:
lines += [unit_profile(entry), ""]
lines += ["impl SamKind {",
" /// Its row of numbers from `catalog/specs.json`.",
armed = [entry for entry in data["units"] if entry["gun"] is not None or entry["missile"] is not None]
lines += ["impl SamKind {", f" pub const ARMED: [SamKind; {len(armed)}] = ["]
lines += [f" SamKind::{entry['kind']}," for entry in armed]
lines += [" ];", "", " /// Its row of numbers from `catalog/specs.json`.",
" pub fn spec(self) -> &'static SamSpec {",
" match self {"]
for entry in data["units"]:
@@ -332,11 +349,12 @@ def main():
sound_output = OUTPUT.with_name("catalog_sound_ids.rs")
variant_output = OUTPUT.with_name("unit_variants_generated.rs")
specs = load_specs()
outputs = ((OUTPUT, generate(load())),
content = load(specs)
outputs = ((OUTPUT, generate(content)),
(sound_output, generate_sound_ids(load_sounds())),
(SPEC_OUTPUT, generate_specs(specs)),
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)),
(variant_output, generate_variants(load())))
(variant_output, generate_variants(content)))
for path, generated in outputs:
if args.check:
if not path.exists() or path.read_text(encoding="utf-8") != generated:
+12 -7
View File
@@ -34,17 +34,22 @@ class ContentCatalogTests(unittest.TestCase):
self.assertEqual(language[f"item.airdef.{name}"], title)
self.assertTrue((root / "airdef-mod/data/airdef/horizon/item" / (name + ".json")).is_file())
def test_a_new_unit_kind_needs_only_catalog_entries(self):
# The validator must not carry its own list of kind names: a hypothetical unit is
# accepted from a specs row plus its content entry, with no code change.
def test_a_new_unit_kind_needs_one_catalog_row(self):
from gen_catalog import generate, generate_unit_specs
data = json.loads(json.dumps(catalog.load_specs()))
content = json.loads(json.dumps(catalog.load()))
template = next(entry for entry in data["units"] if entry["gun"] is not None)
added = dict(template, kind="TestGun", key="testgun", name="Test gun")
item = {"id": "deploy_testgun", "title": "Test remote", "color": [42, 42, 42]}
added = dict(template, kind="TestGun", key="testgun", name="Test gun", item=item)
data["units"].append(added)
content["units"].append({"kind": "TestGun", "item": None})
events = {entry["event"] for entry in catalog.load_sounds()}
catalog.validate_specs(data, content, events)
catalog.validate_specs(data, events)
content = catalog.load(data)
self.assertIn(item, content["items"])
self.assertIn('kind: SamKind::TestGun, deploy_item: "airdef:deploy_testgun"', generate(content))
generated = generate_unit_specs(data)
self.assertIn(" TestGun,", generated)
self.assertIn(" SamKind::TestGun,", generated)
class ManifestTests(unittest.TestCase):