Skip to main content

anvil/
world.rs

1//! `anvil-game.world`: the world of the running session, read straight from
2//! the game (anvil-game 1.11.0; modifiers, units and the selection 1.15.0;
3//! rulers, heirs, consorts, flags and variables 1.20.0; pending events,
4//! statistics and timed modifiers 1.21.0; diplomacy 1.22.0).
5//!
6//! **Thread.** Call it only on the game's main thread after an outer frame:
7//! from a handler of an anvil-game event ([`game`](crate::game)) or from
8//! [`Game::run_on_main_thread`](crate::game::Game::run_on_main_thread) work,
9//! or from a panel click. Anywhere else, and outside a session, a call answers
10//! [`ErrorCode::WrongPhase`] and reads nothing.
11//!
12//! **Results.** [`ErrorCode::NotFound`] for an unknown province ID, tag, war
13//! or unit; [`ErrorCode::NotDeclared`] for a group of calls whose symbols a
14//! port declared absent; [`ErrorCode::Unsupported`] for a call the running
15//! anvil-game is too old to have.
16//!
17//! **What it shows.** Everything, also under terra incognita and in
18//! multiplayer, where that is more than the player sees. A read changes
19//! nothing, so it cannot cause a desync. Values marked "× 1000" are as the
20//! game stores them, as [`Milli`].
21//!
22//! [`ErrorCode::WrongPhase`]: crate::ErrorCode::WrongPhase
23//! [`ErrorCode::NotFound`]: crate::ErrorCode::NotFound
24//! [`ErrorCode::NotDeclared`]: crate::ErrorCode::NotDeclared
25//! [`ErrorCode::Unsupported`]: crate::ErrorCode::Unsupported
26
27use std::fmt;
28use std::mem::size_of;
29
30use crate::error::{check, Error, ErrorCode, Result};
31use crate::game::Date;
32use crate::host::Host;
33use crate::sys::{
34    AnvilGameCountry, AnvilGameDate, AnvilGameDiplomacyStatus, AnvilGameFlag, AnvilGameMonarch,
35    AnvilGamePendingEvent, AnvilGamePlayer, AnvilGameProvince, AnvilGameRelation,
36    AnvilGameStatisticPoint, AnvilGameTag, AnvilGameTimedModifier, AnvilGameUnit, AnvilGameUnitRef,
37    AnvilGameWar, AnvilGameWorldService, ANVIL_GAME_COUNTRY_OBSERVER, ANVIL_GAME_DIPLOMACY_TRUCE,
38    ANVIL_GAME_EXPLORE_COAST, ANVIL_GAME_EXPLORE_SEA, ANVIL_GAME_MONARCH_CONSORT,
39    ANVIL_GAME_MONARCH_FEMALE, ANVIL_GAME_MONARCH_HEIR, ANVIL_GAME_MONARCH_REGENCY,
40    ANVIL_GAME_MONARCH_RULER, ANVIL_GAME_PENDING_HIDDEN, ANVIL_GAME_PLAYER_OBSERVER,
41    ANVIL_GAME_PROVINCE_CITY, ANVIL_GAME_PROVINCE_COASTAL, ANVIL_GAME_PROVINCE_HRE,
42    ANVIL_GAME_PROVINCE_LAND, ANVIL_GAME_PROVINCE_STATE, ANVIL_GAME_PROVINCE_VALUE_DEVASTATION,
43    ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY, ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER,
44    ANVIL_GAME_PROVINCE_WASTELAND, ANVIL_GAME_RELATION_ALLIANCE, ANVIL_GAME_RELATION_DEPENDENCY,
45    ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS, ANVIL_GAME_RELATION_GUARANTEE,
46    ANVIL_GAME_RELATION_MILITARY_ACCESS, ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
47    ANVIL_GAME_RELATION_SUBSIDIES, ANVIL_GAME_RELATION_WARNING, ANVIL_GAME_STATISTIC_INCOME,
48    ANVIL_GAME_STATISTIC_INFLATION, ANVIL_GAME_STATISTIC_NATION_SIZE, ANVIL_GAME_STATISTIC_SCORE,
49    ANVIL_GAME_TIMED_HIDDEN, ANVIL_GAME_TIMED_NO_END, ANVIL_GAME_TIMED_NO_START,
50    ANVIL_GAME_TIMED_RULER, ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY, ANVIL_GAME_VALUE_MANPOWER,
51    ANVIL_GAME_VALUE_MONTHLY_INCOME, ANVIL_GAME_VALUE_PRESTIGE, ANVIL_GAME_VALUE_STABILITY,
52    ANVIL_GAME_VALUE_TREASURY, ANVIL_GAME_WAR_ATTACKERS, ANVIL_GAME_WAR_DEFENDERS,
53    ANVIL_GAME_WORLD_SERVICE_VERSION,
54};
55use crate::table::Table;
56use crate::text::{read_list, read_text, Tag};
57
58/// The service's name.
59pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
60/// The service's major version.
61pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;
62
63/// A value the game stores × 1000: `Milli(4500)` is 4.5.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
65pub struct Milli(pub i32);
66
67impl Milli {
68    /// The value as a float.
69    pub fn get(self) -> f64 {
70        f64::from(self.0) / 1000.0
71    }
72}
73
74impl fmt::Display for Milli {
75    /// With up to three decimals, trailing zeros dropped: `4.5`, `-12`, `0.125`.
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let sign = if self.0 < 0 { "-" } else { "" };
78        let value = self.0.unsigned_abs();
79        let (whole, part) = (value / 1000, value % 1000);
80        if part == 0 {
81            return write!(f, "{sign}{whole}");
82        }
83        let decimals = format!("{part:03}");
84        write!(f, "{sign}{whole}.{}", decimals.trim_end_matches('0'))
85    }
86}
87
88/// A province.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Province {
91    /// Its ID.
92    pub id: i32,
93    /// Its owner; `None` for none.
94    pub owner: Option<Tag>,
95    /// Its controller.
96    pub controller: Option<Tag>,
97    /// Base tax, without the capital's bonus.
98    pub base_tax: Milli,
99    /// Base production.
100    pub base_production: Milli,
101    /// Base manpower.
102    pub base_manpower: Milli,
103    /// Not a sea or a lake.
104    pub land: bool,
105    /// A wasteland.
106    pub wasteland: bool,
107    /// Part of the Holy Roman Empire (anvil-game 1.26.0; `false` before).
108    pub hre: bool,
109    /// A city, not a colony (anvil-game 1.26.0; `false` before).
110    pub city: bool,
111    /// Land the game counts as coastal (anvil-game 1.26.0; `false` before).
112    pub coastal: bool,
113    /// In a state of its owner's, not a territory (anvil-game 1.27.0; `false` before).
114    pub state: bool,
115    /// Local autonomy as the game shows it (anvil-game 1.27.0; `None` before or on a build without it).
116    pub local_autonomy: Option<Milli>,
117    /// Devastation (anvil-game 1.27.0).
118    pub devastation: Option<Milli>,
119    /// Its trade power in its trade node, as of the game's last update (anvil-game 1.27.0).
120    pub trade_power: Option<Milli>,
121}
122
123/// A country. A value this game build does not have is `None`.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct Country {
126    /// Its tag.
127    pub tag: Option<Tag>,
128    /// Its capital province; `None` for none.
129    pub capital: Option<i32>,
130    /// The provinces it owns; above 0 when it exists on the map.
131    pub province_count: i32,
132    /// The observer's pseudo-country.
133    pub observer: bool,
134    /// Ducats.
135    pub treasury: Option<Milli>,
136    /// Stability.
137    pub stability: Option<Milli>,
138    /// Prestige.
139    pub prestige: Option<Milli>,
140    /// Manpower in the game's thousands: `Milli(25000)` is 25 000 men.
141    pub manpower: Option<Milli>,
142    /// The income total of the economy view, before expenses, as of the last
143    /// monthly update.
144    pub monthly_income: Option<Milli>,
145}
146
147/// A running war.
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub struct War {
150    /// Its id: the same while the war runs (a later war may reuse it).
151    pub id: u64,
152    /// Who started it.
153    pub attacker: Option<Tag>,
154    /// Whom it was declared on.
155    pub defender: Option<Tag>,
156}
157
158/// A side of a war.
159#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
160pub enum Side {
161    /// The attacker and its allies.
162    Attackers,
163    /// The defender and its allies.
164    Defenders,
165}
166
167/// An army or a navy.
168#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
169pub enum UnitKind {
170    /// An army.
171    Army,
172    /// A navy.
173    Navy,
174    /// A value this crate does not know.
175    Other(u32),
176}
177
178impl UnitKind {
179    fn from_raw(kind: u32) -> Self {
180        match kind {
181            ANVIL_GAME_UNIT_ARMY => Self::Army,
182            ANVIL_GAME_UNIT_NAVY => Self::Navy,
183            other => Self::Other(other),
184        }
185    }
186}
187
188/// What a unit does on its own, by the game's numbers (`ANVIL_GAME_MISSION_*`).
189#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
190pub struct Mission(pub i32);
191
192impl Mission {
193    /// Not one the service could read.
194    pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
195    /// No mission: the player moves it.
196    pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
197    /// Besiege the enemy's provinces on its own.
198    pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
199    /// Hunt rebels.
200    pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
201    /// Drill.
202    pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
203}
204
205/// A unit: an army or a navy.
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207pub struct Unit {
208    /// Army or navy.
209    pub kind: UnitKind,
210    /// The game's id: the same while the unit exists.
211    pub id: u64,
212    /// The country it belongs to.
213    pub country: Option<Tag>,
214    /// The province it is in or at; `None` for none.
215    pub location: Option<i32>,
216    /// What it does on its own.
217    pub mission: Mission,
218    /// Regiments or ships.
219    pub subunits: u32,
220    /// The sum of the regiments' or ships' strength (men for an army).
221    pub strength: Milli,
222    /// Its leader's id; `None` for no leader.
223    pub leader: Option<u64>,
224}
225
226/// One unit of the player's selection.
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub struct UnitRef {
229    /// The unit's id.
230    pub id: u64,
231    /// The country it belongs to (a player may select units of others to look).
232    pub country: Option<Tag>,
233    /// Army or navy.
234    pub kind: UnitKind,
235}
236
237impl UnitRef {
238    pub(crate) fn to_raw(self) -> AnvilGameUnitRef {
239        AnvilGameUnitRef {
240            id: self.id,
241            country: self
242                .country
243                .map(|tag| tag.to_raw())
244                .unwrap_or(AnvilGameTag { text: [0; 4] }),
245            kind: match self.kind {
246                UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
247                UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
248                UnitKind::Other(other) => other,
249            },
250        }
251    }
252}
253
254/// Which list of the naval exploration dialog [`World::exploration_regions`]
255/// reads (anvil-game 1.25.0).
256#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
257pub enum ExplorationList {
258    /// The regions a coast exploration may take.
259    Coast,
260    /// The regions a sea exploration may take.
261    Sea,
262}
263
264impl ExplorationList {
265    fn raw(self) -> i32 {
266        match self {
267            Self::Coast => ANVIL_GAME_EXPLORE_COAST as i32,
268            Self::Sea => ANVIL_GAME_EXPLORE_SEA as i32,
269        }
270    }
271}
272
273/// The id of a modifier, from its script key ([`World::modifier_id`]).
274#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
275pub struct ModifierId(pub i32);
276
277/// A country's ruler, heir or consort (anvil-game 1.20.0).
278#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
279pub enum MonarchKind {
280    /// The ruler.
281    Ruler,
282    /// The heir.
283    Heir,
284    /// The consort.
285    Consort,
286}
287
288impl MonarchKind {
289    fn raw(self) -> u32 {
290        match self {
291            Self::Ruler => ANVIL_GAME_MONARCH_RULER,
292            Self::Heir => ANVIL_GAME_MONARCH_HEIR,
293            Self::Consort => ANVIL_GAME_MONARCH_CONSORT,
294        }
295    }
296
297    fn from_raw(kind: u32) -> Self {
298        match kind {
299            ANVIL_GAME_MONARCH_HEIR => Self::Heir,
300            ANVIL_GAME_MONARCH_CONSORT => Self::Consort,
301            _ => Self::Ruler,
302        }
303    }
304}
305
306/// A ruler, heir or consort, as the game stores them.
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub struct Monarch {
309    /// Ruler, heir or consort.
310    pub kind: MonarchKind,
311    /// The game's id of the person.
312    pub id: u64,
313    /// The country asked about.
314    pub country: Option<Tag>,
315    /// Female.
316    pub female: bool,
317    /// A regency council or a regent rules for them.
318    pub regency: bool,
319    /// Administrative skill, without modifiers.
320    pub adm: i32,
321    /// Diplomatic skill.
322    pub dip: i32,
323    /// Military skill.
324    pub mil: i32,
325    /// An heir's claim strength; 0 for a ruler or a consort.
326    pub claim: Milli,
327    /// The birth date.
328    pub birth: Date,
329    /// The id of the leader they also are ([`Unit::leader`]); `None` for none.
330    pub leader: Option<u64>,
331}
332
333/// The id of a flag, from its name ([`World::flag_id`]).
334#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
335pub struct FlagId(pub i32);
336
337/// A flag that is set, and when it was set.
338#[derive(Clone, Copy, Debug, PartialEq, Eq)]
339pub struct Flag {
340    /// Its id; [`World::flag_name`] gives the name.
341    pub id: FlagId,
342    /// When it was set.
343    pub date: Date,
344}
345
346/// An event waiting for a country's choice (anvil-game 1.21.0).
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
348pub struct PendingEvent {
349    /// The id [`commands`](crate::commands)' event option takes; unique while it waits.
350    pub pending_id: i32,
351    /// The country it waits for, by the game's rule; `None` for none.
352    pub country: Option<Tag>,
353    /// The scope's province; `None` for a country event.
354    pub province: Option<i32>,
355    /// The event's options in its file; the window may disable some.
356    pub options: u32,
357    /// Hidden: the game shows no window for it.
358    pub hidden: bool,
359    /// The game chooses for the player the day after this date.
360    pub auto_select: Date,
361}
362
363/// One of the four series of the game's graphs (anvil-game 1.21.0).
364#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
365pub enum StatisticKind {
366    /// The income graph, whole ducats (the game's value ÷ 1000, truncated).
367    Income,
368    /// The score, whole points (÷ 1000, truncated).
369    Score,
370    /// The provinces the country owns, a count.
371    NationSize,
372    /// Inflation, whole percent (÷ 1000, truncated).
373    Inflation,
374}
375
376impl StatisticKind {
377    fn raw(self) -> u32 {
378        match self {
379            Self::Income => ANVIL_GAME_STATISTIC_INCOME,
380            Self::Score => ANVIL_GAME_STATISTIC_SCORE,
381            Self::NationSize => ANVIL_GAME_STATISTIC_NATION_SIZE,
382            Self::Inflation => ANVIL_GAME_STATISTIC_INFLATION,
383        }
384    }
385}
386
387/// One year of a series. The value is whole units, not × 1000.
388#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
389pub struct StatisticPoint {
390    /// The year whose 1 January wrote it: 1720 holds the value at the end of 1719.
391    pub year: i32,
392    /// The value then (0 for a year before the country had one).
393    pub value: i32,
394}
395
396/// A named modifier a country or a province has for a time, as an effect such
397/// as `add_country_modifier` gave it ([`World::country_timed_modifiers`]).
398#[derive(Clone, Debug, PartialEq, Eq)]
399pub struct TimedModifier {
400    /// Its key, as the game's files write it.
401    pub key: String,
402    /// `hidden = yes`: the game's windows do not list it.
403    pub hidden: bool,
404    /// A ruler modifier: it goes with the ruler.
405    pub ruler: bool,
406    /// When it was given; `None` when the game keeps no start date.
407    pub start: Option<Date>,
408    /// When it ends; `None` when it lasts until an effect removes it.
409    pub end: Option<Date>,
410}
411
412/// A kind of relation between two countries (anvil-game 1.22.0). A relation
413/// is one object in both countries' lists: who did what comes from
414/// [`Relation::first`] and [`Relation::second`], never from whose list it is.
415#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
416pub enum RelationKind {
417    /// An alliance.
418    Alliance,
419    /// A royal marriage.
420    RoyalMarriage,
421    /// `first` guarantees `second`.
422    Guarantee,
423    /// The country asked is `first`: it has access to `second`'s land.
424    MilitaryAccess,
425    /// The country asked is `second`: it gives `first` access.
426    GivingMilitaryAccess,
427    /// `first` pays `second`.
428    Subsidies,
429    /// `first` is the overlord, `second` the subject ([`World::subject_type`]).
430    Dependency,
431    /// `first` warns `second`.
432    Warning,
433}
434
435impl RelationKind {
436    fn raw(self) -> u32 {
437        match self {
438            Self::Alliance => ANVIL_GAME_RELATION_ALLIANCE,
439            Self::RoyalMarriage => ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
440            Self::Guarantee => ANVIL_GAME_RELATION_GUARANTEE,
441            Self::MilitaryAccess => ANVIL_GAME_RELATION_MILITARY_ACCESS,
442            Self::GivingMilitaryAccess => ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS,
443            Self::Subsidies => ANVIL_GAME_RELATION_SUBSIDIES,
444            Self::Dependency => ANVIL_GAME_RELATION_DEPENDENCY,
445            Self::Warning => ANVIL_GAME_RELATION_WARNING,
446        }
447    }
448}
449
450/// A relation, as the game's save writes it ([`World::country_relations`]).
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub struct Relation {
453    /// The guarantor, the one with access, the payer, the overlord, the one who warns.
454    pub first: Option<Tag>,
455    /// The other one.
456    pub second: Option<Tag>,
457    /// When it began; `None` when the game keeps no date.
458    pub start: Option<Date>,
459    /// When it ends; `None` for most, which have no end date.
460    pub end: Option<Date>,
461}
462
463/// The player's tags ([`World::player_tags`]).
464#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465pub struct PlayerTags {
466    /// The country the game treats as the player's: what [`World::player`] answers.
467    pub tag: Option<Tag>,
468    /// The player's own tag as the game stores it: the observer's
469    /// pseudo-country in observe mode.
470    pub own: Option<Tag>,
471    /// The observed country as the game stores it.
472    pub observed: Option<Tag>,
473    /// `own` is the observer's pseudo-country: observe mode.
474    pub observer: bool,
475}
476
477/// What one country keeps about another ([`World::diplomacy_status`]).
478#[derive(Clone, Copy, Debug, PartialEq, Eq)]
479pub struct DiplomacyStatus {
480    /// Its opinion of the other, whole points: the number of the diplomacy
481    /// window as the game's cache holds it, refreshed at least monthly for a
482    /// human and yearly for an AI.
483    pub opinion: i32,
484    /// The sum of its timed opinion modifiers toward the other, whole points,
485    /// not clamped: not the opinion.
486    pub timed_sum: i32,
487    /// Trust, 0..100; 50 until something changes it.
488    pub trust: u32,
489    /// Favors, × 1000.
490    pub favors: Milli,
491    /// The two have a truce (its end date is the game's to work out).
492    pub truce: bool,
493}
494
495/// The `anvil-game.world` service.
496#[derive(Clone, Copy)]
497pub struct World {
498    table: Table<AnvilGameWorldService>,
499}
500
501impl fmt::Debug for World {
502    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503        f.debug_struct("World")
504            .field("size", &self.table.size())
505            .finish()
506    }
507}
508
509fn sized<T>() -> T {
510    // SAFETY: the world's structs are plain data for which zero is valid.
511    let mut value: T = unsafe { std::mem::zeroed() };
512    let size = size_of::<T>() as u32;
513    // SAFETY: each of them starts with `uint32_t size`.
514    unsafe { std::ptr::from_mut(&mut value).cast::<u32>().write(size) };
515    value
516}
517
518fn known(value: i32, values: u32, bit: u32) -> Option<Milli> {
519    (values & bit != 0).then_some(Milli(value))
520}
521
522const EMPTY_TAG: AnvilGameTag = AnvilGameTag { text: [0; 4] };
523
524impl World {
525    /// The service; `None` without anvil-game 1.11.0 or on a game build whose
526    /// symbols for it are declared absent.
527    pub fn get(host: &Host) -> Option<Self> {
528        // SAFETY: the table type of anvil-game.world version 1.
529        let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
530        Some(Self { table })
531    }
532
533    /// The C table, for what this crate does not wrap.
534    pub fn c_api(&self) -> Table<AnvilGameWorldService> {
535        self.table
536    }
537
538    /// The country the game treats as the player's (the observed one in observe mode).
539    pub fn player(&self) -> Result<Option<Tag>> {
540        let f = function!(self.table, AnvilGameWorldService, player)?;
541        let mut tag = EMPTY_TAG;
542        // SAFETY: the service's function with an out pointer.
543        check(unsafe { f(&mut tag) }, || "world player")?;
544        Ok(Tag::from_raw(&tag))
545    }
546
547    /// Valid province IDs are `1..limit`; 0 where a call is not allowed.
548    pub fn province_limit(&self) -> i32 {
549        // SAFETY: the service's function.
550        function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
551    }
552
553    /// A province.
554    pub fn province(&self, id: i32) -> Result<Province> {
555        let f = function!(self.table, AnvilGameWorldService, province)?;
556        let mut raw: AnvilGameProvince = sized();
557        // SAFETY: the service's function; `size` says how much it may write.
558        check(unsafe { f(id, &mut raw) }, || {
559            format!("world province {id}")
560        })?;
561        Ok(Province {
562            id: raw.id,
563            owner: Tag::from_raw(&raw.owner),
564            controller: Tag::from_raw(&raw.controller),
565            base_tax: Milli(raw.base_tax),
566            base_production: Milli(raw.base_production),
567            base_manpower: Milli(raw.base_manpower),
568            land: raw.flags & ANVIL_GAME_PROVINCE_LAND != 0,
569            wasteland: raw.flags & ANVIL_GAME_PROVINCE_WASTELAND != 0,
570            hre: raw.flags & ANVIL_GAME_PROVINCE_HRE != 0,
571            city: raw.flags & ANVIL_GAME_PROVINCE_CITY != 0,
572            coastal: raw.flags & ANVIL_GAME_PROVINCE_COASTAL != 0,
573            state: raw.flags & ANVIL_GAME_PROVINCE_STATE != 0,
574            local_autonomy: (raw.values & ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY != 0)
575                .then_some(Milli(raw.local_autonomy)),
576            devastation: (raw.values & ANVIL_GAME_PROVINCE_VALUE_DEVASTATION != 0)
577                .then_some(Milli(raw.devastation)),
578            trade_power: (raw.values & ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER != 0)
579                .then_some(Milli(raw.trade_power)),
580        })
581    }
582
583    /// The name the game displays (it follows the owner's culture).
584    pub fn province_name(&self, id: i32) -> Result<String> {
585        let f = function!(self.table, AnvilGameWorldService, province_name)?;
586        // SAFETY: the service fills at most `capacity` bytes.
587        read_text(
588            || format!("world province_name {id}"),
589            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
590        )
591    }
592
593    /// The tags with a core on the province.
594    pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
595        let f = function!(self.table, AnvilGameWorldService, province_cores)?;
596        // SAFETY: the service fills at most `capacity` tags.
597        let raw = read_list(
598            EMPTY_TAG,
599            || format!("world province_cores {id}"),
600            |out, capacity, count| unsafe { f(id, out, capacity, count) },
601        )?;
602        Ok(raw.iter().filter_map(Tag::from_raw).collect())
603    }
604
605    /// A country (the tag ignores case).
606    pub fn country(&self, tag: Tag) -> Result<Country> {
607        let f = function!(self.table, AnvilGameWorldService, country)?;
608        let text = tag.c_text();
609        let mut raw: AnvilGameCountry = sized();
610        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
611        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
612            format!("world country {tag}")
613        })?;
614        let v = raw.values;
615        Ok(Country {
616            tag: Tag::from_raw(&raw.tag),
617            capital: (raw.capital != 0).then_some(raw.capital),
618            province_count: raw.province_count,
619            observer: raw.flags & ANVIL_GAME_COUNTRY_OBSERVER != 0,
620            treasury: known(raw.treasury, v, ANVIL_GAME_VALUE_TREASURY),
621            stability: known(raw.stability, v, ANVIL_GAME_VALUE_STABILITY),
622            prestige: known(raw.prestige, v, ANVIL_GAME_VALUE_PRESTIGE),
623            manpower: known(raw.manpower, v, ANVIL_GAME_VALUE_MANPOWER),
624            monthly_income: known(raw.monthly_income, v, ANVIL_GAME_VALUE_MONTHLY_INCOME),
625        })
626    }
627
628    /// The IDs of the provinces a country owns, in the game's order.
629    pub fn country_provinces(&self, tag: Tag) -> Result<Vec<i32>> {
630        let f = function!(self.table, AnvilGameWorldService, country_provinces)?;
631        let text = tag.c_text();
632        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` IDs.
633        read_list(
634            0i32,
635            || format!("world country_provinces {tag}"),
636            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
637        )
638    }
639
640    /// The ids of the running wars.
641    pub fn war_ids(&self) -> Result<Vec<u64>> {
642        let f = function!(self.table, AnvilGameWorldService, war_ids)?;
643        // SAFETY: the service fills at most `capacity` ids.
644        read_list(
645            0u64,
646            || "world war_ids".to_owned(),
647            |out, capacity, count| unsafe { f(out, capacity, count) },
648        )
649    }
650
651    /// A running war.
652    pub fn war(&self, id: u64) -> Result<War> {
653        let f = function!(self.table, AnvilGameWorldService, war)?;
654        let mut raw: AnvilGameWar = sized();
655        // SAFETY: `size` says how much it may write.
656        check(unsafe { f(id, &mut raw) }, || format!("world war {id:#x}"))?;
657        Ok(War {
658            id: raw.id,
659            attacker: Tag::from_raw(&raw.attacker),
660            defender: Tag::from_raw(&raw.defender),
661        })
662    }
663
664    /// A war's name as the game shows it.
665    pub fn war_name(&self, id: u64) -> Result<String> {
666        let f = function!(self.table, AnvilGameWorldService, war_name)?;
667        // SAFETY: the service fills at most `capacity` bytes.
668        read_text(
669            || format!("world war_name {id:#x}"),
670            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
671        )
672    }
673
674    /// The countries on one side of a war now.
675    pub fn war_side(&self, id: u64, side: Side) -> Result<Vec<Tag>> {
676        let f = function!(self.table, AnvilGameWorldService, war_side)?;
677        let side_raw = match side {
678            Side::Attackers => ANVIL_GAME_WAR_ATTACKERS,
679            Side::Defenders => ANVIL_GAME_WAR_DEFENDERS,
680        };
681        // SAFETY: the service fills at most `capacity` tags.
682        let raw = read_list(
683            EMPTY_TAG,
684            || format!("world war_side {id:#x}"),
685            |out, capacity, count| unsafe { f(id, side_raw, out, capacity, count) },
686        )?;
687        Ok(raw.iter().filter_map(Tag::from_raw).collect())
688    }
689
690    /// The id of a modifier from its script key (`land_morale`,
691    /// `local_tax_modifier`), case included. It holds as long as the game
692    /// runs: ask once, as this walks every definition.
693    pub fn modifier_id(&self, key: &str) -> Result<ModifierId> {
694        let f = function!(self.table, AnvilGameWorldService, modifier_id)?;
695        let key_c = crate::text::c_string(key);
696        let mut id = 0i32;
697        // SAFETY: a NUL-terminated key and an out pointer.
698        check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
699            format!("world modifier_id {key}")
700        })?;
701        Ok(ModifierId(id))
702    }
703
704    /// A country's modifier as the game uses it (a yes-or-no one is 1000 or 0).
705    pub fn country_modifier(&self, tag: Tag, id: ModifierId) -> Result<Milli> {
706        let f = function!(self.table, AnvilGameWorldService, country_modifier)?;
707        let text = tag.c_text();
708        let mut value = 0i32;
709        // SAFETY: a NUL-terminated tag and an out pointer.
710        check(unsafe { f(text.as_ptr(), id.0, &mut value) }, || {
711            format!("world country_modifier {tag} {}", id.0)
712        })?;
713        Ok(Milli(value))
714    }
715
716    /// A province's own modifier (not its owner's values).
717    pub fn province_modifier(&self, province: i32, id: ModifierId) -> Result<Milli> {
718        let f = function!(self.table, AnvilGameWorldService, province_modifier)?;
719        let mut value = 0i32;
720        // SAFETY: an out pointer.
721        check(unsafe { f(province, id.0, &mut value) }, || {
722            format!("world province_modifier {province} {}", id.0)
723        })?;
724        Ok(Milli(value))
725    }
726
727    /// The ids of a country's armies and navies, in the game's order.
728    pub fn country_units(&self, tag: Tag) -> Result<Vec<u64>> {
729        let f = function!(self.table, AnvilGameWorldService, country_units)?;
730        let text = tag.c_text();
731        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` ids.
732        read_list(
733            0u64,
734            || format!("world country_units {tag}"),
735            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
736        )
737    }
738
739    /// A unit by its country and id.
740    pub fn unit(&self, tag: Tag, id: u64) -> Result<Unit> {
741        let f = function!(self.table, AnvilGameWorldService, unit)?;
742        let text = tag.c_text();
743        let mut raw: AnvilGameUnit = sized();
744        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
745        check(unsafe { f(text.as_ptr(), id, &mut raw) }, || {
746            format!("world unit {tag} {id:#x}")
747        })?;
748        Ok(Unit {
749            kind: UnitKind::from_raw(raw.kind),
750            id: raw.id,
751            country: Tag::from_raw(&raw.country),
752            location: (raw.location != 0).then_some(raw.location),
753            mission: Mission(raw.mission),
754            subunits: raw.subunits,
755            strength: Milli(raw.strength),
756            leader: (raw.leader != 0).then_some(raw.leader),
757        })
758    }
759
760    /// The name the game shows for a unit ("1st Army").
761    pub fn unit_name(&self, tag: Tag, id: u64) -> Result<String> {
762        let f = function!(self.table, AnvilGameWorldService, unit_name)?;
763        let text = tag.c_text();
764        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
765        read_text(
766            || format!("world unit_name {tag} {id:#x}"),
767            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
768        )
769    }
770
771    /// A unit's leader's name; `NotFound` also for a unit without one.
772    pub fn unit_leader_name(&self, tag: Tag, id: u64) -> Result<String> {
773        let f = function!(self.table, AnvilGameWorldService, unit_leader_name)?;
774        let text = tag.c_text();
775        // SAFETY: as in unit_name.
776        read_text(
777            || format!("world unit_leader_name {tag} {id:#x}"),
778            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
779        )
780    }
781
782    /// The armies and navies the player has selected, in the game's order.
783    pub fn selected_units(&self) -> Result<Vec<UnitRef>> {
784        let f = function!(self.table, AnvilGameWorldService, selected_units)?;
785        let empty = AnvilGameUnitRef {
786            id: 0,
787            country: EMPTY_TAG,
788            kind: 0,
789        };
790        // SAFETY: the service fills at most `capacity` entries.
791        let raw = read_list(
792            empty,
793            || "world selected_units".to_owned(),
794            |out, capacity, count| unsafe { f(out, capacity, count) },
795        )?;
796        Ok(raw
797            .iter()
798            .map(|r| UnitRef {
799                id: r.id,
800                country: Tag::from_raw(&r.country),
801                kind: UnitKind::from_raw(r.kind),
802            })
803            .collect())
804    }
805
806    /// A country's ruler, heir or consort. `NotFound` when it has none: the
807    /// game then holds a placeholder that every such country shares, and the
808    /// service never reads it. A country no longer on the map keeps its last
809    /// ruler: check [`Country::province_count`] when that matters.
810    pub fn monarch(&self, tag: Tag, kind: MonarchKind) -> Result<Monarch> {
811        let f = function!(self.table, AnvilGameWorldService, monarch)?;
812        let text = tag.c_text();
813        let mut raw: AnvilGameMonarch = sized();
814        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
815        check(unsafe { f(text.as_ptr(), kind.raw(), &mut raw) }, || {
816            format!("world monarch {tag} {kind:?}")
817        })?;
818        Ok(Monarch {
819            kind: MonarchKind::from_raw(raw.kind),
820            id: raw.id,
821            country: Tag::from_raw(&raw.country),
822            female: raw.flags & ANVIL_GAME_MONARCH_FEMALE != 0,
823            regency: raw.flags & ANVIL_GAME_MONARCH_REGENCY != 0,
824            adm: raw.adm,
825            dip: raw.dip,
826            mil: raw.mil,
827            claim: Milli(raw.claim),
828            birth: Date::from_raw(&raw.birth),
829            leader: (raw.leader != 0).then_some(raw.leader),
830        })
831    }
832
833    /// Their name as the game keeps it; empty in an interregnum.
834    pub fn monarch_name(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
835        let f = function!(self.table, AnvilGameWorldService, monarch_name)?;
836        let text = tag.c_text();
837        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
838        read_text(
839            || format!("world monarch_name {tag} {kind:?}"),
840            |buffer, capacity, length| unsafe {
841                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
842            },
843        )
844    }
845
846    /// Their dynasty as the game shows it (a regency council shows the heir's).
847    pub fn monarch_dynasty(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
848        let f = function!(self.table, AnvilGameWorldService, monarch_dynasty)?;
849        let text = tag.c_text();
850        // SAFETY: as in monarch_name.
851        read_text(
852            || format!("world monarch_dynasty {tag} {kind:?}"),
853            |buffer, capacity, length| unsafe {
854                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
855            },
856        )
857    }
858
859    /// The id of a flag from its name, case included. It holds as long as the
860    /// game runs: ask once. `NotFound` for a name nothing has set yet in this
861    /// run of the game.
862    pub fn flag_id(&self, name: &str) -> Result<FlagId> {
863        let f = function!(self.table, AnvilGameWorldService, flag_id)?;
864        let name_c = crate::text::c_string(name);
865        let mut id = 0i32;
866        // SAFETY: a NUL-terminated name and an out pointer.
867        check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
868            format!("world flag_id {name}")
869        })?;
870        Ok(FlagId(id))
871    }
872
873    /// A flag's name.
874    pub fn flag_name(&self, id: FlagId) -> Result<String> {
875        let f = function!(self.table, AnvilGameWorldService, flag_name)?;
876        // SAFETY: the service fills at most `capacity` bytes.
877        read_text(
878            || format!("world flag_name {}", id.0),
879            |buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
880        )
881    }
882
883    /// A country's flags, with the date each was set.
884    pub fn country_flags(&self, tag: Tag) -> Result<Vec<Flag>> {
885        let f = function!(self.table, AnvilGameWorldService, country_flags)?;
886        let text = tag.c_text();
887        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
888        flags(
889            || format!("world country_flags {tag}"),
890            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
891        )
892    }
893
894    /// A province's flags as `has_province_flag` sees them, its permanent ones included.
895    pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
896        let f = function!(self.table, AnvilGameWorldService, province_flags)?;
897        // SAFETY: the service fills at most `capacity` flags.
898        flags(
899            || format!("world province_flags {province}"),
900            |out, capacity, count| unsafe { f(province, out, capacity, count) },
901        )
902    }
903
904    /// A ruler's, heir's or consort's flags; `NotFound` as for [`World::monarch`].
905    pub fn monarch_flags(&self, tag: Tag, kind: MonarchKind) -> Result<Vec<Flag>> {
906        let f = function!(self.table, AnvilGameWorldService, monarch_flags)?;
907        let text = tag.c_text();
908        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
909        flags(
910            || format!("world monarch_flags {tag} {kind:?}"),
911            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
912        )
913    }
914
915    /// The global flags.
916    pub fn global_flags(&self) -> Result<Vec<Flag>> {
917        let f = function!(self.table, AnvilGameWorldService, global_flags)?;
918        // SAFETY: the service fills at most `capacity` flags.
919        flags(
920            || "world global_flags".to_owned(),
921            |out, capacity, count| unsafe { f(out, capacity, count) },
922        )
923    }
924
925    /// A country's variable by its name, case included. `NotFound` when it
926    /// has none of that name (the game's triggers take that as 0).
927    pub fn country_variable(&self, tag: Tag, name: &str) -> Result<Milli> {
928        let f = function!(self.table, AnvilGameWorldService, country_variable)?;
929        let text = tag.c_text();
930        let name_c = crate::text::c_string(name);
931        let mut value = 0i32;
932        // SAFETY: a NUL-terminated tag and name, and an out pointer.
933        let result = unsafe { f(text.as_ptr(), name_c.as_ptr(), &mut value) };
934        check(result, || format!("world country_variable {tag} {name}"))?;
935        Ok(Milli(value))
936    }
937
938    /// A province's variable by its name.
939    pub fn province_variable(&self, province: i32, name: &str) -> Result<Milli> {
940        let f = function!(self.table, AnvilGameWorldService, province_variable)?;
941        let name_c = crate::text::c_string(name);
942        let mut value = 0i32;
943        // SAFETY: a NUL-terminated name and an out pointer.
944        check(unsafe { f(province, name_c.as_ptr(), &mut value) }, || {
945            format!("world province_variable {province} {name}")
946        })?;
947        Ok(Milli(value))
948    }
949
950    /// The names of a country's variables, in the game's order.
951    pub fn country_variable_names(&self, tag: Tag) -> Result<Vec<String>> {
952        let f = function!(self.table, AnvilGameWorldService, country_variable_names)?;
953        let text = tag.c_text();
954        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
955        let all = read_text(
956            || format!("world country_variable_names {tag}"),
957            |buffer, capacity, length| unsafe { f(text.as_ptr(), buffer, capacity, length) },
958        )?;
959        Ok(split_names(&all))
960    }
961
962    /// The names of a province's variables, in the game's order.
963    pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
964        let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
965        // SAFETY: the service fills at most `capacity` bytes.
966        let all = read_text(
967            || format!("world province_variable_names {province}"),
968            |buffer, capacity, length| unsafe { f(province, buffer, capacity, length) },
969        )?;
970        Ok(split_names(&all))
971    }
972
973    /// The ids of the events waiting for a country's choice, in the game's
974    /// order; `None` for the player's own country (`NotFound` in observe
975    /// mode). An entry counts once it was in the game's list at two outer
976    /// frames in a row, which leaves out an AI's choices and hidden events.
977    /// Key on the id: the same event can wait twice.
978    pub fn pending_events(&self, tag: Option<Tag>) -> Result<Vec<i32>> {
979        let f = function!(self.table, AnvilGameWorldService, pending_events)?;
980        let text = tag.map(|t| t.c_text());
981        let tag_ptr = text.as_ref().map_or(std::ptr::null(), |t| t.as_ptr());
982        // SAFETY: a NUL-terminated tag or null; the service fills at most `capacity` ids.
983        read_list(
984            0i32,
985            || format!("world pending_events {tag:?}"),
986            |out, capacity, count| unsafe { f(tag_ptr, out, capacity, count) },
987        )
988    }
989
990    /// A waiting event; `NotFound` for an id that is not waiting (or not yet counted).
991    pub fn pending_event(&self, pending_id: i32) -> Result<PendingEvent> {
992        let f = function!(self.table, AnvilGameWorldService, pending_event)?;
993        let mut raw: AnvilGamePendingEvent = sized();
994        // SAFETY: `size` says how much it may write.
995        check(unsafe { f(pending_id, &mut raw) }, || {
996            format!("world pending_event {pending_id}")
997        })?;
998        Ok(PendingEvent {
999            pending_id: raw.pending_id,
1000            country: Tag::from_raw(&raw.country),
1001            province: (raw.province != 0).then_some(raw.province),
1002            options: raw.options,
1003            hidden: raw.flags & ANVIL_GAME_PENDING_HIDDEN != 0,
1004            auto_select: Date::from_raw(&raw.auto_select),
1005        })
1006    }
1007
1008    /// The waiting event's key as the game's files name it (`flavor_tur.203`).
1009    pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
1010        let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
1011        // SAFETY: the service fills at most `capacity` bytes.
1012        read_text(
1013            || format!("world pending_event_key {pending_id}"),
1014            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
1015        )
1016    }
1017
1018    /// The localisation key of its title, not the translated text.
1019    pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
1020        let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
1021        // SAFETY: the service fills at most `capacity` bytes.
1022        read_text(
1023            || format!("world pending_event_title {pending_id}"),
1024            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
1025        )
1026    }
1027
1028    /// A country's yearly series of the game's graphs, oldest first. It
1029    /// changes only at [`game::YEAR`](crate::game::YEAR). `NotFound` for a tag
1030    /// without a series (none has one before its first year end).
1031    pub fn country_statistics(&self, tag: Tag, kind: StatisticKind) -> Result<Vec<StatisticPoint>> {
1032        let f = function!(self.table, AnvilGameWorldService, country_statistics)?;
1033        let text = tag.c_text();
1034        let empty = AnvilGameStatisticPoint { year: 0, value: 0 };
1035        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` points.
1036        let raw = read_list(
1037            empty,
1038            || format!("world country_statistics {tag} {kind:?}"),
1039            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1040        )?;
1041        Ok(raw
1042            .iter()
1043            .map(|p| StatisticPoint {
1044                year: p.year,
1045                value: p.value,
1046            })
1047            .collect())
1048    }
1049
1050    /// A country's timed modifiers, in the game's order, each with its key.
1051    /// Call it on the main thread, as every read: the list and the keys come
1052    /// from two calls of the service in the same frame.
1053    pub fn country_timed_modifiers(&self, tag: Tag) -> Result<Vec<TimedModifier>> {
1054        let list = function!(self.table, AnvilGameWorldService, country_timed_modifiers)?;
1055        let keys = function!(
1056            self.table,
1057            AnvilGameWorldService,
1058            country_timed_modifier_keys
1059        )?;
1060        let text = tag.c_text();
1061        let context = || format!("world country_timed_modifiers {tag}");
1062        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` entries or bytes.
1063        let raw = timed_list(context, |out, capacity, count| unsafe {
1064            list(text.as_ptr(), out, capacity, count)
1065        })?;
1066        // SAFETY: as above.
1067        let all = read_text(context, |buffer, capacity, length| unsafe {
1068            keys(text.as_ptr(), buffer, capacity, length)
1069        })?;
1070        timed_modifiers(&raw, &all, context)
1071    }
1072
1073    /// A province's timed modifiers, in the game's order, each with its key.
1074    pub fn province_timed_modifiers(&self, province: i32) -> Result<Vec<TimedModifier>> {
1075        let list = function!(self.table, AnvilGameWorldService, province_timed_modifiers)?;
1076        let keys = function!(
1077            self.table,
1078            AnvilGameWorldService,
1079            province_timed_modifier_keys
1080        )?;
1081        let context = || format!("world province_timed_modifiers {province}");
1082        // SAFETY: the service fills at most `capacity` entries or bytes.
1083        let raw = timed_list(context, |out, capacity, count| unsafe {
1084            list(province, out, capacity, count)
1085        })?;
1086        // SAFETY: as above.
1087        let all = read_text(context, |buffer, capacity, length| unsafe {
1088            keys(province, buffer, capacity, length)
1089        })?;
1090        timed_modifiers(&raw, &all, context)
1091    }
1092
1093    /// The province the game's province view shows while that window is
1094    /// open; `NotFound` while none is open.
1095    pub fn province_view(&self) -> Result<i32> {
1096        let f = function!(self.table, AnvilGameWorldService, province_view)?;
1097        let mut province = 0i32;
1098        // SAFETY: an out pointer.
1099        check(unsafe { f(&mut province) }, || {
1100            "world province_view".to_owned()
1101        })?;
1102        Ok(province)
1103    }
1104
1105    /// The province last selected on the map; 0 while none has been selected
1106    /// in this session (anvil-game 1.24.0).
1107    pub fn selected_province(&self) -> Result<i32> {
1108        let f = function!(self.table, AnvilGameWorldService, selected_province)?;
1109        let mut province = 0i32;
1110        // SAFETY: an out pointer.
1111        check(unsafe { f(&mut province) }, || {
1112            "world selected_province".to_owned()
1113        })?;
1114        Ok(province)
1115    }
1116
1117    /// The province under the point (`x`, `y`) of the game window's client
1118    /// area, in pixels, as the game's hover finds it; 0 off the map
1119    /// (anvil-game 1.24.0).
1120    pub fn province_at(&self, x: i32, y: i32) -> Result<i32> {
1121        let f = function!(self.table, AnvilGameWorldService, province_at)?;
1122        let mut province = 0i32;
1123        // SAFETY: an out pointer.
1124        check(unsafe { f(x, y, &mut province) }, || {
1125            format!("world province_at {x},{y}")
1126        })?;
1127        Ok(province)
1128    }
1129
1130    /// The army or navy the map picks at the same point, as the game's
1131    /// cursor does; `NotFound` when it picks no unit there (anvil-game 1.24.0).
1132    pub fn unit_at(&self, x: i32, y: i32) -> Result<UnitRef> {
1133        let f = function!(self.table, AnvilGameWorldService, unit_at)?;
1134        let mut raw = AnvilGameUnitRef {
1135            id: 0,
1136            country: EMPTY_TAG,
1137            kind: 0,
1138        };
1139        // SAFETY: an out pointer.
1140        check(unsafe { f(x, y, &mut raw) }, || {
1141            format!("world unit_at {x},{y}")
1142        })?;
1143        Ok(UnitRef {
1144            id: raw.id,
1145            country: Tag::from_raw(&raw.country),
1146            kind: UnitKind::from_raw(raw.kind),
1147        })
1148    }
1149
1150    /// The keys of the province triggered modifiers a province has been given
1151    /// (`add_province_triggered_modifier`), in the game's order, whether or
1152    /// not their triggers hold now. With
1153    /// [`province_timed_modifiers`](Self::province_timed_modifiers) they are
1154    /// every key `has_province_modifier` looks for (anvil-game 1.25.0).
1155    pub fn province_triggered_modifiers(&self, province: i32) -> Result<Vec<String>> {
1156        let keys = function!(
1157            self.table,
1158            AnvilGameWorldService,
1159            province_triggered_modifier_keys
1160        )?;
1161        let context = || format!("world province_triggered_modifiers {province}");
1162        // SAFETY: the service fills at most `capacity` bytes.
1163        let all = read_text(context, |buffer, capacity, length| unsafe {
1164            keys(province, buffer, capacity, length)
1165        })?;
1166        Ok(split_names(&all))
1167    }
1168
1169    /// A country's relations of one kind, in the game's order (anvil-game 1.22.0).
1170    pub fn country_relations(&self, tag: Tag, kind: RelationKind) -> Result<Vec<Relation>> {
1171        let f = function!(self.table, AnvilGameWorldService, country_relations)?;
1172        let text = tag.c_text();
1173        // SAFETY: plain data for which zero is valid.
1174        let empty: AnvilGameRelation = unsafe { std::mem::zeroed() };
1175        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` relations.
1176        let raw = read_list(
1177            empty,
1178            || format!("world country_relations {tag} {kind:?}"),
1179            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1180        )?;
1181        Ok(raw
1182            .iter()
1183            .map(|r| Relation {
1184                first: Tag::from_raw(&r.first),
1185                second: Tag::from_raw(&r.second),
1186                start: (r.start.size != 0).then(|| Date::from_raw(&r.start)),
1187                end: (r.end.size != 0).then(|| Date::from_raw(&r.end)),
1188            })
1189            .collect())
1190    }
1191
1192    /// The key of `subject`'s subject type under `overlord` (`vassal`,
1193    /// `march`); `NotFound` when it is not `overlord`'s subject.
1194    pub fn subject_type(&self, overlord: Tag, subject: Tag) -> Result<String> {
1195        let f = function!(self.table, AnvilGameWorldService, subject_type)?;
1196        let (a, b) = (overlord.c_text(), subject.c_text());
1197        // SAFETY: NUL-terminated tags; the service fills at most `capacity` bytes.
1198        read_text(
1199            || format!("world subject_type {overlord} {subject}"),
1200            |buffer, capacity, length| unsafe {
1201                f(a.as_ptr(), b.as_ptr(), buffer, capacity, length)
1202            },
1203        )
1204    }
1205
1206    /// What `from` keeps about `to`, with its opinion from the game's cache.
1207    /// `NotFound` for a country that owns no province now and while the cache
1208    /// has no entry for `to` yet; `InvalidArgument` for the same country twice.
1209    pub fn diplomacy_status(&self, from: Tag, to: Tag) -> Result<DiplomacyStatus> {
1210        let f = function!(self.table, AnvilGameWorldService, diplomacy_status)?;
1211        let (a, b) = (from.c_text(), to.c_text());
1212        let mut raw: AnvilGameDiplomacyStatus = sized();
1213        // SAFETY: NUL-terminated tags; `size` says how much it may write.
1214        check(unsafe { f(a.as_ptr(), b.as_ptr(), &mut raw) }, || {
1215            format!("world diplomacy_status {from} {to}")
1216        })?;
1217        Ok(DiplomacyStatus {
1218            opinion: raw.opinion,
1219            timed_sum: raw.timed_sum,
1220            trust: raw.trust,
1221            favors: Milli(raw.favors),
1222            truce: raw.flags & ANVIL_GAME_DIPLOMACY_TRUCE != 0,
1223        })
1224    }
1225
1226    /// The countries `tag` has chosen as rivals, in the game's order.
1227    pub fn country_rivals(&self, tag: Tag) -> Result<Vec<Tag>> {
1228        let f = function!(self.table, AnvilGameWorldService, country_rivals)?;
1229        let text = tag.c_text();
1230        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
1231        let raw = read_list(
1232            EMPTY_TAG,
1233            || format!("world country_rivals {tag}"),
1234            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1235        )?;
1236        Ok(raw.iter().filter_map(Tag::from_raw).collect())
1237    }
1238
1239    /// Its overlord; `NotFound` also for a country without one.
1240    pub fn country_overlord(&self, tag: Tag) -> Result<Tag> {
1241        let f = function!(self.table, AnvilGameWorldService, country_overlord)?;
1242        let text = tag.c_text();
1243        let mut raw = EMPTY_TAG;
1244        // SAFETY: a NUL-terminated tag and an out pointer.
1245        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
1246            format!("world country_overlord {tag}")
1247        })?;
1248        Tag::from_raw(&raw)
1249            .ok_or_else(|| Error::new(ErrorCode::Internal, format!("world country_overlord {tag}")))
1250    }
1251
1252    /// Its direct subjects, in the game's order.
1253    pub fn country_subjects(&self, tag: Tag) -> Result<Vec<Tag>> {
1254        let f = function!(self.table, AnvilGameWorldService, country_subjects)?;
1255        let text = tag.c_text();
1256        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
1257        let raw = read_list(
1258            EMPTY_TAG,
1259            || format!("world country_subjects {tag}"),
1260            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1261        )?;
1262        Ok(raw.iter().filter_map(Tag::from_raw).collect())
1263    }
1264
1265    /// What [`World::player`] answers and the two tags it is chosen from, read
1266    /// at once (anvil-game 1.23.0). In a normal game `tag` and `own` are the
1267    /// player's country and `observed` is as the game stores it: usually `None`,
1268    /// but it can hold a tag left over; in observe mode `own` is the
1269    /// observer's pseudo-country and `tag` the observed country while there is
1270    /// one.
1271    pub fn player_tags(&self) -> Result<PlayerTags> {
1272        let f = function!(self.table, AnvilGameWorldService, player_tags)?;
1273        let mut raw: AnvilGamePlayer = sized();
1274        // SAFETY: `size` says how much it may write.
1275        check(unsafe { f(&mut raw) }, || "world player_tags")?;
1276        Ok(PlayerTags {
1277            tag: Tag::from_raw(&raw.tag),
1278            own: Tag::from_raw(&raw.own),
1279            observed: Tag::from_raw(&raw.observed),
1280            observer: raw.flags & ANVIL_GAME_PLAYER_OBSERVER != 0,
1281        })
1282    }
1283
1284    /// The regions the fleet may explore, as the game's naval exploration
1285    /// dialog lists them: each region once, in the game's order. It calls the
1286    /// dialog's own function and changes nothing; `InvalidArgument` for an
1287    /// army (anvil-game 1.25.0).
1288    pub fn exploration_regions(&self, fleet: &UnitRef, list: ExplorationList) -> Result<Vec<i32>> {
1289        let f = function!(self.table, AnvilGameWorldService, exploration_regions)?;
1290        let raw = fleet.to_raw();
1291        // SAFETY: a unit reference; the service fills at most `capacity` indexes.
1292        read_list(
1293            0i32,
1294            || format!("world exploration_regions {} {list:?}", fleet.id),
1295            |out, capacity, count| unsafe { f(&raw, list.raw(), out, capacity, count) },
1296        )
1297    }
1298
1299    /// The region's name as the game shows it, in the game's language
1300    /// (anvil-game 1.25.0).
1301    pub fn region_name(&self, region: i32) -> Result<String> {
1302        let f = function!(self.table, AnvilGameWorldService, region_name)?;
1303        // SAFETY: the service fills at most `capacity` bytes.
1304        read_text(
1305            || format!("world region_name {region}"),
1306            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1307        )
1308    }
1309
1310    /// The region's script key, such as `baltic_sea_region` (anvil-game 1.25.0).
1311    pub fn region_key(&self, region: i32) -> Result<String> {
1312        let f = function!(self.table, AnvilGameWorldService, region_key)?;
1313        // SAFETY: the service fills at most `capacity` bytes.
1314        read_text(
1315            || format!("world region_key {region}"),
1316            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1317        )
1318    }
1319
1320    fn province_key(&self, province: i32, key: u32, name: &str) -> Result<String> {
1321        let f = function!(self.table, AnvilGameWorldService, province_key)?;
1322        // SAFETY: the service fills at most `capacity` bytes.
1323        read_text(
1324            || format!("world {name} {province}"),
1325            |buffer, capacity, length| unsafe { f(province, key, buffer, capacity, length) },
1326        )
1327    }
1328
1329    fn country_key(&self, tag: Tag, key: u32, name: &str) -> Result<String> {
1330        let f = function!(self.table, AnvilGameWorldService, country_key)?;
1331        let text = tag.c_text();
1332        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
1333        read_text(
1334            || format!("world {name} {tag}"),
1335            |buffer, capacity, length| unsafe { f(text.as_ptr(), key, buffer, capacity, length) },
1336        )
1337    }
1338
1339    /// The script key of a province's religion, such as `orthodox`;
1340    /// `NotFound` when it has none (anvil-game 1.26.0).
1341    pub fn province_religion(&self, province: i32) -> Result<String> {
1342        self.province_key(
1343            province,
1344            crate::sys::ANVIL_GAME_KEY_RELIGION,
1345            "province_religion",
1346        )
1347    }
1348
1349    /// The script key of a province's culture, such as `russian`; `NotFound`
1350    /// when it has none (anvil-game 1.26.0).
1351    pub fn province_culture(&self, province: i32) -> Result<String> {
1352        self.province_key(
1353            province,
1354            crate::sys::ANVIL_GAME_KEY_CULTURE,
1355            "province_culture",
1356        )
1357    }
1358
1359    /// The script key of a province's trade goods, such as `grain`;
1360    /// `NotFound` when it has none (anvil-game 1.26.0).
1361    pub fn province_trade_goods(&self, province: i32) -> Result<String> {
1362        self.province_key(
1363            province,
1364            crate::sys::ANVIL_GAME_KEY_TRADE_GOODS,
1365            "province_trade_goods",
1366        )
1367    }
1368
1369    /// The script key of a country's state religion; `NotFound` when it has
1370    /// none (anvil-game 1.26.0).
1371    pub fn country_religion(&self, tag: Tag) -> Result<String> {
1372        self.country_key(tag, crate::sys::ANVIL_GAME_KEY_RELIGION, "country_religion")
1373    }
1374
1375    /// The script key of a country's primary culture; `NotFound` when it has
1376    /// none (anvil-game 1.26.0).
1377    pub fn country_culture(&self, tag: Tag) -> Result<String> {
1378        self.country_key(tag, crate::sys::ANVIL_GAME_KEY_CULTURE, "country_culture")
1379    }
1380
1381    /// The script key of the group of a province's religion, such as
1382    /// `christian`; `NotFound` when it has none (anvil-game 1.26.0).
1383    pub fn province_religion_group(&self, province: i32) -> Result<String> {
1384        self.province_key(
1385            province,
1386            crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
1387            "province_religion_group",
1388        )
1389    }
1390
1391    /// The script key of the group of a province's culture, such as
1392    /// `east_slavic`; `NotFound` when it has none (anvil-game 1.26.0).
1393    pub fn province_culture_group(&self, province: i32) -> Result<String> {
1394        self.province_key(
1395            province,
1396            crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
1397            "province_culture_group",
1398        )
1399    }
1400
1401    /// The script key of a province's area, such as `uppland_area`;
1402    /// `NotFound` when it has none (anvil-game 1.26.0).
1403    pub fn province_area(&self, province: i32) -> Result<String> {
1404        self.province_key(province, crate::sys::ANVIL_GAME_KEY_AREA, "province_area")
1405    }
1406
1407    /// The script key of a province's region, such as `scandinavia_region`;
1408    /// `NotFound` when it has none (anvil-game 1.26.0).
1409    pub fn province_region(&self, province: i32) -> Result<String> {
1410        self.province_key(
1411            province,
1412            crate::sys::ANVIL_GAME_KEY_REGION,
1413            "province_region",
1414        )
1415    }
1416
1417    /// The script key of a province's superregion, such as
1418    /// `europe_superregion`; `NotFound` when it has none (anvil-game 1.26.0).
1419    pub fn province_superregion(&self, province: i32) -> Result<String> {
1420        self.province_key(
1421            province,
1422            crate::sys::ANVIL_GAME_KEY_SUPERREGION,
1423            "province_superregion",
1424        )
1425    }
1426
1427    /// The script key of a province's continent, such as `europe`;
1428    /// `NotFound` when it has none (anvil-game 1.26.0).
1429    pub fn province_continent(&self, province: i32) -> Result<String> {
1430        self.province_key(
1431            province,
1432            crate::sys::ANVIL_GAME_KEY_CONTINENT,
1433            "province_continent",
1434        )
1435    }
1436
1437    /// The script key of a province's trade node, such as `baltic_sea`;
1438    /// `NotFound` when it has none (anvil-game 1.26.0).
1439    pub fn province_trade_node(&self, province: i32) -> Result<String> {
1440        self.province_key(
1441            province,
1442            crate::sys::ANVIL_GAME_KEY_TRADE_NODE,
1443            "province_trade_node",
1444        )
1445    }
1446
1447    /// The script key of the group of a country's state religion; `NotFound`
1448    /// when it has none (anvil-game 1.26.0).
1449    pub fn country_religion_group(&self, tag: Tag) -> Result<String> {
1450        self.country_key(
1451            tag,
1452            crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
1453            "country_religion_group",
1454        )
1455    }
1456
1457    /// The script key of the group of a country's primary culture; `NotFound`
1458    /// when it has none (anvil-game 1.26.0).
1459    pub fn country_culture_group(&self, tag: Tag) -> Result<String> {
1460        self.country_key(
1461            tag,
1462            crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
1463            "country_culture_group",
1464        )
1465    }
1466}
1467
1468fn timed_list(
1469    context: impl Fn() -> String,
1470    call: impl FnMut(*mut AnvilGameTimedModifier, u32, *mut u32) -> crate::sys::AnvilResult,
1471) -> Result<Vec<AnvilGameTimedModifier>> {
1472    // SAFETY: plain data for which zero is valid.
1473    let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
1474    read_list(empty, context, call)
1475}
1476
1477// The entries with their keys; a count that differs means the list changed
1478// between the two calls, which happens only off the main thread.
1479fn timed_modifiers(
1480    raw: &[AnvilGameTimedModifier],
1481    keys: &str,
1482    context: impl Fn() -> String,
1483) -> Result<Vec<TimedModifier>> {
1484    let keys = split_names(keys);
1485    if keys.len() != raw.len() {
1486        return Err(Error::new(ErrorCode::Internal, context()));
1487    }
1488    Ok(raw
1489        .iter()
1490        .zip(keys)
1491        .map(|(m, key)| TimedModifier {
1492            key,
1493            hidden: m.flags & ANVIL_GAME_TIMED_HIDDEN != 0,
1494            ruler: m.flags & ANVIL_GAME_TIMED_RULER != 0,
1495            start: (m.flags & ANVIL_GAME_TIMED_NO_START == 0).then(|| Date::from_raw(&m.start)),
1496            end: (m.flags & ANVIL_GAME_TIMED_NO_END == 0).then(|| Date::from_raw(&m.end)),
1497        })
1498        .collect())
1499}
1500
1501/// Names that each end with a NUL, one after the other.
1502fn split_names(all: &str) -> Vec<String> {
1503    all.split_terminator('\0').map(str::to_owned).collect()
1504}
1505
1506fn flags(
1507    context: impl Fn() -> String,
1508    call: impl FnMut(*mut AnvilGameFlag, u32, *mut u32) -> crate::sys::AnvilResult,
1509) -> Result<Vec<Flag>> {
1510    let empty = AnvilGameFlag {
1511        id: 0,
1512        reserved: 0,
1513        date: AnvilGameDate {
1514            size: 0,
1515            year: 0,
1516            month: 0,
1517            day: 0,
1518            session: 0,
1519        },
1520    };
1521    let raw = read_list(empty, context, call)?;
1522    Ok(raw
1523        .iter()
1524        .map(|f| Flag {
1525            id: FlagId(f.id),
1526            date: Date::from_raw(&f.date),
1527        })
1528        .collect())
1529}