1use 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#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
95#[getset(get = "pub", get_mut = "pub", set = "pub")]
96pub struct GroupFormations {
97 formations: Vec<GroupFormation>,
99}
100
101#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
106#[getset(get = "pub", get_mut = "pub", set = "pub")]
107pub struct GroupFormation {
108 name: String,
110
111 ai_priority: f32,
113
114 ai_purpose: AIPurpose,
116
117 uk_2: u32,
119
120 min_unit_category_percentage: Vec<MinUnitCategoryPercentage>,
122
123 ai_supported_subcultures: Vec<String>,
127
128 ai_supported_factions: Vec<String>,
132
133 group_formation_blocks: Vec<GroupFormationBlock>,
135}
136
137#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
141#[getset(get = "pub", get_mut = "pub", set = "pub")]
142pub struct MinUnitCategoryPercentage {
143 category: UnitCategory,
145
146 percentage: u32,
148}
149
150#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
155#[getset(get = "pub", get_mut = "pub", set = "pub")]
156pub struct GroupFormationBlock {
157 block_id: u32,
159
160 block: Block,
162}
163
164#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
170pub enum Block {
171 ContainerAbsolute(ContainerAbsolute),
173
174 ContainerRelative(ContainerRelative),
176
177 Spanning(Spanning)
179}
180
181#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
186#[getset(get = "pub", get_mut = "pub", set = "pub")]
187pub struct ContainerAbsolute {
188 block_priority: f32,
190
191 entity_arrangement: EntityArrangement,
193
194 inter_entity_spacing: f32,
196
197 crescent_y_offset: f32,
199
200 position_x: f32,
202
203 position_y: f32,
205
206 minimum_entity_threshold: i32,
208
209 maximum_entity_threshold: i32,
211
212 entity_preferences: Vec<EntityPreference>,
214}
215
216#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
221#[getset(get = "pub", get_mut = "pub", set = "pub")]
222pub struct ContainerRelative {
223 block_priority: f32,
225
226 relative_block_id: u32,
228
229 entity_arrangement: EntityArrangement,
231
232 inter_entity_spacing: f32,
234
235 crescent_y_offset: f32,
237
238 position_x: f32,
240
241 position_y: f32,
243
244 minimum_entity_threshold: i32,
246
247 maximum_entity_threshold: i32,
249
250 entity_preferences: Vec<EntityPreference>,
252}
253
254#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
259#[getset(get = "pub", get_mut = "pub", set = "pub")]
260pub struct EntityPreference {
261 priority: f32,
263
264 entity: Entity,
269
270 entity_weight: EntityWeight,
272
273 uk_1: u32,
275
276 entity_class: String,
278}
279
280#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
284#[getset(get = "pub", get_mut = "pub", set = "pub")]
285pub struct Spanning {
286 spanned_block_ids: Vec<u32>,
288}
289
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
292pub enum GroupFormationsFormat {
293
294 Shogun2,
296
297 Rome2,
299
300 Troy,
302
303 Warhammer3,
305}
306
307#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
312pub enum AIPurpose {
313 V1(versions::v1::AIPurposeFlags),
314 V2(versions::v2::AIPurposeFlags),
315}
316
317#[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#[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#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
348pub enum Entity {
349 V1(versions::v1::EntityType),
350 V2(versions::v2::EntityType),
351}
352
353#[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
369impl GroupFormationsFormat {
374
375 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 _ => Err(RLibError::DecodingUnsupportedGameSelected(game_info.key().to_string())),
403 }
404 }
405
406 pub fn has_ai_supported_factions(&self) -> bool {
408 matches!(self, Self::Shogun2 | Self::Rome2 | Self::Warhammer3)
409 }
410
411 pub fn has_ai_supported_subcultures(&self) -> bool {
413 matches!(self, Self::Rome2 | Self::Troy | Self::Warhammer3)
414 }
415
416 pub fn has_formation_uk_2(&self) -> bool {
418 matches!(self, Self::Troy | Self::Warhammer3)
419 }
420
421 pub fn has_entity_weight(&self) -> bool {
423 matches!(self, Self::Rome2 | Self::Troy | Self::Warhammer3)
424 }
425
426 pub fn has_entity_class(&self) -> bool {
428 matches!(self, Self::Troy | Self::Warhammer3)
429 }
430
431 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 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 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 Self::Troy | Self::Warhammer3 => Entity::V2(versions::v2::EntityType::Invalid),
455 }
456 }
457}
458
459impl GroupFormation {
460
461 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 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 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 pub fn bits(&self) -> u32 {
514 match self {
515 Self::V1(flags) => flags.bits(),
516 Self::V2(flags) => flags.bits(),
517 }
518 }
519
520 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 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 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 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 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 pub const ALL: [Self; 4] = [Self::Line, Self::Column, Self::CrescentFront, Self::CrescentBack];
568}
569
570impl UnitCategory {
571
572 pub const ALL: [Self; 6] = [Self::Cavalry, Self::InfantryMelee, Self::InfantryRanged, Self::NavalHeavy, Self::NavalMedium, Self::NavalLight];
574}
575
576impl EntityWeight {
577
578 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 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}