--!strict -- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft -- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads -- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over -- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, -- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). -- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks -- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with -- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its -- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, -- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header -- and one chunk's NBT without building voxels. -- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the -- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Deflate = require("@formats/codecs/compress/Deflate") local Nbt = require("@formats/codecs/text/Nbt") local Mc = require("@formats/codecs/model/Minecraft") local Chunk = require("@formats/model/mca/Chunk") local Lz4Block = require("@formats/model/mca/Lz4Block") -- ------------------------------------------------------------------------------------------------ contract local Mca = { name = "mca", category = "model", extensions = { "mca", "mcr" }, mime = { "application/x-minecraft-region" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, caps = { decode = true, encode = false, voxels = true, blocks = true }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files name: string?, -- the file name (the api fills it in) resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc } export type Entry = { x: number, -- local chunk coordinates 0 .. 31 z: number, sector: number, -- 4 KiB sector of the chunk sectors: number, timestamp: number, -- seconds since 1970 } -- ------------------------------------------------------------------------------------------------ constants local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } -- ------------------------------------------------------------------------------------------------ sniff function Mca.sniff(r: Bytes.Reader): number local n = r.limit - r.base if n < 8192 then return 0 end local sectors = (n + 4095) // 4096 local used, b = 0, r.buf for i = 0, 1023 do local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) if e ~= 0 then local off, cnt = e // 256, e % 256 if off < 2 or cnt == 0 or off + cnt > sectors then return 0 end used += 1 if used == 1 then local p = r.base + off * 4096 if p + 5 > r.limit then return 0 end local c = buffer.readu8(b, p + 4) % 128 if COMPRESSION[c] == nil then return 0 end end end end return if used > 0 then 0.8 else 0.2 end -- ------------------------------------------------------------------------------------------------ decode -- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) local n = r.limit - r.base if n < 8192 then return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) end local out: { Entry } = {} for i = 0, 1023 do local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) if e ~= 0 then table.insert(out, { x = i % 32, z = i // 32, sector = e // 256, sectors = e % 256, timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), }) end end return out, nil end local function regionCoords(o: DecodeOptions): (number?, number?) if o.region then return o.region[1], o.region[2] end if o.name then local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") if x then return tonumber(x), tonumber(z) end end return nil, nil end -- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) local p = r.base + e.sector * 4096 if p + 5 > r.limit then return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) end local len = bit32.byteswap(buffer.readu32(r.buf, p)) local ctype = buffer.readu8(r.buf, p + 4) local data: buffer, start: number, size: number = r.buf, p + 5, len - 1 if ctype >= 128 then -- stored in c...mcc next to the region (whole file = the compressed payload) local rx, rz = regionCoords(o) if not o.resolve or rx == nil then return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) end local name = string.format("c.%d.%d.mcc", (rx :: number) * 32 + e.x, (rz :: number) * 32 + e.z) local ext = o.resolve(name) if type(ext) ~= "buffer" then return nil, Err.new(Err.IO, "cannot read " .. name) end data, start, size = ext, 0, buffer.len(ext) ctype -= 128 elseif len < 1 or p + 4 + len > r.limit then return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) end local comp = COMPRESSION[ctype] local maxBytes = o.maxBytes or 2 ^ 26 local out, err if comp == "gzip" then out, err = Deflate.gunzip(data, start, size) elseif comp == "zlib" then out, err = Deflate.zlib(data, start, size) elseif comp == "none" then out = buffer.create(size :: number) buffer.copy(out, 0, data, start, size) elseif comp == "lz4" then local msg out, msg = Lz4Block.decode(data, start, size :: number, maxBytes) if not out then err = Err.from(msg, start - r.base) end else return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) end if not out then return nil, err end if buffer.len(out) > maxBytes then return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) end return out, comp end -- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) local o: DecodeOptions = opts or {} if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") end local entries, lerr = Mca.list(r) if not entries then return nil, lerr end for _, e in entries do if e.x == x and e.z == z then local raw, comp = payload(r, e, o) if not raw then return nil, comp end local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) if v == nil then return nil, info end return v, comp end end return nil, nil end function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local o: DecodeOptions = opts or {} local entries, lerr = Mca.list(r) if not entries then return nil, lerr end local want: { [number]: boolean }? = nil if o.chunks then local w: { [number]: boolean } = {} for _, c in o.chunks do w[(c[1] or 0) + 32 * (c[2] or 0)] = true end want = w end local area = o.area if area and #area ~= 6 then return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") end local keep = o.keepNbt ~= false local chunks: { Chunk.Blocks } = {} local infos = {} for _, e in entries do if not want or want[e.x + 32 * e.z] then local raw, comp = payload(r, e, o) if not raw then return nil, comp end local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) if v == nil then return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) end local blocks, berr = Chunk.blocks(v) if not blocks then return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) end local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) if inArea then table.insert(chunks, blocks) table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = if keep then v else nil }) end end end -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, c in chunks do lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) for _, s in c.sections do local solid = false for _, st in s.states do if not Mc.isAir(st) then solid = true break end end if solid then lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) end end end if area then for k = 1, 3 do lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) if area[k] > area[k + 3] then return nil, Err.new(Err.ARG, "area minimum past its maximum") end end if lo[2] == math.huge then lo[2], hi[2] = area[2], area[5] end end if lo[2] == math.huge then lo[2], hi[2] = 0, -1 -- no blocks at all end if #chunks == 0 then lo, hi = { 0, 0, 0 }, { -1, -1, -1 } end local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) local n = sx * sy * sz if n > (o.maxCells or 2 ^ 25) then return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) end -- one palette for the grid (air first), each section copied in through a remap table local states = { "minecraft:air" } local index: { [string]: number } = { ["minecraft:air"] = 0 } local grid = buffer.create(n * 2) local bes, ents = {}, {} for _, c in chunks do local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] for _, s in c.sections do local cy = s.y * 16 - lo[2] if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then local lut = table.create(#s.states) :: { number } for i, st in s.states do local g = index[st] if g == nil then table.insert(states, st) g = #states - 1 index[st] = g end lut[i] = g end if #states > 65536 then return nil, Err.new(Err.LIMIT, "more than 65536 block states") end local cells = s.cells local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) for y = y0, y1 do for z = z0, z1 do local src = ((y * 16 + z) * 16 + x0) * 2 local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 for _ = x0, x1 do buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) src += 2 dst += 2 end end end end end for _, rec in c.blockEntities do local be = Mc.blockEntity(rec, "flat") if be then local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then be.pos = { px, py, pz } table.insert(bes, be) end end end for _, ent in c.entities do table.insert(ents, ent) end end local v = Mc.voxels(sx, sy, sz, states, grid) local b = v.blocks :: Types.VoxelBlocks b.blockEntities = bes b.entities = ents local scene = Types.Scene.new() scene.voxels = { v } scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } scene.roots = { 1 } scene.meta.up = "y" scene.meta.unit = 1 local rx, rz = regionCoords(o) scene.meta.source = { format = "mca", region = if rx then { rx, rz } else nil, chunks = infos } return scene, nil end return Mca