diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 01:44:35 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 01:44:35 +0300 |
| commit | aaaa7aa0fd045de515079d21eeaf71e0815aa927 (patch) | |
| tree | f666c08f6735c22ed46d4a403b4a174be46bee4e /crates/fparkan-assets/src/help_screen.rs | |
| parent | 905fea2fc8f35992769546aa15649200b3982c4d (diff) | |
| download | fparkan-aaaa7aa0fd045de515079d21eeaf71e0815aa927.tar.xz fparkan-aaaa7aa0fd045de515079d21eeaf71e0815aa927.zip | |
feat(ui): open mission help and full message history with F1
Diffstat (limited to 'crates/fparkan-assets/src/help_screen.rs')
| -rw-r--r-- | crates/fparkan-assets/src/help_screen.rs | 432 |
1 files changed, 432 insertions, 0 deletions
diff --git a/crates/fparkan-assets/src/help_screen.rs b/crates/fparkan-assets/src/help_screen.rs new file mode 100644 index 00000000..c0e6a950 --- /dev/null +++ b/crates/fparkan-assets/src/help_screen.rs @@ -0,0 +1,432 @@ +//! 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; + +/// 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 CLOSE: [u32; 4] = [593, 2, 640, 23]; +const SCROLL: [[u32; 4]; 2] = [[526, 458, 576, 477], [576, 458, 626, 477]]; +const WHITE: [u8; 3] = [255; 3]; +const GREEN: [u8; 3] = [0, 255, 0]; +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: [RgbaImage; 3], + buttons: [RgbaImage; 3], + icons: [RgbaImage; 3], + labels: HelpLabels, + pages: [Vec<Row>; 3], + tab_index: usize, + scroll: [usize; 3], + message_count: usize, +} + +#[derive(Default)] +struct Row { + spans: Vec<(Vec<u8>, [u8; 3])>, + 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 mut screen = Self { + font: load_game_font(vfs)?, + frame: UiFrame::load(vfs)?, + tab: load_ui_sprites( + vfs, + "ui/compaund.cfg", + ["ccres_ending_text", "ccres_body_text", "ccres_ending_stub"], + )?, + buttons: load_ui_sprites( + vfs, + "ui/compaund.cfg", + [ + "ccres_exit_button_normal", + "ccres_long_button_off", + "ccres_long_button_normal", + ], + )?, + 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, + }; + 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 + 197, 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 })) + } + + /// 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 tint = if index == self.tab_index { + WHITE + } else { + GREEN + }; + let [leading, body, ending] = &self.tab; + sprite(&mut image, leading, [left, 2, left + 5, 21], WHITE); + sprite(&mut image, body, [left + 5, 2, left + 184, 21], WHITE); + sprite(&mut image, ending, [left + 184, 2, left + 189, 21], WHITE); + let text = encode(&self.labels.tabs[index])?; + let width = u32::from(self.font.line_metrics_bytes(&text)?[0]); + let center = scale(left + 94); + self.text( + &mut image, + &text, + [center.saturating_sub(width / 2), scale(6)], + tint, + )?; + } + sprite(&mut image, &self.buttons[0], [593, 2, 640, 21], WHITE); + sprite(&mut image, &self.icons[0], [610, 5, 623, 18], WHITE); + let start = self.scroll[self.tab_index]; + let enabled = [start < self.last_scroll(), start > 0]; + for (index, bounds) in SCROLL.into_iter().enumerate() { + let [l, t, _, _] = bounds; + sprite( + &mut image, + &self.buttons[1 + usize::from(enabled[index])], + bounds, + WHITE, + ); + sprite( + &mut image, + &self.icons[index + 1], + [l + 10, t + 2, l + 40, t + 17], + WHITE, + ); + } + let mut y = scale(PAGE[1]); + let [_, glyph_height] = self.font.line_metrics("")?; + for row in &self.pages[self.tab_index][start..] { + if y + u32::from(glyph_height) > scale(PAGE[3]) { + break; + } + let mut x = scale(PAGE[0]); + for (bytes, color) in &row.spans { + self.text(&mut image, bytes, [x, y], *color)?; + x += u32::from(self.font.line_metrics_bytes(bytes)?[0]); + } + y += row.advance; + } + Ok(image) + } + + fn last_scroll(&self) -> usize { + let rows = &self.pages[self.tab_index]; + let visible = scale(PAGE[3]) - scale(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 mut rows = vec![ + self.text_row(&self.labels.common_keys, YELLOW)?, + self.row(100)?, + ]; + 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); + rows.push(self.text_row(&self.labels.game_menu_hint.replace("%s", &key), WHITE)?); + rows.push(self.row(100)?); + for (group, title) in groups.iter().zip(&self.labels.controls) { + rows.push(self.text_row(title, YELLOW)?); + for entry in group { + rows.push(self.control_row(entry)?); + } + rows.push(self.row(150)?); + } + Ok(rows) + } + + fn control_row(&self, entry: &HelpBinding) -> Result<Row, String> { + let mut row = self.row(150)?; + let mut keys = entry.keys.iter().filter(|key| !key.is_empty()); + if let Some(key) = keys.next() { + let mut label = key.clone(); + if let Some(second) = keys.next() { + label.extend_from_slice(b" + "); + label.extend_from_slice(second); + } + label.extend_from_slice(b" : "); + row.spans.push((label, WHITE)); + } + row.spans.push((entry.description.clone(), [230; 3])); + 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: (u32::from(height) * u32::from(spacing) / 100).max(1), + ..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 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 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); + } +} |
