aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-02 01:30:06 +0300
committerValentin Popov <valentin@popov.link>2026-12-02 01:30:06 +0300
commit905fea2fc8f35992769546aa15649200b3982c4d (patch)
treed024e31eef055673da63099790e4f0dc4ab54b66 /crates
parentb8f6c1e8e169bc8d8ff0f85de1e3ddd478026e3d (diff)
downloadfparkan-905fea2fc8f35992769546aa15649200b3982c4d.tar.xz
fparkan-905fea2fc8f35992769546aa15649200b3982c4d.zip
feat(ui): decode mission help resources
Diffstat (limited to 'crates')
-rw-r--r--crates/fparkan-assets/src/help_resources.rs261
-rw-r--r--crates/fparkan-assets/src/lib.rs1
2 files changed, 262 insertions, 0 deletions
diff --git a/crates/fparkan-assets/src/help_resources.rs b/crates/fparkan-assets/src/help_resources.rs
new file mode 100644
index 00000000..2bd0e7e8
--- /dev/null
+++ b/crates/fparkan-assets/src/help_resources.rs
@@ -0,0 +1,261 @@
+//! Text and controls used by the original in-mission help terminal.
+
+use crate::ui_configuration::read;
+use fparkan_path::{normalize_relative, PathPolicy};
+use fparkan_vfs::{Vfs, VfsError};
+use std::collections::BTreeMap;
+
+const CONTROL_TABLES: [&str; 4] = ["ui_hero", "ui_bots", "ui_hq", "ui_other"];
+
+/// A token from a mission's CP1251 `Mistips.mis`.
+#[derive(Debug, PartialEq, Eq)]
+pub enum MissionTip {
+ /// Original bytes to draw with the game font.
+ Text(Vec<u8>),
+ /// An explicit line break independent of the file's physical newlines.
+ Break,
+ /// RGB tint for the following text.
+ Color([u8; 3]),
+ /// Closes a color span.
+ EndColor,
+ /// Line spacing as a percentage.
+ Interleave(u16),
+}
+
+/// One entry in a help command table, in its original CP1251 encoding.
+#[derive(Debug, PartialEq, Eq)]
+pub struct HelpBinding {
+ /// Command identifier as read from a `.man` file.
+ pub command: String,
+ /// Localized description from `Command.dsc`.
+ pub description: Vec<u8>,
+ /// Modifier and primary key labels from `Scancode.dsc`.
+ pub keys: [Vec<u8>; 2],
+}
+
+/// Resource-backed pages that are available before any messages have arrived.
+#[derive(Debug)]
+pub struct HelpResources {
+ /// None for maps without a `Mistips.mis` file.
+ pub mission: Option<Vec<MissionTip>>,
+ /// Battle suit, warbot, bunker/MCU, and additional controls, in native order.
+ pub controls: [Vec<HelpBinding>; 4],
+}
+
+impl HelpResources {
+ /// Loads the selected mission's tips and the original help bindings.
+ /// The alternate input profile reads the `_d.man` variants.
+ pub fn load(vfs: &dyn Vfs, mission: &str, alternate_controls: bool) -> Result<Self, String> {
+ let mission_directory = mission
+ .rsplit_once(['/', '\\'])
+ .map_or("", |(directory, _)| directory);
+ let tips = if mission_directory.is_empty() {
+ "Mistips.mis".into()
+ } else {
+ format!("{mission_directory}/Mistips.mis")
+ };
+ let path = normalize_relative(tips.as_bytes(), PathPolicy::StrictLegacy)
+ .map_err(|error| error.to_string())?;
+ let mission = match vfs.read(&path) {
+ Ok(bytes) => Some(parse_tips(&bytes)?),
+ Err(VfsError::NotFound(_)) => None,
+ Err(error) => return Err(error.to_string()),
+ };
+ let commands = read(vfs, "Command.dsc")?;
+ let scancodes = read(vfs, "Scancode.dsc")?;
+ let commands = descriptions(&commands);
+ let scancodes = descriptions(&scancodes);
+ let mut controls = std::array::from_fn(|_| Vec::new());
+ for (section, base) in controls.iter_mut().zip(CONTROL_TABLES) {
+ let suffix = if alternate_controls { "_d" } else { "" };
+ let path = format!("{base}{suffix}.man");
+ let data = read(vfs, &path)?;
+ *section = control_table(&data, &commands, &scancodes)
+ .map_err(|error| format!("{path}: {error}"))?;
+ }
+ Ok(Self { mission, controls })
+ }
+}
+
+fn parse_tips(mut input: &[u8]) -> Result<Vec<MissionTip>, String> {
+ let mut output = Vec::new();
+ while let Some(start) = input.windows(2).position(|pair| pair == b"<<") {
+ if start != 0 {
+ output.push(MissionTip::Text(input[..start].to_vec()));
+ }
+ input = &input[start + 2..];
+ let end = input
+ .windows(2)
+ .position(|pair| pair == b">>")
+ .ok_or("unterminated mission advice directive")?;
+ let command = std::str::from_utf8(&input[..end])
+ .map_err(|_| "mission advice directive is outside ASCII")?;
+ output.push(parse_tip_directive(command)?);
+ input = &input[end + 2..];
+ }
+ if !input.is_empty() {
+ output.push(MissionTip::Text(input.to_vec()));
+ }
+ Ok(output)
+}
+
+fn parse_tip_directive(command: &str) -> Result<MissionTip, String> {
+ if command == "br" {
+ return Ok(MissionTip::Break);
+ }
+ if command == "/color" {
+ return Ok(MissionTip::EndColor);
+ }
+ if let Some(value) = command.strip_prefix("interleave=") {
+ return value
+ .parse()
+ .map(MissionTip::Interleave)
+ .map_err(|_| format!("invalid mission advice spacing {value}"));
+ }
+ if let Some(value) = command.strip_prefix("color=") {
+ let channels = value
+ .split(',')
+ .map(str::parse)
+ .collect::<Result<Vec<u8>, _>>();
+ if let Ok(channels) = channels {
+ if let Ok(rgb) = channels.try_into() {
+ return Ok(MissionTip::Color(rgb));
+ }
+ }
+ return Err(format!("invalid mission advice color {value}"));
+ }
+ Err(format!("unknown mission advice directive {command}"))
+}
+
+fn descriptions(input: &[u8]) -> BTreeMap<&[u8], &[u8]> {
+ input
+ .split(|&byte| byte == b'\n')
+ .map(<[u8]>::trim_ascii)
+ .filter(|line| line.starts_with(b"SCAN_") || line.starts_with(b"CMD_"))
+ .map(|line| {
+ let end = line
+ .iter()
+ .position(u8::is_ascii_whitespace)
+ .unwrap_or(line.len());
+ (&line[..end], line[end..].trim_ascii())
+ })
+ .collect()
+}
+
+fn control_table(
+ input: &[u8],
+ commands: &BTreeMap<&[u8], &[u8]>,
+ scancodes: &BTreeMap<&[u8], &[u8]>,
+) -> Result<Vec<HelpBinding>, String> {
+ input
+ .split(|&byte| byte == b'\n')
+ .map(<[u8]>::trim_ascii)
+ .filter(|line| !line.is_empty())
+ .map(|line| {
+ let mut fields = line
+ .split(u8::is_ascii_whitespace)
+ .filter(|part| !part.is_empty());
+ let (Some(command), Some(modifier), Some(key), None) =
+ (fields.next(), fields.next(), fields.next(), fields.next())
+ else {
+ return Err("expected command, modifier, and scancode".into());
+ };
+ let description = description_field(commands, command)?;
+ let keys = [
+ description_field(scancodes, modifier)?,
+ description_field(scancodes, key)?,
+ ];
+ let command = std::str::from_utf8(command)
+ .map_err(|_| "command identifier is outside ASCII")?
+ .to_owned();
+ Ok(HelpBinding {
+ command,
+ description,
+ keys,
+ })
+ })
+ .collect()
+}
+
+fn description_field(
+ records: &BTreeMap<&[u8], &[u8]>,
+ identifier: &[u8],
+) -> Result<Vec<u8>, String> {
+ records
+ .get(identifier)
+ .map(|&value| value.to_vec())
+ .ok_or_else(|| {
+ format!(
+ "missing help description for {}",
+ String::from_utf8_lossy(identifier)
+ )
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn advice_preserves_cp1251_and_explicit_breaks() {
+ assert_eq!(
+ parse_tips(b"<<interleave=150>><<color=255,0,0>>\xcd\xe0<</color>><<br>>").unwrap(),
+ [
+ MissionTip::Interleave(150),
+ MissionTip::Color([255, 0, 0]),
+ MissionTip::Text(vec![0xcd, 0xe0]),
+ MissionTip::EndColor,
+ MissionTip::Break,
+ ]
+ );
+ assert!(parse_tips(b"<<color=255,0>>").is_err());
+ assert!(parse_tips(b"unfinished <<br").is_err());
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn resolves_stock_fireline_help_and_f1_from_game_files() {
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
+ let vfs = fparkan_vfs::DirectoryVfs::new(root);
+ let help = HelpResources::load(
+ &vfs,
+ "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma",
+ false,
+ )
+ .unwrap();
+ assert!(matches!(
+ help.mission.unwrap().first(),
+ Some(MissionTip::Interleave(150))
+ ));
+ assert_eq!(help.controls.each_ref().map(Vec::len), [8, 13, 8, 44]);
+ let help_key = help.controls[3]
+ .iter()
+ .find(|binding| binding.command == "CMD_HELP")
+ .unwrap();
+ assert_eq!(help_key.keys, [vec![], b"F1".to_vec()]);
+ assert!(!help_key.description.is_empty());
+ HelpResources::load(
+ &vfs,
+ "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma",
+ true,
+ )
+ .unwrap();
+ let prefix = normalize_relative(b"MISSIONS", PathPolicy::StrictLegacy).unwrap();
+ let mut documents = 0;
+ for entry in vfs.list(&prefix).unwrap() {
+ if entry
+ .path
+ .as_bytes()
+ .rsplit(|&byte| byte == b'/')
+ .next()
+ .is_some_and(|name| name.eq_ignore_ascii_case(b"mistips.mis"))
+ {
+ let bytes = vfs.read(&entry.path).unwrap();
+ parse_tips(&bytes)
+ .unwrap_or_else(|error| panic!("{}: {error}", entry.path.as_str()));
+ documents += 1;
+ }
+ }
+ assert!(documents > 1);
+ }
+}
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index 810a5300..83231ebb 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -36,6 +36,7 @@ mod control_drive;
mod control_weapon_sound;
mod explosion_profile;
pub mod game_font;
+pub mod help_resources;
pub mod mission_loader;
pub mod mission_pager;
pub mod object_descriptions;