--!strict -- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are -- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes -- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. -- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Chunks = require("@formats/containers/Chunks") local Mat4 = require("@formats/codecs/model/Mat4") local Read = {} export type Options = { resolve: ((uri: string) -> any)?, files: { [string]: any }?, maxVertices: number?, maxDepth: number?, } local LAYOUT: Chunks.Layout = { maxChunks = 1000000 } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } } type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number } type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } } type Bone = { node: number, target: MeshRec?, list: { number } } type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } -- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated -- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored local function vec(r: Bytes.Reader): { number } local x, y, z = r:f32le(), r:f32le(), r:f32le() return { x, y, -z } end local function quat(r: Bytes.Reader): { number } local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le() local l = math.sqrt(w * w + x * x + y * y + z * z) if l < 1e-12 or l ~= l then return { 0, 0, 0, 1 } end return { x / l, y / l, -z / l, w / l } end local function fetcher(opts: Options?): (string) -> buffer? local files = opts and opts.files local resolve = opts and opts.resolve return function(uri: string): buffer? local v: any = if type(files) == "table" then files[uri] else nil if v == nil and type(resolve) == "function" then local ok, res = pcall(resolve, uri) v = if ok then res else nil end return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil end end -- scene(r, opts) -> Scene | nil, message, kind function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) local buf = src.buf local maxVertices = opts and opts.maxVertices or 2 ^ 24 local maxDepth = opts and opts.maxDepth or 256 local fetch = fetcher(opts) local top = Chunks.walk(buf, src.base, src.limit, LAYOUT) local head = top[1] if not head or head.id ~= "BB3D" then return nil, "not a BB3D file", nil end if head.truncated then return nil, "truncated", "truncated" end local hr = Bytes.reader(buf, head.offset, head.size) local version = hr:i32le() if hr.err then return nil, "truncated", "truncated" end local scene = Types.Scene.new() local texs: { TexInfo } = {} local brushes: { Brush } = {} local materialOf: { [number]: number } = {} -- brush index (0-based) -> material local meshes: { MeshRec } = {} local bones: { Bone } = {} local nodeKeys: { [number]: Keys } = {} local anim: { frames: number, fps: number, flags: number }? = nil local lastMesh: MeshRec? = nil local totalVertices = 0 local failure: string?, failKind: string? = nil, nil local function fail(msg: string, kind: string?) if not failure then failure, failKind = msg, kind end end local function body(c: Chunks.Chunk): Bytes.Reader if c.truncated then fail("truncated " .. c.id .. " chunk", "truncated") end return Bytes.reader(buf, c.offset, c.avail) end local function readTexs(r: Bytes.Reader) while r.pos < r.limit and not r.err do local file = r:cstring() local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 } if r.err then return fail("truncated TEXS entry", "truncated") end local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] } local data = fetch(file) if not data then local base = string.match(file, "([^/\\]+)$") if base and base ~= file then data = fetch(base) end end tex.data = data if bit32.band(t.flags, 48) ~= 0 then tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" } end tex.extras = { b3d = { flags = t.flags, blend = t.blend } } table.insert(scene.textures, tex) t.index = #scene.textures table.insert(texs, t) end end local function readBrus(r: Bytes.Reader) local n = r:i32le() if r.err or n < 0 or n > 8 then return fail("bad BRUS texture count") end while r.pos < r.limit and not r.err do local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} } for i = 1, n do b.textures[i] = r:i32le() end if r.err then return fail("truncated BRUS entry", "truncated") end table.insert(brushes, b) end end -- the material of brush id (0-based) | nil for -1 / out of range local function material(id: number): number? if id < 0 or id >= #brushes then return nil end local have = materialOf[id] if have then return have end local b = brushes[id + 1] local m = Types.Scene.material(b.name ~= "" and b.name or nil) local c = b.color local function clamp01(v: number): number return if v ~= v then 1 else math.clamp(v, 0, 1) end m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) } m.metallic = 0 m.roughness = 1 - 0.8 * clamp01(b.shininess) m.doubleSided = bit32.band(b.fx, 16) ~= 0 if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then m.alphaMode = "blend" end if bit32.band(b.fx, 1) ~= 0 then m.extensions = { KHR_materials_unlit = {} } end local extraTex: { number } = {} for i, tid in b.textures do local t = texs[tid + 1] if tid >= 0 and t then if not m.baseColorTexture then local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil } local o, s, rot = t.offset, t.scale, t.rotation if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot } end m.baseColorTexture = ref if bit32.band(t.flags, 4) ~= 0 then m.alphaMode = "mask" elseif bit32.band(t.flags, 2) ~= 0 then m.alphaMode = "blend" end else extraTex[i] = t.index end end end m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } } table.insert(scene.materials, m) materialOf[id] = #scene.materials return #scene.materials end local function readMesh(r: Bytes.Reader, nodeIndex: number): number? local master = r:i32le() if r.err then fail("truncated MESH", "truncated") return nil end local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT) local attrs: { [string]: Types.Accessor }? = nil local count = 0 local mesh: Types.Mesh = { primitives = {} } local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} } for _, c in list do local cr = body(c) if c.id == "VRTS" and not attrs then local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le() if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then fail("bad VRTS header") return nil end local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0 local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4 local n = (cr.limit - cr.pos) // stride totalVertices += n if totalVertices > maxVertices then fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit") return nil end local pos = buffer.create(n * 12) local nrm = if hasN then buffer.create(n * 12) else nil local col = if hasC then buffer.create(n * 16) else nil local uvs: { buffer } = {} for s = 1, sets do uvs[s] = buffer.create(n * 8) end local readf32, writef32 = buffer.readf32, buffer.writef32 local p = cr.pos for i = 0, n - 1 do writef32(pos, i * 12, readf32(buf, p)) writef32(pos, i * 12 + 4, readf32(buf, p + 4)) writef32(pos, i * 12 + 8, -readf32(buf, p + 8)) p += 12 if nrm then writef32(nrm, i * 12, readf32(buf, p)) writef32(nrm, i * 12 + 4, readf32(buf, p + 4)) writef32(nrm, i * 12 + 8, -readf32(buf, p + 8)) p += 12 end if col then for k = 0, 3 do writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4)) end p += 16 end for s = 1, sets do if size >= 1 then writef32(uvs[s], i * 8, readf32(buf, p)) end if size >= 2 then writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4)) end p += size * 4 end end local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) } if nrm then a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n) end if col then a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n) end if size > 0 then for s = 1, sets do a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n) end end attrs, count = a, n mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } } elseif c.id == "TRIS" then local brush = cr:i32le() if cr.err then fail("truncated TRIS", "truncated") return nil end if not attrs then fail("TRIS before VRTS") return nil end local nt = (cr.limit - cr.pos) // 12 local idx = buffer.create(nt * 12) local readu32, writeu32 = buffer.readu32, buffer.writeu32 local p = cr.pos for i = 0, nt - 1 do local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8) if a >= count or b >= count or cc >= count then fail(string.format("triangle %d: vertex index out of range", i)) return nil end -- mirrored z: reverse the winding to keep the faces front-facing writeu32(idx, i * 12, a) writeu32(idx, i * 12 + 4, cc) writeu32(idx, i * 12 + 8, b) p += 12 end local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" } prim.material = material(if brush == -1 then master else brush) table.insert(mesh.primitives, prim) end end if not attrs then return nil -- a mesh without vertices: the node stays a pivot end if #mesh.primitives == 0 then table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) end table.insert(scene.meshes, mesh) rec.mesh, rec.count = #scene.meshes, count table.insert(meshes, rec) lastMesh = rec return #scene.meshes end local function readBone(r: Bytes.Reader, nodeIndex: number) local b: Bone = { node = nodeIndex, target = lastMesh, list = {} } table.insert(bones, b) local list = b.list while r.pos + 8 <= r.limit do local v, w = r:i32le(), r:f32le() table.insert(list, v) table.insert(list, w) end end local function readKeys(r: Bytes.Reader, nodeIndex: number) local flags = r:i32le() local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0) local k = nodeKeys[nodeIndex] if not k then k = { t = {}, s = {}, r = {} } nodeKeys[nodeIndex] = k end while not r.err and r.pos + per <= r.limit do local frame = r:i32le() if bit32.band(flags, 1) ~= 0 then k.t[frame] = vec(r) end if bit32.band(flags, 2) ~= 0 then local x, y, z = r:f32le(), r:f32le(), r:f32le() k.s[frame] = { x, y, z } end if bit32.band(flags, 4) ~= 0 then k.r[frame] = quat(r) end end end local function readNode(c: Chunks.Chunk, depth: number): number? if depth > maxDepth then fail("limit: nodes nested deeper than " .. maxDepth, "limit") return nil end local r = body(c) local name = r:cstring() local t = vec(r) local sx, sy, sz = r:f32le(), r:f32le(), r:f32le() local q = quat(r) if r.err then fail("truncated NODE", "truncated") return nil end local node: Types.Node = { name = name, children = {} } if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then node.translation = t end if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then node.rotation = q end if sx ~= 1 or sy ~= 1 or sz ~= 1 then node.scale = { sx, sy, sz } end table.insert(scene.nodes, node) local index = #scene.nodes for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do if failure then break end local id = sub.id if id == "NODE" then local child = readNode(sub, depth + 1) if child then table.insert(node.children, child) end elseif id == "MESH" and not node.mesh then node.mesh = readMesh(body(sub), index) elseif id == "BONE" then readBone(body(sub), index) elseif id == "KEYS" then readKeys(body(sub), index) elseif id == "ANIM" then local ar = body(sub) local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le() if not ar.err and not anim then anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 } end end end return index end for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do if failure then break end if c.id == "TEXS" then readTexs(body(c)) elseif c.id == "BRUS" then readBrus(body(c)) elseif c.id == "NODE" then local n = readNode(c, 1) if n then table.insert(scene.roots, n) end end end if failure then return nil, failure, failKind end if #scene.nodes == 0 then return nil, "no NODE chunk", nil end -- ------------------------------------------------------------------------------------------ skins local parent: { [number]: number } = {} for i, n in scene.nodes do for _, ch in n.children do parent[ch] = i end end local worldCache: { [number]: { number } } = {} local function world(i: number): { number } local w = worldCache[i] if not w then local n = scene.nodes[i] local l = Mat4.compose(n.translation, n.rotation, n.scale) w = if parent[i] then Mat4.mul(world(parent[i]), l) else l worldCache[i] = w end return w end local bonesOf: { [MeshRec]: { Bone } } = {} for _, b in bones do local m = b.target if m then local l = bonesOf[m] or {} bonesOf[m] = l table.insert(l, b) end end for _, rec in meshes do local list = bonesOf[rec] if list then local nv = rec.count local inf: { { number } } = {} local joints: { number } = {} for j, b in list do joints[j] = b.node local l = b.list for k = 1, #l, 2 do local v, w = l[k], l[k + 1] if v >= 0 and v < nv and w > 0 and w == w then local e = inf[v + 1] if not e then e = {} inf[v + 1] = e end table.insert(e, j - 1) table.insert(e, w) end end end local self: number? = nil -- the mesh node as a joint, for vertices no bone moves local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) for v = 0, nv - 1 do local e = inf[v + 1] if not e then if not self then table.insert(joints, rec.node) self = #joints - 1 end buffer.writeu16(jb, v * 8, self :: number) buffer.writef32(wb, v * 16, 1) else -- the 4 strongest, normalised local order = {} for k = 1, #e, 2 do table.insert(order, k) end table.sort(order, function(a: number, b: number): boolean return e[a + 1] > e[b + 1] end) local sum = 0 for k = 1, math.min(4, #order) do sum += e[order[k] + 1] end for k = 1, math.min(4, #order) do buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]]) buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum) end end end local meshWorld = world(rec.node) local ibm = buffer.create(#joints * 64) for j, ni in joints do local inv = Mat4.inverse(world(ni)) or Mat4.identity() local m = Mat4.mul(inv, meshWorld) for k = 1, 16 do buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) end end local ia = Types.Scene.accessor(ibm, "f32", 16, #joints) ia.matrix = true table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia }) scene.nodes[rec.node].skin = #scene.skins local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv) for _, prim in scene.meshes[rec.mesh].primitives do prim.attributes.JOINTS_0 = J prim.attributes.WEIGHTS_0 = W end end end -- ------------------------------------------------------------------------------------------ animation local fps = if anim then anim.fps else 60 local channels: { Types.Channel } = {} for ni = 1, #scene.nodes do local k = nodeKeys[ni] if k then for _, path in { "translation", "rotation", "scale" } do local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s local frames = {} for f in map do table.insert(frames, f) end if #frames > 0 then table.sort(frames) local nc = if path == "rotation" then 4 else 3 local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4) for i, f in frames do buffer.writef32(input, (i - 1) * 4, f / fps) local v = map[f] for c = 1, nc do buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c]) end end table.insert(channels, { node = ni, path = path :: any, input = Types.Scene.accessor(input, "f32", 1, #frames), output = Types.Scene.accessor(output, "f32", nc, #frames), interpolation = "LINEAR" :: "LINEAR", }) end end end end if #channels > 0 then table.insert(scene.animations, { name = "b3d", channels = channels }) end scene.meta.up = "y" scene.meta.source = { format = "b3d", version = version, brushes = #brushes, frames = if anim then anim.frames else nil, fps = if anim then anim.fps else nil, handedness = "left", -- converted: z mirrored, winding reversed } return scene, nil, nil end return Read