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