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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
|
//! The mission terminal's text pages and original atlas controls.
use crate::{
game_font::{load_game_font, BitmapFont},
help_resources::{HelpBinding, HelpResources, MissionTip},
mission_pager::{copy_sprite, scale, UiFrame},
ui_sprite::load_ui_sprites,
RgbaImage,
};
use encoding_rs::WINDOWS_1251;
use fparkan_vfs::Vfs;
use std::time::{Duration, Instant};
/// Drawable extent used to compose the original font profile.
pub const EXTENT: [u32; 2] = [800, 600];
const PAGE: [u32; 4] = [15, 35, 637, 430];
const TAB_X: [u32; 3] = [2, 199, 396];
const KEY_COLUMN: u32 = PAGE[0] + 250;
const CLOSE: [u32; 4] = [593, 2, 640, 23];
const SCROLL: [[u32; 4]; 2] = [[526, 458, 576, 477], [576, 458, 626, 477]];
const HOVER_STEP_MS: u64 = 251;
const SCROLL_STEP: Duration = Duration::from_millis(51);
const WHITE: [u8; 3] = [255; 3];
const GREEN: [u8; 3] = [0, 255, 0];
const PALE_GREEN: [u8; 3] = [100, 255, 100];
const YELLOW: [u8; 3] = [255, 255, 0];
/// A hit in the native 640×480 coordinate space.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HelpAction {
/// Selects the specified native tab.
Tab(usize),
/// Scrolls a number of lines.
Scroll(i32),
/// Closes the terminal.
Close,
}
/// Strings read from the game's localized table.
pub struct HelpLabels {
/// Mission, controls and journal tab captions.
pub tabs: [String; 3],
/// Headings of the four control tables.
pub controls: [String; 4],
/// Heading of the commonly used commands.
pub common_keys: String,
/// Localized sentence with the game-menu key placeholder.
pub game_menu_hint: String,
/// Journal text before any messages are received.
pub empty_journal: String,
/// Localized format for a journal sequence number.
pub message_number: String,
}
/// Original UI page data, independent of the window and GPU backend.
pub struct HelpScreen {
font: BitmapFont,
frame: UiFrame,
tab_body: RgbaImage,
emitter: [RgbaImage; 2],
close: [RgbaImage; 2],
scroll_button: [RgbaImage; 3],
icons: [RgbaImage; 3],
labels: HelpLabels,
pages: [Vec<Row>; 3],
tab_index: usize,
scroll: [usize; 3],
message_count: usize,
pointer: HelpPointer,
}
struct HelpPointer {
hover: Option<HelpAction>,
blink_start: Instant,
bright: bool,
blink_at: Option<Instant>,
scroll_at: Option<Instant>,
}
#[derive(Default)]
struct Row {
spans: Vec<(Vec<u8>, [u8; 3])>,
key: Option<Vec<u8>>,
width: u32,
advance: u32,
}
impl HelpScreen {
/// Prepares original mission and keyboard help pages and their shared frame.
pub fn load(vfs: &dyn Vfs, mission: &str, labels: HelpLabels) -> Result<Self, String> {
let data = HelpResources::load(vfs, mission, false)?;
let [tab_body, ray_normal, ray_pressed, close_normal, close_pressed, off, normal, pressed] =
load_ui_sprites(
vfs,
"ui/compaund.cfg",
[
"ccres_body_text",
"ccres_ray_emitter_normal",
"ccres_ray_emitter_pressed",
"ccres_exit_button_normal",
"ccres_exit_button_pressed",
"ccres_long_button_off",
"ccres_long_button_normal",
"ccres_long_button_pressed",
],
)?;
let mut screen = Self {
font: load_game_font(vfs)?,
frame: UiFrame::load(vfs)?,
tab_body,
emitter: [ray_normal, ray_pressed],
close: [close_normal, close_pressed],
scroll_button: [off, normal, pressed],
icons: load_ui_sprites(
vfs,
"ui/hq.cfg",
["exit_icon", "scroll_down_icon", "scroll_up_icon"],
)?,
labels,
pages: Default::default(),
tab_index: 0,
scroll: [0; 3],
message_count: 0,
pointer: HelpPointer {
hover: None,
blink_start: Instant::now(),
bright: false,
blink_at: None,
scroll_at: None,
},
};
screen.pages = [
screen.mission_rows(data.mission)?,
screen.control_rows(data.controls)?,
vec![
screen.row(150)?,
screen.text_row(&screen.labels.empty_journal, YELLOW)?,
],
];
Ok(screen)
}
/// Adds the complete body to the journal before the pager shortens it.
pub fn post(&mut self, sender: &str, body: &str) -> Result<(), String> {
let count = self.message_count + 1;
let header = self.labels.message_number.replace("%d", &count.to_string());
let mut rows = Vec::new();
if self.message_count == 0 {
rows.push(self.row(150)?);
}
rows.push(self.text_row(&format!("{header} {sender}"), YELLOW)?);
rows.extend(
self.font
.wrap_pager_lines(body, self.wrap_width() as u16)?
.iter()
.map(|line| self.text_row(line, WHITE))
.collect::<Result<Vec<_>, _>>()?,
);
rows.push(self.row(150)?);
let journal = &mut self.pages[2];
if self.message_count == 0 {
journal.clear();
}
journal.extend(rows);
self.message_count = count;
Ok(())
}
/// Changes the selected tab or scroll position and reports a redraw.
pub fn navigate(&mut self, action: HelpAction) -> bool {
match action {
HelpAction::Tab(index) if index < self.pages.len() => {
let changed = self.tab_index != index;
self.tab_index = index;
changed
}
HelpAction::Scroll(lines) => {
let before = self.scroll[self.tab_index];
let position = before.saturating_add_signed(lines as isize);
self.scroll[self.tab_index] = position.min(self.last_scroll());
before != self.scroll[self.tab_index]
}
_ => false,
}
}
/// Advances or reverses the tab order with wraparound.
pub fn cycle(&mut self, reverse: bool) -> bool {
let offset = if reverse { self.pages.len() - 1 } else { 1 };
self.navigate(HelpAction::Tab(
(self.tab_index + offset) % self.pages.len(),
))
}
/// Looks up a tab or terminal control from a normalized 640×480 point.
pub fn hit_test([x, y]: [f32; 2]) -> Option<HelpAction> {
let hit =
|[l, t, r, b]: [u32; 4]| x >= l as f32 && x < r as f32 && y >= t as f32 && y < b as f32;
for (index, l) in TAB_X.into_iter().enumerate() {
if hit([l, 2, l + 184, 23]) {
return Some(HelpAction::Tab(index));
}
}
if hit(CLOSE) {
return Some(HelpAction::Close);
}
SCROLL
.into_iter()
.position(hit)
.map(|index| HelpAction::Scroll(if index == 0 { 1 } else { -1 }))
}
/// Changes the hovered control and releases scrolling when leaving the arrows.
pub fn point(&mut self, position: [f32; 2]) -> bool {
let hover = Self::hit_test(position);
if self.pointer.hover == hover {
return false;
}
self.pointer.hover = hover;
if !matches!(hover, Some(HelpAction::Scroll(_))) {
self.pointer.scroll_at = None;
}
true
}
/// Selects a tab or latches the hovered scroll arrow for the next update.
pub fn press_pointer(&mut self, now: Instant) -> Option<HelpAction> {
let action = self.pointer.hover?;
if matches!(action, HelpAction::Scroll(_)) {
self.pointer.scroll_at = Some(now);
None
} else {
Some(action)
}
}
/// Releases a held arrow and reports whether its appearance might change.
pub fn release_pointer(&mut self) -> bool {
self.pointer.scroll_at.take().is_some()
}
/// Updates the hovered control using real time while mission time is paused.
pub fn update_pointer(&mut self, now: Instant) -> bool {
let elapsed = now.duration_since(self.pointer.blink_start).as_millis();
let step = u128::from(HOVER_STEP_MS);
let bright = elapsed / step % 2 != 0;
let mut redraw = self.pointer.bright != bright
&& self.pointer.scroll_at.is_none()
&& self.next_pointer_update().is_some();
self.pointer.bright = bright;
self.pointer.blink_at =
Some(now + Duration::from_millis(HOVER_STEP_MS - (elapsed % step) as u64));
if self.pointer.scroll_at.is_some_and(|at| now >= at) {
if let Some(action @ HelpAction::Scroll(_)) = self.pointer.hover {
redraw |= self.navigate(action);
}
self.pointer.scroll_at = Some(now + SCROLL_STEP);
}
redraw
}
/// Next visible pointer update. Idle help pages need no timer.
pub fn next_pointer_update(&self) -> Option<Instant> {
match self.pointer.hover? {
HelpAction::Tab(index) if index == self.tab_index => None,
HelpAction::Scroll(lines) if !self.scroll_enabled(lines) => None,
_ => self.pointer.scroll_at.or(self.pointer.blink_at),
}
}
/// Paints the selected page from the original UI parts and game font.
pub fn paint(&self) -> Result<RgbaImage, String> {
let [width, height] = EXTENT;
let mut image = RgbaImage {
width,
height,
rgba8: vec![0; (width * height * 4) as usize],
};
for pixel in image.rgba8.chunks_exact_mut(4) {
pixel[3] = 255;
}
self.frame
.paint(&mut image, [2, 24, 637, 454], [0, 64, 0, 255]);
for (index, left) in TAB_X.into_iter().enumerate() {
let hovered = self.pointer.hover == Some(HelpAction::Tab(index));
let lit = index == self.tab_index || (hovered && self.pointer.bright);
let tint = match (lit, hovered) {
(true, _) => WHITE,
(false, true) => PALE_GREEN,
_ => GREEN,
};
let emitter = &self.emitter[usize::from(lit)];
sprite(&mut image, emitter, [left, 2, left + 10, 21], WHITE);
sprite(
&mut image,
&self.tab_body,
[left + 10, 2, left + 189, 21],
WHITE,
);
copy_sprite(
&mut image,
emitter,
[left + 183, 2, left + 194, 21].map(scale),
[true, false],
WHITE,
);
let text = encode(&self.labels.tabs[index])?;
let width = u32::from(self.font.line_metrics_bytes(&text)?[0]);
let center = scale(left + 100);
self.text(
&mut image,
&text,
[center.saturating_sub(width / 2), scale(6)],
tint,
)?;
}
let close_lit = self.pointer.hover == Some(HelpAction::Close) && self.pointer.bright;
sprite(
&mut image,
&self.emitter[usize::from(close_lit)],
[593, 2, 603, 21],
WHITE,
);
sprite(
&mut image,
&self.close[usize::from(close_lit)],
[603, 2, 638, 21],
WHITE,
);
sprite(
&mut image,
&self.icons[0],
[618, 5, 631, 18],
[if close_lit { 255 } else { 240 }; 3],
);
let start = self.scroll[self.tab_index];
for (index, bounds) in SCROLL.into_iter().enumerate() {
let [l, t, _, _] = bounds;
let lines = if index == 0 { 1 } else { -1 };
let state = self.scroll_state(lines);
sprite(&mut image, &self.scroll_button[state], bounds, WHITE);
sprite(
&mut image,
&self.icons[index + 1],
[l + 10, t + 2, l + 40, t + 17],
[[128; 3], [240; 3], WHITE][state],
);
}
let mut y = PAGE[1];
let height = self.font.line_metrics("")?[1] - 1;
for row in &self.pages[self.tab_index][start..] {
if y >= PAGE[3] {
break;
}
let text_y = if row.key.is_some() {
scale(y + logical_height(u32::from(height) + 1))
} else {
scale(y)
};
let mut x = scale(PAGE[0]);
for (bytes, color) in &row.spans {
self.text(&mut image, bytes, [x, text_y], *color)?;
x += u32::from(self.font.line_metrics_bytes(bytes)?[0]);
}
if let Some(key) = &row.key {
self.text(&mut image, key, [scale(KEY_COLUMN), text_y], WHITE)?;
}
y += row.advance;
}
Ok(image)
}
fn scroll_enabled(&self, lines: i32) -> bool {
let start = self.scroll[self.tab_index];
if lines > 0 {
start < self.last_scroll()
} else {
start > 0
}
}
fn scroll_state(&self, lines: i32) -> usize {
if !self.scroll_enabled(lines) {
return 0;
}
let pressed = self.pointer.hover == Some(HelpAction::Scroll(lines))
&& (self.pointer.bright || self.pointer.scroll_at.is_some());
1 + usize::from(pressed)
}
fn last_scroll(&self) -> usize {
let rows = &self.pages[self.tab_index];
let visible = PAGE[3] - PAGE[1];
let mut height = 0;
let count = rows
.iter()
.rev()
.take_while(|row| {
height += row.advance;
height <= visible
})
.count();
rows.len().saturating_sub(count.max(1))
}
fn mission_rows(&self, tips: Option<Vec<MissionTip>>) -> Result<Vec<Row>, String> {
let Some(tips) = tips else {
return Ok(vec![
self.row(100)?,
self.text_row("No mission tips", YELLOW)?,
self.row(100)?,
]);
};
let mut rows = Vec::new();
let mut color = WHITE;
let mut spacing = 100;
let mut row = self.row(spacing)?;
for token in tips {
match token {
MissionTip::Break => rows.push(std::mem::replace(&mut row, self.row(spacing)?)),
MissionTip::Color(value) => color = value,
MissionTip::EndColor => color = WHITE,
MissionTip::Interleave(value) => {
spacing = value;
row.advance = self.row(spacing)?.advance;
}
MissionTip::Text(bytes) => {
for word in bytes
.split(u8::is_ascii_whitespace)
.filter(|word| !word.is_empty())
{
let word_width = u32::from(self.font.line_metrics_bytes(word)?[0]);
let space = u32::from(self.font.line_metrics_bytes(b" ")?[0]);
if row.width + space + word_width > self.wrap_width() && row.width != 0 {
rows.push(std::mem::replace(&mut row, self.row(spacing)?));
}
if row.width != 0 {
row.spans.push((vec![b' '], color));
row.width += space;
}
row.spans.push((word.to_vec(), color));
row.width += word_width;
}
}
}
}
if !row.spans.is_empty() {
rows.push(row);
}
Ok(rows)
}
fn control_rows(&self, groups: [Vec<HelpBinding>; 4]) -> Result<Vec<Row>, String> {
let short_step = self.row(100)?.advance;
let append_gap = |rows: &mut Vec<Row>, count| {
rows.extend((0..count).map(|_| Row {
advance: short_step,
..Row::default()
}));
};
let mut heading = self.text_row(&self.labels.common_keys, YELLOW)?;
heading.advance = short_step;
let mut rows = vec![heading];
append_gap(&mut rows, 1);
let mut menu_key = &[][..];
for command in ["CMD_HELP", "CMD_GAME_MENU", "CMD_JAMES_MISSION_OBJ"] {
let entry = groups[3]
.iter()
.find(|entry| entry.command == command)
.ok_or_else(|| format!("missing common help binding {command}"))?;
rows.push(self.control_row(entry)?);
if command == "CMD_GAME_MENU" {
menu_key = &entry.keys[1];
}
}
let (key, _, _) = WINDOWS_1251.decode(menu_key);
append_gap(&mut rows, 3);
let mut hint = self.text_row(&self.labels.game_menu_hint.replace("%s", &key), [230; 3])?;
hint.advance = short_step;
rows.push(hint);
append_gap(&mut rows, 4);
for (group, title) in groups.iter().zip(&self.labels.controls) {
let mut heading = self.text_row(title, YELLOW)?;
heading.advance = short_step;
rows.push(heading);
append_gap(&mut rows, 1);
for entry in group {
rows.push(self.control_row(entry)?);
}
append_gap(&mut rows, 4);
}
Ok(rows)
}
fn control_row(&self, entry: &HelpBinding) -> Result<Row, String> {
let mut row = self.row(150)?;
row.spans.push((entry.description.clone(), WHITE));
row.key = Some(entry.keys[1].clone());
Ok(row)
}
fn wrap_width(&self) -> u32 {
((PAGE[2] - PAGE[0]) as f32 * 1.25 * 0.98).round_ties_even() as u32
}
fn row(&self, spacing: u16) -> Result<Row, String> {
let [_, height] = self.font.line_metrics("")?;
Ok(Row {
advance: row_advance(height - 1, spacing),
..Row::default()
})
}
fn text_row(&self, text: &str, color: [u8; 3]) -> Result<Row, String> {
let mut row = self.row(150)?;
row.spans.push((encode(text)?, color));
Ok(row)
}
fn text(
&self,
image: &mut RgbaImage,
text: &[u8],
[x, y]: [u32; 2],
color: [u8; 3],
) -> Result<(), String> {
let [w, h] = self.font.line_metrics_bytes(text)?;
if w > 0 {
let raster = self.font.centered_line_bytes(text, w, h)?;
copy_sprite(
image,
&raster,
[x, y, x + raster.width, y + raster.height],
[false; 2],
color,
);
}
Ok(())
}
}
fn logical_height(pixels: u32) -> u32 {
(f64::from(pixels) / 1.25).round_ties_even() as u32
}
fn row_advance(font_height: u16, spacing: u16) -> u32 {
logical_height(u32::from(font_height) * u32::from(spacing) / 100).max(1)
}
fn sprite(image: &mut RgbaImage, source: &RgbaImage, rect: [u32; 4], color: [u8; 3]) {
copy_sprite(image, source, rect.map(scale), [false; 2], color);
}
fn encode(text: &str) -> Result<Vec<u8>, String> {
let (bytes, _, unmappable) = WINDOWS_1251.encode(text);
if unmappable {
return Err("help text contains characters outside CP1251".into());
}
Ok(bytes.into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn f1_controls_use_native_columns_and_line_steps() {
assert_eq!([PAGE[0], KEY_COLUMN], [15, 265]);
assert_eq!(logical_height(9 + 1), 8);
assert_eq!(row_advance(9, 150), 10);
}
#[test]
fn help_hit_targets_select_native_tabs_and_scroll_directions() {
assert_eq!(
HelpScreen::hit_test([410.0, 10.0]),
Some(HelpAction::Tab(2))
);
assert_eq!(HelpScreen::hit_test([620.0, 10.0]), Some(HelpAction::Close));
assert_eq!(
HelpScreen::hit_test([540.0, 469.0]),
Some(HelpAction::Scroll(1))
);
assert_eq!(
HelpScreen::hit_test([620.0, 469.0]),
Some(HelpAction::Scroll(-1))
);
assert_eq!(HelpScreen::hit_test([300.0, 400.0]), None);
}
#[test]
#[ignore = "requires licensed corpus"]
fn help_pointer_keeps_the_blink_phase_and_repeats_a_held_arrow() {
let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
let mut help = HelpScreen::load(
&fparkan_vfs::DirectoryVfs::new(root),
"MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma",
HelpLabels {
tabs: Default::default(),
controls: Default::default(),
common_keys: String::new(),
game_menu_hint: String::new(),
empty_journal: String::new(),
message_number: String::new(),
},
)
.unwrap();
let start = help.pointer.blink_start;
let at = |ms| start + Duration::from_millis(ms);
assert!(help.navigate(HelpAction::Tab(1)));
assert_eq!([help.scroll_state(1), help.scroll_state(-1)], [1, 0]);
assert!(help.point([60.0, 10.0]));
assert!(!help.update_pointer(at(250)));
assert!(help.update_pointer(at(251)));
assert!(help.pointer.bright);
assert!(help.point([620.0, 10.0]));
assert!(help.pointer.bright);
assert!(help.point([540.0, 469.0]));
help.update_pointer(at(502));
assert_eq!(help.scroll_state(1), 1);
assert_eq!(help.press_pointer(at(502)), None);
assert_eq!(help.scroll_state(1), 2);
assert!(help.update_pointer(at(502)));
assert_eq!(help.scroll[1], 1);
assert!(!help.update_pointer(at(552)));
assert!(help.update_pointer(at(553)));
assert_eq!(help.scroll[1], 2);
assert!(help.point([300.0, 400.0]));
assert_eq!(help.next_pointer_update(), None);
assert!(!help.update_pointer(at(604)));
assert_eq!(help.scroll[1], 2);
}
}
|