Shaders, profiling and the rest of the issues: GTAO and HD GPU pass timing in the fork (patch 15; #9), explosion effects culled early per pixel (#11), a native sim runner with scenario tests run in CI (#8), named scenarios (#17), /airdef why and failure counters in raid reports (#18), IRIS-T and AMRAAM models and launch sounds by kind (#28)
build / mod (push) Successful in 3m24s
build / mod (push) Successful in 3m24s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
//! Named scenarios: a snapshot of the layout (systems, objects), the wave menu's raid and the
|
||||
//! random generator, kept under a name and loaded back later. The body is the autosave's text
|
||||
//! (`state_text`); a header names the format's version and the world it was made in.
|
||||
use super::*;
|
||||
|
||||
/// The format this build writes and reads.
|
||||
const VERSION: u32 = 1;
|
||||
/// Names of the saved scenarios, one a line.
|
||||
const INDEX: &str = "scenarios";
|
||||
|
||||
fn key(name: &str) -> String {
|
||||
format!("scn-{name}")
|
||||
}
|
||||
|
||||
fn valid(name: &str) -> Result<String, String> {
|
||||
let n = name.to_lowercase();
|
||||
if n.is_empty() || n.len() > 32 || !n.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
return Err("Имя сценария: до 32 символов, латиница, цифры, - и _".into());
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn names() -> Vec<String> {
|
||||
storage::get(INDEX).map(|b| String::from_utf8_lossy(&b).lines().map(str::to_string).filter(|l| !l.is_empty()).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
impl AirDef {
|
||||
/// The scenario as text.
|
||||
fn scenario_text(&self, name: &str, fresh: bool) -> String {
|
||||
let mut text = format!("scenario {VERSION}\nname {name}\nworld {}\n", self.state_key());
|
||||
text += &self.state_text(fresh, false);
|
||||
text += &format!("seed {}\nwave {}\n", self.sim.rng.state(), self.wave.text());
|
||||
text
|
||||
}
|
||||
|
||||
/// Replaces the world's layout with the scenario `text`; nothing changes if it is refused.
|
||||
fn apply_scenario(&mut self, text: &str, force: bool) -> Result<(), String> {
|
||||
let mut lines = text.lines();
|
||||
let version = lines
|
||||
.next()
|
||||
.and_then(|l| l.strip_prefix("scenario "))
|
||||
.ok_or("Это не сценарий (нет строки версии)")?
|
||||
.trim();
|
||||
match version.parse::<u32>() {
|
||||
Ok(VERSION) => {}
|
||||
_ => return Err(format!("Сценарий формата {version}: эта версия мода понимает только формат {VERSION}")),
|
||||
}
|
||||
let world = text.lines().find_map(|l| l.strip_prefix("world ")).unwrap_or("").trim();
|
||||
if !force && world != self.state_key() {
|
||||
return Err("Сценарий сделан в другом мире: координаты могут не подойти (загрузить всё равно: добавьте force)".into());
|
||||
}
|
||||
if self.replay.is_some() {
|
||||
self.stop_replay();
|
||||
}
|
||||
// Everything of the last layout goes: its systems with their jobs and targets, the sky,
|
||||
// the cook-offs to come; ids are made anew with the new systems.
|
||||
self.sim.clear();
|
||||
self.sim.sams.clear();
|
||||
self.sim.targets.clear();
|
||||
self.sim.target_health.clear();
|
||||
self.sim.roles.clear();
|
||||
self.sim.kills = 0;
|
||||
self.sim.hits = 0;
|
||||
self.sim.launched = 0;
|
||||
self.monitor = None;
|
||||
self.grid_ids.clear();
|
||||
self.moving = None;
|
||||
self.pending.clear();
|
||||
render::set_models(&[]);
|
||||
self.apply_state(text);
|
||||
self.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `/airdef scenario save|load|list|delete`.
|
||||
pub(crate) fn scenario_command(&mut self, args: &[&str]) -> Result<String, String> {
|
||||
match args {
|
||||
["save", name, flags @ ..] => {
|
||||
let name = valid(name)?;
|
||||
let fresh = flags.contains(&"fresh");
|
||||
let text = self.scenario_text(&name, fresh);
|
||||
storage::set(&key(&name), text.as_bytes()).map_err(|e| format!("Не удалось сохранить: {e}"))?;
|
||||
let mut all = names();
|
||||
if !all.contains(&name) {
|
||||
all.push(name.clone());
|
||||
storage::set(INDEX, all.join("\n").as_bytes()).map_err(|e| format!("Не удалось записать список: {e}"))?;
|
||||
}
|
||||
Ok(format!(
|
||||
"Сценарий «{name}» сохранён: комплексов {}, объектов {}{}",
|
||||
self.sim.sams.len(),
|
||||
self.sim.targets.len(),
|
||||
if fresh { " (целые, с полным боезапасом)" } else { "" }
|
||||
))
|
||||
}
|
||||
["load", name, flags @ ..] => {
|
||||
let name = valid(name)?;
|
||||
let bytes = storage::get(&key(&name)).ok_or(format!("Нет сценария «{name}» (/airdef scenario list)"))?;
|
||||
self.apply_scenario(&String::from_utf8_lossy(&bytes), flags.contains(&"force"))?;
|
||||
Ok(format!("Сценарий «{name}» загружен: комплексов {}, объектов {}", self.sim.sams.len(), self.sim.targets.len()))
|
||||
}
|
||||
["list"] => {
|
||||
let all = names();
|
||||
if all.is_empty() {
|
||||
return Ok("Сценариев нет: /airdef scenario save <имя>".into());
|
||||
}
|
||||
Ok(format!("Сценарии: {}", all.join(", ")))
|
||||
}
|
||||
["delete", name] => {
|
||||
let name = valid(name)?;
|
||||
let mut all = names();
|
||||
if !all.contains(&name) {
|
||||
return Err(format!("Нет сценария «{name}»"));
|
||||
}
|
||||
all.retain(|n| *n != name);
|
||||
storage::delete(&key(&name));
|
||||
storage::set(INDEX, all.join("\n").as_bytes()).map_err(|e| format!("Не удалось записать список: {e}"))?;
|
||||
Ok(format!("Сценарий «{name}» удалён"))
|
||||
}
|
||||
_ => Err("/airdef scenario save <имя> [fresh] | load <имя> [force] | list | delete <имя>".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user