//! 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; 3], tab_index: usize, scroll: [usize; 3], message_count: usize, pointer: HelpPointer, } struct HelpPointer { hover: Option, blink_start: Instant, bright: bool, blink_at: Option, scroll_at: Option, } #[derive(Default)] struct Row { spans: Vec<(Vec, [u8; 3])>, key: Option>, 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 { 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::, _>>()?, ); 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 { 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 { 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 { 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 { 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>) -> Result, 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; 4]) -> Result, String> { let short_step = self.row(100)?.advance; let append_gap = |rows: &mut Vec, 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 { 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 { 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 { 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, 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); } }