redguard-preservation 0.6.3

A CLI tool to preserve Redguard files
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::import::png::save_png;
use crate::{Result, error::Error};
use image::{DynamicImage, GrayImage, Luma};
use std::path::{Path, PathBuf};

pub const WLD_HEADER_BYTES: usize = 1184;
pub const WLD_HEADER_DWORDS: usize = WLD_HEADER_BYTES / 4;
pub const WLD_SECTION_COUNT: usize = 4;
pub const WLD_SECTION_HEADER_BYTES: usize = 22;
pub const WLD_MAP_SIDE: usize = 128;
pub const WLD_MAP_BYTES: usize = WLD_MAP_SIDE * WLD_MAP_SIDE;
pub const WLD_SECTION_BYTES: usize = WLD_SECTION_HEADER_BYTES + (4 * WLD_MAP_BYTES);
pub const WLD_FOOTER_BYTES: usize = 16;

#[derive(Debug, Clone)]
/// Parsed WLD header stored as raw 32-bit fields.
pub struct WldHeader {
    pub fields: [u32; WLD_HEADER_DWORDS],
}

impl WldHeader {
    /// Returns the four section offsets from header fields 36..39.
    #[must_use]
    pub const fn section_offsets(&self) -> [u32; WLD_SECTION_COUNT] {
        [
            self.fields[36],
            self.fields[37],
            self.fields[38],
            self.fields[39],
        ]
    }
}

#[derive(Debug, Clone)]
/// Parsed WLD section containing a header blob and four 128x128 maps.
pub struct WldSection {
    pub header: [u8; WLD_SECTION_HEADER_BYTES],
    pub maps: [[u8; WLD_MAP_BYTES]; 4],
}

#[derive(Debug, Clone)]
/// Parsed WLD file with header, four sections, and footer bytes.
pub struct WldFile {
    pub header: WldHeader,
    // Keep terrain maps off the call stack, including parser return temporaries in WASM.
    pub sections: Box<[WldSection; WLD_SECTION_COUNT]>,
    pub footer: [u8; WLD_FOOTER_BYTES],
}

fn read_u32_le(data: &[u8], offset: usize) -> Result<u32> {
    if offset + 4 > data.len() {
        return Err(Error::Parse(format!(
            "WLD read out of bounds at offset {offset}"
        )));
    }
    Ok(u32::from_le_bytes(
        data[offset..offset + 4]
            .try_into()
            .map_err(|_| Error::Parse(format!("WLD failed to parse LE u32 at offset {offset}")))?,
    ))
}

fn read_fixed<const N: usize>(data: &[u8], offset: usize) -> Result<[u8; N]> {
    if offset + N > data.len() {
        return Err(Error::Parse(format!(
            "WLD read out of bounds at offset {offset} for {N} bytes"
        )));
    }

    data[offset..offset + N].try_into().map_err(|_| {
        Error::Parse(format!(
            "WLD failed to read fixed buffer at offset {offset}"
        ))
    })
}

/// Parses a WLD file from bytes and validates core section layout.
pub fn parse_wld_file(data: &[u8]) -> Result<WldFile> {
    let minimum_size = WLD_HEADER_BYTES + WLD_FOOTER_BYTES;
    if data.len() < minimum_size {
        return Err(Error::Parse(format!(
            "WLD file too small: {} bytes (minimum {minimum_size})",
            data.len()
        )));
    }

    let mut fields = [0_u32; WLD_HEADER_DWORDS];
    for (idx, field) in fields.iter_mut().enumerate() {
        *field = read_u32_le(data, idx * 4)?;
    }
    let header = WldHeader { fields };

    let offsets = header.section_offsets();
    if usize::try_from(offsets[0]).unwrap_or(usize::MAX) != WLD_HEADER_BYTES {
        return Err(Error::Parse(format!(
            "WLD section0 offset mismatch: expected {WLD_HEADER_BYTES}, found {}",
            offsets[0]
        )));
    }
    if usize::try_from(header.fields[6]).unwrap_or(usize::MAX) != WLD_SECTION_HEADER_BYTES {
        return Err(Error::Parse(format!(
            "WLD section-header-size mismatch: expected {WLD_SECTION_HEADER_BYTES}, found {}",
            header.fields[6]
        )));
    }
    for (idx, off) in offsets.iter().enumerate() {
        let next_off = if idx + 1 < WLD_SECTION_COUNT {
            usize::try_from(offsets[idx + 1]).unwrap_or(usize::MAX)
        } else {
            data.len().saturating_sub(WLD_FOOTER_BYTES)
        };

        let current = usize::try_from(*off).unwrap_or(usize::MAX);
        if current >= data.len() {
            return Err(Error::Parse(format!(
                "WLD section {idx} offset out of range: {current}"
            )));
        }
        if current >= next_off {
            return Err(Error::Parse(format!(
                "WLD section offsets are not strictly increasing at index {idx}: {current} >= {next_off}"
            )));
        }
        let span = next_off - current;
        if span < WLD_SECTION_BYTES {
            return Err(Error::Parse(format!(
                "WLD section {idx} too small: {span} bytes (minimum {WLD_SECTION_BYTES})"
            )));
        }
    }

    let mut parsed_sections = Vec::with_capacity(WLD_SECTION_COUNT);
    for off in offsets {
        let start = usize::try_from(off)
            .map_err(|_| Error::Parse("WLD section offset does not fit usize".to_string()))?;
        let header_bytes = read_fixed::<WLD_SECTION_HEADER_BYTES>(data, start)?;
        let mut cursor = start + WLD_SECTION_HEADER_BYTES;
        let mut maps = [[0_u8; WLD_MAP_BYTES]; 4];
        for map in &mut maps {
            *map = read_fixed::<WLD_MAP_BYTES>(data, cursor)?;
            cursor += WLD_MAP_BYTES;
        }
        parsed_sections.push(WldSection {
            header: header_bytes,
            maps,
        });
    }

    let sections: Box<[WldSection; WLD_SECTION_COUNT]> =
        parsed_sections.into_boxed_slice().try_into().map_err(|_| {
            Error::Parse("WLD internal section conversion failed (expected 4 sections)".to_string())
        })?;

    let footer = read_fixed::<WLD_FOOTER_BYTES>(data, data.len() - WLD_FOOTER_BYTES)?;

    Ok(WldFile {
        header,
        sections,
        footer,
    })
}

impl WldFile {
    /// Combines one map layer across the four WLD sections into a 2x2 grid.
    pub fn combined_map(&self, map_index: usize) -> Result<Vec<u8>> {
        if map_index >= 4 {
            return Err(Error::Parse(format!(
                "WLD map index out of range: {map_index} (expected 0..3)"
            )));
        }

        let out_side = WLD_MAP_SIDE * 2;
        let mut out = vec![0_u8; out_side * out_side];

        for y in 0..WLD_MAP_SIDE {
            let src_row = y * WLD_MAP_SIDE;
            let dst_top = y * out_side;
            let dst_bottom = (y + WLD_MAP_SIDE) * out_side;

            out[dst_top..dst_top + WLD_MAP_SIDE].copy_from_slice(
                &self.sections[0].maps[map_index][src_row..src_row + WLD_MAP_SIDE],
            );
            out[dst_top + WLD_MAP_SIDE..dst_top + out_side].copy_from_slice(
                &self.sections[1].maps[map_index][src_row..src_row + WLD_MAP_SIDE],
            );
            out[dst_bottom..dst_bottom + WLD_MAP_SIDE].copy_from_slice(
                &self.sections[2].maps[map_index][src_row..src_row + WLD_MAP_SIDE],
            );
            out[dst_bottom + WLD_MAP_SIDE..dst_bottom + out_side].copy_from_slice(
                &self.sections[3].maps[map_index][src_row..src_row + WLD_MAP_SIDE],
            );
        }

        Ok(out)
    }

    /// Returns combined map 1 with the high bit cleared for heightmap luminance.
    pub fn combined_heightmap_luma(&self) -> Result<Vec<u8>> {
        let map1 = self.combined_map(0)?;
        Ok(map1.into_iter().map(|value| value & 0x7F).collect())
    }
}

fn ensure_parent_dir(path: &Path) -> Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent).map_err(|e| Error::File {
            path: parent.to_path_buf(),
            message: format!("failed to create directory: {e}"),
        })?;
    }
    Ok(())
}

/// Exports combined WLD heightmap data to a PNG file.
pub fn export_wld_heightmap_png(
    input_path: &Path,
    output_path: &Path,
    compress: bool,
) -> Result<()> {
    let paths = export_wld_maps_pngs(input_path, output_path, compress)?;
    if paths.map1_path != output_path {
        std::fs::copy(&paths.map1_path, output_path).map_err(|e| Error::File {
            path: output_path.to_path_buf(),
            message: format!("failed to copy from '{}': {e}", paths.map1_path.display()),
        })?;
    }
    Ok(())
}

#[derive(Debug, Clone)]
/// Output PNG paths generated when exporting all four WLD maps.
pub struct WldMapExportPaths {
    pub map1_path: PathBuf,
    pub map2_path: PathBuf,
    pub map3_path: PathBuf,
    pub map4_path: PathBuf,
}

fn write_luma_png(output_path: &Path, luma: &[u8], compress: bool) -> Result<()> {
    let expected = (WLD_MAP_SIDE * 2) * (WLD_MAP_SIDE * 2);
    if luma.len() != expected {
        return Err(Error::Conversion(format!(
            "invalid luma buffer size: got {}, expected {}",
            luma.len(),
            expected
        )));
    }

    let image_side = u32::try_from(WLD_MAP_SIDE * 2)
        .map_err(|_| Error::Conversion("WLD image side does not fit u32".to_string()))?;
    let mut image = GrayImage::new(image_side, image_side);
    for (idx, px) in luma.iter().enumerate() {
        let x = u32::try_from(idx % (WLD_MAP_SIDE * 2))
            .map_err(|_| Error::Conversion("WLD x coordinate does not fit u32".to_string()))?;
        let y = u32::try_from(idx / (WLD_MAP_SIDE * 2))
            .map_err(|_| Error::Conversion("WLD y coordinate does not fit u32".to_string()))?;
        image.put_pixel(x, y, Luma([*px]));
    }

    ensure_parent_dir(output_path)?;
    save_png(&DynamicImage::ImageLuma8(image), output_path, compress).map_err(|e| {
        Error::Conversion(format!(
            "failed to write PNG '{}': {e}",
            output_path.display()
        ))
    })
}

fn map_output_paths(output_path: &Path) -> WldMapExportPaths {
    let mut base = output_path.to_path_buf();
    base.set_extension("");

    let stem = base
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("wld_map");
    let parent = output_path.parent().unwrap_or_else(|| Path::new(""));

    WldMapExportPaths {
        map1_path: parent.join(format!("{stem}_map1.png")),
        map2_path: parent.join(format!("{stem}_map2.png")),
        map3_path: parent.join(format!("{stem}_map3.png")),
        map4_path: parent.join(format!("{stem}_map4.png")),
    }
}

/// Exports all four combined WLD maps as grayscale PNG files.
pub fn export_wld_maps_pngs(
    input_path: &Path,
    output_path: &Path,
    compress: bool,
) -> Result<WldMapExportPaths> {
    let bytes = std::fs::read(input_path)?;
    let wld = parse_wld_file(&bytes)?;
    let paths = map_output_paths(output_path);

    write_luma_png(&paths.map1_path, &wld.combined_heightmap_luma()?, compress)?;
    write_luma_png(&paths.map2_path, &wld.combined_map(1)?, compress)?;
    write_luma_png(&paths.map3_path, &wld.combined_map(2)?, compress)?;
    write_luma_png(&paths.map4_path, &wld.combined_map(3)?, compress)?;

    Ok(paths)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn combine_map_stitches_sections_as_2x2_grid() {
        let section = |fill: u8| WldSection {
            header: [0_u8; WLD_SECTION_HEADER_BYTES],
            maps: [
                [fill; WLD_MAP_BYTES],
                [0; WLD_MAP_BYTES],
                [0; WLD_MAP_BYTES],
                [0; WLD_MAP_BYTES],
            ],
        };

        let file = WldFile {
            header: WldHeader {
                fields: [0; WLD_HEADER_DWORDS],
            },
            sections: Box::new([section(10), section(20), section(30), section(40)]),
            footer: [0; WLD_FOOTER_BYTES],
        };

        let stitched = file.combined_map(0).expect("combined map");
        let side = WLD_MAP_SIDE * 2;
        assert_eq!(stitched.len(), side * side);

        assert_eq!(stitched[0], 10);
        assert_eq!(stitched[WLD_MAP_SIDE], 20);
        assert_eq!(stitched[WLD_MAP_SIDE * side], 30);
        assert_eq!(stitched[(WLD_MAP_SIDE * side) + WLD_MAP_SIDE], 40);
    }

    #[test]
    fn parse_keeps_terrain_maps_on_heap() {
        assert!(std::mem::size_of::<WldFile>() < 2048);
        let mut bytes =
            vec![0; WLD_HEADER_BYTES + WLD_SECTION_COUNT * WLD_SECTION_BYTES + WLD_FOOTER_BYTES];
        bytes[24..28].copy_from_slice(&(WLD_SECTION_HEADER_BYTES as u32).to_le_bytes());
        for index in 0..WLD_SECTION_COUNT {
            let start = WLD_HEADER_BYTES + index * WLD_SECTION_BYTES;
            let offset = (36 + index) * 4;
            bytes[offset..offset + 4].copy_from_slice(&(start as u32).to_le_bytes());
            bytes[start + WLD_SECTION_HEADER_BYTES] = (index + 1) as u8;
        }
        let file = parse_wld_file(&bytes).expect("valid terrain");
        assert_eq!(
            file.sections.each_ref().map(|section| section.maps[0][0]),
            [1, 2, 3, 4]
        );
    }

    #[test]
    fn parse_rejects_too_small_file() {
        let bytes = vec![0_u8; 32];
        let err = parse_wld_file(&bytes).expect_err("expected parse error");
        assert!(matches!(err, Error::Parse(_)));
    }

    #[test]
    fn combined_heightmap_strips_high_bit_without_scaling() {
        let mut section = WldSection {
            header: [0_u8; WLD_SECTION_HEADER_BYTES],
            maps: [[0; WLD_MAP_BYTES]; 4],
        };
        section.maps[0][0] = 0xFF;

        let file = WldFile {
            header: WldHeader {
                fields: [0; WLD_HEADER_DWORDS],
            },
            sections: Box::new([section.clone(), section.clone(), section.clone(), section]),
            footer: [0; WLD_FOOTER_BYTES],
        };

        let luma = file
            .combined_heightmap_luma()
            .expect("combined heightmap luma");
        assert_eq!(luma[0], 0x7F);
    }

    #[test]
    fn map_output_paths_append_map_suffixes() {
        let paths = map_output_paths(Path::new("out/island_height.png"));
        assert_eq!(paths.map1_path, PathBuf::from("out/island_height_map1.png"));
        assert_eq!(paths.map2_path, PathBuf::from("out/island_height_map2.png"));
        assert_eq!(paths.map3_path, PathBuf::from("out/island_height_map3.png"));
        assert_eq!(paths.map4_path, PathBuf::from("out/island_height_map4.png"));
    }
}

const WLD_HEIGHT_TABLE: [u16; 128] = [
    0, 40, 40, 40, 80, 80, 80, 120, 120, 120, 160, 160, 160, 200, 200, 200, 240, 240, 240, 280,
    280, 320, 320, 320, 360, 360, 400, 400, 400, 440, 440, 480, 480, 480, 520, 520, 560, 560, 600,
    600, 600, 640, 640, 680, 680, 720, 720, 760, 760, 800, 800, 840, 840, 880, 880, 920, 920, 960,
    1000, 1000, 1040, 1040, 1080, 1120, 1120, 1160, 1160, 1200, 1240, 1240, 1280, 1320, 1320, 1360,
    1400, 1440, 1440, 1480, 1520, 1560, 1600, 1600, 1640, 1680, 1720, 1760, 1800, 1840, 1880, 1920,
    1960, 2000, 2040, 2080, 2120, 2200, 2240, 2280, 2320, 2400, 2440, 2520, 2560, 2640, 2680, 2760,
    2840, 2920, 3000, 3080, 3160, 3240, 3360, 3440, 3560, 3680, 3800, 3960, 4080, 4280, 4440, 4680,
    4920, 5200, 5560, 6040, 6680, 7760,
];

/// Decodes a WLD height byte to unshifted engine Y in map units, positive down.
/// The build-time high bit is discarded. See `docs/formats/WLD.md`.
#[must_use]
pub fn decode_height(value: u8) -> i16 {
    -(WLD_HEIGHT_TABLE[usize::from(value & 0x7f)] as i16)
}

#[cfg(test)]
mod height_tests {
    #[test]
    fn decoded_heights_retain_engine_sign_and_strip_build_flag() {
        assert_eq!(super::decode_height(0), 0);
        assert_eq!(super::decode_height(43), -680);
        assert_eq!(super::decode_height(127), -7760);
        for value in 0..128 {
            assert_eq!(
                super::decode_height(value),
                super::decode_height(value | 128)
            );
        }
    }
}