feat: generate simulation numeric profiles from catalog/specs.json

catalog/specs.json is now the single copy of the numeric rows for
DroneSpec, MissileSpec and SamSpec: speed, guidance, warheads, models'
parts, RCS, seekers, launch and motor sounds, mount drives, gravity,
the Oreshnik split height and logistics limits, plus the named part
sets. tools/gen_catalog.py generates airdef-mod/src/sim/specs_generated.rs
(included by mod.rs, so the mod and airdef-core compile the same rows)
and unit_specs_generated.rs (included by units.rs). The hand-written
spec matches are gone; DroneKind::spec, MissileKind::spec and
SamKind::spec read the generated constants.

load_specs validates the schema, sound references, kind coverage against
content.json, named-part references and unused rows. gen_catalog.py
--check already runs in the CI generated-assets step, so a JSON/Rust
drift fails the build.

Every value was compared with the literals at 632061d field by field.
The only mismatch was the P1-SUN motor voice pitch in JSON (1.6 instead
of the actual 1.7, the flame == 0 branch in voices.rs); the JSON was
corrected and behaviour is unchanged. Save keys, raid order, RNG and
gameplay traces are untouched.

Verified: core release 194 passed + 8 scenarios (7 ignored), adapter
64 unit + 1 boundary + 5 scenarios, WASM contract 27 steps, catalog and
model generators fresh, asset/sound/model-bound/report tests pass.
This commit is contained in:
2026-11-04 20:31:41 +03:00
parent abf3d76fdb
commit ead87343d2
14 changed files with 2476 additions and 815 deletions
+322 -3
View File
@@ -1,8 +1,18 @@
"""Shared content identities and item presentation used by runtime and assets."""
import json
import math
import re
from pathlib import Path
PATH = Path(__file__).resolve().parents[2] / "catalog" / "content.json"
SPECS = PATH.parent / "specs.json"
FAMILIES = {"trainable", "gun", "turret", "vertical", "static", "truck", "light"}
CLASSES = {"drone", "jet", "cruise", "supersonic", "ballistic"}
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_]+"
def load():
@@ -27,8 +37,6 @@ def load():
def load_sounds():
"""Load stable event IDs and engine attenuation metadata."""
import re
entries = json.loads((PATH.parent / "sounds.json").read_text(encoding="utf-8"))
seen = set()
for entry in entries:
@@ -47,6 +55,317 @@ def load_sounds():
return entries
def _exact(entry, keys, where):
if not isinstance(entry, dict) or set(entry) != set(keys):
got = sorted(entry) if isinstance(entry, dict) else type(entry).__name__
raise ValueError(f"{where}: expected keys {sorted(keys)}, got {got}")
def _number(value, where, minimum=None):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValueError(f"{where}: expected a finite number, got {value!r}")
if minimum is not None and value < minimum:
raise ValueError(f"{where}: {value!r} is below {minimum}")
return value
def _integer(value, where, minimum=0):
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
raise ValueError(f"{where}: expected an integer >= {minimum}, got {value!r}")
return value
def _text(value, where, pattern=None):
if not isinstance(value, str) or not value:
raise ValueError(f"{where}: expected a non-empty string")
if pattern and not re.fullmatch(pattern, value):
raise ValueError(f"{where}: {value!r} does not match {pattern}")
return value
def _sound(value, where, events):
_text(value, where, r"[a-z0-9_]+\.[a-z0-9_]+")
if value not in events:
raise ValueError(f"{where}: sound event {value!r} is not registered in sounds.json")
def _named_ref(value, where, named, kind):
_exact(value, {"ref"}, where)
name = value["ref"]
if name not in named or named[name]["kind"] != kind:
raise ValueError(f"{where}: unknown {kind} reference {name!r}")
return name
def _model_ref(value, where, named, kind):
return f"NAMED_{_named_ref(value, where, named, kind).upper()}"
def _parts(entry, where, named):
_exact(entry, {"body", "launcher", "pack", "dish", "fixed", "spinner"}, where)
_text(entry["body"], f"{where}.body", MODEL)
for slot in ("launcher", "pack"):
if entry[slot] is not None:
_text(entry[slot], f"{where}.{slot}", MODEL)
dish = entry["dish"]
if dish is not None:
if not isinstance(dish, list) or len(dish) != 4:
raise ValueError(f"{where}.dish: expected [model, height, forward, tilt]")
_text(dish[0], f"{where}.dish.model", MODEL)
for i, v in enumerate(dish[1:], 1):
_number(v, f"{where}.dish[{i}]")
fixed = entry["fixed"]
if isinstance(fixed, dict):
_named_ref(fixed, f"{where}.fixed", named, "fixed")
elif not isinstance(fixed, list):
raise ValueError(f"{where}.fixed: expected a list or a named reference")
else:
for i, piece in enumerate(fixed):
if not isinstance(piece, list) or len(piece) != 3:
raise ValueError(f"{where}.fixed[{i}]: expected [model, height, back]")
_text(piece[0], f"{where}.fixed[{i}].model", MODEL)
_number(piece[1], f"{where}.fixed[{i}].height")
_number(piece[2], f"{where}.fixed[{i}].back")
spinner = entry["spinner"]
if isinstance(spinner, dict):
_named_ref(spinner, f"{where}.spinner", named, "spinner")
elif spinner is not None:
if not isinstance(spinner, list) or len(spinner) != 5:
raise ValueError(f"{where}.spinner: expected [model, height, back, size, tilt]")
_text(spinner[0], f"{where}.spinner.model", MODEL)
for i, v in enumerate(spinner[1:], 1):
_number(v, f"{where}.spinner[{i}]")
def _muzzle(entry, where):
if not isinstance(entry, dict) or entry.get("type") not in MUZZLES:
raise ValueError(f"{where}: expected one of {sorted(MUZZLES)}")
kind = entry["type"]
keys = {"grid": {"type", "cols", "rows", "size"}, "rails": {"type", "xs"}}.get(kind, {"type"})
_exact(entry, keys, where)
if kind == "grid":
_integer(entry["cols"], f"{where}.cols", 1)
_integer(entry["rows"], f"{where}.rows", 1)
_number(entry["size"], f"{where}.size", 0)
elif kind == "rails":
xs = entry["xs"]
if not isinstance(xs, list) or not xs:
raise ValueError(f"{where}.xs: expected a non-empty list")
for i, v in enumerate(xs):
_number(v, f"{where}.xs[{i}]")
def _rest_pitch(entry, where):
if isinstance(entry, dict):
_exact(entry, {"half_pi"}, where)
_number(entry["half_pi"], f"{where}.half_pi")
else:
_number(entry, where)
def load_specs():
"""Load the numeric profiles shared by Rust and Python, validating every reference."""
data = json.loads(SPECS.read_text(encoding="utf-8"))
_exact(data, {"shared", "drones", "units", "missiles", "named"}, "specs.json")
events = {entry["event"] for entry in load_sounds()}
content = load()
shared = data["shared"]
_exact(shared, {"mobility", "flight", "logistics"}, "shared")
_exact(shared["mobility"], {"drive_scale", "drive_ramp", "trainable", "vertical", "other"}, "shared.mobility")
_number(shared["mobility"]["drive_scale"], "shared.mobility.drive_scale", 0)
_number(shared["mobility"]["drive_ramp"], "shared.mobility.drive_ramp", 0)
for family in ("trainable", "vertical", "other"):
axes = shared["mobility"][family]
if not isinstance(axes, list) or len(axes) != 2:
raise ValueError(f"shared.mobility.{family}: expected [yaw, pitch]")
for i, v in enumerate(axes):
_number(v, f"shared.mobility.{family}[{i}]")
_exact(shared["flight"], {"gravity", "block_split"}, "shared.flight")
_number(shared["flight"]["gravity"], "shared.flight.gravity", 0)
_number(shared["flight"]["block_split"], "shared.flight.block_split", 0)
_exact(shared["logistics"], {"depot_reach", "handover", "truck_load", "stock_limit"}, "shared.logistics")
_number(shared["logistics"]["depot_reach"], "shared.logistics.depot_reach", 0)
_number(shared["logistics"]["handover"], "shared.logistics.handover", 0)
_integer(shared["logistics"]["truck_load"], "shared.logistics.truck_load", 1)
_integer(shared["logistics"]["stock_limit"], "shared.logistics.stock_limit", 1)
named = data["named"]
if not isinstance(named, dict):
raise ValueError("named: expected an object")
referenced = set()
for name, entry in named.items():
where = f"named.{name}"
_exact(entry, {"kind", "value"}, where)
value = entry["value"]
if not isinstance(value, list):
raise ValueError(f"{where}.value: expected a list")
if entry["kind"] == "fixed":
for i, piece in enumerate(value):
if not isinstance(piece, list) or len(piece) != 3:
raise ValueError(f"{where}.value[{i}]: expected [model, height, back]")
_text(piece[0], f"{where}.value[{i}].model", MODEL)
_number(piece[1], f"{where}.value[{i}].height")
_number(piece[2], f"{where}.value[{i}].back")
elif entry["kind"] == "spinner":
if len(value) != 5:
raise ValueError(f"{where}: expected [model, height, back, size, tilt]")
_text(value[0], f"{where}.model", MODEL)
for i, v in enumerate(value[1:], 1):
_number(v, f"{where}[{i}]")
elif entry["kind"] == "pivot":
if len(value) != 3:
raise ValueError(f"{where}: expected [x, y, z]")
for i, v in enumerate(value):
_number(v, f"{where}[{i}]")
else:
raise ValueError(f"{where}.kind: expected fixed, spinner or pivot")
missile_kinds = set()
for i, entry in enumerate(data["missiles"]):
where = f"missiles[{i}]"
_exact(entry, {"kind", "model", "speed", "accel", "turn", "boost", "cold", "pk", "fuse",
"life", "scale", "flame", "rear", "seeker", "launch_sound", "voice"}, 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"):
_number(entry[field], f"{where}.{field}", 0)
_integer(entry["boost"], f"{where}.boost")
_integer(entry["cold"], f"{where}.cold")
_integer(entry["life"], f"{where}.life", 1)
_sound(entry["launch_sound"], f"{where}.launch_sound", events)
_exact(entry["voice"], {"event", "gain", "pitch"}, f"{where}.voice")
_sound(entry["voice"]["event"], f"{where}.voice.event", events)
_number(entry["voice"]["gain"], f"{where}.voice.gain", 0)
_number(entry["voice"]["pitch"], f"{where}.voice.pitch", 0)
drone_kinds = []
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",
"rcs", "launch_sound"}, where)
kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*")
drone_kinds.append(kind)
key = _text(entry["key"], f"{where}.key", r"[a-z0-9_]+")
if key in keys:
raise ValueError(f"{where}: duplicate key {key}")
keys.add(key)
_text(entry["name"], f"{where}.name")
_text(entry["model"], f"{where}.model", MODEL)
for field in ("speed", "turn", "cruise", "clearance", "dive", "scale", "stealth", "rcs"):
_number(entry[field], f"{where}.{field}", 0)
_integer(entry["warhead"], f"{where}.warhead")
if not isinstance(entry["decoy"], bool):
raise ValueError(f"{where}.decoy: expected a boolean")
engine = entry["engine"]
if not isinstance(engine, dict) or engine.get("type") not in ENGINES:
raise ValueError(f"{where}.engine: expected one of {sorted(ENGINES)}")
_exact(engine, ENGINES[engine["type"]], f"{where}.engine")
for field in ENGINES[engine["type"]] - {"type"}:
_number(engine[field], f"{where}.engine.{field}")
_exact(entry["sound"], {"event", "pitch", "interval"}, f"{where}.sound")
_sound(entry["sound"]["event"], f"{where}.sound.event", events)
_number(entry["sound"]["pitch"], f"{where}.sound.pitch", 0)
_integer(entry["sound"]["interval"], f"{where}.sound.interval", 1)
if entry["class"] not in CLASSES:
raise ValueError(f"{where}.class: expected one of {sorted(CLASSES)}")
if entry["ballistic"] is not None:
_number(entry["ballistic"], f"{where}.ballistic", 0)
_sound(entry["launch_sound"], f"{where}.launch_sound", events)
unit_kinds = []
used_missiles = set()
armed = {"Patriot", "Gepard", "Pantsir", "S400", "S500", "IrisT", "Nasams", "Buk", "Tor", "P1sun"}
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)
kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*")
unit_kinds.append(kind)
key = _text(entry["key"], f"{where}.key", r"[a-z0-9_]+")
if key in keys:
raise ValueError(f"{where}: duplicate key {key}")
keys.add(key)
_text(entry["name"], f"{where}.name")
_integer(entry["reload"], f"{where}.reload")
_number(entry["scale"], f"{where}.scale", 0)
_rest_pitch(entry["rest_pitch"], f"{where}.rest_pitch")
_integer(entry["roles"], f"{where}.roles")
if entry["roles"] > 0x1F:
raise ValueError(f"{where}.roles: mask out of range")
if entry["family"] not in FAMILIES:
raise ValueError(f"{where}.family: expected one of {sorted(FAMILIES)}")
_parts(entry["parts"], f"{where}.parts", named)
if not isinstance(entry["mount"], list) or len(entry["mount"]) != 2:
raise ValueError(f"{where}.mount: expected [up, forward]")
for j, v in enumerate(entry["mount"]):
_number(v, f"{where}.mount[{j}]")
pivot = entry["pivot"]
if isinstance(pivot, dict):
_model_ref(pivot, f"{where}.pivot", named, "pivot")
elif not isinstance(pivot, list) or len(pivot) != 3:
raise ValueError(f"{where}.pivot: expected [x, y, z] or a named reference")
else:
for j, v in enumerate(pivot):
_number(v, f"{where}.pivot[{j}]")
_muzzle(entry["muzzle"], f"{where}.muzzle")
_number(entry["sensor"], f"{where}.sensor", 0)
_number(entry["mast"], f"{where}.mast", 0)
missile = entry["missile"]
if missile is not None:
_exact(missile, {"kind", "magazine", "min", "max", "interval"}, f"{where}.missile")
used_missiles.add(_text(missile["kind"], f"{where}.missile.kind", r"[A-Z][A-Za-z0-9]*"))
_integer(missile["magazine"], f"{where}.missile.magazine", 1)
_number(missile["min"], f"{where}.missile.min", 0)
_number(missile["max"], f"{where}.missile.max", 0)
_integer(missile["interval"], f"{where}.missile.interval", 1)
gun = entry["gun"]
if gun is not None:
_exact(gun, {"range", "track", "p", "bursts", "shell", "slew"}, f"{where}.gun")
for field in ("range", "track", "p", "shell"):
_number(gun[field], f"{where}.gun.{field}", 0)
_integer(gun["bursts"], f"{where}.gun.bursts", 1)
if not isinstance(gun["slew"], list) or len(gun["slew"]) != 2:
raise ValueError(f"{where}.gun.slew: expected [yaw, pitch]")
for j, v in enumerate(gun["slew"]):
_number(v, f"{where}.gun.slew[{j}]", 0)
if kind in armed and missile is None and gun is None:
raise ValueError(f"{where}: an armed unit needs missiles or a gun")
if kind not in armed and (missile is not None or gun is not None):
raise ValueError(f"{where}: a support unit has no weapons")
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")
missing = used_missiles - missile_kinds
if missing:
raise ValueError(f"units reference missiles without a profile: {sorted(missing)}")
unused = missile_kinds - used_missiles
if unused:
raise ValueError(f"missile profiles are not carried by any unit: {sorted(unused)}")
for entry in data["units"]:
parts = entry["parts"]
for slot in ("fixed", "spinner"):
if isinstance(parts[slot], dict):
referenced.add(parts[slot]["ref"])
if isinstance(entry["pivot"], dict):
referenced.add(entry["pivot"]["ref"])
idle = set(named) - referenced
if idle:
raise ValueError(f"named part profiles are not referenced: {sorted(idle)}")
return data
def sound_events(entries):
"""Build the Minecraft sound event registry without generating audio."""
events = {}
@@ -56,4 +375,4 @@ def sound_events(entries):
events[event] = {"sounds": [{"name": f"airdef:{name}", "attenuation_distance": distance}]}
if entry["far"]:
events[event + "_far"] = {"sounds": [{"name": f"airdef:{name}_far", "attenuation_distance": int(distance * 1.6)}]}
return events
return events
+268 -2
View File
@@ -4,9 +4,17 @@ import argparse
from pathlib import Path
import re
from airdef_assets.catalog import load, load_sounds
from airdef_assets.catalog import 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")
UNIT_SPEC_OUTPUT = OUTPUT.with_name("unit_specs_generated.rs")
CLASSES = {"drone": "Drone", "jet": "Jet", "cruise": "Cruise", "supersonic": "Supersonic",
"ballistic": "Ballistic"}
FAMILIES = {"trainable": "Trainable", "gun": "Gun", "turret": "Turret", "vertical": "Vertical",
"static": "Static", "truck": "Truck", "light": "Light"}
SOUND_PREFIX = "sound::"
def generate(data):
@@ -40,12 +48,270 @@ def generate_sound_ids(entries):
return "\n".join(lines + [""])
def num(value):
"""A Rust float literal that round-trips the catalog value exactly."""
value = float(value)
text = repr(value)
return text.replace("e+", "e")
def integer(value):
return str(int(value))
def text(value):
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def sound_ref(event):
return SOUND_PREFIX + event.replace(".", "_").upper()
def parts_value(parts, indent):
pad = " " * indent
lines = [pad + "parts: Parts {"]
inner = " " * (indent + 4)
lines.append(f"{inner}body: {text(parts['body'])},")
for slot in ("launcher", "pack"):
value = parts[slot]
lines.append(f"{inner}{slot}: " + (f"Some({text(value)})" if value is not None else "None") + ",")
dish = parts["dish"]
if dish is None:
lines.append(f"{inner}dish: None,")
else:
lines.append(f"{inner}dish: Some(({text(dish[0])}, {', '.join(num(v) for v in dish[1:])})),")
fixed = parts["fixed"]
if isinstance(fixed, dict):
lines.append(f"{inner}fixed: NAMED_{fixed['ref'].upper()},")
else:
pieces = ", ".join(f"({text(piece[0])}, {num(piece[1])}, {num(piece[2])})" for piece in fixed)
lines.append(f"{inner}fixed: &[{pieces}],")
spinner = parts["spinner"]
if isinstance(spinner, dict):
lines.append(f"{inner}spinner: NAMED_{spinner['ref'].upper()},")
elif spinner is None:
lines.append(f"{inner}spinner: None,")
else:
lines.append(f"{inner}spinner: Some(({text(spinner[0])}, {', '.join(num(v) for v in spinner[1:])})),")
lines.append(pad + "},")
return lines
def pivot_value(pivot):
if isinstance(pivot, dict):
return f"NAMED_{pivot['ref'].upper()}"
if all(float(v) == 0.0 for v in pivot):
return "DVec3::ZERO"
return f"DVec3::new({', '.join(num(v) for v in pivot)})"
def muzzle_value(muzzle):
kind = muzzle["type"]
if kind == "grid":
return f"Muzzle::Grid({muzzle['cols']}, {muzzle['rows']}, {num(muzzle['size'])})"
if kind == "rails":
return f"Muzzle::Rails(&[{', '.join(num(v) for v in muzzle['xs'])}])"
return "Muzzle::" + {"none": "None", "patriot": "Patriot", "pantsir": "Pantsir", "cells": "Cells"}[kind]
def rest_pitch_value(pitch):
if isinstance(pitch, dict):
offset = float(pitch["half_pi"])
if offset == 0.0:
return "HALF_PI"
if offset < 0.0:
return f"HALF_PI - {num(-offset)}"
return f"HALF_PI + {num(offset)}"
return num(pitch)
def drone_profile(entry):
engine = entry["engine"]
if engine["type"] == "prop":
motor = f"Engine::Prop({num(engine['back'])}, {num(engine['size'])})"
elif engine["type"] == "jet":
motor = f"Engine::Jet({num(engine['up'])}, {num(engine['back'])}, {num(engine['size'])})"
else:
motor = f"Engine::Rocket({num(engine['back'])}, {num(engine['size'])})"
sound = entry["sound"]
ballistic = "None" if entry["ballistic"] is None else f"Some({num(entry['ballistic'])})"
lines = [f"const DRONE_SPEC_{entry['kind'].upper()}: DroneSpec = DroneSpec {{",
f" name: {text(entry['name'])},",
f" key: {text(entry['key'])},",
f" model: {text(entry['model'])},",
f" speed: {num(entry['speed'])},",
f" turn: {num(entry['turn'])},",
f" cruise: {num(entry['cruise'])},",
f" clearance: {num(entry['clearance'])},",
f" dive: {num(entry['dive'])},",
f" warhead: {integer(entry['warhead'])},",
f" scale: {num(entry['scale'])},",
f" engine: {motor},",
f" decoy: {str(entry['decoy']).lower()},",
f" stealth: {num(entry['stealth'])},",
f" rcs: {num(entry['rcs'])},",
f" sound: ({sound_ref(sound['event'])}, {num(sound['pitch'])}, {integer(sound['interval'])}),",
f" class: Class::{CLASSES[entry['class']]},",
f" ballistic: {ballistic},",
f" launch_sound: {sound_ref(entry['launch_sound'])},",
"};"]
return "\n".join(lines)
def missile_profile(entry):
voice = entry["voice"]
lines = [f"const MISSILE_SPEC_{entry['kind'].upper()}: MissileSpec = MissileSpec {{",
f" model: {text(entry['model'])},",
f" speed: {num(entry['speed'])},",
f" accel: {num(entry['accel'])},",
f" turn: {num(entry['turn'])},",
f" boost: {integer(entry['boost'])},",
f" cold: {integer(entry['cold'])},",
f" pk: {num(entry['pk'])},",
f" fuse: {num(entry['fuse'])},",
f" life: {integer(entry['life'])},",
f" scale: {num(entry['scale'])},",
f" flame: {num(entry['flame'])},",
f" rear: {num(entry['rear'])},",
f" seeker: {num(entry['seeker'])},",
f" launch_sound: {sound_ref(entry['launch_sound'])},",
f" voice: ({sound_ref(voice['event'])}, {num(voice['gain'])}, {num(voice['pitch'])}),",
"};"]
return "\n".join(lines)
def unit_profile(entry):
missile = entry["missile"]
gun = entry["gun"]
if missile is None:
missile_expr = "None"
else:
missile_expr = (f"Some(MissileLoad {{ kind: MissileKind::{missile['kind']}, magazine: {integer(missile['magazine'])}, "
f"min: {num(missile['min'])}, max: {num(missile['max'])}, interval: {integer(missile['interval'])} }})")
if gun is None:
gun_expr = "None"
else:
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])}) }})")
lines = [f"const UNIT_SPEC_{entry['kind'].upper()}: SamSpec = SamSpec {{",
f" name: {text(entry['name'])},",
f" key: {text(entry['key'])},",
f" missile: {missile_expr},",
f" gun: {gun_expr},",
f" reload: {integer(entry['reload'])},",
f" scale: {num(entry['scale'])},",
f" rest_pitch: {rest_pitch_value(entry['rest_pitch'])},",
f" roles: {integer(entry['roles'])},",
f" family: Family::{FAMILIES[entry['family']]},"]
lines += parts_value(entry["parts"], 4)
lines += [f" mount: ({num(entry['mount'][0])}, {num(entry['mount'][1])}),",
f" pivot: {pivot_value(entry['pivot'])},",
f" muzzle: {muzzle_value(entry['muzzle'])},",
f" sensor: {num(entry['sensor'])},",
f" mast: {num(entry['mast'])},",
"};"]
return "\n".join(lines)
def generate_specs(data):
"""The simulation's numeric rows, generated for both the mod and airdef-core."""
shared = data["shared"]
lines = ["// 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.",
f"const DRIVE_SCALE: f64 = {num(shared['mobility']['drive_scale'])};",
"/// Ticks a drive takes to reach its top speed (and to stop from it).",
f"const DRIVE_RAMP: f64 = {num(shared['mobility']['drive_ramp'])};"]
for family in ("trainable", "vertical", "other"):
axes = shared["mobility"][family]
lines.append(f"const DRIVE_{family.upper()}: (f64, f64) = ({num(axes[0])}, {num(axes[1])});")
lines += ["/// Ballistic flight's gravity, blocks a tick².",
f"const GRAVITY: f64 = {num(shared['flight']['gravity'])};",
"/// Height over the target where the Oreshnik's blocks release their submunitions.",
f"const BLOCK_SPLIT: f64 = {num(shared['flight']['block_split'])};",
"/// How near a depot a system reloads straight from it.",
f"const DEPOT_REACH: f64 = {num(shared['logistics']['depot_reach'])};",
"/// How near a truck must come to hand a reload over, or to load up at a depot.",
f"const HANDOVER: f64 = {num(shared['logistics']['handover'])};",
"/// What a truck carries.",
f"const TRUCK_LOAD: u32 = {integer(shared['logistics']['truck_load'])};",
f"const STOCK_LIMIT: u32 = {integer(shared['logistics']['stock_limit'])};",
""]
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`.",
" pub fn spec(self) -> &'static DroneSpec {",
" match self {"]
for entry in data["drones"]:
lines.append(f" DroneKind::{entry['kind']} => &DRONE_SPEC_{entry['kind'].upper()},")
lines += [" }", " }", "}", "",
"impl MissileKind {",
" fn spec(self) -> &'static MissileSpec {",
" match self {"]
for entry in data["missiles"]:
lines.append(f" MissileKind::{entry['kind']} => &MISSILE_SPEC_{entry['kind'].upper()},")
lines += [" }", " }", "}", "",
"/// Save keys by kind; a rename needs an explicit migration.",
"#[cfg(test)]",
f"pub(super) const DRONE_SPEC_KEYS: [(DroneKind, &str); {len(data['drones'])}] = ["]
for entry in data["drones"]:
lines.append(f" (DroneKind::{entry['kind']}, {text(entry['key'])}),")
lines += ["];", "",
"#[cfg(test)]",
f"pub(super) const MISSILE_SPEC_MODELS: [(MissileKind, &str); {len(data['missiles'])}] = ["]
for entry in data["missiles"]:
lines.append(f" (MissileKind::{entry['kind']}, {text(entry['model'])}),")
return "\n".join(lines + ["];", ""])
def generate_unit_specs(data):
"""The deployed units' rows, generated where the unit types live."""
lines = ["// 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.",
""]
for name, entry in data["named"].items():
value = entry["value"]
if entry["kind"] == "fixed":
pieces = ", ".join(f"({text(piece[0])}, {num(piece[1])}, {num(piece[2])})" for piece in value)
lines.append(f"const NAMED_{name.upper()}: &[(&str, f64, f64)] = &[{pieces}];")
elif entry["kind"] == "spinner":
lines.append(f"const NAMED_{name.upper()}: Option<(&str, f64, f64, f64, f64)> = "
f"Some(({text(value[0])}, {', '.join(num(v) for v in value[1:])}));")
else:
lines.append(f"const NAMED_{name.upper()}: DVec3 = DVec3::new({', '.join(num(v) for v in value)});")
lines.append("")
for entry in data["units"]:
lines += [unit_profile(entry), ""]
lines += ["impl SamKind {",
" /// Its row of numbers from `catalog/specs.json`.",
" pub fn spec(self) -> &'static SamSpec {",
" match self {"]
for entry in data["units"]:
lines.append(f" SamKind::{entry['kind']} => &UNIT_SPEC_{entry['kind'].upper()},")
lines += [" }", " }", "}", "",
"/// Save keys by kind; a rename needs an explicit migration.",
"#[cfg(test)]",
f"pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); {len(data['units'])}] = ["]
for entry in data["units"]:
lines.append(f" (SamKind::{entry['kind']}, {text(entry['key'])}),")
return "\n".join(lines + ["];", ""])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
sound_output = OUTPUT.with_name("catalog_sound_ids.rs")
outputs = ((OUTPUT, generate(load())), (sound_output, generate_sound_ids(load_sounds())))
specs = load_specs()
outputs = ((OUTPUT, generate(load())),
(sound_output, generate_sound_ids(load_sounds())),
(SPEC_OUTPUT, generate_specs(specs)),
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)))
for path, generated in outputs:
if args.check:
if not path.exists() or path.read_text(encoding="utf-8") != generated: