--!strict -- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the -- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA -- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 -- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. -- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as -- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view -- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and -- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). -- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; -- options default to the source file's settings. -- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -- ------------------------------------------------------------------------------------------------ contract local Qb = { name = "qb", category = "model", extensions = { "qb" }, mime = { "model/x-qubicle" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, voxels = true, truecolor = true }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) } export type EncodeOptions = { compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) } -- ------------------------------------------------------------------------------------------------ constants local CODEFLAG, NEXTSLICEFLAG = 2, 6 -- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 -- ------------------------------------------------------------------------------------------------ sniff function Qb.sniff(r: Bytes.Reader): number if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then return 0 end local b, p = r.buf, r.pos local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) if fmt > 1 or z > 1 or comp > 1 or mask > 1 then return 0 end return 0.9 end -- ------------------------------------------------------------------------------------------------ decode -- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them local function indexed(v: Types.Voxels, colors: buffer, n: number) local count: { [number]: number } = {} for i = 0, n - 1 do local c = buffer.readu32(colors, i * 4) if c >= 0x1000000 then -- alpha > 0: filled local rgb = c % 0x1000000 local k = count[rgb] if k == nil then count[rgb] = 1 else count[rgb] = k + 1 end end end local order = {} for rgb in count do table.insert(order, rgb) end table.sort(order, function(a: number, b: number): boolean if count[a] ~= count[b] then return count[a] > count[b] end return a < b end) local slot: { [number]: number } = {} for i = 1, math.min(255, #order) do local rgb = order[i] slot[rgb] = i v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 } end for i = 256, #order do local rgb = order[i] local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536 local best, bd = 1, math.huge for k = 1, 255 do local p = v.palette[k] local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 if d < bd then best, bd = k, d end end slot[rgb] = best end for i = 0, n - 1 do local c = buffer.readu32(colors, i * 4) buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0) end end function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local o: DecodeOptions = opts or {} local maxCells = o.maxCells or 2 ^ 27 local ver = r:string(4) local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() if r.err then return nil, r.err end if ver ~= "\1\1\0\0" then return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) end if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then return nil, Err.new(Err.CORRUPT, "bad header flags", 4) end if count > r:remaining() // 25 then return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) end local scene = Types.Scene.new() local grids: { Types.Voxels } = {} scene.voxels = grids local total = 0 local bgra = fmt == 1 for m = 1, count do local at = r:tell() local nameLen = r:u8() local name = r:string(nameLen) local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() local px, py, pz = r:i32le(), r:i32le(), r:i32le() if r.err then return nil, r.err end if sx * sy * sz + total > maxCells then return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) end local n = sx * sy * sz total += n local colors = buffer.create(n * 4) local b = r.buf local function put(x: number, y: number, z: number, c: number) if bgra then -- b, g, r, a -> r, g, b, a c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216 end if c < 0x1000000 then c = 0 -- alpha 0: empty end local zz = if zAxis == 0 then sz - 1 - z else z buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) end if compressed == 0 then if not r:need(n * 4) then return nil, r.err end local p = r.pos for z = 0, sz - 1 do for y = 0, sy - 1 do for x = 0, sx - 1 do put(x, y, z, buffer.readu32(b, p)) p += 4 end end end r.pos = p else local slice = sx * sy for z = 0, sz - 1 do local index = 0 while true do local d = r:u32le() if r.err then return nil, r.err end if d == NEXTSLICEFLAG then break elseif d == CODEFLAG then local run, c = r:u32le(), r:u32le() if r.err then return nil, r.err end if index + run > slice then return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) end for _ = 1, run do put(index % sx, index // sx, z, c) index += 1 end else if index >= slice then return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) end put(index % sx, index // sx, z, d) index += 1 end end end end local v = Types.Voxels.new(sx, sy, sz) v.name = name v.colors = colors indexed(v, colors, n) table.insert(grids, v) local tz = if zAxis == 0 then 0 - (pz + sz) else pz table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) table.insert(scene.roots, #scene.nodes) end scene.meta.up = "y" scene.meta.source = { format = "qb", colorFormat = if bgra then "bgra" else "rgba", rightHanded = zAxis == 1, compressed = compressed == 1, visibilityMask = mask == 1, } return scene, nil end -- ------------------------------------------------------------------------------------------------ encode local function cellColor(v: Types.Voxels, i: number): number if v.colors then return buffer.readu32(v.colors, i * 4) end local idx = buffer.readu8(v.data, i) if idx == 0 then return 0 end local p = v.palette[idx] or { 0, 0, 0, 255 } return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 end function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {} local function add(v: any, name: string?, pos: { number }): string? if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then return "expected Types.Voxels grids" end local n = v.size[1] * v.size[2] * v.size[3] if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then return "voxel data shorter than its size" end local nm = name or v.name or ("matrix" .. (#grids + 1)) if #nm > 255 then return "matrix name longer than 255 bytes" end table.insert(grids, { v = v, name = nm, pos = pos }) return nil end local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil if type(value) == "table" and value.kind == "voxels" then local e = add(value, nil, { 0, 0, 0 }) if e then return nil, Err.new(Err.ARG, e) end elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then local used: { [number]: boolean } = {} local function walk(i: number, base: { number }, depth: number): string? local node = value.nodes[i] if type(node) ~= "table" or depth > 64 then return nil end local t = node.translation or { 0, 0, 0 } local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } if node.voxels and value.voxels[node.voxels] then used[node.voxels] = true local e = add(value.voxels[node.voxels], node.name, p) if e then return e end end for _, c in node.children or {} do local e = walk(c, p, depth + 1) if e then return e end end return nil end for _, root in value.roots or {} do local e = walk(root, { 0, 0, 0 }, 0) if e then return nil, Err.new(Err.ARG, e) end end for i, v in value.voxels do if not used[i] then local e = add(v, nil, { 0, 0, 0 }) if e then return nil, Err.new(Err.ARG, e) end end end else return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") end local function pick(opt: any, key: string, default: any): any if opt ~= nil then return opt elseif src and src[key] ~= nil then return src[key] end return default end local compressed = pick(o.compressed, "compressed", true) local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" local right = pick(o.rightHanded, "rightHanded", true) local mask = pick(o.visibilityMask, "visibilityMask", false) local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks local w = Bytes.writer(1024) w:string("\1\1\0\0") w:u32le(if bgra then 1 else 0) w:u32le(if right then 1 else 0) w:u32le(if compressed then 1 else 0) w:u32le(if mask then 1 else 0) w:u32le(#grids) for _, g in grids do local v = g.v local sx, sy, sz = v.size[1], v.size[2], v.size[3] w:u8(#g.name) w:string(g.name) w:u32le(sx) w:u32le(sy) w:u32le(sz) local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) w:u32le(px % 4294967296) w:u32le(py % 4294967296) w:u32le((if right then pz else -pz - sz) % 4294967296) local function filled(x: number, y: number, z: number): boolean if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then return false end return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 end -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked local function value(x: number, y: number, z: number): number local zz = if right then z else sz - 1 - z local c = cellColor(v, x + sx * (y + sy * zz)) if c < 0x1000000 then return 0 end local a = c // 16777216 if mask and not keepMask then a = 1 if not filled(x - 1, y, zz) then a += LEFT end if not filled(x + 1, y, zz) then a += RIGHT end if not filled(x, y + 1, zz) then a += TOP end if not filled(x, y - 1, zz) then a += BOTTOM end if not filled(x, y, zz + 1) then a += FRONT end if not filled(x, y, zz - 1) then a += BACK end elseif not mask and src and src.visibilityMask then a = 255 -- masks are not colours end local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256 if bgra then r, b = b, r end return r + gg * 256 + b * 65536 + a * 16777216 end for z = 0, sz - 1 do if compressed then local x, y = 0, 0 local slice = sx * sy local i = 0 while i < slice do x, y = i % sx, i // sx local c = value(x, y, z) local run = 1 while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do run += 1 end if run > 2 then w:u32le(CODEFLAG) w:u32le(run) w:u32le(c) else for _ = 1, run do w:u32le(c) end end i += run end w:u32le(NEXTSLICEFLAG) else for y = 0, sy - 1 do for x = 0, sx - 1 do w:u32le(value(x, y, z)) end end end end end return w:finish(), nil end return Qb