feat(m2): content-driven ruleset, balance cli and tuning findings
This commit is contained in:
+248
-6
@@ -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<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)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user