use std::fmt;
use std::mem::size_of;
use crate::error::{check, Result};
use crate::host::Host;
use crate::sys::{
AnvilGameCommand, AnvilGameCommandResult, AnvilGameCommandsService, AnvilGameUnitRef,
AnvilPlugin, ANVIL_GAME_COMMANDS_SERVICE_VERSION, ANVIL_GAME_COMMAND_DRILL,
ANVIL_GAME_COMMAND_EVENT_OPTION, ANVIL_GAME_COMMAND_EXPLORE, ANVIL_GAME_COMMAND_MAX_PER_FRAME,
ANVIL_GAME_COMMAND_MAX_UNITS, ANVIL_GAME_COMMAND_MERGE, ANVIL_GAME_COMMAND_MOVE,
ANVIL_GAME_COMMAND_QUEUE, ANVIL_GAME_COMMAND_SIEGE_AREA, ANVIL_GAME_COMMAND_SPEED,
ANVIL_GAME_COMMAND_SPLIT, ANVIL_GAME_COMMAND_START, ANVIL_GAME_COMMAND_SUPPRESS_AREA,
ANVIL_GAME_EXPLORE_CIRCUMNAVIGATE, ANVIL_GAME_EXPLORE_LAND, ANVIL_GAME_EXPLORE_STOP,
ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY,
};
use crate::world::{UnitKind, UnitRef};
pub const SERVICE: &std::ffi::CStr = c"anvil-game.commands";
pub const VERSION: u32 = ANVIL_GAME_COMMANDS_SERVICE_VERSION;
pub const MAX_UNITS: usize = ANVIL_GAME_COMMAND_MAX_UNITS as usize;
pub const MAX_PER_FRAME: u32 = ANVIL_GAME_COMMAND_MAX_PER_FRAME;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Posted {
pub posted: u32,
pub skipped: u32,
pub refused: u32,
}
#[derive(Clone, Copy)]
pub struct Commands {
table: &'static AnvilGameCommandsService,
plugin: *mut AnvilPlugin,
version: u32,
}
unsafe impl Send for Commands {}
unsafe impl Sync for Commands {}
impl fmt::Debug for Commands {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Commands")
.field("size", &self.table.size)
.finish()
}
}
fn raw_ref(unit: &UnitRef) -> AnvilGameUnitRef {
AnvilGameUnitRef {
id: unit.id,
country: unit
.country
.map(|tag| tag.to_raw())
.unwrap_or(crate::sys::AnvilGameTag { text: [0; 4] }),
kind: match unit.kind {
UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
UnitKind::Other(other) => other,
},
}
}
impl Commands {
pub fn get(host: &Host) -> Option<Self> {
[VERSION, 2, 1].into_iter().find_map(|version| {
let table = unsafe { host.service::<AnvilGameCommandsService>(SERVICE, version) }?;
Some(Self {
table,
plugin: host.raw_plugin(),
version,
})
})
}
pub fn version(&self) -> u32 {
self.version
}
pub fn c_api(&self) -> &'static AnvilGameCommandsService {
self.table
}
fn post(&self, kind: u32, flags: u32, units: &[UnitRef], what: &str) -> Result<Posted> {
self.post_with(kind, flags, units, 0, 0, what)
}
fn post_with(
&self,
kind: u32,
flags: u32,
units: &[UnitRef],
explore: i32,
province: i32,
what: &str,
) -> Result<Posted> {
let raw: Vec<AnvilGameUnitRef> = units.iter().map(raw_ref).collect();
let command = AnvilGameCommand {
size: if self.version >= 2 {
size_of::<AnvilGameCommand>()
} else {
std::mem::offset_of!(AnvilGameCommand, pending_event_id)
} as u32,
type_: kind,
flags,
count: u32::try_from(raw.len()).unwrap_or(u32::MAX),
units: if raw.is_empty() {
std::ptr::null()
} else {
raw.as_ptr()
},
pending_event_id: 0,
option_index: 0,
speed: 0,
explore,
province,
};
self.send(&command, what, units.len())
}
fn send(&self, command: &AnvilGameCommand, what: &str, units: usize) -> Result<Posted> {
let f = function!(self.table, AnvilGameCommandsService, post)?;
let mut out = AnvilGameCommandResult {
size: size_of::<AnvilGameCommandResult>() as u32,
posted: 0,
skipped: 0,
refused: 0,
};
check(unsafe { f(self.plugin, command, &mut out) }, || {
format!("commands {what} ({units} units)")
})?;
Ok(Posted {
posted: out.posted,
skipped: out.skipped,
refused: out.refused,
})
}
pub fn drill(&self, armies: &[UnitRef], start: bool) -> Result<Posted> {
let flags = if start { ANVIL_GAME_COMMAND_START } else { 0 };
self.post(ANVIL_GAME_COMMAND_DRILL, flags, armies, "drill")
}
pub fn merge(&self, units: &[UnitRef]) -> Result<Posted> {
self.post(ANVIL_GAME_COMMAND_MERGE, 0, units, "merge")
}
pub fn split(&self, unit: &UnitRef) -> Result<Posted> {
self.post(
ANVIL_GAME_COMMAND_SPLIT,
0,
std::slice::from_ref(unit),
"split",
)
}
pub fn choose_event_option(&self, pending_event_id: i32, option: i32) -> Result<Posted> {
if self.version < 2 {
return Err(crate::Error::new(
crate::ErrorCode::Unsupported,
"commands event option: anvil-game.commands version 1",
));
}
let command = AnvilGameCommand {
size: size_of::<AnvilGameCommand>() as u32,
type_: ANVIL_GAME_COMMAND_EVENT_OPTION,
flags: 0,
count: 0,
units: std::ptr::null(),
pending_event_id,
option_index: option,
speed: 0,
explore: 0,
province: 0,
};
self.send(&command, "event option", 0)
}
pub fn set_speed(&self, speed: i32) -> Result<Posted> {
if self.version < 3 {
return Err(crate::Error::new(
crate::ErrorCode::Unsupported,
"commands speed: anvil-game.commands before version 3",
));
}
let command = AnvilGameCommand {
size: size_of::<AnvilGameCommand>() as u32,
type_: ANVIL_GAME_COMMAND_SPEED,
flags: 0,
count: 0,
units: std::ptr::null(),
pending_event_id: 0,
option_index: 0,
speed,
explore: 0,
province: 0,
};
self.send(&command, "speed", 0)
}
pub fn explore(&self, units: &[UnitRef], how: Explore) -> Result<Posted> {
self.need_version_3("explore")?;
let mission = match how {
Explore::Stop => ANVIL_GAME_EXPLORE_STOP,
Explore::Land => ANVIL_GAME_EXPLORE_LAND,
Explore::Circumnavigate => ANVIL_GAME_EXPLORE_CIRCUMNAVIGATE,
};
self.post_with(
ANVIL_GAME_COMMAND_EXPLORE,
0,
units,
mission as i32,
0,
"explore",
)
}
pub fn move_to(&self, units: &[UnitRef], province: i32, queue: bool) -> Result<Posted> {
self.need_version_3("move")?;
let flags = if queue { ANVIL_GAME_COMMAND_QUEUE } else { 0 };
self.post_with(ANVIL_GAME_COMMAND_MOVE, flags, units, 0, province, "move")
}
pub fn siege_area(&self, armies: &[UnitRef], province: i32) -> Result<Posted> {
self.need_version_3("siege area")?;
self.post_with(
ANVIL_GAME_COMMAND_SIEGE_AREA,
0,
armies,
0,
province,
"siege area",
)
}
pub fn suppress_area(&self, armies: &[UnitRef], province: i32) -> Result<Posted> {
self.need_version_3("suppress area")?;
self.post_with(
ANVIL_GAME_COMMAND_SUPPRESS_AREA,
0,
armies,
0,
province,
"suppress area",
)
}
fn need_version_3(&self, what: &str) -> Result<()> {
if self.version < 3 {
return Err(crate::Error::new(
crate::ErrorCode::Unsupported,
format!("commands {what}: anvil-game.commands before version 3"),
));
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Explore {
Stop,
Land,
Circumnavigate,
}