1use 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
23pub const SERVICE: &std::ffi::CStr = c"anvil-game.game";
25pub const VERSION: u32 = ANVIL_GAME_SERVICE_VERSION;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum SessionChange {
31 Started,
33 Ended,
35 Other(u32),
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct Session {
42 pub change: SessionChange,
44 pub ironman: bool,
46 pub multiplayer: bool,
48 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
70pub struct Date {
71 pub year: i32,
73 pub month: u32,
75 pub day: u32,
77 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 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 write!(f, "{}.{}.{}", self.year, self.month, self.day)
96 }
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct Frame {
102 pub number: u64,
104}
105
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
108pub struct OosFlags(pub u32);
109
110impl OosFlags {
111 pub const DETECTED: u32 = crate::sys::ANVIL_GAME_OOS_DETECTED;
113 pub const PAUSED: u32 = crate::sys::ANVIL_GAME_OOS_PAUSED;
115
116 pub const fn detected(self) -> bool {
118 self.0 & Self::DETECTED != 0
119 }
120 pub const fn paused(self) -> bool {
122 self.0 & Self::PAUSED != 0
123 }
124}
125
126#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
130pub struct PauseFlags(pub u32);
131
132impl PauseFlags {
133 pub const PLAYER: u32 = crate::sys::ANVIL_GAME_PAUSE_PLAYER;
135 pub const GAME: u32 = crate::sys::ANVIL_GAME_PAUSE_GAME;
138
139 pub const fn player(self) -> bool {
141 self.0 & Self::PLAYER != 0
142 }
143 pub const fn game(self) -> bool {
145 self.0 & Self::GAME != 0
146 }
147}
148
149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
151pub struct KeyboardFlags(pub u32);
152
153impl KeyboardFlags {
154 pub const TEXT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_TEXT;
156 pub const SHORTCUT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_SHORTCUT;
158
159 pub const fn text(self) -> bool {
161 self.0 & Self::TEXT != 0
162 }
163 pub const fn shortcut(self) -> bool {
165 self.0 & Self::SHORTCUT != 0
166 }
167}
168
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub struct OosChange {
172 pub flags: OosFlags,
174 pub previous: OosFlags,
176 pub session: u64,
178}
179
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub struct DateChange {
183 pub days: u32,
186 pub date: Date,
188 pub previous: Date,
190}
191
192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub struct PlayerChange {
195 pub tag: Option<Tag>,
197 pub previous: Option<Tag>,
199 pub session: u64,
201}
202
203#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
205pub enum WarChangeKind {
206 Started,
208 Ended,
210 Other(u32),
212}
213
214#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct WarChange {
217 pub change: WarChangeKind,
219 pub war: u64,
221 pub attacker: Option<Tag>,
223 pub defender: Option<Tag>,
225 pub name: String,
227 pub session: u64,
229}
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
233pub enum PendingChangeKind {
234 Added,
236 Removed,
238 Other(u32),
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub struct PendingChange {
245 pub change: PendingChangeKind,
247 pub pending_id: i32,
250 pub country: Option<Tag>,
252 pub session: u64,
254}
255
256unsafe impl Payload for Frame {
258 unsafe fn read(raw: *const c_void) -> Option<Self> {
259 unsafe { read_sized::<AnvilGameFrame>(raw) }.map(|f| Self { number: f.number })
261 }
262}
263
264unsafe impl Payload for Session {
266 unsafe fn read(raw: *const c_void) -> Option<Self> {
267 unsafe { read_sized::<AnvilGameSession>(raw) }.map(|s| Self::from_raw(&s))
269 }
270}
271
272unsafe impl Payload for OosChange {
274 unsafe fn read(raw: *const c_void) -> Option<Self> {
275 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
284unsafe impl Payload for DateChange {
286 unsafe fn read(raw: *const c_void) -> Option<Self> {
287 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
296unsafe impl Payload for PlayerChange {
298 unsafe fn read(raw: *const c_void) -> Option<Self> {
299 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
308unsafe impl Payload for WarChange {
310 unsafe fn read(raw: *const c_void) -> Option<Self> {
311 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 name: unsafe { owned_string(c.name) },
325 session: c.session,
326 })
327 }
328}
329
330unsafe impl Payload for PendingChange {
332 unsafe fn read(raw: *const c_void) -> Option<Self> {
333 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
349pub const READY: Event<()> = unsafe { Event::new(c"anvil-game.ready") };
352pub const FRAME: Event<Frame> = unsafe { Event::new(c"anvil-game.frame") };
355pub const SESSION: Event<Session> = unsafe { Event::new(c"anvil-game.session") };
358pub const MAIN_MENU: Event<()> = unsafe { Event::new(c"anvil-game.main_menu") };
361pub const OOS: Event<OosChange> = unsafe { Event::new(c"anvil-game.oos") };
364pub const DAY: Event<DateChange> = unsafe { Event::new(c"anvil-game.day") };
367pub const MONTH: Event<DateChange> = unsafe { Event::new(c"anvil-game.month") };
370pub const YEAR: Event<DateChange> = unsafe { Event::new(c"anvil-game.year") };
373pub const PLAYER: Event<PlayerChange> = unsafe { Event::new(c"anvil-game.player") };
376pub const WAR: Event<WarChange> = unsafe { Event::new(c"anvil-game.war") };
379pub const PENDING_EVENT: Event<PendingChange> = unsafe { Event::new(c"anvil-game.pending_event") };
382
383#[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 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 pub fn get(host: &Host) -> Option<Self> {
413 let table = unsafe { host.service::<AnvilGameService>(SERVICE, VERSION) }?;
415 Some(Self { table })
416 }
417
418 pub fn c_api(&self) -> Table<AnvilGameService> {
420 self.table
421 }
422
423 pub fn ready(&self) -> bool {
425 function!(self.table, AnvilGameService, ready).is_ok_and(|f| unsafe { f() } != 0)
427 }
428
429 pub fn main_thread_id(&self) -> u32 {
431 function!(self.table, AnvilGameService, main_thread_id).map_or(0, |f| unsafe { f() })
433 }
434
435 pub fn frame_number(&self) -> u64 {
437 function!(self.table, AnvilGameService, frame_number).map_or(0, |f| unsafe { f() })
439 }
440
441 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 let result = unsafe { call(Some(run_work::<F>), context.cast()) };
454 check(result, || "run_on_main_thread").inspect_err(|_| {
455 drop(unsafe { Box::from_raw(context) });
457 })
458 }
459
460 pub fn session(&self) -> Option<Session> {
462 let f = function!(self.table, AnvilGameService, session).ok()?;
463 let mut raw: AnvilGameSession = unsafe { std::mem::zeroed() };
465 raw.size = std::mem::size_of::<AnvilGameSession>() as u32;
466 (unsafe { f(&mut raw) } != 0).then(|| Session::from_raw(&raw))
468 }
469
470 pub fn date(&self) -> Option<Date> {
473 let f = function!(self.table, AnvilGameService, date).ok()?;
474 let mut raw: AnvilGameDate = unsafe { std::mem::zeroed() };
476 raw.size = std::mem::size_of::<AnvilGameDate>() as u32;
477 (unsafe { f(&mut raw) } != 0).then(|| Date::from_raw(&raw))
479 }
480
481 pub fn main_menu(&self) -> Option<bool> {
483 function!(self.table, AnvilGameService, main_menu)
485 .ok()
486 .map(|f| unsafe { f() } != 0)
487 }
488
489 pub fn out_of_sync(&self) -> Option<OosFlags> {
491 function!(self.table, AnvilGameService, out_of_sync)
493 .ok()
494 .map(|f| OosFlags(unsafe { f() }))
495 }
496
497 pub fn keyboard(&self) -> Option<KeyboardFlags> {
501 let f = function!(self.table, AnvilGameService, keyboard).ok()?;
502 let mut flags = 0u32;
503 (unsafe { f(&mut flags) } != 0).then_some(KeyboardFlags(flags))
505 }
506
507 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 check(unsafe { f(host.raw_plugin(), flags) }, || "restart")
524 }
525
526 pub fn speed(&self) -> Option<i32> {
530 let f = function!(self.table, AnvilGameService, speed).ok()?;
531 let mut speed = 0i32;
532 (unsafe { f(&mut speed) } != 0).then_some(speed)
534 }
535
536 pub fn paused(&self) -> Option<PauseFlags> {
541 let f = function!(self.table, AnvilGameService, paused).ok()?;
542 let mut flags = 0u32;
543 (unsafe { f(&mut flags) } != 0).then_some(PauseFlags(flags))
545 }
546
547 pub fn user_dir(&self) -> Option<std::path::PathBuf> {
553 let f = function!(self.table, AnvilGameService, user_dir).ok()?;
554 let dir = unsafe { f() };
556 (!dir.is_null()).then(|| crate::host::wide_path(dir))
557 }
558}