diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0250ba7..ab1b266 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -43,6 +43,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | +| model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 9d01ae2..10f00bd 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -470,6 +470,18 @@ local list: { Entry } = { return require("@formats/model/rbxmx") end, }, + { + name = "robloxmesh", + category = "model", + path = "model/robloxmesh", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, + load = function() + return require("@formats/model/robloxmesh") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/model/rbxm/init.luau b/src/Formats/model/rbxm/init.luau index 7fb49e7..b903f92 100644 --- a/src/Formats/model/rbxm/init.luau +++ b/src/Formats/model/rbxm/init.luau @@ -50,6 +50,36 @@ function Rbxm.sniff(r: Bytes.Reader): number return if r:peek(14) == MAGIC then 1 else 0 end +-- variant(r) -> "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +function Rbxm.variant(r: Bytes.Reader): string? + local b, p, e = r.buf, r.base + 32, r.limit + if r:peek(14) ~= MAGIC then + return nil + end + while p + 16 <= e do + local name, clen, ulen = readstring(b, p, 4), readu32(b, p + 4), readu32(b, p + 8) + local size = if clen == 0 then ulen else clen + if p + 16 + size > e or name == "END\0" then + break + end + if name == "INST" then + local body: buffer?, o = b, p + 16 + if clen ~= 0 then + body = if Zstd.isFrame(b, p + 16) then Zstd.decompress(b, p + 16, clen, { maxBytes = ulen }) else Lz4.decompress(b, p + 16, clen, ulen) + o = 0 + end + if body and o + 8 <= buffer.len(body) then + local q = o + 8 + readu32(body, o + 4) + if q < buffer.len(body) and readu8(body, q) == 1 then + return "rbxl" + end + end + end + p += 16 + size + end + return "rbxm" +end + -- ------------------------------------------------------------------------------------------------ decode type Class = { id: number, name: string, refs: { number }, service: boolean } diff --git a/src/Formats/model/rbxmx/init.luau b/src/Formats/model/rbxmx/init.luau index b2427ac..91ec602 100644 --- a/src/Formats/model/rbxmx/init.luau +++ b/src/Formats/model/rbxmx/init.luau @@ -81,6 +81,12 @@ function Rbxmx.sniff(r: Bytes.Reader): number return 0 end +-- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +function Rbxmx.variant(r: Bytes.Reader): string? + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + return if find(text, ' lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + local r = record(version) + local nv = nf * 3 + r.numVerts, r.numFaces = nv, nf + r.pos, r.nrm, r.uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + r.faces = buffer.create(nf * 12) + local scale = if version == "1.00" then 0.5 else 1 + local i = 0 + local vals = table.create(9, 0) + local k = 0 + local start = string.find(text, "[", 1, true) or (#text + 1) + for a, b, c in string.gmatch(string.sub(text, start), "%[%s*([^,%]]+)%s*,%s*([^,%]]+)%s*,%s*([^,%]]+)%s*%]") do + local x, y, z = tonumber(a), tonumber(b), tonumber(c) + if not x or not y or not z then + return nil, "corrupt: bad number in a vector" + end + vals[k * 3 + 1], vals[k * 3 + 2], vals[k * 3 + 3] = x, y, z + k += 1 + if k == 3 then + if i >= nv then + break + end + writef32(r.pos, i * 12, vals[1] * scale) + writef32(r.pos, i * 12 + 4, vals[2] * scale) + writef32(r.pos, i * 12 + 8, vals[3] * scale) + writef32(r.nrm, i * 12, vals[4]) + writef32(r.nrm, i * 12 + 4, vals[5]) + writef32(r.nrm, i * 12 + 8, vals[6]) + writef32(r.uv, i * 8, vals[7]) + writef32(r.uv, i * 8 + 4, 1 - vals[8]) -- version 1 stores V upside down + i += 1 + k = 0 + end + end + if i < nv then + return nil, "truncated: " .. i .. " of " .. nv .. " vertices" + end + for f = 0, nv - 1 do + writeu32(r.faces, f * 4, f) + end + r.lods = { 0, nf } + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ binary parts +-- vertices of size vs (36 / 40) at p +local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) + local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + local col = if vs >= 40 then buffer.create(n * 4) else nil + for i = 0, n - 1 do + local q = p + i * vs + buffer.copy(pos, i * 12, b, q, 12) + buffer.copy(nrm, i * 12, b, q + 12, 12) + buffer.copy(uv, i * 8, b, q + 24, 8) + buffer.copy(tan, i * 4, b, q + 32, 4) + if col then + buffer.copy(col, i * 4, b, q + 36, 4) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col = pos, nrm, uv, tan, col + r.numVerts = n +end + +local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? + local out = buffer.create(n * 12) + local nv = r.numVerts + for i = 0, n - 1 do + for k = 0, 2 do + local v = readu32(b, p + i * fs + k * 4) + if v >= nv then + return "corrupt: face " .. i .. " uses vertex " .. v .. " of " .. nv + end + writeu32(out, i * 12 + k * 4, v) + end + end + r.faces, r.numFaces = out, n + return nil +end + +local function bones(b: buffer, p: number, n: number, names: string, r: Record) + for i = 0, n - 1 do + local q = p + i * 60 + local ni = readu32(b, q) + local name = string.match(string.sub(names, ni + 1), "^[^%z]*") or "" + local parent = readu16(b, q + 4) + local cf = table.create(12, 0) + for k = 0, 11 do + cf[k + 1] = readf32(b, q + 12 + 4 * k) + end + r.bones[i + 1] = { name = name, parent = if parent == 0xFFFF then nil else parent, lodParent = readu16(b, q + 6), culling = readf32(b, q + 8), cf = cf } + end +end + +local function subsets(b: buffer, p: number, n: number, r: Record) + for i = 0, n - 1 do + local q = p + i * 72 + local count = math.min(readu32(b, q + 16), 26) + local list = table.create(count, 0) + for k = 0, count - 1 do + list[k + 1] = readu16(b, q + 20 + 2 * k) + end + r.subsets[i + 1] = { facesBegin = readu32(b, q), facesLength = readu32(b, q + 4), vertsBegin = readu32(b, q + 8), vertsLength = readu32(b, q + 12), bones = list } + end +end + +local function lods(b: buffer, p: number, n: number, r: Record) + local out = table.create(n, 0) + for i = 0, n - 1 do + out[i + 1] = readu32(b, p + 4 * i) + end + r.lods = out +end + +-- ------------------------------------------------------------------------------------------------ versions 2 .. 5 +local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local major = tonumber(string.sub(version, 1, 1)) or 0 + if p + 12 > e then + return nil, "truncated header" + end + local hs = readu16(b, p) + local nv: number, nf: number, vs: number, fs: number = 0, 0, 40, 12 + local nlod: number, nbones: number, namesSize: number, nsub: number = 0, 0, 0, 0 + if major == 2 or major == 3 then + vs = readu8(b, p + 2) + fs = readu8(b, p + 3) + if major == 2 then + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + else + if p + 16 > e then + return nil, "truncated header" + end + nlod = readu16(b, p + 6) + nv = readu32(b, p + 8) + nf = readu32(b, p + 12) + end + else + if p + 24 > e then + return nil, "truncated header" + end + r.lodType = readu16(b, p + 2) + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + nlod = readu16(b, p + 12) + nbones = readu16(b, p + 14) + namesSize = readu32(b, p + 16) + nsub = readu16(b, p + 20) + r.highQualityLods = readu8(b, p + 22) + if major >= 5 then + if p + 32 > e then + return nil, "truncated header" + end + r.facsFormat = readu32(b, p + 24) + end + end + if vs < 36 or fs < 12 then + return nil, "corrupt: vertex size " .. vs .. ", face size " .. fs + end + if nv > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces" + end + local q = p + hs + if q + nv * vs > e then + return nil, "truncated vertices" + end + vertices(b, q, nv, vs, r) + q += nv * vs + if nbones > 0 then + if q + nv * 8 > e then + return nil, "truncated skinning" + end + local env = buffer.create(nv * 8) + buffer.copy(env, 0, b, q, nv * 8) + r.env = env + q += nv * 8 + end + if q + nf * fs > e then + return nil, "truncated faces" + end + local ferr = faces(b, q, nf, fs, r) + if ferr then + return nil, ferr + end + q += nf * fs + if q + nlod * 4 > e then + return nil, "truncated LOD offsets" + end + lods(b, q, nlod, r) + q += nlod * 4 + if q + nbones * 60 + namesSize + nsub * 72 > e then + return nil, "truncated bones / subsets" + end + local names = readstring(b, q + nbones * 60, namesSize) + bones(b, q, nbones, names, r) + q += nbones * 60 + namesSize + subsets(b, q, nsub, r) + q += nsub * 72 + if major >= 5 then + local size = readu32(b, p + 28) + if size > 0 then + if q + size > e then + return nil, "truncated FACS data" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q, size) + r.facs = facs + end + end + if #r.lods == 0 then + r.lods = { 0, nf } + end + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ versions 6 / 7 +local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local core = false + while p < e do + if p + 16 > e then + return nil, "truncated chunk header" + end + local name = string.gsub(readstring(b, p, 8), "%z+$", "") + local cv, size = readu32(b, p + 8), readu32(b, p + 12) + local q = p + 16 + local ce = q + size + if ce > e then + return nil, "truncated chunk " .. name + end + if name == "COREMESH" then + if cv == 2 then + return nil, "unsupported: Draco-compressed COREMESH (needs codecs/model/Draco)" + elseif cv ~= 1 then + return nil, "unsupported: COREMESH version " .. cv + end + if q + 4 > ce then + return nil, "truncated COREMESH" + end + local nv = readu32(b, q) + if nv > lim.maxVertices then + return nil, "limit: " .. nv .. " vertices" + end + if q + 4 + nv * 40 + 4 > ce then + return nil, "truncated COREMESH vertices" + end + vertices(b, q + 4, nv, 40, r) + local fq = q + 4 + nv * 40 + local nf = readu32(b, fq) + if nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + if fq + 4 + nf * 12 > ce then + return nil, "truncated COREMESH faces" + end + local ferr = faces(b, fq + 4, nf, 12, r) + if ferr then + return nil, ferr + end + core = true + elseif name == "LODS" and cv == 1 then + if q + 7 > ce then + return nil, "truncated LODS" + end + r.lodType = readu16(b, q) + r.highQualityLods = readu8(b, q + 2) + local n = readu32(b, q + 3) + if q + 7 + n * 4 > ce then + return nil, "truncated LODS" + end + lods(b, q + 7, n, r) + elseif name == "SKINNING" and cv == 1 then + if not core then + return nil, "corrupt: SKINNING before COREMESH" + end + if q + 4 > ce then + return nil, "truncated SKINNING" + end + local ns = readu32(b, q) + local s = q + 4 + if ns ~= r.numVerts or s + ns * 8 + 4 > ce then + return nil, "corrupt: SKINNING count" + end + local env = buffer.create(ns * 8) + buffer.copy(env, 0, b, s, ns * 8) + r.env = env + s += ns * 8 + local nb = readu32(b, s) + s += 4 + if s + nb * 60 + 4 > ce then + return nil, "truncated SKINNING bones" + end + local bq = s + s += nb * 60 + local namesSize = readu32(b, s) + s += 4 + if s + namesSize + 4 > ce then + return nil, "truncated SKINNING names" + end + bones(b, bq, nb, readstring(b, s, namesSize), r) + s += namesSize + local nsub = readu32(b, s) + s += 4 + if s + nsub * 72 > ce then + return nil, "truncated SKINNING subsets" + end + subsets(b, s, nsub, r) + if nb == 0 then + r.env = nil + end + elseif name == "FACS" and cv == 1 then + if q + 4 > ce then + return nil, "truncated FACS" + end + local size = readu32(b, q) + if q + 4 + size > ce then + return nil, "truncated FACS" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q + 4, size) + r.facs, r.facsFormat = facs, 1 + else + local data = buffer.create(size) + buffer.copy(data, 0, b, q, size) + table.insert(r.chunks, { name = name, version = cv, data = data }) + end + p = ce + end + if not core then + return nil, "corrupt: no COREMESH chunk" + end + if #r.lods == 0 then + r.lods = { 0, r.numFaces } + end + return r, nil +end + +-- parse(b, p, e, lim) -> Record | nil, message +function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) + if e - p < 13 then + return nil, "truncated: no version line" + end + local line = readstring(b, p, 12) + local version = string.match(line, "^version (%d%.%d%d)$") + if not version or readu8(b, p + 12) ~= 10 and readu8(b, p + 12) ~= 13 then + return nil, "corrupt: bad version line" + end + local q = p + 13 + if readu8(b, p + 12) == 13 and q < e and readu8(b, q) == 10 then + q += 1 + end + local major = string.sub(version, 1, 1) + if major == "1" then + return ascii(readstring(b, p, e - p), version, lim) + elseif major == "2" or major == "3" or major == "4" or major == "5" then + return classic(b, q, e, version, lim) + elseif major == "6" or major == "7" then + return chunked(b, q, e, version, lim) + end + return nil, "unsupported: version " .. version +end + +-- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +local function snorm(v: number): number + local x = if v >= 128 then v - 256 else v + return math.clamp(x / 127, -1, 1) +end +function Parse.tangent(tan: buffer, i: number): (number, number, number, number) + return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) +end + +return Parse diff --git a/src/Formats/model/robloxmesh/Write.luau b/src/Formats/model/robloxmesh/Write.luau new file mode 100644 index 0000000..7b54c03 --- /dev/null +++ b/src/Formats/model/robloxmesh/Write.luau @@ -0,0 +1,109 @@ +--!strict +--!native +--!optimize 2 +-- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: +-- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning +-- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +local Parse = require("@formats/model/robloxmesh/Parse") +local Bytes = require("@formats/core/Bytes") + +local Write = {} + +local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) + local p = w:reserve(if colors then 40 else 36) + local b = w.buf + buffer.copy(b, p, r.pos, i * 12, 12) + buffer.copy(b, p + 12, r.nrm, i * 12, 12) + buffer.copy(b, p + 24, r.uv, i * 8, 8) + if r.tan then + buffer.copy(b, p + 32, r.tan, i * 4, 4) + else + buffer.writeu32(b, p + 32, 0x7F810000) -- (0, 0, -1, 1) + end + if colors then + if r.col then + buffer.copy(b, p + 36, r.col, i * 4, 4) + else + buffer.writeu32(b, p + 36, 0xFFFFFFFF) + end + end + w.pos = p + (if colors then 40 else 36) +end + +-- write(r, version) -> buffer ("2.00" | "4.00") +function Write.write(r: Parse.Record, version: string): buffer + local nv, nf = r.numVerts, r.numFaces + local w = Bytes.writer(64 + nv * 48 + nf * 12) + w:string("version " .. version .. "\n") + if version == "2.00" then + local colors = r.col ~= nil + w:u16le(12) + w:u8(if colors then 40 else 36) + w:u8(12) + w:u32le(nv) + w:u32le(nf) + for i = 0, nv - 1 do + vertex(w, r, i, colors) + end + w:bytes(r.faces, 0, nf * 12) + return w:finish() + end + -- 4.00 + local names = {} + local nameAt = {} + local size = 0 + for i, bone in r.bones do + nameAt[i] = size + table.insert(names, bone.name .. "\0") + size += #bone.name + 1 + end + local nb = #r.bones + w:u16le(24) + w:u16le(r.lodType) + w:u32le(nv) + w:u32le(nf) + w:u16le(#r.lods) + w:u16le(nb) + w:u32le(size) + w:u16le(#r.subsets) + w:u8(r.highQualityLods) + w:u8(0) + for i = 0, nv - 1 do + vertex(w, r, i, true) + end + if nb > 0 then + local env = r.env + if env then + w:bytes(env, 0, nv * 8) + else + w:fill(0, nv * 8) + end + end + w:bytes(r.faces, 0, nf * 12) + for _, o in r.lods do + w:u32le(o) + end + for i, bone in r.bones do + w:u32le(nameAt[i]) + w:u16le(if bone.parent then bone.parent else 0xFFFF) + w:u16le(bone.lodParent) + w:f32le(bone.culling) + for k = 1, 12 do + w:f32le(bone.cf[k] or 0) + end + end + w:string(table.concat(names)) + for _, s in r.subsets do + w:u32le(s.facesBegin) + w:u32le(s.facesLength) + w:u32le(s.vertsBegin) + w:u32le(s.vertsLength) + w:u32le(#s.bones) + for k = 1, 26 do + w:u16le(s.bones[k] or 0xFFFF) + end + end + return w:finish() +end + +return Write diff --git a/src/Formats/model/robloxmesh/init.luau b/src/Formats/model/robloxmesh/init.luau new file mode 100644 index 0000000..b3e1b70 --- /dev/null +++ b/src/Formats/model/robloxmesh/init.luau @@ -0,0 +1,578 @@ +--!strict +-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh +-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. +-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, +-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown +-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2) is Err.UNSUPPORTED until codecs/model/Draco +-- exists. One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed +-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in +-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' +-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes +-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw +-- (meta.source.facs). meta.up = "y"; units are studs. +-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every +-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes +-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to +-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). +-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing +-- 3.00 / 5.00+ / FACS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Parse = require("@formats/model/robloxmesh/Parse") +local Write = require("@formats/model/robloxmesh/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local RobloxMesh = { + name = "robloxmesh", + category = "model", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +export type EncodeOptions = { + version: ("2.00" | "4.00")?, -- default "2.00" +} + +-- ------------------------------------------------------------------------------------------------ constants +local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16 +local accessor = Types.Scene.accessor + +-- ------------------------------------------------------------------------------------------------ sniff +function RobloxMesh.sniff(r: Bytes.Reader): number + return if string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z) +local function boneMatrix(cf: { number }): { number } + return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } +end + +local function indices(r: Parse.Record, from: number, to: number): Types.Accessor + local n = math.max(0, to - from) + local d = buffer.create(n * 12) + buffer.copy(d, 0, r.faces, from * 12, n * 12) + return accessor(d, "u32", 1, n * 3) +end + +function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local lim = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25 } + local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim) + if not r then + return nil, Err.from(msg, rd.base) + end + local nv, nf = r.numVerts, r.numFaces + local attrs: { [string]: Types.Accessor } = { + POSITION = accessor(r.pos, "f32", 3, nv), + NORMAL = accessor(r.nrm, "f32", 3, nv), + TEXCOORD_0 = accessor(r.uv, "f32", 2, nv), + } + local tan = r.tan + if tan then + local t = buffer.create(nv * 16) + for i = 0, nv - 1 do + local x, y, z, w = Parse.tangent(tan, i) + writef32(t, i * 16, x) + writef32(t, i * 16 + 4, y) + writef32(t, i * 16 + 8, z) + writef32(t, i * 16 + 12, w) + end + attrs.TANGENT = accessor(t, "f32", 4, nv) + end + if r.col then + attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) + end + -- LOD ranges (offsets clamped to the faces) + local offs = {} + for _, o in r.lods do + table.insert(offs, math.clamp(o, 0, nf)) + end + if #offs < 2 then + offs = { 0, nf } + end + local scene = Types.Scene.new() + local prim: Types.Primitive = { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" } + local lods = {} + for k = 2, #offs - 1 do + table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" }) + end + local mesh: Types.Mesh = { name = "Mesh", primitives = { prim } } + if #lods > 0 then + mesh.extras = { lods = lods } + end + scene.meshes[1] = mesh + scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + -- bones and skinning + local nb = #r.bones + if nb > 0 then + local world: { { number } } = table.create(nb) :: any + for i, bone in r.bones do + world[i] = boneMatrix(bone.cf) + end + local joints = table.create(nb, 0) + local ibm = buffer.create(nb * 64) + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + local m = world[i] + if parent then + local inv = Mat4.inverse(world[parent]) + if inv then + m = Mat4.mul(inv, m) + end + end + local node: Types.Node = { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } } + table.insert(scene.nodes, node) + joints[i] = #scene.nodes + local inv = Mat4.inverse(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k]) + end + end + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + if parent then + table.insert(scene.nodes[joints[parent]].children, joints[i]) + else + table.insert(scene.roots, joints[i]) + end + end + scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) } + scene.nodes[1].skin = 1 + local env = r.env + if env then + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4) + for i = 0, nv - 1 do + for k = 0, 3 do + writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k)) + end + end + for _, s in r.subsets do + local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1 + for v = s.vertsBegin, last do + for k = 0, 3 do + local li = readu8(env, v * 8 + k) + local g = s.bones[li + 1] + writeu16(jb, v * 8 + k * 2, if g and g < nb and readu8(wb, v * 4 + k) > 0 then g else 0) + end + end + end + attrs.JOINTS_0 = accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv) + end + end + local subsets = {} + for _, s in r.subsets do + table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones }) + end + scene.meta.up = "y" + scene.meta.source = { + format = "robloxmesh", + version = r.version, + lodType = r.lodType, + highQualityLods = r.highQualityLods, + lodOffsets = r.lods, + subsets = subsets, + facsFormat = r.facsFormat, + facs = r.facs, + chunks = r.chunks, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(attr: any, i: number, c: number, default: number): number + if not attr or c >= attr.components then + return default + end + return attr.values[i * attr.components + c + 1] +end + +-- area-weighted vertex normals +local function normals(pos: buffer, nv: number, corners: { number }): buffer + local acc = table.create(nv * 3, 0) + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + writef32(out, v * 12, x / l) + writef32(out, v * 12 + 4, y / l) + writef32(out, v * 12 + 8, z / l) + else + writef32(out, v * 12 + 4, 1) + end + end + return out +end + +-- world matrices of every node (parents through children lists) +local function worlds(scene: any): { [number]: { number } } + local out: { [number]: { number } } = {} + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parent[c] = i + end + end + local function world(i: number, depth: number): { number } + if out[i] then + return out[i] + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + if p and depth < 256 then + m = Mat4.mul(world(p, depth + 1), m) + end + out[i] = m + return m + end + for i in scene.nodes do + world(i, 0) + end + return out +end + +-- the bones of a skin: Parse.Bone list, or nil, message +local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) + local joints = skin.joints + if type(joints) ~= "table" or #joints == 0 then + return nil, "a skin without joints" + end + if #joints > 65534 then + return nil, "too many joints" + end + local w = worlds(scene) + local index: { [number]: number } = {} + for i, j in joints do + index[j] = i - 1 + end + local parentOf: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parentOf[c] = i + end + end + local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices) + local out = {} + for i, j in joints do + local node = scene.nodes[j] + if not node then + return nil, "a joint names a missing node" + end + local m = w[j] + if ibm and #ibm >= i * 16 then + local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0))) + if inv then + m = inv + end + end + local ex = if type(node.extras) == "table" then node.extras else {} + local p = parentOf[j] + out[i] = { + name = if type(node.name) == "string" then node.name else "Bone" .. i, + parent = if p then index[p] else nil, + lodParent = if type(ex.lodParent) == "number" then ex.lodParent else 0xFFFF, + culling = if type(ex.culling) == "number" then ex.culling else 0, + cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }, + } + end + return out, nil +end + +-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) +local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) + local nv = #order + local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0 + local col = nil + if C then + local scale = if C.raw then 1 else 255 + local white = true + col = buffer.create(nv * 4) + for i, src in order do + for k = 0, 3 do + local v = math.clamp(math.floor(num(C, src, k, if C.raw then 255 else 1) * scale + 0.5), 0, 255) + writeu8(col, (i - 1) * 4 + k, v) + if v ~= 255 then + white = false + end + end + end + if white then + col = nil + end + end + for i, src in order do + local o = i - 1 + for k = 0, 2 do + writef32(pos, o * 12 + k * 4, num(P, src, k, 0)) + end + if N then + for k = 0, 2 do + writef32(nb, o * 12 + k * 4, num(N, src, k, 0)) + end + elseif nrm then + buffer.copy(nb, o * 12, nrm, src * 12, 12) + end + writef32(uv, o * 8, num(U, src, 0, 0)) + writef32(uv, o * 8 + 4, num(U, src, 1, 0)) + if T then + for k = 0, 3 do + local v = math.clamp(math.floor(num(T, src, k, if k == 3 then 1 else 0) * 127 + 0.5), -127, 127) + writeu8(tan, o * 4 + k, v % 256) + end + else + buffer.writeu32(tan, o * 4, 0x7F810000) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv +end + +function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or "2.00" + if version ~= "2.00" and version ~= "4.00" then + return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"") + end + if type(scene) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true } + local m, merr = Flatten.merge(scene, function(name: string): boolean + return keep[name] == true + end, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local corners = m.corners + if not m.sizes or #corners == 0 then + return nil, Err.new(Err.ARG, "no triangles to write") + end + local nv0 = m.count + if nv0 > 2 ^ 32 - 1 then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local r: Parse.Record = { + version = version, + numVerts = 0, + numFaces = #corners // 3, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + facsFormat = 0, + chunks = {}, + } + local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" then scene.meta.source else nil + if src and type(src.lodType) == "number" then + r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 + end + -- normals when the scene has none + local nrm: buffer? = nil + if not m.attrs.NORMAL then + local pb = buffer.create(nv0 * 12) + for i = 0, nv0 - 1 do + for k = 0, 2 do + writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0)) + end + end + nrm = normals(pb, nv0, corners) + end + -- the skin (4.00): the first node with a mesh and a skin + local skin = nil + if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then + for _, n in scene.nodes or {} do + if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then + skin = scene.skins[n.skin] + break + end + end + end + local nf = #corners // 3 + if skin then + local bones, berr = skinBones(scene, skin) + if not bones then + return nil, Err.new(Err.ARG, berr or "bad skin") + end + r.bones = bones + local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 + local wscale = if W.raw then 1 / 255 else 1 + local nb = #bones + -- per vertex: up to 4 (joint, weight) pairs with weight > 0 + local influences: { { { number } } } = table.create(nv0) :: any + for v = 0, nv0 - 1 do + local list = {} + for k = 0, 3 do + local wt = num(W, v, k, 0) * wscale + local j = num(J, v, k, 0) + if wt > 0 and j >= 0 and j < nb then + table.insert(list, { j, wt }) + end + end + influences[v + 1] = list + end + -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + local faceIdx = buffer.create(nf * 12) + local order: { number } = {} + local s: any = nil + local function close() + if s then + table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones }) + end + end + local function open(f: number) + s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} } + end + open(0) + for f = 0, nf - 1 do + local need = {} + local extra = 0 + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + if s.local_[inf[1]] == nil and not need[inf[1]] then + need[inf[1]] = true + extra += 1 + end + end + end + if #s.bones + extra > 26 then + close() + open(f) + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + need[inf[1]] = true + end + end + end + for j in need do + if s.local_[j] == nil then + table.insert(s.bones, j) + s.local_[j] = #s.bones - 1 + end + end + for c = 1, 3 do + local v = corners[f * 3 + c] + local nvx = s.remap[v] + if not nvx then + table.insert(order, v) + nvx = #order - 1 + s.remap[v] = nvx + end + buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx) + end + s.faceCount += 1 + end + close() + r.faces = faceIdx + fill(r, m, order, nrm) + -- envelopes: subset-local bone indices, weights summing to 255 + local env = buffer.create(#order * 8) + for _, sub in r.subsets do + local loc: { [number]: number } = {} + for i, j in sub.bones do + loc[j] = i - 1 + end + for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do + local list = influences[order[o + 1] + 1] + local total = 0 + for _, inf in list do + total += inf[2] + end + local bytes, sum, best = {}, 0, 1 + for k, inf in list do + local b = if total > 0 then math.floor(inf[2] / total * 255 + 0.5) else 0 + bytes[k] = b + sum += b + if inf[2] > list[best][2] then + best = k + end + end + if #list > 0 then + bytes[best] += 255 - sum + end + for k = 0, 3 do + local inf = list[k + 1] + writeu8(env, o * 8 + k, if inf then loc[inf[1]] or 0 else 0) + writeu8(env, o * 8 + 4 + k, if inf then math.clamp(bytes[k + 1], 0, 255) else 0) + end + end + end + r.env = env + r.lods = { 0, nf } + else + local order = table.create(nv0, 0) + for i = 1, nv0 do + order[i] = i - 1 + end + fill(r, m, order, nrm) + local faces = buffer.create(nf * 12) + for i, c in corners do + buffer.writeu32(faces, (i - 1) * 4, c) + end + r.faces = faces + r.lods = { 0, nf } + -- extra LODs of a single untransformed primitive + local part = m.parts[1] + local mesh = part and part.mesh + local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil + if version == "4.00" and type(lods) == "table" and #lods > 0 then + local list = {} + for _, lp in lods do + local idx = if type(lp) == "table" and lp.indices then Flatten.numbers(lp.indices) else nil + if idx and #idx % 3 == 0 then + table.insert(list, idx) + end + end + local total = nf + for _, idx in list do + total += #idx // 3 + end + local all = buffer.create(total * 12) + buffer.copy(all, 0, faces, 0, nf * 12) + local at = nf + for _, idx in list do + for i, c in idx do + if c >= nv0 then + return nil, Err.new(Err.ARG, "a LOD index is out of range") + end + buffer.writeu32(all, at * 12 + (i - 1) * 4, c) + end + at += #idx // 3 + table.insert(r.lods, at) + end + r.faces, r.numFaces = all, total + end + end + return Write.write(r, version), nil +end + +return RobloxMesh diff --git a/tests/model/rbxm.luau b/tests/model/rbxm.luau index 70276df..e7deadc 100644 --- a/tests/model/rbxm.luau +++ b/tests/model/rbxm.luau @@ -240,6 +240,23 @@ do t:check(e8 and e8.code == Err.CORRUPT, "a cycle: " .. tostring(e8)) end +-- through the api: detection (variant: rbxl for places), load, save, convert +do + local F = require("@formats") + t:eq(F.detect(file("place.rbxl").data), "rbxl", "detect a place") + t:eq(F.detect(file("model.rbxm").data), "rbxm", "detect a model") + t:eq(F.detect(file("place.rbxlx").data), "rbxlx", "detect an XML place") + t:eq(F.detect(file("model.rbxmx").data), "rbxmx", "detect an XML model") + local tree = F.load(file("model.rbxm").data) + t:check(tree and tree.kind == "rbxtree", "F.load") + local again = F.save(tree) + t:check(type(again) == "buffer" and Rbxm.sniff(Bytes.reader(again)) == 1, "F.save keeps the source format") + local x = F.convert(file("model.rbxm").data, "rbxmx") + t:check(type(x) == "buffer" and Rbxmx.sniff(Bytes.reader(x)) == 1, "F.convert to rbxmx") + local l = F.save(tree, nil, { format = "rbxl" }) + t:eq(F.detect(l), "rbxl", "save as rbxl marks services") +end + -- fuzz do local samples = { file("model-raw.rbxm").data, Rbxm.encode(H.everything(), { compression = "none" }) :: buffer, Rbxm.encode(H.everything()) :: buffer } diff --git a/tests/model/robloxmesh.luau b/tests/model/robloxmesh.luau new file mode 100644 index 0000000..9d2da02 --- /dev/null +++ b/tests/model/robloxmesh.luau @@ -0,0 +1,202 @@ +-- model/robloxmesh tests: meshes of every version written by the fixture's spec writer (1.00 / 1.01 ASCII, 2.00 with +-- 36- and 40-byte vertices, 3.00 / 3.01 LODs, 4.00 / 4.01 / 5.00 skinned with one and several subsets, 5.00 FACS, +-- 6.00 / 7.00 chunked) decode to the values they were written from (attribute CRCs, LOD index CRCs, global joints and +-- weights, bone names / parents / world transforms, FACS, raw chunks); a Draco COREMESH is UNSUPPORTED; our 2.00 / +-- 4.00 output read back by the fixture's reader (verdicts); round trips; errors and the fuzz pass. +-- Fixtures: tools/fixtures/robloxmesh.py. +local T = require("@tests/T") +local RobloxMesh = require("@formats/model/robloxmesh") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Fx = require("@tests/gen/robloxmesh") + +local t = T.suite("robloxmesh") + +t:eq(RobloxMesh.name, "robloxmesh", "name") +t:eq(RobloxMesh.category, "model", "category") +t:check(table.find(RobloxMesh.extensions, "mesh") ~= nil, "extensions") +t:check(RobloxMesh.caps.decode and RobloxMesh.caps.encode, "caps") + +local function decode(data: any, opts: any?): (any, any) + return RobloxMesh.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- a world matrix of node i (parents through the children lists) +local function world(scene: any, i: number): { number } + local parent = {} + for k, n in scene.nodes do + for _, c in n.children do + parent[c] = k + end + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + while p do + m = Mat4.mul(Types.Scene.nodeMatrix(scene.nodes[p]), m) + p = parent[p] + end + return m +end + +local ncases = 0 +for _, c in Fx.cases do + local scene, err = decode(c.data) + if c.unsupported then + t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": unsupported (" .. tostring(err) .. ")") + continue + end + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + if not scene then + continue + end + ncases += 1 + local prim = scene.meshes[1].primitives[1] + local a = prim.attributes + t:eq(scene.meta.source.version, c.version, c.name .. ": version") + t:eq(a.POSITION.count, c.vertices, c.name .. ": vertices") + t:eq(Crc32.of(a.POSITION.data), c.pos, c.name .. ": POSITION") + t:eq(Crc32.of(a.NORMAL.data), c.nrm, c.name .. ": NORMAL") + t:eq(Crc32.of(a.TEXCOORD_0.data), c.uv, c.name .. ": TEXCOORD_0") + if c.tan then + t:check(a.TANGENT and Crc32.of(a.TANGENT.data) == c.tan, c.name .. ": TANGENT") + end + if c.col then + t:check(a.COLOR_0 and a.COLOR_0.type == "unorm8" and Crc32.of(a.COLOR_0.data) == c.col, c.name .. ": COLOR_0") + else + t:check(a.COLOR_0 == nil, c.name .. ": no COLOR_0") + end + local lods = { prim } + for _, l in (scene.meshes[1].extras or {}).lods or {} do + table.insert(lods, l) + end + t:eq(#lods, #c.lods, c.name .. ": LODs") + for k, want in c.lods do + t:check(lods[k] and Crc32.of(lods[k].indices.data) == want, c.name .. ": LOD " .. (k - 1) .. " indices") + end + if c.joints then + t:check(a.JOINTS_0 and Crc32.of(a.JOINTS_0.data) == c.joints, c.name .. ": JOINTS_0") + t:check(a.WEIGHTS_0 and Crc32.of(a.WEIGHTS_0.data) == c.weights, c.name .. ": WEIGHTS_0") + local skin = scene.skins[1] + t:eq(#skin.joints, #c.bones, c.name .. ": joints") + t:eq(skin.inverseBindMatrices.count, #c.bones, c.name .. ": inverse bind matrices") + t:eq(scene.nodes[1].skin, 1, c.name .. ": the mesh node is skinned") + local worst = 0 + for i, b in c.bones do + local j = skin.joints[i] + local node = scene.nodes[j] + t:eq(node.name, b.name, c.name .. ": bone name") + t:eq(node.extras.culling, b.culling, c.name .. ": culling") + local isRoot = table.find(scene.roots, j) ~= nil + t:eq(isRoot, b.parent == nil, c.name .. ": " .. b.name .. " root") + if b.parent then + t:check(table.find(scene.nodes[skin.joints[b.parent + 1]].children, j) ~= nil, c.name .. ": " .. b.name .. " parent") + end + local m = world(scene, j) + local cf = b.cf + local want = { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } + for k = 1, 16 do + worst = math.max(worst, math.abs(m[k] - want[k])) + end + end + t:check(worst < 1e-4, c.name .. ": bone world transforms (" .. worst .. ")") + end + if c.facs then + t:check(scene.meta.source.facs and Crc32.of(scene.meta.source.facs) == c.facs, c.name .. ": FACS kept raw") + end + if c.chunks then + t:eq(scene.meta.source.chunks[1].name, c.chunks[1], c.name .. ": raw chunk") + end + t:eq(scene.meta.up, "y", c.name .. ": up") +end +t:note("%d meshes match", ncases) + +for _, v in Fx.ours do + t:check(v.ok, v.name .. ": " .. v.detail) +end +t:note("%d of our files read back by the fixture's reader", #Fx.ours) + +-- round trips through our encoder +do + for _, name in { "v2.00-40", "v4.00-lods", "v4.00-40bones", "v6.00" } do + local c + for _, x in Fx.cases do + if x.name == name then + c = x + end + end + local s = decode(c.data) + local out = RobloxMesh.encode(s, { version = "4.00" }) :: buffer + local back = decode(out) + t:check(back ~= nil, name .. ": re-read") + local p0, p1 = s.meshes[1].primitives[1], back.meshes[1].primitives[1] + t:eq(p1.indices.count, p0.indices.count, name .. ": triangles") + if not c.joints then + t:eq(Crc32.of(p1.attributes.POSITION.data), Crc32.of(p0.attributes.POSITION.data), name .. ": positions") + t:eq(Crc32.of(p1.indices.data), Crc32.of(p0.indices.data), name .. ": indices") + t:eq(Crc32.of(p1.attributes.TANGENT.data), Crc32.of(p0.attributes.TANGENT.data), name .. ": tangents") + else + t:eq(#back.skins[1].joints, #s.skins[1].joints, name .. ": joints") + end + local v2 = decode(RobloxMesh.encode(s) :: buffer) + t:eq(v2.meta.source.version, "2.00", name .. ": 2.00 by default") + end + -- a glTF-style scene: a quad under a transformed node, no normals / colours + local s = Types.Scene.new() + local pos = buffer.create(48) + for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do + buffer.writef32(pos, (i - 1) * 4, v) + end + local idx = buffer.create(24) + for i, v in { 0, 1, 2, 0, 2, 3 } do + buffer.writeu32(idx, (i - 1) * 4, v) + end + s.meshes[1] = { primitives = { { attributes = { POSITION = Types.Scene.accessor(pos, "f32", 3, 4) }, indices = Types.Scene.accessor(idx, "u32", 1, 6), mode = "triangles" } } } + s.nodes[1] = { children = {}, mesh = 1, translation = { 10, 0, 0 } } + s.roots[1] = 1 + local q = decode(RobloxMesh.encode(s) :: buffer) + local qa = q.meshes[1].primitives[1].attributes + t:eq(buffer.readf32(qa.POSITION.data, 12), 11, "node transform applied") + t:eq(buffer.readf32(qa.NORMAL.data, 8), 1, "computed normal +Z") + t:check(qa.COLOR_0 == nil, "white / no colours: 36-byte vertices") +end + +-- sniff, errors +do + local c = Fx.cases[3] + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring("version 1.0"))), 0, "sniff short") + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring("solid cube\n"))), 0, "sniff STL") + local _, e1 = decode("version 9.00\n") + t:check(e1 and e1.code == Err.UNSUPPORTED, "version 9: " .. tostring(e1)) + local _, e2 = decode(string.sub(c.data, 1, 60)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode(c.data, { maxVertices = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "maxVertices: " .. tostring(e3)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, buffer.len(bad) - 4, 99999) + local _, e4 = decode(bad) + t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) + local _, e5 = decode("hello there, a mesh") + t:check(e5 and e5.code == Err.CORRUPT, "no version line: " .. tostring(e5)) + local _, e6 = RobloxMesh.encode(Types.Scene.new()) + t:check(e6 and e6.code == Err.ARG, "an empty scene: " .. tostring(e6)) + local _, e7 = RobloxMesh.encode(decode(c.data), { version = "3.00" } :: any) + t:check(e7 and e7.code == Err.ARG, "version 3.00 is not written") +end + +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return RobloxMesh.decode(Bytes.reader(b)) + end, samples, { mutations = 30, garbage = 300, keepHeader = 13 }) +end + +t:done() diff --git a/tools/fixtures/_robloxmesh_encode.luau b/tools/fixtures/_robloxmesh_encode.luau new file mode 100644 index 0000000..99b4ae3 --- /dev/null +++ b/tools/fixtures/_robloxmesh_encode.luau @@ -0,0 +1,30 @@ +-- tools/fixtures/_robloxmesh_encode.luau: run by tools/fixtures/robloxmesh.py under the luau CLI: decodes every case of +-- tests/gen/robloxmesh and writes it back as versions 2.00 and 4.00; prints "/ " lines for the +-- fixture's own reader. +local RobloxMesh = require("@formats/model/robloxmesh") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/robloxmesh") + +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 + +for _, c in Fx.cases do + if not c.unsupported then + local scene, err = RobloxMesh.decode(Bytes.reader(buffer.fromstring(c.data))) + if not scene then + error(c.name .. ": " .. tostring(err)) + end + for _, v in { "2.00", "4.00" } do + local out, e = RobloxMesh.encode(scene, { version = v } :: any) + if not out then + error(c.name .. "/" .. v .. ": " .. tostring(e)) + end + print(c.name .. "/" .. v .. " " .. hex(out)) + end + end +end diff --git a/tools/fixtures/robloxmesh.py b/tools/fixtures/robloxmesh.py new file mode 100644 index 0000000..a404222 --- /dev/null +++ b/tools/fixtures/robloxmesh.py @@ -0,0 +1,461 @@ +# Roblox FileMesh fixtures (tools/fixtures.py) for model/robloxmesh. No reference tool reads .mesh files, so this +# generator is an independent writer + reader written from the spec (MaximumADHD's "Roblox Mesh Format" notes, +# devforum 326114): it writes meshes of every version (1.00 / 1.01 ASCII, 2.00 with 36- and 40-byte vertices, 3.00 / +# 3.01 with LODs, 4.00 / 4.01 with bones, skinning and several subsets, 5.00 with a FACS blob, 6.00 / 7.00 chunked +# with LODS, SKINNING, FACS and HSRAVIS chunks, a 7.00 Draco COREMESH) with the values they hold, and reads our +# encoder's output (tools/fixtures/_robloxmesh_encode.luau under the luau CLI) back, as verdicts. +# tests/gen/robloxmesh.luau { cases = { { name, data, version, vertices, faces, pos, nrm, uv, tan?, col?, lods = +# { idx crc ... }, joints?, weights?, bones? = { { name, parent, cf } }, facs?, chunks?, +# unsupported? } }, ours = { { name, ok, detail } } } +import json, math, os, random, shutil, struct, subprocess, zlib + +INPUTS = ["src/Formats/model/robloxmesh", "tools/fixtures/_robloxmesh_encode.luau"] + + +def f32(x): + return struct.unpack("= 128 else v + + +# ---------------------------------------------------------------------------------------------------- geometry +def sphere(rng, rings, segs, radius=2.0): + verts, faces = [], [] + for i in range(rings + 1): + th = math.pi * i / rings + for j in range(segs + 1): + ph = 2 * math.pi * j / segs + n = [math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)] + verts.append({ + "pos": [f32(c * radius + rng.uniform(-0.01, 0.01)) for c in n], + "nrm": [f32(c) for c in n], + "uv": [f32(j / segs), f32(i / rings)], + "tan": [rng.randrange(-127, 128) for _ in range(3)] + [rng.choice((-127, 127))], + "col": [rng.randrange(256) for _ in range(4)], + }) + for i in range(rings): + for j in range(segs): + a = i * (segs + 1) + j + b = a + segs + 1 + faces += [(a, b, a + 1), (a + 1, b, b + 1)] + return verts, faces + + +def vbytes(v, size): + out = pk("f", v["pos"] + v["nrm"] + v["uv"]) + bytes(t & 255 for t in v["tan"]) + if size >= 40: + out += bytes(v["col"]) + return out + + +def fbytes(faces): + return b"".join(pk("I", list(f)) for f in faces) + + +def tangent_f32(t): + return [f32(max(-1.0, min(1.0, c / 127))) for c in t] + + +def expect_core(verts, faces, lods, colors, tangents=True): + exp = { + "vertices": len(verts), "faces": len(faces), + "pos": crc(b"".join(pk("f", v["pos"]) for v in verts)), + "nrm": crc(b"".join(pk("f", v["nrm"]) for v in verts)), + "uv": crc(b"".join(pk("f", v["uv"]) for v in verts)), + "lods": [crc(fbytes(faces[lods[k]:lods[k + 1]])) for k in range(len(lods) - 1)], + } + if tangents: + exp["tan"] = crc(b"".join(pk("f", tangent_f32(v["tan"])) for v in verts)) + if colors: + exp["col"] = crc(b"".join(bytes(v["col"]) for v in verts)) + return exp + + +# ---------------------------------------------------------------------------------------------------- bones / skinning +def rot_y(a): + c, s = math.cos(a), math.sin(a) + return [c, 0, s, 0, 1, 0, -s, 0, c] + + +def make_bones(rng, n): + bones = [] + for i in range(n): + parent = None if i == 0 else rng.randrange(i) + r = rot_y(rng.uniform(-3, 3)) + cf = [f32(x) for x in r + [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)]] + bones.append({"name": "Bone%02d" % i if i else "Root", "parent": parent, "cf": cf, "culling": f32(rng.uniform(0, 5)), "lodParent": 0xFFFF}) + return bones + + +def make_skin(rng, verts, faces, bones, segs=12): + """influences per vertex (1..4 bones from a window that moves with the sphere ring, so a third of the faces needs + at most ~20 bones), then subsets by face thirds; vertices are duplicated per subset (the format needs contiguous + vertex ranges). Returns new verts, faces, subsets, envelopes, the expected global joints / weights""" + nb = len(bones) + infl = [] + for v in range(len(verts)): + ring = v // (segs + 1) + window = [(ring * 4 + k) % nb for k in range(min(8, nb))] + k = rng.randrange(1, 5) + bs = rng.sample(window, min(k, len(window))) + w = [rng.randrange(1, 100) for _ in bs] + tot = sum(w) + wb = [x * 255 // tot for x in w] + wb[0] += 255 - sum(wb) + infl.append(list(zip(bs, wb))) + nverts, nfaces, subsets, env, joints, weights = [], [], [], [], [], [] + chunk = max(1, len(faces) // 3) + for s0 in range(0, len(faces), chunk): + sub_faces = faces[s0:s0 + chunk] + used = [] + for f in sub_faces: + for v in f: + if v not in used: + used.append(v) + sub_bones = sorted({b for v in used for b, _ in infl[v]}) + assert len(sub_bones) <= 26 + loc = {b: i for i, b in enumerate(sub_bones)} + remap = {} + vb = len(nverts) + for v in used: + remap[v] = len(nverts) + nverts.append(verts[v]) + pairs = infl[v] + [(None, 0)] * (4 - len(infl[v])) + env.append(bytes(loc[b] if b is not None else 0 for b, _ in pairs) + bytes(w for _, w in pairs)) + joints.append([b if b is not None else 0 for b, _ in pairs]) + weights.append([w for _, w in pairs]) + for f in sub_faces: + nfaces.append(tuple(remap[v] for v in f)) + subsets.append({"facesBegin": s0, "facesLength": len(sub_faces), "vertsBegin": vb, "vertsLength": len(nverts) - vb, "bones": sub_bones}) + return nverts, nfaces, subsets, env, joints, weights + + +def bone_bytes(bones): + names = b"" + out = b"" + for b in bones: + idx = len(names) + names += b["name"].encode() + b"\0" + out += struct.pack("= 40 else [255] * 4 + verts.append({"pos": list(v[:3]), "nrm": list(v[3:6]), "uv": list(v[6:8]), "tan": t, "col": col}) + p += nv * vs + env = [] + if version == "4.00" and nb > 0: + env = [rest[p + 8 * i:p + 8 * i + 8] for i in range(nv)] + p += 8 * nv + faces = [struct.unpack_from("<3I", rest, p + 12 * i) for i in range(nf)] + p += 12 * nf + if version == "4.00": + lods = list(struct.unpack_from("<%dI" % nl, rest, p)) + p += 4 * nl + bones = [] + for i in range(nb): + ni, par, lp, cull = struct.unpack_from(" ok, detail""" + a, b = src, out + if len(b["verts"]) < 1: + return False, "no vertices" + if sorted(corners(a)) != sorted(corners(b)): + return False, "LOD 0 triangles differ" + if b["version"] == "4.00": + if len(a["lods"]) != len(b["lods"]) and not b["bones"]: + return False, "LOD count %d, want %d" % (len(b["lods"]), len(a["lods"])) + if not b["bones"]: + for k in range(len(a["lods"]) - 1): + if sorted(corners(a, k)) != sorted(corners(b, k)): + return False, "LOD %d differs" % k + if a["bones"]: + if [x["name"] for x in a["bones"]] != [x["name"] for x in b["bones"]] or [x["parent"] for x in a["bones"]] != [x["parent"] for x in b["bones"]]: + return False, "bones differ" + for x, y in zip(a["bones"], b["bones"]): + if any(abs(p - q) > 1e-4 for p, q in zip(x["cf"], y["cf"])): + return False, "bone %s transform differs" % x["name"] + ia, ib = vertex_influences(a), vertex_influences(b) + key = lambda m, i: tuple(m["verts"][i]["pos"] + m["verts"][i]["uv"]) + want = {key(a, i): ia[i] for i in range(len(a["verts"]))} + for i in range(len(b["verts"])): + w = want.get(key(b, i)) + if w is None or ib[i] is None: + return False, "vertex %d has no influences" % i + if set(w) != set(ib[i]) or any(abs(w[j] - ib[i][j]) > 1 for j in w): + return False, "vertex %d influences %r, want %r" % (i, ib[i], w) + return True, "%d vertices, %d faces, %d bones, %d subsets" % (len(b["verts"]), len(b["faces"]), len(b["bones"]), len(b["subsets"])) + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def generate(ctx): + rng = random.Random(1337) + cases = [] + sv, sf = sphere(rng, 8, 12) + for version in ("1.00", "1.01"): + data, exp = write_v1(version, sv, sf[:60]) + cases.append(dict(exp, name="v" + version, data=data, version=version)) + for colors in (False, True): + data, exp = write_v2(sv, sf, colors) + cases.append(dict(exp, name="v2.00-%d" % (40 if colors else 36), data=data, version="2.00")) + lods = [0, len(sf) // 2, len(sf) * 3 // 4, len(sf)] + for version in ("3.00", "3.01"): + data, exp = write_v3(version, sv, sf, lods) + cases.append(dict(exp, name="v" + version, data=data, version=version)) + # skinned: 6 bones (one subset of all of them) and 40 bones (several subsets of up to 26) + bones6 = make_bones(rng, 6) + bones40 = make_bones(rng, 40) + for version in ("4.00", "4.01", "5.00"): + for bones in (bones6, bones40): + nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones) + lods2 = [0, len(nf)] + facs = bytes(rng.randrange(256) for _ in range(77)) if version == "5.00" else None + data, exp = write_v45(version, nv, nf, lods2, bones, subs, env, facs) + exp = skin_expect(exp, bones, joints, weights) + if facs: + exp["facs"] = crc(facs) + cases.append(dict(exp, name="v%s-%dbones" % (version, len(bones)), data=data, version=version)) + # unskinned 4.00 with LODs + data, exp = write_v45("4.00", sv, sf, lods, [], [], []) + cases.append(dict(exp, name="v4.00-lods", data=data, version="4.00")) + for version in ("6.00", "7.00"): + nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones40) + facs = bytes(rng.randrange(256) for _ in range(40)) + data, exp = write_v67(version, nv, nf, [0, len(nf) // 2, len(nf)], bones40, subs, env, facs, hsr=True) + exp = skin_expect(exp, bones40, joints, weights) + exp["facs"] = crc(facs) + exp["chunks"] = ["HSRAVIS"] + cases.append(dict(exp, name="v" + version, data=data, version=version)) + data, _ = write_v67("7.00", sv, sf, [0, len(sf)], [], [], [], None, hsr=False, draco=True) + cases.append({"name": "v7.00-draco", "data": data, "version": "7.00", "unsupported": True}) + ctx.emit("robloxmesh", {"cases": cases}) + + # ours: every decodable case re-encoded as 2.00 and 4.00, read back here + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_robloxmesh_encode.luau")], capture_output=True, cwd=ctx.root) + if enc.returncode != 0: + raise RuntimeError("_robloxmesh_encode: " + enc.stderr.decode(errors="replace")[-3000:]) + originals = {} + byname = {c["name"]: c for c in cases} + ours = [] + for line in enc.stdout.decode().split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + name, version = label.rsplit("/", 1) + try: + out = read_mesh(bytes.fromhex(hexdata.strip())) + if name not in originals: + originals[name] = read_original(byname[name]) + ok, detail = check_ours(originals[name], out) + except Exception as e: # a reader failure is a verdict, not a fixture error + ok, detail = False, "read: %r" % e + ours.append({"name": label, "ok": ok, "detail": detail}) + ctx.emit("robloxmesh", {"cases": cases, "ours": ours}) + + +def read_original(case): + """a fixture case as the record read_mesh gives (version 1 / 3 / 5 / 6 / 7 are rewritten through the 4.00 shape)""" + data = case["data"] + line, rest = data.split(b"\n", 1) + version = line.decode().split()[1] + if version in ("1.00", "1.01"): + text = rest.decode().split("\n", 1)[1] + vals = [float(x) for x in text.replace("][", ",").strip("[]").split(",")] + scale = 0.5 if version == "1.00" else 1 + verts = [] + for i in range(0, len(vals), 9): + verts.append({"pos": [f32(c * scale) for c in vals[i:i + 3]], "nrm": [f32(c) for c in vals[i + 3:i + 6]], "uv": [f32(vals[i + 6]), f32(1 - vals[i + 7])]}) + nf = len(verts) // 3 + return {"version": version, "verts": verts, "faces": [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(nf)], "lods": [0, nf], "bones": [], "subsets": [], "env": []} + if version == "2.00": + return read_mesh(data) + if version in ("3.00", "3.01"): + hs, vs, fs, ls, nl, nv, nf = struct.unpack_from("