rpfm_lib/files/font/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//! CUF (Creative Assembly Unicode Font) file format support.
12//!
13//! This module handles `.cuf` font files used by Total War games to render text.
14//! CUF files contain glyph data, metrics, and optional kerning information for
15//! bitmap-based font rendering.
16//!
17//! # File Format
18//!
19//! CUF files use a custom binary format with the signature `CUF0`. The structure includes:
20//! - Font properties (line height, baseline, spacing, etc.)
21//! - Glyph mapping table (character code to glyph index)
22//! - Glyph dimensions (allocated size, actual size)
23//! - Glyph bitmap data (8-bit grayscale)
24//! - Optional kerning data (pair-wise spacing adjustments)
25//!
26//! # Testing Status
27//!
28//! Currently, only Empire: Total War fonts have been thoroughly tested. Other games
29//! may use slight variations of the format.
30//!
31//! # Credits
32//!
33//! Most of the reverse-engineering work was done by the Europa Barbarorum Team for
34//! their CUF tool. Their comments and insights have been ported here for reference.
35//!
36//! # Glyph Storage
37//!
38//! Glyphs are stored as 8-bit grayscale bitmaps. The format uses a sparse representation
39//! where only used character codes (non-0xFFFF values) have associated glyph data.
40//!
41//! # Kerning
42//!
43//! Kerning support is optional and only present in some font files. When present,
44//! kerning data provides spacing adjustments for specific character pairs to improve
45//! visual appearance.
46//!
47//! # Usage
48//!
49//! ```ignore
50//! use rpfm_lib::files::font::Font;
51//! use rpfm_lib::files::Decodeable;
52//!
53//! // Decode a font file
54//! let font = Font::decode(&mut data, &None)?;
55//!
56//! // Access font properties
57//! println!("Line height: {}", font.properties().line_height());
58//! println!("Supports kerning: {}", font.supports_kerning());
59//!
60//! // Access glyphs
61//! for (char_code, glyph) in font.glyphs() {
62//! println!("Character {}: {}x{}", char_code, glyph.width(), glyph.height());
63//! }
64//! ```
65
66use getset::*;
67use serde_derive::{Serialize, Deserialize};
68
69use std::collections::BTreeMap;
70use std::io::Write;
71
72use crate::binary::{ReadBytes, WriteBytes};
73use crate::error::{Result, RLibError};
74use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
75use crate::utils::check_size_mismatch;
76
77pub use crate::files::detection::font::EXTENSION;
78
79#[cfg(test)] mod font_test;
80
81/// CUF file format signature (`CUF0`).
82const SIGNATURE: &[u8; 4] = b"CUF0";
83
84//---------------------------------------------------------------------------//
85// Enum & Structs
86//---------------------------------------------------------------------------//
87
88/// Represents a CUF font file.
89///
90/// Contains font properties, glyph data, and optional kerning information.
91/// Glyphs are stored in a sparse map indexed by character code (0-65535).
92#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
93#[getset(get = "pub", get_mut = "pub", set = "pub")]
94pub struct Font {
95 /// Font rendering properties and metrics.
96 properties: CUFProperties,
97
98 /// Map of character codes to glyph data.
99 ///
100 /// Only contains entries for characters actually defined in the font.
101 /// Character codes map to Unicode-like values.
102 glyphs: BTreeMap<u16, Glyph>,
103
104 /// Whether this font file includes kerning data.
105 supports_kerning: bool,
106
107 /// Character codes below this value do not have kerning data.
108 kerning_skip: u16,
109
110 /// Kerning adjustment blocks (one per character code >= kerning_skip).
111 kerning_blocks: Vec<Vec<u8>>,
112}
113
114/// Font properties controlling text layout and rendering.
115///
116/// Many of these properties are indices or references whose exact purpose is still
117/// being researched. Comments from the Europa Barbarorum Team's research have been
118/// preserved for reference.
119#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
120#[getset(get = "pub", get_mut = "pub", set = "pub")]
121pub struct CUFProperties {
122 /// Unknown purpose (first CUF property).
123 first_prop: u16,
124
125 /// Unknown purpose. Second CUF property.
126 second_prop: u16,
127
128 /// Index of the value which appears to have something to do with line height. Underscore line? Base line?
129 line_height: u16,
130
131 /// Unknown purpose. Fourth CUF property.
132 fourth_prop: u16,
133
134 /// Unknown purpose. Fifth CUF property.
135 fifth_prop: u16,
136
137 /// Index of the value which appears to correspond to a ‘baseline’ of sorts in the CUF file format.
138 baseline: u16,
139
140 /// Index of the value which determines y-offset w.r.t. the bounding box of a string of text in this font.
141 layout_y_offset: u16,
142
143 /// Used to specify how wide a space is for justification and text wrapping calculations.
144 space_justify: u16,
145
146 /// Index of the value which determines x-offset w.r.t. the bounding box of a string of text in this font.
147 layout_x_offset: u16,
148
149 /// Index of the value which determines a maximum width for glyphs.
150 /// Glyphs which are wider than the maximum specified for this property will appear cut-off.
151 ///
152 /// There appears to be no effect on the position of a glyph
153 /// after a glyph of which the advance is larger than the value specified for this setting.
154 ///
155 /// Note that individual glyphs contain sufficient information to calculate a much more optimal bounding box than by simply using
156 /// multiples of the value corresponding to this index.
157 h_size: u16,
158
159 /// Index of the value which determines a maximum height for glyphs.
160 /// The corresponding value probably should include leading.
161 /// Glyphs which are taller than the maximum specified for this property will appear cut-off.
162 ///
163 /// Too small values for this property may result in crashes or unspecified errors on exit in M2TW.
164 ///
165 /// Note that individual glyphs contain sufficient information to calculate a much more optimal bounding box than by simply using
166 /// multiples of the value corresponding to this index.
167 v_size: u16,
168}
169
170/// Represents a single glyph (character) in a font.
171///
172/// Contains the character's bitmap data and rendering metrics. Glyphs store both
173/// allocated dimensions (for layout) and actual bitmap dimensions (for rendering).
174///
175/// # Bitmap Data
176///
177/// The `data` field contains 8-bit grayscale pixel data in row-major order:
178/// - Each byte represents one pixel's intensity/alpha (0-255)
179/// - Total size is `width × height` bytes
180/// - Empty glyphs (spaces, etc.) may have zero-sized data
181///
182/// # Dimensions
183///
184/// Two sets of dimensions are stored:
185/// - **Allocated** (`alloc_width`, `alloc_height`): Space reserved for layout
186/// - **Actual** (`width`, `height`): Size of the bitmap data
187///
188/// Allocated height can be negative for characters with descenders (e.g., 'g', 'y').
189#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
190#[getset(get = "pub", get_mut = "pub", set = "pub")]
191pub struct Glyph {
192 /// Glyph code/index in the font.
193 ///
194 /// This is the internal glyph identifier used by the font file format.
195 code: u16,
196
197 /// Unicode character code this glyph represents.
198 ///
199 /// Maps to the Unicode character value (0-65535 range for BMP).
200 /// This is the character that will be displayed when this glyph is rendered.
201 character: u16,
202
203 /// Allocated height in the font layout (can be negative).
204 ///
205 /// This is the vertical space reserved for the glyph in text layout.
206 /// Negative values indicate descenders (parts of characters below the baseline).
207 /// For example, lowercase 'g' or 'y' typically have negative allocated heights.
208 alloc_height: i8,
209
210 /// Allocated width in the font layout.
211 ///
212 /// This is the horizontal advance width - how far to move the cursor after
213 /// rendering this glyph. May differ from the actual bitmap width.
214 alloc_width: u8,
215
216 /// Actual bitmap width in pixels.
217 ///
218 /// The width of the glyph's pixel data. The `data` field contains
219 /// `width × height` bytes of bitmap information.
220 width: u8,
221
222 /// Actual bitmap height in pixels.
223 ///
224 /// The height of the glyph's pixel data. The `data` field contains
225 /// `width × height` bytes of bitmap information.
226 height: u8,
227
228 /// Kerning adjustment value.
229 ///
230 /// Used for pair-wise spacing adjustments between specific character combinations.
231 /// The exact interpretation depends on the kerning data in the font.
232 kerning: u32,
233
234 /// 8-bit grayscale bitmap data.
235 ///
236 /// Contains the glyph's pixel data in row-major order:
237 /// - Size: `width × height` bytes
238 /// - Format: One byte per pixel (0 = transparent, 255 = opaque)
239 /// - Empty for characters with no visual representation (e.g., spaces)
240 ///
241 /// # Example Layout
242 ///
243 /// For a 3×2 glyph, data is stored as:
244 /// ```text
245 /// [row0_col0, row0_col1, row0_col2, row1_col0, row1_col1, row1_col2]
246 /// ```
247 data: Vec<u8>,
248}
249
250//---------------------------------------------------------------------------//
251// Implementation of Font
252//---------------------------------------------------------------------------//
253
254impl Decodeable for Font {
255
256 fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
257 let signature_bytes = data.read_slice(4, false)?;
258 if signature_bytes.as_slice() != SIGNATURE {
259 return Err(RLibError::DecodingFontUnsupportedSignature(signature_bytes));
260 }
261
262 let mut font = Self::default();
263
264 // Get the properties of the font.
265 font.properties.first_prop = data.read_u16()?;
266 font.properties.second_prop = data.read_u16()?;
267 font.properties.line_height = data.read_u16()?;
268 font.properties.fourth_prop = data.read_u16()?;
269 font.properties.fifth_prop = data.read_u16()?;
270 font.properties.baseline = data.read_u16()?;
271 font.properties.layout_y_offset = data.read_u16()?;
272 font.properties.space_justify = data.read_u16()?;
273 font.properties.layout_x_offset = data.read_u16()?;
274 font.properties.h_size = data.read_u16()?;
275 font.properties.v_size = data.read_u16()?;
276
277 // These are used glyph count, and the size of the data section. Unused by the decoder.
278 let _glyph_count = data.read_u16()?;
279 let _glyph_data_size = data.read_u32()?;
280
281 // Get the glyphs/characters table. This is a list of u16 from 0 to u16 max value.
282 //
283 // 0xFFFF values are unused.
284 for index in 0..=u16::MAX {
285 let code = data.read_u16()?;
286 if code == 0xFFFF {
287 continue;
288 }
289
290 let mut glyph = Glyph::default();
291
292 glyph.code = code;
293 glyph.character = index;
294
295 font.glyphs.insert(index, glyph);
296 }
297
298 // Get the glyph dimensions data.
299 for index in 0..=u16::MAX {
300 if let Some(glyph) = font.glyphs_mut().get_mut(&index) {
301 glyph.alloc_height = data.read_i8()?;
302 glyph.alloc_width = data.read_u8()?;
303 glyph.width = data.read_u8()?;
304 glyph.height = data.read_u8()?;
305 }
306 }
307
308 // Get the glyph data offset for the next section. As they're consecutive and have a fixed size, we really don't use
309 // these offsets, but this code is left here for format documentation.
310 //
311 // This list only contains the glyphs that are used, because fuck consistency.
312 for _ in 0..font.glyphs().len() {
313 let _offset = data.read_u32()?;
314 }
315
316 for glyph in font.glyphs_mut().values_mut() {
317 let size = glyph.height as usize * glyph.width as usize;
318 if size != 0 {
319 glyph.data = data.read_slice(size, false)?;
320 }
321 }
322
323 // Get the glyph kerning info. This seems to be only from certain files onward, so a fail here has to be considered as
324 // not an error.
325 if let Ok(kerning_size) = data.read_u16() {
326 font.supports_kerning = true;
327
328 // Codes lower than the skip one do not have kerning data.
329 font.kerning_skip = data.read_u16()?;
330
331 for _ in 0..kerning_size {
332 let block = data.read_slice(kerning_size as usize, false)?;
333 font.kerning_blocks.push(block);
334 }
335 }
336
337 // If we are not in the last byte, it means we didn't parse the entire file, which means this file is corrupt.
338 check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
339
340 Ok(font)
341 }
342}
343
344impl Encodeable for Font {
345
346 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
347 buffer.write_all(SIGNATURE)?;
348
349 buffer.write_u16(*self.properties().first_prop())?;
350 buffer.write_u16(*self.properties().second_prop())?;
351 buffer.write_u16(*self.properties().line_height())?;
352 buffer.write_u16(*self.properties().fourth_prop())?;
353 buffer.write_u16(*self.properties().fifth_prop())?;
354 buffer.write_u16(*self.properties().baseline())?;
355 buffer.write_u16(*self.properties().layout_y_offset())?;
356 buffer.write_u16(*self.properties().space_justify())?;
357 buffer.write_u16(*self.properties().layout_x_offset())?;
358 buffer.write_u16(*self.properties().h_size())?;
359 buffer.write_u16(*self.properties().v_size())?;
360
361 buffer.write_u16(self.glyphs().len() as u16)?;
362
363 let mut glyphs = vec![];
364 let mut dimensions = vec![];
365 let mut offsets = vec![];
366 let mut data = vec![];
367
368 for index in 0..=u16::MAX {
369 match self.glyphs().get(&index) {
370 Some(glyph) => {
371 glyphs.write_u16(glyph.code)?;
372
373 dimensions.write_i8(glyph.alloc_height)?;
374 dimensions.write_u8(glyph.alloc_width)?;
375 dimensions.write_u8(glyph.width)?;
376 dimensions.write_u8(glyph.height)?;
377
378 if glyph.data().is_empty() &&
379 glyph.alloc_height == 0 &&
380 glyph.alloc_width == 0 &&
381 glyph.width == 0 &&
382 glyph.height == 0 {
383 offsets.write_u32(0)?;
384 } else {
385 offsets.write_u32(data.len() as u32)?;
386
387 data.write_all(&glyph.data)?;
388 }
389
390 },
391 None => {
392 glyphs.write_u16(0xFFFF)?;
393 },
394 }
395 }
396 buffer.write_u32(data.len() as u32)?;
397
398 buffer.write_all(&glyphs)?;
399 buffer.write_all(&dimensions)?;
400 buffer.write_all(&offsets)?;
401 buffer.write_all(&data)?;
402
403 if self.supports_kerning {
404 buffer.write_u16(self.kerning_blocks.len() as u16)?;
405 buffer.write_u16(self.kerning_skip)?;
406
407 for block in self.kerning_blocks() {
408 buffer.write_all(block)?;
409 }
410 }
411
412 Ok(())
413 }
414}