Skip to main content

anvil/
map.rs

1//! `anvil-map.modes`: map modes of the plugin's own, each a button on the
2//! minimap's list, a colour for each province and lines in the province's
3//! tooltip (`anvil_map.h`).
4//!
5//! Depend on anvil-map in plugin.toml (`[[dependencies]] id = "anvil-map"`,
6//! `version = "^1"`) and look the service up with [`MapModes::get`]. A mode
7//! changes nothing in the game's state, so it needs no
8//! `affects_gameplay = true`.
9//!
10//! The game paints the map and builds tooltips also in frames drawn inside a
11//! game update, where [`World`](crate::world::World) may not be read. So the
12//! plugin computes its colours in a step of its own ([`SHOWN`], a
13//! [`game`](crate::game) event) and hands them over with
14//! [`MapModes::set_colors`]; the map shows the last buffer. Text is UTF-8;
15//! anvil-map writes it in the game's encoding and shows it as written.
16
17use std::ffi::{c_char, c_void, CStr};
18use std::fmt;
19use std::ptr::{self, NonNull};
20use std::sync::atomic::AtomicBool;
21
22use crate::error::{check, Error, ErrorCode, Result};
23use crate::event::{read_sized, Event, Payload};
24use crate::host::Host;
25use crate::panic::run_callback;
26use crate::sys::{
27    AnvilMapMode, AnvilMapModeChange, AnvilMapModeInfo, AnvilMapModesService,
28    ANVIL_MAP_MODES_SERVICE_VERSION, ANVIL_MAP_NO_COLOR, ANVIL_MAP_TAB_1, ANVIL_MAP_TAB_2,
29    ANVIL_MAP_TAB_3, ANVIL_MAP_TAB_4, ANVIL_MAP_TAB_DEFAULT,
30};
31use crate::table::Table;
32use crate::text::{c_string, static_str};
33
34/// The service's name.
35pub const SERVICE: &CStr = c"anvil-map.modes";
36/// The service's major version.
37pub const VERSION: u32 = ANVIL_MAP_MODES_SERVICE_VERSION;
38
39/// The colour that leaves a province as the political map mode shows it
40/// (sea, wasteland and empty land look as players know them).
41pub const NO_COLOR: u32 = ANVIL_MAP_NO_COLOR;
42
43/// A colour, `0x00RRGGBB`.
44pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
45    ((r as u32) << 16) | ((g as u32) << 8) | b as u32
46}
47
48/// The tab of the minimap's list where the mode's button goes, named by the
49/// game's modes it starts with. The buttons of the tabs stand two by two:
50/// political and diplomacy above, trade and terrain below.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum Tab {
53    /// anvil-map's choice: [`Tab::Diplomacy`].
54    #[default]
55    Default,
56    /// Tab 1, from the political mode.
57    Political,
58    /// Tab 2, from the terrain mode.
59    Terrain,
60    /// Tab 3, from the trade mode.
61    Trade,
62    /// Tab 4, from the diplomacy mode.
63    Diplomacy,
64}
65
66impl Tab {
67    const fn raw(self) -> u32 {
68        (match self {
69            Self::Default => ANVIL_MAP_TAB_DEFAULT,
70            Self::Political => ANVIL_MAP_TAB_1,
71            Self::Terrain => ANVIL_MAP_TAB_2,
72            Self::Trade => ANVIL_MAP_TAB_3,
73            Self::Diplomacy => ANVIL_MAP_TAB_4,
74        }) as u32
75    }
76}
77
78/// What [`MapModes::register`] takes. The strings are copied.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct ModeInfo<'a> {
81    /// The tab.
82    pub tab: Tab,
83    /// `<plugin-id>.<name>`: the plugin's own id, `.`, then `[a-z0-9_-]{1,32}`.
84    pub id: &'a str,
85    /// The button's name, 1 to 64 bytes.
86    pub label: &'a str,
87    /// The button's tooltip, at most 512 bytes.
88    pub description: Option<&'a str>,
89    /// A sprite (`GFX_...`) of the game or of the plugin's mod; `None`: an
90    /// empty button frame.
91    pub sprite: Option<&'a str>,
92}
93
94impl<'a> ModeInfo<'a> {
95    /// A mode on the default tab with no description and no sprite.
96    pub const fn new(id: &'a str, label: &'a str) -> Self {
97        Self {
98            tab: Tab::Default,
99            id,
100            label,
101            description: None,
102            sprite: None,
103        }
104    }
105}
106
107/// A registered mode; anvil-map keeps it until the process ends.
108#[derive(Clone, Copy, PartialEq, Eq, Hash)]
109pub struct Mode {
110    raw: NonNull<AnvilMapMode>,
111}
112
113// SAFETY: a mode is never freed, and every service call may come from any
114// thread (anvil_map.h).
115unsafe impl Send for Mode {}
116// SAFETY: as above.
117unsafe impl Sync for Mode {}
118
119impl fmt::Debug for Mode {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.debug_tuple("Mode").field(&self.raw).finish()
122    }
123}
124
125impl Mode {
126    fn from_raw(raw: *const AnvilMapMode) -> Option<Self> {
127        NonNull::new(raw.cast_mut()).map(|raw| Self { raw })
128    }
129
130    /// The raw mode, for the C table.
131    pub fn as_raw(&self) -> *const AnvilMapMode {
132        self.raw.as_ptr()
133    }
134}
135
136/// The payload of [`SHOWN`] and [`HIDDEN`].
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub struct ModeChange {
139    /// The mode.
140    pub mode: Option<Mode>,
141    /// Its id.
142    pub id: Option<&'static str>,
143}
144
145// SAFETY: anvil-map publishes both events with an AnvilMapModeChange whose
146// id lives for the process.
147unsafe impl Payload for ModeChange {
148    unsafe fn read(raw: *const c_void) -> Option<Self> {
149        // SAFETY: the payload of anvil-map.shown or anvil-map.hidden.
150        let change = unsafe { read_sized::<AnvilMapModeChange>(raw) }?;
151        Some(Self {
152            mode: Mode::from_raw(change.mode),
153            // SAFETY: the mode's id, kept with the mode.
154            id: unsafe { static_str(change.id) },
155        })
156    }
157}
158
159/// `anvil-map.shown`: a plugin mode became the map mode shown. On the main
160/// thread after a frame of the main loop, where `World` may be read.
161// SAFETY: anvil-map publishes it with an AnvilMapModeChange.
162pub const SHOWN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.shown") };
163/// `anvil-map.hidden`: a plugin mode stopped being the map mode shown (also at
164/// the end of a session). Published before `shown` of the next one.
165// SAFETY: as above.
166pub const HIDDEN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.hidden") };
167
168/// The `anvil-map.modes` service.
169#[derive(Clone, Copy)]
170pub struct MapModes {
171    table: Table<AnvilMapModesService>,
172}
173
174impl fmt::Debug for MapModes {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.debug_struct("MapModes")
177            .field("size", &self.table.size())
178            .finish()
179    }
180}
181
182struct DescribeAdapter<F> {
183    handler: F,
184    panicked: AtomicBool,
185}
186
187/// `lines` into the C buffer: at most `capacity - 1` bytes, cut at a whole
188/// character and at a NUL, then a terminating zero. Returns the length.
189///
190/// # Safety
191/// `text` has room for `capacity` bytes, `capacity > 0`.
192unsafe fn write_lines(lines: &str, text: *mut c_char, capacity: usize) -> usize {
193    let end = lines.find('\0').unwrap_or(lines.len());
194    let mut length = end.min(capacity - 1);
195    while !lines.is_char_boundary(length) {
196        length -= 1;
197    }
198    // SAFETY: `length` < `capacity` bytes into the caller's buffer.
199    unsafe {
200        ptr::copy_nonoverlapping(lines.as_ptr(), text.cast::<u8>(), length);
201        *text.add(length) = 0;
202    }
203    length
204}
205
206unsafe extern "C" fn describe_adapter<F>(
207    context: *mut c_void,
208    mode: *const AnvilMapMode,
209    province: i32,
210    text: *mut c_char,
211    capacity: usize,
212) -> usize
213where
214    F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
215{
216    // SAFETY: the adapter register_with_tooltip leaked, never freed.
217    let adapter = unsafe { &*context.cast::<DescribeAdapter<F>>() };
218    let Some(mode) = Mode::from_raw(mode) else {
219        return 0;
220    };
221    if text.is_null() || capacity == 0 {
222        return 0;
223    }
224    run_callback("map mode tooltip", &adapter.panicked, 0, || {
225        match (adapter.handler)(mode, province) {
226            // SAFETY: anvil-map's buffer of `capacity` bytes.
227            Some(lines) => unsafe { write_lines(&lines, text, capacity) },
228            None => 0,
229        }
230    })
231}
232
233impl MapModes {
234    /// The service; `None` without anvil-map.
235    pub fn get(host: &Host) -> Option<Self> {
236        // SAFETY: the table type of anvil-map.modes version 1.
237        let table = unsafe { host.service::<AnvilMapModesService>(SERVICE, VERSION) }?;
238        Some(Self { table })
239    }
240
241    /// The C table, for what this crate does not wrap.
242    pub fn c_api(&self) -> Table<AnvilMapModesService> {
243        self.table
244    }
245
246    /// Registers a mode with no lines of its own in the tooltip, which then
247    /// shows the province's name and owner only. A pool of 13 numbers is lent
248    /// in the order modes register: a fourteenth is `Unsupported`, and so is
249    /// any mode when another loader of map modes runs. A taken id is
250    /// `AlreadyExists`; a bad id, label, description or sprite is
251    /// `InvalidArgument`.
252    pub fn register(&self, info: &ModeInfo<'_>) -> Result<Mode> {
253        self.register_raw(info, None, ptr::null_mut())
254    }
255
256    /// Registers a mode whose tooltip lines `describe` gives: for a province
257    /// ID, the lines (separated by `\n`), or `None` for none. It runs on the
258    /// main thread after a frame of the main loop, where `World` may be read,
259    /// for the province under the cursor while the mode is shown; keep it
260    /// short. Text past the buffer anvil-map gives is cut at a whole
261    /// character.
262    pub fn register_with_tooltip<F>(&self, info: &ModeInfo<'_>, describe: F) -> Result<Mode>
263    where
264        F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
265    {
266        // Never freed: anvil-map keeps the mode, and may call it, for the process.
267        let adapter: &'static DescribeAdapter<F> = Box::leak(Box::new(DescribeAdapter {
268            handler: describe,
269            panicked: AtomicBool::new(false),
270        }));
271        self.register_raw(
272            info,
273            Some(describe_adapter::<F>),
274            ptr::from_ref(adapter).cast_mut().cast(),
275        )
276    }
277
278    fn register_raw(
279        &self,
280        info: &ModeInfo<'_>,
281        describe: crate::sys::AnvilMapDescribe,
282        context: *mut c_void,
283    ) -> Result<Mode> {
284        let f = function!(self.table, AnvilMapModesService, register_mode)?;
285        let id = c_string(info.id);
286        let label = c_string(info.label);
287        let description = info.description.map(c_string);
288        let sprite = info.sprite.map(c_string);
289        let raw_info = AnvilMapModeInfo {
290            size: std::mem::size_of::<AnvilMapModeInfo>() as u32,
291            tab: info.tab.raw(),
292            id: id.as_ptr(),
293            label: label.as_ptr(),
294            description: description
295                .as_ref()
296                .map_or(ptr::null(), |text| text.as_ptr()),
297            sprite: sprite.as_ref().map_or(ptr::null(), |text| text.as_ptr()),
298            describe,
299            context,
300        };
301        let mut out: *const AnvilMapMode = ptr::null();
302        // SAFETY: an info whose strings live until the call returns, and an
303        // out pointer; anvil-map copies the strings.
304        check(unsafe { f(&raw_info, &mut out) }, || {
305            format!("map mode register {:?}", info.id)
306        })?;
307        Mode::from_raw(out).ok_or_else(|| {
308            Error::new(
309                ErrorCode::Internal,
310                format!("map mode register {:?}: no mode", info.id),
311            )
312        })
313    }
314
315    /// Hands over the colours of `mode`: `colors[i]` for the province with
316    /// ID `i` (see [`rgb`] and [`NO_COLOR`]); provinces past the slice and
317    /// province 0 keep the political colour. The slice is copied. Only while
318    /// a session runs (`WrongPhase` otherwise, also when it ends during the
319    /// call: the slice is dropped); more entries than the
320    /// session's province limit, or a colour with a top byte other than 0 or
321    /// 0xFF, is `InvalidArgument`.
322    pub fn set_colors(&self, mode: Mode, colors: &[u32]) -> Result<()> {
323        let f = function!(self.table, AnvilMapModesService, set_colors)?;
324        let count = u32::try_from(colors.len()).map_err(|_| {
325            Error::new(
326                ErrorCode::InvalidArgument,
327                "map mode set_colors: too many colours",
328            )
329        })?;
330        // SAFETY: the mode and `count` colours valid during the call.
331        check(unsafe { f(mode.as_raw(), colors.as_ptr(), count) }, || {
332            "map mode set_colors"
333        })
334    }
335
336    /// The id of the plugin mode that borrowed `number`, a value of the
337    /// game's map mode enum; `None` for the game's own modes.
338    pub fn mode_id(&self, number: i32) -> Option<&'static str> {
339        let f = function!(self.table, AnvilMapModesService, mode_id).ok()?;
340        // SAFETY: the service's function; the id lives for the process.
341        unsafe { static_str(f(number)) }
342    }
343
344    /// The plugin mode shown on the map as of anvil-map's last step.
345    pub fn shown(&self) -> Option<Mode> {
346        let f = function!(self.table, AnvilMapModesService, shown).ok()?;
347        // SAFETY: the service's function.
348        Mode::from_raw(unsafe { f() })
349    }
350
351    /// The id of `mode`.
352    pub fn id(&self, mode: Mode) -> Option<&'static str> {
353        let f = function!(self.table, AnvilMapModesService, id).ok()?;
354        // SAFETY: the service's function with its mode; the id lives for the process.
355        unsafe { static_str(f(mode.as_raw())) }
356    }
357
358    /// Shows `mode` on the map, as its button does: anvil-map sets it in its
359    /// next step, and `anvil-map.shown` follows there. Any thread while a
360    /// session runs (`WrongPhase` otherwise); `Unsupported` with an older
361    /// anvil-map or without its hooks.
362    pub fn show(&self, mode: Mode) -> Result<()> {
363        let f = function!(self.table, AnvilMapModesService, show)?;
364        // SAFETY: the service's function with its mode.
365        check(unsafe { f(mode.as_raw()) }, || "map mode show")
366    }
367}