anvil/script.rs
1//! The services of the standard plugin anvil-script (`anvil_script.h`).
2//!
3//! **`anvil-script.effects`** ([`Effects`], ADR 0008): effects of the
4//! plugin's own in EU4's script language. A mod writes `chisel_set_terrain =
5//! mountain` in an event option, a decision or a scripted effect; the game
6//! parses it as one of its own effects and, when it runs it, calls the
7//! plugin's handler with the value and the scope. Only an early plugin
8//! (`phase = "early"`) with `affects_gameplay = true` registers, and only in
9//! its [`Plugin::load`](crate::Plugin), before the game parses its first
10//! effect. Keys are `<owner>_<name>`: the plugin's id with `-` as `_`, lower
11//! case. The handlers run where the game runs its own effects and tooltips
12//! (the main thread, inside a command or the day), where
13//! [`World`](crate::world::World) answers `WrongPhase`. In multiplayer every
14//! client runs its own copy of the effect, so `execute` must be
15//! deterministic. While Anvil suspends the plugin, its effects do nothing.
16//!
17//! **`anvil-script.day_end`** ([`DayEnd`], ADR 0009): a callback at the Day
18//! end, once a day after the game has finished the day (with its month and
19//! year), on the main thread, when no worker thread of the day runs, before
20//! the game compares checksums. Only a plugin with `affects_gameplay = true`
21//! subscribes, and only before the first Day end of the process: in its
22//! `Plugin::load`. The handler runs inside the game's day command, where
23//! `World` answers `WrongPhase` too, must be deterministic for multiplayer,
24//! and is not called while Anvil suspends the plugin.
25//!
26//! Depend on anvil-script in plugin.toml (`[[dependencies]] id =
27//! "anvil-script"`, `version = "^1.16"` for the effects, `"^1.18"` for the Day
28//! end) and look the services up with [`Effects::get`] and [`DayEnd::get`].
29//!
30//! ```no_run
31//! use anvil::script::{Call, Effects};
32//! # fn load(host: &anvil::Host) -> anvil::Result<()> {
33//! let effects = Effects::get(host).expect("anvil-script.effects");
34//! effects.register_with_tooltip(
35//! host,
36//! "hello_script_log",
37//! |call: &Call<'_>| {
38//! if let Some(host) = anvil::Host::current() {
39//! host.log(anvil::LogLevel::Info, format_args!("{} in {:?}", call.value, call.province));
40//! }
41//! },
42//! |call: &Call<'_>| Some(format!("Writes \"{}\" to anvil.log", call.value)),
43//! )?;
44//! # Ok(())
45//! # }
46//! ```
47
48use std::borrow::Cow;
49use std::ffi::{c_char, c_void, CStr, CString};
50use std::fmt;
51use std::ptr;
52use std::sync::atomic::AtomicBool;
53
54use crate::error::{check, Error, ErrorCode, Result};
55use crate::event::read_sized;
56use crate::host::Host;
57use crate::panic::run_callback;
58use crate::sys::{
59 AnvilGameTag, AnvilScriptCall, AnvilScriptDay, AnvilScriptDayEndService, AnvilScriptEffect,
60 AnvilScriptEffectsService, ANVIL_SCRIPT_DAY_END_SERVICE_VERSION, ANVIL_SCRIPT_DAY_NEW_MONTH,
61 ANVIL_SCRIPT_DAY_NEW_YEAR, ANVIL_SCRIPT_EFFECTS_SERVICE_VERSION,
62};
63use crate::table::Table;
64use crate::Tag;
65
66/// The Day end service's name.
67pub const SERVICE: &CStr = c"anvil-script.day_end";
68/// The Day end service's major version.
69pub const VERSION: u32 = ANVIL_SCRIPT_DAY_END_SERVICE_VERSION;
70
71/// The effects service's name.
72pub const EFFECTS_SERVICE: &CStr = c"anvil-script.effects";
73/// The effects service's major version.
74pub const EFFECTS_VERSION: u32 = ANVIL_SCRIPT_EFFECTS_SERVICE_VERSION;
75
76// ---- the effects --------------------------------------------------------------
77
78/// One execution or description of one effect: valid only during the call.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct Call<'a> {
81 /// The registered key, e.g. `chisel_set_terrain`.
82 pub key: &'a str,
83 /// The right-hand side as the file has it, without quotes: `mountain`,
84 /// `yes`. Bytes that are not UTF-8 (a file in the game's own code page)
85 /// come as U+FFFD.
86 pub value: Cow<'a, str>,
87 /// The scope's province ID; `None` when the scope has none.
88 pub province: Option<i32>,
89 /// The scope's country; `None` when the scope has none.
90 pub country: Option<Tag>,
91}
92
93impl<'a> Call<'a> {
94 /// The call anvil-script passes, `None` for a NULL pointer or a key.
95 ///
96 /// # Safety
97 /// `raw` is NULL or points to a call whose strings are NUL-terminated and
98 /// outlive `'a`.
99 unsafe fn from_raw(raw: *const AnvilScriptCall) -> Option<Self> {
100 // SAFETY: the caller's pointer, NULL or valid for the call, starts with
101 // the size anvil-script knows: a call of an older anvil-script is read
102 // only that far, the rest zero (no strings, no scope).
103 let raw = unsafe { read_sized::<AnvilScriptCall>(raw.cast()) }?;
104 if raw.key.is_null() {
105 return None;
106 }
107 // SAFETY: NUL-terminated strings anvil-script keeps for the call.
108 let key = unsafe { CStr::from_ptr(raw.key) }.to_str().ok()?;
109 let value = if raw.value.is_null() {
110 Cow::Borrowed("")
111 } else {
112 // SAFETY: as above.
113 unsafe { CStr::from_ptr(raw.value) }.to_string_lossy()
114 };
115 let province = (raw.scope.province != 0).then_some(raw.scope.province);
116 let country = Tag::from_raw(&AnvilGameTag {
117 text: raw.scope.country,
118 });
119 Some(Self {
120 key,
121 value,
122 province,
123 country,
124 })
125 }
126}
127
128/// The `anvil-script.effects` service.
129#[derive(Clone, Copy)]
130pub struct Effects {
131 table: Table<AnvilScriptEffectsService>,
132}
133
134impl fmt::Debug for Effects {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.debug_struct("Effects")
137 .field("size", &self.table.size())
138 .finish()
139 }
140}
141
142struct EffectAdapter<E, D> {
143 execute: E,
144 describe: Option<D>,
145 execute_panicked: AtomicBool,
146 describe_panicked: AtomicBool,
147}
148
149unsafe extern "C" fn execute_adapter<E, D>(context: *mut c_void, call: *const AnvilScriptCall)
150where
151 E: Fn(&Call<'_>) + Send + Sync + 'static,
152 D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
153{
154 // SAFETY: the adapter register leaked, never freed.
155 let adapter = unsafe { &*context.cast::<EffectAdapter<E, D>>() };
156 // SAFETY: anvil-script's call, valid for this call.
157 let Some(call) = (unsafe { Call::from_raw(call) }) else {
158 return;
159 };
160 run_callback("script effect", &adapter.execute_panicked, (), || {
161 (adapter.execute)(&call)
162 });
163}
164
165/// Writes the first line of `line` into the caller's buffer, cut at a whole
166/// character, and gives the whole line's length in bytes, as `snprintf` does.
167///
168/// # Safety
169/// `utf8` has room for `capacity` bytes, or `capacity` is 0.
170unsafe fn write_line(line: &str, utf8: *mut c_char, capacity: u32) -> u32 {
171 let end = line.find(['\n', '\r', '\0']).unwrap_or(line.len());
172 let line = &line[..end];
173 if capacity > 0 && !utf8.is_null() {
174 let mut length = line.len().min(capacity as usize - 1);
175 while !line.is_char_boundary(length) {
176 length -= 1;
177 }
178 // SAFETY: `length` < `capacity` bytes into the caller's buffer.
179 unsafe {
180 ptr::copy_nonoverlapping(line.as_ptr(), utf8.cast::<u8>(), length);
181 *utf8.add(length) = 0;
182 }
183 }
184 u32::try_from(line.len()).unwrap_or(u32::MAX)
185}
186
187unsafe extern "C" fn describe_adapter<E, D>(
188 context: *mut c_void,
189 call: *const AnvilScriptCall,
190 utf8: *mut c_char,
191 capacity: u32,
192) -> u32
193where
194 E: Fn(&Call<'_>) + Send + Sync + 'static,
195 D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
196{
197 // SAFETY: the adapter register leaked, never freed.
198 let adapter = unsafe { &*context.cast::<EffectAdapter<E, D>>() };
199 let Some(describe) = adapter.describe.as_ref() else {
200 return 0;
201 };
202 // SAFETY: anvil-script's call, valid for this call.
203 let Some(call) = (unsafe { Call::from_raw(call) }) else {
204 return 0;
205 };
206 run_callback(
207 "script effect tooltip",
208 &adapter.describe_panicked,
209 0,
210 || {
211 match describe(&call) {
212 // SAFETY: anvil-script's buffer of `capacity` bytes.
213 Some(line) if !line.is_empty() => unsafe { write_line(&line, utf8, capacity) },
214 _ => 0,
215 }
216 },
217 )
218}
219
220/// The type of the describe handler of an effect without a tooltip.
221type NoDescribe = fn(&Call<'_>) -> Option<String>;
222
223impl Effects {
224 /// The service; `None` without anvil-script or on an Anvil older than
225 /// 1.16.
226 pub fn get(host: &Host) -> Option<Self> {
227 // SAFETY: the table type of anvil-script.effects version 1.
228 let table =
229 unsafe { host.service::<AnvilScriptEffectsService>(EFFECTS_SERVICE, EFFECTS_VERSION) }?;
230 Some(Self { table })
231 }
232
233 /// The C table, for what this crate does not wrap.
234 pub fn c_api(&self) -> Table<AnvilScriptEffectsService> {
235 self.table
236 }
237
238 /// Registers the effect `key` with no line of its own in tooltips.
239 /// `execute` runs each time the game runs the effect. Results, in the order
240 /// anvil-script checks them: `WrongKind` for a plugin with
241 /// `affects_gameplay = false`; `WrongPhase` for a plugin that is not early,
242 /// or once the game has parsed an effect; `InvalidArgument` for a key that
243 /// is not `<owner>_<name>` (or holds a NUL); `AlreadyExists` for a taken
244 /// key; `OutOfMemory` past 256 keys. The handler is kept for the process;
245 /// a panic in it is logged once and the game's command goes on.
246 pub fn register<E>(&self, host: &Host, key: &str, execute: E) -> Result<()>
247 where
248 E: Fn(&Call<'_>) + Send + Sync + 'static,
249 {
250 self.register_raw::<E, NoDescribe>(host, key, execute, None)
251 }
252
253 /// Registers the effect `key` as [`register`](Self::register) does, with
254 /// a tooltip line: `describe` gives the line (UTF-8, its first line only)
255 /// or `None` for none, for the scope the tooltip is built for. Text past
256 /// anvil-script's buffer is cut at a whole character.
257 pub fn register_with_tooltip<E, D>(
258 &self,
259 host: &Host,
260 key: &str,
261 execute: E,
262 describe: D,
263 ) -> Result<()>
264 where
265 E: Fn(&Call<'_>) + Send + Sync + 'static,
266 D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
267 {
268 self.register_raw(host, key, execute, Some(describe))
269 }
270
271 fn register_raw<E, D>(
272 &self,
273 host: &Host,
274 key: &str,
275 execute: E,
276 describe: Option<D>,
277 ) -> Result<()>
278 where
279 E: Fn(&Call<'_>) + Send + Sync + 'static,
280 D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
281 {
282 let f = function!(self.table, AnvilScriptEffectsService, register_effect)?;
283 let c_key = CString::new(key).map_err(|_| {
284 Error::new(
285 ErrorCode::InvalidArgument,
286 format!("register effect {key:?}: the key holds a NUL"),
287 )
288 })?;
289 let has_describe = describe.is_some();
290 // Never freed: anvil-script keeps the callbacks and the context for the
291 // process (it copies the key and the table's fields).
292 let adapter: &'static EffectAdapter<E, D> = Box::leak(Box::new(EffectAdapter {
293 execute,
294 describe,
295 execute_panicked: AtomicBool::new(false),
296 describe_panicked: AtomicBool::new(false),
297 }));
298 let effect = AnvilScriptEffect {
299 size: std::mem::size_of::<AnvilScriptEffect>() as u32,
300 flags: 0,
301 key: c_key.as_ptr(),
302 execute: Some(execute_adapter::<E, D>),
303 describe: if has_describe {
304 Some(describe_adapter::<E, D>)
305 } else {
306 None
307 },
308 context: ptr::from_ref(adapter).cast_mut().cast(),
309 };
310 // SAFETY: this plugin's handle and an effect whose key lives until the
311 // call returns, with callbacks and a context that live for the process.
312 check(unsafe { f(host.raw_plugin(), &effect) }, || {
313 format!("register effect {key:?}")
314 })
315 }
316}
317
318// ---- the Day end --------------------------------------------------------------
319
320/// The day that just ended: the date the game computed it for, which
321/// `anvil-game.day` reports after the frame.
322#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
323pub struct Day {
324 /// The year.
325 pub year: i32,
326 /// 1–12.
327 pub month: i32,
328 /// 1–31.
329 pub day: i32,
330 /// The 1st of a month: the game ran its monthly update in this day.
331 pub new_month: bool,
332 /// 1 January: the game also ran its yearly update.
333 pub new_year: bool,
334}
335
336impl Day {
337 fn from_raw(raw: &AnvilScriptDay) -> Self {
338 Self {
339 year: raw.year,
340 month: raw.month,
341 day: raw.day,
342 new_month: raw.flags & ANVIL_SCRIPT_DAY_NEW_MONTH != 0,
343 new_year: raw.flags & ANVIL_SCRIPT_DAY_NEW_YEAR != 0,
344 }
345 }
346}
347
348/// The `anvil-script.day_end` service.
349#[derive(Clone, Copy)]
350pub struct DayEnd {
351 table: Table<AnvilScriptDayEndService>,
352}
353
354impl fmt::Debug for DayEnd {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("DayEnd")
357 .field("size", &self.table.size())
358 .finish()
359 }
360}
361
362struct Adapter<F> {
363 handler: F,
364 panicked: AtomicBool,
365}
366
367unsafe extern "C" fn day_end_adapter<F>(context: *mut c_void, day: *const AnvilScriptDay)
368where
369 F: Fn(&Day) + Send + Sync + 'static,
370{
371 // SAFETY: the adapter subscribe leaked, never freed.
372 let adapter = unsafe { &*context.cast::<Adapter<F>>() };
373 // SAFETY: anvil-script passes its day for the call (or NULL, never seen),
374 // read only as far as its size.
375 let Some(raw) = (unsafe { read_sized::<AnvilScriptDay>(day.cast()) }) else {
376 return;
377 };
378 let day = Day::from_raw(&raw);
379 run_callback("day end", &adapter.panicked, (), || (adapter.handler)(&day));
380}
381
382impl DayEnd {
383 /// The service; `None` without anvil-script, on an Anvil older than 1.18,
384 /// or on a build without the Day end's symbols.
385 pub fn get(host: &Host) -> Option<Self> {
386 // SAFETY: the table type of anvil-script.day_end version 1.
387 let table = unsafe { host.service::<AnvilScriptDayEndService>(SERVICE, VERSION) }?;
388 Some(Self { table })
389 }
390
391 /// The C table, for what this crate does not wrap.
392 pub fn c_api(&self) -> Table<AnvilScriptDayEndService> {
393 self.table
394 }
395
396 /// Calls `handler` at every Day end, after the handlers that subscribed
397 /// before it. `WrongKind` for a plugin with `affects_gameplay = false`,
398 /// `WrongPhase` once the game has ended a day. The handler is kept for
399 /// the process; a panic in it is logged once and that Day end goes on.
400 pub fn subscribe<F>(&self, host: &Host, handler: F) -> Result<()>
401 where
402 F: Fn(&Day) + Send + Sync + 'static,
403 {
404 let f = function!(self.table, AnvilScriptDayEndService, subscribe)?;
405 // Never freed: anvil-script keeps the subscription for the process.
406 let adapter: &'static Adapter<F> = Box::leak(Box::new(Adapter {
407 handler,
408 panicked: AtomicBool::new(false),
409 }));
410 // SAFETY: this plugin's handle, a callback of the C type and its
411 // context, which live for the process.
412 check(
413 unsafe {
414 f(
415 host.raw_plugin(),
416 Some(day_end_adapter::<F>),
417 ptr::from_ref(adapter).cast_mut().cast(),
418 )
419 },
420 || "day end subscribe".to_string(),
421 )
422 }
423}