ws-voxel: model/schematic (.schem v1-3, .schematic, .litematic read + write), codecs/model/Minecraft (block states, default colours, legacy ids, packed arrays)

Types change (backward compatible): Types.Voxels gains optional blocks (VoxelBlocks: exact block states as
u16 indices into a state palette, block entities, entities) and colors (exact u32 RGBA per cell).
This commit is contained in:
4DBug committed 2026-10-31 14:37:43 -05:00
1 parent 7fc5d3f5f0
commit fea56f4391
11 files changed
+524 -40

No files matched your search

+1 -1
View File
@@ -41,7 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | **missing** |
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` |
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
@@ -53,21 +53,18 @@ Legacy.RENAMED = {
melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block",
red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks",
mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block",
quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water",
flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone",
stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion",
quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad",
tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone",
stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion",
fence = "oak_fence", fence_gate = "oak_fence_gate",
wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate",
wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign",
wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston",
silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta",
monster_egg = "infested_stone",
standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull",
bed = "red_bed",
}
} :: { [string]: string }
-- legacy names whose data value selects the variant: the modern names by data value (0-based)
local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black"
@@ -105,7 +102,7 @@ Legacy.VARIANTS = {
stained_hardened_clay = dyed("terracotta"),
concrete = dyed("concrete"),
concrete_powder = dyed("concrete_powder"),
}
Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 }
} :: { [string]: { string } }
Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number }
return Legacy
+6 -6
View File
@@ -121,18 +121,18 @@ end
local EXACT: { [string]: { number } } = {}
for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do
EXACT[name] = hex(h)
EXACT[name :: string] = hex(h :: string)
end
local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA)
local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES)
-- longest prefixes first, so light_blue wins over blue and dark_oak over oak
local function byLength(names: { string }): { { any } }
local out = {}
local out: { { any } } = {}
for i, n in names do
table.insert(out, { n, i })
end
table.sort(out, function(a, b)
return #a[1] > #b[1]
table.sort(out, function(a: { any }, b: { any }): boolean
return #(a[1] :: string) > #(b[1] :: string)
end)
return out
end
@@ -141,8 +141,8 @@ local SUFFIXES = {
"_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button",
"_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars",
}
local PREFIXES = { "waxed_", "potted_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
local CORAL = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") }
local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") }
local FALLBACK = hex("909090")
local function mix(c: { number }, w: { number }, t: number): { number }
+3 -3
View File
@@ -46,9 +46,9 @@ end
function Common.ints(v: any): { number }?
if Nbt.isTag(v) and v.type == "intArray" then
return v.value
elseif type(v) == "table" and not Nbt.isTag(v) and v[1] ~= nil then
local out = {}
for i, x in v do
elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then
local out: { number } = {}
for i, x in v :: { any } do
out[i] = Nbt.number(x) or 0
end
return out
+46 -10
View File
@@ -91,18 +91,18 @@ function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any)
table.insert(bes, be)
end
end
return {
local regions: { Common.Region } = {
{
name = nil,
size = { sx, sy, sz },
size = { sx, sy :: number, sz :: number },
position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 },
states = states,
indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number),
blockEntities = bes,
entities = Common.list(root.Entities),
},
},
{ materials = root.Materials }
}
return regions, { materials = root.Materials }
end
-- the legacy blocks a colour can become (full blocks of distinct colours)
@@ -160,14 +160,50 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?)
return nil, "a .schematic is at most 65535 cells on each axis"
end
local n = sx * sy * sz
local ids, datas = table.create(#r.states), table.create(#r.states)
-- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list
local map: { [string]: number } = {}
if type(base) == "table" then
if Types.isObject(base.SchematicaMapping) then
for _, k in Types.keys(base.SchematicaMapping) do
local id = Common.int(base.SchematicaMapping[k])
if id then
map[k] = id
end
end
end
if Types.isObject(base.BlockIDs) then
for _, k in Types.keys(base.BlockIDs) do
local id = tonumber(k)
if id and type(base.BlockIDs[k]) == "string" then
map[base.BlockIDs[k]] = id
end
end
end
end
local ids, datas = table.create(#r.states) :: { number }, table.create(#r.states) :: { number }
local high = false
for i, s in r.states do
local id, d = Mc.legacyId(s)
if id == nil then
id, d = nearest(s)
if id ~= nil then
local lname = Mc.Legacy.NAMES[id + 1]
local mapped = lname and map["minecraft:" .. lname]
if mapped then
id = mapped
end
else
local name, props = Mc.parseState(s)
if map[name] then
id, d = map[name], 0
for _, kv in props do
if kv[1] == "data" then
d = (tonumber(kv[2]) or 0) % 16
end
end
else
id, d = nearest(s)
end
end
ids[i], datas[i] = id, d
ids[i], datas[i] = id :: number, d :: number
if (id :: number) > 255 then
high = true
end
@@ -189,7 +225,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?)
table.insert(tiles, Common.flatBlockEntity(be, "flat"))
end
local ents = if #r.entities > 0 then r.entities else Nbt.list("compound")
local fields = {
local fields: { { any } } = {
{ "Width", Nbt.short(sx) },
{ "Height", Nbt.short(sy) },
{ "Length", Nbt.short(sz) },
@@ -206,7 +242,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?)
table.insert(fields, { "WEOffsetY", p[2] })
table.insert(fields, { "WEOffsetZ", p[3] })
end
local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true })
local root = Common.merge(base, fields, { Add = true })
return root, nil
end
+5 -5
View File
@@ -67,18 +67,18 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any)
end
end
local off = Common.ints(s.Offset) or { 0, 0, 0 }
return {
local regions: { Common.Region } = {
{
name = nil,
size = { sx, sy, sz },
size = { sx, sy :: number, sz :: number },
position = { off[1] or 0, off[2] or 0, off[3] or 0 },
states = states,
indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number),
blockEntities = bes,
entities = Common.list(s.Entities),
},
},
{ version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata }
}
return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata }
end
-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil,
@@ -101,7 +101,7 @@ function Sponge.write(r: Common.Region, version: number, dataVersion: number, ba
for _, be in r.blockEntities do
table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos"))
end
local ents = if #r.entities > 0 then r.entities else nil
local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") -- optional, but readers expect it
local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] })
local fields: { { any } } = {
{ "Version", version },
+31 -6
View File
@@ -49,11 +49,22 @@ export type EncodeOptions = {
title: string?, -- .litematic Metadata.Name
compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them
level: number?, -- deflate level
format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...)
}
-- ------------------------------------------------------------------------------------------------ constants
local DEFAULT_DATA_VERSION = 3953
local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" }
local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed)
local function hinted(head: string, hints: { string }): boolean
for _, h in hints do
if string.find(head, string.char(0, #h) .. h, 1, true) then
return true
end
end
return false
end
-- ------------------------------------------------------------------------------------------------ sniff
function Schematic.sniff(r: Bytes.Reader): number
@@ -65,12 +76,25 @@ function Schematic.sniff(r: Bytes.Reader): number
return 1
end
local head = buffer.tostring(p.head)
for _, h in LITEMATIC_HINTS do
if string.find(head, string.char(0, #h) .. h, 1, true) then
return 1
end
return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0
end
-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes)
function Schematic.variant(r: Bytes.Reader): string?
local p = Nbt.peek(r.buf, r.base, r.limit - r.base)
if not p then
return nil
end
return 0
if p.firstName == "Schematic" then
return "schem"
end
local head = buffer.tostring(p.head)
if hinted(head, LITEMATIC_HINTS) then
return "litematic"
elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then
return "schem"
end
return if p.name == "Schematic" then "schematic" else nil
end
-- ------------------------------------------------------------------------------------------------ decode
@@ -114,7 +138,8 @@ function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?,
regions, extra = Mcedit.read(s, maxCells)
end
if not regions then
return nil, Err.from(extra)
local msg = tostring(extra)
return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil)
end
local scene = Types.Scene.new()
scene.voxels = {}
+155
View File
@@ -0,0 +1,155 @@
-- codecs/model/Minecraft tests: packed index arrays (spanning and not, 1..16 bits, against a bit-by-bit reference),
-- Sponge varints, nibble arrays, YZX reordering, block-state strings and their NBT form, every legacy id / data pair
-- through legacyState / legacyId, colours (air, families, fallbacks), voxels / blocksOf and nearest-colour blocks.
-- The formats using it: tests/model/schematic.luau, tests/model/mca.luau.
local T = require("@tests/T")
local Mc = require("@formats/codecs/model/Minecraft")
local Types = require("@formats/Types")
local t = T.suite("minecraft")
local P = Mc.Packed
local rand = T.rng(3)
-- 1. packed arrays against a reference that walks the bits one at a time
local function refBit(longs: buffer, p: number): number
return bit32.extract(buffer.readu8(longs, p // 8), p % 8, 1)
end
for bits = 1, 16 do
for _, spanning in { true, false } do
local count = 100 + rand(300)
local max = math.min(2 ^ bits, 70000)
local idx = buffer.create(count * 2)
for i = 0, count - 1 do
buffer.writeu16(idx, i * 2, rand(max))
end
local longs = P.pack(idx, count, bits, spanning)
t:eq(buffer.len(longs), P.longsNeeded(count, bits, spanning) * 8, bits .. " bits: size")
local per = 64 // bits
local bad = 0
for i = 0, count - 1 do
local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits
local v = 0
for k = 0, bits - 1 do
v += refBit(longs, p + k) * 2 ^ k
end
if v ~= buffer.readu16(idx, i * 2) then
bad += 1
end
end
t:eq(bad, 0, bits .. " bits " .. tostring(spanning) .. ": layout")
local back = buffer.create(count * 2)
local ok, e = P.unpack(longs, bits, count, spanning, back, max)
t:check(ok, tostring(e))
t:eq(buffer.tostring(back), buffer.tostring(idx), bits .. " bits " .. tostring(spanning) .. ": round trip")
end
end
do
local out = buffer.create(40)
t:check(not P.unpack(buffer.create(8), 4, 20, false, out, 16), "too few longs")
local l = P.pack(buffer.fromstring("\5\0"), 1, 4, false)
t:check(not P.unpack(l, 4, 1, false, out, 3), "index past the palette")
t:eq(P.bitsFor(17, 4), 5, "bitsFor")
t:eq(P.bitsFor(1, 2), 2, "bitsFor minimum")
end
-- 2. varints, nibbles, YZX
do
local idx = buffer.create(400)
for i = 0, 199 do
buffer.writeu16(idx, i * 2, (i * 997) % 20000)
end
local v = P.toVarints(idx, 200)
local back = buffer.create(400)
t:check(P.varints(v, 0, buffer.len(v), 200, back, 20000), "varints")
t:eq(buffer.tostring(back), buffer.tostring(idx), "varints round trip")
t:check(not P.varints(v, 0, buffer.len(v) - 1, 200, back, 20000), "varints truncated")
local nib = buffer.create(2)
P.setNibble(nib, 0, 0, 0xA, true)
P.setNibble(nib, 0, 1, 0x3, true)
P.setNibble(nib, 0, 2, 0x7, false)
t:eq(buffer.readu8(nib, 0), 0xA3, "high nibble first")
t:eq(buffer.readu8(nib, 1), 0x07, "low nibble first")
t:eq(P.nibble(nib, 0, 1, true), 3, "read nibble")
local sx, sy, sz = 3, 4, 5
local yzx = buffer.create(sx * sy * sz * 2)
for y = 0, sy - 1 do
for z = 0, sz - 1 do
for x = 0, sx - 1 do
buffer.writeu16(yzx, (x + z * sx + y * sx * sz) * 2, x * 100 + y * 10 + z)
end
end
end
local vox = P.fromYzx(yzx, sx, sy, sz)
t:eq(buffer.readu16(vox, (2 + sx * (3 + sy * 4)) * 2), 234, "fromYzx")
t:eq(buffer.tostring(P.toYzx(vox, sx, sy, sz)), buffer.tostring(yzx), "toYzx")
end
-- 3. states
do
local name, props = Mc.parseState("oak_log[axis=y, foo = bar]")
t:eq(name, "minecraft:oak_log", "namespace added")
t:eq(#props, 2, "props")
t:eq(Mc.stateString(name, props), "minecraft:oak_log[axis=y,foo=bar]", "stateString")
local c = Mc.stateToNbt("minecraft:chest[facing=north,type=single]")
t:eq(table.concat(Types.keys(c.Properties), ","), "facing,type", "NBT property order")
t:eq(Mc.stateFromNbt(c), "minecraft:chest[facing=north,type=single]", "stateFromNbt")
t:eq(Mc.baseName("minecraft:stone"), "stone", "baseName")
t:check(Mc.isAir("minecraft:cave_air") and not Mc.isAir("minecraft:stone"), "isAir")
end
-- 4. legacy ids: every id / data pair reads back exactly
do
local bad = 0
for id = 0, 255 do
for d = 0, 15 do
local s = Mc.legacyState(id, d)
local i2, d2 = Mc.legacyId(s)
if i2 ~= id or d2 ~= d then
bad += 1
end
end
end
t:eq(bad, 0, "legacy round trip")
t:eq(Mc.legacyState(35, 14), "minecraft:red_wool", "wool 14")
t:eq(Mc.legacyState(5, 2), "minecraft:birch_planks", "planks 2")
t:eq(Mc.legacyState(17, 5), "minecraft:spruce_log[data=5]", "log axis bits kept")
t:eq(select(1, Mc.legacyId("minecraft:white_concrete")), 251, "modern name -> legacy id")
end
-- 5. colours
do
t:eq(Mc.color("minecraft:air"), nil, "air")
local function hex(s: string): string
local c = Mc.color(s) :: { number }
return string.format("%02x%02x%02x%02x", c[1], c[2], c[3], c[4])
end
t:eq(hex("minecraft:stone"), "7d7d7dff", "exact")
t:eq(hex("minecraft:stone_brick_stairs[facing=east]"), hex("minecraft:stone_bricks"), "stairs -> base")
t:eq(hex("minecraft:red_concrete"), "8e2020ff", "dye family")
t:eq(hex("minecraft:dark_oak_log"), "3e2f17ff", "wood bark")
t:eq(string.sub(hex("minecraft:red_stained_glass"), 7, 8), "80", "stained glass translucent")
t:eq(hex("minecraft:wool[data=14]"), hex("minecraft:red_wool"), "legacy data colour")
t:eq(hex("mod:something_odd"), "909090ff", "fallback")
end
-- 6. voxels / blocksOf
do
local states = { "minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:stone" }
local idx = buffer.create(8 * 2)
for i = 0, 7 do
buffer.writeu16(idx, i * 2, i % 4)
end
local v = Mc.voxels(2, 2, 2, states, idx)
t:eq(buffer.readu8(v.data, 0), 0, "air -> 0")
t:eq(buffer.readu8(v.data, 1), buffer.readu8(v.data, 3), "same colour, same index")
t:check(buffer.readu8(v.data, 2) ~= buffer.readu8(v.data, 1), "different colours")
local s2, i2 = Mc.blocksOf(v)
t:check(s2 == states and i2 == idx, "blocksOf keeps the blocks")
local g = Types.Voxels.new(2, 1, 1)
g.palette[7] = { 240, 118, 19, 255 }
buffer.writeu8(g.data, 1, 7)
local s3, i3 = Mc.blocksOf(g)
t:eq((s3 :: { string })[buffer.readu16(i3, 2) + 1], "minecraft:orange_wool", "nearest block by colour")
t:eq((s3 :: { string })[buffer.readu16(i3, 0) + 1], "minecraft:air", "empty -> air")
end
t:done()
+221
View File
@@ -0,0 +1,221 @@
-- model/schematic tests: .litematic files written by litemapy (several regions, negative sizes, a 40-state palette,
-- tile entities), Sponge .schem v2 (litemapy) and v1 / v3 (nbtlib, by the spec; two-byte varints), MCEdit
-- .schematic (legacy ids + data, WorldEdit AddBlocks, a Schematica name table): every cell's block state, placement,
-- block entities; our re-encodings give the same NBT for the same variant, and the reference readers (litemapy /
-- nbtlib, in the fixture step) read our output, across variants and from colour-only grids, to the same cells;
-- detection, the api, error codes and the fuzz pass. Fixtures: tools/fixtures/schematic.py.
local T = require("@tests/T")
local F = require("@formats")
local Schematic = require("@formats/model/schematic")
local Mc = require("@formats/codecs/model/Minecraft")
local Nbt = require("@formats/codecs/text/Nbt")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/schematic")
local Ours = require("@tests/gen/schematic_ours")
local t = T.suite("schematic")
t:eq(Schematic.name, "schematic", "name")
t:check(Schematic.caps.decode and Schematic.caps.encode, "caps")
local function dec(data: string | buffer, opts: any?): (Types.Scene?, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Schematic.decode(Bytes.reader(b), opts)
end
-- the region record of node i: { name, min, size, cells (state per cell, "\n"-joined), legacy (id * 16 + data) }
local function regions(scene: Types.Scene): { any }
local out = {}
for _, node in scene.nodes do
local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number]
local b = v.blocks :: Types.VoxelBlocks
local n = v.size[1] * v.size[2] * v.size[3]
local cells, legacy = table.create(n), table.create(n)
for i = 0, n - 1 do
local st = b.palette[buffer.readu16(b.data, i * 2) + 1]
cells[i + 1] = st
local id, d = Mc.legacyId(st)
legacy[i + 1] = if id then id * 16 + (d :: number) else -1
end
local tr = node.translation :: { number }
table.insert(out, { name = node.name, min = tr, size = v.size, cells = table.concat(cells, "\n"), legacy = legacy, voxels = v, blockEntities = #(b.blockEntities or {}) })
end
return out
end
local function sameRegion(got: any, want: any, label: string)
t:eq(got.size[1] .. "," .. got.size[2] .. "," .. got.size[3], want.size[1] .. "," .. want.size[2] .. "," .. want.size[3], label .. ": size")
t:eq(got.min[1] .. "," .. got.min[2] .. "," .. got.min[3], want.min[1] .. "," .. want.min[2] .. "," .. want.min[3], label .. ": minimum corner")
if want.cells then
t:eq(got.cells, want.cells, label .. ": cells")
else
local bad = 0
for i, x in want.legacy do
if got.legacy[i] ~= x then
bad += 1
end
end
t:eq(bad, 0, label .. ": legacy ids")
end
end
-- 1. reference files
local decoded: { [string]: Types.Scene } = {}
for _, c in Fx.cases do
local scene, err = dec(c.data)
t:check(scene ~= nil, c.name .. ": " .. tostring(err))
local s = scene :: Types.Scene
decoded[c.name] = s
t:eq(s.meta.source.variant, c.variant, c.name .. ": variant")
if c.version > 0 then
t:eq(s.meta.source.version, c.version, c.name .. ": version")
end
local regs = regions(s)
t:eq(#regs, #c.regions, c.name .. ": regions")
local bes = 0
for i, want in c.regions do
sameRegion(regs[i], want, c.name .. " region " .. i)
if want.name ~= "" then
t:eq(regs[i].name, want.name, c.name .. " region " .. i .. ": name")
end
bes += regs[i].blockEntities
end
t:eq(bes, c.blockEntities, c.name .. ": block entities")
-- colours: air is empty, the rest coloured from the default table
local v = regs[1].voxels
local b = v.blocks
for i = 0, v.size[1] * v.size[2] * v.size[3] - 1 do
local st = b.palette[buffer.readu16(b.data, i * 2) + 1]
local idx = buffer.readu8(v.data, i)
if Mc.isAir(st) ~= (idx == 0) then
t:check(false, c.name .. ": cell " .. i .. " colour index " .. idx .. " for " .. st)
end
if idx > 0 then
local col, p = Mc.color(st) :: { number }, v.palette[idx]
if col[1] ~= p[1] or col[2] ~= p[2] or col[3] ~= p[3] then
t:check(false, c.name .. ": cell " .. i .. " colour of " .. st)
end
end
end
-- the same variant again: the same NBT (every field), the same cells
local out, eerr = Schematic.encode(s)
t:check(out ~= nil, c.name .. ": encode " .. tostring(eerr))
local again = assert(dec(out :: buffer))
t:eq(Nbt.print(again.meta.source.nbt), Nbt.print(s.meta.source.nbt), c.name .. ": same NBT")
t:eq(again.meta.source.rootName, s.meta.source.rootName, c.name .. ": root name")
for i, r in regions(again) do
sameRegion(r, regs[i], c.name .. " again region " .. i)
end
-- api: detection by content (the flavour) and loading
t:eq(F.detect(c.data), c.variant, c.name .. ": F.detect")
local viaApi = F.load(c.data)
t:check(viaApi and viaApi.kind == "scene", c.name .. ": F.load")
end
-- 2. our encodings read back by litemapy / nbtlib (fixture step)
local outputs: { [string]: () -> (buffer?, any) } = {}
local function colorGrid(): Types.Voxels
local v = Types.Voxels.new(4, 3, 2)
v.palette[1] = { 160, 40, 35, 255 }
v.palette[2] = { 125, 125, 125, 255 }
v.palette[3] = { 60, 110, 230, 120 }
for i = 0, 4 * 3 * 2 - 1 do
buffer.writeu8(v.data, i, i % 4)
end
return v
end
outputs["litemapy.litematic"] = function() return Schematic.encode(decoded.litemapy) end
outputs["litemapy.schem"] = function() return Schematic.encode(decoded.litemapy, { variant = "schem", version = 2 }) end
outputs["sponge2.schem"] = function() return Schematic.encode(decoded.sponge2) end
outputs["sponge2.litematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "litematic" }) end
outputs["sponge3.schem"] = function() return Schematic.encode(decoded.sponge3) end
outputs["sponge3v2.schem"] = function() return Schematic.encode(decoded.sponge3, { version = 2 }) end
outputs["sponge1.schem"] = function() return Schematic.encode(decoded.sponge1) end
outputs["mcedit.schematic"] = function() return Schematic.encode(decoded.mcedit) end
outputs["worldedit_add.schematic"] = function() return Schematic.encode(decoded.worldedit_add) end
outputs["sponge2.schematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "schematic" }) end
outputs["mcedit.schem"] = function() return Schematic.encode(decoded.mcedit, { variant = "schem" }) end
outputs["colors.schem"] = function() return Schematic.encode(colorGrid()) end
outputs["colors.litematic"] = function() return Schematic.encode(colorGrid(), { variant = "litematic" }) end
outputs["colors.schematic"] = function() return Schematic.encode(colorGrid(), { variant = "schematic" }) end
local count = 0
for name, ref in Ours do
local make = outputs[name]
t:check(make ~= nil, name .. ": known output")
local mine = assert(dec(assert(make())))
local regs = regions(mine)
t:eq(#regs, #ref.regions, name .. ": regions read back")
for i, want in ref.regions do
sameRegion(regs[i], want, name .. " (reference) region " .. i)
end
if ref.litemapy then
t:eq(ref.litemapy, regs[1].cells, name .. ": litemapy's Sponge reader")
end
count += 1
end
t:eq(count, 14, "every output checked")
-- the source cells survive the conversions
do
local function cellsVia(name: string): string
return regions(assert(dec(assert(outputs[name]()))))[1].cells
end
t:eq(cellsVia("sponge2.litematic"), regions(decoded.sponge2)[1].cells, "schem -> litematic cells")
t:eq(cellsVia("sponge3v2.schem"), regions(decoded.sponge3)[1].cells, "v3 -> v2 cells")
local legacy = regions(assert(dec(assert(outputs["mcedit.schem"]()))))[1].legacy
local src = regions(decoded.mcedit)[1].legacy
t:eq(table.concat(legacy, ","), table.concat(src, ","), "schematic -> schem keeps legacy states")
-- litematic -> schem merges the regions into one grid covering them all
local merged = regions(assert(dec(assert(outputs["litemapy.schem"]()))))[1]
t:eq(merged.size[1] .. "," .. merged.size[2] .. "," .. merged.size[3], "31,5,12", "merged size")
-- colour grid -> blocks by colour
local cg = regions(assert(dec(assert(outputs["colors.schem"]()))))[1]
local first = string.split(cg.cells, "\n")
t:eq(first[1], "minecraft:air", "empty cell -> air")
t:eq(first[2], "minecraft:red_wool", "red -> red wool")
t:eq(first[4], "minecraft:light_blue_stained_glass", "translucent blue -> stained glass")
end
-- 3. through the api
do
local scene = assert(F.load(Fx.cases[1].data, { name = "x.litematic" }))
local schem = assert(F.save(scene, nil, { format = "schem" })) :: buffer
t:eq(F.detect(schem), "schem", "F.save format = schem")
local lite = assert(F.save(scene, nil, { format = "litematic" })) :: buffer
t:eq(F.detect(lite), "litematic", "F.save format = litematic")
local legacy = assert(F.save(scene, nil, { format = "schematic", variant = "schematic" })) :: buffer
t:eq(F.detect(legacy), "schematic", "variant schematic")
t:eq(F.detect(legacy, { name = "a.schematic" }), "schematic", "detect with a name")
-- a vox-like grid without blocks through F.save
local g = Types.Voxels.new(2, 2, 2)
buffer.writeu8(g.data, 0, 5)
t:check(F.save(g, nil, { format = "schem" }) ~= nil, "save a bare Voxels")
end
-- 4. errors
do
local _, e1 = dec(assert(Nbt.encode(Nbt.compound({ a = 1 }, { "a" }))))
t:check(e1 and e1.code == Err.CORRUPT, "not a schematic")
local _, e2 = dec(Fx.cases[1].data, { maxCells = 10 })
t:check(e2 and e2.code == Err.LIMIT, "maxCells")
local _, e3 = Schematic.encode({ kind = "scene" } :: any)
t:check(e3 and e3.code == Err.ARG, "encode without voxels")
local _, e4 = Schematic.encode(colorGrid(), { variant = "x" :: any })
t:check(e4 and e4.code == Err.ARG, "unknown variant")
local bad = Nbt.compound({ Width = Nbt.short(4), Height = Nbt.short(4), Length = Nbt.short(4), Blocks = buffer.create(10) }, { "Width", "Height", "Length", "Blocks" })
local _, e5 = dec(assert(Nbt.encode(bad, { name = "Schematic" })))
t:check(e5 and e5.code == Err.TRUNCATED, "short Blocks")
end
-- 5. fuzz (the uncompressed NBT too, so mutations reach the layouts, not just gzip's CRC)
local samples = {}
for _, c in Fx.cases do
local s = assert(dec(c.data))
table.insert(samples, (assert(Nbt.encode(s.meta.source.nbt, { name = s.meta.source.rootName, compression = "none" }))))
end
table.insert(samples, Fx.cases[1].data)
t:fuzz("decode", function(b: buffer)
return Schematic.decode(Bytes.reader(b))
end, samples)
t:done()
+49
View File
@@ -0,0 +1,49 @@
-- tools/fixtures/schematic.py helper: our model/schematic encoder's output for the reference readers (litemapy,
-- nbtlib). Prints "<name>\t<hex>" lines. Inputs: the decoded fixtures of tests/gen/schematic, plus grids built here.
local Schematic = require("@formats/model/schematic")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/schematic")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local function emit(name: string, b: buffer?, e: any)
if not b then
error(name .. ": " .. tostring(e))
end
print(name .. "\t" .. hex(b))
end
local byName = {}
for _, c in Fx.cases do
byName[c.name] = assert(Schematic.decode(Bytes.reader(buffer.fromstring(c.data))))
end
-- same variant (fields kept), and across variants
emit("litemapy.litematic", Schematic.encode(byName.litemapy))
emit("litemapy.schem", Schematic.encode(byName.litemapy, { variant = "schem", version = 2 }))
emit("sponge2.schem", Schematic.encode(byName.sponge2))
emit("sponge2.litematic", Schematic.encode(byName.sponge2, { variant = "litematic" }))
emit("sponge3.schem", Schematic.encode(byName.sponge3))
emit("sponge3v2.schem", Schematic.encode(byName.sponge3, { version = 2 }))
emit("sponge1.schem", Schematic.encode(byName.sponge1))
emit("mcedit.schematic", Schematic.encode(byName.mcedit))
emit("worldedit_add.schematic", Schematic.encode(byName.worldedit_add))
emit("sponge2.schematic", Schematic.encode(byName.sponge2, { variant = "schematic" }))
emit("mcedit.schem", Schematic.encode(byName.mcedit, { variant = "schem" }))
-- a colour grid (no block states): each palette colour becomes the block nearest in colour
local v = Types.Voxels.new(4, 3, 2)
v.palette[1] = { 160, 40, 35, 255 }
v.palette[2] = { 125, 125, 125, 255 }
v.palette[3] = { 60, 110, 230, 120 }
for i = 0, 4 * 3 * 2 - 1 do
buffer.writeu8(v.data, i, i % 4)
end
emit("colors.schem", Schematic.encode(v))
emit("colors.litematic", Schematic.encode(v, { variant = "litematic" }))
emit("colors.schematic", Schematic.encode(v, { variant = "schematic" }))
+1
View File
@@ -119,6 +119,7 @@ def varints(idx):
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))