rpfm_lib/files/portrait_settings/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//! Portrait settings for unit and character portraits.
12//!
13//! This module handles binary portrait settings files that define camera positions
14//! and rendering parameters for unit portraits in Total War games. These portraits
15//! appear in various places:
16//! - Unit cards at the bottom of the battle/campaign UI
17//! - Character details windows in campaign
18//! - Diplomacy screens
19//!
20//! # Supported Versions
21//!
22//! - **Version 1**: Used in Warhammer 2, Warhammer 1, Thrones of Britannia, and Attila
23//! - **Version 4**: Used in Warhammer 3
24//!
25//! # File Location
26//!
27//! Portrait settings files are typically found at `ui/portraits/` within game packs.
28
29use getset::*;
30use serde_derive::{Serialize, Deserialize};
31
32use crate::error::{Result, RLibError};
33use crate::binary::{ReadBytes, WriteBytes};
34use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
35use crate::utils::check_size_mismatch;
36
37pub use crate::files::detection::portrait_settings::EXTENSION;
38
39mod versions;
40
41#[cfg(test)] mod portrait_settings_test;
42
43//---------------------------------------------------------------------------//
44// Enum & Structs
45//---------------------------------------------------------------------------//
46
47/// Portrait settings file containing camera configurations for unit portraits.
48///
49/// Each entry in this file corresponds to an art set and defines how the camera
50/// should be positioned when rendering that unit's portrait.
51#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
52#[getset(get = "pub", get_mut = "pub", set = "pub")]
53pub struct PortraitSettings {
54
55 /// Format version of this file (1 or 4).
56 version: u32,
57
58 /// Portrait entries, one per art set.
59 entries: Vec<Entry>,
60}
61
62/// A portrait entry defining camera settings for a specific art set.
63///
64/// Each entry links an art set ID to camera configurations for rendering
65/// head and optionally full-body portraits.
66#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
67#[getset(get = "pub", get_mut = "pub", set = "pub")]
68pub struct Entry {
69
70 /// Art set key this entry applies to.
71 ///
72 /// References a key in the art set tables (e.g., `land_units_tables`).
73 id: String,
74
75 /// Camera settings for the head/portrait view.
76 ///
77 /// This is the porthole camera used for unit cards in the bottom-left UI area.
78 camera_settings_head: CameraSetting,
79
80 /// Camera settings for the full-body view (optional).
81 ///
82 /// Used in character detail windows in campaign. Only needed for characters
83 /// and heroes; regular units don't require body camera settings.
84 camera_settings_body: Option<CameraSetting>,
85
86 /// Texture variants for this portrait.
87 ///
88 /// Allows different textures to be used based on conditions like season,
89 /// character level, or faction role.
90 variants: Vec<Variant>
91}
92
93/// Camera positioning and field-of-view settings for a portrait.
94///
95/// Defines how the camera is positioned relative to the character model when
96/// rendering a portrait. The camera has an auto-level feature that compensates
97/// for vertical rotation (pitch) exceeding 90/-90 degrees.
98#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
99#[getset(get = "pub", get_mut = "pub", set = "pub")]
100pub struct CameraSetting {
101
102 /// Distance from the character along the Z axis (depth).
103 z: f32,
104
105 /// Vertical displacement of the camera (height offset).
106 y: f32,
107
108 /// Horizontal rotation angle in degrees (left/right).
109 yaw: f32,
110
111 /// Vertical rotation angle in degrees (up/down).
112 pitch: f32,
113
114 /// Camera distance. Only used in version 1.
115 distance: f32,
116
117 /// Spherical coordinate theta. Only used in version 1.
118 theta: f32,
119
120 /// Spherical coordinate phi. Only used in version 1.
121 phi: f32,
122
123 /// Field of view angle in degrees.
124 fov: f32,
125
126 /// Skeleton bone to use as the camera focus point.
127 ///
128 /// If specified, all camera offsets and rotations are relative to this bone's
129 /// position. Common values include head or chest bones.
130 skeleton_node: String,
131}
132
133/// A texture variant for a portrait entry.
134///
135/// Variants allow different portrait textures to be used based on game conditions
136/// such as season, character level, age, or faction role.
137#[derive(PartialEq, Eq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
138#[getset(get = "pub", get_mut = "pub", set = "pub")]
139pub struct Variant {
140
141 /// Variant identifier matching the `variant_filename` column in variants tables.
142 filename: String,
143
144 /// Path to the diffuse (color) texture for this variant.
145 file_diffuse: String,
146
147 /// Path to first mask texture (purpose unknown).
148 file_mask_1: String,
149
150 /// Path to second mask texture (purpose unknown).
151 file_mask_2: String,
152
153 /// Path to third mask texture (purpose unknown).
154 file_mask_3: String,
155
156 /// Season when this variant applies. Only used in version 1.
157 season: String,
158
159 /// Character level threshold. Only used in version 1.
160 level: i32,
161
162 /// Character age threshold. Only used in version 1.
163 age: i32,
164
165 /// Whether this variant is for politicians. Only used in version 1.
166 politician: bool,
167
168 /// Whether this variant is for faction leaders. Only used in version 1.
169 faction_leader: bool,
170}
171
172//---------------------------------------------------------------------------//
173// Implementation of PortraitSettings
174//---------------------------------------------------------------------------//
175
176impl Decodeable for PortraitSettings {
177
178 fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
179 let version = data.read_u32()?;
180
181 let mut settings = Self::default();
182 settings.version = version;
183
184 match version {
185 1 => settings.read_v1(data)?,
186 4 => settings.read_v4(data)?,
187 _ => Err(RLibError::DecodingPortraitSettingUnsupportedVersion(version as usize))?,
188 }
189
190 // Trigger an error if there's left data on the source.
191 check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
192
193 Ok(settings)
194 }
195}
196
197impl Encodeable for PortraitSettings {
198
199 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
200 buffer.write_u32(self.version)?;
201
202 match self.version {
203 1 => self.write_v1(buffer)?,
204 4 => self.write_v4(buffer)?,
205 _ => unimplemented!()
206 }
207
208 Ok(())
209 }
210}
211
212
213impl PortraitSettings {
214
215 /// Deserializes portrait settings from a JSON string.
216 pub fn from_json(data: &str) -> Result<Self> {
217 serde_json::from_str(data).map_err(From::from)
218 }
219
220 /// Serializes this portrait settings to a pretty-printed JSON string.
221 pub fn to_json(&self) -> Result<String> {
222 serde_json::to_string_pretty(&self).map_err(From::from)
223 }
224}
225
226impl Default for Variant {
227 fn default() -> Self {
228 Self {
229 filename: Default::default(),
230 file_diffuse: Default::default(),
231 file_mask_1: Default::default(),
232 file_mask_2: Default::default(),
233 file_mask_3: Default::default(),
234 season: "none".to_owned(),
235 level: Default::default(),
236 age: Default::default(),
237 politician: Default::default(),
238 faction_leader: Default::default(),
239 }
240 }
241}