use std::ffi::c_void;
use std::fmt;
use crate::error::{check, Result};
use crate::event::{read_sized, Event, Payload};
use crate::host::Host;
use crate::sys::{
AnvilGameDate, AnvilGameDateChange, AnvilGameFrame, AnvilGameOosChange, AnvilGamePlayerChange,
AnvilGameService, AnvilGameSession, AnvilGameWarChange, ANVIL_GAME_SERVICE_VERSION,
ANVIL_GAME_SESSION_ENDED, ANVIL_GAME_SESSION_STARTED, ANVIL_GAME_WAR_ENDED,
ANVIL_GAME_WAR_STARTED,
};
use crate::text::{owned_string, Tag};
pub const SERVICE: &std::ffi::CStr = c"anvil-game.game";
pub const VERSION: u32 = ANVIL_GAME_SERVICE_VERSION;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SessionChange {
Started,
Ended,
Other(u32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Session {
pub change: SessionChange,
pub ironman: bool,
pub multiplayer: bool,
pub number: u64,
}
impl Session {
fn from_raw(raw: &AnvilGameSession) -> Self {
let change = match raw.change {
c if c == ANVIL_GAME_SESSION_STARTED as u32 => SessionChange::Started,
c if c == ANVIL_GAME_SESSION_ENDED as u32 => SessionChange::Ended,
other => SessionChange::Other(other),
};
Self {
change,
ironman: raw.ironman != 0,
multiplayer: raw.multiplayer != 0,
number: raw.number,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date {
pub year: i32,
pub month: u32,
pub day: u32,
pub session: u64,
}
impl Date {
fn from_raw(raw: &AnvilGameDate) -> Self {
Self {
year: raw.year,
month: raw.month,
day: raw.day,
session: raw.session,
}
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.year, self.month, self.day)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Frame {
pub number: u64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct OosFlags(pub u32);
impl OosFlags {
pub const DETECTED: u32 = crate::sys::ANVIL_GAME_OOS_DETECTED;
pub const PAUSED: u32 = crate::sys::ANVIL_GAME_OOS_PAUSED;
pub const fn detected(self) -> bool {
self.0 & Self::DETECTED != 0
}
pub const fn paused(self) -> bool {
self.0 & Self::PAUSED != 0
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct KeyboardFlags(pub u32);
impl KeyboardFlags {
pub const TEXT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_TEXT;
pub const SHORTCUT: u32 = crate::sys::ANVIL_GAME_KEYBOARD_SHORTCUT;
pub const fn text(self) -> bool {
self.0 & Self::TEXT != 0
}
pub const fn shortcut(self) -> bool {
self.0 & Self::SHORTCUT != 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OosChange {
pub flags: OosFlags,
pub previous: OosFlags,
pub session: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DateChange {
pub days: u32,
pub date: Date,
pub previous: Date,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlayerChange {
pub tag: Option<Tag>,
pub previous: Option<Tag>,
pub session: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WarChangeKind {
Started,
Ended,
Other(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WarChange {
pub change: WarChangeKind,
pub war: u64,
pub attacker: Option<Tag>,
pub defender: Option<Tag>,
pub name: String,
pub session: u64,
}
unsafe impl Payload for Frame {
unsafe fn read(raw: *const c_void) -> Option<Self> {
unsafe { read_sized::<AnvilGameFrame>(raw) }.map(|f| Self { number: f.number })
}
}
unsafe impl Payload for Session {
unsafe fn read(raw: *const c_void) -> Option<Self> {
unsafe { read_sized::<AnvilGameSession>(raw) }.map(|s| Self::from_raw(&s))
}
}
unsafe impl Payload for OosChange {
unsafe fn read(raw: *const c_void) -> Option<Self> {
unsafe { read_sized::<AnvilGameOosChange>(raw) }.map(|c| Self {
flags: OosFlags(c.flags),
previous: OosFlags(c.previous),
session: c.session,
})
}
}
unsafe impl Payload for DateChange {
unsafe fn read(raw: *const c_void) -> Option<Self> {
unsafe { read_sized::<AnvilGameDateChange>(raw) }.map(|c| Self {
days: c.days,
date: Date::from_raw(&c.date),
previous: Date::from_raw(&c.previous),
})
}
}
unsafe impl Payload for PlayerChange {
unsafe fn read(raw: *const c_void) -> Option<Self> {
unsafe { read_sized::<AnvilGamePlayerChange>(raw) }.map(|c| Self {
tag: Tag::from_raw(&c.tag),
previous: Tag::from_raw(&c.previous),
session: c.session,
})
}
}
unsafe impl Payload for WarChange {
unsafe fn read(raw: *const c_void) -> Option<Self> {
let c = unsafe { read_sized::<AnvilGameWarChange>(raw) }?;
let change = match c.change {
k if k == ANVIL_GAME_WAR_STARTED as u32 => WarChangeKind::Started,
k if k == ANVIL_GAME_WAR_ENDED as u32 => WarChangeKind::Ended,
other => WarChangeKind::Other(other),
};
Some(Self {
change,
war: c.war,
attacker: Tag::from_raw(&c.attacker),
defender: Tag::from_raw(&c.defender),
name: unsafe { owned_string(c.name) },
session: c.session,
})
}
}
pub const READY: Event<()> = unsafe { Event::new(c"anvil-game.ready") };
pub const FRAME: Event<Frame> = unsafe { Event::new(c"anvil-game.frame") };
pub const SESSION: Event<Session> = unsafe { Event::new(c"anvil-game.session") };
pub const MAIN_MENU: Event<()> = unsafe { Event::new(c"anvil-game.main_menu") };
pub const OOS: Event<OosChange> = unsafe { Event::new(c"anvil-game.oos") };
pub const DAY: Event<DateChange> = unsafe { Event::new(c"anvil-game.day") };
pub const MONTH: Event<DateChange> = unsafe { Event::new(c"anvil-game.month") };
pub const YEAR: Event<DateChange> = unsafe { Event::new(c"anvil-game.year") };
pub const PLAYER: Event<PlayerChange> = unsafe { Event::new(c"anvil-game.player") };
pub const WAR: Event<WarChange> = unsafe { Event::new(c"anvil-game.war") };
#[derive(Clone, Copy)]
pub struct Game {
table: &'static AnvilGameService,
}
impl fmt::Debug for Game {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Game")
.field("size", &self.table.size)
.finish()
}
}
struct Work<F> {
work: F,
}
unsafe extern "C" fn run_work<F: FnOnce() + Send + 'static>(context: *mut c_void) {
let work = unsafe { Box::from_raw(context.cast::<Work<F>>()) };
let logged = std::sync::atomic::AtomicBool::new(false);
crate::panic::run_callback("run_on_main_thread work", &logged, (), move || {
(work.work)()
});
}
impl Game {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilGameService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilGameService {
self.table
}
pub fn ready(&self) -> bool {
function!(self.table, AnvilGameService, ready).is_ok_and(|f| unsafe { f() } != 0)
}
pub fn main_thread_id(&self) -> u32 {
function!(self.table, AnvilGameService, main_thread_id).map_or(0, |f| unsafe { f() })
}
pub fn frame_number(&self) -> u64 {
function!(self.table, AnvilGameService, frame_number).map_or(0, |f| unsafe { f() })
}
pub fn run_on_main_thread(&self, work: impl FnOnce() + Send + 'static) -> Result<()> {
self.queue(work)
}
fn queue<F: FnOnce() + Send + 'static>(&self, work: F) -> Result<()> {
let call = function!(self.table, AnvilGameService, run_on_main_thread)?;
let context = Box::into_raw(Box::new(Work { work }));
let result = unsafe { call(Some(run_work::<F>), context.cast()) };
check(result, || "run_on_main_thread").inspect_err(|_| {
drop(unsafe { Box::from_raw(context) });
})
}
pub fn session(&self) -> Option<Session> {
let f = function!(self.table, AnvilGameService, session).ok()?;
let mut raw: AnvilGameSession = unsafe { std::mem::zeroed() };
raw.size = std::mem::size_of::<AnvilGameSession>() as u32;
(unsafe { f(&mut raw) } != 0).then(|| Session::from_raw(&raw))
}
pub fn date(&self) -> Option<Date> {
let f = function!(self.table, AnvilGameService, date).ok()?;
let mut raw: AnvilGameDate = unsafe { std::mem::zeroed() };
raw.size = std::mem::size_of::<AnvilGameDate>() as u32;
(unsafe { f(&mut raw) } != 0).then(|| Date::from_raw(&raw))
}
pub fn main_menu(&self) -> Option<bool> {
function!(self.table, AnvilGameService, main_menu)
.ok()
.map(|f| unsafe { f() } != 0)
}
pub fn out_of_sync(&self) -> Option<OosFlags> {
function!(self.table, AnvilGameService, out_of_sync)
.ok()
.map(|f| OosFlags(unsafe { f() }))
}
pub fn keyboard(&self) -> Option<KeyboardFlags> {
let f = function!(self.table, AnvilGameService, keyboard).ok()?;
let mut flags = 0u32;
(unsafe { f(&mut flags) } != 0).then_some(KeyboardFlags(flags))
}
}