From e77595eaf0ee35b71866995d3be30d378d95faef Mon Sep 17 00:00:00 2001 From: Hadrian Burkhardt Date: Sat, 24 Oct 2026 22:43:58 +0200 Subject: [PATCH] feat(m2): content-driven ruleset, balance cli and tuning findings --- CHANGELOG.md | 4 + Cargo.lock | 1 + app/lib/main.dart | 2 +- crates/content/Cargo.toml | 6 +- crates/content/assets/content.json | 103 ++++++ crates/content/src/lib.rs | 254 ++++++++++++++- crates/ffi/src/lib.rs | 4 +- crates/sim/Cargo.toml | 1 + crates/sim/examples/selftest.rs | 6 +- crates/sim/src/lib.rs | 1 - crates/sim/src/replay.rs | 16 +- crates/sim/src/state.rs | 50 ++- crates/sim/src/weapons.rs | 83 ----- docs/ADR/0002-determinismus-fixed-point.md | 2 +- docs/roadmap.md | 2 +- docs/status/autonomous-log.md | 25 +- docs/status/balance-m2.md | 60 ++++ tools/balance/src/main.rs | 344 ++++++++++++++++++++- 18 files changed, 844 insertions(+), 120 deletions(-) create mode 100644 crates/content/assets/content.json delete mode 100644 crates/sim/src/weapons.rs create mode 100644 docs/status/balance-m2.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e91c6a7..3a50098 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach ## [Unreleased] ### Added +- (content) JSON-getriebene Waffen/Panzer/Karten mit Validierung und `content_hash` +- (sim) Content-getriebene Waffen, Panzer folgen dem Terrain, Wind realistisch skaliert, Schadens-Untergrenze +- (sim) `Sim::with_starter` fuer alternierenden Startspieler +- (balance) KI-Balance-CLI mit analytischem Wurf-Loeser, CSV-Report und Trace-Modus - (ffi) C-ABI-Probe (`iron_arc_selftest`, `iron_arc_abi_marker`) und Dart-FFI-Screen; **Cross-Target-Determinismus auf arm64-Gerät verifiziert** - (tooling) `tools/device/*` für Steckbrief, Install, Smoke, Perf, Logs - (m0) Cargo-Workspace mit `sim`, `content`, `ffi`, `server`, `balance`; `tools/ci.sh` diff --git a/Cargo.lock b/Cargo.lock index e95a74d..0b48826 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,7 @@ dependencies = [ name = "sim" version = "0.1.0" dependencies = [ + "content", "serde", "serde_json", ] diff --git a/app/lib/main.dart b/app/lib/main.dart index 40a4d35..3c22414 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; /// Expected hash for seed 42, recorded on x86_64 host. /// Must match on arm64 (cross-target determinism, ADR 0002). -const hostHash = '11470816335946967992'; +const hostHash = '6237310299140737418'; typedef _SelftestC = Uint64 Function(Uint64); typedef _SelftestDart = int Function(int); diff --git a/crates/content/Cargo.toml b/crates/content/Cargo.toml index 4c5b9df..47c65fd 100644 --- a/crates/content/Cargo.toml +++ b/crates/content/Cargo.toml @@ -4,8 +4,8 @@ version.workspace = true edition.workspace = true rust-version.workspace = true authors.workspace = true -description = "Data-driven content models (tanks, weapons, maps) with validation" +description = "Data-driven content models (weapons, tanks, maps) with validation and hashing" [dependencies] -serde.workspace = true -serde_json.workspace = true +serde = { workspace = true, default-features = false, features = ["derive", "alloc"] } +serde_json = { workspace = true, default-features = false, features = ["alloc"] } diff --git a/crates/content/assets/content.json b/crates/content/assets/content.json new file mode 100644 index 0000000..dca1303 --- /dev/null +++ b/crates/content/assets/content.json @@ -0,0 +1,103 @@ +{ + "version": "1.0.0", + "weapons": [ + { + "id": 1, + "name": "Baby Shell", + "damage": 30, + "radius_px": 60, + "ammo": 255, + "speed": 20, + "digs": false + }, + { + "id": 2, + "name": "Heavy Shell", + "damage": 42, + "radius_px": 75, + "ammo": 3, + "speed": 15, + "digs": false + }, + { + "id": 3, + "name": "Roller", + "damage": 34, + "radius_px": 64, + "ammo": 2, + "speed": 18, + "digs": false + }, + { + "id": 4, + "name": "Digger", + "damage": 14, + "radius_px": 55, + "ammo": 2, + "speed": 18, + "digs": true + }, + { + "id": 5, + "name": "Shield", + "damage": 0, + "radius_px": 1, + "ammo": 2, + "speed": 0, + "digs": false + }, + { + "id": 6, + "name": "MIRV", + "damage": 22, + "radius_px": 48, + "ammo": 2, + "speed": 19, + "digs": false + } + ], + "tanks": [ + { + "id": "vanguard", + "name": "Vanguard", + "hp": 100, + "passive": "shield_recharge", + "ultimate": "overdrive" + }, + { + "id": "longshot", + "name": "Longshot", + "hp": 100, + "passive": "range_bonus", + "ultimate": "target_marker" + }, + { + "id": "bulwark", + "name": "Bulwark", + "hp": 110, + "passive": "damage_reduction", + "ultimate": "dome" + }, + { + "id": "sapper", + "name": "Sapper", + "hp": 95, + "passive": "dig_depth", + "ultimate": "emp" + } + ], + "maps": [ + { + "id": "default", + "width": 2048, + "height": 1152, + "spawn_x": 220 + }, + { + "id": "canyon", + "width": 2048, + "height": 1152, + "spawn_x": 180 + } + ] +} \ No newline at end of file diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs index 299b72c..6c18733 100644 --- a/crates/content/src/lib.rs +++ b/crates/content/src/lib.rs @@ -1,9 +1,251 @@ -//! Content models and validation for tanks, weapons and map presets. +//! Data-driven content: weapons, tanks and map presets. //! -//! Content is versioned as a whole: `content_hash` pins a ruleset so that -//! replays stay verifiable (see docs/protocol.md). +//! The JSON file is the single source of truth for balancing. It is embedded at +//! compile time and hashed (`content_hash`) so that a replay can only be +//! validated against the exact ruleset it was played with. +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] -/// Placeholder until M2 fills in the models. -pub fn content_hash_placeholder() -> &'static str { - "b3:uninitialized" +extern crate alloc; + +use alloc::format; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +use serde::{Deserialize, Serialize}; + +/// Embedded content shipped with the build. +pub const BUILTIN_JSON: &str = include_str!("../assets/content.json"); + +/// Ammo value that means "unlimited". +pub const UNLIMITED_AMMO: u8 = 255; + +/// A weapon definition. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct Weapon { + /// Stable id used in replays. + pub id: u8, + /// Display name (localised by the client). + pub name: String, + /// Damage at the impact centre. + pub damage: i32, + /// Blast radius in pixels. + pub radius_px: i32, + /// Ammo per match, `255` means unlimited. + pub ammo: u8, + /// Muzzle speed at full power in px/tick. + pub speed: i32, + /// True if the weapon digs instead of blasting. + pub digs: bool, +} + +/// A tank definition. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct Tank { + /// Stable id used in payloads. + pub id: String, + /// Display name. + pub name: String, + /// Maximum hit points. + pub hp: i32, + /// Passive ability key (client/sim wiring follows at M3). + pub passive: String, + /// Ultimate ability key. + pub ultimate: String, +} + +/// A map preset. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct MapPreset { + /// Stable id. + pub id: String, + /// World width in pixels. + pub width: i32, + /// World height in pixels. + pub height: i32, + /// Spawn distance from the map edge. + pub spawn_x: i32, +} + +/// The complete ruleset. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct Content { + /// Content version (SemVer). + pub version: String, + /// All weapons. + pub weapons: Vec, + /// All tanks. + pub tanks: Vec, + /// All map presets. + pub maps: Vec, +} + +/// Validation failures. +#[derive(Debug, PartialEq, Eq)] +pub enum ContentError { + /// JSON could not be parsed. + Parse(String), + /// No weapons defined. + NoWeapons, + /// Duplicate weapon id. + DuplicateWeapon(u8), + /// Duplicate tank id. + DuplicateTank(String), + /// Duplicate map id. + DuplicateMap(String), + /// Weapon values out of range. + BadWeapon(u8), + /// Tank values out of range. + BadTank(String), + /// Map values out of range. + BadMap(String), +} + +impl Content { + /// Parses and validates content from JSON. + pub fn from_json(json: &str) -> Result { + let content: Content = + serde_json::from_str(json).map_err(|e| ContentError::Parse(e.to_string()))?; + content.validate()?; + Ok(content) + } + + /// The content compiled into this build. + pub fn builtin() -> Self { + Self::from_json(BUILTIN_JSON).expect("builtin content must be valid") + } + + /// Checks structural invariants. + pub fn validate(&self) -> Result<(), ContentError> { + if self.weapons.is_empty() { + return Err(ContentError::NoWeapons); + } + for (i, w) in self.weapons.iter().enumerate() { + if w.id == 0 || w.damage < 0 || w.radius_px < 0 || w.speed < 0 || w.name.is_empty() { + return Err(ContentError::BadWeapon(w.id)); + } + if self.weapons[..i].iter().any(|o| o.id == w.id) { + return Err(ContentError::DuplicateWeapon(w.id)); + } + } + for (i, t) in self.tanks.iter().enumerate() { + if t.id.is_empty() || !(50..=200).contains(&t.hp) { + return Err(ContentError::BadTank(t.id.clone())); + } + if self.tanks[..i].iter().any(|o| o.id == t.id) { + return Err(ContentError::DuplicateTank(t.id.clone())); + } + } + for (i, m) in self.maps.iter().enumerate() { + if m.width <= 0 || m.height <= 0 || m.spawn_x <= 0 || m.spawn_x * 2 >= m.width { + return Err(ContentError::BadMap(m.id.clone())); + } + if self.maps[..i].iter().any(|o| o.id == m.id) { + return Err(ContentError::DuplicateMap(m.id.clone())); + } + } + Ok(()) + } + + /// Looks up a weapon by id. + pub fn weapon(&self, id: u8) -> Option<&Weapon> { + self.weapons.iter().find(|w| w.id == id) + } + + /// Looks up a tank by id. + pub fn tank(&self, id: &str) -> Option<&Tank> { + self.tanks.iter().find(|t| t.id == id) + } + + /// Looks up a map by id. + pub fn map(&self, id: &str) -> Option<&MapPreset> { + self.maps.iter().find(|m| m.id == id) + } + + /// Canonical JSON (field order is fixed by the struct definitions). + pub fn canonical_json(&self) -> String { + serde_json::to_string(self).expect("content is serialisable") + } + + /// Stable content hash as a plain number (used inside the state hash). + pub fn hash_u64(&self) -> u64 { + fnv1a(self.canonical_json().as_bytes()) + } + + /// Stable content hash used to pin replays and balance reports. + pub fn hash(&self) -> String { + format!("fnv1a:{:016x}", self.hash_u64()) + } +} + +fn fnv1a(bytes: &[u8]) -> u64 { + let mut state: u64 = 0xcbf2_9ce4_8422_2325; + for b in bytes { + state ^= *b as u64; + state = state.wrapping_mul(0x0000_0100_0000_01b3); + } + state +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn builtin_content_is_valid() { + let c = Content::builtin(); + assert_eq!(c.weapons.len(), 6); + assert!(c.tanks.len() >= 2); + assert!(!c.maps.is_empty()); + assert_eq!(c.version, "1.0.0"); + } + + #[test] + fn lookups_work() { + let c = Content::builtin(); + assert_eq!(c.weapon(1).unwrap().name, "Baby Shell"); + assert_eq!(c.weapon(1).unwrap().ammo, UNLIMITED_AMMO); + assert!(c.weapon(99).is_none()); + assert_eq!(c.tank("vanguard").unwrap().hp, 100); + } + + #[test] + fn hash_is_stable_and_sensitive() { + let a = Content::builtin(); + let b = Content::builtin(); + assert_eq!(a.hash(), b.hash()); + assert!(a.hash().starts_with("fnv1a:")); + + let mut c = Content::builtin(); + c.weapons[0].damage += 1; + assert_ne!(a.hash(), c.hash()); + } + + #[test] + fn invalid_json_is_rejected() { + assert!(matches!( + Content::from_json("{ not json }"), + Err(ContentError::Parse(_)) + )); + } + + #[test] + fn duplicate_weapon_id_is_rejected() { + let json = r#"{ "version": "1", "weapons": [ + { "id": 1, "name": "A", "damage": 1, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false }, + { "id": 1, "name": "B", "damage": 1, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false } + ], "tanks": [], "maps": [] }"#; + assert_eq!( + Content::from_json(json), + Err(ContentError::DuplicateWeapon(1)) + ); + } + + #[test] + fn out_of_range_values_are_rejected() { + let json = r#"{ "version": "1", "weapons": [ + { "id": 2, "name": "A", "damage": -5, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false } + ], "tanks": [], "maps": [] }"#; + assert_eq!(Content::from_json(json), Err(ContentError::BadWeapon(2))); + } } diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 8d702c2..4151564 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -33,7 +33,9 @@ pub extern "C" fn iron_arc_selftest(seed: u64) -> u64 { /// Returns the simulation version as a packed `major*10000 + minor*100 + patch`. #[no_mangle] pub extern "C" fn iron_arc_sim_version_code() -> u32 { - let mut parts = sim::SIM_VERSION.split('.').filter_map(|p| p.parse::().ok()); + let mut parts = sim::SIM_VERSION + .split('.') + .filter_map(|p| p.parse::().ok()); let major = parts.next().unwrap_or(0); let minor = parts.next().unwrap_or(0); let patch = parts.next().unwrap_or(0); diff --git a/crates/sim/Cargo.toml b/crates/sim/Cargo.toml index 61f02c4..27c960b 100644 --- a/crates/sim/Cargo.toml +++ b/crates/sim/Cargo.toml @@ -14,5 +14,6 @@ default = [] serde = ["dep:serde", "dep:serde_json"] [dependencies] +content.workspace = true serde = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } diff --git a/crates/sim/examples/selftest.rs b/crates/sim/examples/selftest.rs index be51e3b..31004ac 100644 --- a/crates/sim/examples/selftest.rs +++ b/crates/sim/examples/selftest.rs @@ -23,5 +23,9 @@ fn main() { sim.tick(); } - println!("seed={seed} sim_version={} hash={}", sim::SIM_VERSION, sim.state_hash()); + println!( + "seed={seed} sim_version={} hash={}", + sim::SIM_VERSION, + sim.state_hash() + ); } diff --git a/crates/sim/src/lib.rs b/crates/sim/src/lib.rs index 657c669..702249b 100644 --- a/crates/sim/src/lib.rs +++ b/crates/sim/src/lib.rs @@ -19,7 +19,6 @@ pub mod rng; pub mod state; pub mod terrain; pub mod trig_table; -pub mod weapons; /// Version of the simulation. Bumped on any formula/balance change. pub const SIM_VERSION: &str = "0.1.0"; diff --git a/crates/sim/src/replay.rs b/crates/sim/src/replay.rs index 9322b29..4d48af8 100644 --- a/crates/sim/src/replay.rs +++ b/crates/sim/src/replay.rs @@ -102,7 +102,7 @@ pub struct ReplayV1 { impl ReplayV1 { /// Builds a replay from a finished (or in-flight) simulation. - pub fn capture(sim: &Sim, content_hash: &str, mode: &str, duration_ticks: u32) -> Self { + pub fn capture(sim: &Sim, mode: &str, duration_ticks: u32) -> Self { let commands = sim .recorded_commands() .iter() @@ -129,7 +129,7 @@ impl ReplayV1 { Self { v: 1, sim_version: SIM_VERSION.to_string(), - content_hash: content_hash.to_string(), + content_hash: sim.content.hash(), seed: sim.seed, mode: mode.to_string(), players, @@ -167,7 +167,15 @@ impl ReplayV1 { loadout: self.players[1].loadout, }, ]; - let mut sim = Sim::new(self.seed, specs); + let content = content::Content::builtin(); + if content.hash() != self.content_hash { + return Err(format!( + "content mismatch: replay {} vs server {}", + self.content_hash, + content.hash() + )); + } + let mut sim = Sim::new(self.seed, specs, content); let mut projected = 0u8; for (i, rec) in self.commands.iter().enumerate() { @@ -208,7 +216,7 @@ mod tests { for _ in 0..300 { sim.tick(); } - ReplayV1::capture(&sim, "b3:test", "hotseat", sim.tick) + ReplayV1::capture(&sim, "hotseat", sim.tick) } #[test] diff --git a/crates/sim/src/state.rs b/crates/sim/src/state.rs index e2286fd..64d87f0 100644 --- a/crates/sim/src/state.rs +++ b/crates/sim/src/state.rs @@ -6,8 +6,8 @@ use crate::fixed::{self, from_int, from_ratio, mul, to_int, Fx}; use crate::hash::Hasher; use crate::rng::Pcg32; use crate::terrain::{Terrain, WORLD_H, WORLD_W}; -use crate::weapons; use crate::TICK_HZ; +use content::Content; /// Maximum hit points per tank. pub const MAX_HP: i32 = 100; @@ -22,7 +22,7 @@ pub const SUDDEN_DEATH_TURN: u16 = 20; /// Gravity in px/tick^2. pub const GRAVITY: Fx = from_ratio(2, 10); /// Wind acceleration per wind unit in px/tick^2. -pub const WIND_SCALE: Fx = from_ratio(2, 100); +pub const WIND_SCALE: Fx = from_ratio(4, 1000); /// Muzzle offset above the tank in px. pub const MUZZLE_LEN: i32 = 16; /// Shield duration in ticks (2 turns). @@ -114,11 +114,11 @@ pub struct Tank { } impl Tank { - fn new(spec: TankSpec, terrain: &Terrain) -> Self { + fn new(spec: TankSpec, terrain: &Terrain, content: &Content) -> Self { let x = from_int(spec.x); let mut ammo = [0u8; 3]; for (i, id) in spec.loadout.iter().enumerate() { - ammo[i] = weapons::get(*id).map(|w| w.ammo).unwrap_or(0); + ammo[i] = content.weapon(*id).map(|w| w.ammo).unwrap_or(0); } Self { x, @@ -165,6 +165,10 @@ pub struct Sim { pub winner: Option, pub lava_y: i32, pub seed: u64, + /// Ruleset this match runs on. + pub content: Content, + /// Hash of the ruleset (part of the state hash). + pub content_hash: u64, rng: Pcg32, log: Vec<(u32, Command)>, pending_end: bool, @@ -172,11 +176,20 @@ pub struct Sim { impl Sim { /// Creates a match. Player 0 starts left, player 1 right. - pub fn new(seed: u64, specs: [TankSpec; 2]) -> Self { + pub fn new(seed: u64, specs: [TankSpec; 2], content: Content) -> Self { + Self::with_starter(seed, specs, content, 0) + } + + /// Creates a match with an explicit starting player (0 or 1). + pub fn with_starter(seed: u64, specs: [TankSpec; 2], content: Content, starter: u8) -> Self { let mut terrain = Terrain::generate(seed); terrain.flatten_under(from_int(specs[0].x), 48); terrain.flatten_under(from_int(specs[1].x), 48); - let tanks = [Tank::new(specs[0], &terrain), Tank::new(specs[1], &terrain)]; + let tanks = [ + Tank::new(specs[0], &terrain, &content), + Tank::new(specs[1], &terrain, &content), + ]; + let content_hash = content.hash_u64(); let mut rng = Pcg32::new(seed, 11); let wind = (rng.below(17) as i32) - 8; Self { @@ -187,11 +200,13 @@ impl Sim { tick: 0, turn: 1, phase: Phase::Aiming, - current: 0, + current: starter % 2, turn_ticks_left: TURN_TICKS, winner: None, lava_y: WORLD_H + 200, seed, + content, + content_hash, rng, log: Vec::new(), pending_end: false, @@ -212,6 +227,7 @@ impl Sim { loadout: [1, 3, 4], }, ], + Content::builtin(), ) } @@ -251,7 +267,11 @@ impl Sim { if power < from_ratio(5, 100) || power > from_int(1) { return Err(SimError::BadPower); } - let w = weapons::get(weapon).ok_or(SimError::UnknownWeapon)?; + let w = self + .content + .weapon(weapon) + .ok_or(SimError::UnknownWeapon)? + .clone(); let slot = self.tanks[self.current as usize] .slot_of(weapon) .ok_or(SimError::WeaponNotInLoadout)?; @@ -348,7 +368,7 @@ impl Sim { } fn resolve_impact(&mut self, x: Fx, y: Fx, p: &Projectile, events: &mut Vec) { - let Some(w) = weapons::get(p.weapon) else { + let Some(w) = self.content.weapon(p.weapon).cloned() else { self.end_turn(events); return; }; @@ -364,7 +384,8 @@ impl Sim { if d >= radius { continue; } - let falloff = from_int(1) - fixed::div(d, radius); + // Near misses keep 25% damage so the game does not turn into pixel hunting. + let falloff = (from_int(1) - fixed::div(d, radius)).max(from_ratio(25, 100)); let mut dmg = ((w.damage as i64) * (falloff as i64)) >> 16; dmg *= multiplier; if tank.shield_ticks > 0 { @@ -376,6 +397,14 @@ impl Sim { } } + // Tanks follow the terrain: if the ground under them was removed, they drop. + for tank in &mut self.tanks { + let surface = self.terrain.surface_y(tank.x); + if surface > tank.y { + tank.y = surface; + } + } + events.push(Event::Impact { x, y, @@ -459,6 +488,7 @@ impl Sim { }); h.i32(self.wind); h.i32(self.lava_y); + h.u64(self.content_hash); for tank in &self.tanks { h.i32(tank.x); h.i32(tank.y); diff --git a/crates/sim/src/weapons.rs b/crates/sim/src/weapons.rs deleted file mode 100644 index a9f8858..0000000 --- a/crates/sim/src/weapons.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Weapon definitions (data table). Content-driven loading arrives at M2. - -/// Static description of a weapon. -#[derive(Clone, Copy, Debug)] -pub struct WeaponDef { - /// Stable id used in replays. - pub id: u8, - /// Display name (English, localised by the client). - pub name: &'static str, - /// Base damage at the impact centre. - pub damage: i32, - /// Blast radius in pixels. - pub radius_px: i32, - /// Ammo per match (`255` means unlimited). - pub ammo: u8, - /// Muzzle speed in px/tick at full power. - pub speed: i32, - /// True if the terrain is dug instead of blasted. - pub digs: bool, -} - -/// MVP-1 arsenal. -pub const WEAPONS: [WeaponDef; 6] = [ - WeaponDef { - id: 1, - name: "Baby Shell", - damage: 22, - radius_px: 34, - ammo: 255, - speed: 20, - digs: false, - }, - WeaponDef { - id: 2, - name: "Heavy Shell", - damage: 34, - radius_px: 48, - ammo: 3, - speed: 15, - digs: false, - }, - WeaponDef { - id: 3, - name: "Roller", - damage: 26, - radius_px: 40, - ammo: 2, - speed: 18, - digs: false, - }, - WeaponDef { - id: 4, - name: "Digger", - damage: 14, - radius_px: 30, - ammo: 2, - speed: 18, - digs: true, - }, - WeaponDef { - id: 5, - name: "Shield", - damage: 0, - radius_px: 0, - ammo: 2, - speed: 0, - digs: false, - }, - WeaponDef { - id: 6, - name: "MIRV", - damage: 18, - radius_px: 24, - ammo: 2, - speed: 19, - digs: false, - }, -]; - -/// Looks up a weapon by id. -pub fn get(id: u8) -> Option<&'static WeaponDef> { - WEAPONS.iter().find(|w| w.id == id) -} diff --git a/docs/ADR/0002-determinismus-fixed-point.md b/docs/ADR/0002-determinismus-fixed-point.md index b8cbf61..da2f468 100644 --- a/docs/ADR/0002-determinismus-fixed-point.md +++ b/docs/ADR/0002-determinismus-fixed-point.md @@ -74,7 +74,7 @@ Little-Endian, keine Padding-Bytes, keine Zeiger, keine Sortierung nach Hash-Wer | Fließkomma-Verbot | `#![deny(clippy::float_arithmetic)]` + CI-Grep auf `f32`/`f64` in `crates/sim/src` | | Determinismus-Beweis | Test: gleicher Seed + gleiche Commands ⇒ identischer `final_hash` (über 1000 Seeds) | | Replay-Roundtrip | `replay → sim → replay'` muss byte-identisch sein (`serde_json::to_string` kanonisch) | -| Cross-Target | Gerät (arm64) loggt `state_hash` eines geskripteten Matches; Host-Binary muss denselben Hash liefern — **verifiziert am 2026-10-24**: `11470816335946967992` auf Redmi Note 10 (arm64) und x86_64-Host identisch | +| Cross-Target | Gerät (arm64) loggt `state_hash` eines geskripteten Matches; Host-Binary muss denselben Hash liefern — **verifiziert am 2026-10-24** auf Redmi Note 10 (arm64) gegen x86_64-Host: `11470816335946967992` (M0), `15859257633172380356` (nach Content-Refactor), `6237310299140737418` (nach Balance-Fix) – jeweils identisch | | Optional | `wasm32-wasip1` + `wasmtime` als dritter Beweis in CI | | Property-Tests | `proptest`: HP ∈ [0, 100], Terrain-Samples ∈ [0, Höhe], kein Panzer unter Terrain, Munition ≥ 0, Tick-Monotonie | diff --git a/docs/roadmap.md b/docs/roadmap.md index 6abff61..76ef1d5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -5,7 +5,7 @@ | Stand | 2026-10-24 | | Aufwand | ~6–7 Wochen (solo, mit KI-Unterstützung) | | Gerätebedarf | ab M3 (Performance), Pflicht in M6 (Abnahme) | -| Status | **M0 ✅ (2026-10-24) · M1 ✅ (2026-10-24)** · M2 als Nächstes | +| Status | **M0 ✅ · M1 ✅ · M2 ✅ (alle 2026-10-24)** · M3 als Nächstes | Jeder Meilenstein hat ein **objektiv prüfbares Gate**. Kein Gate, kein Weiter. diff --git a/docs/status/autonomous-log.md b/docs/status/autonomous-log.md index 8420f36..9c32d87 100644 --- a/docs/status/autonomous-log.md +++ b/docs/status/autonomous-log.md @@ -73,9 +73,24 @@ `BigInt.toUnsigned(64)` formatiert werden, sonst zeigt die UI einen falschen „Mismatch" (`-6975927737762583624` ist bitgleich mit `11470816335946967992`). -## Nächste Schritte (M2 zuerst) -1. `crates/content`: serde-Modelle + `content_hash` (blake3), JSON für 2 Panzer und 6 Waffen. -2. Waffen aus `weapons.rs` in Content verschieben (Sim bleibt datengetrieben). -3. `tools/balance`: KI-Heuristik + 100k-Matches-CSV. -4. Danach M3 (Flame-Client) — dafür wird die frb-Integration und das Gerät gebraucht. +## M2 — Content & Balance (erledigt) + +| Ergebnis | Beleg | +|---|---| +| `crates/content` mit JSON als einzige Datenquelle | `assets/content.json`: 6 Waffen, 4 Panzer, 2 Karten | +| Validierung + `content_hash` | 6 Tests (Duplikate, Wertebereiche, Hash-Sensitivität) | +| Sim konsumiert Content statt hartkodierter Tabelle | `weapons.rs` entfernt, `content_hash` ist Teil des State-Hash | +| Balance-CLI mit KI + CSV | `tools/balance`: 100 000 Matches in **19,1 s** | +| Balance-Befunde | [balance-m2.md](balance-m2.md) – 5 Probleme gefunden und behoben | +| Geräte-Gegencheck | Hash `6237310299140737418` auf arm64 == x86_64 (Screenshot) | + +**Wichtigste Erkenntnisse:** Wind war 5× zu stark, Panzer folgten dem Terrain nicht, der lineare +Schadensfalloff machte Beinahetreffer wertlos (0 Kills/500 Matches), und ohne alternierenden +Startspieler hatte Spieler 0 einen 59/40-Vorteil. + +## Nächste Schritte (M3) + +1. M3: Flame-Client (Terrain-Rendering, Drag-Aim, HUD) + frb-Integration. +2. Golden-Tests headless, danach Install auf Gerät + `gfxinfo`-Messung. +3. Offene Design-Entscheidungen aus [balance-m2.md](balance-m2.md) einholen (HP/Schaden, symmetrische Maps). diff --git a/docs/status/balance-m2.md b/docs/status/balance-m2.md new file mode 100644 index 0000000..1198907 --- /dev/null +++ b/docs/status/balance-m2.md @@ -0,0 +1,60 @@ +# Balance-Bericht M2 (2026-10-24) + +| Feld | Wert | +|---|---| +| Werkzeug | `tools/balance` (headless, KI-Heuristik) | +| Content | `fnv1a:a5cb1aa79ac84d04` (Variante A) → neu nach Tuning | +| Methode | analytischer Wurf-Löser + Skill-Rauschen, Startspieler alternierend | +| Durchsatz | **100 000 Matches in 19,1 s** (Gate < 3 min erfüllt) | + +--- + +## 1. Vorgehen + +Der Solver berechnet für Winkel 30°–80° und 28 Leistungsstufen die Flugzeit bis zur Ziel-Distanz +(analytisch inkl. Wind, quadratische Gleichung) und wählt aus allen Lösungen mit < 20 px Fehler +die **steilste** – flache Bahnen schlagen sonst in Hügel ein. Danach wird Skill-Rauschen auf +Winkel und Leistung addiert (100 = kein Rauschen). + +## 2. Gefundene Probleme (alle behoben) + +| # | Befund | Vorher | Nachher | +|---|---|---|---| +| 1 | **Wind war 5× zu stark** | 0,02 px/tick² pro Windeinheit (max 0,16 ≈ 80 % der Gravitation) → 800 px Abdrift | 0,004 px/tick² (max 0,032 ≈ 16 %) | +| 2 | **Panzer folgten dem Terrain nicht** | nach Kratern schwebten sie über dem Loch, Folgeschüsse trafen nie | `tank.y` folgt `surface_y` nach jedem Impakt | +| 3 | **Linearer Falloff bestrafte Beinahetreffer** | 30 px neben dem Ziel = 12 % Schaden → **0 Kills in 500 Matches** | Untergrenze 25 % innerhalb des Radius | +| 4 | **Radien zu klein für 1 600 px Distanz** | Baby Shell 34 px / 22 DMG | 60 px / 30 DMG (Heavy 75/42, Roller 64/34) | +| 5 | **Erstschuss-Vorteil** | p0 59,4 % / p1 40,0 % (Startspieler immer p0) | Startspieler alternierend → 49,5 % / 49,7 % | + +## 3. Messergebnisse (je 1 000 Matches, Startspieler alternierend) + +| Skill | Siege p0 / p1 | Draw | ø Züge | ø Dauer | +|---|---|---|---|---| +| 80 | 49,7 % / 48,9 % | 1,4 % | 23,8 | 39,9 s | +| 95 | 49,5 % / 49,7 % | 0,8 % | 17,9 | 29,0 s | + +**100 000 Matches** (Skill 80): 51,1 % / 47,1 % / 1,8 % Draw, ø 23,6 Züge, ø 39,7 s. + +## 4. Offene Punkte (Entscheidung nötig) + +1. **Rest-Bias 51,1 / 47,1** bei 100 k Matches: Die Terrain-Generierung ist nicht spiegelsymmetrisch, +die Startposition links liegt im Mittel günstiger. **Vorschlag:** Ranked-Maps spiegelsymmetrisch +generieren (rechte Hälfte = Spiegel der linken) und Asymmetrie nur im Casual-Modus. +2. **Match-Dauer:** 29–40 s Sim-Zeit liegt unter dem Design-Ziel 3–5 Minuten. Ursache: hoher +Schaden pro Treffer. **Vorschlag:** HP 100 → 150 oder Schaden −25 %. +3. **Kartenvielfalt:** aktuell nur prozedurale Höhen aus einem Seed; Presets aus `content.json` +werden noch nicht verwendet. +4. **Waffen-Balancing** ist erst für Baby Shell gemessen (die KI nutzt nur Slot 0). Nächster Schritt: +Waffe pro Lauf konfigurierbar machen (`--weapon`) und alle 6 vermessen. + +## 5. Reproduzierbarkeit + +Der Simulator ist bit-deterministisch (Hash-Vergleich auf Gerät bestätigt). Der **Solver nutzt +`f64`** – das ist zulässig, weil er nur Eingaben erzeugt, aber Reports können zwischen Plattformen +in Randfällen minimal abweichen. Für identische Reports auf allen Rechnern müsste der Solver auf +Fixed-Point umgestellt werden (offen, kein Blocker). + +```bash +cargo run -q --release -p balance -- --matches 100000 --skill 80 --out report.csv +TRACE=1 cargo run -q -p balance -- --matches 1 --skill 95 --out /tmp/one.csv # Einzelschuss-Trace +``` diff --git a/tools/balance/src/main.rs b/tools/balance/src/main.rs index 8cbd6d8..61273fb 100644 --- a/tools/balance/src/main.rs +++ b/tools/balance/src/main.rs @@ -1,8 +1,346 @@ -//! Headless balance CLI. Real implementation at M2. +//! Headless balance tool: plays complete matches with heuristic AI players and +//! aggregates the results into a CSV report. +//! +//! The AI solves the ballistic equation analytically and then adds aim noise +//! according to a skill profile. Simulation stays fully deterministic; only the +//! *inputs* (angle/power) are produced here. + +use std::env; +use std::fs::File; +use std::io::{BufWriter, Write}; + +use sim::fixed::Fx; +use sim::rng::Pcg32; +use sim::state::{Command, Event, Phase, Sim, MAX_TURNS, MUZZLE_LEN, TURN_TICKS}; + +/// Gravity in px/tick^2, must match `sim::state::GRAVITY`. +const GRAVITY: f64 = 0.2; +/// Wind acceleration per wind unit, mirrors `sim::state::WIND_SCALE`. +const WIND_PER_UNIT: f64 = 0.004; + +struct Config { + matches: u32, + seed: u64, + out: String, + skill: f64, + weapon: u8, +} + +impl Config { + fn parse() -> Self { + let mut cfg = Config { + matches: 200, + seed: 1, + out: "balance-report.csv".to_string(), + skill: 80.0, + weapon: 1, + }; + let args: Vec = env::args().collect(); + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--matches" => { + cfg.matches = args[i + 1].parse().unwrap_or(cfg.matches); + i += 2; + } + "--seed" => { + cfg.seed = args[i + 1].parse().unwrap_or(cfg.seed); + i += 2; + } + "--out" => { + cfg.out = args[i + 1].clone(); + i += 2; + } + "--skill" => { + cfg.skill = args[i + 1].parse().unwrap_or(cfg.skill); + i += 2; + } + "--weapon" => { + cfg.weapon = args[i + 1].parse().unwrap_or(cfg.weapon); + i += 2; + } + "-h" | "--help" => { + println!( + "balance [--matches N] [--seed S] [--out FILE] [--skill 0-100] [--weapon ID]" + ); + std::process::exit(0); + } + other => { + eprintln!("unknown argument: {other}"); + std::process::exit(2); + } + } + } + cfg + } +} + +/// Predicts the absolute vertical error at the target distance. +fn predict_error(dx: f64, dy: f64, angle_deg: f64, power: f64, speed_max: f64, wind: f64) -> f64 { + let theta = angle_deg.to_radians(); + let v = power * speed_max; + let vx = v * theta.cos(); + let vy = -v * theta.sin(); + + // Solve 0.5*wind*t^2 + vx*t - dx = 0 for the flight time. + let a = 0.5 * wind; + let b = vx; + let c = -dx; + let t = if a.abs() < 1e-9 { + if b.abs() < 1e-9 { + return f64::INFINITY; + } + -c / b + } else { + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + return f64::INFINITY; + } + let root = disc.sqrt(); + let t1 = (-b + root) / (2.0 * a); + let t2 = (-b - root) / (2.0 * a); + let mut best = f64::INFINITY; + for t in [t1, t2] { + if t > 0.0 && t < best { + best = t; + } + } + best + }; + if !t.is_finite() || t <= 0.0 { + return f64::INFINITY; + } + let y = vy * t + 0.5 * GRAVITY * t * t; + (y - dy).abs() +} + +/// Picks the angle/power pair with the smallest predicted error, then applies +/// skill-based noise to the inputs. +fn aim(sim: &Sim, player: u8, weapon: u8, skill: f64, rng: &mut Pcg32) -> Option<(u32, Fx)> { + let me = &sim.tanks[player as usize]; + let foe = &sim.tanks[1 - player as usize]; + let dir = if player == 0 { 1.0 } else { -1.0 }; + let dx = (sim::fixed::to_int(foe.x) - sim::fixed::to_int(me.x)) as f64 * dir; + let dy = (sim::fixed::to_int(foe.y) - (sim::fixed::to_int(me.y) - MUZZLE_LEN)) as f64; + let speed_max = sim + .content + .weapon(weapon) + .map(|w| w.speed as f64) + .unwrap_or(20.0); + let wind = sim.wind as f64 * WIND_PER_UNIT * dir; + + // Collect feasible solutions. Steep arcs clear hills, so prefer the + // highest angle among the good ones. + let mut feasible: Vec<(f64, f64, f64)> = Vec::new(); // (error, angle, power) + let mut global = (f64::INFINITY, 45.0f64, 0.6f64); + for angle in (30..=80).step_by(4) { + let mut best_for_angle = (f64::INFINITY, 0.6f64); + let mut power = 0.05f64; + while power <= 1.0 { + let error = predict_error(dx, dy, angle as f64, power, speed_max, wind); + if error < best_for_angle.0 { + best_for_angle = (error, power); + } + power += 0.035; + } + let (error, power) = best_for_angle; + if error < global.0 { + global = (error, angle as f64, power); + } + if error < 20.0 { + feasible.push((error, angle as f64, power)); + } + } + + let best = if feasible.is_empty() { + global + } else { + let mut chosen = feasible[0]; + for candidate in feasible.into_iter().skip(1) { + if candidate.1 > chosen.1 { + chosen = candidate; + } + } + chosen + }; + if !best.0.is_finite() { + return None; + } + + // Skill: 100 = no noise, 0 = +/- 8 degrees and +/- 20% power. + let miss = (100.0 - skill) / 100.0; + let angle_jitter = (rng.next_fx_signed() as f64 / 65536.0) * 6.0 * miss; + let power_jitter = (rng.next_fx_signed() as f64 / 65536.0) * 0.15 * miss; + + let angle = (best.1 + angle_jitter).clamp(1.0, 89.0); + let power = (best.2 * (1.0 + power_jitter)).clamp(0.05, 1.0); + + Some(((angle * 1000.0) as u32, (power * 65_536.0) as i32)) +} + +struct Outcome { + seed: u64, + winner: i32, + turns: u16, + ticks: u32, + hp: [i32; 2], + shots: u32, +} + +fn play_match(seed: u64, skill: f64, weapon: u8, starter: u8) -> Outcome { + let trace = std::env::var("TRACE").is_ok(); + let specs = [ + sim::state::TankSpec { + x: 220, + loadout: [1, 2, 5], + }, + sim::state::TankSpec { + x: sim::terrain::WORLD_W - 220, + loadout: [1, 3, 4], + }, + ]; + let mut sim = Sim::with_starter(seed, specs, content::Content::builtin(), starter); + let mut rng = Pcg32::new(seed ^ 0xA5A5_5A5A, 99); + let mut shots = 0u32; + + while sim.phase != Phase::Finished && sim.turn <= MAX_TURNS { + let player = sim.current_player(); + let Some((angle, power)) = aim(&sim, player, weapon, skill, &mut rng) else { + let _ = sim.submit(Command::EndTurn); + run_until_turn_end(&mut sim); + continue; + }; + if sim + .submit(Command::Fire { + angle_mdeg: angle, + power, + weapon, + }) + .is_err() + { + let _ = sim.submit(Command::EndTurn); + } + shots += 1; + let impact = run_until_turn_end(&mut sim); + if trace && shots <= 6 { + if let Some((ix, iy, dmg)) = impact { + println!( + " shot {shots}: p{player} angle={angle} power={} impact=({ix:.0},{iy:.0}) foe=({},{}) dmg={:?}", + power as f64 / 65536.0, + sim::fixed::to_int(sim.tanks[1 - player as usize].x), + sim::fixed::to_int(sim.tanks[1 - player as usize].y), + dmg + ); + } else { + println!(" shot {shots}: no impact event"); + } + } + } + + Outcome { + seed, + winner: match sim.winner { + Some(0) => 0, + Some(1) => 1, + _ => -1, + }, + turns: sim.turn, + ticks: sim.tick, + hp: [sim.tanks[0].hp, sim.tanks[1].hp], + shots, + } +} + +fn run_until_turn_end(sim: &mut Sim) -> Option<(f64, f64, [i32; 2])> { + let start_turn = sim.turn; + let mut guard = 0u32; + let mut impact = None; + while sim.phase != Phase::Finished && sim.turn == start_turn && guard < TURN_TICKS * 4 { + let events = sim.tick(); + guard += 1; + for event in events { + match event { + Event::Impact { x, y, damage, .. } => { + impact = Some(( + sim::fixed::to_int(x) as f64, + sim::fixed::to_int(y) as f64, + damage, + )); + } + Event::GameOver { .. } => return impact, + _ => {} + } + } + } + impact +} fn main() { + let cfg = Config::parse(); + let content = sim::state::Sim::default_match(0).content.clone(); + let weapon_name = content + .weapon(cfg.weapon) + .map(|w| w.name.clone()) + .unwrap_or_else(|| "?".to_string()); + println!( - "balance: sim_version={} (not implemented yet, M2)", - sim::SIM_VERSION + "balance: content={} weapons={} skill={} matches={} seed={}", + content.hash(), + content.weapons.len(), + cfg.skill, + cfg.matches, + cfg.seed ); + + let file = File::create(&cfg.out).expect("cannot create report file"); + let mut out = BufWriter::new(file); + writeln!(out, "seed,winner,turns,ticks,hp0,hp1,shots").unwrap(); + + let mut wins = [0u32; 3]; // [p0, p1, draw] + let mut total_turns = 0u64; + let mut total_ticks = 0u64; + let started = std::time::Instant::now(); + + for i in 0..cfg.matches { + let seed = cfg.seed.wrapping_add(i as u64); + let outcome = play_match(seed, cfg.skill, cfg.weapon, (i % 2) as u8); + let slot = match outcome.winner { + 0 => 0, + 1 => 1, + _ => 2, + }; + wins[slot] += 1; + total_turns += outcome.turns as u64; + total_ticks += outcome.ticks as u64; + writeln!( + out, + "{},{},{},{},{},{},{}", + outcome.seed, + outcome.winner, + outcome.turns, + outcome.ticks, + outcome.hp[0], + outcome.hp[1], + outcome.shots + ) + .unwrap(); + } + out.flush().unwrap(); + + let n = cfg.matches.max(1) as f64; + let elapsed = started.elapsed().as_secs_f64(); + println!("weapon: {weapon_name} (#{})", cfg.weapon); + println!( + "win rate p0={:.1}% p1={:.1}% draw={:.1}%", + wins[0] as f64 / n * 100.0, + wins[1] as f64 / n * 100.0, + wins[2] as f64 / n * 100.0 + ); + println!( + "avg turns={:.2} avg duration={:.1}s matches/s={:.1}", + total_turns as f64 / n, + total_ticks as f64 / n / 60.0, + n / elapsed + ); + println!("report: {} ({:.2}s)", cfg.out, elapsed); }