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
use super::*;
use crate::nbt::{self, Value};
use biome::Biome;
use flate2::read::ZlibDecoder;

pub trait RegionDrawer {
    fn draw(&mut self, xc_rel: usize, zc_rel: usize, chunk: &Chunk);
}

pub struct Chunk {
    heights: Vec<u16>,
    sections: Vec<Option<Section>>,
    biomes: Option<Vec<i32>>,
}

impl Chunk {
    pub fn new(heights: Vec<u16>, sections: Vec<Section>, biomes: Option<Vec<i32>>) -> Self {
        let mut s = Vec::new();
        s.resize_with(16, || None);

        for sec in sections {
            let y = sec.y as usize;
            s[y] = Some(sec);
        }

        Self {
            heights,
            sections: s,
            biomes,
        }
    }

    pub fn id_of(&self, x: usize, y: usize, z: usize) -> &str {
        let containing_section_y = y / 16;
        let ref sec = self.sections[containing_section_y as usize];

        if let Some(sec) = sec {
            let sec_y = y - sec.y as usize * 16;
            let state_index = (sec_y as usize * 16 * 16) + x * 16 + z;
            let pal_index = sec.states[state_index] as usize;
            &sec.palette[pal_index]
        } else {
            ""
        }
    }

    pub fn height_of(&self, x: usize, z: usize) -> usize {
        self.heights[x * 16 + z] as usize
    }

    pub fn biome_of(&self, x: usize, _y: usize, z: usize) -> Option<Biome> {
        // TODO: Take into account height. For overworld this doesn't matter (at least not yet)
        // TODO: Make use of data version?

        // For biome len of 1024,
        //  it's 4x4x4 sets of blocks stored by z then x then y (+1 moves one in z)
        //  for overworld theres no vertical chunks so it looks like only first 16 values are used.
        // For biome len of 256, it's chunk 1x1 columns stored z then x.

        let biomes = self.biomes.as_ref()?;

        if biomes.len() == 1024 {
            Biome::try_from(biomes[(x / 4) * 4 + (z / 4)]).ok()
        } else {
            Biome::try_from(biomes[x * 16 + z]).ok()
        }
    }
}

#[derive(Debug)]
pub struct Section {
    pub states: Vec<u16>,
    pub palette: Vec<String>,
    pub y: u8,
}

pub struct RegionMap<T> {
    pub data: Vec<T>,
    pub x_region: isize,
    pub z_region: isize,
}

impl<T: Clone> RegionMap<T> {
    pub fn new(x_region: isize, z_region: isize, default: T) -> Self {
        let mut data: Vec<T> = Vec::new();
        data.resize(16 * 16 * 32 * 32, default);
        Self {
            data,
            x_region,
            z_region,
        }
    }

    pub fn chunk_mut(&mut self, x: usize, z: usize) -> &mut [T] {
        let len = 16 * 16;
        let begin = (x * 32 + z) * len; // TODO: x or z ordered?
        &mut self.data[begin..begin + len]
    }

    pub fn chunk(&self, x: usize, z: usize) -> &[T] {
        let len = 16 * 16;
        let begin = (x * 32 + z) * len; // TODO: x or z ordered?
        &self.data[begin..begin + len]
    }
}

pub type Rgb = [u8; 3];

pub struct RegionHeightmapDrawer<'a> {
    map: &'a mut RegionMap<Rgb>,
}

impl<'a> RegionHeightmapDrawer<'a> {
    pub fn new(map: &'a mut RegionMap<Rgb>) -> Self {
        Self { map }
    }
}

impl<'a> RegionDrawer for RegionHeightmapDrawer<'a> {
    fn draw(&mut self, xc_rel: usize, zc_rel: usize, chunk: &Chunk) {
        let data = (*self.map).chunk_mut(xc_rel, zc_rel);

        for z in 0..16 {
            for x in 0..16 {
                const SEA_LEVEL: u16 = 63;
                let height = chunk.heights[x * 16 + z];

                if height <= SEA_LEVEL {
                    data[x * 16 + z] = [height as u8, height as u8, 150];
                } else {
                    let height = (height - 63) * 2;
                    data[x * 16 + z] = [height as u8, 150, height as u8];
                }
            }
        }
    }
}

#[derive(Debug)]
pub enum DrawError {
    ParseAnvil(super::Error),
    ParseNbt(nbt::Error),
    MissingHeightMap,
    InvalidPalette,
}

impl From<nbt::Error> for DrawError {
    fn from(err: nbt::Error) -> DrawError {
        DrawError::ParseNbt(err)
    }
}

impl From<super::Error> for DrawError {
    fn from(err: super::Error) -> DrawError {
        DrawError::ParseAnvil(err)
    }
}

pub type DrawResult<T> = std::result::Result<T, DrawError>;

pub fn parse_region<F: RegionDrawer + ?Sized>(
    mut region: Region<std::fs::File>,
    draw_to: &mut F,
) -> DrawResult<()> {
    let mut offsets = Vec::<ChunkLocation>::new();

    for x in 0..32 {
        for z in 0..32 {
            let loc = region.chunk_location(x, z)?;

            // 0,0 chunk location means the chunk isn't present.
            // cannot decide if this means we should return an error from chunk_location() or not.
            if loc.begin_sector != 0 && loc.sector_count != 0 {
                offsets.push(loc);
            }
        }
    }

    offsets.sort_by(|o1, o2| o1.begin_sector.cmp(&o2.begin_sector));

    for off in offsets {
        let mut buf = vec![0u8; off.sector_count * SECTOR_SIZE];
        region.load_chunk(&off, &mut buf[..])?;

        let chunk = parse_chunk(buf.as_slice());

        match chunk {
            Ok(chunk) => draw_to.draw(off.x, off.z, &chunk),
            Err(DrawError::MissingHeightMap) => {} // skip this chunk.
            Err(e) => return Err(e),
        };
    }

    Ok(())
}

pub fn parse_chunk(data: &[u8]) -> DrawResult<Chunk> {
    let meta = super::ChunkMeta::new(data)?;

    let buf = &data[5..];
    let decoder = match meta.compression_scheme {
        CompressionScheme::Zlib => ZlibDecoder::new(buf),
        _ => panic!("unknown compression scheme (gzip?)"),
    };

    let mut parser = nbt::Parser::new(decoder);

    nbt::find_compound(&mut parser, Some("Level"))?;

    let mut sections = Vec::new();
    let mut heightmap: Option<Vec<u16>> = None;
    let mut biomes = None;

    loop {
        match parser.next()? {
            Value::List(Some(ref name), _, n) if name == "Sections" => {
                for _ in 0..n {
                    if let Some(section) = process_section(&mut parser)? {
                        sections.push(section);
                    }
                }
            }
            Value::IntArray(Some(ref name), b) if name == "Biomes" => {
                biomes = Some(b);
            }
            Value::Compound(Some(name)) if name == "Heightmaps" => {
                heightmap = process_heightmap(&mut parser)?;
            }
            Value::Compound(_) => {
                // don't enter another compound.
                nbt::skip_compound(&mut parser)?;
            }
            Value::CompoundEnd => {
                if heightmap == None {
                    return Err(DrawError::MissingHeightMap);
                }

                return Ok(Chunk::new(heightmap.unwrap(), sections, biomes));
            }
            _ => {}
        }
    }
}

fn process_palette<R: Read>(parser: &mut nbt::Parser<R>, size: usize) -> DrawResult<Vec<String>> {
    let mut names = Vec::<String>::new();

    for _ in 0..size {
        let v = parser.next().map_err(|_| Error::InsufficientData)?; // start compound

        match v {
            nbt::Value::Compound(None) => {}
            _ => return Err(DrawError::InvalidPalette),
        }

        // Find name, skipping the rest of the stuff.
        loop {
            let v = parser.next()?;

            match v {
                Value::Compound(_) => {
                    nbt::skip_compound(parser)?;
                } // if we find a nested compound, skip it.
                Value::String(Some(name), str) if name == "Name" => {
                    names.push(str);
                    break;
                }
                Value::CompoundEnd => return Err(DrawError::InvalidPalette), // didn't find name.
                Value::List(_, _, _) => return Err(DrawError::InvalidPalette),
                _ => {}
            }
        }

        // Loop until we find the End.
        nbt::skip_compound(parser)?;
    }

    Ok(names)
}

fn process_section<R: Read>(mut parser: &mut nbt::Parser<R>) -> DrawResult<Option<Section>> {
    nbt::find_compound(&mut parser, None)?;
    let mut states = Vec::<i64>::new();
    let mut palette = Vec::<String>::new();
    let mut y = None;

    loop {
        let value = parser.next()?;

        match value {
            Value::List(Some(ref name), _, n) if name == "Palette" => {
                palette = process_palette(&mut parser, n as usize)?;
            }
            Value::LongArray(Some(ref name), s) if name == "BlockStates" => {
                states = s;
            }
            Value::Byte(Some(ref name), b) if name == "Y" => {
                y = Some(b);
            }
            Value::Compound(_) => {
                // don't enter another compound.
                nbt::skip_compound(&mut parser)?;
            }
            Value::CompoundEnd => {
                // Sections might be empty if there are no blocks
                // Also see sections with y = -1 with no data.
                return Ok(None);
            }
            _ => {}
        }

        // Do we have a palette and blockstate?
        if states.len() > 0 && palette.len() > 0 && y.is_some() {
            let expanded = bits::expand_blockstates(&states[..], palette.len());
            nbt::skip_compound(&mut parser)?;
            return Ok(Some(Section {
                states: expanded,
                palette,
                y: y.unwrap() as u8, // know y.is_some() above.
            }));
        }
    }
}

fn process_heightmap<R: Read>(mut parser: &mut nbt::Parser<R>) -> DrawResult<Option<Vec<u16>>> {
    loop {
        match parser.next()? {
            Value::LongArray(Some(ref name), data) if name == "WORLD_SURFACE" => {
                nbt::skip_compound(&mut parser)?;
                return Ok(Some(bits::expand_heightmap(data.as_slice())));
            }
            Value::Compound(_) => {
                // don't enter another compound.
                nbt::skip_compound(&mut parser)?;
            }
            Value::CompoundEnd => {
                // No heightmap found, it happens.
                return Ok(None);
            }
            _ => {}
        }
    }
}