mc_schem 1.1.2

A library to read, create, modify and write various Minecraft schematic 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
mc_schem is a rust library to generate, load, manipulate and save minecraft schematic files.
Copyright (C) 2024  joseph

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use strum::{Display, EnumString};
use std::collections::{BTreeMap, HashMap};
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use fastnbt::Value;

/// `Block` is a type of block with namespace and properties(aka attributes) in MC.
#[derive(Debug, Clone, Eq)]
pub struct Block {
    /// Namespace of the block. All vanilla blocks have namespace `minecraft`
    pub namespace: String,
    /// ID of the block. for example: `stone`
    pub id: String,
    /// Properties of the block. The key is property names, and value is property value
    pub attributes: BTreeMap<String, String>,

}

/// Error of parsing block id in string
#[repr(u8)]
#[derive(Debug,EnumString,Display,PartialEq,Copy,Clone)]
pub enum BlockIdParseError {
    TooManyColons = 0,
    TooManyLeftBrackets = 1,
    TooManyRightBrackets = 2,
    MissingBlockId = 3,
    BracketsNotInPairs = 4,
    BracketInWrongPosition = 5,
    ColonsInWrongPosition = 6,
    MissingEqualInAttributes = 7,
    TooManyEqualsInAttributes = 8,
    MissingAttributeName = 9,
    MissingAttributeValue = 10,
    ExtraStringAfterRightBracket = 11,
    InvalidCharacter = 12,
}

fn check_blockid_characters(blkid:&str) ->Result<(),BlockIdParseError> {
    for ch in blkid.chars() {
        if ch>='a' && ch <='z' {
            continue;
        }
        if ch >= '0' && ch <= '9' {
            continue;
        }

        let other_valid_chars=[',','=','[',']',':','_'];
        if other_valid_chars.contains(&ch) {
            continue;
        }
        //panic!("Invalid char {}", ch);
        return Err(BlockIdParseError::InvalidCharacter);
    }
    return Ok(());
}
fn check_for_bracket(full_id: &str) -> Result<Option<(usize, usize)>, BlockIdParseError> {
    if full_id.find('[') != full_id.rfind('[') {
        return Err(BlockIdParseError::TooManyLeftBrackets);
    }
    if full_id.find(']') != full_id.rfind(']') {
        return Err(BlockIdParseError::TooManyRightBrackets);
    }

    let left_loc = full_id.find('[');
    let right_loc = full_id.find(']');

    if left_loc.is_some() != right_loc.is_some() {
        return Err(BlockIdParseError::BracketsNotInPairs);
    }

    return if left_loc.is_some() {
        let left_loc = left_loc.unwrap();
        let right_loc = right_loc.unwrap();

        if left_loc >= right_loc {
            return Err(BlockIdParseError::BracketInWrongPosition);
        }

        Ok(Some((left_loc, right_loc)))
    } else {
        Ok(None)
    };
}

fn check_attributes_segment(att_seg: &str) -> Result<(), BlockIdParseError> {
    if att_seg.is_empty() {
        return Ok(());
    }

    for seg in att_seg.split(',') {
        let eq_loc = seg.find('=');
        match eq_loc {
            None => return Err(BlockIdParseError::MissingEqualInAttributes),
            Some(eq_loc) => {
                if eq_loc != seg.rfind('=').unwrap() {
                    return Err(BlockIdParseError::TooManyEqualsInAttributes);
                }

                if eq_loc <= 0 {
                    return Err(BlockIdParseError::MissingAttributeName);
                }
                if eq_loc + 1 >= seg.len() {
                    return Err(BlockIdParseError::MissingAttributeValue);
                }

                continue;
            }
        }
    }
    return Ok(());
}

/// Split a string id into 3 segments: namespace, id and property list.
pub fn parse_block_id(full_id: &str) -> Result<(&str, &str, &str), BlockIdParseError> {
    match check_blockid_characters(full_id) {
        Err(err) => return Err(err),
        _ => {},
    }

    let mut namespace = "";
    let colon_loc_opt = full_id.find(':');
    match colon_loc_opt {
        Some(colon_loc) => if colon_loc != full_id.rfind(':').unwrap()
        { return Err(BlockIdParseError::TooManyColons); } else {
            namespace = &full_id[0..colon_loc];
        }
        None => {}
    }

    let id;
    let id_begin_idx = match colon_loc_opt {
        Some(col_loc) => col_loc + 1,
        None => 0,
    };


    let bracket_locs_opt = check_for_bracket(full_id);
    let bracket_locs: (usize, usize);
    match bracket_locs_opt {
        Err(e) => return Err(e),
        Ok(locs_opt) => {
            match locs_opt {
                None => {
                    id = &full_id[id_begin_idx..full_id.len()];
                    if id.is_empty() {return Err(BlockIdParseError::MissingBlockId);}
                    return Ok((namespace, id, ""));
                }
                Some(locs) => {
                    if locs.0 <= id_begin_idx {
                        return Err(BlockIdParseError::ColonsInWrongPosition);
                    }
                    bracket_locs = locs;
                    id=&full_id[id_begin_idx..bracket_locs.0];
                    if id.is_empty() {return Err(BlockIdParseError::MissingBlockId);}
                }
            }
        }
    }

    if bracket_locs.1+1 <full_id.len() {
        return Err(BlockIdParseError::ExtraStringAfterRightBracket);
    }

    let attributes = &full_id[(bracket_locs.0 + 1)..bracket_locs.1];

    let check_res = check_attributes_segment(attributes);
    match check_res {
        Err(e) => return Err(e),
        _ => {}
    }

    return Ok((namespace, id, attributes));
}

/// Parse property list of a string id.
pub fn parse_attributes_segment(att_seg: &str) -> Result<Vec<(&str, &str)>, BlockIdParseError> {
    let mut result: Vec<(&str, &str)> = Vec::new();

    if att_seg.is_empty() {
        return Ok(result);
    }

    for seg in att_seg.split(',') {
        let eq_loc = seg.find('=');
        match eq_loc {
            None => return Err(BlockIdParseError::MissingEqualInAttributes),
            Some(eq_loc) => {
                if eq_loc != seg.rfind('=').unwrap() {
                    return Err(BlockIdParseError::TooManyEqualsInAttributes);
                }

                if eq_loc <= 0 {
                    return Err(BlockIdParseError::MissingAttributeName);
                }
                if eq_loc + 1 >= seg.len() {
                    return Err(BlockIdParseError::MissingAttributeValue);
                }

                result.push((&seg[0..eq_loc], &seg[(eq_loc + 1)..seg.len()]));
            }
        }
    }
    return Ok(result);
}

impl PartialEq<Self> for Block {
    fn eq(&self, other: &Self) -> bool {
        if self.namespace != other.namespace {
            return false;
        }
        if self.id != other.id {
            return false;
        }

        if self.attributes.len() != other.attributes.len() {
            return false;
        }

        for att in &self.attributes {
            let find_res = other.attributes.get(att.0);
            match find_res {
                None => return false,
                Some(vaule) => {
                    if vaule == att.1 { continue; } else { return false; }
                }
            }
        }

        return true;
    }
}

#[allow(dead_code)]
impl Block {
    /// Returns `minecraft:air`
    pub fn new() -> Block {
        return Block {
            namespace: String::from("minecraft"),
            id: String::from("air"),
            attributes: BTreeMap::new(),
        };
    }
    /// Parse a block from `blkid`
    pub fn from_id(blkid: &str) -> Result<Block, BlockIdParseError> {
        let parse_res = parse_block_id(blkid);
        let segmented: (&str, &str, &str);
        match parse_res {
            Err(e) => return Err(e),
            Ok(segs) => segmented = segs,
        }

        let attri_res = parse_attributes_segment(segmented.2);
        let attri_list: Vec<(&str, &str)>;
        match attri_res {
            Err(e) => return Err(e),
            Ok(attri_l) => attri_list = attri_l,
        }

        let mut blk: Block = Block::new();
        blk.namespace = segmented.0.to_string();
        blk.id = segmented.1.to_string();

        for attri in attri_list {
            blk.attributes.insert(String::from(attri.0), String::from(attri.1));
        }

        return Ok(blk);
    }
    /// Returns property list in string
    pub fn attribute_str(&self) -> String {
        let mut result: String = String::new();
        for (k, v) in &self.attributes {
            result.push_str(k.as_str());
            result.push('=');
            result.push_str(v.as_str());
            result.push(',');
        }

        result.pop();
        return result;
    }
    /// Format property list
    pub fn fmt_attributes(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for (idx, (k, v)) in self.attributes.iter().enumerate() {
            write!(f, "{}={}", k, v)?;
            if idx < self.attributes.len() - 1 {
                write!(f, ",")?;
            }
        }

        return Ok(());
    }

    /// Returns the full id
    pub fn full_id(&self) -> String {
        // return if self.attributes.is_empty() {
        //     format!("{}:{}", self.namespace.as_str(), self.id.as_str())
        // } else {
        //     let attrib_str = self.attribute_str();
        //     format!("{}:{}[{}]", self.namespace.as_str(), self.id.as_str(), attrib_str)
        // };
        return self.to_string();
    }
    /// Returns true if the block is `minecraft:structure_void`
    pub fn is_structure_void(&self) -> bool {
        if self.namespace != "minecraft" {
            return false;
        }
        if self.id != "structure_void" {
            return false;
        }
        if !self.attributes.is_empty() {
            return false;
        }

        return true;
    }
    /// Returns true if the block is `minecraft:air`
    pub fn is_air(&self) -> bool {
        if self.namespace != "minecraft" {
            return false;
        }
        if self.id != "air" {
            return false;
        }
        if !self.attributes.is_empty() {
            return false;
        }
        return true;
    }
    /// Returns `minecraft:air`
    pub fn air() -> Block {
        return Block {
            namespace: String::from("minecraft"),
            id: String::from("air"),
            attributes: BTreeMap::new(),
        }
    }
    /// Returns a block with empty namespace, id and properties
    pub fn empty_block() -> Block {
        return Block {
            namespace: "".to_string(),
            id: "".to_string(),
            attributes: BTreeMap::new(),
        }
    }

    /// Returns true if the block is `minecraft:structure_void`
    pub fn structure_void() -> Block {
        return Block {
            namespace: String::from("minecraft"),
            id: String::from("structure_void"),
            attributes: BTreeMap::new(),
        }
    }
    /// Convert the block info nbt format
    pub fn to_nbt(&self) -> HashMap<String, Value> {
        let mut nbt: HashMap<String, Value> = HashMap::new();
        nbt.insert(String::from("Name"),
                   Value::String(format!("{}:{}", self.namespace, self.id)));
        if !self.attributes.is_empty() {
            let mut props: HashMap<String, Value> = HashMap::new();
            for (key, val) in &self.attributes {
                props.insert(key.clone(), Value::String(val.clone()));
            }
            nbt.insert(String::from("Properties"), Value::Compound(props));
        }

        return nbt;
    }

    ///Set property of a block
    pub fn set_property<V: ?Sized>(&mut self, key: &str, value: &V)
        where for<'a> &'a V: Display {
        self.attributes.insert(key.to_string(), value.to_string());
    }

    /// Returns true if `self` can be made by adding 1 or more properties to `blk_less_attr`
    pub fn is_inherited_from(&self, blk_less_attr: &Block) -> bool {
        if self.attributes.len() < blk_less_attr.attributes.len() {
            return false;
        }
        if self.id != blk_less_attr.id {
            return false;
        }

        for (key, val) in &blk_less_attr.attributes {
            if let Some(val_self) = self.attributes.get(key) {
                if val_self != val {
                    return false;
                }
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
}

impl Hash for Block {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.namespace.hash(state);
        self.id.hash(state);
        for (key, val) in &self.attributes {
            key.hash(state);
            val.hash(state);
        }
    }
}

impl Display for Block {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if !self.namespace.is_empty() {
            write!(f, "{}:", self.namespace)?;
        }

        write!(f, "{}", self.id)?;

        if !self.attributes.is_empty() {
            write!(f, "[")?;
            self.fmt_attributes(f)?;
            write!(f, "]")?;
        }

        return Ok(());
        //return write!(f, "{}", &self.full_id());
    }
}

// impl<T> Borrow<T> for Block
//     where T: ?Sized {
//     fn borrow(&self) -> &T
//     {
//         return self;
//     }
// }

/// Enumerate common blocks
#[repr(u16)]
#[derive(Debug, Display, Clone, Copy)]
#[allow(dead_code)]
pub enum CommonBlock {
    Air = 0,
    StructureVoid = 1,
}


impl CommonBlock {
    /// Convert `CommonBlock` to `Block`
    pub fn to_block(&self) -> Block {
        return match self {
            CommonBlock::Air => Block::air(),
            CommonBlock::StructureVoid => Block::structure_void(),
        }
    }
}