Skip to main content

anvil/
game.rs

1//! `anvil-game.game`: the game's main loop, sessions and date, and the events
2//! anvil-game publishes on the game's main thread (`anvil_game.h`).
3//!
4//! Depend on anvil-game in plugin.toml (`[[dependencies]] id = "anvil-game"`)
5//! and look the service up with [`Game::get`].
6
7use std::ffi::c_void;
8use std::fmt;
9
10use crate::error::{check, Result};
11use crate::event::{read_sized, Event, Payload};
12use crate::host::Host;
13use crate::sys::{
14    AnvilGameDate, AnvilGameDateChange, AnvilGameFrame, AnvilGameOosChange, AnvilGamePendingChange,
15    AnvilGamePlayerChange, AnvilGameService, AnvilGameSession, AnvilGameWarChange,
16    ANVIL_GAME_PENDING_ADDED, ANVIL_GAME_PENDING_REMOVED, ANVIL_GAME_SERVICE_VERSION,
17    ANVIL_GAME_SESSION_ENDED, ANVIL_GAME_SESSION_STARTED, ANVIL_GAME_WAR_ENDED,
18    ANVIL_GAME_WAR_STARTED,
19};
20use crate::table::Table;
21use crate::text::{owned_string, Tag};
22
23/// The service's name.
24pub const SERVICE: &std::ffi::CStr = c"anvil-game.game";
25/// The service's major version.
26pub const VERSION: u32 = ANVIL_GAME_SERVICE_VERSION;
27
28/// How a session changed.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum SessionChange {
31    /// A save or a new game is loaded and running.
32    Started,
33    /// The player left it (to the menu, or by loading another save).
34    Ended,
35    /// A value this crate does not know.
36    Other(u32),
37}
38
39/// A game session: `anvil-game.session`'s payload and [`Game::session`].
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct Session {
42    /// Started or ended; an end carries the flags the session had.
43    pub change: SessionChange,
44    /// An ironman game.
45    pub ironman: bool,
46    /// A multiplayer game.
47    pub multiplayer: bool,
48    /// 1 for the first session since the game started, then 2, …
49    pub number: u64,
50}
51
52impl Session {
53    fn from_raw(raw: &AnvilGameSession) -> Self {
54        let change = match raw.change {
55            c if c == ANVIL_GAME_SESSION_STARTED as u32 => SessionChange::Started,
56            c if c == ANVIL_GAME_SESSION_ENDED as u32 => SessionChange::Ended,
57            other => SessionChange::Other(other),
58        };
59        Self {
60            change,
61            ironman: raw.ironman != 0,
62            multiplayer: raw.multiplayer != 0,
63            number: raw.number,
64        }
65    }
66}
67
68/// An in-game date, as the game's top bar shows it (years have 365 days).
69#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
70pub struct Date {
71    /// E.g. 1444.
72    pub year: i32,
73    /// 1..12.
74    pub month: u32,
75    /// 1..31.
76    pub day: u32,
77    /// The [`Session::number`] it belongs to.
78    pub session: u64,
79}
80
81impl Date {
82    pub(crate) fn from_raw(raw: &AnvilGameDate) -> Self {
83        Self {
84            year: raw.year,
85            month: raw.month,
86            day: raw.day,
87            session: raw.session,
88        }
89    }
90}
91
92impl fmt::Display for Date {
93    /// `1444.11.11`, as the game writes dates.
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(f, "{}.{}.{}", self.year, self.month, self.day)
96    }
97}
98
99/// `anvil-game.frame`'s payload.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct Frame {
102    /// The game's own frame counter after this frame.
103    pub number: u64,
104}
105
106/// Out-of-sync flags (`ANVIL_GAME_OOS_*`).
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
108pub struct OosFlags(pub u32);
109
110impl OosFlags {
111    /// This game's checksums differed from the host's (a client only).
112    pub const DETECTED: u32 = crate::sys::ANVIL_GAME_OOS_DETECTED;
113    /// The game is paused because a machine went out of sync.
114    pub const PAUSED: u32 = crate::sys::ANVIL_GAME_OOS_PAUSED;
115
116    /// Whether the game is out of sync.
117    pub const fn detected(self) -> bool {
118        self.0 & Self::DETECTED != 0
119    }
120    /// Whether the game is paused for it.
121    pub const fn paused(self) -> bool {
122        self.0 & Self::PAUSED != 0
123    }
124}
125
126/// Why the game is paused (`ANVIL_GAME_PAUSE_*`): one reason, the player's
127/// pause while it is on (the game may hold one of its own as well), else the
128/// game's.
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
130pub struct PauseFlags(pub u32);
131
132impl PauseFlags {
133    /// The player's pause, the one the space bar and the pause button toggle.
134    pub const PLAYER: u32 = crate::sys::ANVIL_GAME_PAUSE_PLAYER;
135    /// In single player, the game's own list of pauses is not empty and the
136    /// player's pause is off.
137    pub const GAME: u32 = crate::sys::ANVIL_GAME_PAUSE_GAME;
138
139    /// Whether the player paused the game.
140    pub const fn player(self) -> bool {
141        self.0 & Self::PLAYER != 0
142    }
143    /// Whether the game holds a pause of its own.
144    pub const fn game(self) -> bool {
145        self.0 & Self::GAME != 0
146    }
147}
148
149/// What of the game's GUI takes the keyboard (`ANVIL_GAME_KEYBOARD_*`).
150#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
151pub struct KeyboardFlags(pub u32);
152
153impl KeyboardFlags {
154    /// A text field of the game has focus.
155    pub const TEXT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_TEXT;
156    /// The shortcut editor waits for a key.
157    pub const SHORTCUT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_SHORTCUT;
158
159    /// Whether a text field has focus.
160    pub const fn text(self) -> bool {
161        self.0 & Self::TEXT != 0
162    }
163    /// Whether the shortcut editor waits.
164    pub const fn shortcut(self) -> bool {
165        self.0 & Self::SHORTCUT != 0
166    }
167}
168
169/// `anvil-game.oos`'s payload.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub struct OosChange {
172    /// The flags now.
173    pub flags: OosFlags,
174    /// The flags before.
175    pub previous: OosFlags,
176    /// The [`Session::number`].
177    pub session: u64,
178}
179
180/// The payload of `anvil-game.day`, `.month` and `.year`.
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub struct DateChange {
183    /// How many days the step covers: 1 in a single-player game, perhaps more
184    /// on a multiplayer client.
185    pub days: u32,
186    /// The date now.
187    pub date: Date,
188    /// The date before.
189    pub previous: Date,
190}
191
192/// `anvil-game.player`'s payload: the player's country changed within a session.
193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub struct PlayerChange {
195    /// The country now; `None` for none.
196    pub tag: Option<Tag>,
197    /// The country before.
198    pub previous: Option<Tag>,
199    /// The [`Session::number`].
200    pub session: u64,
201}
202
203/// How a war changed.
204#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
205pub enum WarChangeKind {
206    /// The war started.
207    Started,
208    /// The war ended.
209    Ended,
210    /// A value this crate does not know.
211    Other(u32),
212}
213
214/// `anvil-game.war`'s payload.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct WarChange {
217    /// Started or ended.
218    pub change: WarChangeKind,
219    /// The war's id (no longer valid for an end).
220    pub war: u64,
221    /// Who started it.
222    pub attacker: Option<Tag>,
223    /// Whom it was declared on.
224    pub defender: Option<Tag>,
225    /// The war's name as the game shows it.
226    pub name: String,
227    /// The [`Session::number`].
228    pub session: u64,
229}
230
231/// How a pending event of the player changed (anvil-game 1.21.0).
232#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
233pub enum PendingChangeKind {
234    /// It came: the player can choose.
235    Added,
236    /// It left: chosen, by the player, a plugin or the game's auto-select.
237    Removed,
238    /// A value this crate does not know.
239    Other(u32),
240}
241
242/// `anvil-game.pending_event`'s payload.
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub struct PendingChange {
245    /// Added or removed.
246    pub change: PendingChangeKind,
247    /// The pending id ([`World::pending_event`](crate::world::World::pending_event));
248    /// no longer valid for a removal.
249    pub pending_id: i32,
250    /// The player's country.
251    pub country: Option<Tag>,
252    /// The [`Session::number`].
253    pub session: u64,
254}
255
256// SAFETY: anvil-game.frame publishes a const AnvilGameFrame*.
257unsafe impl Payload for Frame {
258    unsafe fn read(raw: *const c_void) -> Option<Self> {
259        // SAFETY: the event's payload type.
260        unsafe { read_sized::<AnvilGameFrame>(raw) }.map(|f| Self { number: f.number })
261    }
262}
263
264// SAFETY: anvil-game.session publishes a const AnvilGameSession*.
265unsafe impl Payload for Session {
266    unsafe fn read(raw: *const c_void) -> Option<Self> {
267        // SAFETY: the event's payload type.
268        unsafe { read_sized::<AnvilGameSession>(raw) }.map(|s| Self::from_raw(&s))
269    }
270}
271
272// SAFETY: anvil-game.oos publishes a const AnvilGameOosChange*.
273unsafe impl Payload for OosChange {
274    unsafe fn read(raw: *const c_void) -> Option<Self> {
275        // SAFETY: the event's payload type.
276        unsafe { read_sized::<AnvilGameOosChange>(raw) }.map(|c| Self {
277            flags: OosFlags(c.flags),
278            previous: OosFlags(c.previous),
279            session: c.session,
280        })
281    }
282}
283
284// SAFETY: anvil-game.day, .month and .year publish a const AnvilGameDateChange*.
285unsafe impl Payload for DateChange {
286    unsafe fn read(raw: *const c_void) -> Option<Self> {
287        // SAFETY: the event's payload type.
288        unsafe { read_sized::<AnvilGameDateChange>(raw) }.map(|c| Self {
289            days: c.days,
290            date: Date::from_raw(&c.date),
291            previous: Date::from_raw(&c.previous),
292        })
293    }
294}
295
296// SAFETY: anvil-game.player publishes a const AnvilGamePlayerChange*.
297unsafe impl Payload for PlayerChange {
298    unsafe fn read(raw: *const c_void) -> Option<Self> {
299        // SAFETY: the event's payload type.
300        unsafe { read_sized::<AnvilGamePlayerChange>(raw) }.map(|c| Self {
301            tag: Tag::from_raw(&c.tag),
302            previous: Tag::from_raw(&c.previous),
303            session: c.session,
304        })
305    }
306}
307
308// SAFETY: anvil-game.war publishes a const AnvilGameWarChange* with its name.
309unsafe impl Payload for WarChange {
310    unsafe fn read(raw: *const c_void) -> Option<Self> {
311        // SAFETY: the event's payload type; a zeroed name (an older publisher) is null.
312        let c = unsafe { read_sized::<AnvilGameWarChange>(raw) }?;
313        let change = match c.change {
314            k if k == ANVIL_GAME_WAR_STARTED as u32 => WarChangeKind::Started,
315            k if k == ANVIL_GAME_WAR_ENDED as u32 => WarChangeKind::Ended,
316            other => WarChangeKind::Other(other),
317        };
318        Some(Self {
319            change,
320            war: c.war,
321            attacker: Tag::from_raw(&c.attacker),
322            defender: Tag::from_raw(&c.defender),
323            // SAFETY: the name is valid during the handler.
324            name: unsafe { owned_string(c.name) },
325            session: c.session,
326        })
327    }
328}
329
330// SAFETY: anvil-game.pending_event publishes a const AnvilGamePendingChange*.
331unsafe impl Payload for PendingChange {
332    unsafe fn read(raw: *const c_void) -> Option<Self> {
333        // SAFETY: the event's payload type.
334        let c = unsafe { read_sized::<AnvilGamePendingChange>(raw) }?;
335        let change = match c.change {
336            k if k == ANVIL_GAME_PENDING_ADDED as u32 => PendingChangeKind::Added,
337            k if k == ANVIL_GAME_PENDING_REMOVED as u32 => PendingChangeKind::Removed,
338            other => PendingChangeKind::Other(other),
339        };
340        Some(Self {
341            change,
342            pending_id: c.pending_id,
343            country: Tag::from_raw(&c.country),
344            session: c.session,
345        })
346    }
347}
348
349/// Once, when the game has finished initializing (the main menu is up).
350// SAFETY: anvil_game.h names the payload type, which this one reads.
351pub const READY: Event<()> = unsafe { Event::new(c"anvil-game.ready") };
352/// After every frame of the main loop. Keep the handler short.
353// SAFETY: anvil_game.h names the payload type, which this one reads.
354pub const FRAME: Event<Frame> = unsafe { Event::new(c"anvil-game.frame") };
355/// A session started or ended.
356// SAFETY: anvil_game.h names the payload type, which this one reads.
357pub const SESSION: Event<Session> = unsafe { Event::new(c"anvil-game.session") };
358/// The main menu came up or went away (anvil-game 1.8.0); ask [`Game::main_menu`].
359// SAFETY: anvil_game.h names the payload type, which this one reads.
360pub const MAIN_MENU: Event<()> = unsafe { Event::new(c"anvil-game.main_menu") };
361/// The out-of-sync flags changed (anvil-game 1.14.0).
362// SAFETY: anvil_game.h names the payload type, which this one reads.
363pub const OOS: Event<OosChange> = unsafe { Event::new(c"anvil-game.oos") };
364/// The date moved (anvil-game 1.11.0).
365// SAFETY: anvil_game.h names the payload type, which this one reads.
366pub const DAY: Event<DateChange> = unsafe { Event::new(c"anvil-game.day") };
367/// A new month began (anvil-game 1.11.0), after the game's monthly update.
368// SAFETY: anvil_game.h names the payload type, which this one reads.
369pub const MONTH: Event<DateChange> = unsafe { Event::new(c"anvil-game.month") };
370/// A new year began (anvil-game 1.11.0), after the game's yearly update.
371// SAFETY: anvil_game.h names the payload type, which this one reads.
372pub const YEAR: Event<DateChange> = unsafe { Event::new(c"anvil-game.year") };
373/// The player's country changed within a session (anvil-game 1.11.0).
374// SAFETY: anvil_game.h names the payload type, which this one reads.
375pub const PLAYER: Event<PlayerChange> = unsafe { Event::new(c"anvil-game.player") };
376/// A war started or ended (anvil-game 1.11.0).
377// SAFETY: anvil_game.h names the payload type, which this one reads.
378pub const WAR: Event<WarChange> = unsafe { Event::new(c"anvil-game.war") };
379/// A pending event of the player's own country came or left (anvil-game 1.21.0).
380// SAFETY: anvil_game.h names the payload type, which this one reads.
381pub const PENDING_EVENT: Event<PendingChange> = unsafe { Event::new(c"anvil-game.pending_event") };
382
383/// The `anvil-game.game` service.
384#[derive(Clone, Copy)]
385pub struct Game {
386    table: Table<AnvilGameService>,
387}
388
389impl fmt::Debug for Game {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        f.debug_struct("Game")
392            .field("size", &self.table.size())
393            .finish()
394    }
395}
396
397struct Work<F> {
398    work: F,
399}
400
401unsafe extern "C" fn run_work<F: FnOnce() + Send + 'static>(context: *mut c_void) {
402    // SAFETY: the box run_on_main_thread queued, run once.
403    let work = unsafe { Box::from_raw(context.cast::<Work<F>>()) };
404    let logged = std::sync::atomic::AtomicBool::new(false);
405    crate::panic::run_callback("run_on_main_thread work", &logged, (), move || {
406        (work.work)()
407    });
408}
409
410impl Game {
411    /// The service; `None` without anvil-game.
412    pub fn get(host: &Host) -> Option<Self> {
413        // SAFETY: the table type of anvil-game.game version 1.
414        let table = unsafe { host.service::<AnvilGameService>(SERVICE, VERSION) }?;
415        Some(Self { table })
416    }
417
418    /// The C table, for what this crate does not wrap.
419    pub fn c_api(&self) -> Table<AnvilGameService> {
420        self.table
421    }
422
423    /// Whether `anvil-game.ready` was published.
424    pub fn ready(&self) -> bool {
425        // SAFETY: the service's function.
426        function!(self.table, AnvilGameService, ready).is_ok_and(|f| unsafe { f() } != 0)
427    }
428
429    /// The game's main thread; 0 before its first frame.
430    pub fn main_thread_id(&self) -> u32 {
431        // SAFETY: as above.
432        function!(self.table, AnvilGameService, main_thread_id).map_or(0, |f| unsafe { f() })
433    }
434
435    /// The frame number of the last `anvil-game.frame`; 0 before it.
436    pub fn frame_number(&self) -> u64 {
437        // SAFETY: as above.
438        function!(self.table, AnvilGameService, frame_number).map_or(0, |f| unsafe { f() })
439    }
440
441    /// Queues `work` to run on the main thread after the next frame of the
442    /// main loop, in the order queued. Callable from any thread. Work still
443    /// queued when the game quits never runs, and frames stop while a save
444    /// loads: never wait for it without a limit.
445    pub fn run_on_main_thread(&self, work: impl FnOnce() + Send + 'static) -> Result<()> {
446        self.queue(work)
447    }
448
449    fn queue<F: FnOnce() + Send + 'static>(&self, work: F) -> Result<()> {
450        let call = function!(self.table, AnvilGameService, run_on_main_thread)?;
451        let context = Box::into_raw(Box::new(Work { work }));
452        // SAFETY: the adapter never unwinds and frees the box when it runs.
453        let result = unsafe { call(Some(run_work::<F>), context.cast()) };
454        check(result, || "run_on_main_thread").inspect_err(|_| {
455            // SAFETY: refused, so it never runs: the box is still ours.
456            drop(unsafe { Box::from_raw(context) });
457        })
458    }
459
460    /// The running session, as of the last frame of the main loop.
461    pub fn session(&self) -> Option<Session> {
462        let f = function!(self.table, AnvilGameService, session).ok()?;
463        // SAFETY: zeroed plain data with its size set, filled by the service.
464        let mut raw: AnvilGameSession = unsafe { std::mem::zeroed() };
465        raw.size = std::mem::size_of::<AnvilGameSession>() as u32;
466        // SAFETY: the service's function with a valid out pointer.
467        (unsafe { f(&mut raw) } != 0).then(|| Session::from_raw(&raw))
468    }
469
470    /// The current date while a session runs (anvil-game 1.6.0); `None` in
471    /// the menu, while a save loads from it, or with an older anvil-game.
472    pub fn date(&self) -> Option<Date> {
473        let f = function!(self.table, AnvilGameService, date).ok()?;
474        // SAFETY: as in session().
475        let mut raw: AnvilGameDate = unsafe { std::mem::zeroed() };
476        raw.size = std::mem::size_of::<AnvilGameDate>() as u32;
477        // SAFETY: as in session().
478        (unsafe { f(&mut raw) } != 0).then(|| Date::from_raw(&raw))
479    }
480
481    /// Whether the main menu is up (anvil-game 1.8.0); `None` with an older one.
482    pub fn main_menu(&self) -> Option<bool> {
483        // SAFETY: the service's function.
484        function!(self.table, AnvilGameService, main_menu)
485            .ok()
486            .map(|f| unsafe { f() } != 0)
487    }
488
489    /// The session's out-of-sync flags (anvil-game 1.14.0); `None` with an older one.
490    pub fn out_of_sync(&self) -> Option<OosFlags> {
491        // SAFETY: the service's function.
492        function!(self.table, AnvilGameService, out_of_sync)
493            .ok()
494            .map(|f| OosFlags(unsafe { f() }))
495    }
496
497    /// Whether the game's GUI takes the keyboard for itself (anvil-game
498    /// 1.18.0), read live: ask on the main thread. `None` with an older
499    /// anvil-game or on a build that declares its symbols absent.
500    pub fn keyboard(&self) -> Option<KeyboardFlags> {
501        let f = function!(self.table, AnvilGameService, keyboard).ok()?;
502        let mut flags = 0u32;
503        // SAFETY: the service's function with a valid out pointer.
504        (unsafe { f(&mut flags) } != 0).then_some(KeyboardFlags(flags))
505    }
506
507    /// Asks the game for its own restart (anvil-game 1.23.0, Anvil's ADR 0012),
508    /// on the player's request only. `close_campaign` is the caller's word that
509    /// the player accepted closing a running single-player campaign (ironman
510    /// is saved, anything else loses its progress since the last save).
511    /// `WrongPhase` before the game is ready, in a multiplayer session, or in
512    /// a campaign without `close_campaign`; `Unsupported` with an older
513    /// anvil-game or a build without its symbols. `host` is this plugin's, for
514    /// the log.
515    pub fn restart(&self, host: &Host, close_campaign: bool) -> Result<()> {
516        let f = function!(self.table, AnvilGameService, restart)?;
517        let flags = if close_campaign {
518            crate::sys::ANVIL_GAME_RESTART_CLOSE_CAMPAIGN
519        } else {
520            0
521        };
522        // SAFETY: the service's function with this plugin's handle.
523        check(unsafe { f(host.raw_plugin(), flags) }, || "restart")
524    }
525
526    /// The game speed as the speed bar shows it, 1 to 5, as of the last frame
527    /// (anvil-game 1.24.0); it keeps its value while paused. `None` without a
528    /// session, with an older anvil-game or on a build without its symbols.
529    pub fn speed(&self) -> Option<i32> {
530        let f = function!(self.table, AnvilGameService, speed).ok()?;
531        let mut speed = 0i32;
532        // SAFETY: the service's function with a valid out pointer.
533        (unsafe { f(&mut speed) } != 0).then_some(speed)
534    }
535
536    /// Why the game is paused, as of the last frame (anvil-game 1.24.0):
537    /// `Some` while a session runs and is paused, `None` while it runs on,
538    /// without a session, with an older anvil-game or on a build without its
539    /// symbols. A pause for going out of sync is [`Game::out_of_sync`]'s.
540    pub fn paused(&self) -> Option<PauseFlags> {
541        let f = function!(self.table, AnvilGameService, paused).ok()?;
542        let mut flags = 0u32;
543        // SAFETY: the service's function with a valid out pointer.
544        (unsafe { f(&mut flags) } != 0).then_some(PauseFlags(flags))
545    }
546
547    /// The game's own write folder, where it keeps `save games`, `logs` and
548    /// `settings.txt` (by default `Documents\Paradox Interactive\Europa
549    /// Universalis IV`, or what `-userdir` and `userdir.txt` choose). `None`
550    /// until the game set it at start-up (it has by `anvil-game.ready`), with
551    /// an older anvil-game or on a build without its symbol. Any thread.
552    pub fn user_dir(&self) -> Option<std::path::PathBuf> {
553        let f = function!(self.table, AnvilGameService, user_dir).ok()?;
554        // SAFETY: the service's function; it answers NULL or a string anvil-game keeps.
555        let dir = unsafe { f() };
556        (!dir.is_null()).then(|| crate::host::wide_path(dir))
557    }
558}