Skip to main content

rpfm_lib/files/anims_table/
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//! Animation table file format support.
12//!
13//! This module handles animation table files (`*_tables.bin`) which define animation
14//! sets and their associated fragments for unit skeletons in Total War games. These
15//! files act as indices that map skeleton types to their animation fragment files.
16//!
17//! # File Format
18//!
19//! Animation tables use a binary format (version 2) containing:
20//! - List of animation table entries
21//! - Each entry maps a skeleton type to animation fragments
22//! - Fragment references with metadata
23//!
24//! # File Naming Convention
25//!
26//! Animation table files must end with `_tables.bin` to be recognized by RPFM.
27//! This is a library-specific requirement for disambiguation, not a game limitation.
28//!
29//! Common naming patterns:
30//! - `humanoid01_tables.bin` - Human skeleton animations
31//! - `cavalry_tables.bin` - Mounted unit animations
32//! - `monster_tables.bin` - Large creature animations
33//!
34//! # File Organization
35//!
36//! Animation tables are stored in:
37//! ```text
38//! animations/animation_tables/{skeleton_type}_tables.bin
39//! ```
40//!
41//! # Structure
42//!
43//! Each table contains entries that define:
44//! - Animation table name (logical identifier)
45//! - Skeleton type (which skeleton this applies to)
46//! - Mount table reference (for mounted units)
47//! - List of animation fragments with metadata
48//!
49//! # Supported Versions
50//!
51//! Currently only version 2 is supported, used in modern Total War games
52//! (Warhammer 2, Three Kingdoms, Warhammer 3, etc.).
53//!
54//! # Usage
55//!
56//! ```ignore
57//! use rpfm_lib::files::anims_table::AnimsTable;
58//! use rpfm_lib::files::Decodeable;
59//!
60//! // Decode an animation table
61//! let table = AnimsTable::decode(&mut data, &None)?;
62//!
63//! // Access entries
64//! for entry in table.entries() {
65//!     println!("Table: {} for skeleton: {}",
66//!         entry.table_name(),
67//!         entry.skeleton_type()
68//!     );
69//!
70//!     // List fragments
71//!     for fragment in entry.fragments() {
72//!         println!("  Fragment: {}", fragment.name());
73//!     }
74//! }
75//! ```
76
77use getset::{Getters, Setters};
78use serde_derive::{Serialize, Deserialize};
79
80use crate::binary::{ReadBytes, WriteBytes};
81use crate::error::{RLibError, Result};
82use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
83use crate::utils::check_size_mismatch;
84
85pub use crate::files::detection::anims_table::{BASE_PATH, EXTENSION};
86
87mod versions;
88
89#[cfg(test)] mod anims_table_test;
90
91//---------------------------------------------------------------------------//
92//                              Enum & Structs
93//---------------------------------------------------------------------------//
94
95/// Represents an animation table file (`*_tables.bin`).
96///
97/// Animation tables serve as indices mapping skeleton types to their available animation
98/// fragment files. Each table contains one or more entries defining animation sets for
99/// different skeleton configurations.
100///
101/// # Fields
102///
103/// - `version`: File format version (currently only version 2 is supported)
104/// - `entries`: List of animation table entries, each mapping a skeleton to fragments
105///
106/// # Version Support
107///
108/// - **Version 2**: Current format used in Warhammer 2, Three Kingdoms, Warhammer 3
109///
110/// # Example
111///
112/// ```ignore
113/// // Create a new animation table
114/// let mut table = AnimsTable::default();
115/// table.set_version(2);
116///
117/// // Add an entry for humanoid skeletons
118/// let mut entry = Entry::default();
119/// entry.set_table_name("humanoid01_animations".to_string());
120/// entry.set_skeleton_type("humanoid01".to_string());
121/// table.entries_mut().push(entry);
122/// ```
123#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
124#[getset(get = "pub", set = "pub")]
125pub struct AnimsTable {
126    /// File format version number.
127    ///
128    /// Only version 2 is currently supported.
129    version: u32,
130
131    /// List of animation table entries.
132    ///
133    /// Each entry defines animations for a specific skeleton type and configuration.
134    entries: Vec<Entry>,
135}
136
137/// Represents a single animation table entry mapping a skeleton to fragments.
138///
139/// Each entry defines an animation set for a specific skeleton type. Entries can
140/// reference mount tables for cavalry/mounted units and contain lists of animation
141/// fragments that apply to this skeleton configuration.
142///
143/// # Fields
144///
145/// - `table_name`: Logical name of this animation table (e.g., "humanoid01_animations")
146/// - `skeleton_type`: Skeleton identifier this entry applies to (e.g., "humanoid01")
147/// - `mount_table_name`: Reference to mount table for mounted units (empty for infantry)
148/// - `fragments`: List of animation fragment references
149/// - `uk_6`: Unknown boolean flag (purpose unclear)
150/// - `uk_7`: Unknown boolean flag (purpose unclear)
151///
152/// # Mount Tables
153///
154/// For mounted units (cavalry, chariots, monsters with riders), `mount_table_name`
155/// references another animation table that defines the mount's animations. Infantry
156/// units leave this field empty.
157///
158/// # Example
159///
160/// ```ignore
161/// // Infantry entry
162/// let mut infantry = Entry::default();
163/// infantry.set_table_name("hu1_animations".to_string());
164/// infantry.set_skeleton_type("humanoid01".to_string());
165/// infantry.set_mount_table_name(String::new());
166///
167/// // Cavalry entry
168/// let mut cavalry = Entry::default();
169/// cavalry.set_table_name("cav_animations".to_string());
170/// cavalry.set_skeleton_type("humanoid01".to_string());
171/// cavalry.set_mount_table_name("horse_animations".to_string());
172/// ```
173#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
174#[getset(get = "pub", set = "pub")]
175pub struct Entry {
176    /// Logical name of this animation table.
177    ///
178    /// Used as an identifier for this animation set (e.g., "humanoid01_animations").
179    ///
180    /// FIXME: This is possibly not table_name, but skeleton_type, and skeleton_type is possibly skeleton_type_cinematic.
181    table_name: String,
182
183    /// Skeleton type identifier.
184    ///
185    /// Specifies which skeleton this entry's animations apply to (e.g., "humanoid01",
186    /// "cavalry", "monster").
187    skeleton_type: String,
188
189    /// Mount table reference for mounted units.
190    ///
191    /// For cavalry/mounted units, this references the animation table for the mount
192    /// (e.g., "horse_animations"). Empty string for infantry/unmounted units.
193    mount_table_name: String,
194
195    /// List of animation fragments for this skeleton.
196    ///
197    /// Each fragment references an animation file and associated metadata.
198    fragments: Vec<Fragment>,
199
200    /// Unknown boolean flag.
201    ///
202    /// Purpose currently unclear. May be related to animation blending or state flags.
203    uk_6: bool,
204
205    /// Unknown boolean flag.
206    ///
207    /// Purpose currently unclear. May be related to animation blending or state flags.
208    uk_7: bool,
209}
210
211/// Represents a reference to an animation fragment file.
212///
213/// Fragments are individual animation files that can be applied to a skeleton.
214/// Each fragment reference includes the fragment's name and associated metadata.
215///
216/// # Fields
217///
218/// - `name`: Animation fragment file name (without path or extension)
219/// - `uk_5`: Unknown 32-bit metadata value (purpose unclear)
220///
221/// # Fragment Naming
222///
223/// Fragment names typically follow patterns like:
224/// - `hu1_walk_01` - Humanoid walking animation
225/// - `cav_charge_02` - Cavalry charge animation
226/// - `monster_attack_melee` - Monster melee attack
227///
228/// The actual fragment files are stored in separate `.bin` or `.frg` files in the
229/// animations directory structure.
230///
231/// # Example
232///
233/// ```ignore
234/// let mut fragment = Fragment::default();
235/// fragment.set_name("hu1_idle_breathing_01".to_string());
236/// fragment.set_uk_5(0);  // Unknown field
237/// ```
238#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
239#[getset(get = "pub", set = "pub")]
240pub struct Fragment {
241    /// Animation fragment file name.
242    ///
243    /// The name of the fragment file (without path or extension). For example,
244    /// "hu1_walk_01" refers to a humanoid walking animation fragment.
245    name: String,
246
247    /// Unknown 32-bit metadata value.
248    ///
249    /// Purpose currently unclear. May be related to fragment priority, blending
250    /// weight, or other animation system metadata.
251    uk_5: u32,
252}
253
254//---------------------------------------------------------------------------//
255//                      Implementation of AnimsTable
256//---------------------------------------------------------------------------//
257
258impl Decodeable for AnimsTable {
259
260    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
261        let mut table = Self::default();
262        table.version = data.read_u32()?;
263
264        match table.version {
265            2 => table.read_v2(data)?,
266            _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(table.version as usize))?,
267        }
268
269        // If we are not in the last byte, it means we didn't parse the entire file, which means this file is corrupt.
270        check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
271
272        Ok(table)
273    }
274}
275
276impl Encodeable for AnimsTable {
277
278    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
279        buffer.write_u32(self.version)?;
280
281        match self.version {
282            2 => self.write_v2(buffer)?,
283            _ => Err(RLibError::DecodingAnimFragmentUnsupportedVersion(self.version as usize))?,
284        };
285
286        Ok(())
287    }
288}