1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
use crate::TfntDocument;
use encoding_rs::WINDOWS_1251;
use fparkan_texm::{decode_mip_rgba8, RgbaImage};
/// The original bitmap and metrics for the native variable-width text path.
pub struct BitmapFont {
atlas: RgbaImage,
glyphs: Box<[Glyph]>,
glyph_height: usize,
line_height: usize,
spacing: usize,
}
#[derive(Clone, Copy, Default)]
struct Glyph {
left: usize,
top: usize,
source_width: usize,
source_height: usize,
width: usize,
}
impl BitmapFont {
/// Prepares source rectangles from the Tfnt UV pairs and common height.
pub fn prepare(font: &TfntDocument) -> Result<Self, String> {
let atlas = decode_mip_rgba8(&font.texm, 0).map_err(|error| error.to_string())?;
let glyph_height = usize::try_from(font.header.vertical_extent)
.ok()
.filter(|&height| height < atlas.height as usize)
.ok_or("invalid Tfnt height")?
+ 1;
let spacing = usize::try_from(font.header.character_spacing)
.ok()
.filter(|&spacing| spacing < atlas.width as usize)
.ok_or("invalid Tfnt spacing")?;
let v_span = f32::from_bits(font.header.word_0c_bits);
// Several HUD widgets keep multiple prepared fonts on the window thread.
let mut glyphs = vec![Glyph::default(); font.glyphs.len()].into_boxed_slice();
for (glyph, record) in glyphs.iter_mut().zip(&font.glyphs) {
let top_v = f32::from_bits(record.word2);
let left = texel(f32::from_bits(record.word0), atlas.width)?;
let right = texel(f32::from_bits(record.word1), atlas.width)?;
let top = texel(top_v, atlas.height)?;
let bottom = texel(top_v + v_span, atlas.height)?;
let width = usize::try_from(record.advance)
.ok()
.filter(|&advance| advance < atlas.width as usize)
.ok_or("invalid Tfnt glyph advance")?
+ 1;
*glyph = Glyph {
left,
top,
source_width: right.checked_sub(left).ok_or("reversed Tfnt U interval")?,
source_height: bottom.checked_sub(top).ok_or("reversed Tfnt V interval")?,
width,
};
}
Ok(Self {
atlas,
glyphs,
glyph_height,
line_height: glyph_height + 1,
spacing,
})
}
/// Draw a CP1251 caption using the atlas, preserving explicit line breaks.
/// Returns the occupied height and a fixed-size RGBA image.
pub fn caption(&self, text: &str, width: u16, height: u16) -> Result<(u32, Vec<u8>), String> {
const PADDING: usize = 12;
let (width, height) = (usize::from(width), usize::from(height));
if width <= 2 * PADDING || height < 2 * PADDING + self.glyph_height {
return Err("caption image is too small".into());
}
let (bytes, _, unmappable) = WINDOWS_1251.encode(text);
if unmappable {
return Err("mission caption contains characters outside CP1251".into());
}
let limit = width - PADDING;
let bottom = height - PADDING;
let bytes_len = width
.checked_mul(height)
.and_then(|area| area.checked_mul(4))
.filter(|&len| len <= isize::MAX as usize)
.ok_or("caption image is too large")?;
let mut pixels = vec![0; bytes_len];
for pixel in pixels.chunks_exact_mut(4) {
pixel[3] = 192;
}
let mut y = PADDING;
let mut occupied = PADDING + self.glyph_height;
'paragraphs: for paragraph in bytes.split(|&byte| byte == b'\n') {
let mut x = PADDING;
for word in paragraph
.split(u8::is_ascii_whitespace)
.filter(|word| !word.is_empty())
{
let advance = word.iter().map(|&byte| self.advance(byte)).sum::<usize>();
if x != PADDING {
if x + self.advance(b' ') + advance > limit {
x = PADDING;
y += self.line_height;
} else {
x += self.advance(b' ');
}
}
for &byte in word {
let glyph = self.glyphs[usize::from(byte)];
if x + glyph.width > limit && x != PADDING {
x = PADDING;
y += self.line_height;
}
if y + self.glyph_height > bottom {
break 'paragraphs;
}
self.draw_glyph(glyph, &mut pixels, width, [x, y], limit - x);
x = (x + self.advance(byte)).min(limit);
occupied = y + self.glyph_height;
}
}
y += self.line_height;
}
Ok(((occupied + PADDING) as u32, pixels))
}
/// Renders a single line centered in a transparent RGBA image.
pub fn centered_line(&self, text: &str, width: u16, height: u16) -> Result<RgbaImage, String> {
let (bytes, _, unmappable) = WINDOWS_1251.encode(text);
if unmappable {
return Err("game text contains characters outside CP1251".into());
}
self.centered_line_bytes(&bytes, width, height)
}
/// Text extent in native atlas pixels, including character spacing.
pub fn line_metrics(&self, text: &str) -> Result<[u16; 2], String> {
let (bytes, _, unmappable) = WINDOWS_1251.encode(text);
if unmappable {
return Err("game text contains characters outside CP1251".into());
}
self.line_metrics_bytes(&bytes)
}
/// Measures an original CP1251 string in atlas pixels.
pub fn line_metrics_bytes(&self, bytes: &[u8]) -> Result<[u16; 2], String> {
let width = bytes.iter().map(|&byte| self.advance(byte)).sum::<usize>();
let width = u16::try_from(width).map_err(|_| "game text is too wide")?;
let height = u16::try_from(self.glyph_height).map_err(|_| "game font is too tall")?;
Ok([width, height])
}
/// Wraps pager tokens by their atlas advances. A newline starts a row
/// when it opens a token, while spaces inside a row retain their width.
pub fn wrap_pager_lines(&self, mut text: &str, max_width: u16) -> Result<Vec<String>, String> {
let mut lines = Vec::new();
let mut line = String::new();
let mut width = 0;
while !text.is_empty() {
if let Some(after) = text.strip_prefix('\n') {
lines.push(std::mem::take(&mut line));
text = after;
width = 0;
continue;
}
let is_space = text.starts_with(' ');
let end = if is_space {
text.len() - text.trim_start_matches(' ').len()
} else {
text.find(' ').unwrap_or(text.len())
};
let token = &text[..end];
text = &text[end..];
let advance = usize::from(self.line_metrics(token)?[0]);
if !line.is_empty() && width + advance > usize::from(max_width) {
lines.push(std::mem::take(&mut line));
width = 0;
}
if !is_space || !line.is_empty() {
line.push_str(token);
width += advance;
}
}
if !line.is_empty() {
lines.push(line);
}
Ok(lines)
}
/// Composes a single line from a game resource's original CP1251 bytes.
pub fn centered_line_bytes(
&self,
bytes: &[u8],
width: u16,
height: u16,
) -> Result<RgbaImage, String> {
let (width, height) = (usize::from(width), usize::from(height));
if height < self.glyph_height || width == 0 {
return Err("game text rectangle is too small".into());
}
let len = width
.checked_mul(height)
.and_then(|area| area.checked_mul(4))
.filter(|&len| len <= isize::MAX as usize)
.ok_or("game text rectangle is too large")?;
let mut pixels = vec![0; len];
let advance = bytes.iter().map(|&byte| self.advance(byte)).sum::<usize>();
let mut x = width.saturating_sub(advance) / 2;
let y = (height - self.glyph_height) / 2;
for &byte in bytes.iter() {
self.draw_glyph(
self.glyphs[usize::from(byte)],
&mut pixels,
width,
[x, y],
width - x,
);
x = (x + self.advance(byte)).min(width);
}
Ok(RgbaImage {
width: width as u32,
height: height as u32,
rgba8: pixels,
})
}
fn advance(&self, byte: u8) -> usize {
self.glyphs[usize::from(byte)].width - 1 + self.spacing
}
fn draw_glyph(
&self,
glyph: Glyph,
pixels: &mut [u8],
stride: usize,
[x, y]: [usize; 2],
available: usize,
) {
if glyph.source_width == 0 || glyph.source_height == 0 {
return;
}
let atlas_width = self.atlas.width as usize;
for row in 0..self.glyph_height {
let source_y = glyph.top + row * glyph.source_height / self.glyph_height;
for col in 0..glyph.width.min(available) {
let source_x = glyph.left + col * glyph.source_width / glyph.width;
let source = (source_y * atlas_width + source_x) * 4;
let dest = ((y + row) * stride + x + col) * 4;
let rgb = &self.atlas.rgba8[source..source + 3];
for (output, &component) in pixels[dest..dest + 3].iter_mut().zip(rgb) {
*output = (*output).max(component);
}
pixels[dest + 3] = pixels[dest + 3].max(*rgb.iter().max().unwrap());
}
}
}
}
fn texel(coordinate: f32, extent: u32) -> Result<usize, String> {
if !(0.0..=1.0).contains(&coordinate) {
return Err("Tfnt coordinate is outside the texture atlas".into());
}
Ok((coordinate * extent as f32).round() as usize)
}
|