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
264
|
//! Resources used by the satellite map overlay.
use crate::{
mission_pager::{scale, UiFrame},
ui_configuration::{field, number, object, read},
};
use fparkan_nres::{decode, EntryId, ReadProfile};
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_resource::{resource_name, CachedResourceRepository, ResourceRepository};
use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage};
use fparkan_vfs::Vfs;
use std::sync::Arc;
/// Framed map bounds in the original 640×480 coordinates (iron3d+0x733e0).
pub const MAP_RECT: [u32; 4] = [374, 0, 640, 266];
/// Inset between the frame and the mission image (iron3d+0x74cf0).
pub const MAP_INSET: u32 = 5;
/// Initial satellite background opacity in the GOG HUD.
pub const MAP_INITIAL_ALPHA: u8 = 128;
/// Steps the background opacity as in iron3d+0x749a0 and +0x74a00.
pub fn step_map_alpha(alpha: u8, increase: bool) -> u8 {
let step = if increase { 12 } else { -12 };
(i16::from(alpha) + step).clamp(30, 255) as u8
}
fn displayed_map_alpha(alpha: u8) -> u16 {
(u16::from(alpha) * 100 / 255 / 5 * 5).max(10)
}
const ALPHA_LABELS: usize = 19;
const FONT_EXTENTS: [[u32; 2]; 3] = [[640, 480], [800, 600], [1024, 768]];
/// Precomposed percent strings from the original GAME_FONT profiles.
pub struct MapOpacityLabels {
pub atlas_size: [u32; 2],
frames: [[[u32; 3]; ALPHA_LABELS]; FONT_EXTENTS.len()],
}
impl MapOpacityLabels {
pub fn load(vfs: &dyn Vfs) -> Result<(Self, RgbaImage), String> {
let mut labels = Vec::new();
let mut frames = [[[0; 3]; ALPHA_LABELS]; FONT_EXTENTS.len()];
let (mut width, mut height) = (0, 0);
for (profile, (extent, frames)) in FONT_EXTENTS.into_iter().zip(&mut frames).enumerate() {
let [font] =
crate::game_font::load_profile(vfs, (profile + 1) as u8, extent, &["GAME_FONT"])?;
for (index, frame) in frames.iter_mut().enumerate() {
let text = format!("{}%", 10 + index * 5);
let [w, h] = font.line_metrics(&text)?;
let label = font.centered_line(&text, w, h)?;
*frame = [height, label.width, label.height];
width = width.max(label.width);
// A transparent row keeps linear sampling away from the next label.
height += label.height + 1;
labels.push(label);
}
}
let mut rgba8 = vec![0; (width * height * 4) as usize];
for ([top, w, _], label) in frames.iter().flatten().copied().zip(labels) {
let rows = rgba8.chunks_exact_mut((width * 4) as usize);
for (dest, source) in rows
.skip(top as usize)
.zip(label.rgba8.chunks_exact((w * 4) as usize))
{
dest[..source.len()].copy_from_slice(source);
}
}
Ok((
Self {
atlas_size: [width, height],
frames,
},
RgbaImage {
width,
height,
rgba8,
},
))
}
/// Returns the atlas row and unscaled glyph extent for the active resolution.
pub fn frame(&self, extent: [u32; 2], alpha: u8) -> [u32; 3] {
let profile = FONT_EXTENTS
.iter()
.rposition(|&[width, height]| extent[0] >= width && extent[1] >= height)
.unwrap_or(0);
let index = usize::from((displayed_map_alpha(alpha) - 10) / 5);
self.frames[profile][index]
}
}
/// The mission map, compass and contact atlas from the installed game.
pub struct SatelliteMapAssets {
pub frame: RgbaImage,
pub background: RgbaImage,
pub compass: RgbaImage,
pub icons: RgbaImage,
}
/// Resolves `minimap` through the mission CFG and the compass through the game UI CFG.
pub fn load_satellite_map(
vfs: Arc<dyn Vfs>,
mission: &str,
) -> Result<Option<SatelliteMapAssets>, String> {
let cfg = mission.rsplit_once('/').map_or_else(
|| "mission.cfg".to_owned(),
|(dir, _)| format!("{dir}/mission.cfg"),
);
let bytes = read(vfs.as_ref(), &cfg)?;
let cfg = String::from_utf8_lossy(&bytes);
let Some(minimap) = object(&cfg, "minimap") else {
return Ok(None);
};
let archive = normalize_relative(
field(&minimap, "LIBRARY")?.as_bytes(),
PathPolicy::StrictLegacy,
)
.map_err(|error| error.to_string())?;
let repo = CachedResourceRepository::new(vfs.clone());
let archive_id = repo
.open_archive(&archive)
.map_err(|error| error.to_string())?;
let file = field(&minimap, "MINIMAP")?;
let entry = repo
.find(archive_id, &resource_name(file))
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("missing mission map {file} in {}", archive.as_str()))?;
let payload = repo.read(entry).map_err(|error| error.to_string())?;
let background = texture(payload.as_slice())?;
let hq = read(vfs.as_ref(), "ui/hq.cfg")?;
let hq = String::from_utf8_lossy(&hq);
let icon = object(&hq, "map_compass_icon").ok_or("missing map_compass_icon in ui/hq.cfg")?;
let game = read(vfs.as_ref(), "ui/game_resources.cfg")?;
let game = String::from_utf8_lossy(&game);
let textures = object(&game, "textures").ok_or("missing textures in ui/game_resources.cfg")?;
let atlas = field(&textures, "LIBRARY")?;
let page = field(&icon, "TEXTURE")?.to_ascii_uppercase();
let pages = decode(read(vfs.as_ref(), atlas)?, ReadProfile::Strict)
.map_err(|error| error.to_string())?;
let page = pages
.payload(EntryId(number(&textures, &page)?))
.map_err(|error| error.to_string())?;
let compass = crop(
&texture(page)?,
[number(&icon, "OFFSET_X")?, number(&icon, "OFFSET_Y")?],
[number(&icon, "WIDTH")?, number(&icon, "HEIGHT")?],
)?;
let icon_page = pages
.payload(EntryId(number(&textures, "ICONS")?))
.map_err(|error| error.to_string())?;
let icons = texture(icon_page)?;
if icons.width != 256 || icons.height != 256 {
return Err("unexpected satellite icon atlas dimensions".into());
}
let [left, top, right, bottom] = MAP_RECT;
let bounds = [0, 0, right - left, bottom - top];
let [_, _, width, height] = bounds.map(scale);
let mut frame = RgbaImage {
width,
height,
rgba8: vec![0; (width * height * 4) as usize],
};
UiFrame::load(vfs.as_ref())?.paint(&mut frame, bounds, [0; 4]);
Ok(Some(SatelliteMapAssets {
frame,
background,
compass,
icons,
}))
}
fn texture(bytes: &[u8]) -> Result<RgbaImage, String> {
let document = decode_texm(Arc::from(bytes)).map_err(|error| error.to_string())?;
decode_mip_rgba8(&document, 0).map_err(|error| error.to_string())
}
#[cfg(test)]
mod opacity_tests {
use super::*;
#[test]
fn satellite_opacity_uses_native_steps_and_rounded_label() {
assert_eq!(step_map_alpha(MAP_INITIAL_ALPHA, true), 140);
assert_eq!(step_map_alpha(MAP_INITIAL_ALPHA, false), 116);
assert_eq!(step_map_alpha(30, false), 30);
assert_eq!(step_map_alpha(32, false), 30);
assert_eq!(step_map_alpha(248, true), 255);
assert_eq!(step_map_alpha(255, true), 255);
assert_eq!(
[30, 116, 128, 140, 255].map(displayed_map_alpha),
[10, 45, 50, 50, 100]
);
}
}
fn crop(
image: &RgbaImage,
[x, y]: [u32; 2],
[width, height]: [u32; 2],
) -> Result<RgbaImage, String> {
let right = x
.checked_add(width)
.filter(|&right| right <= image.width && width != 0);
let bottom = y
.checked_add(height)
.filter(|&bottom| bottom <= image.height && height != 0);
let (Some(right), Some(bottom)) = (right, bottom) else {
return Err("map compass rectangle is outside the texture atlas".into());
};
let stride = image.width as usize * 4;
let mut rgba8 = Vec::new();
for row in y as usize..bottom as usize {
rgba8.extend_from_slice(
&image.rgba8[row * stride + x as usize * 4..row * stride + right as usize * 4],
);
}
Ok(RgbaImage {
width,
height,
rgba8,
})
}
#[cfg(test)]
mod tests {
use super::load_satellite_map;
use fparkan_vfs::DirectoryVfs;
use std::sync::Arc;
#[test]
#[ignore = "requires licensed corpus"]
fn loads_distinct_mission_textures_and_the_shared_compass() {
let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
let vfs = Arc::new(DirectoryVfs::new(root));
let load = |mission| {
load_satellite_map(vfs.clone(), &format!("MISSIONS/{mission}/data.tma"))
.unwrap()
.expect("authored map")
};
let range = load("CAMPAIGN/CAMPAIGN.00/Mission.01");
let fortresses = load("Single.01");
assert_eq!(
[range.background.width, range.background.height],
[256, 256]
);
assert_eq!([range.compass.width, range.compass.height], [21, 42]);
assert_eq!([range.frame.width, range.frame.height], [332, 332]);
assert_eq!(range.frame, fortresses.frame);
assert!(range.frame.rgba8[..332 * 4]
.chunks_exact(4)
.any(|pixel| pixel[3] != 0));
assert_eq!(range.frame.rgba8[(166 * 332 + 166) * 4 + 3], 0);
assert_ne!(range.background.rgba8, fortresses.background.rgba8);
assert_eq!(range.compass, fortresses.compass);
assert!(range
.compass
.rgba8
.chunks_exact(4)
.any(|pixel| pixel[3] != 0));
}
}
|