Spaces:
Sleeping
Sleeping
Delete nbt.rs
Browse files
nbt.rs
DELETED
|
@@ -1,1188 +0,0 @@
|
|
| 1 |
-
//! Разбор .litematic: gzip → NBT → группы позиций.
|
| 2 |
-
//!
|
| 3 |
-
//! Результат — `Groups`: (название блока, SNBT tile entity или "") → готовые ячейки
|
| 4 |
-
//! позиций по 28 байт. Ячейки пишутся прямо в горячем цикле (без промежуточных
|
| 5 |
-
//! списков координат и без форматирования строк). Массивы NBT не копируются:
|
| 6 |
-
//! `BlockStates` читается прямо из распакованного буфера.
|
| 7 |
-
|
| 8 |
-
use std::collections::btree_map::Entry;
|
| 9 |
-
use std::collections::BTreeMap;
|
| 10 |
-
use std::fmt::{self, Write as _};
|
| 11 |
-
use std::io::Read;
|
| 12 |
-
use std::sync::atomic::{AtomicBool, Ordering};
|
| 13 |
-
|
| 14 |
-
use crate::encoder::{self, Groups};
|
| 15 |
-
|
| 16 |
-
pub type Pos = (i32, i32, i32);
|
| 17 |
-
/// Сдвиг (x, y, z), который прибавляется ко всем позициям.
|
| 18 |
-
pub type Offset = [i32; 3];
|
| 19 |
-
|
| 20 |
-
const MAX_DEPTH: usize = 64;
|
| 21 |
-
const AIR: [&str; 3] = ["minecraft:air", "minecraft:cave_air", "minecraft:void_air"];
|
| 22 |
-
|
| 23 |
-
#[derive(Debug, Clone)]
|
| 24 |
-
pub struct Limits {
|
| 25 |
-
/// Максимум байт после распаковки gzip.
|
| 26 |
-
pub max_decompressed: usize,
|
| 27 |
-
/// Максимум непустых (не воздух) блоков.
|
| 28 |
-
pub max_blocks: usize,
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
impl Default for Limits {
|
| 32 |
-
fn default() -> Self {
|
| 33 |
-
Limits {
|
| 34 |
-
max_decompressed: 64 * 1024 * 1024,
|
| 35 |
-
max_blocks: 500_000,
|
| 36 |
-
}
|
| 37 |
-
}
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
#[derive(Debug, Clone, PartialEq, Eq)]
|
| 41 |
-
pub enum NbtError {
|
| 42 |
-
Gzip(String),
|
| 43 |
-
TooLarge(usize),
|
| 44 |
-
Malformed(String),
|
| 45 |
-
NotLitematic(String),
|
| 46 |
-
TooManyBlocks(usize),
|
| 47 |
-
Coord(String),
|
| 48 |
-
Cancelled,
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
impl fmt::Display for NbtError {
|
| 52 |
-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 53 |
-
match self {
|
| 54 |
-
NbtError::Gzip(m) => write!(f, "не удалось распаковать gzip: {m}"),
|
| 55 |
-
NbtError::TooLarge(n) => write!(f, "после распаковки файл больше {n} байт"),
|
| 56 |
-
NbtError::Malformed(m) => write!(f, "повреждённый файл: {m}"),
|
| 57 |
-
NbtError::NotLitematic(m) => write!(f, "это не .litematic: {m}"),
|
| 58 |
-
NbtError::TooManyBlocks(n) => {
|
| 59 |
-
write!(f, "схематика слишком большая: больше {n} непустых блоков")
|
| 60 |
-
}
|
| 61 |
-
NbtError::Coord(m) => write!(f, "{m}"),
|
| 62 |
-
NbtError::Cancelled => write!(f, "обработка отменена: не уложились в срок"),
|
| 63 |
-
}
|
| 64 |
-
}
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
impl std::error::Error for NbtError {}
|
| 68 |
-
|
| 69 |
-
fn malformed(msg: impl Into<String>) -> NbtError {
|
| 70 |
-
NbtError::Malformed(msg.into())
|
| 71 |
-
}
|
| 72 |
-
|
| 73 |
-
// ---------------------------------------------------------------- gzip
|
| 74 |
-
|
| 75 |
-
/// Распаковывает gzip с ограничением размера результата.
|
| 76 |
-
pub fn gunzip(data: &[u8], limit: usize) -> Result<Vec<u8>, NbtError> {
|
| 77 |
-
if data.len() < 2 || data[0] != 0x1f || data[1] != 0x8b {
|
| 78 |
-
return Err(NbtError::NotLitematic(
|
| 79 |
-
"ожидается gzip-сжатый NBT (файл не начинается с gzip-заголовка)".to_string(),
|
| 80 |
-
));
|
| 81 |
-
}
|
| 82 |
-
let decoder = flate2::read::GzDecoder::new(data);
|
| 83 |
-
let mut out = Vec::new();
|
| 84 |
-
decoder
|
| 85 |
-
.take(limit as u64 + 1)
|
| 86 |
-
.read_to_end(&mut out)
|
| 87 |
-
.map_err(|e| NbtError::Gzip(e.to_string()))?;
|
| 88 |
-
if out.len() > limit {
|
| 89 |
-
return Err(NbtError::TooLarge(limit));
|
| 90 |
-
}
|
| 91 |
-
Ok(out)
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
// ---------------------------------------------------------------- NBT
|
| 95 |
-
|
| 96 |
-
/// Массивы хранятся как сырые байты (big-endian) — без копирования.
|
| 97 |
-
#[allow(dead_code)]
|
| 98 |
-
#[derive(Debug, Clone, PartialEq)]
|
| 99 |
-
pub enum Tag<'a> {
|
| 100 |
-
Byte(i8),
|
| 101 |
-
Short(i16),
|
| 102 |
-
Int(i32),
|
| 103 |
-
Long(i64),
|
| 104 |
-
Float(f32),
|
| 105 |
-
Double(f64),
|
| 106 |
-
ByteArray(&'a [u8]),
|
| 107 |
-
String(String),
|
| 108 |
-
List(Vec<Tag<'a>>),
|
| 109 |
-
Compound(BTreeMap<String, Tag<'a>>),
|
| 110 |
-
IntArray(&'a [u8]),
|
| 111 |
-
LongArray(&'a [u8]),
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
impl<'a> Tag<'a> {
|
| 115 |
-
fn get(&self, key: &str) -> Option<&Tag<'a>> {
|
| 116 |
-
if let Tag::Compound(m) = self {
|
| 117 |
-
m.get(key)
|
| 118 |
-
} else {
|
| 119 |
-
None
|
| 120 |
-
}
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
fn as_int(&self) -> Option<i32> {
|
| 124 |
-
if let Tag::Int(v) = self {
|
| 125 |
-
Some(*v)
|
| 126 |
-
} else {
|
| 127 |
-
None
|
| 128 |
-
}
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
fn as_str(&self) -> Option<&str> {
|
| 132 |
-
if let Tag::String(s) = self {
|
| 133 |
-
Some(s.as_str())
|
| 134 |
-
} else {
|
| 135 |
-
None
|
| 136 |
-
}
|
| 137 |
-
}
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
struct Reader<'a> {
|
| 141 |
-
buf: &'a [u8],
|
| 142 |
-
pos: usize,
|
| 143 |
-
}
|
| 144 |
-
|
| 145 |
-
impl<'a> Reader<'a> {
|
| 146 |
-
fn new(buf: &'a [u8]) -> Self {
|
| 147 |
-
Reader { buf, pos: 0 }
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
fn remaining(&self) -> usize {
|
| 151 |
-
self.buf.len() - self.pos
|
| 152 |
-
}
|
| 153 |
-
|
| 154 |
-
fn take(&mut self, n: usize) -> Result<&'a [u8], NbtError> {
|
| 155 |
-
let end = self
|
| 156 |
-
.pos
|
| 157 |
-
.checked_add(n)
|
| 158 |
-
.filter(|&e| e <= self.buf.len())
|
| 159 |
-
.ok_or_else(|| malformed("неожиданный конец данных"))?;
|
| 160 |
-
let slice = &self.buf[self.pos..end];
|
| 161 |
-
self.pos = end;
|
| 162 |
-
Ok(slice)
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
fn u8(&mut self) -> Result<u8, NbtError> {
|
| 166 |
-
Ok(self.take(1)?[0])
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
fn u16(&mut self) -> Result<u16, NbtError> {
|
| 170 |
-
Ok(u16::from_be_bytes(self.take(2)?.try_into().unwrap()))
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
fn i16(&mut self) -> Result<i16, NbtError> {
|
| 174 |
-
Ok(i16::from_be_bytes(self.take(2)?.try_into().unwrap()))
|
| 175 |
-
}
|
| 176 |
-
|
| 177 |
-
fn i32(&mut self) -> Result<i32, NbtError> {
|
| 178 |
-
Ok(i32::from_be_bytes(self.take(4)?.try_into().unwrap()))
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
fn i64(&mut self) -> Result<i64, NbtError> {
|
| 182 |
-
Ok(i64::from_be_bytes(self.take(8)?.try_into().unwrap()))
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
-
fn len(&mut self) -> Result<usize, NbtError> {
|
| 186 |
-
let n = self.i32()?;
|
| 187 |
-
usize::try_from(n).map_err(|_| malformed("отрицательная длина"))
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
fn string(&mut self) -> Result<String, NbtError> {
|
| 191 |
-
let n = self.u16()? as usize;
|
| 192 |
-
let bytes = self.take(n)?;
|
| 193 |
-
Ok(String::from_utf8_lossy(bytes).into_owned())
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
fn payload(&mut self, id: u8, depth: usize) -> Result<Tag<'a>, NbtError> {
|
| 197 |
-
if depth > MAX_DEPTH {
|
| 198 |
-
return Err(malformed("слишком глубокая вложенность"));
|
| 199 |
-
}
|
| 200 |
-
Ok(match id {
|
| 201 |
-
1 => Tag::Byte(self.u8()? as i8),
|
| 202 |
-
2 => Tag::Short(self.i16()?),
|
| 203 |
-
3 => Tag::Int(self.i32()?),
|
| 204 |
-
4 => Tag::Long(self.i64()?),
|
| 205 |
-
5 => Tag::Float(f32::from_bits(self.i32()? as u32)),
|
| 206 |
-
6 => Tag::Double(f64::from_bits(self.i64()? as u64)),
|
| 207 |
-
7 => {
|
| 208 |
-
let n = self.len()?;
|
| 209 |
-
Tag::ByteArray(self.take(n)?)
|
| 210 |
-
}
|
| 211 |
-
8 => Tag::String(self.string()?),
|
| 212 |
-
9 => {
|
| 213 |
-
let elem = self.u8()?;
|
| 214 |
-
let n = self.len()?;
|
| 215 |
-
if n > 0 && elem == 0 {
|
| 216 |
-
return Err(malformed("список с типом элементов End"));
|
| 217 |
-
}
|
| 218 |
-
if n > self.remaining() {
|
| 219 |
-
return Err(malformed("длина списка больше оставшихся данных"));
|
| 220 |
-
}
|
| 221 |
-
let mut items = Vec::with_capacity(n);
|
| 222 |
-
for _ in 0..n {
|
| 223 |
-
items.push(self.payload(elem, depth + 1)?);
|
| 224 |
-
}
|
| 225 |
-
Tag::List(items)
|
| 226 |
-
}
|
| 227 |
-
10 => {
|
| 228 |
-
let mut map = BTreeMap::new();
|
| 229 |
-
loop {
|
| 230 |
-
let t = self.u8()?;
|
| 231 |
-
if t == 0 {
|
| 232 |
-
break;
|
| 233 |
-
}
|
| 234 |
-
let name = self.string()?;
|
| 235 |
-
let value = self.payload(t, depth + 1)?;
|
| 236 |
-
map.insert(name, value);
|
| 237 |
-
}
|
| 238 |
-
Tag::Compound(map)
|
| 239 |
-
}
|
| 240 |
-
11 => {
|
| 241 |
-
let n = self.len()?;
|
| 242 |
-
let size = n.checked_mul(4).ok_or_else(|| malformed("длина массива"))?;
|
| 243 |
-
Tag::IntArray(self.take(size)?)
|
| 244 |
-
}
|
| 245 |
-
12 => {
|
| 246 |
-
let n = self.len()?;
|
| 247 |
-
let size = n.checked_mul(8).ok_or_else(|| malformed("длина массива"))?;
|
| 248 |
-
Tag::LongArray(self.take(size)?)
|
| 249 |
-
}
|
| 250 |
-
other => return Err(malformed(format!("неизвестный тип тега {other}"))),
|
| 251 |
-
})
|
| 252 |
-
}
|
| 253 |
-
}
|
| 254 |
-
|
| 255 |
-
/// Разбирает несжатый NBT. Корень обязан быть compound.
|
| 256 |
-
pub fn parse_nbt(data: &[u8]) -> Result<Tag<'_>, NbtError> {
|
| 257 |
-
let mut r = Reader::new(data);
|
| 258 |
-
let id = r.u8()?;
|
| 259 |
-
if id != 10 {
|
| 260 |
-
return Err(malformed("корневой тег не compound"));
|
| 261 |
-
}
|
| 262 |
-
let _root_name = r.string()?;
|
| 263 |
-
r.payload(10, 0)
|
| 264 |
-
}
|
| 265 |
-
|
| 266 |
-
// ---------------------------------------------------------------- SNBT
|
| 267 |
-
|
| 268 |
-
fn write_quoted(s: &str, out: &mut String) {
|
| 269 |
-
out.push('"');
|
| 270 |
-
for c in s.chars() {
|
| 271 |
-
match c {
|
| 272 |
-
'"' => out.push_str("\\\""),
|
| 273 |
-
'\\' => out.push_str("\\\\"),
|
| 274 |
-
_ => out.push(c),
|
| 275 |
-
}
|
| 276 |
-
}
|
| 277 |
-
out.push('"');
|
| 278 |
-
}
|
| 279 |
-
|
| 280 |
-
fn write_key(k: &str, out: &mut String) {
|
| 281 |
-
let plain = !k.is_empty()
|
| 282 |
-
&& k.chars()
|
| 283 |
-
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'));
|
| 284 |
-
if plain {
|
| 285 |
-
out.push_str(k);
|
| 286 |
-
} else {
|
| 287 |
-
write_quoted(k, out);
|
| 288 |
-
}
|
| 289 |
-
}
|
| 290 |
-
|
| 291 |
-
fn write_compound(map: &BTreeMap<String, Tag<'_>>, skip: &[&str], out: &mut String) {
|
| 292 |
-
out.push('{');
|
| 293 |
-
let mut first = true;
|
| 294 |
-
for (k, v) in map {
|
| 295 |
-
if skip.iter().any(|s| *s == k.as_str()) {
|
| 296 |
-
continue;
|
| 297 |
-
}
|
| 298 |
-
if !first {
|
| 299 |
-
out.push(',');
|
| 300 |
-
}
|
| 301 |
-
first = false;
|
| 302 |
-
write_key(k, out);
|
| 303 |
-
out.push(':');
|
| 304 |
-
write_snbt(v, out);
|
| 305 |
-
}
|
| 306 |
-
out.push('}');
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
fn write_snbt(tag: &Tag<'_>, out: &mut String) {
|
| 310 |
-
match tag {
|
| 311 |
-
Tag::Byte(v) => {
|
| 312 |
-
let _ = write!(out, "{v}b");
|
| 313 |
-
}
|
| 314 |
-
Tag::Short(v) => {
|
| 315 |
-
let _ = write!(out, "{v}s");
|
| 316 |
-
}
|
| 317 |
-
Tag::Int(v) => {
|
| 318 |
-
let _ = write!(out, "{v}");
|
| 319 |
-
}
|
| 320 |
-
Tag::Long(v) => {
|
| 321 |
-
let _ = write!(out, "{v}L");
|
| 322 |
-
}
|
| 323 |
-
Tag::Float(v) => {
|
| 324 |
-
let _ = write!(out, "{v}f");
|
| 325 |
-
}
|
| 326 |
-
Tag::Double(v) => {
|
| 327 |
-
let _ = write!(out, "{v}d");
|
| 328 |
-
}
|
| 329 |
-
Tag::String(s) => write_quoted(s, out),
|
| 330 |
-
Tag::ByteArray(b) => {
|
| 331 |
-
out.push_str("[B;");
|
| 332 |
-
for (i, x) in b.iter().enumerate() {
|
| 333 |
-
if i > 0 {
|
| 334 |
-
out.push(',');
|
| 335 |
-
}
|
| 336 |
-
let _ = write!(out, "{}b", *x as i8);
|
| 337 |
-
}
|
| 338 |
-
out.push(']');
|
| 339 |
-
}
|
| 340 |
-
Tag::IntArray(b) => {
|
| 341 |
-
out.push_str("[I;");
|
| 342 |
-
for (i, c) in b.chunks_exact(4).enumerate() {
|
| 343 |
-
if i > 0 {
|
| 344 |
-
out.push(',');
|
| 345 |
-
}
|
| 346 |
-
let _ = write!(out, "{}", i32::from_be_bytes(c.try_into().unwrap()));
|
| 347 |
-
}
|
| 348 |
-
out.push(']');
|
| 349 |
-
}
|
| 350 |
-
Tag::LongArray(b) => {
|
| 351 |
-
out.push_str("[L;");
|
| 352 |
-
for (i, c) in b.chunks_exact(8).enumerate() {
|
| 353 |
-
if i > 0 {
|
| 354 |
-
out.push(',');
|
| 355 |
-
}
|
| 356 |
-
let _ = write!(out, "{}L", i64::from_be_bytes(c.try_into().unwrap()));
|
| 357 |
-
}
|
| 358 |
-
out.push(']');
|
| 359 |
-
}
|
| 360 |
-
Tag::List(items) => {
|
| 361 |
-
out.push('[');
|
| 362 |
-
for (i, t) in items.iter().enumerate() {
|
| 363 |
-
if i > 0 {
|
| 364 |
-
out.push(',');
|
| 365 |
-
}
|
| 366 |
-
write_snbt(t, out);
|
| 367 |
-
}
|
| 368 |
-
out.push(']');
|
| 369 |
-
}
|
| 370 |
-
Tag::Compound(m) => write_compound(m, &[], out),
|
| 371 |
-
}
|
| 372 |
-
}
|
| 373 |
-
|
| 374 |
-
/// SNBT compound без ключей из `skip`. Ключи по алфавиту — результат детерминирован.
|
| 375 |
-
pub fn compound_snbt(map: &BTreeMap<String, Tag<'_>>, skip: &[&str]) -> String {
|
| 376 |
-
let mut s = String::new();
|
| 377 |
-
write_compound(map, skip, &mut s);
|
| 378 |
-
s
|
| 379 |
-
}
|
| 380 |
-
|
| 381 |
-
/// NBT compound как JSON-словарь `{ключ: текст}`: значение — обычный текст для строк, SNBT-текст для остального
|
| 382 |
-
/// (числа, списки, вложенные compound; экранирует serde_json). Ключи из `skip` и пустые теги (`{}`, `[]`) пропускаются, порядок — по алфавиту.
|
| 383 |
-
pub fn compound_dict_json(map: &BTreeMap<String, Tag<'_>>, skip: &[&str]) -> String {
|
| 384 |
-
let mut obj = serde_json::Map::new();
|
| 385 |
-
for (k, v) in map {
|
| 386 |
-
if skip.iter().any(|s| *s == k.as_str()) {
|
| 387 |
-
continue;
|
| 388 |
-
}
|
| 389 |
-
let t = match v {
|
| 390 |
-
Tag::String(s) => s.clone(),
|
| 391 |
-
_ => {
|
| 392 |
-
let mut t = String::new();
|
| 393 |
-
write_snbt(v, &mut t);
|
| 394 |
-
// пустые теги (`{}`, `[]`) не храним
|
| 395 |
-
if t == "{}" || t == "[]" {
|
| 396 |
-
continue;
|
| 397 |
-
}
|
| 398 |
-
t
|
| 399 |
-
}
|
| 400 |
-
};
|
| 401 |
-
obj.insert(k.clone(), serde_json::Value::String(t));
|
| 402 |
-
}
|
| 403 |
-
serde_json::Value::Object(obj).to_string()
|
| 404 |
-
}
|
| 405 |
-
|
| 406 |
-
// ---------------------------------------------------------------- litematic
|
| 407 |
-
|
| 408 |
-
/// Gzip → группы позиций со сдвигом `offset`.
|
| 409 |
-
pub fn parse_litematic_gz(
|
| 410 |
-
gz: &[u8],
|
| 411 |
-
limits: &Limits,
|
| 412 |
-
offset: Offset,
|
| 413 |
-
cancel: &AtomicBool,
|
| 414 |
-
) -> Result<Groups, NbtError> {
|
| 415 |
-
let raw = gunzip(gz, limits.max_decompressed)?;
|
| 416 |
-
parse_litematic(&raw, limits.max_blocks, offset, cancel)
|
| 417 |
-
}
|
| 418 |
-
|
| 419 |
-
/// Несжатый NBT → группы «(блок, SNBT) → ячейки позиций».
|
| 420 |
-
/// Воздух пропускается. Регионы обходятся по имени, внутри региона — в порядке
|
| 421 |
-
/// индекса litematica (y, затем z, затем x), поэтому результат детерминирован.
|
| 422 |
-
/// Позиция = `Position` региона + локальная позиция + `offset`.
|
| 423 |
-
/// `cancel` проверяется на каждом слое по y: взведён — вернётся `Cancelled`.
|
| 424 |
-
pub fn parse_litematic(
|
| 425 |
-
data: &[u8],
|
| 426 |
-
max_blocks: usize,
|
| 427 |
-
offset: Offset,
|
| 428 |
-
cancel: &AtomicBool,
|
| 429 |
-
) -> Result<Groups, NbtError> {
|
| 430 |
-
let root = parse_nbt(data)?;
|
| 431 |
-
let regions = match root.get("Regions") {
|
| 432 |
-
Some(Tag::Compound(m)) => m,
|
| 433 |
-
_ => return Err(NbtError::NotLitematic("нет тега Regions".to_string())),
|
| 434 |
-
};
|
| 435 |
-
let mut groups = Groups::new();
|
| 436 |
-
let mut total = 0usize;
|
| 437 |
-
for (name, region) in regions {
|
| 438 |
-
parse_region(name, region, max_blocks, offset, cancel, &mut total, &mut groups)?;
|
| 439 |
-
}
|
| 440 |
-
Ok(groups)
|
| 441 |
-
}
|
| 442 |
-
|
| 443 |
-
fn bad(region: &str, msg: &str) -> NbtError {
|
| 444 |
-
malformed(format!("регион «{region}»: {msg}"))
|
| 445 |
-
}
|
| 446 |
-
|
| 447 |
-
fn read_vec3(region: &Tag<'_>, key: &str, name: &str) -> Result<[i32; 3], NbtError> {
|
| 448 |
-
let tag = region
|
| 449 |
-
.get(key)
|
| 450 |
-
.ok_or_else(|| bad(name, &format!("нет поля {key}")))?;
|
| 451 |
-
let mut out = [0i32; 3];
|
| 452 |
-
for (slot, axis) in out.iter_mut().zip(["x", "y", "z"]) {
|
| 453 |
-
*slot = tag
|
| 454 |
-
.get(axis)
|
| 455 |
-
.and_then(|t| t.as_int())
|
| 456 |
-
.ok_or_else(|| bad(name, &format!("{key}.{axis} не является числом")))?;
|
| 457 |
-
}
|
| 458 |
-
Ok(out)
|
| 459 |
-
}
|
| 460 |
-
|
| 461 |
-
/// Название блока с состоянием, без префикса `minecraft:`:
|
| 462 |
-
/// `oak_stairs[facing=north,half=bottom]`. Другие пространства имён (`create:cogwheel`)
|
| 463 |
-
/// остаются как есть. Для воздуха возвращает `None`.
|
| 464 |
-
fn palette_name(entry: &Tag<'_>, region: &str) -> Result<Option<String>, NbtError> {
|
| 465 |
-
let name = entry
|
| 466 |
-
.get("Name")
|
| 467 |
-
.and_then(|t| t.as_str())
|
| 468 |
-
.ok_or_else(|| bad(region, "в палитре нет Name"))?;
|
| 469 |
-
if AIR.iter().any(|a| *a == name) {
|
| 470 |
-
return Ok(None);
|
| 471 |
-
}
|
| 472 |
-
let mut s = name.strip_prefix("minecraft:").unwrap_or(name).to_string();
|
| 473 |
-
if let Some(Tag::Compound(props)) = entry.get("Properties") {
|
| 474 |
-
let parts: Vec<String> = props
|
| 475 |
-
.iter()
|
| 476 |
-
.filter_map(|(k, v)| v.as_str().map(|v| format!("{k}={v}")))
|
| 477 |
-
.collect();
|
| 478 |
-
if !parts.is_empty() {
|
| 479 |
-
s.push('[');
|
| 480 |
-
s.push_str(&parts.join(","));
|
| 481 |
-
s.push(']');
|
| 482 |
-
}
|
| 483 |
-
}
|
| 484 |
-
Ok(Some(s))
|
| 485 |
-
}
|
| 486 |
-
|
| 487 |
-
/// Tile entities региона: (индекс ячейки в массиве блоков, SNBT без x/y/z),
|
| 488 |
-
/// по возрастанию индекса. Координаты tile entity — локальные в регионе.
|
| 489 |
-
/// Ключи `x`, `y`, `z` и `id` игнорируются.
|
| 490 |
-
/// Записи без координат, вне региона или без данных пропускаются.
|
| 491 |
-
fn tile_entities(region: &Tag<'_>, abs: [u64; 3]) -> Vec<(u64, String)> {
|
| 492 |
-
let list = match region.get("TileEntities") {
|
| 493 |
-
Some(Tag::List(l)) => l,
|
| 494 |
-
_ => return Vec::new(),
|
| 495 |
-
};
|
| 496 |
-
let mut found: BTreeMap<u64, String> = BTreeMap::new();
|
| 497 |
-
for te in list {
|
| 498 |
-
let coord = |k: &str| te.get(k).and_then(|t| t.as_int());
|
| 499 |
-
let (x, y, z) = match (coord("x"), coord("y"), coord("z")) {
|
| 500 |
-
(Some(x), Some(y), Some(z)) if x >= 0 && y >= 0 && z >= 0 => {
|
| 501 |
-
(x as u64, y as u64, z as u64)
|
| 502 |
-
}
|
| 503 |
-
_ => continue,
|
| 504 |
-
};
|
| 505 |
-
if x >= abs[0] || y >= abs[1] || z >= abs[2] {
|
| 506 |
-
continue;
|
| 507 |
-
}
|
| 508 |
-
let snbt = match te {
|
| 509 |
-
Tag::Compound(m) => compound_dict_json(m, &["x", "y", "z", "id"]),
|
| 510 |
-
_ => continue,
|
| 511 |
-
};
|
| 512 |
-
if snbt == "{}" {
|
| 513 |
-
continue;
|
| 514 |
-
}
|
| 515 |
-
found.insert((y * abs[2] + z) * abs[0] + x, snbt);
|
| 516 |
-
}
|
| 517 |
-
found.into_iter().collect()
|
| 518 |
-
}
|
| 519 |
-
|
| 520 |
-
#[inline]
|
| 521 |
-
fn long_at(raw: &[u8], i: usize) -> u64 {
|
| 522 |
-
let b: [u8; 8] = raw[i * 8..i * 8 + 8].try_into().unwrap();
|
| 523 |
-
u64::from_be_bytes(b)
|
| 524 |
-
}
|
| 525 |
-
|
| 526 |
-
/// Достаёт `bits`-битное значение с номером `index` из упакованного массива.
|
| 527 |
-
/// Litematica упаковывает значения подряд, без выравнивания по границе long.
|
| 528 |
-
#[inline]
|
| 529 |
-
fn get_bits(raw: &[u8], index: u64, bits: u64, mask: u64) -> u64 {
|
| 530 |
-
let start = index * bits;
|
| 531 |
-
let first = (start >> 6) as usize;
|
| 532 |
-
let last = ((start + bits - 1) >> 6) as usize;
|
| 533 |
-
let offset = start & 63;
|
| 534 |
-
let low = long_at(raw, first) >> offset;
|
| 535 |
-
if first == last {
|
| 536 |
-
low & mask
|
| 537 |
-
} else {
|
| 538 |
-
(low | (long_at(raw, last) << (64 - offset))) & mask
|
| 539 |
-
}
|
| 540 |
-
}
|
| 541 |
-
|
| 542 |
-
fn merge(groups: &mut Groups, key: (String, String), buf: Vec<u8>) {
|
| 543 |
-
match groups.entry(key) {
|
| 544 |
-
Entry::Vacant(v) => {
|
| 545 |
-
v.insert(buf);
|
| 546 |
-
}
|
| 547 |
-
Entry::Occupied(mut o) => o.get_mut().extend_from_slice(&buf),
|
| 548 |
-
}
|
| 549 |
-
}
|
| 550 |
-
|
| 551 |
-
fn parse_region(
|
| 552 |
-
name: &str,
|
| 553 |
-
region: &Tag<'_>,
|
| 554 |
-
max_blocks: usize,
|
| 555 |
-
offset: Offset,
|
| 556 |
-
cancel: &AtomicBool,
|
| 557 |
-
total: &mut usize,
|
| 558 |
-
groups: &mut Groups,
|
| 559 |
-
) -> Result<(), NbtError> {
|
| 560 |
-
if cancel.load(Ordering::Relaxed) {
|
| 561 |
-
return Err(NbtError::Cancelled);
|
| 562 |
-
}
|
| 563 |
-
let pos = read_vec3(region, "Position", name)?;
|
| 564 |
-
let size = read_vec3(region, "Size", name)?;
|
| 565 |
-
let abs = size.map(|s| u64::from(s.unsigned_abs()));
|
| 566 |
-
let volume = abs[0]
|
| 567 |
-
.checked_mul(abs[1])
|
| 568 |
-
.and_then(|v| v.checked_mul(abs[2]))
|
| 569 |
-
.ok_or_else(|| bad(name, "размер региона слишком велик"))?;
|
| 570 |
-
if volume == 0 {
|
| 571 |
-
return Ok(()); // пустой регион
|
| 572 |
-
}
|
| 573 |
-
|
| 574 |
-
let palette = match region.get("BlockStatePalette") {
|
| 575 |
-
Some(Tag::List(l)) => l,
|
| 576 |
-
_ => return Err(bad(name, "нет BlockStatePalette")),
|
| 577 |
-
};
|
| 578 |
-
let raw: &[u8] = match region.get("BlockStates") {
|
| 579 |
-
Some(Tag::LongArray(a)) => *a,
|
| 580 |
-
_ => return Err(bad(name, "нет BlockStates")),
|
| 581 |
-
};
|
| 582 |
-
if palette.is_empty() {
|
| 583 |
-
return Err(bad(name, "пустая палитра"));
|
| 584 |
-
}
|
| 585 |
-
let names: Vec<Option<String>> = palette
|
| 586 |
-
.iter()
|
| 587 |
-
.map(|e| palette_name(e, name))
|
| 588 |
-
.collect::<Result<_, _>>()?;
|
| 589 |
-
|
| 590 |
-
let bits = u64::from((usize::BITS - (palette.len() - 1).leading_zeros()).max(2));
|
| 591 |
-
let total_bits = volume
|
| 592 |
-
.checked_mul(bits)
|
| 593 |
-
.ok_or_else(|| bad(name, "размер региона слишком велик"))?;
|
| 594 |
-
let needed = total_bits / 64 + u64::from(total_bits % 64 != 0);
|
| 595 |
-
if ((raw.len() / 8) as u64) < needed {
|
| 596 |
-
return Err(bad(name, "BlockStates короче, чем размер региона"));
|
| 597 |
-
}
|
| 598 |
-
let mask = (1u64 << bits) - 1;
|
| 599 |
-
|
| 600 |
-
// Минимальный угол региона со сдвигом. Размер может быть отрицательным.
|
| 601 |
-
let mut min = [0i64; 3];
|
| 602 |
-
for i in 0..3 {
|
| 603 |
-
let back = if size[i] < 0 { i64::from(size[i]) + 1 } else { 0 };
|
| 604 |
-
min[i] = i64::from(pos[i]) + back + i64::from(offset[i]);
|
| 605 |
-
}
|
| 606 |
-
|
| 607 |
-
let te = tile_entities(region, abs);
|
| 608 |
-
let mut ti = 0usize;
|
| 609 |
-
let mut next_te = te.first().map(|t| t.0).unwrap_or(u64::MAX);
|
| 610 |
-
|
| 611 |
-
let (sx, sy, sz) = (abs[0] as i64, abs[1] as i64, abs[2] as i64);
|
| 612 |
-
let mut bufs: Vec<Vec<u8>> = vec![Vec::new(); palette.len()];
|
| 613 |
-
let mut special: BTreeMap<(usize, String), Vec<u8>> = BTreeMap::new();
|
| 614 |
-
let mut index: u64 = 0;
|
| 615 |
-
|
| 616 |
-
for y in 0..sy {
|
| 617 |
-
if cancel.load(Ordering::Relaxed) {
|
| 618 |
-
return Err(NbtError::Cancelled);
|
| 619 |
-
}
|
| 620 |
-
for z in 0..sz {
|
| 621 |
-
for x in 0..sx {
|
| 622 |
-
let id = get_bits(raw, index, bits, mask) as usize;
|
| 623 |
-
let is_te = index == next_te;
|
| 624 |
-
if is_te {
|
| 625 |
-
ti += 1;
|
| 626 |
-
next_te = te.get(ti).map(|t| t.0).unwrap_or(u64::MAX);
|
| 627 |
-
}
|
| 628 |
-
index += 1;
|
| 629 |
-
let slot = names
|
| 630 |
-
.get(id)
|
| 631 |
-
.ok_or_else(|| bad(name, "индекс блока вне палитры"))?;
|
| 632 |
-
if slot.is_none() {
|
| 633 |
-
continue;
|
| 634 |
-
}
|
| 635 |
-
*total += 1;
|
| 636 |
-
if *total > max_blocks {
|
| 637 |
-
return Err(NbtError::TooManyBlocks(max_blocks));
|
| 638 |
-
}
|
| 639 |
-
let wx = i32::try_from(min[0] + x).map_err(|_| bad(name, "координата вне i32"))?;
|
| 640 |
-
let wy = i32::try_from(min[1] + y).map_err(|_| bad(name, "координата вне i32"))?;
|
| 641 |
-
let wz = i32::try_from(min[2] + z).map_err(|_| bad(name, "координата вне i32"))?;
|
| 642 |
-
let target: &mut Vec<u8> = if is_te {
|
| 643 |
-
special.entry((id, te[ti - 1].1.clone())).or_default()
|
| 644 |
-
} else {
|
| 645 |
-
&mut bufs[id]
|
| 646 |
-
};
|
| 647 |
-
encoder::push_position(target, wx, wy, wz)
|
| 648 |
-
.map_err(|e| NbtError::Coord(e.to_string()))?;
|
| 649 |
-
}
|
| 650 |
-
}
|
| 651 |
-
}
|
| 652 |
-
|
| 653 |
-
for (id, buf) in bufs.into_iter().enumerate() {
|
| 654 |
-
if buf.is_empty() {
|
| 655 |
-
continue;
|
| 656 |
-
}
|
| 657 |
-
if let Some(block) = &names[id] {
|
| 658 |
-
merge(groups, (block.clone(), String::new()), buf);
|
| 659 |
-
}
|
| 660 |
-
}
|
| 661 |
-
for ((id, snbt), buf) in special {
|
| 662 |
-
if let Some(block) = &names[id] {
|
| 663 |
-
merge(groups, (block.clone(), snbt), buf);
|
| 664 |
-
}
|
| 665 |
-
}
|
| 666 |
-
Ok(())
|
| 667 |
-
}
|
| 668 |
-
|
| 669 |
-
#[cfg(test)]
|
| 670 |
-
mod tests {
|
| 671 |
-
use super::*;
|
| 672 |
-
use flate2::{write::GzEncoder, Compression};
|
| 673 |
-
use std::io::Write;
|
| 674 |
-
|
| 675 |
-
type Palette = Vec<(&'static str, Vec<(&'static str, &'static str)>)>;
|
| 676 |
-
|
| 677 |
-
// ---- минимальный NBT-писатель для тестов ----
|
| 678 |
-
fn w_str(out: &mut Vec<u8>, s: &str) {
|
| 679 |
-
out.extend((s.len() as u16).to_be_bytes());
|
| 680 |
-
out.extend(s.as_bytes());
|
| 681 |
-
}
|
| 682 |
-
fn named(out: &mut Vec<u8>, id: u8, name: &str) {
|
| 683 |
-
out.push(id);
|
| 684 |
-
w_str(out, name);
|
| 685 |
-
}
|
| 686 |
-
fn int_named(out: &mut Vec<u8>, name: &str, v: i32) {
|
| 687 |
-
named(out, 3, name);
|
| 688 |
-
out.extend(v.to_be_bytes());
|
| 689 |
-
}
|
| 690 |
-
fn vec3(out: &mut Vec<u8>, name: &str, v: [i32; 3]) {
|
| 691 |
-
named(out, 10, name);
|
| 692 |
-
int_named(out, "x", v[0]);
|
| 693 |
-
int_named(out, "y", v[1]);
|
| 694 |
-
int_named(out, "z", v[2]);
|
| 695 |
-
out.push(0);
|
| 696 |
-
}
|
| 697 |
-
fn palette_entry(out: &mut Vec<u8>, name: &str, props: &[(&str, &str)]) {
|
| 698 |
-
named(out, 8, "Name");
|
| 699 |
-
w_str(out, name);
|
| 700 |
-
if !props.is_empty() {
|
| 701 |
-
named(out, 10, "Properties");
|
| 702 |
-
for (k, v) in props {
|
| 703 |
-
named(out, 8, k);
|
| 704 |
-
w_str(out, v);
|
| 705 |
-
}
|
| 706 |
-
out.push(0);
|
| 707 |
-
}
|
| 708 |
-
out.push(0);
|
| 709 |
-
}
|
| 710 |
-
fn region_te(
|
| 711 |
-
out: &mut Vec<u8>,
|
| 712 |
-
name: &str,
|
| 713 |
-
pos: [i32; 3],
|
| 714 |
-
size: [i32; 3],
|
| 715 |
-
palette: &Palette,
|
| 716 |
-
states: &[i64],
|
| 717 |
-
tes: &[(i32, i32, i32, &str)],
|
| 718 |
-
) {
|
| 719 |
-
named(out, 10, name);
|
| 720 |
-
vec3(out, "Position", pos);
|
| 721 |
-
vec3(out, "Size", size);
|
| 722 |
-
named(out, 9, "BlockStatePalette");
|
| 723 |
-
out.push(10);
|
| 724 |
-
out.extend((palette.len() as i32).to_be_bytes());
|
| 725 |
-
for (n, p) in palette {
|
| 726 |
-
palette_entry(out, n, p);
|
| 727 |
-
}
|
| 728 |
-
named(out, 12, "BlockStates");
|
| 729 |
-
out.extend((states.len() as i32).to_be_bytes());
|
| 730 |
-
for s in states {
|
| 731 |
-
out.extend(s.to_be_bytes());
|
| 732 |
-
}
|
| 733 |
-
if !tes.is_empty() {
|
| 734 |
-
named(out, 9, "TileEntities");
|
| 735 |
-
out.push(10);
|
| 736 |
-
out.extend((tes.len() as i32).to_be_bytes());
|
| 737 |
-
for (x, y, z, id) in tes {
|
| 738 |
-
int_named(out, "x", *x);
|
| 739 |
-
int_named(out, "y", *y);
|
| 740 |
-
int_named(out, "z", *z);
|
| 741 |
-
named(out, 8, "Lock");
|
| 742 |
-
w_str(out, id);
|
| 743 |
-
out.push(0);
|
| 744 |
-
}
|
| 745 |
-
}
|
| 746 |
-
out.push(0);
|
| 747 |
-
}
|
| 748 |
-
fn region(
|
| 749 |
-
out: &mut Vec<u8>,
|
| 750 |
-
name: &str,
|
| 751 |
-
pos: [i32; 3],
|
| 752 |
-
size: [i32; 3],
|
| 753 |
-
palette: &Palette,
|
| 754 |
-
states: &[i64],
|
| 755 |
-
) {
|
| 756 |
-
region_te(out, name, pos, size, palette, states, &[]);
|
| 757 |
-
}
|
| 758 |
-
fn litematic(regions: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
|
| 759 |
-
let mut out = Vec::new();
|
| 760 |
-
named(&mut out, 10, "");
|
| 761 |
-
named(&mut out, 10, "Regions");
|
| 762 |
-
regions(&mut out);
|
| 763 |
-
out.push(0); // конец Regions
|
| 764 |
-
out.push(0); // конец корня
|
| 765 |
-
out
|
| 766 |
-
}
|
| 767 |
-
/// Независимая упаковка: бит за битом.
|
| 768 |
-
fn pack(values: &[u64], bits: u64) -> Vec<i64> {
|
| 769 |
-
let total_bits = values.len() as u64 * bits;
|
| 770 |
-
let mut longs = vec![0u64; ((total_bits + 63) / 64) as usize];
|
| 771 |
-
for (i, v) in values.iter().enumerate() {
|
| 772 |
-
for b in 0..bits {
|
| 773 |
-
if (*v >> b) & 1 == 1 {
|
| 774 |
-
let p = i as u64 * bits + b;
|
| 775 |
-
longs[(p / 64) as usize] |= 1u64 << (p % 64);
|
| 776 |
-
}
|
| 777 |
-
}
|
| 778 |
-
}
|
| 779 |
-
longs.into_iter().map(|l| l as i64).collect()
|
| 780 |
-
}
|
| 781 |
-
fn air_stone() -> Palette {
|
| 782 |
-
vec![("minecraft:air", vec![]), ("minecraft:stone", vec![])]
|
| 783 |
-
}
|
| 784 |
-
fn gzip(data: &[u8]) -> Vec<u8> {
|
| 785 |
-
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
| 786 |
-
e.write_all(data).unwrap();
|
| 787 |
-
e.finish().unwrap()
|
| 788 |
-
}
|
| 789 |
-
|
| 790 |
-
// ---- чтение результата ----
|
| 791 |
-
fn dec(c: &[u8]) -> i32 {
|
| 792 |
-
let s = std::str::from_utf8(c).unwrap();
|
| 793 |
-
if let Some(r) = s.strip_prefix('-') {
|
| 794 |
-
-r.parse::<i32>().unwrap()
|
| 795 |
-
} else {
|
| 796 |
-
s.parse().unwrap()
|
| 797 |
-
}
|
| 798 |
-
}
|
| 799 |
-
fn positions(buf: &[u8]) -> Vec<Pos> {
|
| 800 |
-
assert_eq!(buf.len() % encoder::CELL_LEN, 0);
|
| 801 |
-
buf.chunks_exact(encoder::CELL_LEN)
|
| 802 |
-
.map(|c| (dec(&c[5..9]), dec(&c[14..18]), dec(&c[23..27])))
|
| 803 |
-
.collect()
|
| 804 |
-
}
|
| 805 |
-
fn key(name: &str) -> (String, String) {
|
| 806 |
-
(name.to_string(), String::new())
|
| 807 |
-
}
|
| 808 |
-
fn parse(data: &[u8], max: usize) -> Result<Groups, NbtError> {
|
| 809 |
-
parse_litematic(data, max, [0, 0, 0], &AtomicBool::new(false))
|
| 810 |
-
}
|
| 811 |
-
fn parse_off(data: &[u8], offset: Offset) -> Result<Groups, NbtError> {
|
| 812 |
-
parse_litematic(data, 1000, offset, &AtomicBool::new(false))
|
| 813 |
-
}
|
| 814 |
-
|
| 815 |
-
#[test]
|
| 816 |
-
fn simple_region() {
|
| 817 |
-
let data = litematic(|o| region(o, "main", [0, 0, 0], [2, 1, 2], &air_stone(), &pack(&[0, 1, 1, 0], 2)));
|
| 818 |
-
let g = parse(&data, 1000).unwrap();
|
| 819 |
-
assert_eq!(g.len(), 1);
|
| 820 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(1, 0, 0), (0, 0, 1)]);
|
| 821 |
-
}
|
| 822 |
-
|
| 823 |
-
#[test]
|
| 824 |
-
fn cells_have_expected_text() {
|
| 825 |
-
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 826 |
-
let g = parse(&data, 10).unwrap();
|
| 827 |
-
let cell = String::from_utf8(g[&key("stone")].clone()).unwrap();
|
| 828 |
-
assert_eq!(cell, r#"{'x':-005,'y':0010,'z':-001}"#);
|
| 829 |
-
}
|
| 830 |
-
|
| 831 |
-
#[test]
|
| 832 |
-
fn empty_regions_tag() {
|
| 833 |
-
let data = litematic(|_| {});
|
| 834 |
-
assert!(parse(&data, 10).unwrap().is_empty());
|
| 835 |
-
}
|
| 836 |
-
|
| 837 |
-
#[test]
|
| 838 |
-
fn empty_region_zero_size() {
|
| 839 |
-
let data = litematic(|o| region(o, "r", [3, 3, 3], [0, 0, 0], &air_stone(), &[]));
|
| 840 |
-
assert!(parse(&data, 10).unwrap().is_empty());
|
| 841 |
-
}
|
| 842 |
-
|
| 843 |
-
#[test]
|
| 844 |
-
fn region_with_only_air() {
|
| 845 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 2, 2], &air_stone(), &pack(&[0; 8], 2)));
|
| 846 |
-
assert!(parse(&data, 10).unwrap().is_empty());
|
| 847 |
-
}
|
| 848 |
-
|
| 849 |
-
#[test]
|
| 850 |
-
fn negative_position() {
|
| 851 |
-
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 852 |
-
let g = parse(&data, 10).unwrap();
|
| 853 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(-5, 10, -1)]);
|
| 854 |
-
}
|
| 855 |
-
|
| 856 |
-
#[test]
|
| 857 |
-
fn negative_size_extends_backwards() {
|
| 858 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [-2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 859 |
-
let g = parse(&data, 10).unwrap();
|
| 860 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(-1, 0, 0), (0, 0, 0)]);
|
| 861 |
-
}
|
| 862 |
-
|
| 863 |
-
#[test]
|
| 864 |
-
fn coordinate_out_of_cell_range() {
|
| 865 |
-
let data = litematic(|o| region(o, "r", [10_000, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 866 |
-
assert!(matches!(parse(&data, 10), Err(NbtError::Coord(_))));
|
| 867 |
-
}
|
| 868 |
-
|
| 869 |
-
#[test]
|
| 870 |
-
fn values_spanning_long_boundary() {
|
| 871 |
-
let names = ["minecraft:air", "minecraft:a", "minecraft:b", "minecraft:c", "minecraft:d"];
|
| 872 |
-
let palette: Palette = names.iter().map(|n| (*n, Vec::new())).collect();
|
| 873 |
-
let values: Vec<u64> = (0..30u64).map(|i| i % 5).collect();
|
| 874 |
-
let states = pack(&values, 3);
|
| 875 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [30, 1, 1], &palette, &states));
|
| 876 |
-
let g = parse(&data, 1000).unwrap();
|
| 877 |
-
assert_eq!(g.len(), 4);
|
| 878 |
-
let expected: Vec<Pos> = (0..30).filter(|i| i % 5 == 2).map(|i| (i, 0, 0)).collect();
|
| 879 |
-
assert_eq!(positions(&g[&key("b")]), expected);
|
| 880 |
-
}
|
| 881 |
-
|
| 882 |
-
#[test]
|
| 883 |
-
fn properties_are_sorted_in_name() {
|
| 884 |
-
let palette: Palette = vec![
|
| 885 |
-
("minecraft:air", vec![]),
|
| 886 |
-
("minecraft:oak_stairs", vec![("half", "bottom"), ("facing", "north")]),
|
| 887 |
-
];
|
| 888 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &palette, &pack(&[1], 2)));
|
| 889 |
-
let g = parse(&data, 10).unwrap();
|
| 890 |
-
assert!(g.contains_key(&key("oak_stairs[facing=north,half=bottom]")));
|
| 891 |
-
}
|
| 892 |
-
|
| 893 |
-
#[test]
|
| 894 |
-
fn multiple_regions_merge_sorted_by_region_name() {
|
| 895 |
-
let data = litematic(|o| {
|
| 896 |
-
region(o, "b", [10, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 897 |
-
region(o, "a", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 898 |
-
});
|
| 899 |
-
let g = parse(&data, 10).unwrap();
|
| 900 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0), (10, 0, 0)]);
|
| 901 |
-
}
|
| 902 |
-
|
| 903 |
-
#[test]
|
| 904 |
-
fn deterministic() {
|
| 905 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [3, 3, 3], &air_stone(), &pack(&[1; 27], 2)));
|
| 906 |
-
assert_eq!(parse(&data, 100).unwrap(), parse(&data, 100).unwrap());
|
| 907 |
-
}
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
// ---- имена без minecraft: ----
|
| 911 |
-
#[test]
|
| 912 |
-
fn block_names_lose_minecraft_prefix_only() {
|
| 913 |
-
let palette: Palette = vec![
|
| 914 |
-
("minecraft:air", vec![]),
|
| 915 |
-
("create:cogwheel", vec![]),
|
| 916 |
-
("minecraft:stone", vec![]),
|
| 917 |
-
];
|
| 918 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &palette, &pack(&[1, 2], 2)));
|
| 919 |
-
let g = parse(&data, 10).unwrap();
|
| 920 |
-
let mut names: Vec<&str> = g.keys().map(|k| k.0.as_str()).collect();
|
| 921 |
-
names.sort();
|
| 922 |
-
assert_eq!(names, vec!["create:cogwheel", "stone"]);
|
| 923 |
-
}
|
| 924 |
-
|
| 925 |
-
#[test]
|
| 926 |
-
fn stripped_name_keeps_properties() {
|
| 927 |
-
let palette: Palette = vec![
|
| 928 |
-
("minecraft:air", vec![]),
|
| 929 |
-
("minecraft:oak_stairs", vec![("facing", "north")]),
|
| 930 |
-
];
|
| 931 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &palette, &pack(&[1], 2)));
|
| 932 |
-
let g = parse(&data, 10).unwrap();
|
| 933 |
-
assert!(g.contains_key(&key("oak_stairs[facing=north]")));
|
| 934 |
-
}
|
| 935 |
-
|
| 936 |
-
// ---- сдвиг ----
|
| 937 |
-
#[test]
|
| 938 |
-
fn offset_shifts_positions() {
|
| 939 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 940 |
-
let g = parse_off(&data, [10, -20, 5]).unwrap();
|
| 941 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(10, -20, 5), (11, -20, 5)]);
|
| 942 |
-
}
|
| 943 |
-
|
| 944 |
-
#[test]
|
| 945 |
-
fn offset_adds_to_region_position() {
|
| 946 |
-
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 947 |
-
let g = parse_off(&data, [100, 1, 1]).unwrap();
|
| 948 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(95, 11, 0)]);
|
| 949 |
-
}
|
| 950 |
-
|
| 951 |
-
#[test]
|
| 952 |
-
fn offset_with_negative_size() {
|
| 953 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [-2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 954 |
-
let g = parse_off(&data, [5, 0, 0]).unwrap();
|
| 955 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(4, 0, 0), (5, 0, 0)]);
|
| 956 |
-
}
|
| 957 |
-
|
| 958 |
-
#[test]
|
| 959 |
-
fn offset_applies_to_every_region() {
|
| 960 |
-
let data = litematic(|o| {
|
| 961 |
-
region(o, "a", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 962 |
-
region(o, "b", [10, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 963 |
-
});
|
| 964 |
-
let g = parse_off(&data, [0, 0, 7]).unwrap();
|
| 965 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 7), (10, 0, 7)]);
|
| 966 |
-
}
|
| 967 |
-
|
| 968 |
-
#[test]
|
| 969 |
-
fn offset_applies_to_tile_entities() {
|
| 970 |
-
let data = litematic(|o| {
|
| 971 |
-
region_te(
|
| 972 |
-
o,
|
| 973 |
-
"r",
|
| 974 |
-
[0, 0, 0],
|
| 975 |
-
[2, 1, 1],
|
| 976 |
-
&air_stone(),
|
| 977 |
-
&pack(&[1, 1], 2),
|
| 978 |
-
&[(1, 0, 0, "minecraft:chest")],
|
| 979 |
-
)
|
| 980 |
-
});
|
| 981 |
-
let g = parse_off(&data, [100, 0, 0]).unwrap();
|
| 982 |
-
let k = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 983 |
-
assert_eq!(positions(&g[&k]), vec![(101, 0, 0)]);
|
| 984 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(100, 0, 0)]);
|
| 985 |
-
}
|
| 986 |
-
|
| 987 |
-
#[test]
|
| 988 |
-
fn offset_pushing_out_of_cell_range_is_error() {
|
| 989 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 990 |
-
assert!(matches!(parse_off(&data, [10_000, 0, 0]), Err(NbtError::Coord(_))));
|
| 991 |
-
assert!(matches!(parse_off(&data, [0, -1000, 0]), Err(NbtError::Coord(_))));
|
| 992 |
-
assert!(parse_off(&data, [9_999, -999, 0]).is_ok());
|
| 993 |
-
}
|
| 994 |
-
|
| 995 |
-
#[test]
|
| 996 |
-
fn offset_overflowing_i32_is_error() {
|
| 997 |
-
let data = litematic(|o| region(o, "r", [1, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 998 |
-
assert!(matches!(parse_off(&data, [i32::MAX, 0, 0]), Err(NbtError::Malformed(_))));
|
| 999 |
-
}
|
| 1000 |
-
|
| 1001 |
-
// ---- tile entities ----
|
| 1002 |
-
#[test]
|
| 1003 |
-
fn tile_entity_splits_group_and_gets_snbt() {
|
| 1004 |
-
let data = litematic(|o| {
|
| 1005 |
-
region_te(
|
| 1006 |
-
o,
|
| 1007 |
-
"r",
|
| 1008 |
-
[0, 0, 0],
|
| 1009 |
-
[3, 1, 1],
|
| 1010 |
-
&air_stone(),
|
| 1011 |
-
&pack(&[1, 1, 1], 2),
|
| 1012 |
-
&[(1, 0, 0, "minecraft:chest")],
|
| 1013 |
-
)
|
| 1014 |
-
});
|
| 1015 |
-
let g = parse(&data, 10).unwrap();
|
| 1016 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0), (2, 0, 0)]);
|
| 1017 |
-
let with_nbt = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 1018 |
-
assert_eq!(positions(&g[&with_nbt]), vec![(1, 0, 0)]);
|
| 1019 |
-
}
|
| 1020 |
-
|
| 1021 |
-
#[test]
|
| 1022 |
-
fn tile_entity_on_air_or_outside_is_ignored() {
|
| 1023 |
-
let data = litematic(|o| {
|
| 1024 |
-
region_te(
|
| 1025 |
-
o,
|
| 1026 |
-
"r",
|
| 1027 |
-
[0, 0, 0],
|
| 1028 |
-
[2, 1, 1],
|
| 1029 |
-
&air_stone(),
|
| 1030 |
-
&pack(&[0, 1], 2),
|
| 1031 |
-
&[(0, 0, 0, "minecraft:chest"), (5, 0, 0, "minecraft:chest"), (-1, 0, 0, "x")],
|
| 1032 |
-
)
|
| 1033 |
-
});
|
| 1034 |
-
let g = parse(&data, 10).unwrap();
|
| 1035 |
-
assert_eq!(g.len(), 1);
|
| 1036 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(1, 0, 0)]);
|
| 1037 |
-
}
|
| 1038 |
-
|
| 1039 |
-
#[test]
|
| 1040 |
-
fn tile_entities_same_nbt_share_group() {
|
| 1041 |
-
let data = litematic(|o| {
|
| 1042 |
-
region_te(
|
| 1043 |
-
o,
|
| 1044 |
-
"r",
|
| 1045 |
-
[0, 0, 0],
|
| 1046 |
-
[2, 1, 1],
|
| 1047 |
-
&air_stone(),
|
| 1048 |
-
&pack(&[1, 1], 2),
|
| 1049 |
-
&[(0, 0, 0, "minecraft:chest"), (1, 0, 0, "minecraft:chest")],
|
| 1050 |
-
)
|
| 1051 |
-
});
|
| 1052 |
-
let g = parse(&data, 10).unwrap();
|
| 1053 |
-
assert_eq!(g.len(), 1);
|
| 1054 |
-
let k = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 1055 |
-
assert_eq!(positions(&g[&k]), vec![(0, 0, 0), (1, 0, 0)]);
|
| 1056 |
-
}
|
| 1057 |
-
|
| 1058 |
-
// ---- SNBT ----
|
| 1059 |
-
#[test]
|
| 1060 |
-
fn dict_json_values_are_snbt_text() {
|
| 1061 |
-
let mut inner: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1062 |
-
inner.insert("Count".into(), Tag::Byte(1));
|
| 1063 |
-
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1064 |
-
m.insert("id".into(), Tag::String("minecraft:chest".into()));
|
| 1065 |
-
m.insert("x".into(), Tag::Int(1));
|
| 1066 |
-
m.insert("Lock".into(), Tag::String("a \"b\"".into()));
|
| 1067 |
-
m.insert("components".into(), Tag::Compound(BTreeMap::new()));
|
| 1068 |
-
m.insert("Empty".into(), Tag::List(vec![]));
|
| 1069 |
-
m.insert("Items".into(), Tag::List(vec![Tag::Compound(inner)]));
|
| 1070 |
-
let v: serde_json::Value =
|
| 1071 |
-
serde_json::from_str(&compound_dict_json(&m, &["x", "id"])).unwrap();
|
| 1072 |
-
assert_eq!(
|
| 1073 |
-
v,
|
| 1074 |
-
serde_json::json!({ "Items": "[{Count:1b}]", "Lock": "a \"b\"" })
|
| 1075 |
-
);
|
| 1076 |
-
}
|
| 1077 |
-
|
| 1078 |
-
#[test]
|
| 1079 |
-
fn snbt_scalars_and_quoting() {
|
| 1080 |
-
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1081 |
-
m.insert("id".into(), Tag::String("a\"b\\c".into()));
|
| 1082 |
-
m.insert("Count".into(), Tag::Byte(3));
|
| 1083 |
-
m.insert("a b".into(), Tag::Short(7));
|
| 1084 |
-
m.insert("l".into(), Tag::Long(5));
|
| 1085 |
-
m.insert("d".into(), Tag::Double(1.5));
|
| 1086 |
-
m.insert("f".into(), Tag::Float(2.0));
|
| 1087 |
-
assert_eq!(
|
| 1088 |
-
compound_snbt(&m, &[]),
|
| 1089 |
-
r#"{Count:3b,"a b":7s,d:1.5d,f:2f,id:"a\"b\\c",l:5L}"#
|
| 1090 |
-
);
|
| 1091 |
-
assert_eq!(compound_snbt(&m, &["id", "Count", "a b", "d", "f"]), "{l:5L}");
|
| 1092 |
-
}
|
| 1093 |
-
|
| 1094 |
-
#[test]
|
| 1095 |
-
fn snbt_lists_and_arrays() {
|
| 1096 |
-
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1097 |
-
m.insert("list".into(), Tag::List(vec![Tag::Int(1), Tag::Int(2)]));
|
| 1098 |
-
m.insert("ints".into(), Tag::IntArray(&[0, 0, 0, 1, 0, 0, 0, 2]));
|
| 1099 |
-
m.insert("bytes".into(), Tag::ByteArray(&[1, 255]));
|
| 1100 |
-
m.insert("longs".into(), Tag::LongArray(&[0, 0, 0, 0, 0, 0, 0, 9]));
|
| 1101 |
-
let mut inner: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1102 |
-
inner.insert("k".into(), Tag::Int(1));
|
| 1103 |
-
m.insert("c".into(), Tag::List(vec![Tag::Compound(inner)]));
|
| 1104 |
-
assert_eq!(
|
| 1105 |
-
compound_snbt(&m, &[]),
|
| 1106 |
-
"{bytes:[B;1b,-1b],c:[{k:1}],ints:[I;1,2],list:[1,2],longs:[L;9L]}"
|
| 1107 |
-
);
|
| 1108 |
-
}
|
| 1109 |
-
|
| 1110 |
-
// ---- ошибки и лимиты ----
|
| 1111 |
-
#[test]
|
| 1112 |
-
fn not_litematic_without_regions() {
|
| 1113 |
-
let mut data = Vec::new();
|
| 1114 |
-
named(&mut data, 10, "");
|
| 1115 |
-
int_named(&mut data, "Version", 6);
|
| 1116 |
-
data.push(0);
|
| 1117 |
-
assert!(matches!(parse(&data, 10), Err(NbtError::NotLitematic(_))));
|
| 1118 |
-
}
|
| 1119 |
-
|
| 1120 |
-
#[test]
|
| 1121 |
-
fn garbage_is_malformed() {
|
| 1122 |
-
assert!(matches!(parse(&[1, 2, 3], 10), Err(NbtError::Malformed(_))));
|
| 1123 |
-
assert!(matches!(parse(&[], 10), Err(NbtError::Malformed(_))));
|
| 1124 |
-
}
|
| 1125 |
-
|
| 1126 |
-
#[test]
|
| 1127 |
-
fn truncated_is_malformed() {
|
| 1128 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 2], &air_stone(), &pack(&[0, 1, 1, 0], 2)));
|
| 1129 |
-
let cut = &data[..data.len() - 5];
|
| 1130 |
-
assert!(matches!(parse(cut, 10), Err(NbtError::Malformed(_))));
|
| 1131 |
-
}
|
| 1132 |
-
|
| 1133 |
-
#[test]
|
| 1134 |
-
fn index_outside_palette() {
|
| 1135 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[3], 2)));
|
| 1136 |
-
assert!(matches!(parse(&data, 10), Err(NbtError::Malformed(_))));
|
| 1137 |
-
}
|
| 1138 |
-
|
| 1139 |
-
#[test]
|
| 1140 |
-
fn states_too_short() {
|
| 1141 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [4, 4, 4], &air_stone(), &pack(&[1], 2)));
|
| 1142 |
-
assert!(matches!(parse(&data, 100), Err(NbtError::Malformed(_))));
|
| 1143 |
-
}
|
| 1144 |
-
|
| 1145 |
-
#[test]
|
| 1146 |
-
fn block_limit() {
|
| 1147 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 1148 |
-
assert!(matches!(parse(&data, 1), Err(NbtError::TooManyBlocks(1))));
|
| 1149 |
-
assert!(parse(&data, 2).is_ok());
|
| 1150 |
-
}
|
| 1151 |
-
|
| 1152 |
-
#[test]
|
| 1153 |
-
fn cancel_flag_stops_parsing() {
|
| 1154 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 1155 |
-
let cancel = AtomicBool::new(true);
|
| 1156 |
-
assert_eq!(parse_litematic(&data, 10, [0, 0, 0], &cancel), Err(NbtError::Cancelled));
|
| 1157 |
-
}
|
| 1158 |
-
|
| 1159 |
-
#[test]
|
| 1160 |
-
fn gz_roundtrip() {
|
| 1161 |
-
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 1162 |
-
let g = parse_litematic_gz(&gzip(&data), &Limits::default(), [0, 0, 0], &AtomicBool::new(false)).unwrap();
|
| 1163 |
-
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0)]);
|
| 1164 |
-
}
|
| 1165 |
-
|
| 1166 |
-
#[test]
|
| 1167 |
-
fn gunzip_limit_and_errors() {
|
| 1168 |
-
let gz = gzip(&vec![7u8; 1000]);
|
| 1169 |
-
assert_eq!(gunzip(&gz, 1000).unwrap().len(), 1000);
|
| 1170 |
-
assert!(matches!(gunzip(&gz, 999), Err(NbtError::TooLarge(999))));
|
| 1171 |
-
assert!(matches!(gunzip(b"<html>", 10), Err(NbtError::NotLitematic(_))));
|
| 1172 |
-
assert!(matches!(gunzip(&[], 10), Err(NbtError::NotLitematic(_))));
|
| 1173 |
-
let mut broken = gz.clone();
|
| 1174 |
-
broken.truncate(broken.len() / 2);
|
| 1175 |
-
assert!(gunzip(&broken, 1000).is_err());
|
| 1176 |
-
}
|
| 1177 |
-
|
| 1178 |
-
#[test]
|
| 1179 |
-
fn bits_for_palette_sizes() {
|
| 1180 |
-
// 2 бита минимум; 5 записей → 3 бита; 17 записей → 5 бит
|
| 1181 |
-
let bits = |n: usize| u64::from((usize::BITS - (n - 1).leading_zeros()).max(2));
|
| 1182 |
-
assert_eq!(bits(1), 2);
|
| 1183 |
-
assert_eq!(bits(4), 2);
|
| 1184 |
-
assert_eq!(bits(5), 3);
|
| 1185 |
-
assert_eq!(bits(16), 4);
|
| 1186 |
-
assert_eq!(bits(17), 5);
|
| 1187 |
-
}
|
| 1188 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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