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
|
//! Settings shared with the installed game's `Iron_3D.ini` profile.
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_vfs::{Vfs, VfsError};
use std::sync::Arc;
/// The original game's profile. A missing INI supplies no overrides.
#[derive(Default)]
pub struct GameSettings(Arc<[u8]>);
impl GameSettings {
/// Reads the installed profile through the same VFS as the game data.
pub fn load(vfs: &dyn Vfs) -> Result<Self, VfsError> {
let path = normalize_relative(b"Iron_3D.ini", PathPolicy::StrictLegacy)
.map_err(|_| VfsError::Path)?;
match vfs.read(&path) {
Ok(bytes) => Ok(Self(bytes)),
Err(VfsError::NotFound(_)) => Ok(Self::default()),
Err(error) => Err(error),
}
}
/// Reads an integer from the case-insensitive `[CS]` section.
pub fn integer(&self, key: &str) -> Option<i32> {
let text = String::from_utf8_lossy(&self.0);
let mut controls = false;
for line in text.lines().map(str::trim) {
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
controls = section.0.eq_ignore_ascii_case("CS");
continue;
}
if controls {
if let Some((name, value)) = line.split_once('=') {
if name.trim().eq_ignore_ascii_case(key) {
return value.trim().parse().ok();
}
}
}
}
None
}
/// Returns the requested display when both client dimensions are present.
pub fn display(&self) -> Option<DisplaySettings> {
let positive = |key| u32::try_from(self.integer(key)?).ok().filter(|&n| n != 0);
Some(DisplaySettings {
extent: [positive("DISPLAY_WIDTH")?, positive("DISPLAY_HEIGHT")?],
bit_depth: positive("BITDEPTH").unwrap_or(32),
windowed: self.integer("WINDOW_MODE").unwrap_or(1) != 0,
})
}
/// An explicit zero disables the separate water reflection pass.
pub fn water_reflections(&self) -> bool {
self.integer("REFLECTIONS").unwrap_or(1) != 0
}
/// Reads separate wave and CD volume settings from the original profile.
pub fn audio(&self) -> AudioSettings {
let gain = |key| {
self.integer(key)
.map(|value| value.clamp(0, 100) as f32 * 0.01)
};
AudioSettings {
effects_gain: gain("SFX_VOLUME"),
cd_gain: gain("CD_VOLUME"),
play_cd: self.integer("PLAY_CD_MUSIC").unwrap_or_default() != 0,
}
}
/// Replaces selected `[CS]` integers, preserving the other profile bytes.
pub fn with_cs_integers(&self, updates: &[(&str, i32)]) -> Vec<u8> {
let mut bytes = self.0.to_vec();
let newline = if bytes.windows(2).any(|pair| pair == b"\r\n") {
"\r\n"
} else {
"\n"
};
for &(key, value) in updates {
write_cs_integer(&mut bytes, key, value, newline);
}
bytes
}
}
fn write_cs_integer(bytes: &mut Vec<u8>, key: &str, value: i32, newline: &str) {
let mut offset = 0;
let mut in_cs = false;
let mut insert_at = None;
for line in bytes.split_inclusive(|&byte| byte == b'\n') {
let trimmed = line.trim_ascii();
if let Some(section) = trimmed.strip_prefix(b"[") {
in_cs = section
.iter()
.position(|&byte| byte == b']')
.is_some_and(|end| section[..end].eq_ignore_ascii_case(b"CS"));
} else if in_cs {
if let Some(equals) = line.iter().position(|&byte| byte == b'=') {
if line[..equals]
.trim_ascii()
.eq_ignore_ascii_case(key.as_bytes())
{
let field = &line[equals + 1..];
let content = field.trim_ascii_end();
let start =
offset + equals + 1 + content.len() - content.trim_ascii_start().len();
let end = offset + equals + 1 + content.len();
bytes.splice(start..end, value.to_string().bytes());
return;
}
}
}
offset += line.len();
if in_cs {
insert_at = Some(offset);
}
}
let at = insert_at.unwrap_or(bytes.len());
let separator = if at > 0 && bytes[at - 1] != b'\n' {
newline
} else {
""
};
let entry = match insert_at {
Some(_) => format!("{separator}{key}={value}{newline}"),
None => format!("{separator}[CS]{newline}{key}={value}{newline}"),
};
bytes.splice(at..at, entry.bytes());
}
/// The size, color depth and display mode requested by the legacy profile.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DisplaySettings {
pub extent: [u32; 2],
pub bit_depth: u32,
pub windowed: bool,
}
impl DisplaySettings {
/// The original mode selector gives each pixel of difference a weight of 100.
pub fn mode_distance(self, extent: [u32; 2], bit_depth: u32) -> u64 {
let [width, height] = self.extent;
(u64::from(width.abs_diff(extent[0])) + u64::from(height.abs_diff(extent[1]))) * 100
+ u64::from(self.bit_depth.abs_diff(bit_depth))
}
}
/// Initial gains by sound source. Omitted controls leave the mixer defaults.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AudioSettings {
pub effects_gain: Option<f32>,
pub cd_gain: Option<f32>,
pub play_cd: bool,
}
#[cfg(test)]
#[test]
fn reads_the_original_display_profile_and_scores_video_modes() {
let settings = GameSettings(Arc::from(
&b"[OTHER]\nDISPLAY_WIDTH=1\n[cs]\n display_width=800\n DISPLAY_HEIGHT = 600\nBITDEPTH=16\nWINDOW_MODE=0"[..],
));
let display = settings.display().unwrap();
assert_eq!(display.extent, [800, 600]);
assert!(!display.windowed);
assert_eq!(display.mode_distance([800, 600], 32), 16);
assert_eq!(display.mode_distance([799, 601], 16), 200);
assert!(GameSettings::default().display().is_none());
}
#[cfg(test)]
#[test]
fn reads_water_reflections_independently_of_embm() {
let settings = GameSettings(Arc::from(&b"[CS]\nREFLECTIONS=0\nEMBM=1"[..]));
assert!(!settings.water_reflections());
let settings = GameSettings(Arc::from(&b"[CS]\nREFLECTIONS=1\nEMBM=0"[..]));
assert!(settings.water_reflections());
assert!(GameSettings::default().water_reflections());
}
#[cfg(test)]
#[test]
fn reads_separate_effects_and_cd_controls() {
let settings = GameSettings(Arc::from(
&b"[CS]\nSFX_VOLUME=20\nCD_VOLUME=120\nPLAY_CD_MUSIC=0\n[OTHER]\nSFX_VOLUME=60"[..],
));
let audio = settings.audio();
assert!((audio.effects_gain.unwrap() - 0.2).abs() < f32::EPSILON);
assert_eq!(audio.cd_gain, Some(1.0));
assert!(!audio.play_cd);
assert_eq!(GameSettings::default().audio().effects_gain, None);
let music = GameSettings(Arc::from(&b"[CS]\nCD_VOLUME=0\nPLAY_CD_MUSIC=1"[..]));
assert_eq!(music.audio().cd_gain, Some(0.0));
assert!(music.audio().play_cd);
}
#[cfg(test)]
#[test]
fn updates_only_the_chosen_cs_entries() {
let settings = GameSettings(Arc::from(
&b";\xef\xf0\xe8\xec\xe5\xf0\r\n[cs]\r\n sfx_volume = 20 \r\n[NETWORK]\r\nSFX_VOLUME=5"[..],
));
assert_eq!(
settings.with_cs_integers(&[("SFX_VOLUME", 48), ("PLAY_CD_MUSIC", 1)]),
b";\xef\xf0\xe8\xec\xe5\xf0\r\n[cs]\r\n sfx_volume = 48 \r\nPLAY_CD_MUSIC=1\r\n[NETWORK]\r\nSFX_VOLUME=5"
);
assert_eq!(
GameSettings::default().with_cs_integers(&[("CD_VOLUME", 33)]),
b"[CS]\nCD_VOLUME=33\n"
);
}
|