From 2be536bd98801296f0b9045d66a8ad943d08661a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:56:33 -0500 Subject: [PATCH] ws-voxel: docs/guide/voxel.md (NBT / SNBT, schematics, regions, Qubicle; tested snippets) + inputs generator; bench lines for NBT, SNBT, packed arrays, schem, qb --- docs/guide/README.md | 1 + docs/guide/data.md | 3 +- docs/guide/scene.md | 5 ++ docs/guide/voxel.md | 145 +++++++++++++++++++++++++++++++++++ tools/bench.luau | 78 +++++++++++++++++++ tools/fixtures/docs_voxel.py | 84 ++++++++++++++++++++ 6 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 docs/guide/voxel.md create mode 100644 tools/fixtures/docs_voxel.py diff --git a/docs/guide/README.md b/docs/guide/README.md index d1fff6c..b9c2a72 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -18,6 +18,7 @@ and the host notes. Each standard type has its own page: | [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont | | [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 | | [Data](data.md) | plain values, `XmlNode`, `Date` | JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist | +| [Minecraft and voxels](voxel.md) | typed values, `Scene` + `Voxels` | NBT, SNBT, `.schem` / `.schematic` / `.litematic`, Anvil `.mca`, Qubicle `.qb` | | [Vector](vector.md) | `Vector` | SVG | | [Layered images](layered.md) | `Layered` | PSD, Aseprite | | [Tile maps](tilemap.md) | `TileMap` | Tiled TMX / TMJ | diff --git a/docs/guide/data.md b/docs/guide/data.md index 3b40019..46a6d52 100644 --- a/docs/guide/data.md +++ b/docs/guide/data.md @@ -3,7 +3,8 @@ The data formats (JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist) decode to plain Luau values: tables, strings, numbers, booleans. Three helpers fill the gaps Luau tables leave: `F.data.null` (a null that can sit in a table), ordered objects (`F.Types.object`: key order, and `{}` that stays an object), and `F.Types.Date` (TOML, -YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. +YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. Minecraft's NBT and SNBT (typed +numbers kept) are on the [Minecraft and voxels](voxel.md) page. ```luau local v = assert(F.data.load('{"name": "ada", "tags": ["x", "y"], "boss": null}')) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..659ecd4 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -329,6 +329,8 @@ node that shows a model has `node.voxels` (an index into `scene.voxels`) and no | `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` | | `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models | | `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties | +| `blocks` | `{ palette, data, blockEntities?, entities? }?` | Minecraft grids: the exact block state of every cell ([voxel.md](voxel.md)) | +| `colors` | `buffer?` | true-colour grids (Qubicle): r, g, b, a bytes per cell | ```luau local V = F.Types.Voxels @@ -392,6 +394,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| Minecraft `.schem` / `.schematic` / `.litematic` | yes | yes | block grids, see [voxel.md](voxel.md) | +| Minecraft region `.mca` | yes | | block grids of chosen chunks, see [voxel.md](voxel.md) | +| Qubicle `.qb` | yes | yes | true-colour grids, see [voxel.md](voxel.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/docs/guide/voxel.md b/docs/guide/voxel.md new file mode 100644 index 0000000..5371656 --- /dev/null +++ b/docs/guide/voxel.md @@ -0,0 +1,145 @@ +# Minecraft and voxel files + +Minecraft's NBT data, its schematics (`.schem`, `.schematic`, `.litematic`) and region files (`.mca`), and Qubicle +`.qb` models. NBT and SNBT load as plain values (the [Data](data.md) category); schematics, regions and Qubicle files +load as a `Scene` whose `scene.voxels` holds `Voxels` grids (see [3D scenes](scene.md#voxels)), so they mesh and save +like a `.vox`. + +| Format | Read | Write | Value | +|---|---|---|---| +| NBT (`.nbt`, `.dat`, `.mcstructure`) | yes | yes | typed plain values; Java big-endian, Bedrock little-endian, gzip / zlib / raw | +| SNBT (`.snbt`) | yes | yes | the same values as text | +| Sponge `.schem` v1 / v2 / v3 | yes | yes | Scene, one grid with block states | +| MCEdit / WorldEdit `.schematic` | yes | yes | Scene; pre-1.13 numeric ids | +| Litematica `.litematic` | yes | yes | Scene, one grid per region | +| Anvil region `.mca` | yes | | Scene, the chosen chunks as one grid, plus each chunk's NBT | +| Qubicle `.qb` | yes | yes | Scene, one grid per matrix, exact colours | + +## NBT and SNBT + +NBT values are plain Luau with their tag type kept, so what you load saves back the same: + +| NBT tag | Luau value | +|---|---| +| int | number | +| string | string | +| byte array | buffer | +| compound | ordered table (`F.Types.object`, keys in file order) | +| list | array (its element type: `Nbt.listType(list)`) | +| byte, short, long, float, double | a tag `{ type = "byte", value = 1 }` (`tostring` gives SNBT: `1b`); longs past 2^53 hold their exact decimal text | +| int array, long array | a tag with `value` = numbers / a buffer of 8-byte little-endian longs | + +```luau +local level = assert(F.load(levelDatBytes, { name = "level.dat" })) -- gzip NBT +local data = level.Data +assert(data.LevelName == "My World" and data.SpawnY == 64) -- ints and strings are plain +assert(data.Difficulty.type == "byte" and data.Difficulty.value == 2) +assert(data.RandomSeed.value == "-4011880356862312345") -- past 2^53: exact text +assert(tostring(data.Player.Health) == "20.0f") + +local Nbt = F.format("nbt").Nbt -- the engine: codecs/text/Nbt +data.Difficulty = Nbt.byte(3) +data.Tags = Nbt.list("string", { "a", "b" }) +local saved = assert(F.save(level, nil, { format = "nbt" })) -- gzip again, like the source +assert(F.load(saved, { format = "nbt" }).Data.Difficulty.value == 3) +local info = F.format("nbt").info(level) -- how it was stored +assert(info.compression == "gzip" and info.endian == "big" and info.name == "") +``` + +Plain inputs work too: a whole number writes as an int, other numbers as a double, `true` / `false` as bytes, a table +with string keys as a compound and an array as a list. Bedrock files (little-endian, with or without the `level.dat` +header) are detected; `endian = "little"`, `varint = true` (network NBT) and `compression` force a layout when saving. + +```luau +local text = assert(F.convert(levelDatBytes, "snbt", { format = "nbt" })) -- NBT -> SNBT text +assert(string.find(buffer.tostring(text), 'LevelName:"My World"', 1, true)) +local v = assert(F.load("{pos:[I;1,2,3],name:'x',scale:1.5f,big:9007199254740993L}", { format = "snbt" })) +assert(v.pos.value[2] == 2 and v.scale.type == "float" and v.big.value == "9007199254740993") +assert(F.saveString(v, { format = "snbt" }) == '{pos:[I;1,2,3],name:"x",scale:1.5f,big:9007199254740993L}') +local pretty = assert(F.saveString(v, { format = "snbt", indent = 2 })) +local bedrock = assert(F.save(v, nil, { format = "nbt", endian = "little", compression = "none" })) +``` + +## Schematics + +A schematic loads as a Scene with `meta.up = "y"` and one unit per block. Each grid has its usual colour view +(`data` / `palette`, from a built-in table of block colours) and `voxels.blocks` with the exact blocks: + +| `voxels.blocks` field | Meaning | +|---|---| +| `palette` | block states (`"minecraft:oak_log[axis=y]"`), entry 1 is index 0 | +| `data` | a buffer, one u16 per cell (same cell order as `voxels.data`): the 0-based palette index | +| `blockEntities` | `{ { pos = { x, y, z }, id, data } }`: chests, signs, ... (`data` is their NBT) | +| `entities` | entity NBT records | + +```luau +local scene = assert(F.load(schemBytes)) -- detected by content: F.detect gives "schem" +local grid = scene.voxels[1] +assert(grid.size[1] == 5 and grid.size[2] == 4) -- x, y (up), z +local blocks = grid.blocks +local function blockAt(x: number, y: number, z: number): string + local i = x + grid.size[1] * (y + grid.size[2] * z) + return blocks.palette[buffer.readu16(blocks.data, i * 2) + 1] +end +assert(blockAt(0, 0, 0) == "minecraft:stone" and blockAt(2, 2, 0) == "minecraft:glass") +assert(F.Types.Voxels.get(grid, 1, 1, 1) == 0) -- air is empty in the colour view + +local lite = assert(F.load(litematicBytes)) +assert(#lite.voxels == 2 and lite.nodes[2].name == "pillar") -- a node per region, placed by translation +local legacy = assert(F.save(lite, nil, { format = "schematic", variant = "schematic" })) -- regions merged +local schem = assert(F.save(lite, nil, { format = "schem" })) -- Sponge v3 +assert(F.detect(schem) == "schem") +``` + +`F.save` picks the flavour from `variant`, the destination's extension (`"out.litematic"`), `format = "schem"` / +`"litematic"`, or the loaded file's. A grid without `blocks` (a `.vox`, a `.qb`) gets the block nearest in colour for +each palette colour, so converting voxel art works: + +```luau +local vox = assert(F.load(voxBytes)) +local schem = assert(F.save(vox, nil, { format = "schem" })) +local back = assert(F.load(schem)) +assert(back.voxels[1].blocks.palette[1] == "minecraft:air") +``` + +## Region files + +An Anvil region holds 32 x 32 chunks. Loading it builds one grid over the chunks you pick (`chunks = { { x, z } }`, +local 0..31), or the blocks inside `area = { minX, minY, minZ, maxX, maxY, maxZ }` (world coordinates), between the +lowest and highest sections holding blocks; `maxCells` (default 2^25) guards against loading a whole world. + +```luau +local Mca = F.format("mca") +local region = assert(F.load(regionBytes, { name = "r.0.0.mca", chunks = { { 0, 0 }, { 1, 0 } } })) +local grid = region.voxels[1] +assert(grid.size[1] == 32 and grid.size[3] == 16) +local corner = region.nodes[1].translation -- the grid's world position +assert(corner[1] == 0 and corner[2] == -64) +local chunk = region.meta.source.chunks[1] +assert(chunk.dataVersion == 3953 and chunk.nbt.Status == "minecraft:full") -- the chunk's whole NBT + +local list = assert(Mca.list(F.Bytes.reader(regionBytes))) -- the chunks present, with timestamps +local nbt = assert(Mca.chunk(F.Bytes.reader(regionBytes), 3, 2)) +assert(nbt.xPos == 3) +``` + +All chunk layouts read: 1.18+ sections, 1.13 - 1.17 palettes and pre-1.13 numeric ids (as state names such as +`minecraft:red_wool`, with `[data=N]` for the rest of a data value). Chunk payloads may be gzip, zlib, LZ4 or stored; +chunks in external `.mcc` files load through `opts.resolve` (filled in when loading by path). Regions are read-only. + +## Qubicle + +Each matrix becomes a grid with `voxels.colors`, the exact colour of every cell (`r, g, b, a` bytes; `a = 0` is +empty), next to the indexed `data` / `palette` view. Left-handed files are mirrored into the scene's right-handed +axes; saving writes the source's settings unless `compressed`, `colorFormat` (`"rgba"` / `"bgra"`), `rightHanded` or +`visibilityMask` say otherwise. + +```luau +local box = assert(F.load(qbBytes)) +local grid = box.voxels[1] +local first = buffer.readu32(grid.colors, 0) -- r + g * 256 + b * 65536 + a * 2^24 +assert(first % 256 == 200 and first // 16777216 == 255) +assert(box.nodes[1].name == "box") +local again = assert(F.save(box, nil, { format = "qb", compressed = false })) +local vox = assert(F.save(box, nil, { format = "vox" })) -- or .schem, .glb after F.ops.mesh.meshVoxels +``` diff --git a/tools/bench.luau b/tools/bench.luau index e7d1364..59a36c4 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1091,3 +1091,81 @@ do jitTune(false) end end +do + -- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds) + -- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file + local Nbt = require("@formats/codecs/text/Nbt") + local Mc = require("@formats/codecs/model/Minecraft") + local Schematic = require("@formats/model/schematic") + local Qb = require("@formats/model/qb") + local sections = Nbt.list("compound") + for s = 1, 24 do + local pal = Nbt.list("compound") + for p = 1, 16 do + table.insert(pal, Nbt.compound({ Name = "minecraft:block_" .. p, Properties = Nbt.compound({ axis = "y" }, { "axis" }) }, { "Name", "Properties" })) + end + local longs = buffer.create(256 * 8) + for i = 0, 511 do + buffer.writeu32(longs, i * 4, (i * 2654435761) % 4294967296) + end + table.insert(sections, Nbt.compound({ Y = Nbt.byte(s - 5), block_states = Nbt.compound({ palette = pal, data = Nbt.longArray(longs) }, { "palette", "data" }) }, { "Y", "block_states" })) + end + local ents = Nbt.list("compound") + for i = 1, 4000 do + table.insert(ents, Nbt.compound({ + id = "minecraft:thing", + Pos = Nbt.list("double", { Nbt.double(i * 0.5), Nbt.double(64), Nbt.double(-i * 0.25) }), + Health = Nbt.float(20), + UUID = Nbt.intArray({ i, -i, i * 3, 7 }), + Tags = Nbt.list("string", { "a", "b" }), + Age = Nbt.short(i % 1000), + Seed = Nbt.long(i * 1234567), + }, { "id", "Pos", "Health", "UUID", "Tags", "Age", "Seed" })) + end + local root = Nbt.compound({ DataVersion = 3953, sections = sections, entities = ents }, { "DataVersion", "sections", "entities" }) + local raw = assert(Nbt.encode(root, { compression = "none" })) + bench("nbt decode (" .. buffer.len(raw) // 1000 .. " KB)", 5, buffer.len(raw), function() + Nbt.decode(raw) + end) + bench("nbt encode", 5, buffer.len(raw), function() + Nbt.encode(root, { compression = "none" }) + end) + local text = assert(Nbt.print(root)) + bench("snbt parse (" .. #text // 1000 .. " KB)", 3, #text, function() + Nbt.parse(text) + end) + bench("snbt print", 3, #text, function() + Nbt.print(root) + end) + local n = 1048576 + local idx = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(idx, i * 2, (i * 7) % 32) + end + local packed = Mc.Packed.pack(idx, n, 5, false) + local out = buffer.create(n * 2) + bench("packed unpack 1M x 5 bits (MB out)", 5, n * 2, function() + Mc.Packed.unpack(packed, 5, n, false, out, 32) + end) + local V = 64 + local states = { "minecraft:air" } + for i = 1, 40 do + table.insert(states, "minecraft:block_" .. i) + end + local cells = buffer.create(V * V * V * 2) + for i = 0, V * V * V - 1 do + buffer.writeu16(cells, i * 2, if (i // V) % 3 == 0 then 0 else 1 + (i // 97) % 40) + end + local grid = Mc.voxels(V, V, V, states, cells) + local schem = assert(Schematic.encode(grid, { compression = "none" })) + bench("schem decode 64^3 (MB of cells)", 3, V * V * V, function() + Schematic.decode(Bytes.reader(schem)) + end) + bench("schem encode 64^3", 3, V * V * V, function() + Schematic.encode(grid, { compression = "none" }) + end) + local qb = assert(Qb.encode(grid)) + bench("qb decode 64^3 rle (MB of cells)", 3, V * V * V, function() + Qb.decode(Bytes.reader(qb)) + end) +end diff --git a/tools/fixtures/docs_voxel.py b/tools/fixtures/docs_voxel.py new file mode 100644 index 0000000..5e3ff9f --- /dev/null +++ b/tools/fixtures/docs_voxel.py @@ -0,0 +1,84 @@ +# Docs inputs for the voxel guide page (docs/guide/voxel.md): a level.dat-like gzip NBT file and a Sponge v3 .schem +# (nbtlib), a two-region .litematic (litemapy), a small Anvil region from tools/fixtures/mca.py and a Qubicle file +# from tools/fixtures/qb.py's writer. +# tests/gen/docs_voxel.luau { files = { [name] = bytes }, vars = { levelDatBytes = ..., ... } } +import importlib.util, os, pickle, subprocess + +INPUTS = ["tools/docs_check.py", "tools/fixtures/mca.py", "tools/fixtures/qb.py"] + +BODY = r''' +import nbtlib, pickle, sys, io, gzip, os, tempfile +from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, IntArray, ByteArray +import numpy as np +from litemapy import Schematic, Region, BlockState +files = {} +level = Compound({"Data": Compound({"LevelName": String("My World"), "DataVersion": Int(3953), "Difficulty": Byte(2), + "RandomSeed": Long(-4011880356862312345), "SpawnX": Int(16), "SpawnY": Int(64), "SpawnZ": Int(-8), + "GameRules": Compound({"doDaylightCycle": String("true")}), + "Player": Compound({"Pos": List[Double]([Double(16.5), Double(64.0), Double(-7.5)]), "Health": Float(20.0)})})}) +f = nbtlib.File(level, root_name="") +buf = io.BytesIO() +f.write(buf) +files["level.dat"] = gzip.compress(buf.getvalue(), mtime=0) +# a 5 x 4 x 3 Sponge v3 schematic: a stone floor, oak planks walls, one glass block +w, h, l = 5, 4, 3 +states = ["minecraft:air", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass"] +idx = [] +for y in range(h): + for z in range(l): + for x in range(w): + idx.append(1 if y == 0 else (3 if (x, y, z) == (2, 2, 0) else (2 if x in (0, w - 1) else 0))) +s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l), + "Offset": IntArray([0, 0, 0]), "Metadata": Compound({"Name": String("hut")}), + "Blocks": Compound({"Palette": Compound({st: Int(i) for i, st in enumerate(states)}), + "Data": ByteArray(idx), "BlockEntities": List[Compound]([])})}) +buf = io.BytesIO() +nbtlib.File({"Schematic": s}, root_name="").write(buf) +files["hut.schem"] = gzip.compress(buf.getvalue(), mtime=0) +a = Region(0, 0, 0, 3, 2, 3) +for x in range(3): + for z in range(3): + a[x, 0, z] = BlockState("minecraft:cobblestone") +b = Region(5, 0, 0, 2, 3, 1) +for y in range(3): + b[0, y, 0] = BlockState("minecraft:oak_log", axis="y") +tmp = tempfile.mkdtemp() +p = os.path.join(tmp, "build.litematic") +Schematic(name="build", author="docs", regions={"floor": a, "pillar": b}).save(p) +files["build.litematic"] = open(p, "rb").read() +sys.stdout.buffer.write(pickle.dumps(files, protocol=4)) +''' + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_voxel_" + name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + try: + files = pickle.loads(ctx.python(["nbtlib", "litemapy", "numpy"], BODY)) + except subprocess.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) + mca = load(ctx, "mca") + regions = pickle.loads(ctx.python(["nbtlib", "numpy", "lz4", "xxhash"], mca.BODY))["regions"] + files["r.0.0.mca"] = regions[0]["data"] # 1.18+ chunks, every compression type + qb = load(ctx, "qb") + cells = {(x, y, z): ((200, 40, 40, 255) if y == 0 else (240, 240, 240, 255)) for x in range(3) for y in range(2) for z in range(3)} + files["box.qb"] = qb.write_qb([("box", (3, 2, 3), (0, 0, 0), cells)], False, True, True, False) + docs_check(ctx).emit_inputs(ctx, files, { + "levelDatBytes": "level.dat", + "schemBytes": "hut.schem", + "litematicBytes": "build.litematic", + "regionBytes": "r.0.0.mca", + "qbBytes": "box.qb", + })