//! The script host — SCI's whole reason to exist, minus its whole reason to //! crash. Rooms carry [rhai](https://rhai.rs) scripts with hook functions: //! //! ```rhai //! fn on_enter() { say("The precinct hums."); } //! fn on_verb(verb, noun) { if verb == "do" && noun == "console" { ... return true; } false } //! fn on_trigger(name) { if name == "tripwire" { die("Zap."); } } //! fn on_tick() { /* every cycle — keep it light */ } //! fn my_timer() { say("The kettle boils."); } // via after(90, "my_timer") //! ``` //! //! Scripts never touch the engine directly: reads go through a shared //! [`ScriptCtx`] snapshot, writes queue as [`Fx`] effects the state layer //! applies after the call returns. That one-way airlock is why a buggy //! script can print garbage but can't corrupt the sim — the modern answer //! to `Error 47: Not an object`. //! //! Timers (`after`) count **game ticks**, not wall time, and the only RNG is //! the engine's seeded xorshift — so a replayed command log is bit-identical //! on any machine. The entire CPU-speed-bug family, extinct. use crate::audio::AudioCue; use rhai::{Engine, Scope, AST}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; /// Effects a script can queue. Applied in order by the state layer. #[derive(Clone, Debug)] pub enum Fx { Say(String), SayBy(String, String), Give(String), RemoveItem(String), GotoRoom(u32), PlaceEgo(i32, i32), WalkEgo(i32, i32), FreezeEgo(bool), NpcWalk(String, i32, i32), NpcPlace(String, i32, i32), NpcFreeze(String, bool), Play(String), Music(u8), AddPoints(u32), Win, Die(String), After(u32, String), PalCycle(usize, bool), } /// What scripts see and touch. Flags/vars are written directly (so a script /// reads back its own writes mid-call); everything else queues as Fx. #[derive(Default)] pub struct ScriptCtx { pub flags: HashMap, pub vars: HashMap, pub inventory: Vec, pub ego: (i32, i32), pub room: u32, pub rng: u64, pub fx: Vec, } impl ScriptCtx { /// xorshift64* — tiny, seedable, identical everywhere. The only RNG any /// game logic is allowed to have. pub fn next_rand(&mut self, n: i64) -> i64 { if n <= 1 { return 0; } let mut x = self.rng.max(1); x ^= x >> 12; x ^= x << 25; x ^= x >> 27; self.rng = x; ((x.wrapping_mul(0x2545F4914F6CDD1D) >> 33) % n as u64) as i64 } } pub struct ScriptHost { engine: Engine, ast: Option, pub ctx: Arc>, /// Last compile error, surfaced once as an Event::Error by the caller. pub compile_error: Option, } impl ScriptHost { pub fn new() -> Self { let ctx: Arc> = Arc::new(Mutex::new(ScriptCtx::default())); let mut engine = Engine::new(); // Scripts run at most 50k ops per hook call: an accidental // `while true {}` becomes a skipped hook, not a hung game. engine.set_max_operations(50_000); macro_rules! fx { ($ctx:expr, $e:expr) => {{ $ctx.lock().unwrap().fx.push($e); }}; } let c = ctx.clone(); engine.register_fn("say", move |s: &str| fx!(c, Fx::Say(s.into()))); let c = ctx.clone(); engine.register_fn("say_by", move |who: &str, s: &str| fx!(c, Fx::SayBy(who.into(), s.into()))); let c = ctx.clone(); engine.register_fn("flag", move |n: &str| -> bool { c.lock().unwrap().flags.get(n).copied().unwrap_or(false) }); let c = ctx.clone(); engine.register_fn("set_flag", move |n: &str, v: bool| { c.lock().unwrap().flags.insert(n.into(), v); }); // ("var" is a rhai reserved word, so numeric state reads as val().) let c = ctx.clone(); engine.register_fn("val", move |n: &str| -> i64 { c.lock().unwrap().vars.get(n).copied().unwrap_or(0) }); let c = ctx.clone(); engine.register_fn("set_val", move |n: &str, v: i64| { c.lock().unwrap().vars.insert(n.into(), v); }); let c = ctx.clone(); engine.register_fn("has", move |item: &str| -> bool { c.lock().unwrap().inventory.iter().any(|i| i == item) }); let c = ctx.clone(); engine.register_fn("give", move |item: &str| fx!(c, Fx::Give(item.into()))); let c = ctx.clone(); engine.register_fn("remove_item", move |item: &str| fx!(c, Fx::RemoveItem(item.into()))); let c = ctx.clone(); engine.register_fn("room", move || -> i64 { c.lock().unwrap().room as i64 }); let c = ctx.clone(); engine.register_fn("ego_x", move || -> i64 { c.lock().unwrap().ego.0 as i64 }); let c = ctx.clone(); engine.register_fn("ego_y", move || -> i64 { c.lock().unwrap().ego.1 as i64 }); let c = ctx.clone(); engine.register_fn("goto_room", move |n: i64| fx!(c, Fx::GotoRoom(n.max(0) as u32))); let c = ctx.clone(); engine.register_fn("place_ego", move |x: i64, y: i64| fx!(c, Fx::PlaceEgo(x as i32, y as i32))); let c = ctx.clone(); engine.register_fn("walk_ego", move |x: i64, y: i64| fx!(c, Fx::WalkEgo(x as i32, y as i32))); let c = ctx.clone(); engine.register_fn("freeze_ego", move |v: bool| fx!(c, Fx::FreezeEgo(v))); let c = ctx.clone(); engine.register_fn("npc_walk", move |n: &str, x: i64, y: i64| fx!(c, Fx::NpcWalk(n.into(), x as i32, y as i32))); let c = ctx.clone(); engine.register_fn("npc_place", move |n: &str, x: i64, y: i64| fx!(c, Fx::NpcPlace(n.into(), x as i32, y as i32))); let c = ctx.clone(); engine.register_fn("npc_freeze", move |n: &str, v: bool| fx!(c, Fx::NpcFreeze(n.into(), v))); let c = ctx.clone(); engine.register_fn("play", move |cue: &str| fx!(c, Fx::Play(cue.into()))); let c = ctx.clone(); engine.register_fn("music", move |mood: i64| fx!(c, Fx::Music(mood.clamp(0, 255) as u8))); let c = ctx.clone(); engine.register_fn("points", move |n: i64| fx!(c, Fx::AddPoints(n.max(0) as u32))); let c = ctx.clone(); engine.register_fn("win", move || fx!(c, Fx::Win)); let c = ctx.clone(); engine.register_fn("die", move |text: &str| fx!(c, Fx::Die(text.into()))); let c = ctx.clone(); engine.register_fn("after", move |ticks: i64, f: &str| fx!(c, Fx::After(ticks.max(1) as u32, f.into()))); let c = ctx.clone(); engine.register_fn("pal_cycle", move |i: i64, on: bool| fx!(c, Fx::PalCycle(i.max(0) as usize, on))); let c = ctx.clone(); engine.register_fn("rand", move |n: i64| -> i64 { c.lock().unwrap().next_rand(n) }); ScriptHost { engine, ast: None, ctx, compile_error: None } } /// Compile `main.rhai` (if any) + the room script (if any) into one AST. /// A compile error disables the host for this room and is reported — /// the game keeps running on its declarative data. pub fn load(&mut self, global_src: Option<&str>, room_src: Option<&str>) { self.ast = None; self.compile_error = None; let mut ast: Option = None; for (label, src) in [("main.rhai", global_src), ("room script", room_src)] { let Some(src) = src else { continue }; match self.engine.compile(src) { Ok(a) => { ast = Some(match ast { None => a, Some(mut base) => { base += a; base } }); } Err(e) => { self.compile_error = Some(format!("{}: {}", label, e)); return; } } } self.ast = ast; } pub fn active(&self) -> bool { self.ast.is_some() } /// Call a hook that returns nothing. Missing functions are fine (rooms /// implement only the hooks they care about); real errors are returned. pub fn call(&self, name: &str, args: impl rhai::FuncArgs) -> Result<(), String> { let Some(ast) = &self.ast else { return Ok(()); }; let mut scope = Scope::new(); match self.engine.call_fn::(&mut scope, ast, name, args) { Ok(_) => Ok(()), Err(e) => match *e { rhai::EvalAltResult::ErrorFunctionNotFound(ref f, _) if f.starts_with(name) => Ok(()), _ => Err(format!("script {}(): {}", name, e)), }, } } /// Call `on_verb(verb, noun)` → did the script handle it? pub fn call_on_verb(&self, verb: &str, noun: &str) -> Result { let Some(ast) = &self.ast else { return Ok(false); }; let mut scope = Scope::new(); match self.engine.call_fn::(&mut scope, ast, "on_verb", (verb.to_string(), noun.to_string())) { Ok(d) => Ok(d.as_bool().unwrap_or(false)), Err(e) => match *e { rhai::EvalAltResult::ErrorFunctionNotFound(ref f, _) if f.starts_with("on_verb") => Ok(false), _ => Err(format!("script on_verb(): {}", e)), }, } } /// Map a cue name from scripts to the engine's cue set (unknown = blip — /// a wrong sound, never a crash). pub fn cue_by_name(name: &str) -> AudioCue { AudioCue::ALL.into_iter().find(|c| c.name() == name).unwrap_or(AudioCue::Blip) } } impl Default for ScriptHost { fn default() -> Self { Self::new() } }