Skip to main content

rpfm_lib/files/group_formations/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! This module contains the implementation of the Group Formations file format for Total War games.
12//!
13//! Group formations define fixed formation templates that both the AI and player can use to
14//! deploy their units on the battlefield. Each formation is designed for specific tactical
15//! scenarios (attack, defend, naval, etc.) and specifies unit placement, spacing, arrangement
16//! patterns, and which unit types should be placed in each position.
17//!
18//! # File Format
19//!
20//! The group formations file (`groupformations.bin`) is a binary file containing formation
21//! definitions that can be used by both AI and players to deploy armies tactically. Each
22//! formation can specify:
23//!
24//! - AI purpose flags (attack, defend, river crossing, naval, etc.)
25//! - Priority and unit category requirements
26//! - Supported factions and subcultures
27//! - Formation blocks defining unit positions (absolute, relative, or spanning)
28//! - Entity preferences specifying which unit types go where
29//!
30//! # Game Support
31//!
32//! This file format is not versioned in the traditional sense. Instead, different games have
33//! different implementations in the `versions/` subdirectory:
34//!
35//! - Shogun 2: Basic formation system with entity types and arrangements
36//! - Rome 2 (and later): Extended system with entity weights, subcultures, and more AI purposes
37//!
38//! # File Location
39//!
40//! Group formations files are typically found at:
41//! - `groupformations.bin` in the root of a game's pack
42//!
43//! # Usage Example
44//!
45//! ```rust,ignore
46//! use rpfm_lib::files::{Decodeable, group_formations::*};
47//!
48//! // Decode a group formations file
49//! let mut data = std::io::Cursor::new(file_data);
50//! let extra_data = Some(DecodeableExtraData {
51//!     game_info: Some(game_info),
52//!     ..Default::default()
53//! });
54//! let formations = GroupFormations::decode(&mut data, &extra_data)?;
55//!
56//! // Access formation data
57//! for formation in formations.formations() {
58//!     println!("Formation: {}", formation.name());
59//!     println!("Priority: {}", formation.ai_priority());
60//! }
61//! ```
62
63use bitflags::Flags;
64use getset::*;
65use serde_derive::{Serialize, Deserialize};
66
67use std::fmt::Display;
68
69use crate::binary::{ReadBytes, WriteBytes};
70use crate::error::{Result, RLibError};
71use crate::files::{Decodeable, EncodeableExtraData, Encodeable};
72use crate::games::{GameInfo, supported_games::*};
73use crate::utils::*;
74
75use super::DecodeableExtraData;
76
77pub use crate::files::detection::group_formations::PATH;
78
79pub mod edit;
80pub mod layout;
81pub mod validation;
82pub mod versions;
83
84#[cfg(test)] mod test_group_formations;
85
86//---------------------------------------------------------------------------//
87//                              Enum & Structs
88//---------------------------------------------------------------------------//
89
90/// Represents an entire Group Formations file decoded in memory.
91///
92/// Contains a list of formation templates that both AI and players can use to
93/// deploy armies on the battlefield for various tactical scenarios.
94#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
95#[getset(get = "pub", get_mut = "pub", set = "pub")]
96pub struct GroupFormations {
97    /// List of all formation definitions in the file.
98    formations: Vec<GroupFormation>,
99}
100
101/// A single formation definition specifying how units should be arranged.
102///
103/// Each formation includes AI usage criteria, unit requirements, and a set of
104/// formation blocks that define where different unit types should be positioned.
105#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
106#[getset(get = "pub", get_mut = "pub", set = "pub")]
107pub struct GroupFormation {
108    /// Name identifier for this formation.
109    name: String,
110
111    /// AI priority value for selecting this formation (higher = more preferred).
112    ai_priority: f32,
113
114    /// Bitflags indicating when this formation should be used (attack, defend, naval, etc.).
115    ai_purpose: AIPurpose,
116
117    /// Unknown field, present in Troy and later.
118    uk_2: u32,
119
120    /// Minimum percentage requirements for unit categories in this formation.
121    min_unit_category_percentage: Vec<MinUnitCategoryPercentage>,
122
123    /// List of supported subcultures (introduced in Rome 2).
124    ///
125    /// If non-empty, this formation is only available to armies from these subcultures.
126    ai_supported_subcultures: Vec<String>,
127
128    /// List of supported factions (introduced in Rome 2).
129    ///
130    /// If non-empty, this formation is only available to armies from these factions.
131    ai_supported_factions: Vec<String>,
132
133    /// Formation blocks defining unit positions and arrangements.
134    group_formation_blocks: Vec<GroupFormationBlock>,
135}
136
137/// Specifies a minimum percentage requirement for a unit category in a formation.
138///
139/// For example, a formation might require at least 30% cavalry units.
140#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
141#[getset(get = "pub", get_mut = "pub", set = "pub")]
142pub struct MinUnitCategoryPercentage {
143    /// The unit category (cavalry, infantry melee, infantry ranged, etc.).
144    category: UnitCategory,
145
146    /// Minimum percentage (0-100) of the army that must belong to this category.
147    percentage: u32,
148}
149
150/// A formation block defining a specific position or region in the formation.
151///
152/// Each block has an ID and contains either absolute positioning, relative positioning
153/// to another block, or spans multiple other blocks.
154#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
155#[getset(get = "pub", get_mut = "pub", set = "pub")]
156pub struct GroupFormationBlock {
157    /// Unique identifier for this block, used for relative positioning references.
158    block_id: u32,
159
160    /// The block type and its associated data.
161    block: Block,
162}
163
164/// Types of formation blocks that can be used to define unit positions.
165///
166/// - `ContainerAbsolute`: Positioned at fixed coordinates.
167/// - `ContainerRelative`: Positioned relative to another block.
168/// - `Spanning`: Encompasses multiple other blocks.
169#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
170pub enum Block {
171    /// A container positioned at absolute coordinates.
172    ContainerAbsolute(ContainerAbsolute),
173
174    /// A container positioned relative to another block.
175    ContainerRelative(ContainerRelative),
176
177    /// A spanning block that encompasses multiple other blocks.
178    Spanning(Spanning)
179}
180
181/// A container block positioned at absolute coordinates on the battlefield.
182///
183/// Defines how units should be arranged at a specific location, including their
184/// spacing, arrangement pattern, and which types of units should occupy this position.
185#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
186#[getset(get = "pub", get_mut = "pub", set = "pub")]
187pub struct ContainerAbsolute {
188    /// Priority for filling this block (higher priority blocks are filled first).
189    block_priority: f32,
190
191    /// How units should be arranged (line, column, crescent, etc.).
192    entity_arrangement: EntityArrangement,
193
194    /// Spacing between units in this block.
195    inter_entity_spacing: f32,
196
197    /// Y-axis offset for crescent formations.
198    crescent_y_offset: f32,
199
200    /// X coordinate of this block's position.
201    position_x: f32,
202
203    /// Y coordinate of this block's position.
204    position_y: f32,
205
206    /// Minimum number of units required to use this block.
207    minimum_entity_threshold: i32,
208
209    /// Maximum number of units that can be placed in this block.
210    maximum_entity_threshold: i32,
211
212    /// Ordered list of preferred unit types for this block.
213    entity_preferences: Vec<EntityPreference>,
214}
215
216/// A container block positioned relative to another block.
217///
218/// Similar to `ContainerAbsolute` but positioned at an offset from a reference block,
219/// allowing formations to be built up from interconnected positioned blocks.
220#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
221#[getset(get = "pub", get_mut = "pub", set = "pub")]
222pub struct ContainerRelative {
223    /// Priority for filling this block (higher priority blocks are filled first).
224    block_priority: f32,
225
226    /// ID of the block this is positioned relative to.
227    relative_block_id: u32,
228
229    /// How units should be arranged (line, column, crescent, etc.).
230    entity_arrangement: EntityArrangement,
231
232    /// Spacing between units in this block.
233    inter_entity_spacing: f32,
234
235    /// Y-axis offset for crescent formations.
236    crescent_y_offset: f32,
237
238    /// X offset relative to the reference block.
239    position_x: f32,
240
241    /// Y offset relative to the reference block.
242    position_y: f32,
243
244    /// Minimum number of units required to use this block.
245    minimum_entity_threshold: i32,
246
247    /// Maximum number of units that can be placed in this block.
248    maximum_entity_threshold: i32,
249
250    /// Ordered list of preferred unit types for this block.
251    entity_preferences: Vec<EntityPreference>,
252}
253
254/// Defines a preference for a specific type of unit to occupy a formation block.
255///
256/// Multiple preferences can be defined in priority order, so the AI will try to place
257/// the highest priority matching units first.
258#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
259#[getset(get = "pub", get_mut = "pub", set = "pub")]
260pub struct EntityPreference {
261    /// Priority for this entity type (higher = more preferred).
262    priority: f32,
263
264    /// The type of unit entity (infantry, cavalry, artillery, etc.).
265    ///
266    /// Note: This is called EntityClass in Rome 2 and EntityDescription in Shogun 2,
267    /// but represents the same concept.
268    entity: Entity,
269
270    /// Weight class of the unit (light, medium, heavy, etc.). Introduced in Rome 2.
271    entity_weight: EntityWeight,
272
273    /// Unknown field, present in Troy and later. Vanilla files almost always use 6.
274    uk_1: u32,
275
276    /// Entity class string identifier, present in Troy and later.
277    entity_class: String,
278}
279
280/// A spanning block that encompasses multiple other blocks.
281///
282/// Used to group related blocks together for organization or special handling.
283#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
284#[getset(get = "pub", get_mut = "pub", set = "pub")]
285pub struct Spanning {
286    /// IDs of the blocks that this spanning block encompasses.
287    spanned_block_ids: Vec<u32>,
288}
289
290/// Binary layout of a Group Formations file, which depends on the game it belongs to.
291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
292pub enum GroupFormationsFormat {
293
294    /// Shogun 2.
295    Shogun2,
296
297    /// Rome 2, Attila and Thrones of Britannia.
298    Rome2,
299
300    /// Troy and Pharaoh.
301    Troy,
302
303    /// Three Kingdoms and Warhammer 3.
304    Warhammer3,
305}
306
307/// AI purpose flags indicating when a formation should be used.
308///
309/// - V1: Shogun 2 flag layout (different bit assignments from Rome 2+).
310/// - V2: Rome 2 and later flag layout.
311#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
312pub enum AIPurpose {
313    V1(versions::v1::AIPurposeFlags),
314    V2(versions::v2::AIPurposeFlags),
315}
316
317/// How units should be arranged within a formation block (line, column, crescent, etc.).
318///
319/// Identical across all game versions.
320#[derive(Default, Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
321#[repr(u32)]
322pub enum EntityArrangement {
323    #[default] Line = 0,
324    Column = 1,
325    CrescentFront = 2,
326    CrescentBack = 3,
327}
328
329/// Unit category classifications (cavalry, infantry melee, infantry ranged, naval, etc.).
330///
331/// Identical across all game versions.
332#[derive(Default, Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
333#[repr(u32)]
334pub enum UnitCategory {
335    #[default] Cavalry = 0,
336    InfantryMelee = 13,
337    InfantryRanged = 14,
338    NavalHeavy = 15,
339    NavalMedium = 16,
340    NavalLight = 17,
341}
342
343/// Entity type classifications.
344///
345/// - V1: Shogun 2 entity types (65+ specific unit classes like CavalryHeavy, InfantryLine, etc.).
346/// - V2: Rome 2 and later entity types (18 abstract classes like InfMel, CavShk, etc.).
347#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
348pub enum Entity {
349    V1(versions::v1::EntityType),
350    V2(versions::v2::EntityType),
351}
352
353/// Entity weight classifications (light, medium, heavy, etc.).
354///
355/// Introduced in Rome 2. Identical across all post-Shogun 2 game versions.
356/// Shogun 2 does not use entity weights.
357#[derive(Default, Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
358#[repr(u32)]
359pub enum EntityWeight {
360    VeryLight = 0,
361    Light = 1,
362    Medium = 2,
363    Heavy = 3,
364    VeryHeavy = 4,
365    SuperHeavy = 5,
366    #[default] Any = 6,
367}
368
369//---------------------------------------------------------------------------//
370//                          Implementation of GroupFormations
371//---------------------------------------------------------------------------//
372
373impl GroupFormationsFormat {
374
375    /// Returns the format used by the provided game.
376    ///
377    /// # Arguments
378    ///
379    /// * `game_info` - The game the file belongs to.
380    ///
381    /// # Returns
382    ///
383    /// The format of the game's Group Formations file.
384    ///
385    /// # Errors
386    ///
387    /// Returns an error if the game doesn't support Group Formations files.
388    pub fn from_game(game_info: &GameInfo) -> Result<Self> {
389        match game_info.key() {
390            KEY_PHARAOH_DYNASTIES |
391            KEY_PHARAOH |
392            KEY_TROY => Ok(Self::Troy),
393            KEY_THREE_KINGDOMS |
394            KEY_WARHAMMER_3 => Ok(Self::Warhammer3),
395            KEY_THRONES_OF_BRITANNIA |
396            KEY_ATTILA |
397            KEY_ROME_2 => Ok(Self::Rome2),
398            KEY_SHOGUN_2_COMPLETE_EDITION |
399            KEY_SHOGUN_2 => Ok(Self::Shogun2),
400
401            // Warhammer, Warhammer 2, Napoleon and Empire formats are not yet researched.
402            _ => Err(RLibError::DecodingUnsupportedGameSelected(game_info.key().to_string())),
403        }
404    }
405
406    /// Returns if formations in this format have a list of supported factions.
407    pub fn has_ai_supported_factions(&self) -> bool {
408        matches!(self, Self::Shogun2 | Self::Rome2 | Self::Warhammer3)
409    }
410
411    /// Returns if formations in this format have a list of supported subcultures.
412    pub fn has_ai_supported_subcultures(&self) -> bool {
413        matches!(self, Self::Rome2 | Self::Troy | Self::Warhammer3)
414    }
415
416    /// Returns if formations in this format have the `uk_2` field.
417    pub fn has_formation_uk_2(&self) -> bool {
418        matches!(self, Self::Troy | Self::Warhammer3)
419    }
420
421    /// Returns if entity preferences in this format have an entity weight.
422    pub fn has_entity_weight(&self) -> bool {
423        matches!(self, Self::Rome2 | Self::Troy | Self::Warhammer3)
424    }
425
426    /// Returns if entity preferences in this format have the `uk_1` and `entity_class` fields.
427    pub fn has_entity_class(&self) -> bool {
428        matches!(self, Self::Troy | Self::Warhammer3)
429    }
430
431    /// Returns an empty set of AI purpose flags of the version used by this format.
432    pub fn default_ai_purpose(&self) -> AIPurpose {
433        match self {
434            Self::Shogun2 => AIPurpose::V1(versions::v1::AIPurposeFlags::empty()),
435            Self::Rome2 | Self::Troy | Self::Warhammer3 => AIPurpose::V2(versions::v2::AIPurposeFlags::empty()),
436        }
437    }
438
439    /// Returns all the entity types of the version used by this format.
440    pub fn entities(&self) -> Vec<Entity> {
441        match self {
442            Self::Shogun2 => versions::v1::EntityType::ALL.iter().map(|entity| Entity::V1(*entity)).collect(),
443            Self::Rome2 | Self::Troy | Self::Warhammer3 => versions::v2::EntityType::ALL.iter().map(|entity| Entity::V2(*entity)).collect(),
444        }
445    }
446
447    /// Returns the default entity type of the version used by this format.
448    pub fn default_entity(&self) -> Entity {
449        match self {
450            Self::Shogun2 => Entity::V1(versions::v1::EntityType::Any),
451            Self::Rome2 => Entity::V2(versions::v2::EntityType::InfMel),
452
453            // Vanilla files pair the "any" entity class with this value.
454            Self::Troy | Self::Warhammer3 => Entity::V2(versions::v2::EntityType::Invalid),
455        }
456    }
457}
458
459impl GroupFormation {
460
461    /// Creates an empty formation valid for the provided format.
462    ///
463    /// # Arguments
464    ///
465    /// * `name` - Name of the new formation.
466    /// * `format` - Format of the file the formation will belong to.
467    ///
468    /// # Returns
469    ///
470    /// A formation with no blocks and the AI purpose version expected by the format.
471    pub fn new(name: &str, format: GroupFormationsFormat) -> Self {
472        Self {
473            name: name.to_owned(),
474            ai_purpose: format.default_ai_purpose(),
475            ..Default::default()
476        }
477    }
478}
479
480impl EntityPreference {
481
482    /// Creates an entity preference valid for the provided format, with the defaults used by vanilla files.
483    ///
484    /// # Arguments
485    ///
486    /// * `format` - Format of the file the preference will belong to.
487    ///
488    /// # Returns
489    ///
490    /// An entity preference with the entity version expected by the format.
491    pub fn new(format: GroupFormationsFormat) -> Self {
492        Self {
493            priority: 1.0,
494            entity: format.default_entity(),
495            entity_weight: EntityWeight::Any,
496            uk_1: if format.has_entity_class() { 6 } else { 0 },
497            entity_class: if format.has_entity_class() { "any".to_owned() } else { String::new() },
498        }
499    }
500}
501
502impl AIPurpose {
503
504    /// Returns the name and bit of every flag of the same version as these flags.
505    pub fn flags(&self) -> Vec<(&'static str, u32)> {
506        match self {
507            Self::V1(_) => versions::v1::AIPurposeFlags::FLAGS.iter().map(|flag| (flag.name(), flag.value().bits())).collect(),
508            Self::V2(_) => versions::v2::AIPurposeFlags::FLAGS.iter().map(|flag| (flag.name(), flag.value().bits())).collect(),
509        }
510    }
511
512    /// Returns the raw bits of these flags.
513    pub fn bits(&self) -> u32 {
514        match self {
515            Self::V1(flags) => flags.bits(),
516            Self::V2(flags) => flags.bits(),
517        }
518    }
519
520    /// Returns flags of the same version as these flags, with the provided bits.
521    pub fn with_bits(&self, bits: u32) -> Self {
522        match self {
523            Self::V1(_) => Self::V1(versions::v1::AIPurposeFlags::from_bits_retain(bits)),
524            Self::V2(_) => Self::V2(versions::v2::AIPurposeFlags::from_bits_retain(bits)),
525        }
526    }
527
528    /// Returns the raw bits of these flags, if they're the V1 (Shogun 2) version.
529    pub(crate) fn v1_bits(&self) -> Result<u32> {
530        match self {
531            Self::V1(flags) => Ok(flags.bits()),
532            Self::V2(_) => Err(RLibError::EncodingGroupFormationsMismatchedVersion("AIPurpose".to_owned())),
533        }
534    }
535
536    /// Returns the raw bits of these flags, if they're the V2 (Rome 2 and later) version.
537    pub(crate) fn v2_bits(&self) -> Result<u32> {
538        match self {
539            Self::V2(flags) => Ok(flags.bits()),
540            Self::V1(_) => Err(RLibError::EncodingGroupFormationsMismatchedVersion("AIPurpose".to_owned())),
541        }
542    }
543}
544
545impl Entity {
546
547    /// Returns the raw value of this entity, if it's the V1 (Shogun 2) version.
548    pub(crate) fn v1_value(&self) -> Result<u32> {
549        match self {
550            Self::V1(entity) => Ok((*entity).into()),
551            Self::V2(_) => Err(RLibError::EncodingGroupFormationsMismatchedVersion("Entity".to_owned())),
552        }
553    }
554
555    /// Returns the raw value of this entity, if it's the V2 (Rome 2 and later) version.
556    pub(crate) fn v2_value(&self) -> Result<u32> {
557        match self {
558            Self::V2(entity) => Ok((*entity).into()),
559            Self::V1(_) => Err(RLibError::EncodingGroupFormationsMismatchedVersion("Entity".to_owned())),
560        }
561    }
562}
563
564impl EntityArrangement {
565
566    /// All the possible values, in their binary order.
567    pub const ALL: [Self; 4] = [Self::Line, Self::Column, Self::CrescentFront, Self::CrescentBack];
568}
569
570impl UnitCategory {
571
572    /// All the possible values, in their binary order.
573    pub const ALL: [Self; 6] = [Self::Cavalry, Self::InfantryMelee, Self::InfantryRanged, Self::NavalHeavy, Self::NavalMedium, Self::NavalLight];
574}
575
576impl EntityWeight {
577
578    /// All the possible values, in their binary order.
579    pub const ALL: [Self; 7] = [Self::VeryLight, Self::Light, Self::Medium, Self::Heavy, Self::VeryHeavy, Self::SuperHeavy, Self::Any];
580}
581
582impl Display for Entity {
583    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
584        match self {
585            Self::V1(entity) => entity.fmt(f),
586            Self::V2(entity) => entity.fmt(f),
587        }
588    }
589}
590
591impl Display for EntityArrangement {
592    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
593        match self {
594            Self::Line => write!(f, "Line"),
595            Self::Column => write!(f, "Column"),
596            Self::CrescentFront => write!(f, "Crescent Front"),
597            Self::CrescentBack => write!(f, "Crescent Back"),
598        }
599    }
600}
601
602impl Display for UnitCategory {
603    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
604        match self {
605            Self::Cavalry => write!(f, "Cavalry"),
606            Self::InfantryMelee => write!(f, "Melee Infantry"),
607            Self::InfantryRanged => write!(f, "Ranged Infantry"),
608            Self::NavalHeavy => write!(f, "Heavy Naval"),
609            Self::NavalMedium => write!(f, "Medium Naval"),
610            Self::NavalLight => write!(f, "Light Naval"),
611        }
612    }
613}
614
615impl Display for EntityWeight {
616    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
617        match self {
618            Self::VeryLight => write!(f, "Very Light"),
619            Self::Light => write!(f, "Light"),
620            Self::Medium => write!(f, "Medium"),
621            Self::Heavy => write!(f, "Heavy"),
622            Self::VeryHeavy => write!(f, "Very Heavy"),
623            Self::SuperHeavy => write!(f, "Super Heavy"),
624            Self::Any => write!(f, "Any"),
625        }
626    }
627}
628
629impl Block {
630
631    /// Returns the ids of the blocks this block needs to be positioned first.
632    ///
633    /// # Returns
634    ///
635    /// The parent block for relative containers, the spanned blocks for spans, and nothing for absolute containers.
636    pub fn dependencies(&self) -> &[u32] {
637        match self {
638            Self::ContainerAbsolute(_) => &[],
639            Self::ContainerRelative(container) => std::slice::from_ref(&container.relative_block_id),
640            Self::Spanning(span) => &span.spanned_block_ids,
641        }
642    }
643}
644
645impl Default for Block {
646    fn default() -> Self {
647        Self::ContainerAbsolute(ContainerAbsolute::default())
648    }
649}
650
651impl Default for AIPurpose {
652    fn default() -> Self {
653        Self::V1(versions::v1::AIPurposeFlags::default())
654    }
655}
656
657impl Default for Entity {
658    fn default() -> Self {
659        Self::V2(versions::v2::EntityType::default())
660    }
661}
662
663impl TryFrom<u32> for EntityArrangement {
664    type Error = RLibError;
665    fn try_from(value: u32) -> Result<Self> {
666        match value {
667            _ if value == Self::Line as u32 => Ok(Self::Line),
668            _ if value == Self::Column as u32 => Ok(Self::Column),
669            _ if value == Self::CrescentFront as u32 => Ok(Self::CrescentFront),
670            _ if value == Self::CrescentBack as u32 => Ok(Self::CrescentBack),
671            _ => Err(RLibError::DecodingGroupFormationsUnknownEnumValue("EntityArrangement".to_string(), value)),
672        }
673    }
674}
675
676impl From<EntityArrangement> for u32 {
677    fn from(value: EntityArrangement) -> u32 {
678        value as u32
679    }
680}
681
682impl TryFrom<u32> for UnitCategory {
683    type Error = RLibError;
684    fn try_from(value: u32) -> Result<Self> {
685        match value {
686            _ if value == Self::Cavalry as u32 => Ok(Self::Cavalry),
687            _ if value == Self::InfantryMelee as u32 => Ok(Self::InfantryMelee),
688            _ if value == Self::InfantryRanged as u32 => Ok(Self::InfantryRanged),
689            _ if value == Self::NavalHeavy as u32 => Ok(Self::NavalHeavy),
690            _ if value == Self::NavalMedium as u32 => Ok(Self::NavalMedium),
691            _ if value == Self::NavalLight as u32 => Ok(Self::NavalLight),
692            _ => Err(RLibError::DecodingGroupFormationsUnknownEnumValue("UnitCategory".to_string(), value)),
693        }
694    }
695}
696
697impl From<UnitCategory> for u32 {
698    fn from(value: UnitCategory) -> u32 {
699        value as u32
700    }
701}
702
703impl TryFrom<u32> for EntityWeight {
704    type Error = RLibError;
705    fn try_from(value: u32) -> Result<Self> {
706        match value {
707            _ if value == Self::VeryLight as u32 => Ok(Self::VeryLight),
708            _ if value == Self::Light as u32 => Ok(Self::Light),
709            _ if value == Self::Medium as u32 => Ok(Self::Medium),
710            _ if value == Self::Heavy as u32 => Ok(Self::Heavy),
711            _ if value == Self::VeryHeavy as u32 => Ok(Self::VeryHeavy),
712            _ if value == Self::SuperHeavy as u32 => Ok(Self::SuperHeavy),
713            _ if value == Self::Any as u32 => Ok(Self::Any),
714            _ => Err(RLibError::DecodingGroupFormationsUnknownEnumValue("EntityWeight".to_string(), value)),
715        }
716    }
717}
718
719impl From<EntityWeight> for u32 {
720    fn from(value: EntityWeight) -> u32 {
721        value as u32
722    }
723}
724
725impl Decodeable for GroupFormations {
726
727    fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
728        let extra_data = extra_data.as_ref().ok_or(RLibError::DecodingMissingExtraData)?;
729        let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
730
731        let mut decoded = Self::default();
732        let data_len = data.len()?;
733
734        match GroupFormationsFormat::from_game(game_info)? {
735            GroupFormationsFormat::Troy => decoded.decode_troy(data)?,
736            GroupFormationsFormat::Warhammer3 => decoded.decode_wh3(data)?,
737            GroupFormationsFormat::Rome2 => decoded.decode_rom_2(data)?,
738            GroupFormationsFormat::Shogun2 => decoded.decode_sho_2(data)?,
739        }
740
741        check_size_mismatch(data.stream_position()? as usize, data_len as usize)?;
742
743        Ok(decoded)
744    }
745}
746
747impl Encodeable for GroupFormations {
748
749    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()> {
750        let extra_data = extra_data.as_ref().ok_or(RLibError::EncodingMissingExtraData)?;
751        let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
752
753        match GroupFormationsFormat::from_game(game_info)? {
754            GroupFormationsFormat::Troy => self.encode_troy(buffer)?,
755            GroupFormationsFormat::Warhammer3 => self.encode_wh3(buffer)?,
756            GroupFormationsFormat::Rome2 => self.encode_rom_2(buffer)?,
757            GroupFormationsFormat::Shogun2 => self.encode_sho_2(buffer)?,
758        };
759
760        Ok(())
761    }
762}