# model/schematic fixtures: schematics written by reference code through nix, with every cell's block state, and our # encoder's output read back by the same reference code. # .litematic: Python's litemapy (several regions, a negative size, a 40-state palette), a tile entity added with # nbtlib; .schem v2: litemapy's Region.to_sponge_nbt (+ a block entity); .schem v1 / v3 and the legacy # MCEdit .schematic (ids + data, WorldEdit AddBlocks, a SchematicaMapping table): nbtlib, by the specs. # tests/gen/schematic.luau { cases = { { name, data, variant, version, regions = { { name, min = {x,y,z}, # size = {x,y,z}, cells = "state\n..." (Voxels order: x, then y, then z) or legacy = # { id*16+data per cell } } }, blockEntities = n, ... } } } # tests/gen/schematic_ours.luau { [name] = { regions = { { name, min, size, cells } } } }: our encodings # (tools/fixtures/_schematic_encode.luau) read back by litemapy / nbtlib import importlib.util, os, pickle, subprocess, sys INPUTS = ["src/Rosetta/model/schematic", "src/Rosetta/codecs/model/Minecraft", "src/Rosetta/codecs/text/Nbt", "tools/fixtures/_schematic_encode.luau"] _spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py")) R = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(R) COMMON = r''' import nbtlib, pickle, random, struct, sys, io, gzip, os, tempfile from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray import numpy as np from litemapy import Schematic, Region, BlockState def state_of(bs): # a litemapy BlockState as the state string, properties in the NBT order t = bs.to_nbt() props = t.get("Properties") if props: return str(t["Name"]) + "[" + ",".join("%s=%s" % (k, str(v)) for k, v in props.items()) + "]" return str(t["Name"]) def region_cells(reg): xs, ys, zs = list(reg.range_x()), list(reg.range_y()), list(reg.range_z()) out = [] for z in zs: for y in ys: for x in xs: out.append(state_of(reg[x, y, z])) return out def region_info(name, reg): return {"name": name, "min": [reg.min_schem_x(), reg.min_schem_y(), reg.min_schem_z()], "size": [abs(reg.width), abs(reg.height), abs(reg.length)], "cells": "\n".join(region_cells(reg))} def sponge_cells(s): # Sponge v1 / v2 / v3 compound -> min, size, cells v = int(s.get("Version", 1)) w, h, l = int(s["Width"]) & 0xffff, int(s["Height"]) & 0xffff, int(s["Length"]) & 0xffff blocks = s["Blocks"] if v >= 3 else s pal = blocks["Palette"] data = bytes(np.asarray(blocks["Data"] if v >= 3 else blocks["BlockData"], dtype=np.int8).tobytes()) names = {int(i): k for k, i in pal.items()} idx, p = [], 0 while len(idx) < w * h * l: val, sh = 0, 0 while True: c = data[p]; p += 1 val |= (c & 0x7f) << sh sh += 7 if c < 128: break idx.append(val) cells = [] for z in range(l): for y in range(h): for x in range(w): cells.append(names[idx[x + z * w + y * w * l]]) off = list(s["Offset"]) if "Offset" in s else [0, 0, 0] return {"name": "", "min": [int(o) for o in off], "size": [w, h, l], "cells": "\n".join(cells)} ''' BODY = COMMON + r''' rng = random.Random(11) STATES = ["minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:glass", "minecraft:oak_planks", "minecraft:water[level=0]", "minecraft:grass_block[snowy=false]", "minecraft:oak_log[axis=y]", "minecraft:oak_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]", "minecraft:chest[facing=north,type=single,waterlogged=false]", "minecraft:spruce_slab[type=top,waterlogged=false]", "minecraft:lantern[hanging=true,waterlogged=false]"] COLOURS = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"] BIG = ["minecraft:%s_%s" % (c, k) for c in COLOURS for k in ("wool", "concrete", "terracotta")] def bs(s): if "[" in s: name, rest = s.split("[", 1) props = dict(kv.split("=") for kv in rest[:-1].split(",")) return BlockState(name, **props) return BlockState(s) def fill(reg, states): for x in reg.range_x(): for y in reg.range_y(): for z in reg.range_z(): reg[x, y, z] = bs(rng.choice(states)) cases = [] tmp = tempfile.mkdtemp() # 1. litematic: three regions (one with negative sizes, one with a 40-state palette) main = Region(0, 0, 0, 6, 5, 4); fill(main, STATES) neg = Region(10, 2, -3, -4, 3, -5); fill(neg, STATES[:6]) big = Region(-20, 0, 0, 7, 3, 5); fill(big, BIG) sch = Schematic(name="Test", author="rosetta", description="fixture", regions={"main": main, "neg": neg, "big": big}) path = os.path.join(tmp, "t.litematic") sch.save(path) f = nbtlib.load(path) # a tile entity, as Litematica stores them (relative to the region's minimum corner) f["Regions"]["main"]["TileEntities"].append(Compound({"x": Int(1), "y": Int(0), "z": Int(2), "id": String("minecraft:chest"), "Items": List[Compound]([])})) f.save(path) data = open(path, "rb").read() cases.append({"name": "litemapy", "variant": "litematic", "version": 6, "data": data, "blockEntities": 1, "regions": [region_info(n, r) for n, r in Schematic.load(path).regions.items()]}) # 2. schem v2 from litemapy (+ a block entity) reg = Region(0, 0, 0, 5, 4, 6); fill(reg, STATES) sp = reg.to_sponge_nbt(mc_version=3465) sp["BlockEntities"].append(Compound({"Pos": IntArray([1, 2, 3]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})) path = os.path.join(tmp, "v2.schem") sp.save(path, gzipped=True) data = open(path, "rb").read() cases.append({"name": "sponge2", "variant": "schem", "version": 2, "data": data, "blockEntities": 1, "regions": [sponge_cells(nbtlib.load(path))]}) # 3. schem v3 / v1 by the spec (nbtlib), a palette past 128 states (two-byte varints) def varints(idx): out = bytearray() for v in idx: while v >= 128: out.append((v & 0x7f) | 0x80); v >>= 7 out.append(v) return bytes(out) def sponge(version, w, h, l, states, offset): states = list(dict.fromkeys(states)) pal = {s: i for i, s in enumerate(states)} idx = [rng.randrange(len(states)) for _ in range(w * h * l)] data = ByteArray(np.frombuffer(varints(idx), dtype=np.int8)) palc = Compound({s: Int(i) for s, i in pal.items()}) if version >= 3: s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l), "Offset": IntArray(offset), "Metadata": Compound({"Name": String("v3"), "Date": Long(1700000000000)}), "Blocks": Compound({"Palette": palc, "Data": data, "BlockEntities": List[Compound]([ Compound({"Pos": IntArray([0, 1, 2]), "Id": String("minecraft:chest"), "Data": Compound({"Items": List[Compound]([])})})])}), "Biomes": Compound({"Palette": Compound({"minecraft:plains": Int(0)}), "Data": ByteArray([0] * (w * h * l))}), "Entities": List[Compound]([Compound({"Pos": List[Double]([Double(1.5), Double(0.0), Double(2.5)]), "Id": String("minecraft:pig"), "Data": Compound({})})])}) return nbtlib.File({"Schematic": s}, root_name=""), s s = Compound({"Version": Int(1), "Width": Short(w), "Height": Short(h), "Length": Short(l), "Offset": IntArray(offset), "PaletteMax": Int(len(states)), "Palette": palc, "BlockData": data, "TileEntities": List[Compound]([Compound({"Pos": IntArray([0, 0, 0]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})])}) return nbtlib.File(s, root_name="Schematic"), s stairs = ["minecraft:oak_stairs[facing=%s,half=%s,shape=%s,waterlogged=false]" % (f_, h_, s_) for f_ in ("north", "south", "east", "west") for h_ in ("top", "bottom") for s_ in ("straight", "inner_left", "inner_right", "outer_left", "outer_right")] for name, version, states, size, off in [("sponge3", 3, ["minecraft:air"] + BIG + stairs + STATES[1:], (9, 7, 8), [-4, 1, 7]), ("sponge1", 1, STATES, (4, 3, 5), [0, 0, 0])]: f, s = sponge(version, size[0], size[1], size[2], states, off) path = os.path.join(tmp, name + ".schem") f.save(path, gzipped=True) data = open(path, "rb").read() cases.append({"name": name, "variant": "schem", "version": version, "data": data, "blockEntities": 1, "regions": [sponge_cells(s)]}) # 4. MCEdit .schematic: legacy ids and data values (WorldEdit AddBlocks; a Schematica name table) LEGACY = [(0, 0), (1, 0), (1, 3), (35, 14), (35, 0), (5, 2), (17, 5), (53, 3), (20, 0), (98, 1), (159, 11), (251, 4), (44, 9), (2, 0)] for name, ids, add, mapping in [("mcedit", LEGACY, False, False), ("worldedit_add", LEGACY + [(300, 2), (4000, 0)], True, False), ("schematica", LEGACY, False, True)]: w, h, l = 5, 4, 3 n = w * h * l cells = [rng.choice(ids) for _ in range(n)] # in file order (x + z*w + y*w*l) blocks = bytes(c[0] & 0xff for c in cells) datas = bytes(c[1] for c in cells) root = Compound({"Width": Short(w), "Height": Short(h), "Length": Short(l), "Materials": String("Alpha"), "Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)), "Data": ByteArray(np.frombuffer(datas, dtype=np.int8)), "Entities": List[Compound]([]), "TileEntities": List[Compound]([Compound({"x": Int(1), "y": Int(1), "z": Int(1), "id": String("Chest"), "Items": List[Compound]([])})]), "WEOffsetX": Int(-2), "WEOffsetY": Int(0), "WEOffsetZ": Int(3)}) if add: nib = bytearray((n + 1) // 2) for i, c in enumerate(cells): hi = c[0] >> 8 nib[i >> 1] |= (hi << 4) if i % 2 == 0 else hi # high nibble first (WorldEdit) root["AddBlocks"] = ByteArray(np.frombuffer(bytes(nib), dtype=np.int8)) if mapping: root["SchematicaMapping"] = Compound({"minecraft:stone": Short(1), "minecraft:wool": Short(35), "minecraft:planks": Short(5), "minecraft:log": Short(17), "minecraft:oak_stairs": Short(53), "minecraft:air": Short(0), "minecraft:glass": Short(20), "minecraft:stonebrick": Short(98), "minecraft:stained_hardened_clay": Short(159), "minecraft:concrete": Short(251), "minecraft:stone_slab": Short(44), "minecraft:grass": Short(2)}) path = os.path.join(tmp, name + ".schematic") nbtlib.File(root, root_name="Schematic").save(path, gzipped=True) legacy = [] for z in range(l): for y in range(h): for x in range(w): c = cells[x + z * w + y * w * l] legacy.append(c[0] * 16 + c[1]) cases.append({"name": name, "variant": "schematic", "version": 0, "data": open(path, "rb").read(), "blockEntities": 1, "regions": [{"name": "", "min": [-2, 0, 3], "size": [w, h, l], "legacy": legacy}]}) sys.stdout.buffer.write(pickle.dumps(cases, protocol=4)) ''' # our encodings read back: litematic by litemapy, schem v2 by litemapy's from_sponge_nbt, every Sponge version and # the MCEdit layout by nbtlib READ_BACK = COMMON + r''' files = pickle.loads(sys.stdin.buffer.read()) tmp = tempfile.mkdtemp() out = {} for name, data in files.items(): path = os.path.join(tmp, name) open(path, "wb").write(data) f = nbtlib.load(path) if name.endswith(".litematic"): s = Schematic.load(path) out[name] = {"regions": [region_info(n, r) for n, r in s.regions.items()], "author": s.author, "name": s.name} elif name.endswith(".schem"): s = f["Schematic"] if "Schematic" in f and "Version" not in f else f regs = [sponge_cells(s)] res = {"regions": regs, "version": int(s["Version"])} if int(s["Version"]) == 2: reg, mc = Region.from_sponge_nbt(nbtlib.load(path)) cells = region_cells(reg) res["litemapy"] = "\n".join(cells) out[name] = res else: w, h, l = int(f["Width"]), int(f["Height"]), int(f["Length"]) blocks = np.asarray(f["Blocks"], dtype=np.uint8) datas = np.asarray(f["Data"], dtype=np.uint8) add = np.asarray(f["AddBlocks"], dtype=np.uint8) if "AddBlocks" in f else None legacy = [] for z in range(l): for y in range(h): for x in range(w): i = x + z * w + y * w * l bid = int(blocks[i]) if add is not None: bid |= ((int(add[i >> 1]) >> (4 if i % 2 == 0 else 0)) & 15) << 8 legacy.append(bid * 16 + int(datas[i])) out[name] = {"regions": [{"name": "", "min": [int(f.get("WEOffsetX", 0)), int(f.get("WEOffsetY", 0)), int(f.get("WEOffsetZ", 0))], "size": [w, h, l], "legacy": legacy}]} sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) ''' def run(ctx, packages, body, input=None): try: return ctx.python(packages, body, input=input) except subprocess.CalledProcessError as e: raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) def generate(ctx): cases = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], BODY)) ctx.emit("schematic", {"cases": cases}) try: files = R.luau_encode(ctx, "tools/fixtures/_schematic_encode.luau") except subprocess.CalledProcessError as e: raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:] + (e.stdout or b"").decode(errors="replace")[-2000:]) ours = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], READ_BACK, input=pickle.dumps(files))) ctx.emit("schematic_ours", ours)