aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/mission_catalog.rs
blob: 486bd52c305a7c8a65a036bed615ffe5824b5463 (plain) (blame)
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
//! Mission paths and menu captions from the installed mission directories.

use encoding_rs::WINDOWS_1251;
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_vfs::{Vfs, VfsError};
use std::collections::BTreeMap;

/// A playable mission and its display caption.
#[derive(Debug)]
pub struct MissionEntry {
    pub key: String,
    pub title: String,
}

/// One campaign's missions, in directory order.
#[derive(Debug)]
pub struct CampaignEntry {
    pub title: String,
    pub missions: Vec<MissionEntry>,
}

/// Missions offered by the campaign, single-game and demo menus.
#[derive(Debug, Default)]
pub struct MissionCatalog {
    pub campaigns: Vec<CampaignEntry>,
    pub single: Vec<MissionEntry>,
    pub demo: Option<MissionEntry>,
}

/// Lists mission keys in the same order as the numbered command-line entries.
pub fn list_mission_keys(vfs: &dyn Vfs) -> Result<Vec<String>, String> {
    let prefix = normalize_relative(b"MISSIONS", PathPolicy::StrictLegacy)
        .expect("constant missions prefix");
    let entries = vfs
        .list(&prefix)
        .map_err(|error| format!("list missions: {error}"))?;
    Ok(entries
        .into_iter()
        .filter(|entry| {
            entry
                .path
                .as_bytes()
                .rsplit(|&byte| byte == b'/')
                .next()
                .is_some_and(|name| name.eq_ignore_ascii_case(b"data.tma"))
        })
        .map(|entry| entry.path.as_str().to_string())
        .collect())
}

impl MissionCatalog {
    /// Discovers campaigns and solo missions with a readable `descr` caption.
    pub fn load(vfs: &dyn Vfs) -> Result<Self, String> {
        let mut campaigns: BTreeMap<String, CampaignEntry> = BTreeMap::new();
        let mut single = Vec::new();
        let mut demo = None;
        for key in list_mission_keys(vfs)? {
            let (directory, _) = key.rsplit_once('/').expect("mission keys have a directory");
            let components: Vec<_> = directory.split('/').collect();
            match components.as_slice() {
                [_, root, campaign, mission]
                    if root.eq_ignore_ascii_case("CAMPAIGN")
                        && is_numbered(campaign, "CAMPAIGN.")
                        && is_numbered(mission, "Mission.") =>
                {
                    let Some(mission_title) = description(vfs, directory)? else {
                        continue;
                    };
                    let (campaign_dir, _) = directory.rsplit_once('/').expect("campaign directory");
                    let campaign_key = campaign_dir.to_ascii_lowercase();
                    let campaign = match campaigns.entry(campaign_key) {
                        std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
                        std::collections::btree_map::Entry::Vacant(entry) => {
                            let Some(title) = description(vfs, campaign_dir)? else {
                                continue;
                            };
                            entry.insert(CampaignEntry {
                                title,
                                missions: Vec::new(),
                            })
                        }
                    };
                    campaign.missions.push(MissionEntry {
                        key,
                        title: mission_title,
                    });
                }
                [_, single_dir] if is_numbered(single_dir, "Single.") => {
                    if let Some(title) = description(vfs, directory)? {
                        single.push(MissionEntry { key, title });
                    }
                }
                [_, demo_dir] if demo_dir.eq_ignore_ascii_case("Autodemo.00") => {
                    if let Some(title) = description(vfs, directory)? {
                        demo = Some(MissionEntry { key, title });
                    }
                }
                _ => {}
            }
        }
        Ok(Self {
            campaigns: campaigns.into_values().collect(),
            single,
            demo,
        })
    }
}

fn is_numbered(name: &str, prefix: &str) -> bool {
    let Some(head) = name.get(..prefix.len()) else {
        return false;
    };
    let digits = &name.as_bytes()[prefix.len()..];
    head.eq_ignore_ascii_case(prefix) && digits.len() == 2 && digits.iter().all(u8::is_ascii_digit)
}

fn description(vfs: &dyn Vfs, directory: &str) -> Result<Option<String>, String> {
    let name = format!("{directory}/descr");
    let path = normalize_relative(name.as_bytes(), PathPolicy::StrictLegacy)
        .map_err(|error| format!("{name}: {error}"))?;
    let bytes = match vfs.read(&path) {
        Ok(bytes) => bytes,
        Err(VfsError::NotFound(_)) => return Ok(None),
        Err(error) => return Err(format!("{name}: {error}")),
    };
    // iron3d+0x22480 reads one line into a 128-byte C string buffer.
    let length = bytes.len().min(127);
    let line = bytes[..length]
        .split(|&byte| matches!(byte, 0 | b'\n' | b'\r'))
        .next()
        .unwrap_or_default();
    let (text, _) = WINDOWS_1251.decode_without_bom_handling(line);
    let title = text.trim();
    Ok((!title.is_empty()).then(|| title.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use fparkan_vfs::{DirectoryVfs, MemoryVfs};
    use std::sync::Arc;

    #[test]
    fn reads_mission_titles_and_keeps_network_maps_out_of_the_solo_menu() {
        let mut vfs = MemoryVfs::default();
        for (key, bytes) in [
            (
                "MISSIONS/CAMPAIGN/CAMPAIGN.00/descr",
                b"Campaign".as_slice(),
            ),
            ("MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma", b""),
            (
                "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/descr",
                b"\xcf\xee\xeb\xee\xed\r\nextra",
            ),
            ("MISSIONS/Single.01/data.tma", b""),
            ("MISSIONS/Single.01/descr", b"Solo"),
            ("MISSIONS/Multi.01/data.tma", b""),
            ("MISSIONS/Multi.01/descr", b"Network"),
        ] {
            vfs.insert(
                normalize_relative(key.as_bytes(), PathPolicy::StrictLegacy).unwrap(),
                Arc::from(bytes),
            );
        }
        assert_eq!(list_mission_keys(&vfs).unwrap().len(), 3);
        let catalog = MissionCatalog::load(&vfs).unwrap();
        assert_eq!(catalog.campaigns[0].title, "Campaign");
        assert_eq!(catalog.campaigns[0].missions[0].title, "Полон");
        assert_eq!(catalog.single.len(), 1);
        assert_eq!(catalog.single[0].key, "MISSIONS/Single.01/data.tma");
        assert!(catalog.demo.is_none());
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_catalog_loads_all_campaign_and_single_missions() {
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
        let vfs = DirectoryVfs::new(root);
        let catalog = MissionCatalog::load(&vfs).unwrap();
        assert_eq!(catalog.campaigns.len(), 6);
        assert_eq!(
            catalog
                .campaigns
                .iter()
                .map(|campaign| campaign.missions.len())
                .sum::<usize>(),
            20
        );
        assert_eq!(catalog.campaigns[0].missions[0].title, "Огневой рубеж");
        assert_eq!(catalog.single.len(), 2);
        assert!(catalog.single[0].title.starts_with("Две Крепости"));
        assert_eq!(catalog.demo.unwrap().title, "DEMO");
    }
}