merge ws/3d3-mesh

This commit is contained in:
4DBug committed 2026-10-31 16:16:07 -05:00
commit d2727aeab0
7 files changed
+291 -36

No files matched your search

+2 -1
View File
@@ -78,7 +78,8 @@ A `.mesh` of any version from 1.00 to 7.00 loads as a one-mesh `Scene`:
- **Attributes:** `POSITION`, `NORMAL`, `TEXCOORD_0`, `TANGENT` and `COLOR_0`.
- **LODs:** LOD 0 is the primitive. The other LODs are in `mesh.extras.lods`.
- **Skinning:** bones become a skin with joint nodes, and the vertices get `JOINTS_0` / `WEIGHTS_0`.
- **Not decoded yet:** Draco-compressed meshes (7.00) return `UNSUPPORTED`.
- **Draco:** a Draco-compressed core mesh (6.00 / 7.00) decodes through `codecs/model/Draco`; `meta.source.draco` is
`true` for those files.
```luau
local scene = assert(F.load(meshBytes, { format = "robloxmesh" }))
+1 -1
View File
@@ -980,7 +980,7 @@ local list: { Entry } = {
path = "model/robloxmesh",
extensions = { "mesh" },
mime = { "application/x-roblox-mesh" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" },
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")
+48 -28
View File
@@ -3,8 +3,8 @@
--!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.
-- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core
-- callback). 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
@@ -31,9 +31,13 @@ export type Record = {
facsFormat: number,
facs: buffer?,
chunks: { { name: string, version: number, data: buffer } }, -- 6.00+ chunks kept raw (HSRAVIS, unknown)
coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed
}
export type Limits = { maxVertices: number, maxFaces: number }
-- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record
-- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco)
export type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer }
export type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? }
local function record(version: string): Record
return {
@@ -55,6 +59,7 @@ local function record(version: string): Record
facsFormat = 0,
facs = nil,
chunks = {},
coreVersion = nil,
}
end
@@ -298,34 +303,49 @@ local function chunked(b: buffer, p: number, e: number, version: string, lim: Li
end
if name == "COREMESH" then
if cv == 2 then
return nil, "unsupported: Draco-compressed COREMESH (needs codecs/model/Draco)"
local decodeCore = lim.core
if not decodeCore then
return nil, "unsupported: Draco-compressed COREMESH"
end
local c, cerr = decodeCore(b, q, size)
if not c then
return nil, cerr or "corrupt: bad Draco COREMESH"
end
if c.numVerts > lim.maxVertices or c.numFaces > lim.maxFaces then
return nil, "limit: " .. c.numVerts .. " vertices, " .. c.numFaces .. " faces"
end
r.numVerts, r.pos, r.nrm, r.uv, r.tan, r.col = c.numVerts, c.pos, c.nrm, c.uv, c.tan, c.col
r.numFaces, r.faces = c.numFaces, c.faces
core = true
r.coreVersion = 2
elseif cv ~= 1 then
return nil, "unsupported: COREMESH version " .. cv
else
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
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"
+110 -4
View File
@@ -3,8 +3,9 @@
-- 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
-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes
-- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC
-- one as the tangents (meta.source.draco = true). 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
@@ -23,6 +24,7 @@ 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 Draco = require("@formats/codecs/model/Draco")
local Parse = require("@formats/model/robloxmesh/Parse")
local Write = require("@formats/model/robloxmesh/Write")
@@ -32,7 +34,7 @@ local RobloxMesh = {
category = "model",
extensions = { "mesh" },
mime = { "application/x-roblox-mesh" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" },
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" } },
}
@@ -67,8 +69,111 @@ local function indices(r: Parse.Record, from: number, to: number): Types.Accesso
return accessor(d, "u32", 1, n * 3)
end
-- a Draco-compressed COREMESH body -> the record's vertex / face fields
local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?)
-- the stream follows a u32 byte count (accepted without it too)
if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then
len = buffer.readu32(b, off)
off += 4
end
local g, err = Draco.decode(b, off, len)
if not g then
return nil, (err :: Err.Err).message
end
if g.kind ~= "mesh" then
return nil, "corrupt: Draco COREMESH holds a point cloud"
end
local n = g.numPoints
local by: { [string]: Draco.Attribute } = {}
for _, a in g.attributes do
local key = if a.name == "GENERIC" and a.components == 4 then "TANGENT" else a.name
if not by[key] then
by[key] = a
end
end
local pos = by.POSITION
if not pos or pos.components < 3 then
return nil, "corrupt: Draco COREMESH without positions"
end
-- an attribute's values as numbers (normalized integers as -1..1 / 0..1)
local function getter(a: Draco.Attribute): (number, number) -> number
local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type
local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n })
if not rd then
return function(_i: number, _c: number): number
return 0
end
end
return rd
end
local function floats(a: Draco.Attribute?, comps: number): buffer
local out = buffer.create(n * comps * 4)
if a then
local get = getter(a)
local m = math.min(comps, a.components)
for i = 0, n - 1 do
for c = 0, m - 1 do
writef32(out, (i * comps + c) * 4, get(i, c))
end
end
end
return out
end
local tan: buffer? = nil
if by.TANGENT then
local get = getter(by.TANGENT)
local t = buffer.create(n * 4)
for i = 0, n - 1 do
for c = 0, 3 do
local v = if c < by.TANGENT.components then get(i, c) else 1
buffer.writei8(t, i * 4 + c, math.clamp(math.floor(v * 127 + 0.5), -127, 127))
end
end
tan = t
end
local col: buffer? = nil
if by.COLOR then
local a = by.COLOR
local c = buffer.create(n * 4)
if a.type == "u8" and a.components == 4 then
buffer.copy(c, 0, a.data, 0, n * 4)
else
local get = getter(a)
for i = 0, n - 1 do
for k = 0, 3 do
local v = if k < a.components then get(i, k) else 1
if a.type ~= "f32" and not a.normalized then
v /= 255
end
writeu8(c, i * 4 + k, math.clamp(math.floor(v * 255 + 0.5), 0, 255))
end
end
end
col = c
end
return {
numVerts = n,
pos = floats(pos, 3),
nrm = floats(by.NORMAL, 3),
uv = floats(by.TEX_COORD, 2),
tan = tan,
col = col,
numFaces = g.numFaces,
faces = g.indices :: buffer,
}, nil
end
-- Parse is native: nothing may throw through it, so the callback never does
local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?)
local ok, c, err = pcall(dracoCore, b, off, len)
if not ok then
return nil, "corrupt: Draco COREMESH: " .. tostring(c)
end
return c, err
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 lim: Parse.Limits = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25, core = safeCore }
local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim)
if not r then
return nil, Err.from(msg, rd.base)
@@ -188,6 +293,7 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene
facsFormat = r.facsFormat,
facs = r.facs,
chunks = r.chunks,
draco = if r.coreVersion == 2 then true else nil,
}
return scene, nil
end
+3 -2
View File
@@ -1,7 +1,7 @@
-- 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 /
-- weights, bone names / parents / world transforms, FACS, raw chunks); a COREMESH v2 that is not a Draco stream is CORRUPT; 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")
@@ -45,7 +45,8 @@ 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) .. ")")
-- a COREMESH v2 whose body is not a Draco stream (real Draco meshes: tests/model/robloxmesh_draco.luau)
t:check(scene == nil and err and err.code == Err.CORRUPT, c.name .. ": not Draco data (" .. tostring(err) .. ")")
continue
end
t:check(scene ~= nil, c.name .. ": " .. tostring(err))
+57
View File
@@ -0,0 +1,57 @@
-- model/robloxmesh with a Draco-compressed COREMESH (6.00 / 7.00, COREMESH v2): draco_encoder streams of a UV sphere
-- (normals, uvs) and a coloured PLY at three compression levels, wrapped in the chunk layout. Positions, normals,
-- uvs, colours and indices match libdraco's decode byte for byte, and the scene equals the decode of the same mesh
-- written with a plain COREMESH v1; corrupt streams fail without throwing (fuzz). Fixtures:
-- tools/fixtures/robloxmesh_draco.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 Cases = require("@tests/gen/robloxmesh_draco")
local t = T.suite("robloxmesh_draco")
local function decode(data: string): (any, any)
return RobloxMesh.decode(Bytes.reader(buffer.fromstring(data)))
end
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data)
t:check(scene, c.name .. ": " .. tostring(err))
if scene then
t:check(scene.meta.source.draco == true, c.name .. ": meta.source.draco")
local prim = scene.meshes[1].primitives[1]
local a = prim.attributes
t:eq(a.POSITION.count, c.points, c.name .. ": vertices")
t:eq(prim.indices.count, c.faces * 3, c.name .. ": indices")
t:eq(Crc32.of(prim.indices.data), c.indices, c.name .. ": index CRC")
t:eq(Crc32.of(a.POSITION.data), c.pos, c.name .. ": positions")
if c.nrm then
t:eq(Crc32.of(a.NORMAL.data), c.nrm, c.name .. ": normals")
end
if c.uv then
t:eq(Crc32.of(a.TEXCOORD_0.data), c.uv, c.name .. ": uvs")
end
if c.col then
t:eq(Crc32.of(a.COLOR_0.data), c.col, c.name .. ": colours")
end
-- the same mesh as a plain COREMESH v1
local plain = assert(decode(c.plain))
local pp = plain.meshes[1].primitives[1]
for _, name in { "POSITION", "NORMAL", "TEXCOORD_0" } do
t:eq(Crc32.of(a[name].data), Crc32.of(pp.attributes[name].data), c.name .. ": " .. name .. " like COREMESH v1")
end
t:eq(Crc32.of(prim.indices.data), Crc32.of(pp.indices.data), c.name .. ": indices like COREMESH v1")
-- written back as 2.00 and read again
local back = assert(decode(buffer.tostring(assert(RobloxMesh.encode(scene)))))
t:eq(back.meshes[1].primitives[1].indices.count, c.faces * 3, c.name .. ": round trip")
if #c.data < 3000 then
table.insert(samples, c.data)
end
end
end
t:fuzz("decode", function(b: buffer)
return RobloxMesh.decode(Bytes.reader(b))
end, samples, { mutations = 12, keepHeader = 13 })
t:done()
+70
View File
@@ -0,0 +1,70 @@
# Roblox mesh 6.00 / 7.00 with a Draco-compressed COREMESH (v2: a u32 size, then the stream) (tools/fixtures.py). The
# Draco streams are made by draco_encoder 1.5.7 (nix) from a generated UV sphere (OBJ: positions, normals, uvs) and a
# coloured PLY, at two compression levels; each is wrapped with LODS (and for one an empty SKINNING) chunks, and the
# same mesh is also written with a plain COREMESH v1 from libdraco's own decode (tools/fixtures/_draco_dump.cc), so
# the test compares the two decodes and the values against libdraco.
# tests/gen/robloxmesh_draco.luau { { name, data, plain, points, faces, indices = crc, pos, nrm?, uv?, col? = crc } }
import importlib.util, os, struct, subprocess, tempfile, zlib
INPUTS = ["tools/fixtures/_draco_dump.cc", "tools/fixtures/draco.py"]
def chunk(name, version, body):
return name.ljust(8, b"\0") + struct.pack("<II", version, len(body)) + body
def generate(ctx):
spec = importlib.util.spec_from_file_location("draco_fx", os.path.join(ctx.root, "tools", "fixtures", "draco.py"))
dfx = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dfx)
draco = dfx.store_path("draco")
tmp = tempfile.mkdtemp(prefix="formats-rbxdraco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
rng = ctx.rng(7)
inputs = {"sphere.obj": dfx.uv_sphere(10, 16), "colored.ply": dfx.colored_ply(rng, 90)}
cases = []
for iname, text in inputs.items():
ipath = os.path.join(tmp, iname)
open(ipath, "w").write(text)
for cl in (0, 7, 10):
out = os.path.join(tmp, "%s.%d.drc" % (iname, cl))
subprocess.run([os.path.join(draco, "bin", "draco_encoder"), "-i", ipath, "-o", out, "-cl", str(cl)], capture_output=True, check=True)
drc = open(out, "rb").read()
lines = subprocess.run([dump, out], capture_output=True, check=True).stdout.decode().split("\n")
npts, faces, attrs = 0, b"", {}
for line in lines:
p = line.split(" ")
if p[0] == "POINTS":
npts = int(p[1])
elif p[0] == "FACES":
faces = bytes.fromhex(p[2])
elif p[0] == "ATTR":
t = int(p[1])
if t not in attrs:
attrs[t] = (int(p[2]), int(p[3]), bytes.fromhex(p[6]))
# the plain (v1) layout of the same mesh: 40-byte vertices (pos, normal, uv, tangent, colour)
def get(t, i, size):
a = attrs.get(t)
return a[2][i * size:(i + 1) * size] if a else bytes(size)
verts = b""
for i in range(npts):
col = attrs.get(2)
verts += get(0, i, 12) + get(1, i, 12) + get(3, i, 8) + bytes(4) + (col[2][i * 4:i * 4 + 4] if col else b"\xff\xff\xff\xff")
nf = len(faces) // 12
lods = chunk(b"LODS", 1, struct.pack("<HBI", 3, 1, 2) + struct.pack("<II", 0, nf))
for version in ("6.00", "7.00"):
head = ("version %s\n" % version).encode()
data = head + chunk(b"COREMESH", 2, struct.pack("<I", len(drc)) + drc) + lods
plain = head + chunk(b"COREMESH", 1, struct.pack("<I", npts) + verts + struct.pack("<I", nf) + faces) + lods
c = {"name": "%s cl%d v%s" % (iname, cl, version), "data": data, "plain": plain, "points": npts, "faces": nf,
"indices": zlib.crc32(faces), "pos": zlib.crc32(attrs[0][2])}
if 1 in attrs:
c["nrm"] = zlib.crc32(attrs[1][2])
if 3 in attrs:
c["uv"] = zlib.crc32(attrs[3][2])
if 2 in attrs and attrs[2][0] == 2 and attrs[2][1] == 4:
c["col"] = zlib.crc32(attrs[2][2])
cases.append(c)
ctx.emit("robloxmesh_draco", cases)