b43d471706
build / mod (push) Successful in 3m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
9.9 KiB
Rust
202 lines
9.9 KiB
Rust
//! The text of a saved layout (the autosave, the body of a scenario) read and checked as a whole before
|
|
//! anything of the scene is touched (#86). `Layout::parse` is pure: it either returns every record with its
|
|
//! values proven (finite, in range, within the limits) or the line and field that are wrong; `AirDef` swaps the
|
|
//! scene for it only after that. Lines it doesn't know are skipped, so older and newer files read alike.
|
|
use super::*;
|
|
|
|
/// Most systems and most objects one file may hold.
|
|
pub const MAX_UNITS: usize = 2000;
|
|
/// Largest coordinate: the world's border and then some.
|
|
const COORD: f64 = 3.0e7;
|
|
/// Largest count (missiles, bursts, cargo, reload ticks).
|
|
const COUNT: f64 = 1.0e6;
|
|
|
|
pub struct SamRec {
|
|
pub kind: SamKind,
|
|
pub pos: DVec3,
|
|
pub heading: f64,
|
|
pub roles: Option<u8>,
|
|
pub health: Option<f64>,
|
|
pub cargo: Option<u32>,
|
|
/// Missiles, bursts, empty, reloading: older saves have no ammunition (full).
|
|
pub ammo: Option<(u32, u32, bool, u32)>,
|
|
pub dest: Option<DVec3>,
|
|
/// The parts, from the sensor on; older saves have fewer or none.
|
|
pub comps: Vec<f64>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct Layout {
|
|
pub sams: Vec<SamRec>,
|
|
pub targets: Vec<(DVec3, f64)>,
|
|
pub damage: Option<bool>,
|
|
pub seed: Option<u64>,
|
|
pub wave: Option<Vec<String>>,
|
|
pub far: Option<bool>,
|
|
pub effects: Option<(bool, bool)>,
|
|
pub roles: Vec<(SamKind, u8)>,
|
|
}
|
|
|
|
/// One line's words, with the line number for the messages.
|
|
struct Line<'a> {
|
|
n: usize,
|
|
word: &'a str,
|
|
w: Vec<&'a str>,
|
|
}
|
|
|
|
impl Line<'_> {
|
|
fn bad(&self, field: &str, why: &str) -> String {
|
|
format!("строка {}: «{}», поле {field}: {why}", self.n, self.word)
|
|
}
|
|
/// A finite number in `lo..=hi`; `None` where the field is absent.
|
|
fn num(&self, i: usize, field: &str, lo: f64, hi: f64) -> Result<Option<f64>, String> {
|
|
let Some(v) = self.w.get(i) else { return Ok(None) };
|
|
let x: f64 = v.parse().map_err(|_| self.bad(field, &format!("«{v}» не число")))?;
|
|
if !x.is_finite() {
|
|
return Err(self.bad(field, &format!("«{v}» не конечное число")));
|
|
}
|
|
if x < lo || x > hi {
|
|
return Err(self.bad(field, &format!("{x} вне допустимого {lo}..{hi}")));
|
|
}
|
|
Ok(Some(x))
|
|
}
|
|
fn need(&self, i: usize, field: &str, lo: f64, hi: f64) -> Result<f64, String> {
|
|
self.num(i, field, lo, hi)?.ok_or_else(|| self.bad(field, "строка оборвана"))
|
|
}
|
|
fn flag(&self, i: usize, field: &str) -> Result<Option<bool>, String> {
|
|
match self.w.get(i) {
|
|
None => Ok(None),
|
|
Some(&"true") => Ok(Some(true)),
|
|
Some(&"false") => Ok(Some(false)),
|
|
Some(v) => Err(self.bad(field, &format!("«{v}»: нужно true или false"))),
|
|
}
|
|
}
|
|
fn kind(&self, i: usize) -> Result<SamKind, String> {
|
|
let v = self.w.get(i).ok_or_else(|| self.bad("тип", "строка оборвана"))?;
|
|
SamKind::from_key(v).ok_or_else(|| self.bad("тип", &format!("неизвестный тип «{v}»")))
|
|
}
|
|
fn xyz(&self, i: usize, field: &str) -> Result<DVec3, String> {
|
|
Ok(DVec3::new(self.need(i, field, -COORD, COORD)?, self.need(i + 1, field, -COORD, COORD)?, self.need(i + 2, field, -COORD, COORD)?))
|
|
}
|
|
}
|
|
|
|
impl Layout {
|
|
pub fn parse(text: &str) -> Result<Layout, String> {
|
|
let mut out = Layout::default();
|
|
for (n, raw) in text.lines().enumerate() {
|
|
let w: Vec<&str> = raw.split_whitespace().collect();
|
|
let Some(&word) = w.first() else { continue };
|
|
let l = Line { n: n + 1, word, w };
|
|
match word {
|
|
"sam" => {
|
|
if out.sams.len() >= MAX_UNITS {
|
|
return Err(l.bad("число комплексов", &format!("больше {MAX_UNITS}")));
|
|
}
|
|
let kind = l.kind(1)?;
|
|
let pos = l.xyz(2, "координаты")?;
|
|
let heading = l.need(5, "курс", -1.0e6, 1.0e6)?;
|
|
let roles = l.num(6, "роли", 0.0, 255.0)?.map(|r| r as u8);
|
|
let health = l.num(7, "прочность", 0.0, 1.0)?;
|
|
let cargo = l.num(8, "груз", 0.0, COUNT)?.map(|c| c as u32);
|
|
let ammo = match (l.num(9, "ракеты", 0.0, COUNT)?, l.num(10, "очереди", 0.0, COUNT)?) {
|
|
(Some(m), Some(b)) => Some((m as u32, b as u32, l.num(11, "пуст", 0.0, 1.0)? == Some(1.0), l.num(12, "перезарядка", 0.0, COUNT)?.map_or(0, |r| r as u32))),
|
|
_ => None,
|
|
};
|
|
// "- - -": no destination.
|
|
let dest = if l.w.get(13) == Some(&"-") { None } else if l.w.len() > 13 { Some(l.xyz(13, "цель движения")?) } else { None };
|
|
let mut comps = Vec::new();
|
|
for k in 0..6 {
|
|
match l.num(16 + k, "часть", 0.0, 1.0)? {
|
|
Some(c) => comps.push(c),
|
|
None => break,
|
|
}
|
|
}
|
|
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps });
|
|
}
|
|
"target" => {
|
|
if out.targets.len() >= MAX_UNITS {
|
|
return Err(l.bad("число объектов", &format!("больше {MAX_UNITS}")));
|
|
}
|
|
let pos = l.xyz(1, "координаты")?;
|
|
let hp = l.num(4, "прочность", 0.0, 100.0)?.unwrap_or(100.0);
|
|
out.targets.push((pos, hp));
|
|
}
|
|
"damage" => out.damage = l.flag(1, "значение")?,
|
|
"far" => out.far = l.flag(1, "значение")?,
|
|
"effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))),
|
|
"seed" => {
|
|
let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?;
|
|
out.seed = Some(v.parse::<u64>().map_err(|_| l.bad("значение", &format!("«{v}» не число")))?);
|
|
}
|
|
"wave" => {
|
|
crate::wave::WaveConfig::default().check(&l.w[1..]).map_err(|e| l.bad("налёт", &e))?;
|
|
out.wave = Some(l.w[1..].iter().map(|s| s.to_string()).collect());
|
|
}
|
|
"roles" => {
|
|
let kind = l.kind(1)?;
|
|
out.roles.push((kind, l.need(2, "роли", 0.0, 255.0)? as u8));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn key() -> &'static str {
|
|
SamKind::Patriot.key()
|
|
}
|
|
|
|
// #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line
|
|
#[test]
|
|
fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() {
|
|
let good = format!("sam {} 10 70 20 0.5\ntarget 1 2 3 100\n", key());
|
|
assert!(Layout::parse(&good).is_ok());
|
|
let cases: Vec<(String, usize, &str)> = vec![
|
|
("target NaN inf 0 -100\nsam s400 NaN 70 0 0\n".into(), 1, "координаты"),
|
|
(format!("{good}target 1 inf 3 100\n"), 3, "не конечное"),
|
|
(format!("{good}target 1 2 3 -100\n"), 3, "прочность"),
|
|
(format!("{good}target 1 2 3 NaN\n"), 3, "не конечное"),
|
|
(format!("{good}target 1 2\n"), 3, "оборвана"),
|
|
(format!("{good}sam {} 1 2\n", key()), 3, "оборвана"),
|
|
(format!("{good}sam nosuchkind 1 2 3 0\n"), 3, "тип"),
|
|
(format!("{good}sam {} 1 2 3 0 0 7.5\n", key()), 3, "прочность"),
|
|
(format!("{good}sam {} 1 2 3 0 0 1 0 1 1 0 0 - - - 0.5 abc\n", key()), 3, "часть"),
|
|
(format!("{good}sam {} 1e400 2 3 0\n", key()), 3, "координаты"),
|
|
(format!("{good}seed twelve\n"), 3, "значение"),
|
|
(format!("{good}wave 1,2,x 0 300 0 1\n"), 3, "налёт"),
|
|
(format!("{good}damage maybe\n"), 3, "значение"),
|
|
];
|
|
for (text, line, what) in cases {
|
|
let e = Layout::parse(&text).err().unwrap_or_else(|| panic!("accepted: {text}"));
|
|
assert!(e.contains(&format!("строка {line}")) && e.contains(what), "{e} for {text}");
|
|
}
|
|
let many = "target 0 0 0 100\n".repeat(MAX_UNITS + 1);
|
|
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
|
|
}
|
|
|
|
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
|
|
#[test]
|
|
fn older_valid_saves_still_load() {
|
|
let old = format!(
|
|
"sam {k} 10.5 70 -20 1.57\nsam {k} 1 2 3 0 3 0.8 2\nsam {k} 1 2 3 0 3 0.8 2 4 12 1 30 - - -\nsam {k} 1 2 3 0 3 1 0 4 12 0 0 5 70 5 1 0.9 0.8 0.7 0.6 0.5\ntarget 5 6 7\ntarget 5 6 7 0\ndamage false\nfar true\neffects true false\nroles {k} 3\nfuture-line with words\nscenario 1\nname x\nworld state-0\nseed 123456789\nwave 0,1,0,2,0,0,0,0,0 1 300 0 1\n",
|
|
k = key()
|
|
);
|
|
let l = Layout::parse(&old).expect("an old valid save was refused");
|
|
assert_eq!((l.sams.len(), l.targets.len()), (4, 2));
|
|
assert_eq!(l.targets[0].1, 100.0);
|
|
assert_eq!(l.sams[2].ammo, Some((4, 12, true, 30)));
|
|
assert!(l.sams[2].dest.is_none() && l.sams[3].dest == Some(DVec3::new(5.0, 70.0, 5.0)));
|
|
assert_eq!(l.sams[3].comps.len(), 6);
|
|
assert_eq!((l.damage, l.far, l.effects, l.seed), (Some(false), Some(true), Some((true, false)), Some(123456789)));
|
|
assert_eq!(l.roles.len(), 1);
|
|
// What the build writes now reads back (a wave line from the menu's own text).
|
|
let w = crate::wave::WaveConfig::default().text();
|
|
assert!(Layout::parse(&format!("wave {w}\n")).is_ok(), "{w}");
|
|
}
|
|
}
|