rpfm_lib/files/animpack/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//! AnimPack container file format support.
12//!
13//! AnimPacks (`.animpack` files) are container files that bundle animation-related game
14//! data into a single archive. They are primarily used to organize and distribute animation
15//! assets for units and characters in Total War games.
16//!
17//! # File Format
18//!
19//! AnimPacks use a simple binary format with a file count header followed by a list of
20//! embedded files. Each embedded file includes its path, size, and raw data.
21//!
22//! ```text
23//! [u32] file_count
24//! For each file:
25//! [u8 + string] file_path (with backslashes)
26//! [u32] file_size
27//! [bytes] file_data
28//! ```
29//!
30//! # Contained File Types
31//!
32//! AnimPacks typically contain:
33//! - [`AnimsTable`] - Animation table indices
34//! - [`AnimFragmentBattle`] - Animation fragments
35//! - [`MatchedCombat`] - Matched combat definitions
36//! - Other animation-related binary files
37//!
38//! [`AnimsTable`]: crate::files::anims_table::AnimsTable
39//! [`AnimFragmentBattle`]: crate::files::anim_fragment_battle::AnimFragmentBattle
40//! [`MatchedCombat`]: crate::files::matched_combat::MatchedCombat
41//!
42//! # File Location
43//!
44//! AnimPacks are usually found in:
45//! ```text
46//! animations/*.animpack
47//! ```
48//!
49//! # Usage
50//!
51//! ```ignore
52//! use rpfm_lib::files::animpack::AnimPack;
53//! use rpfm_lib::files::{Container, Decodeable};
54//!
55//! // Decode an AnimPack from disk
56//! let mut extra_data = DecodeableExtraData::default();
57//! extra_data.set_disk_file_path(Some("animations/unit.animpack"));
58//! extra_data.set_data_size(file_size);
59//! extra_data.set_timestamp(timestamp);
60//!
61//! let animpack = AnimPack::decode(&mut reader, &Some(extra_data))?;
62//!
63//! // Access contained files
64//! for (path, file) in animpack.files() {
65//! println!("File: {}", path);
66//! }
67//!
68//! // Extract a specific file
69//! if let Some(file) = animpack.file_by_path("battle/animations/humanoid01.bin") {
70//! let data = file.encode(&None, false, false, true)?;
71//! }
72//! ```
73//!
74//! # Version Support
75//!
76//! Complete support for all known AnimPack versions across Total War games.
77
78use serde_derive::{Serialize, Deserialize};
79
80use std::collections::HashMap;
81use std::path::PathBuf;
82use std::str::FromStr;
83
84use crate::binary::{ReadBytes, WriteBytes};
85use crate::error::Result;
86use crate::files::*;
87
88pub use crate::files::detection::animpack::EXTENSION;
89
90#[cfg(test)] mod animpack_test;
91
92//---------------------------------------------------------------------------//
93// Enum & Structs
94//---------------------------------------------------------------------------//
95
96/// Represents an AnimPack file decoded in memory.
97///
98/// AnimPacks are container files that bundle animation-related assets into a single
99/// archive. This struct holds the complete AnimPack structure including metadata and
100/// all contained files.
101///
102/// # Fields
103///
104/// - `disk_file_path`: Path to the AnimPack file on disk (empty if in-memory only)
105/// - `disk_file_offset`: Byte offset within the disk file (0 if standalone file)
106/// - `local_timestamp`: Last modified timestamp for change detection
107/// - `paths`: Lowercase path lookup cache for case-insensitive file searches
108/// - `files`: Map of file paths to their [`RFile`] data
109///
110/// # Binary Format
111///
112/// | Bytes | Type | Data |
113/// | -------------- | ---------------------------- | --------------------------------------- |
114/// | 4 | [u32] | File Count |
115/// | X * File Count | [File](#file-structure) List | List of files inside the AnimPack File |
116///
117/// ## File Structure
118///
119/// | Bytes | Type | Data |
120/// | ----------- | -------------- | --------------------- |
121/// | * | Sized StringU8 | File Path |
122/// | 4 | [u32] | File Length in bytes |
123/// | File Length | &\[[u8]\] | File Data |
124///
125/// # Container Implementation
126///
127/// AnimPack implements the [`Container`] trait, providing:
128/// - File extraction and insertion
129/// - Case-insensitive path lookup via paths cache
130/// - Lazy loading support (when unencrypted)
131/// - Timestamp-based change detection
132///
133/// # Lazy Loading
134///
135/// When `lazy_load` is enabled in [`DecodeableExtraData`], file data is not read
136/// immediately but loaded on-demand. This reduces memory usage for large AnimPacks.
137/// Lazy loading requires:
138/// - Valid `disk_file_path` to a file on disk
139/// - Unencrypted data (encrypted files are always fully loaded)
140///
141/// # Example
142///
143/// ```ignore
144/// use rpfm_lib::files::animpack::AnimPack;
145/// use rpfm_lib::files::Container;
146///
147/// // Create a new empty AnimPack
148/// let mut animpack = AnimPack::default();
149///
150/// // Add a file
151/// animpack.insert(rfile, "battle/animations/unit.bin")?;
152///
153/// // Look up a file (case-insensitive)
154/// if let Some(file) = animpack.file_by_path("BATTLE/animations/UNIT.bin") {
155/// println!("Found file!");
156/// }
157/// ```
158#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
159pub struct AnimPack {
160
161 /// Path to this AnimPack file on disk.
162 ///
163 /// If the AnimPack has not been saved to disk or exists only in memory,
164 /// this is an empty string.
165 disk_file_path: String,
166
167 /// Byte offset of this AnimPack within its disk file.
168 ///
169 /// If the AnimPack is a standalone file (not embedded in another file),
170 /// this is 0.
171 disk_file_offset: u64,
172
173 /// Last modified timestamp of the disk file in seconds.
174 ///
175 /// Used to detect external modifications when lazy loading is enabled.
176 /// Set to 0 for in-memory AnimPacks.
177 local_timestamp: u64,
178
179 /// Case-insensitive path lookup cache.
180 ///
181 /// Maps lowercase file paths to a list of their original-cased variants.
182 /// This enables fast case-insensitive file lookups via [`Container::file_by_path()`].
183 paths: HashMap<String, Vec<String>>,
184
185 /// Map of file paths to their data.
186 ///
187 /// Keys are file paths as stored in the AnimPack (with forward slashes).
188 /// Values are [`RFile`] instances containing the file data (cached or lazy-loaded).
189 files: HashMap<String, RFile>,
190}
191
192//---------------------------------------------------------------------------//
193// Implementation of AnimPack
194//---------------------------------------------------------------------------//
195
196impl Container for AnimPack {
197
198 fn disk_file_path(&self) -> &str {
199 &self.disk_file_path
200 }
201
202 fn files(&self) -> &HashMap<String, RFile> {
203 &self.files
204 }
205
206 fn files_mut(&mut self) -> &mut HashMap<String, RFile> {
207 &mut self.files
208 }
209
210 fn disk_file_offset(&self) -> u64 {
211 self.disk_file_offset
212 }
213
214 fn paths_cache(&self) -> &HashMap<String, Vec<String>> {
215 &self.paths
216 }
217
218 fn paths_cache_mut(&mut self) -> &mut HashMap<String, Vec<String>> {
219 &mut self.paths
220 }
221
222 fn local_timestamp(&self) -> u64 {
223 self.local_timestamp
224 }
225}
226
227impl Decodeable for AnimPack {
228
229 /// Decodes an AnimPack from a binary data source.
230 ///
231 /// # Parameters
232 ///
233 /// - `data`: Binary reader implementing [`ReadBytes`]
234 /// - `extra_data`: Required decoding context (see below)
235 ///
236 /// # Required Extra Data Fields
237 ///
238 /// This implementation requires [`DecodeableExtraData`] with:
239 /// - `lazy_load`: Enable lazy loading (ignored if encrypted)
240 /// - `is_encrypted`: Whether the AnimPack data is encrypted
241 /// - `disk_file_path`: Path to file on disk (required for lazy loading)
242 /// - `disk_file_offset`: Offset within disk file (0 for standalone files)
243 /// - `data_size`: Total size of AnimPack data in bytes
244 /// - `timestamp`: Last modified timestamp in seconds (0 for in-memory)
245 ///
246 /// # Returns
247 ///
248 /// - `Ok(AnimPack)`: Successfully decoded AnimPack with all files
249 /// - `Err(_)`: I/O error, malformed data, or missing required extra data
250 ///
251 /// # Lazy Loading Behavior
252 ///
253 /// When `lazy_load` is true and data is unencrypted:
254 /// - File metadata is read immediately
255 /// - File data is loaded on-demand when accessed
256 /// - Requires valid `disk_file_path` to a file on disk
257 ///
258 /// When encrypted or lazy loading disabled:
259 /// - All file data is read into memory immediately
260 ///
261 /// # Example
262 ///
263 /// ```ignore
264 /// use std::fs::File;
265 /// use std::io::BufReader;
266 /// use rpfm_lib::binary::ReadBytes;
267 /// use rpfm_lib::files::{Decodeable, DecodeableExtraData, animpack::AnimPack};
268 /// use rpfm_lib::utils::last_modified_time_from_file;
269 ///
270 /// let path = "animations/unit.animpack";
271 /// let mut reader = BufReader::new(File::open(path)?);
272 ///
273 /// let mut extra_data = DecodeableExtraData::default();
274 /// extra_data.set_disk_file_path(Some(path));
275 /// extra_data.set_data_size(reader.len()?);
276 /// extra_data.set_timestamp(last_modified_time_from_file(reader.get_ref())?);
277 ///
278 /// let animpack = AnimPack::decode(&mut reader, &Some(extra_data))?;
279 /// ```
280 fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
281 let extra_data = extra_data.as_ref().ok_or(RLibError::DecodingMissingExtraData)?;
282
283 // If we're reading from a file on disk, we require a valid path.
284 // If we're reading from a file on memory, we don't need a valid path.
285 let disk_file_path = match extra_data.disk_file_path {
286 Some(path) => {
287 let file_path = PathBuf::from_str(path).map_err(|_|RLibError::DecodingMissingExtraDataField("disk_file_path".to_owned()))?;
288 if file_path.is_file() {
289 path.to_owned()
290 } else {
291 return Err(RLibError::DecodingMissingExtraData)
292 }
293 }
294 None => String::new()
295 };
296
297 let disk_file_offset = extra_data.disk_file_offset;
298 let disk_file_size = extra_data.data_size;
299 let local_timestamp = extra_data.timestamp;
300 let is_encrypted = extra_data.is_encrypted;
301
302 // If we don't have a path, or the file is encrypted, we can't lazy-load.
303 let lazy_load = !disk_file_path.is_empty() && !is_encrypted && extra_data.lazy_load;
304 let file_count = data.read_u32()?;
305
306 let mut anim_pack = Self {
307 disk_file_path,
308 disk_file_offset,
309 local_timestamp,
310 paths: HashMap::new(),
311 files: if file_count < 50_000 { HashMap::with_capacity(file_count as usize) } else { HashMap::new() },
312 };
313
314 for _ in 0..file_count {
315 let path_in_container = data.read_sized_string_u8()?.replace('\\', "/");
316 let size = data.read_u32()?;
317
318 // Encrypted files cannot be lazy-loaded. They must be read in-place.
319 if !lazy_load || is_encrypted {
320 let data = data.read_slice(size as usize, false)?;
321 let file = RFile {
322 path: path_in_container.to_owned(),
323 timestamp: None,
324 file_type: FileType::AnimPack,
325 container_name: None,
326 data: RFileInnerData::Cached(data),
327 };
328
329 anim_pack.files.insert(path_in_container, file);
330 }
331
332 // Unencrypted and files are not read, but lazy-loaded, unless specified otherwise.
333 else {
334 let data_pos = data.stream_position()? - disk_file_offset;
335 let file = RFile::new_from_container(&anim_pack, size as u64, false, None, data_pos, local_timestamp, &path_in_container)?;
336 data.seek(SeekFrom::Current(size as i64))?;
337
338 anim_pack.files.insert(path_in_container, file);
339 }
340 }
341
342 anim_pack.paths_cache_generate();
343
344 anim_pack.files.par_iter_mut().map(|(_, file)| file.guess_file_type()).collect::<Result<()>>()?;
345
346 check_size_mismatch(data.stream_position()? as usize - anim_pack.disk_file_offset as usize, disk_file_size as usize)?;
347 Ok(anim_pack)
348 }
349}
350
351impl Encodeable for AnimPack {
352
353 /// Encodes this AnimPack to a binary data stream.
354 ///
355 /// # Parameters
356 ///
357 /// - `buffer`: Binary writer implementing [`WriteBytes`]
358 /// - `extra_data`: Encoding options (not used, pass [`None`])
359 ///
360 /// # Returns
361 ///
362 /// - `Ok(())`: Successfully encoded AnimPack
363 /// - `Err(_)`: I/O error, file too large, or encoding error
364 ///
365 /// # Encoding Behavior
366 ///
367 /// - Files are sorted alphabetically by path (case-insensitive)
368 /// - Paths use forward slashes (`/`) not backslashes (`\`)
369 /// - Each file is encoded inline with its size prefix
370 /// - Files larger than 4GB (u32::MAX) return an error
371 ///
372 /// # Path Format
373 ///
374 /// **Important**: Encoded paths use forward slashes because animation sets created
375 /// by assed tool break if backslashes are used.
376 ///
377 /// # Example
378 ///
379 /// ```ignore
380 /// use std::fs::File;
381 /// use std::io::{BufWriter, Write};
382 /// use rpfm_lib::files::{Encodeable, animpack::AnimPack};
383 ///
384 /// let mut animpack = AnimPack::default();
385 /// // ... add files to animpack ...
386 ///
387 /// let mut encoded = vec![];
388 /// animpack.encode(&mut encoded, &None)?;
389 ///
390 /// // Write to disk
391 /// let mut writer = BufWriter::new(File::create("output.animpack")?);
392 /// writer.write_all(&encoded)?;
393 /// ```
394 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()> {
395 buffer.write_u32(self.files.len() as u32)?;
396
397 // NOTE: This has to use /, not \, because for some reason the animsets made by Assed break if we use \.
398 let mut sorted_files = self.files.iter_mut().collect::<Vec<(&String, &mut RFile)>>();
399 sorted_files.sort_unstable_by_key(|(path, _)| path.to_lowercase());
400
401 for (path, file) in sorted_files {
402 buffer.write_sized_string_u8(path)?;
403
404 let data = file.encode(extra_data, false, false, true)?.unwrap();
405
406 // Error on files too big for the AnimPack.
407 if data.len() > u32::MAX as usize {
408 return Err(RLibError::DataTooBigForContainer("AnimPack".to_owned(), u32::MAX as u64, data.len(), path.to_owned()));
409 }
410
411 buffer.write_u32(data.len() as u32)?;
412 buffer.write_all(&data)?;
413 }
414
415 Ok(())
416 }
417}