ws-roblox: model/robloxmesh (.mesh 1.00-5.00, 6.00/7.00 chunked with raw COREMESH read; Draco COREMESH UNSUPPORTED; 2.00 / 4.00 write with skinning subsets and LODs) mapped to Scene; rbxm / rbxmx variant() for F.detect (rbxl / rbxlx); api tests

This commit is contained in:
4DBug committed 2026-10-31 14:33:15 -05:00
1 parent bd696dea1e
commit 3a1965486f
11 files changed
+1886

No files matched your search

+12
View File
@@ -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",
+30
View File
@@ -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 }
+6
View File
@@ -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, '<Item class="Workspace"', 1, true) then "rbxlx" else "rbxmx"
end
-- ------------------------------------------------------------------------------------------------ decode
local function num(s: string?): number
if s == nil then
+440
View File
@@ -0,0 +1,440 @@
--!strict
--!native
--!optimize 2
-- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version:
-- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the
-- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 is "unsupported"). Written from
-- MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data.
local Parse = {}
local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Bone = { name: string, parent: number?, lodParent: number, culling: number, cf: { number } } -- cf: r00..r22, x, y, z
export type Subset = { facesBegin: number, facesLength: number, vertsBegin: number, vertsLength: number, bones: { number } }
export type Record = {
version: string,
numVerts: number,
numFaces: number,
pos: buffer, -- f32 x3
nrm: buffer, -- f32 x3
uv: buffer, -- f32 x2
tan: buffer?, -- i8 x4 (nil in version 1)
col: buffer?, -- u8 x4 (nil when the vertices have none)
faces: buffer, -- u32 x3
lods: { number },
lodType: number,
highQualityLods: number,
bones: { Bone },
subsets: { Subset },
env: buffer?, -- per vertex: 4 subset-local bone indices, 4 weights (u8)
facsFormat: number,
facs: buffer?,
chunks: { { name: string, version: number, data: buffer } }, -- 6.00+ chunks kept raw (HSRAVIS, unknown)
}
export type Limits = { maxVertices: number, maxFaces: number }
local function record(version: string): Record
return {
version = version,
numVerts = 0,
numFaces = 0,
pos = buffer.create(0),
nrm = buffer.create(0),
uv = buffer.create(0),
tan = nil,
col = nil,
faces = buffer.create(0),
lods = {},
lodType = 0,
highQualityLods = 0,
bones = {},
subsets = {},
env = nil,
facsFormat = 0,
facs = nil,
chunks = {},
}
end
-- ------------------------------------------------------------------------------------------------ version 1
local function ascii(text: string, version: string, lim: Limits): (Record?, string?)
local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)"))
if not nf then
return nil, "corrupt: no face count"
end
if nf * 3 > 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
+109
View File
@@ -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
+578
View File
@@ -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