feat(m2): content-driven ruleset, balance cli and tuning findings

This commit is contained in:
2026-10-24 22:43:58 +02:00
parent e371c72a35
commit e77595eaf0
18 changed files with 844 additions and 120 deletions
+4
View File
@@ -7,6 +7,10 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach
## [Unreleased] ## [Unreleased]
### Added ### 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** - (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 - (tooling) `tools/device/*` für Steckbrief, Install, Smoke, Perf, Logs
- (m0) Cargo-Workspace mit `sim`, `content`, `ffi`, `server`, `balance`; `tools/ci.sh` - (m0) Cargo-Workspace mit `sim`, `content`, `ffi`, `server`, `balance`; `tools/ci.sh`
Generated
+1
View File
@@ -112,6 +112,7 @@ dependencies = [
name = "sim" name = "sim"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"content",
"serde", "serde",
"serde_json", "serde_json",
] ]
+1 -1
View File
@@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
/// Expected hash for seed 42, recorded on x86_64 host. /// Expected hash for seed 42, recorded on x86_64 host.
/// Must match on arm64 (cross-target determinism, ADR 0002). /// Must match on arm64 (cross-target determinism, ADR 0002).
const hostHash = '11470816335946967992'; const hostHash = '6237310299140737418';
typedef _SelftestC = Uint64 Function(Uint64); typedef _SelftestC = Uint64 Function(Uint64);
typedef _SelftestDart = int Function(int); typedef _SelftestDart = int Function(int);
+3 -3
View File
@@ -4,8 +4,8 @@ version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
authors.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] [dependencies]
serde.workspace = true serde = { workspace = true, default-features = false, features = ["derive", "alloc"] }
serde_json.workspace = true serde_json = { workspace = true, default-features = false, features = ["alloc"] }
+103
View File
@@ -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
}
]
}
+248 -6
View File
@@ -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 //! The JSON file is the single source of truth for balancing. It is embedded at
//! replays stay verifiable (see docs/protocol.md). //! 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. extern crate alloc;
pub fn content_hash_placeholder() -> &'static str {
"b3:uninitialized" 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<Weapon>,
/// All tanks.
pub tanks: Vec<Tank>,
/// All map presets.
pub maps: Vec<MapPreset>,
}
/// 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<Self, ContentError> {
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)));
}
} }
+3 -1
View File
@@ -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`. /// Returns the simulation version as a packed `major*10000 + minor*100 + patch`.
#[no_mangle] #[no_mangle]
pub extern "C" fn iron_arc_sim_version_code() -> u32 { pub extern "C" fn iron_arc_sim_version_code() -> u32 {
let mut parts = sim::SIM_VERSION.split('.').filter_map(|p| p.parse::<u32>().ok()); let mut parts = sim::SIM_VERSION
.split('.')
.filter_map(|p| p.parse::<u32>().ok());
let major = parts.next().unwrap_or(0); let major = parts.next().unwrap_or(0);
let minor = parts.next().unwrap_or(0); let minor = parts.next().unwrap_or(0);
let patch = parts.next().unwrap_or(0); let patch = parts.next().unwrap_or(0);
+1
View File
@@ -14,5 +14,6 @@ default = []
serde = ["dep:serde", "dep:serde_json"] serde = ["dep:serde", "dep:serde_json"]
[dependencies] [dependencies]
content.workspace = true
serde = { workspace = true, optional = true } serde = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true } serde_json = { workspace = true, optional = true }
+5 -1
View File
@@ -23,5 +23,9 @@ fn main() {
sim.tick(); 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()
);
} }
-1
View File
@@ -19,7 +19,6 @@ pub mod rng;
pub mod state; pub mod state;
pub mod terrain; pub mod terrain;
pub mod trig_table; pub mod trig_table;
pub mod weapons;
/// Version of the simulation. Bumped on any formula/balance change. /// Version of the simulation. Bumped on any formula/balance change.
pub const SIM_VERSION: &str = "0.1.0"; pub const SIM_VERSION: &str = "0.1.0";
+12 -4
View File
@@ -102,7 +102,7 @@ pub struct ReplayV1 {
impl ReplayV1 { impl ReplayV1 {
/// Builds a replay from a finished (or in-flight) simulation. /// 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 let commands = sim
.recorded_commands() .recorded_commands()
.iter() .iter()
@@ -129,7 +129,7 @@ impl ReplayV1 {
Self { Self {
v: 1, v: 1,
sim_version: SIM_VERSION.to_string(), sim_version: SIM_VERSION.to_string(),
content_hash: content_hash.to_string(), content_hash: sim.content.hash(),
seed: sim.seed, seed: sim.seed,
mode: mode.to_string(), mode: mode.to_string(),
players, players,
@@ -167,7 +167,15 @@ impl ReplayV1 {
loadout: self.players[1].loadout, 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; let mut projected = 0u8;
for (i, rec) in self.commands.iter().enumerate() { for (i, rec) in self.commands.iter().enumerate() {
@@ -208,7 +216,7 @@ mod tests {
for _ in 0..300 { for _ in 0..300 {
sim.tick(); sim.tick();
} }
ReplayV1::capture(&sim, "b3:test", "hotseat", sim.tick) ReplayV1::capture(&sim, "hotseat", sim.tick)
} }
#[test] #[test]
+40 -10
View File
@@ -6,8 +6,8 @@ use crate::fixed::{self, from_int, from_ratio, mul, to_int, Fx};
use crate::hash::Hasher; use crate::hash::Hasher;
use crate::rng::Pcg32; use crate::rng::Pcg32;
use crate::terrain::{Terrain, WORLD_H, WORLD_W}; use crate::terrain::{Terrain, WORLD_H, WORLD_W};
use crate::weapons;
use crate::TICK_HZ; use crate::TICK_HZ;
use content::Content;
/// Maximum hit points per tank. /// Maximum hit points per tank.
pub const MAX_HP: i32 = 100; pub const MAX_HP: i32 = 100;
@@ -22,7 +22,7 @@ pub const SUDDEN_DEATH_TURN: u16 = 20;
/// Gravity in px/tick^2. /// Gravity in px/tick^2.
pub const GRAVITY: Fx = from_ratio(2, 10); pub const GRAVITY: Fx = from_ratio(2, 10);
/// Wind acceleration per wind unit in px/tick^2. /// 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. /// Muzzle offset above the tank in px.
pub const MUZZLE_LEN: i32 = 16; pub const MUZZLE_LEN: i32 = 16;
/// Shield duration in ticks (2 turns). /// Shield duration in ticks (2 turns).
@@ -114,11 +114,11 @@ pub struct Tank {
} }
impl 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 x = from_int(spec.x);
let mut ammo = [0u8; 3]; let mut ammo = [0u8; 3];
for (i, id) in spec.loadout.iter().enumerate() { 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 { Self {
x, x,
@@ -165,6 +165,10 @@ pub struct Sim {
pub winner: Option<u8>, pub winner: Option<u8>,
pub lava_y: i32, pub lava_y: i32,
pub seed: u64, 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, rng: Pcg32,
log: Vec<(u32, Command)>, log: Vec<(u32, Command)>,
pending_end: bool, pending_end: bool,
@@ -172,11 +176,20 @@ pub struct Sim {
impl Sim { impl Sim {
/// Creates a match. Player 0 starts left, player 1 right. /// 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); let mut terrain = Terrain::generate(seed);
terrain.flatten_under(from_int(specs[0].x), 48); terrain.flatten_under(from_int(specs[0].x), 48);
terrain.flatten_under(from_int(specs[1].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 mut rng = Pcg32::new(seed, 11);
let wind = (rng.below(17) as i32) - 8; let wind = (rng.below(17) as i32) - 8;
Self { Self {
@@ -187,11 +200,13 @@ impl Sim {
tick: 0, tick: 0,
turn: 1, turn: 1,
phase: Phase::Aiming, phase: Phase::Aiming,
current: 0, current: starter % 2,
turn_ticks_left: TURN_TICKS, turn_ticks_left: TURN_TICKS,
winner: None, winner: None,
lava_y: WORLD_H + 200, lava_y: WORLD_H + 200,
seed, seed,
content,
content_hash,
rng, rng,
log: Vec::new(), log: Vec::new(),
pending_end: false, pending_end: false,
@@ -212,6 +227,7 @@ impl Sim {
loadout: [1, 3, 4], loadout: [1, 3, 4],
}, },
], ],
Content::builtin(),
) )
} }
@@ -251,7 +267,11 @@ impl Sim {
if power < from_ratio(5, 100) || power > from_int(1) { if power < from_ratio(5, 100) || power > from_int(1) {
return Err(SimError::BadPower); 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] let slot = self.tanks[self.current as usize]
.slot_of(weapon) .slot_of(weapon)
.ok_or(SimError::WeaponNotInLoadout)?; .ok_or(SimError::WeaponNotInLoadout)?;
@@ -348,7 +368,7 @@ impl Sim {
} }
fn resolve_impact(&mut self, x: Fx, y: Fx, p: &Projectile, events: &mut Vec<Event>) { fn resolve_impact(&mut self, x: Fx, y: Fx, p: &Projectile, events: &mut Vec<Event>) {
let Some(w) = weapons::get(p.weapon) else { let Some(w) = self.content.weapon(p.weapon).cloned() else {
self.end_turn(events); self.end_turn(events);
return; return;
}; };
@@ -364,7 +384,8 @@ impl Sim {
if d >= radius { if d >= radius {
continue; 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; let mut dmg = ((w.damage as i64) * (falloff as i64)) >> 16;
dmg *= multiplier; dmg *= multiplier;
if tank.shield_ticks > 0 { 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 { events.push(Event::Impact {
x, x,
y, y,
@@ -459,6 +488,7 @@ impl Sim {
}); });
h.i32(self.wind); h.i32(self.wind);
h.i32(self.lava_y); h.i32(self.lava_y);
h.u64(self.content_hash);
for tank in &self.tanks { for tank in &self.tanks {
h.i32(tank.x); h.i32(tank.x);
h.i32(tank.y); h.i32(tank.y);
-83
View File
@@ -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)
}
+1 -1
View File
@@ -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` | | 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) | | 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) | | 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 | | 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 | | Property-Tests | `proptest`: HP ∈ [0, 100], Terrain-Samples ∈ [0, Höhe], kein Panzer unter Terrain, Munition ≥ 0, Tick-Monotonie |
+1 -1
View File
@@ -5,7 +5,7 @@
| Stand | 2026-10-24 | | Stand | 2026-10-24 |
| Aufwand | ~6–7 Wochen (solo, mit KI-Unterstützung) | | Aufwand | ~6–7 Wochen (solo, mit KI-Unterstützung) |
| Gerätebedarf | ab M3 (Performance), Pflicht in M6 (Abnahme) | | 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. Jeder Meilenstein hat ein **objektiv prüfbares Gate**. Kein Gate, kein Weiter.
+20 -5
View File
@@ -73,9 +73,24 @@
`BigInt.toUnsigned(64)` formatiert werden, sonst zeigt die UI einen falschen „Mismatch" `BigInt.toUnsigned(64)` formatiert werden, sonst zeigt die UI einen falschen „Mismatch"
(`-6975927737762583624` ist bitgleich mit `11470816335946967992`). (`-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. ## M2 — Content & Balance (erledigt)
2. Waffen aus `weapons.rs` in Content verschieben (Sim bleibt datengetrieben).
3. `tools/balance`: KI-Heuristik + 100k-Matches-CSV. | Ergebnis | Beleg |
4. Danach M3 (Flame-Client) — dafür wird die frb-Integration und das Gerät gebraucht. |---|---|
| `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).
+60
View File
@@ -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
```
+341 -3
View File
@@ -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<String> = 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() { 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!( println!(
"balance: sim_version={} (not implemented yet, M2)", "balance: content={} weapons={} skill={} matches={} seed={}",
sim::SIM_VERSION 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);
} }