merge ws/roblox (codecs/compress/Lz4 for Anvil LZ4 chunks); registry regenerated

This commit is contained in:
4DBug committed 2026-10-31 14:38:23 -05:00
commit 09354cbd12
23 files changed
+5959 -1

No files matched your search

+5
View File
@@ -41,6 +41,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
| 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 | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.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` |
@@ -106,6 +109,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
@@ -130,6 +134,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
- **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt,
+36
View File
@@ -446,6 +446,42 @@ local list: { Entry } = {
return require("@formats/model/ply")
end,
},
{
name = "rbxm",
category = "model",
path = "model/rbxm",
extensions = { "rbxm", "rbxl" },
mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" },
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" },
caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } },
load = function()
return require("@formats/model/rbxm")
end,
},
{
name = "rbxmx",
category = "model",
path = "model/rbxmx",
extensions = { "rbxmx", "rbxlx" },
mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" },
deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" },
caps = { decode = true, encode = true, tree = true },
load = function()
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 = "schematic",
category = "model",
+291
View File
@@ -0,0 +1,291 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
--
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
-- Lz4.bound(n) -- worst-case block size for n bytes
--
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Lz4 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
}
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len
local band, rshift = bit32.band, bit32.rshift
local MINMATCH = 4
local LASTLITERALS = 5 -- the last 5 bytes are always literals
local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end
local MAX_OFFSET = 65535
local HASH_BITS = 13
local HASH_SIZE = 2 ^ HASH_BITS
-- ------------------------------------------------------------------------------------------------ decode
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
local lo = histStart or d
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
return nil, "corrupt: bad ranges"
end
if p >= limit then
return nil, "truncated: empty block"
end
while true do
if p >= limit then
return nil, "truncated"
end
local token = readu8(src, p)
p += 1
local lit = rshift(token, 4)
if lit == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
lit += b
end
end
if lit > 0 then
if p + lit > limit then
return nil, "truncated: literals past the end"
end
if d + lit > dstLimit then
return nil, "limit: output larger than expected"
end
bcopy(dst, d, src, p, lit)
p += lit
d += lit
end
if p >= limit then
return d, nil -- the last sequence has no match
end
if p + 2 > limit then
return nil, "truncated"
end
local off = readu16(src, p)
p += 2
if off == 0 or d - off < lo then
return nil, "corrupt: bad match offset"
end
local ml = band(token, 15)
if ml == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
ml += b
end
end
ml += MINMATCH
if d + ml > dstLimit then
return nil, "limit: output larger than expected"
end
local s = d - off
if off >= ml then
bcopy(dst, d, dst, s, ml)
d += ml
elseif off == 1 then
buffer.fill(dst, d, readu8(dst, s), ml)
d += ml
else
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
local n = ml
while n > 0 do
local c = d - s
if c > n then
c = n
end
bcopy(dst, d, dst, s, c)
d += c
n -= c
end
end
end
end
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
return nil, aerr
end
if outSize ~= nil then
if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize")
end
local out = bcreate(outSize)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize)
if not e then
return nil, Err.from(msg, o)
end
if e ~= outSize then
return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o)
end
return out, nil
end
local max = (opts and opts.maxBytes) or 2 ^ 28
local size = math.min(math.max(l * 4, 256), max)
while true do
local out = bcreate(size)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size)
if e then
local res = bcreate(e)
bcopy(res, 0, out, 0, e)
return res, nil
end
if not (msg and string.sub(msg, 1, 6) == "limit:") then
return nil, Err.from(msg, o)
end
if size >= max then
return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o)
end
size = math.min(size * 4, max)
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- bound(n) -> the largest block n input bytes can produce
function Lz4.bound(n: number): number
return n + n // 255 + 16
end
-- writes a length's 255-run extension at o; returns the next offset
local function extend(dst: buffer, o: number, n: number): number
while n >= 255 do
writeu8(dst, o, 255)
o += 1
n -= 255
end
writeu8(dst, o, n)
return o + 1
end
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
local function hash(v: number): number
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1
end
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
local op = d
local anchor = p
local iend = p + n
local ht = hashTable
for i = 1, HASH_SIZE do
ht[i] = -1e9
end
if n >= MFLIMIT + 1 then
local mflimit = iend - MFLIMIT -- a match starts before this
local matchEnd = iend - LASTLITERALS -- and ends at or before this
local ip = p
local skip = 64
while ip < mflimit do
local v = readu32(src, ip)
local h = hash(v)
local ref = ht[h]
ht[h] = ip
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
-- back over equal bytes before the match (into the pending literals)
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
ip -= 1
ref -= 1
end
local a = ip + MINMATCH
local bpos = ref + MINMATCH
while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do
a += 4
bpos += 4
end
while a < matchEnd and readu8(src, a) == readu8(src, bpos) do
a += 1
bpos += 1
end
local ml = a - ip
local lit = ip - anchor
local tok = op
op += 1
local tl = if lit >= 15 then 15 else lit
if lit >= 15 then
op = extend(dst, op, lit - 15)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
writeu16(dst, op, ip - ref)
op += 2
local m = ml - MINMATCH
local tm = if m >= 15 then 15 else m
if m >= 15 then
op = extend(dst, op, m - 15)
end
writeu8(dst, tok, tl * 16 + tm)
ip = a
anchor = ip
skip = 64
-- index the position just before the next one (better ratio at no cost)
if ip - 2 >= p and ip - 2 < mflimit then
local w = readu32(src, ip - 2)
ht[hash(w)] = ip - 2
end
else
ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration)
skip += 1
end
end
end
-- the last literals
local lit = iend - anchor
local tok = op
op += 1
if lit >= 15 then
op = extend(dst, op, lit - 15)
writeu8(dst, tok, 0xF0)
else
writeu8(dst, tok, lit * 16)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
return op - d
end
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
if not b then
return nil, aerr
end
local tmp = bcreate(Lz4.bound(l))
local n = Lz4.encodeInto(b, o, l, tmp, 0)
local out = bcreate(n)
bcopy(out, 0, tmp, 0, n)
return out, nil
end
return Lz4
+774
View File
@@ -0,0 +1,774 @@
--!strict
--!native
--!optimize 2
-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk
-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte
-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated"
-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws.
--
-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms)
-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message
-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT)
--
-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none),
-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }.
-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know /
-- a layout it cannot read, which the format keeps raw).
local Rbx = require("@formats/codecs/model/Rbx")
local Bytes = require("@formats/core/Bytes")
local Binary = {}
local readu8, readu16, readi16, readu32, readf32, readf64 =
buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64
local writeu32, readstring = buffer.writeu32, buffer.readstring
local writef32 = buffer.writef32
local floor = math.floor
local scratch = buffer.create(8)
local TWO32 = 4294967296
-- ------------------------------------------------------------------------------------------------ transforms
-- the rotated float encoding: bits rotated left by one (sign in bit 0)
local function unrotate(x: number): number
writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648)
return readf32(scratch, 0)
end
local function rotate(v: number): number
writef32(scratch, 0, v)
local bits = readu32(scratch, 0)
return (bits * 2) % TWO32 + bits // 2147483648
end
local function unzigzag(x: number): number
return if x % 2 == 0 then x // 2 else -(x + 1) // 2
end
local function zigzag32(v: number): number
v = floor(v)
return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32
end
-- n big-endian u32 values interleaved at p (4n bytes)
local function u32s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
local n2, n3 = n * 2, n * 3
for i = 0, n - 1 do
out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i)
end
return out
end
local function i32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unzigzag(out[i])
end
return out
end
local function f32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unrotate(out[i])
end
return out
end
-- n zigzag i64 values (8n interleaved bytes), as doubles
local function i64s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
for i = 0, n - 1 do
local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i)
local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i)
local half = hi * 2147483648 + lo // 2
out[i + 1] = if lo % 2 == 0 then half else -half - 1
end
return out
end
-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64
local function putU32s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(4 * n)
local b = w.buf
for i = 0, n - 1 do
local v = vals[i + 1] % TWO32
buffer.writeu8(b, p + i, v // 16777216)
buffer.writeu8(b, p + n + i, (v // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, v % 256)
end
w.pos = p + 4 * n
end
local function putI32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = zigzag32(v)
end
putU32s(w, t)
end
local function putF32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = rotate(v)
end
putU32s(w, t)
end
local function putI64s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(8 * n)
local b = w.buf
for i = 0, n - 1 do
local v = floor(vals[i + 1])
local z = if v >= 0 then v * 2 else -v * 2 - 1
local hi, lo = (z // TWO32) % TWO32, z % TWO32
buffer.writeu8(b, p + i, hi // 16777216)
buffer.writeu8(b, p + n + i, (hi // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, hi % 256)
buffer.writeu8(b, p + 4 * n + i, lo // 16777216)
buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256)
buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256)
buffer.writeu8(b, p + 7 * n + i, lo % 256)
end
w.pos = p + 8 * n
end
-- referent arrays: zigzag i32, interleaved, each the difference from the previous one
function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number)
if n < 0 or p + 4 * n > limit then
return nil, p
end
local out = i32s(b, p, n)
local acc = 0
for i = 1, n do
acc += out[i]
out[i] = acc
end
return out, p + 4 * n
end
function Binary.writeRefs(w: Bytes.Writer, refs: { number })
local d = table.create(#refs, 0)
local prev = 0
for i, r in refs do
d[i] = r - prev
prev = r
end
putI32s(w, d)
end
-- ------------------------------------------------------------------------------------------------ decode
export type Ctx = {
ref: ((number) -> any)?,
refOf: ((any) -> number)?,
shared: { string }?,
sharedIndex: ((string) -> number)?,
}
-- a length-prefixed string at p: string, next p (nil when it runs past limit)
local function str(b: buffer, p: number, limit: number): (string?, number)
if p + 4 > limit then
return nil, p
end
local len = readu32(b, p)
if p + 4 + len > limit then
return nil, p
end
return readstring(b, p + 4, len), p + 4 + len
end
local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number)
local rots: { { number } } = table.create(n) :: any
for i = 1, n do
if p >= limit then
return nil, p
end
local id = readu8(b, p)
p += 1
if id == 0 then
if p + 36 > limit then
return nil, p
end
local m = table.create(9, 0)
for k = 0, 8 do
m[k + 1] = readf32(b, p + 4 * k)
end
rots[i] = m
p += 36
else
local m = Rbx.ROTATIONS[id]
if not m then
return nil, -1
end
rots[i] = m
end
end
if p + 12 * n > limit then
return nil, p
end
local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n)
local out = table.create(n)
for i = 1, n do
local m = rots[i]
out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] }
end
return out, p + 12 * n
end
local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
[0x02] = 1,
[0x03] = 4,
[0x04] = 4,
[0x05] = 8,
[0x06] = 8,
[0x07] = 16,
[0x08] = 24,
[0x09] = 1,
[0x0A] = 1,
[0x0B] = 4,
[0x0C] = 12,
[0x0D] = 8,
[0x0E] = 12,
[0x0F] = 4,
[0x12] = 4,
[0x13] = 4,
[0x14] = 6,
[0x17] = 8,
[0x18] = 16,
[0x1A] = 3,
[0x1B] = 8,
[0x1C] = 4,
[0x1F] = 16,
[0x21] = 8,
}
-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message
function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any)
if limit > buffer.len(b) or p < 0 or n < 0 then
return nil, "corrupt: bad ranges"
end
local size = FIXED[t]
if size and p + size * n > limit then
return nil, "truncated property values"
end
if t == 0x01 or t == 0x1D then
local out = table.create(n, "")
for i = 1, n do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated string"
end
out[i] = s
p = q
end
return out, p
elseif t == 0x02 then
local out = table.create(n, false)
for i = 1, n do
out[i] = readu8(b, p + i - 1) ~= 0
end
return out, p + n
elseif t == 0x03 then
return i32s(b, p, n), p + 4 * n
elseif t == 0x04 then
return f32s(b, p, n), p + 4 * n
elseif t == 0x05 then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readf64(b, p + 8 * (i - 1))
end
return out, p + 8 * n
elseif t == 0x06 then
local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { s[i], o[i] }
end
return out, p + 8 * n
elseif t == 0x07 then
local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { xs[i], xo[i], ys[i], yo[i] }
end
return out, p + 16 * n
elseif t == 0x08 then
local out = table.create(n)
for i = 1, n do
local q = p + 24 * (i - 1)
out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) }
end
return out, p + 24 * n
elseif t == 0x09 or t == 0x0A then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readu8(b, p + i - 1)
end
return out, p + n
elseif t == 0x0B or t == 0x12 then
return u32s(b, p, n), p + 4 * n
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
local cols: { { number } } = table.create(k) :: any
for c = 1, k do
cols[c] = f32s(b, p + 4 * n * (c - 1), n)
end
local out = table.create(n)
for i = 1, n do
local v = table.create(k, 0)
for c = 1, k do
v[c] = cols[c][i]
end
out[i] = v
end
return out, p + 4 * k * n
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
local out = table.create(n)
for i = 1, n do
local q = p + 2 * k * (i - 1)
out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) }
end
return out, p + 2 * k * n
elseif t == 0x10 then
local out, q = cframes(b, p, limit, n)
if not out then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
return out, q
elseif t == 0x13 then
local refs, q = Binary.readRefs(b, p, limit, n)
if not refs then
return nil, "truncated referents"
end
local out = table.create(n)
local ref = ctx.ref
for i = 1, n do
out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil
end
return out, q
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
local out = table.create(n)
for i = 1, n do
if p + 4 > limit then
return nil, "truncated sequence"
end
local count = readu32(b, p)
p += 4
if p + count * 4 * k > limit then
return nil, "truncated sequence"
end
local seq = table.create(count)
for j = 1, count do
local key = table.create(k, 0)
for c = 1, k do
key[c] = readf32(b, p + 4 * (c - 1))
end
seq[j] = key
p += 4 * k
end
out[i] = seq
end
return out, p
elseif t == 0x17 then
local out = table.create(n)
for i = 1, n do
out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) }
end
return out, p + 8 * n
elseif t == 0x19 then
local out = table.create(n)
for i = 1, n do
if p >= limit then
return nil, "truncated physical properties"
end
local flag = readu8(b, p)
p += 1
if flag % 2 == 1 then
local k = if flag // 2 % 2 == 1 then 6 else 5
if p + 4 * k > limit then
return nil, "truncated physical properties"
end
local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out
for c = 1, k do
v[c] = readf32(b, p + 4 * (c - 1))
end
out[i] = v
p += 4 * k
elseif flag ~= 0 then
return nil, "unknown"
end
end
return out, p
elseif t == 0x1A then
local out = table.create(n)
for i = 1, n do
out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) }
end
return out, p + 3 * n
elseif t == 0x1B or t == 0x21 then
return i64s(b, p, n), p + 8 * n
elseif t == 0x1C then
local idx = u32s(b, p, n)
local shared: { string } = ctx.shared or {}
local out: { string } = table.create(n, "")
for i = 1, n do
local s = shared[idx[i] + 1]
if s == nil then
return nil, "corrupt: shared string index out of range"
end
out[i] = s
end
return out, p + 4 * n
elseif t == 0x1E then
if p >= limit or readu8(b, p) ~= 0x10 then
return nil, "unknown"
end
local cfs, q = cframes(b, p + 1, limit, n)
if not cfs then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
if q + 1 + n > limit or readu8(b, q) ~= 0x02 then
return nil, "truncated optional CFrame flags"
end
local out = table.create(n)
for i = 1, n do
out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil
end
return out, q + 1 + n
elseif t == 0x1F then
local out = table.create(n, "")
local hex = table.create(16, "")
for i = 0, n - 1 do
local by = table.create(16, 0)
for k = 0, 15 do
by[k + 1] = readu8(b, p + k * n + i)
end
-- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it
local carry = by[16] % 2
for k = 9, 16 do
local v = by[k]
by[k] = v // 2 + carry * 128
carry = v % 2
end
for k = 1, 8 do
hex[k] = string.format("%02x", by[8 + k])
end
for k = 1, 8 do
hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)])
end
out[i + 1] = table.concat(hex)
end
return out, p + 16 * n
elseif t == 0x20 then
local out = table.create(n)
for i = 1, n do
local fam, q = str(b, p, limit)
if not fam or q + 3 > limit then
return nil, "truncated font"
end
local weight, style = readu16(b, q), readu8(b, q + 2)
local face, q2 = str(b, q + 3, limit)
if not face then
return nil, "truncated font"
end
out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil }
p = q2
end
return out, p
elseif t == 0x22 then
if p + 4 * n > limit then
return nil, "truncated content"
end
local kinds = i32s(b, p, n)
p += 4 * n
if p + 4 > limit then
return nil, "truncated content"
end
local nu = readu32(b, p)
p += 4
local uris = table.create(math.min(nu, n))
for j = 1, nu do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated content"
end
uris[j] = s
p = q
end
if p + 4 > limit then
return nil, "truncated content"
end
local no = readu32(b, p)
local objs, q = Binary.readRefs(b, p + 4, limit, no)
if not objs or q + 4 > limit then
return nil, "truncated content"
end
if readu32(b, q) ~= 0 then
return nil, "unknown" -- external objects: kept raw
end
p = q + 4
local out = table.create(n)
local iu, io = 1, 1
for i = 1, n do
local k = kinds[i]
if k == 1 then
if iu > nu then
return nil, "corrupt: content uri count"
end
out[i] = uris[iu]
iu += 1
elseif k == 2 then
if io > no then
return nil, "corrupt: content object count"
end
local r = objs[io]
out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil
io += 1
elseif k ~= 0 then
return nil, "unknown"
end
end
return out, p
end
return nil, "unknown"
end
-- ------------------------------------------------------------------------------------------------ encode
local function num(v: any): number
return if type(v) == "number" and v == v then v else 0
end
-- column c of n array values (missing components 0)
local function column(vals: { any }, n: number, c: number): { number }
local out = table.create(n, 0)
for i = 1, n do
local v = vals[i]
out[i] = if type(v) == "table" then num(v[c]) else 0
end
return out
end
local function putString(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
local function putCFrames(w: Bytes.Writer, vals: { any }, n: number)
for i = 1, n do
local v = vals[i]
local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
local id = Rbx.rotationId(cf)
w:u8(id)
if id == 0 then
for k = 4, 12 do
w:f32le(num(cf[k]))
end
end
end
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 2))
putF32s(w, column(vals, n, 3))
end
local function hexByte(s: string, i: number): number
return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0
end
-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are
-- the type's none / default)
function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string?
if t == 0x01 or t == 0x1D then
for i = 1, n do
local v = vals[i]
putString(w, if type(v) == "string" then v else "")
end
elseif t == 0x02 then
for i = 1, n do
w:u8(if vals[i] then 1 else 0)
end
elseif t == 0x03 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI32s(w, c)
elseif t == 0x04 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putF32s(w, c)
elseif t == 0x05 then
for i = 1, n do
w:f64le(num(vals[i]))
end
elseif t == 0x06 then
putF32s(w, column(vals, n, 1))
putI32s(w, column(vals, n, 2))
elseif t == 0x07 then
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 3))
putI32s(w, column(vals, n, 2))
putI32s(w, column(vals, n, 4))
elseif t == 0x08 then
for i = 1, n do
local v = vals[i]
for c = 1, 6 do
w:f32le(if type(v) == "table" then num(v[c]) else 0)
end
end
elseif t == 0x09 or t == 0x0A then
for i = 1, n do
w:u8(num(vals[i]) % 256)
end
elseif t == 0x0B or t == 0x12 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = floor(num(vals[i]))
end
putU32s(w, c)
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
for c = 1, k do
putF32s(w, column(vals, n, c))
end
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
for i = 1, n do
local v = vals[i]
for c = 1, k do
local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536
w:u16le(x)
end
end
elseif t == 0x10 then
putCFrames(w, vals, n)
elseif t == 0x13 then
local refs = table.create(n, -1)
local refOf = ctx.refOf
for i = 1, n do
refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1
end
Binary.writeRefs(w, refs)
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
for i = 1, n do
local seq = vals[i]
if type(seq) ~= "table" then
seq = {}
end
w:u32le(#seq)
for _, key in seq do
for c = 1, k do
w:f32le(if type(key) == "table" then num(key[c]) else 0)
end
end
end
elseif t == 0x17 then
for i = 1, n do
local v = vals[i]
w:f32le(if type(v) == "table" then num(v[1]) else 0)
w:f32le(if type(v) == "table" then num(v[2]) else 0)
end
elseif t == 0x19 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
w:u8(0)
else
local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out)
w:u8(if acoustic then 3 else 1)
for c = 1, if acoustic then 6 else 5 do
w:f32le(num(v[c]))
end
end
end
elseif t == 0x1A then
for c = 1, 3 do
for i = 1, n do
local v = vals[i]
w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255))
end
end
elseif t == 0x1B or t == 0x21 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI64s(w, c)
elseif t == 0x1C then
local idx = table.create(n, 0)
local si = ctx.sharedIndex
for i = 1, n do
local v = vals[i]
idx[i] = if si then si(if type(v) == "string" then v else "") else 0
end
putU32s(w, idx)
elseif t == 0x1E then
w:u8(0x10)
putCFrames(w, vals, n)
w:u8(0x02)
for i = 1, n do
w:u8(if type(vals[i]) == "table" then 1 else 0)
end
elseif t == 0x1F then
local p = w:reserve(16 * n)
local b = w.buf
for i = 0, n - 1 do
local s = vals[i + 1]
if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then
return "a UniqueId is 32 hex digits"
end
-- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit
local by = table.create(16, 0)
for k = 1, 4 do
by[k] = hexByte(s, 12 + k)
by[4 + k] = hexByte(s, 8 + k)
end
local top = hexByte(s, 1) // 128
for k = 1, 8 do
local v = hexByte(s, k)
local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top
by[8 + k] = (v * 2) % 256 + nxt
end
for k = 0, 15 do
buffer.writeu8(b, p + k * n + i, by[k + 1])
end
end
w.pos = p + 16 * n
elseif t == 0x20 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
v = Rbx.default("Font")
end
putString(w, if type(v.family) == "string" then v.family else "")
w:u16le(math.clamp(floor(num(v.weight)), 0, 65535))
w:u8(if v.style == "Italic" then 1 else 0)
putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "")
end
elseif t == 0x22 then
local kinds, uris, objs = table.create(n, 0), {}, {}
local refOf = ctx.refOf
for i = 1, n do
local v = vals[i]
if type(v) == "string" then
kinds[i] = 1
table.insert(uris, v)
elseif type(v) == "table" then
kinds[i] = 2
table.insert(objs, if refOf then refOf(v) else -1)
end
end
putI32s(w, kinds)
w:u32le(#uris)
for _, s in uris do
putString(w, s)
end
w:u32le(#objs)
Binary.writeRefs(w, objs)
w:u32le(0)
else
return "unknown type id " .. t
end
return nil
end
return Binary
+281
View File
@@ -0,0 +1,281 @@
--!strict
-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the
-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the
-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library,
-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself.
--
-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... }
-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} }
-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} }
-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests
-- for inst, depth in Rbx.descendants(tree) do ... end
--
-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor
-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox):
-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes)
-- SharedString string (the content; writers deduplicate)
-- Bool boolean
-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53)
-- Enum, BrickColor, SecurityCapabilities number
-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
-- Axes number: bits X 1, Y 2, Z 4
-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max }
-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1)
-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz }
-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none)
-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... }
-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight,
-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out)
-- Ref an Instance of the tree, or nil
-- UniqueId 32 hex digits: random (16), time (8), index (8)
-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? }
-- Content nil (none) | string (a URI) | an Instance (object)
-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column),
-- index, count }; written back verbatim while the class keeps the same instances in the same order
-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is
-- Name is not a property here: it is inst.name. Never throws.
local Rbx = {}
export type Value = { type: string, value: any }
export type Instance = {
className: string,
name: string,
properties: { [string]: Value },
children: { Instance },
parent: Instance?, -- nil for roots
referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own
service: boolean?, -- a service (binary INST object format 1; rbxl roots)
}
export type Tree = {
kind: "rbxtree",
roots: { Instance },
place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model
metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...)
extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back
meta: { source: { format: string, [string]: any }?, [string]: any },
}
-- ------------------------------------------------------------------------------------------------ tree
function Rbx.tree(place: boolean?): Tree
return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} }
end
function Rbx.instance(className: string, name: string?): Instance
return { className = className, name = name or className, properties = {}, children = {} }
end
-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance
function Rbx.add(parent: any, child: Instance): Instance
if parent.kind == "rbxtree" then
child.parent = nil
table.insert(parent.roots, child)
else
child.parent = parent
table.insert(parent.children, child)
end
return child
end
-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...)
function Rbx.set(inst: Instance, name: string, typ: string, value: any)
inst.properties[name] = { type = typ, value = value }
end
-- get(inst, name) -> the property's value (not the Value table), nil when absent
function Rbx.get(inst: Instance, name: string): any
local v = inst.properties[name]
return if v then v.value else nil
end
-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children
-- at depth 1)
function Rbx.descendants(root: any): () -> (Instance?, number?)
local stack: { any } = {}
local list = if root.kind == "rbxtree" then root.roots else root.children
for i = #list, 1, -1 do
table.insert(stack, { list[i], 1 })
end
return function(): (Instance?, number?)
local top = table.remove(stack)
if not top then
return nil, nil
end
local inst, depth = top[1], top[2]
for i = #inst.children, 1, -1 do
table.insert(stack, { inst.children[i], depth + 1 })
end
return inst, depth
end
end
-- list(tree) -> every instance, depth first
function Rbx.list(tree: any): { Instance }
local out = {}
for inst in Rbx.descendants(tree) do
table.insert(out, inst :: Instance)
end
return out
end
-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil
function Rbx.find(root: any, path: string): Instance?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
local list = if cur.kind == "rbxtree" then cur.roots else cur.children
local found = nil
for _, c in list do
if c.name == part then
found = c
break
end
end
if not found then
return nil
end
cur = found
end
return if cur.kind == "rbxtree" then nil else cur
end
-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root)
function Rbx.fullName(inst: Instance): string
local parts = {}
local cur: Instance? = inst
while cur do
table.insert(parts, 1, cur.name)
cur = cur.parent
end
return table.concat(parts, ".")
end
-- ------------------------------------------------------------------------------------------------ CFrame rotation ids
-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is
-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product.
local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }
-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation
local ROTATIONS: { [number]: { number } } = {}
for a = 0, 5 do
for b = 0, 5 do
if a % 3 ~= b % 3 then
local r, u = AXES[a + 1], AXES[b + 1]
local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] }
-- columns: right, up, back (= right x up)
ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 }
end
end
end
Rbx.ROTATIONS = ROTATIONS
local function axisIndex(x: number, y: number, z: number): number?
for i, a in AXES do
if a[1] == x and a[2] == y and a[3] == z then
return i - 1
end
end
return nil
end
-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned
function Rbx.rotationId(cf: { number }): number
local a = axisIndex(cf[4], cf[7], cf[10])
local b = axisIndex(cf[5], cf[8], cf[11])
if not a or not b then
return 0
end
local id = 6 * a + b + 1
local rot = ROTATIONS[id]
if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then
return 0
end
return id
end
-- ------------------------------------------------------------------------------------------------ values
-- binary type ids (rbx-dom docs/binary.md) by type name, and back
Rbx.TYPE_IDS = table.freeze({
String = 0x01,
BinaryString = 0x01,
ProtectedString = 0x01,
ContentId = 0x01,
Bool = 0x02,
Int32 = 0x03,
Float32 = 0x04,
Float64 = 0x05,
UDim = 0x06,
UDim2 = 0x07,
Ray = 0x08,
Faces = 0x09,
Axes = 0x0A,
BrickColor = 0x0B,
Color3 = 0x0C,
Vector2 = 0x0D,
Vector3 = 0x0E,
Vector2int16 = 0x0F,
CFrame = 0x10,
Enum = 0x12,
Ref = 0x13,
Vector3int16 = 0x14,
NumberSequence = 0x15,
ColorSequence = 0x16,
NumberRange = 0x17,
Rect = 0x18,
PhysicalProperties = 0x19,
Color3uint8 = 0x1A,
Int64 = 0x1B,
SharedString = 0x1C,
Bytecode = 0x1D,
OptionalCFrame = 0x1E,
UniqueId = 0x1F,
Font = 0x20,
SecurityCapabilities = 0x21,
Content = 0x22,
} :: { [string]: number })
local NAMES: { [number]: string } = {}
for name, id in Rbx.TYPE_IDS do
if NAMES[id] == nil or name == "String" then
NAMES[id] = name
end
end
Rbx.TYPE_NAMES = table.freeze(NAMES)
-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the
-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1)
local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
function Rbx.default(typ: string): any
if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then
return ""
elseif typ == "Bool" then
return false
elseif typ == "BrickColor" then
return 194
elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then
return { 0, 0 }
elseif typ == "UDim2" or typ == "Rect" then
return { 0, 0, 0, 0 }
elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then
return { 0, 0, 0 }
elseif typ == "Ray" then
return { 0, 0, 0, 0, 0, 0 }
elseif typ == "CFrame" then
return table.clone(IDENTITY_CF)
elseif typ == "NumberSequence" then
return { { 0, 0, 0 }, { 1, 0, 0 } }
elseif typ == "ColorSequence" then
return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } }
elseif typ == "UniqueId" then
return string.rep("0", 32)
elseif typ == "Font" then
return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" }
elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then
return nil
end
return 0
end
-- STRINGS: the string-valued types (one binary type, several XML tags)
Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean })
return Rbx
+1
View File
@@ -41,6 +41,7 @@ local KIND_CATEGORY: { [string]: string } = {
audio = "audio",
video = "video",
scene = "model",
rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx)
cad = "cad",
font = "font",
archive = "archive",
+605
View File
@@ -0,0 +1,605 @@
--!strict
-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, "<roblox!"), read + write, to and from the instance
-- tree of codecs/model/Rbx (an RbxTree, kind "rbxtree"; not a Scene: Roblox files hold instances, not meshes).
-- Written from the rbx-dom format notes (docs/binary.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
-- Decode: the header, META (tree.metadata), SSTR (shared strings), INST (classes, referents, service flags), PROP (every
-- property type of codecs/model/Rbx/Binary), PRNT (the hierarchy), END; chunk bodies raw, LZ4 or Zstandard. Unknown
-- chunks are kept raw in tree.extra and written back; properties of unknown types become "Raw" values that are
-- written back verbatim while the class keeps its instances. tree.place is true when the file marks services (rbxl).
-- Encode: every instance depth first (referents 0..n-1), classes sorted by name, properties sorted by name, chunks
-- LZ4-compressed (opts.compression = "none" writes them raw), SharedStrings deduplicated (MD5 keys). An instance
-- without a property its class's other instances have gets the type's default (the format stores one value per
-- instance). "XmlRaw" values (unknown XML types) are skipped. Not supported: writing Zstandard chunks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Md5 = require("@formats/core/Md5")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Zstd = require("@formats/codecs/compress/Zstd")
local Rbx = require("@formats/codecs/model/Rbx")
local Binary = require("@formats/codecs/model/Rbx/Binary")
-- ------------------------------------------------------------------------------------------------ contract
local Rbxm = {
name = "rbxm",
category = "model",
extensions = { "rbxm", "rbxl" },
mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" },
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" },
caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxBytes: number?, -- the largest decompressed chunk (default 2^28)
maxInstances: number?, -- default 2^22
}
export type EncodeOptions = {
compression: ("lz4" | "none")?, -- chunk bodies (default "lz4"; END is always raw)
place: boolean?, -- mark the roots as services (an .rbxl; default tree.place, or format = "rbxl")
format: string?, -- "rbxl" writes a place
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "<roblox!\137\255\13\10\26\10"
local readu8, readu32, readi32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readstring
-- ------------------------------------------------------------------------------------------------ sniff
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 }
-- a length-prefixed string at p of b (limit e): string, next | nil
local function str(b: buffer, p: number, e: number): (string?, number)
if p + 4 > e then
return nil, p
end
local n = readu32(b, p)
if p + 4 + n > e then
return nil, p
end
return readstring(b, p + 4, n), p + 4 + n
end
function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
local maxInstances = opts and opts.maxInstances or 2 ^ 22
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 32 then
return nil, Err.new(Err.TRUNCATED, "header", base)
end
if readstring(b, base, 14) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad signature", base)
end
local version = buffer.readu16(b, base + 14)
if version ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14)
end
local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20)
if nClasses < 0 or nInstances < 0 then
return nil, Err.new(Err.CORRUPT, "negative counts", base + 16)
end
if nInstances > maxInstances then
return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20)
end
local tree = Rbx.tree()
tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} }
local classes: { [number]: Class } = {}
local byRef: { [number]: Rbx.Instance } = {}
local shared: { string } = {}
local parented: { [Rbx.Instance]: boolean } = {}
local order: { Rbx.Instance } = {}
local anyService = false
local comp: { [string]: boolean } = {}
local ctx: Binary.Ctx = {
ref = function(n: number): any
return byRef[n]
end,
shared = shared,
}
local p = base + 32
local ended = false
while p < limit do
if p + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "chunk header", p)
end
local name = readstring(b, p, 4)
local clen, ulen = readu32(b, p + 4), readu32(b, p + 8)
local at = p
p += 16
if ulen > maxBytes then
return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at)
end
local body: buffer, bo: number, be: number
if clen == 0 then
if p + ulen > limit then
return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at)
end
body, bo, be = b, p, p + ulen
p += ulen
comp.none = true
else
if p + clen > limit then
return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at)
end
local out, err
if Zstd.isFrame(b, p) then
out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen })
comp.zstd = true
else
out, err = Lz4.decompress(b, p, clen, ulen)
comp.lz4 = true
end
if not out then
return nil, err
end
if buffer.len(out) ~= ulen then
return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at)
end
body, bo, be = out, 0, ulen
p += clen
end
if name == "END\0" then
ended = true
break
elseif name == "META" then
if bo + 4 > be then
return nil, Err.new(Err.TRUNCATED, "META", at)
end
local q = bo + 4
for _ = 1, readu32(body, bo) do
local k, q1 = str(body, q, be)
local v, q2 = str(body, q1, be)
if not k or not v then
return nil, Err.new(Err.TRUNCATED, "META entry", at)
end
tree.metadata[k] = v
q = q2
end
elseif name == "SSTR" then
if bo + 8 > be then
return nil, Err.new(Err.TRUNCATED, "SSTR", at)
end
local q = bo + 8
for i = 1, readu32(body, bo + 4) do
local s, q2 = str(body, q + 16, be)
if not s then
return nil, Err.new(Err.TRUNCATED, "shared string", at)
end
shared[i] = s
q = q2
end
elseif name == "INST" then
local id = if bo + 4 <= be then readi32(body, bo) else -1
local cname, q = str(body, bo + 4, be)
if not cname or q + 5 > be then
return nil, Err.new(Err.TRUNCATED, "INST", at)
end
local fmt, count = readu8(body, q), readu32(body, q + 1)
if count > nInstances then
return nil, Err.new(Err.CORRUPT, "more instances than the header says", at)
end
local refs, q2 = Binary.readRefs(body, q + 5, be, count)
if not refs then
return nil, Err.new(Err.TRUNCATED, "INST referents", at)
end
if id < 0 or classes[id] then
return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at)
end
local service = fmt == 1
if service and q2 + count > be then
return nil, Err.new(Err.TRUNCATED, "INST service markers", at)
end
classes[id] = { id = id, name = cname, refs = refs, service = service }
for i, ref in refs do
if byRef[ref] then
return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at)
end
local inst = Rbx.instance(cname)
inst.referent = tostring(ref)
if service and readu8(body, q2 + i - 1) ~= 0 then
inst.service = true
anyService = true
end
byRef[ref] = inst
table.insert(order, inst)
end
elseif name == "PROP" then
local id = if bo + 4 <= be then readi32(body, bo) else -1
local pname, q = str(body, bo + 4, be)
if not pname or q + 1 > be then
return nil, Err.new(Err.TRUNCATED, "PROP", at)
end
local cls = classes[id]
if not cls then
return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at)
end
local t = readu8(body, q)
local n = #cls.refs
local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx)
if vals then
local tname = Rbx.TYPE_NAMES[t]
for i, ref in cls.refs do
local inst = byRef[ref]
if pname == "Name" and t == 0x01 then
inst.name = vals[i]
else
inst.properties[pname] = { type = tname, value = vals[i] }
end
end
elseif msg == "unknown" then
local data = buffer.create(be - q - 1)
buffer.copy(data, 0, body, q + 1, be - q - 1)
for i, ref in cls.refs do
byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } }
end
else
return nil, Err.from(msg, at)
end
elseif name == "PRNT" then
if bo + 5 > be then
return nil, Err.new(Err.TRUNCATED, "PRNT", at)
end
if readu8(body, bo) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at)
end
local count = readu32(body, bo + 1)
local kids, q = Binary.readRefs(body, bo + 5, be, count)
local parents = if kids then Binary.readRefs(body, q, be, count) else nil
if not kids or not parents then
return nil, Err.new(Err.TRUNCATED, "PRNT referents", at)
end
for i = 1, count do
local child, parent = byRef[kids[i]], parents[i] >= 0 and byRef[parents[i]] or nil
if not child or (parents[i] >= 0 and not parent) then
return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at)
end
if parented[child] then
return nil, Err.new(Err.CORRUPT, "an instance with two parents", at)
end
parented[child] = true
-- refuse cycles: the parent may not be a descendant of the child
local up: Rbx.Instance? = parent
while up do
if up == child then
return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at)
end
up = up.parent
end
Rbx.add(parent or tree, child)
end
else
local data = buffer.create(be - bo)
buffer.copy(data, 0, body, bo, be - bo)
table.insert(tree.extra, { name = name, data = data })
end
end
if not ended then
return nil, Err.new(Err.TRUNCATED, "no END chunk", limit)
end
-- instances PRNT does not mention are roots
for _, inst in order do
if not parented[inst] then
table.insert(tree.roots, inst)
end
end
tree.place = anyService
local list = {}
for k in comp do
table.insert(list, k)
end
table.sort(list)
local src: any = tree.meta.source
src.compression = list
return tree, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the binary type of a property over a class's instances: type id, type name | nil, message
local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?)
local id, tname = nil, nil
for _, inst in insts do
local v = inst.properties[pname]
if v then
if type(v) ~= "table" or type(v.type) ~= "string" then
return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table"
end
local t = if v.type == "Raw" then -1 elseif v.type == "XmlRaw" then -2 else Rbx.TYPE_IDS[v.type]
if not t then
return nil, "property " .. pname .. ": unknown type " .. v.type
end
if id == nil then
id, tname = t, v.type
elseif id ~= t then
return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type
end
end
end
return id, tname
end
local function chunk(w: Bytes.Writer, name: string, body: buffer, compress: boolean)
w:string(name)
local n = buffer.len(body)
if compress then
local z = Lz4.compress(body) :: buffer
w:u32le(buffer.len(z))
w:u32le(n)
w:u32le(0)
w:bytes(z)
else
w:u32le(0)
w:u32le(n)
w:u32le(0)
w:bytes(body)
end
end
local function putStr(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then
return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)")
end
local o: any = opts or {}
local compress = o.compression ~= "none"
local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true
-- every instance depth first; referents in that order
local insts: { Rbx.Instance } = {}
local refOf: { [any]: number } = {}
local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {}
local function visit(inst: any, parent: Rbx.Instance?): Err.Err?
if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then
return Err.new(Err.ARG, "an instance needs className and properties")
end
if refOf[inst] then
return Err.new(Err.ARG, "an instance appears twice in the tree")
end
refOf[inst] = #insts
table.insert(insts, inst)
parentOf[inst] = parent
for _, c in inst.children or {} do
local e = visit(c, inst)
if e then
return e
end
end
return nil
end
for _, root in tree.roots do
local e = visit(root, nil)
if e then
return nil, e
end
end
-- classes by name
local byClass: { [string]: { Rbx.Instance } } = {}
local names = {}
for _, inst in insts do
local list = byClass[inst.className]
if not list then
list = {}
byClass[inst.className] = list
table.insert(names, inst.className)
end
table.insert(list, inst)
end
table.sort(names)
-- shared strings, in order of first use
local sharedIdx: { [string]: number } = {}
local sharedList: { string } = {}
local ctx: Binary.Ctx = {
refOf = function(v: any): number
return refOf[v] or -1
end,
sharedIndex = function(s: string): number
local i = sharedIdx[s]
if not i then
table.insert(sharedList, s)
i = #sharedList - 1
sharedIdx[s] = i
end
return i
end,
}
local props: { buffer } = {}
local instChunks: { buffer } = {}
for classId, cname in names do
local list = byClass[cname]
local id = classId - 1
-- INST
local w = Bytes.writer(64 + 5 * #list)
w:u32le(id)
putStr(w, cname)
local service = place and parentOf[list[1]] == nil
for _, inst in list do
if inst.service then
service = true
end
end
w:u8(if service then 1 else 0)
w:u32le(#list)
local refs = table.create(#list, 0)
for i, inst in list do
refs[i] = refOf[inst]
end
Binary.writeRefs(w, refs)
if service then
for _, inst in list do
w:u8(if inst.service or (place and parentOf[inst] == nil) then 1 else 0)
end
end
table.insert(instChunks, w:finish())
-- PROP: Name, then every property any instance of the class has, sorted
local pnames: { string } = {}
local seen: { [string]: boolean } = {}
for _, inst in list do
for pn in inst.properties do
if not seen[pn] and pn ~= "Name" then
seen[pn] = true
table.insert(pnames, pn)
end
end
end
table.sort(pnames)
table.insert(pnames, 1, "Name")
for _, pn in pnames do
local t: number?, tname: string?
if pn == "Name" then
t, tname = 0x01, "String"
else
local e
t, e = columnType(list, pn)
if not t then
return nil, Err.new(Err.ARG, e or "bad property")
end
tname = e
end
local pw = Bytes.writer(64)
pw:u32le(id)
putStr(pw, pn)
local tid = t :: number
if tid == -1 then
-- Raw: the column read from a file, written back only when this class still has exactly its instances
local first = list[1].properties[pn]
local raw = first and first.value
local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer"
if ok then
for i, inst in list do
local v = inst.properties[pn]
if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then
ok = false
break
end
end
end
if ok then
pw:u8(raw.typeId)
pw:bytes(raw.data)
table.insert(props, pw:finish())
end
elseif tid ~= -2 then
pw:u8(tid)
local vals = table.create(#list)
for i, inst in list do
if pn == "Name" then
vals[i] = if type(inst.name) == "string" then inst.name else inst.className
else
local v = inst.properties[pn]
if v then
vals[i] = v.value
else
vals[i] = Rbx.default(tname :: string)
end
end
end
local e = Binary.encode(tid, vals, #list, pw, ctx)
if e then
return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e)
end
table.insert(props, pw:finish())
end
end
end
-- PRNT
local pw = Bytes.writer(16 + 8 * #insts)
pw:u8(0)
pw:u32le(#insts)
local kids, parents = table.create(#insts, 0), table.create(#insts, 0)
for i, inst in insts do
kids[i] = i - 1
local par = parentOf[inst]
parents[i] = if par then refOf[par] else -1
end
Binary.writeRefs(pw, kids)
Binary.writeRefs(pw, parents)
local out = Bytes.writer(1024)
out:string(MAGIC)
out:u16le(0)
out:u32le(#names)
out:u32le(#insts)
out:u32le(0)
out:u32le(0)
local metaKeys = {}
for k, v in tree.metadata or {} do
if type(k) == "string" and type(v) == "string" then
table.insert(metaKeys, k)
end
end
if #metaKeys > 0 then
table.sort(metaKeys)
local mw = Bytes.writer(64)
mw:u32le(#metaKeys)
for _, k in metaKeys do
putStr(mw, k)
putStr(mw, (tree.metadata :: any)[k])
end
chunk(out, "META", mw:finish(), compress)
end
if #sharedList > 0 then
local sw = Bytes.writer(64)
sw:u32le(0)
sw:u32le(#sharedList)
for _, s in sharedList do
local h = Md5.new()
h:update(buffer.fromstring(s))
sw:string(h:digest())
putStr(sw, s)
end
chunk(out, "SSTR", sw:finish(), compress)
end
for _, c in instChunks do
chunk(out, "INST", c, compress)
end
for _, c in props do
chunk(out, "PROP", c, compress)
end
chunk(out, "PRNT", pw:finish(), compress)
for _, x in tree.extra or {} do
if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then
chunk(out, x.name, x.data, compress)
end
end
chunk(out, "END\0", buffer.fromstring("</roblox>"), false)
return out:finish(), nil
end
return Rbxm
+667
View File
@@ -0,0 +1,667 @@
--!strict
-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, `<roblox version="4">`), read + write, to and from
-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save).
-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
-- Decode: <Meta>, <Item class referent> with <Properties> of every type codecs/model/Rbx lists (string, BinaryString
-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN),
-- token, BrickColor (as rbx-dom: an <int>; read back as BrickColor for the BrickColor properties of a short
-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame,
-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange,
-- PhysicalProperties, Ref, SharedString (+ <SharedStrings>), UniqueId, Font, SecurityCapabilities); unknown property
-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra.
-- tree.place is true when a root is a Workspace (rbxlx).
-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent,
-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control
-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Md5 = require("@formats/core/Md5")
local Xml = require("@formats/codecs/text/Xml")
local Rbx = require("@formats/codecs/model/Rbx")
-- ------------------------------------------------------------------------------------------------ contract
local Rbxmx = {
name = "rbxmx",
category = "model",
extensions = { "rbxmx", "rbxlx" },
mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" },
deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" },
caps = { decode = true, encode = true, tree = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxDepth: number?, -- XML nesting limit (default 10000)
}
export type EncodeOptions = {
indent: (number | string)?, -- default 2 spaces; 0 for none
}
-- ------------------------------------------------------------------------------------------------ constants
local XmlNode = Xml.element
local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch
-- tag name -> type name for the simple (text) types
local SCALAR_TAGS: { [string]: string } = {
string = "String",
ProtectedString = "ProtectedString",
bool = "Bool",
int = "Int32",
int64 = "Int64",
float = "Float32",
double = "Float64",
token = "Enum",
BrickColor = "BrickColor",
SecurityCapabilities = "SecurityCapabilities",
UniqueId = "UniqueId",
}
-- BrickColor properties: XML writes them as <int> (rbx-dom reads them through its reflection database); these known ones
-- read back as BrickColor (the rest of an <int> stays Int32)
local BRICKCOLOR: { [string]: boolean } = {
["BrickColorValue.Value"] = true,
["SpawnLocation.TeamColor"] = true,
["Team.TeamColor"] = true,
["FlagStand.TeamColor"] = true,
["Skin.SkinColor"] = true,
}
-- the strings rbx-dom writes as BinaryString (the rest decides by content)
local BINARY_NAMES: { [string]: boolean } = { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Rbxmx.sniff(r: Bytes.Reader): number
local head = r:peek(256)
head = string.gsub(head, "^\239\187\191", "")
head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "")
if match(head, "^%s*<roblox[%s>]") then
return if find(head, "version=", 1, true) then 1 else 0.8
end
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
return 0
end
local t = string.lower((string.gsub(s, "^%s+", "")))
t = string.gsub(t, "%s+$", "")
if t == "inf" or t == "+inf" or t == "infinity" then
return math.huge
elseif t == "-inf" or t == "-infinity" then
return -math.huge
elseif t == "nan" or t == "-nan" then
return 0 / 0
end
return tonumber(t) or 0
end
local function childText(node: Xml.Node, name: string): string?
local c = Xml.child(node, name)
return if c then Xml.text(c) else nil
end
local function comps(node: Xml.Node?, names: { string }): { number }
local out = table.create(#names, 0)
if node then
for i, n in names do
out[i] = num(childText(node, n))
end
end
return out
end
local function numbers(s: string): { number }
local out = {}
for w in gmatch(s, "%S+") do
table.insert(out, num(w))
end
return out
end
local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" }
local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" }
-- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs
-- come back as { pending = referent })
local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any)
local tag = node.name
local scalar = SCALAR_TAGS[tag]
if tag == "int" and BRICKCOLOR[key] then
scalar = "BrickColor"
end
if scalar then
local s = Xml.text(node)
if scalar == "String" or scalar == "ProtectedString" then
return scalar, s
elseif scalar == "Bool" then
return scalar, match(s, "^%s*true%s*$") ~= nil
elseif scalar == "UniqueId" then
return scalar, string.lower((string.gsub(s, "%s", "")))
end
return scalar, num(s)
elseif tag == "BinaryString" then
local data = Base64.decode((string.gsub(Xml.text(node), "%s", "")))
return "BinaryString", if data then buffer.tostring(data) else ""
elseif tag == "Content" or tag == "ContentId" then
local url = Xml.child(node, "url")
if url then
return "ContentId", Xml.text(url)
end
local uri = Xml.child(node, "uri")
if uri then
return "Content", Xml.text(uri)
end
local obj = Xml.child(node, "Object") or Xml.child(node, "Ref")
if obj then
return "Content", { pending = Xml.text(obj) }
end
if Xml.child(node, "null") then
return (if tag == "ContentId" then "ContentId" else "Content"), (if tag == "ContentId" then "" else nil)
end
return "ContentId", Xml.text(node)
elseif tag == "Vector2" or tag == "Vector2int16" then
return tag, comps(node, { "X", "Y" })
elseif tag == "Vector3" or tag == "Vector3int16" then
return tag, comps(node, { "X", "Y", "Z" })
elseif tag == "Color3" then
if Xml.child(node, "R") then
return tag, comps(node, { "R", "G", "B" })
end
local v = num(Xml.text(node)) % 4294967296
return tag, { (v // 65536) % 256 / 255, (v // 256) % 256 / 255, v % 256 / 255 }
elseif tag == "Color3uint8" then
local v = num(Xml.text(node)) % 4294967296
return tag, { (v // 65536) % 256, (v // 256) % 256, v % 256 }
elseif tag == "CoordinateFrame" or tag == "CFrame" then
return "CFrame", comps(node, CF_NAMES)
elseif tag == "OptionalCoordinateFrame" then
local cf = Xml.child(node, "CFrame")
return "OptionalCFrame", if cf then comps(cf, CF_NAMES) else nil
elseif tag == "UDim" then
return tag, comps(node, { "S", "O" })
elseif tag == "UDim2" then
return tag, comps(node, { "XS", "XO", "YS", "YO" })
elseif tag == "Rect2D" then
local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" })
return "Rect", { a[1], a[2], b[1], b[2] }
elseif tag == "Ray" then
local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" })
return tag, { a[1], a[2], a[3], b[1], b[2], b[3] }
elseif tag == "Faces" or tag == "Axes" then
local t = childText(node, string.lower(tag))
return tag, num(t or Xml.text(node))
elseif tag == "NumberRange" then
local v = numbers(Xml.text(node))
return tag, { v[1] or 0, v[2] or 0 }
elseif tag == "NumberSequence" or tag == "ColorSequence" then
local k = if tag == "NumberSequence" then 3 else 5
local v = numbers(Xml.text(node))
local seq = {}
for i = 1, #v - k + 1, k do
table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0)))
end
return tag, seq
elseif tag == "PhysicalProperties" then
local custom = childText(node, "CustomPhysics")
if not custom or not match(custom, "^%s*true%s*$") then
return tag, nil
end
local v = comps(node, PHYS_NAMES)
local a = childText(node, "AcousticAbsorption")
v[6] = if a then num(a) else 1
return tag, v
elseif tag == "Ref" then
local s = string.gsub(Xml.text(node), "%s", "")
return tag, if s == "" or s == "null" then nil else { pending = s }
elseif tag == "SharedString" then
local key = string.gsub(Xml.text(node), "%s", "")
return tag, shared[key] or ""
elseif tag == "Font" then
local fam = Xml.child(node, "Family")
local face = Xml.child(node, "CachedFaceId")
local f = {
family = if fam then childText(fam, "url") or Xml.text(fam) else "",
weight = num(childText(node, "Weight") or "400"),
style = if match(childText(node, "Style") or "", "Italic") then "Italic" else "Normal",
cachedFaceId = if face then childText(face, "url") or nil else nil,
}
if f.cachedFaceId == "" then
f.cachedFaceId = nil
end
return tag, f
end
return "XmlRaw", node
end
-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary
-- decodes of the same data are equal. Which components are floats, by type (true = all)
local F32: { [string]: any } = {
Float32 = true,
Vector2 = true,
Vector3 = true,
Color3 = true,
CFrame = true,
OptionalCFrame = true,
Rect = true,
Ray = true,
NumberRange = true,
NumberSequence = true,
ColorSequence = true,
PhysicalProperties = true,
UDim = { true, false },
UDim2 = { true, false, true, false },
}
local f32buf = buffer.create(4)
local function f32(v: number): number
buffer.writef32(f32buf, 0, v)
return buffer.readf32(f32buf, 0)
end
local function round32(v: any, which: any): any
if type(v) == "number" then
return f32(v)
elseif type(v) == "table" then
for i, x in v do
if type(x) == "table" then
round32(x, true)
elseif type(x) == "number" and (which == true or which[i]) then
v[i] = f32(x)
end
end
end
return v
end
local function readValue(node: Xml.Node, shared: { [string]: string }, key: string): (string, any)
local t, v = readRaw(node, shared, key)
local which = F32[t]
if which then
v = round32(v, which)
end
return t, v
end
function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } :: any)
if not doc then
return nil, err
end
local root = (doc :: any).root
if not root or root.name ~= "roblox" then
return nil, Err.new(Err.CORRUPT, "the root element is not <roblox>")
end
local tree = Rbx.tree()
tree.meta.source = { format = "rbxmx", version = root.attrs.version }
-- shared strings first (properties name them by key)
local shared: { [string]: string } = {}
for _, ss in Xml.children(root, "SharedStrings") do
for _, s in Xml.children(ss, "SharedString") do
local key = s.attrs.md5
local data = Base64.decode((string.gsub(Xml.text(s), "%s", "")))
if key and data then
shared[key] = buffer.tostring(data)
end
end
end
local byRef: { [string]: Rbx.Instance } = {}
local pending: { { any } } = {} -- { value table, field, referent }
local function item(node: Xml.Node, parent: any): Err.Err?
local cls = node.attrs.class
if type(cls) ~= "string" then
return Err.new(Err.CORRUPT, "an <Item> without a class")
end
local inst = Rbx.instance(cls)
local ref = node.attrs.referent
if type(ref) == "string" then
inst.referent = ref
byRef[ref] = inst
end
Rbx.add(parent, inst)
for _, c in node.children do
if type(c) == "table" then
if c.name == "Properties" then
for _, pnode in c.children do
if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then
local pname = pnode.attrs.name
if type(pname) == "string" then
local t, v = readValue(pnode, shared, cls .. "." .. pname)
if pname == "Name" and (t == "String" or t == "ProtectedString") then
inst.name = v
else
local val = { type = t, value = v }
inst.properties[pname] = val
if type(v) == "table" and v.pending then
table.insert(pending, { val, v.pending })
end
end
end
end
end
elseif c.name == "Item" then
local e = item(c, inst)
if e then
return e
end
end
end
end
return nil
end
for _, c in root.children do
if type(c) == "table" then
if c.name == "Item" then
local e = item(c, tree)
if e then
return nil, e
end
elseif c.name == "Meta" then
if type(c.attrs.name) == "string" then
tree.metadata[c.attrs.name] = Xml.text(c)
end
elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then
table.insert(tree.extra, c)
end
end
end
for _, p in pending do
p[1].value = byRef[p[2]]
end
for _, rt in tree.roots do
if rt.className == "Workspace" then
tree.place = true
end
end
return tree, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the shortest text that reads back as the same float (single: f32 values; else f64)
local function fmt(v: any, single: boolean?): string
if type(v) ~= "number" then
v = 0
end
if v ~= v then
return "NAN"
elseif v == math.huge then
return "INF"
elseif v == -math.huge then
return "-INF"
end
if single then
v = f32(v)
end
if v == math.floor(v) and math.abs(v) < 2 ^ 53 then
return format("%.0f", v)
end
for d = if single then 6 else 15, if single then 9 else 17 do
local s = format("%." .. d .. "g", v)
local back = tonumber(s) or 0
if (if single then f32(back) else back) == v then
return s
end
end
return format("%.17g", v)
end
local function int(v: any): string
return format("%.0f", math.floor(if type(v) == "number" and v == v and math.abs(v) ~= math.huge then v else 0))
end
local function textEl(tag: string, text: string): Xml.Node
return XmlNode(tag, nil, { text })
end
local function compsEl(tag: string, attrs: { [string]: string }?, names: { string }, v: any, single: boolean?, ints: boolean?): Xml.Node
local kids = {}
for i, n in names do
local x = if type(v) == "table" then v[i] else 0
table.insert(kids, textEl(n, if ints then int(x) else fmt(x, single)))
end
return XmlNode(tag, attrs, kids)
end
local function hexDigits(i: number): string
return format("%032X", i)
end
local function xmlSafe(s: string): boolean
if find(s, "[%z\1-\8\11\12\14-\31\127]") then
return false
end
return utf8.len(s) ~= nil
end
-- a property -> its element, or nil to skip
local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node?
local t, x = v.type, v.value
local a = { name = name }
if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then
local s = if type(x) == "string" then x else ""
if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then
return XmlNode("BinaryString", a, { Base64.encode(s) })
end
return XmlNode(if t == "ProtectedString" then "ProtectedString" else "string", a, { s })
elseif t == "ContentId" then
local s = if type(x) == "string" then x else ""
return XmlNode("ContentId", a, { if s == "" then XmlNode("null") else textEl("url", s) })
elseif t == "Content" then
if type(x) == "string" then
return XmlNode("Content", a, { textEl("uri", x) })
elseif type(x) == "table" then
return XmlNode("Content", a, { textEl("Object", refOf(x)) })
end
return XmlNode("Content", a, { XmlNode("null") })
elseif t == "Bool" then
return XmlNode("bool", a, { if x then "true" else "false" })
elseif t == "Int32" then
return XmlNode("int", a, { int(x) })
elseif t == "Int64" then
return XmlNode("int64", a, { int(x) })
elseif t == "Float32" then
return XmlNode("float", a, { fmt(x, true) })
elseif t == "Float64" then
return XmlNode("double", a, { fmt(x) })
elseif t == "Enum" then
return XmlNode("token", a, { int(x) })
elseif t == "BrickColor" then
return XmlNode("int", a, { int(x) })
elseif t == "SecurityCapabilities" then
return XmlNode("SecurityCapabilities", a, { int(x) })
elseif t == "UniqueId" then
return XmlNode("UniqueId", a, { if type(x) == "string" then string.lower(x) else string.rep("0", 32) })
elseif t == "Vector2" then
return compsEl(t, a, { "X", "Y" }, x, true)
elseif t == "Vector3" then
return compsEl(t, a, { "X", "Y", "Z" }, x, true)
elseif t == "Vector2int16" then
return compsEl(t, a, { "X", "Y" }, x, false, true)
elseif t == "Vector3int16" then
return compsEl(t, a, { "X", "Y", "Z" }, x, false, true)
elseif t == "Color3" then
return compsEl(t, a, { "R", "G", "B" }, x, true)
elseif t == "Color3uint8" then
local c = if type(x) == "table" then x else { 0, 0, 0 }
local function b(i: number): number
return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255)
end
return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) })
elseif t == "CFrame" then
return compsEl("CoordinateFrame", a, CF_NAMES, x, true)
elseif t == "OptionalCFrame" then
return XmlNode("OptionalCoordinateFrame", a, if type(x) == "table" then { compsEl("CFrame", nil, CF_NAMES, x, true) } else {})
elseif t == "UDim" then
local u = if type(x) == "table" then x else { 0, 0 }
return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) })
elseif t == "UDim2" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0 }
return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) })
elseif t == "Rect" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0 }
return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) })
elseif t == "Ray" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0, 0, 0 }
return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) })
elseif t == "Faces" or t == "Axes" then
return XmlNode(t, a, { textEl(string.lower(t), int(x)) })
elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then
local parts = {}
local list = if type(x) ~= "table" then {} elseif t == "NumberRange" then { x } else x
for _, key in list do
for _, c in key do
table.insert(parts, fmt(c, true) .. " ")
end
end
return XmlNode(t, a, { table.concat(parts) })
elseif t == "PhysicalProperties" then
if type(x) ~= "table" then
return XmlNode(t, a, { textEl("CustomPhysics", "false") })
end
local kids = { textEl("CustomPhysics", "true") }
for i, n in PHYS_NAMES do
table.insert(kids, textEl(n, fmt(x[i], true)))
end
table.insert(kids, textEl("AcousticAbsorption", fmt(if x[6] ~= nil then x[6] else 1, true)))
return XmlNode(t, a, kids)
elseif t == "Ref" then
return XmlNode("Ref", a, { if x ~= nil then refOf(x) else "null" })
elseif t == "SharedString" then
return XmlNode("SharedString", a, { sharedKey(if type(x) == "string" then x else "") })
elseif t == "Font" then
local f = if type(x) == "table" then x else Rbx.default("Font")
local kids = {
XmlNode("Family", nil, { textEl("url", if type(f.family) == "string" then f.family else "") }),
textEl("Weight", int(f.weight or 400)),
textEl("Style", if f.style == "Italic" then "Italic" else "Normal"),
}
if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then
table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) }))
end
return XmlNode("Font", a, kids)
elseif t == "XmlRaw" then
if type(x) == "table" and type(x.name) == "string" then
local copy = XmlNode(x.name, nil, x.children)
for k, val in x.attrs do
Xml.setAttr(copy, k, val)
end
Xml.setAttr(copy, "name", name)
return copy
end
end
return nil
end
function Rbxmx.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then
return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)")
end
local refs: { [any]: string } = {}
local count = 0
local function assign(inst: any): Err.Err?
if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then
return Err.new(Err.ARG, "an instance needs className and properties")
end
if refs[inst] then
return Err.new(Err.ARG, "an instance appears twice in the tree")
end
refs[inst] = "RBX" .. hexDigits(count)
count += 1
for _, c in inst.children or {} do
local e = assign(c)
if e then
return e
end
end
return nil
end
for _, rt in tree.roots do
local e = assign(rt)
if e then
return nil, e
end
end
local function refOf(x: any): string
return refs[x] or "null"
end
local sharedKeys: { [string]: string } = {}
local sharedList: { string } = {}
local function sharedKey(s: string): string
local k = sharedKeys[s]
if not k then
local h = Md5.new()
h:update(buffer.fromstring(s))
k = Base64.encode(h:digest())
sharedKeys[s] = k
table.insert(sharedList, s)
end
return k
end
local function item(inst: Rbx.Instance): Xml.Node
local props = { textEl("string", inst.name or inst.className) }
props[1].attrs.name = "Name"
local names: { string } = {}
for k in inst.properties do
if k ~= "Name" then
table.insert(names, k)
end
end
table.sort(names)
for _, k in names do
local v = inst.properties[k]
if type(v) == "table" then
local el = writeValue(k, v, refOf, sharedKey)
if el then
table.insert(props, el)
end
end
end
local kids = { XmlNode("Properties", nil, props) }
for _, c in inst.children or {} do
table.insert(kids, item(c))
end
local el = XmlNode("Item", nil, kids)
Xml.setAttr(el, "class", inst.className)
Xml.setAttr(el, "referent", refs[inst])
return el
end
local root = XmlNode("roblox", nil, {})
Xml.setAttr(root, "version", "4")
local metaKeys = {}
for k in tree.metadata or {} do
table.insert(metaKeys, k)
end
table.sort(metaKeys)
for _, k in metaKeys do
local m = textEl("Meta", tostring((tree.metadata :: any)[k]))
m.attrs.name = k
Xml.append(root, m)
end
for _, rt in tree.roots do
Xml.append(root, item(rt))
end
for _, x in tree.extra or {} do
if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then
Xml.append(root, x)
end
end
if #sharedList > 0 then
local ss = XmlNode("SharedStrings", nil, {})
for _, s in sharedList do
local el = XmlNode("SharedString", nil, { Base64.encode(s) })
Xml.setAttr(el, "md5", sharedKeys[s])
Xml.append(ss, el)
end
Xml.append(root, ss)
end
local indent = if opts and opts.indent ~= nil then opts.indent else 2
local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false })
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
return Rbxmx
+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
+101
View File
@@ -0,0 +1,101 @@
-- codecs/compress/Lz4 tests: every reference block (python-lz4 fast at accelerations 1 / 4 / 16, HC 4 / 9 / 12)
-- decodes to its corpus, with and without the size; our encoder's blocks decode with the reference (fixture verdicts)
-- and round trip here; linked blocks through decodeInto's history; error codes; truncated / mutated / random blocks
-- never throw. Fixtures: tools/fixtures/lz4.py.
local T = require("@tests/T")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lz4")
local C = require("@tests/gen/lz4_corpora")
local t = T.suite("lz4")
local nbytes = 0
for _, c in Fx.cases do
local want = C[c.corpus]
local out, err = Lz4.decompress(c.data, nil, nil, #want)
t:check(out ~= nil and buffer.tostring(out) == want, c.name .. ": " .. tostring(err))
if #want > 0 then
local grown = Lz4.decompress(c.data)
t:check(grown ~= nil and buffer.tostring(grown) == want, c.name .. ": without the size")
end
nbytes += #want
end
t:note("%d reference blocks, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
for _, v in Fx.ours do
t:check(v.ok, v.name .. ": the reference decodes our block")
end
for name, data in C do
local b = Lz4.compress(data) :: buffer
local back = Lz4.decompress(b, nil, nil, #data)
t:check(back ~= nil and buffer.tostring(back) == data, name .. ": round trip")
if name == "text" or name == "zeros" or name == "runs" then
t:check(buffer.len(b) < #data / 2, name .. ": compresses")
end
t:check(buffer.len(b) <= Lz4.bound(#data), name .. ": within bound")
end
-- at an offset, and linked blocks: the second block refers into the first one's output
do
local text = C.text
local a, b2 = string.sub(text, 1, 70000), string.sub(text, 70001, 140000)
local pa = Lz4.compress(a) :: buffer
-- a block of b2 that copies the first 40 bytes of b2's region from a (a match reaching back across blocks)
local big = buffer.create(buffer.len(pa) + 20)
buffer.copy(big, 9, pa)
local out = Lz4.decompress(big, 9, buffer.len(pa), #a)
t:check(out ~= nil and buffer.tostring(out) == a, "at an offset")
local hand = buffer.create(3 + 1 + 2 + 1)
-- token: 0 literals, match length 15 + ext; offset = 100 back into the previous block
buffer.writeu8(hand, 0, 0x0F)
buffer.writeu16(hand, 1, 100)
buffer.writeu8(hand, 3, 20) -- match length 4 + 15 + 20 = 39
buffer.writeu8(hand, 4, 0x10) -- the last sequence: one literal
buffer.writeu8(hand, 5, 33)
local dst = buffer.create(#a + 40)
buffer.writestring(dst, 0, a)
local e, msg = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40, 0)
t:check(e == #a + 40, "linked block: " .. tostring(msg))
t:eq(buffer.readstring(dst, #a, 39), string.sub(a, #a - 99, #a - 61), "linked block: match from the history")
local e2, msg2 = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40)
t:check(e2 == nil and string.find(msg2 or "", "offset") ~= nil, "without history the match is corrupt")
t:check(b2 ~= nil, "second half")
end
-- errors
do
local _, e1 = Lz4.decompress("")
t:check(e1 and e1.code == Err.TRUNCATED, "empty: " .. tostring(e1))
local _, e2 = Lz4.decompress("\x50ab")
t:check(e2 and e2.code == Err.TRUNCATED, "literals past the end: " .. tostring(e2))
local _, e3 = Lz4.decompress("\x14abcd\x09\x00\x10z")
t:check(e3 and e3.code == Err.CORRUPT, "offset before the start: " .. tostring(e3))
local _, e4 = Lz4.decompress("\x10a", nil, nil, 5)
t:check(e4 and e4.code == Err.CORRUPT, "shorter than outSize: " .. tostring(e4))
local _, e5 = Lz4.decompress("\x50abcde", nil, nil, 2)
t:check(e5 and e5.code == Err.LIMIT, "longer than outSize: " .. tostring(e5))
local _, e6 = Lz4.decompress(C.zeros and (Lz4.compress(C.zeros) :: buffer), nil, nil, nil, { maxBytes = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
local ok, r1, r2 = pcall(Lz4.decompress, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e7 = Lz4.decompress("\x10a", nil, nil, -1)
t:check(e7 and e7.code == Err.ARG, "bad outSize")
end
do
local samples = {}
for i, c in Fx.cases do
if i % 4 == 0 and #c.data > 8 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Lz4.decompress(b, nil, nil, nil, { maxBytes = 1e6 })
end, samples, { mutations = 30, garbage = 2000 })
t:fuzz("decompress (sized)", function(b: buffer)
return Lz4.decompress(b, nil, nil, 70000)
end, samples, { mutations = 30, garbage = 500, seed = 5 })
end
t:done()
+286
View File
@@ -0,0 +1,286 @@
-- tests/model/_rbx: helpers shared by the model/rbxm and model/rbxmx tests: instance paths (the scheme of the lune dump
-- in tools/fixtures/rbxmx.py), our property values in lune's canonical form, a dump comparison, a deep tree comparison,
-- and a tree with a value of every type built from scratch.
local Rbx = require("@formats/codecs/model/Rbx")
local H = {}
local f32buf = buffer.create(4)
local function f32(v: number): number
buffer.writef32(f32buf, 0, v)
return buffer.readf32(f32buf, 0)
end
local function hex(s: string): string
return (string.gsub(s, ".", function(c: string): string
return string.format("%02x", string.byte(c))
end))
end
-- paths(tree) -> { [path] = instance }, { [instance] = path }: names joined with "/", "#k" for the k-th sibling of a name
function H.paths(tree: any): ({ [string]: any }, { [any]: string })
local byPath, ofInst = {}, {}
local function walk(list: { any }, prefix: string)
local seen: { [string]: number } = {}
for _, inst in list do
local n = inst.name
seen[n] = (seen[n] or 0) + 1
local p = prefix .. (if prefix == "" then "" else "/") .. n .. (if seen[n] > 1 then "#" .. seen[n] else "")
byPath[p] = inst
ofInst[inst] = p
walk(inst.children, p)
end
end
walk(tree.roots, "")
return byPath, ofInst
end
local function numbers(t: string, v: any): { number }?
if type(v) == "number" then
return { v }
elseif type(v) ~= "table" then
return nil
end
if t == "NumberSequence" or t == "ColorSequence" then
local out = {}
for _, k in v do
local n = if t == "ColorSequence" then 4 else 3 -- lune has no ColorSequence envelope
for c = 1, n do
table.insert(out, k[c])
end
end
return out
end
return v
end
-- same(ours: Value, want: lune canon, pathOf, propName) -> ok, detail
function H.same(v: any, want: any, pathOf: { [any]: string }, pname: string): (boolean, string)
local t = if v then v.type else "nil"
local x = if v then v.value else nil
local wt = want.t
if wt == "nil" then
return x == nil, "want nil, got " .. t
elseif wt == "string" then
return type(x) == "string" and hex(x) == want.s, "string differs (" .. t .. ")"
elseif wt == "bool" then
return x == want.b, "bool differs"
elseif wt == "Instance" then
return type(x) == "table" and pathOf[x] == want.s, "ref differs: " .. tostring(x and pathOf[x]) .. " vs " .. tostring(want.s)
elseif wt == "Content" then
if want.kind == "None" then
return x == nil, "content not none"
elseif want.kind == "Uri" then
return x == want.s, "content uri " .. tostring(x)
end
return type(x) == "table" and pathOf[x] == want.s, "content object"
elseif wt == "UniqueId" then
return x == want.s, "uniqueid " .. tostring(x) .. " vs " .. tostring(want.s)
elseif wt == "Font" then
return type(x) == "table" and x.family == want.s and x.weight == want.n[1] and x.style == want.style, "font differs"
end
local got = numbers(t, x)
if t == "Color3uint8" and got then
got = { f32(got[1] / 255), f32(got[2] / 255), f32(got[3] / 255) }
end
local n = want.n
if not got or not n then
return false, "no numbers: " .. t .. " vs " .. tostring(wt)
end
local count = #n
if t == "PhysicalProperties" then
count = math.min(#got, #n)
elseif #got ~= #n then
return false, string.format("%d numbers, want %d (%s / %s)", #got, #n, t, wt)
end
for i = 1, count do
if got[i] ~= n[i] then
return false, string.format("%s[%d] = %.9g, want %.9g", t, i, got[i], n[i])
end
end
return true, ""
end
-- compare(t, tree, dump, label) -> properties compared: every instance / property of a lune dump against our tree
function H.compare(t: any, tree: any, dump: any, label: string): number
local byPath, pathOf = H.paths(tree)
local n = 0
for path, e in dump do
local inst = byPath[path]
t:check(inst ~= nil, label .. ": instance " .. path)
if inst then
t:check(inst.className == e.class, label .. ": " .. path .. " class " .. inst.className .. ", want " .. e.class)
for pname, want in e.props do
local v = if pname == "Name" then { type = "String", value = inst.name } else inst.properties[pname]
local ok, detail = H.same(v, want, pathOf, pname)
t:check(ok, label .. ": " .. path .. "." .. pname .. ": " .. detail)
n += 1
end
end
end
return n
end
-- the type family a value compares under (a binary file has one string type; XML writes BrickColor as an int)
local FAMILY: { [string]: string } = {
String = "string",
BinaryString = "string",
ProtectedString = "string",
ContentId = "string",
Bytecode = "string",
BrickColor = "int",
Int32 = "int",
}
local function family(t: string): string
return FAMILY[t] or t
end
-- equal(a, b, pathA, pathB) -> ok, where: values compared deeply (Refs / Content objects by path)
local function equal(a: any, b: any, pa: { [any]: string }, pb: { [any]: string }): boolean
if type(a) ~= type(b) then
return false
end
if type(a) == "buffer" then
return buffer.tostring(a) == buffer.tostring(b)
elseif type(a) ~= "table" then
return a == b or (a ~= a and b ~= b)
end
if a.className and b.className then
return pa[a] == pb[b]
end
for k, v in a do
if not equal(v, b[k], pa, pb) then
return false
end
end
for k in b do
if a[k] == nil then
return false
end
end
return true
end
-- sameTree(t, a, b, label, opts?) -> instances compared: class, name, children and every property (opts.loose:
-- string / int families compare as one type, properties only b has are allowed when another instance of the class has them in a; opts.skipRaw: Raw values are not compared)
function H.sameTree(t: any, a: any, b: any, label: string, opts: any?): number
local o = opts or {}
local pa = select(2, H.paths(a))
local pb = select(2, H.paths(b))
local n = 0
local bad = 0
local classProps: { [string]: { [string]: boolean } } = {}
for inst in Rbx.descendants(a) do
local i = inst :: any
classProps[i.className] = classProps[i.className] or {}
for k in i.properties do
classProps[i.className][k] = true
end
end
local function walk(la: { any }, lb: { any }, where: string)
if #la ~= #lb then
t:check(false, string.format("%s: %s has %d children, want %d", label, where, #lb, #la))
return
end
for i, x in la do
local y = lb[i]
n += 1
local w = where .. "/" .. x.name
if x.className ~= y.className or x.name ~= y.name then
t:check(false, label .. ": " .. w .. ": " .. y.className .. " " .. y.name)
else
for k, v in x.properties do
local u = y.properties[k]
local skip = o.skipRaw and v.type == "Raw"
if not skip then
local tt = if o.loose then family(v.type) == family(u and u.type or "") else u and u.type == v.type
if not tt or not equal(v.value, u.value, pa, pb) then
bad += 1
if bad < 10 then
t:check(false, label .. ": " .. w .. "." .. k .. " (" .. v.type .. " / " .. tostring(u and u.type) .. ")")
end
end
end
end
for k, u in y.properties do
-- a binary file stores a value for every instance of a class: the writer fills in the ones the XML
-- twin leaves out (when another instance of the class has the property)
local filled = o.loose and classProps[y.className] and classProps[y.className][k]
if x.properties[k] == nil and not (o.skipRaw and u.type == "Raw") and not filled then
bad += 1
if bad < 10 then
t:check(false, label .. ": " .. w .. "." .. k .. " is extra")
end
end
end
walk(x.children, y.children, w)
end
end
end
walk(a.roots, b.roots, "")
t:check(bad == 0, label .. ": " .. bad .. " property differences")
return n
end
-- everything() -> a model with one value of every type (and several instances per class)
function H.everything(): any
local tree = Rbx.tree()
local root = Rbx.add(tree, Rbx.instance("Model", "Everything"))
local a = Rbx.add(root, Rbx.instance("Folder", "A"))
local b = Rbx.add(root, Rbx.instance("Folder", "B"))
local c = Rbx.add(a, Rbx.instance("Part", "C"))
local S = Rbx.set
S(a, "Str", "String", "plain")
S(a, "Bin", "BinaryString", "\0\1\2\255")
S(a, "Prot", "ProtectedString", "print('x')")
S(a, "Cid", "ContentId", "rbxassetid://1")
S(a, "Flag", "Bool", true)
S(a, "I32", "Int32", -2147483648)
S(a, "I64", "Int64", 2 ^ 52 + 1)
S(a, "F32", "Float32", f32(0.1))
S(a, "F64", "Float64", 0.1)
S(a, "En", "Enum", 7)
S(a, "Brick", "BrickColor", 1004)
S(a, "Sec", "SecurityCapabilities", 2 ^ 40)
S(a, "Fc", "Faces", 63)
S(a, "Ax", "Axes", 7)
S(a, "Ud", "UDim", { 0.5, -7 })
S(a, "Ud2", "UDim2", { 0.25, 1, -0.5, 1000 })
S(a, "Nr", "NumberRange", { -1, 1 })
S(a, "V2", "Vector2", { 1.5, -2.5 })
S(a, "V2i", "Vector2int16", { -32768, 32767 })
S(a, "V3", "Vector3", { 1, 2, 3 })
S(a, "V3i", "Vector3int16", { -5, 0, 5 })
S(a, "C3", "Color3", { 0.5, 0.25, 1 })
S(a, "C3u", "Color3uint8", { 0, 128, 255 })
S(a, "Rc", "Rect", { 1, 2, 3, 4 })
S(a, "Ry", "Ray", { 1, 2, 3, 0, 0, -1 })
S(a, "Cf", "CFrame", { 1, 2, 3, 0, -1, 0, 1, 0, 0, 0, 0, 1 })
S(a, "Cf2", "CFrame", { 1, 2, 3, f32(0.36), f32(0.48), f32(-0.8), f32(-0.8), f32(0.6), 0, f32(0.48), f32(0.64), f32(0.6) })
S(a, "Ocf", "OptionalCFrame", { 4, 5, 6, 1, 0, 0, 0, 1, 0, 0, 0, 1 })
S(b, "Ocf", "OptionalCFrame", nil)
S(a, "Ns", "NumberSequence", { { 0, 1, 0 }, { 0.5, 2, 0.25 }, { 1, 3, 0 } })
S(a, "Cs", "ColorSequence", { { 0, 1, 0, 0, 0 }, { 1, 0, 0, 1, 0 } })
S(a, "Phys", "PhysicalProperties", { 1, 0.5, 0.25, 2, 3, 1 })
S(b, "Phys", "PhysicalProperties", { 1, 0.5, 0.25, 2, 3, 0.75 })
S(c, "Phys", "PhysicalProperties", nil)
S(a, "Ref", "Ref", c)
S(b, "Ref", "Ref", nil)
S(a, "Sh", "SharedString", "shared\0bytes")
S(b, "Sh", "SharedString", "shared\0bytes")
S(a, "Uid", "UniqueId", "7fb188dace632b4702e9c68d004815fd")
S(b, "Uid", "UniqueId", "00000000000000010000000200000003")
S(a, "Font", "Font", { family = "rbxasset://fonts/families/Arial.json", weight = 700, style = "Italic", cachedFaceId = "rbxasset://fonts/arialbd.ttf" })
S(a, "Ct", "Content", "rbxassetid://5")
S(b, "Ct", "Content", c)
S(c, "Ct", "Content", nil)
-- the same properties on B (columns of two values), so every type is also written for a second instance
for k, v in a.properties do
if b.properties[k] == nil then
b.properties[k] = v
end
end
return tree
end
return H
+268
View File
@@ -0,0 +1,268 @@
-- model/rbxm tests: binary models and places built by rojo 7.7 and lune 0.11 (rbx-dom) decode to the values lune reads
-- from them (every property the files hold); the binary decode equals the decode of the XML twin; Zstandard and raw
-- chunk variants; an unknown chunk and an unknown property type round trip raw; our rbxm output read back by lune
-- equals the original (fixture verdicts); round trips of a tree with every type; options, errors and the fuzz pass.
-- Fixtures: tools/fixtures/rbxmx.py.
local T = require("@tests/T")
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local Rbx = require("@formats/codecs/model/Rbx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local H = require("@tests/model/_rbx")
local Fx = require("@tests/gen/rbx_files")
local Json = require("@formats/codecs/text/Json")
local Ours = require("@tests/gen/rbx_ours")
local t = T.suite("rbxm")
t:eq(Rbxm.name, "rbxm", "name")
t:eq(Rbxm.category, "model", "category")
t:check(table.find(Rbxm.extensions, "rbxl") ~= nil, "extensions")
t:check(Rbxm.caps.decode and Rbxm.caps.encode, "caps")
local function decode(data: any, opts: any?): (any, any)
return Rbxm.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
local function file(name: string): any
for _, f in Fx.files do
if f.name == name then
return f
end
end
error("no fixture " .. name)
end
-- every binary reference file against lune's reading of it, and against the decode of its XML twin
local nprops = 0
local trees: { [string]: any } = {}
for _, f in Fx.files do
if not f.xml then
local tree, err = decode(f.data)
t:check(tree ~= nil, f.name .. ": " .. tostring(err))
if tree then
trees[f.name] = tree
t:check(tree.kind == "rbxtree" and tree.meta.source.format == "rbxm", f.name .. ": an RbxTree")
t:eq(tree.place, f.place, f.name .. ": place")
nprops += H.compare(t, tree, Json.decode(f.dump), f.name)
end
end
end
t:note("%d binary files, %d property values match lune", #Fx.files - 3, nprops)
for _, pair in { { "model.rbxm", "model.rbxmx" }, { "place.rbxl", "place.rbxlx" }, { "lune.rbxm", "lune.rbxmx" } } do
local xt = Rbxmx.decode(Bytes.reader(buffer.fromstring(file(pair[2]).data)))
local n = H.sameTree(t, xt, trees[pair[1]], pair[1] .. " vs " .. pair[2], { loose = true })
t:check(n > 5, pair[1] .. ": instances compared")
end
-- the typed property folder (tools/fixtures/rbxmx.py TYPES_FOLDER), value by value
do
local tree = trees["model.rbxm"]
local f = Rbx.find(tree, "Kit/Types") :: any
t:check(f ~= nil, "Kit/Types")
local P = f.properties
local function v(name: string, typ: string): any
local x = P[name]
t:check(x ~= nil and x.type == typ, name .. " is " .. typ .. " (" .. tostring(x and x.type) .. ")")
return x and x.value
end
t:eq(v("PString", "String"), "hello <world> & \"quotes\" \u{e9}\u{65e5}", "String")
t:eq(v("PBinary", "String"), "\0\1\2\3\4\255", "BinaryString bytes")
t:eq(v("PBool", "Bool"), true, "Bool")
t:eq(v("PInt32", "Int32"), -123, "Int32")
t:eq(v("PInt64", "Int64"), -1234567890123, "Int64")
t:eq(v("PFloat32", "Float32"), 1.5, "Float32")
t:eq(v("PFloat64", "Float64"), 3.141592653589793, "Float64")
t:eq(table.concat(v("PUDim2", "UDim2"), ","), "0.5,10,0.25,-3", "UDim2")
t:eq(table.concat(v("PRay", "Ray"), ","), "1,2,3,4,5,6", "Ray")
t:eq(v("PFaces", "Faces"), 1 + 2 + 32, "Faces")
t:eq(v("PAxes", "Axes"), 1 + 4, "Axes")
t:eq(v("PBrickColor", "BrickColor"), 21, "BrickColor")
t:eq(table.concat(v("PVector3int16", "Vector3int16"), ","), "-1,2,300", "Vector3int16")
t:eq(table.concat(v("PCFrame", "CFrame"), ","), "1,2,3,0,0,1,0,1,0,-1,0,0", "CFrame (rotation id)")
t:check(v("POptCFrame", "OptionalCFrame")[1] == 1, "OptionalCFrame")
t:check(P.POptNone and P.POptNone.type == "OptionalCFrame" and P.POptNone.value == nil, "OptionalCFrame none")
t:eq(v("PEnum", "Enum"), 3, "Enum")
t:eq(#v("PNumberSequence", "NumberSequence"), 3, "NumberSequence keypoints")
t:eq(v("PNumberSequence", "NumberSequence")[2][2], -3, "NumberSequence value")
t:eq(v("PColorSequence", "ColorSequence")[2][4], 1, "ColorSequence")
t:eq(table.concat(v("PNumberRange", "NumberRange"), ","), "1,5", "NumberRange")
t:eq(table.concat(v("PRect", "Rect"), ","), "1,2,3,4", "Rect")
t:eq(table.concat(v("PPhys", "PhysicalProperties"), ","), "1,0.5,0.25,2,3,0.75", "PhysicalProperties")
t:check(P.PPhysDefault and P.PPhysDefault.value == nil, "PhysicalProperties default")
local font = v("PFont", "Font")
t:check(font.family == "rbxasset://fonts/families/Arial.json" and font.weight == 700 and font.style == "Italic", "Font")
t:eq(v("PUniqueId", "UniqueId"), "44b188dace632b4702e9c68d004815fc", "UniqueId")
t:eq(v("PUniqueId2", "UniqueId"), "7fb188dace632b4702e9c68d004815fd", "UniqueId (top bits)")
t:eq(v("PSecurity", "SecurityCapabilities"), 12345, "SecurityCapabilities")
t:eq(v("PContent", "Content"), "rbxassetid://1234", "Content uri")
t:check(P.PContentNone and P.PContentNone.value == nil, "Content none")
t:eq(v("PContentId", "String"), "rbxassetid://99", "ContentId")
t:eq(v("PShared", "SharedString"), "\0\1\2\3", "SharedString")
local types2 = Rbx.find(tree, "Kit/Types2") :: any
t:eq(types2.properties.PShared.value, "\0\1\2\3", "SharedString shared by two instances")
local ptr = Rbx.find(tree, "Kit/Pointer") :: any
t:check(ptr.properties.Value.type == "Ref" and ptr.properties.Value.value == Rbx.find(tree, "Kit/Base"), "Ref")
t:check(string.find(Rbx.get(Rbx.find(tree, "Kit/Code") :: any, "Source"), "]]>", 1, true) ~= nil, "Source")
t:eq(Rbx.fullName(Rbx.find(tree, "Kit/Gui/Frame/Label") :: any), "Kit.Gui.Frame.Label", "fullName")
t:eq(#Rbx.find(tree, "Kit/Parts").children, 120, "120 parts")
t:eq(#Rbx.list(tree), 1 + 12 + 2 + 120, "every instance")
end
-- chunk variants: Zstandard, raw, an unknown chunk and an unknown property type
do
local base = trees["model.rbxm"]
t:eq(table.concat(base.meta.source.compression, ","), "lz4,none", "rojo: lz4 chunks (END raw)")
for _, name in { "model-zstd.rbxm", "model-raw.rbxm" } do
local tree = trees[name]
H.sameTree(t, base, tree, name)
end
t:eq(table.concat(trees["model-zstd.rbxm"].meta.source.compression, ","), "none,zstd", "zstd chunks")
local u = trees["model-unknown.rbxm"]
H.sameTree(t, base, u, "model-unknown.rbxm", { skipRaw = true })
t:check(#u.extra == 1 and u.extra[1].name == "ZZZZ", "the unknown chunk is kept")
local raws = 0
for inst in Rbx.descendants(u) do
local m = (inst :: any).properties.Mystery
if m then
raws += 1
t:check(m.type == "Raw" and m.value.typeId == 0x7f, "unknown property type kept raw")
end
end
t:check(raws > 0, "instances with the raw property: " .. raws)
local again = decode(Rbxm.encode(u) :: buffer)
t:check(again and #again.extra == 1 and buffer.tostring(again.extra[1].data) == buffer.tostring(u.extra[1].data), "unknown chunk round trip")
H.sameTree(t, u, again, "unknown round trip")
-- an edited class (an instance more) drops the raw column instead of writing it wrong
u = decode(file("model-unknown.rbxm").data)
local cls
for inst in Rbx.descendants(u) do
if (inst :: any).properties.Mystery then
cls = (inst :: any).className
break
end
end
Rbx.add(u.roots[1], Rbx.instance(cls, "Added"))
local edited = decode(Rbxm.encode(u) :: buffer)
local still = false
for inst in Rbx.descendants(edited) do
if (inst :: any).properties.Mystery then
still = true
end
end
t:check(edited and not still, "a raw column is dropped when its class changes")
end
-- our encoder: lune reads our rbxm back to the same values (tools/fixtures/rbxmx.py)
local nours = 0
for _, v in Ours do
if string.sub(v.name, -5) == "/rbxm" then
t:check(v.ok, v.name .. ": " .. v.detail)
nours += 1
end
end
t:note("%d of our rbxm files read back by lune", nours)
-- round trips: every reference file, and a tree with every type
for name, tree in trees do
local out, err = Rbxm.encode(tree)
t:check(out ~= nil, name .. ": encode " .. tostring(err))
if out then
local back = decode(out)
H.sameTree(t, tree, back, name .. ": round trip")
t:eq(back.place, tree.place, name .. ": place round trip")
end
end
do
local tree = H.everything()
local out = Rbxm.encode(tree) :: buffer
local back = decode(out)
H.sameTree(t, tree, back, "every type", { loose = true })
local raw = Rbxm.encode(tree, { compression = "none" }) :: buffer
local back2 = decode(raw)
H.sameTree(t, tree, back2, "every type, raw chunks", { loose = true })
t:eq(table.concat(back2.meta.source.compression, ","), "none", "compression = none")
t:check(buffer.len(raw) > buffer.len(out), "lz4 chunks are smaller")
-- through XML and back
local viaXml = Rbxmx.decode(Bytes.reader(Rbxmx.encode(back) :: buffer))
H.sameTree(t, tree, decode(Rbxm.encode(viaXml) :: buffer), "every type via rbxmx", { loose = true })
-- a place: roots marked as services
local place = Rbx.tree(true)
Rbx.add(place, Rbx.instance("Workspace"))
Rbx.add(place, Rbx.instance("Lighting"))
local pb = decode(Rbxm.encode(place) :: buffer)
t:check(pb.place and pb.roots[1].service and pb.roots[2].service, "place services")
local pm = decode(Rbxm.encode(place, { place = false }) :: buffer)
t:check(not pm.place, "place = false")
tree.metadata.ExplicitAutoJoints = "true"
t:eq(decode(Rbxm.encode(tree) :: buffer).metadata.ExplicitAutoJoints, "true", "META")
end
-- sniff, errors
do
local data = file("model.rbxm").data
t:eq(Rbxm.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff")
t:eq(Rbxm.sniff(Bytes.reader(buffer.fromstring(file("model.rbxmx").data))), 0, "sniff XML")
local _, e1 = decode("<roblox!\137\255\13\10\26\10")
t:check(e1 and e1.code == Err.TRUNCATED, "header only: " .. tostring(e1))
local _, e2 = decode("<roblox?" .. string.rep("\0", 40))
t:check(e2 and e2.code == Err.CORRUPT, "bad magic: " .. tostring(e2))
local _, e3 = decode(string.sub(data, 1, #data - 25))
t:check(e3 and e3.code == Err.TRUNCATED, "no END: " .. tostring(e3))
local _, e4 = decode(data, { maxInstances = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxInstances: " .. tostring(e4))
local _, e5 = Rbxm.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode a non-tree")
local bad = Rbx.tree()
local x, y = Rbx.instance("Folder", "x"), Rbx.instance("Folder", "y")
Rbx.set(x, "P", "Int32", 1)
Rbx.set(y, "P", "Vector3", { 1, 2, 3 })
Rbx.add(bad, x)
Rbx.add(bad, y)
local _, e6 = Rbxm.encode(bad)
t:check(e6 and e6.code == Err.ARG, "mixed property types: " .. tostring(e6))
Rbx.set(y, "P", "Nope", 1)
local _, e7 = Rbxm.encode(bad)
t:check(e7 and e7.code == Err.ARG, "unknown type: " .. tostring(e7))
-- a PRNT cycle (A's parent is B, B's parent is A)
local cyc = Rbx.tree()
local a = Rbx.add(cyc, Rbx.instance("Folder", "A"))
Rbx.add(a, Rbx.instance("Folder", "B"))
local raw = Rbxm.encode(cyc, { compression = "none" }) :: buffer
-- the PRNT body: version, count 2, children [0, 1], parents [-1, 0] -> parents [1, 0]
local s = buffer.tostring(raw)
local at = string.find(s, "PRNT", 1, true) :: number
local body = at - 1 + 16
-- parents are the second referent array: zigzag deltas (1, -1) = (2, 1), interleaved big-endian
buffer.writeu8(raw, body + 5 + 8 + 6, 2)
buffer.writeu8(raw, body + 5 + 8 + 7, 1)
local _, e8 = decode(raw)
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 }
t:fuzz("decode", function(b: buffer)
return Rbxm.decode(Bytes.reader(b))
end, samples, { mutations = 150, garbage = 300, keepHeader = 32 })
end
t:done()
+188
View File
@@ -0,0 +1,188 @@
-- model/rbxmx tests: XML models and places built by rojo 7.7 and lune 0.11 (rbx-dom) decode to the values lune reads
-- from them; our rbxmx output read back by lune equals the original (fixture verdicts); round trips of every reference
-- file and of a tree with every type; XML specifics (BinaryString, CDATA, packed Color3, INF / NAN, unknown property
-- tags kept raw, referents, SharedStrings, floats written exactly); errors and the fuzz pass.
-- Fixtures: tools/fixtures/rbxmx.py.
local T = require("@tests/T")
local Rbxmx = require("@formats/model/rbxmx")
local Rbx = require("@formats/codecs/model/Rbx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local H = require("@tests/model/_rbx")
local Fx = require("@tests/gen/rbx_files")
local Json = require("@formats/codecs/text/Json")
local Ours = require("@tests/gen/rbx_ours")
local t = T.suite("rbxmx")
t:eq(Rbxmx.name, "rbxmx", "name")
t:eq(Rbxmx.category, "model", "category")
t:check(table.find(Rbxmx.extensions, "rbxlx") ~= nil, "extensions")
t:check(Rbxmx.caps.decode and Rbxmx.caps.encode, "caps")
local function decode(data: any, opts: any?): (any, any)
return Rbxmx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
local function encode(tree: any, opts: any?): string
return buffer.tostring(Rbxmx.encode(tree, opts) :: buffer)
end
local nprops = 0
local trees: { [string]: any } = {}
for _, f in Fx.files do
if f.xml then
local tree, err = decode(f.data)
t:check(tree ~= nil, f.name .. ": " .. tostring(err))
if tree then
trees[f.name] = tree
t:check(tree.kind == "rbxtree" and tree.meta.source.format == "rbxmx", f.name .. ": an RbxTree")
t:eq(tree.place, f.place, f.name .. ": place")
nprops += H.compare(t, tree, Json.decode(f.dump), f.name)
end
end
end
t:note("3 XML files, %d property values match lune", nprops)
do
local tree = trees["model.rbxmx"]
local P = (Rbx.find(tree, "Kit/Types") :: any).properties
t:eq(P.PBinary.type, "BinaryString", "BinaryString (CDATA)")
t:eq(P.PBinary.value, "\0\1\2\3\4\255", "BinaryString bytes")
t:eq(P.PContentId.type, "ContentId", "ContentId")
t:eq(P.PFloat32.value, 1.5, "float")
t:eq(P.PUniqueId.value, "44b188dace632b4702e9c68d004815fc", "UniqueId")
t:eq(P.PShared.value, "\0\1\2\3", "SharedString")
t:eq(P.PBrickColor.type, "Int32", "a BrickColor of an unknown property reads as its <int>")
local base = (Rbx.find(tree, "Kit/Base") :: any).properties
t:eq(base.Tags.value, "Enemy\0Boss", "Tags")
t:check(#base.AttributesSerialize.value > 10, "AttributesSerialize")
local lune = trees["lune.rbxmx"]
t:eq((Rbx.find(lune, "Kit/Brick") :: any).properties.Value.type, "BrickColor", "BrickColorValue.Value is a BrickColor")
end
local nours = 0
for _, v in Ours do
if string.sub(v.name, -6) == "/rbxmx" then
t:check(v.ok, v.name .. ": " .. v.detail)
nours += 1
end
end
t:note("%d of our rbxmx files read back by lune", nours)
for name, tree in trees do
local back = decode(encode(tree))
H.sameTree(t, tree, back, name .. ": round trip")
t:eq(back.place, tree.place, name .. ": place round trip")
end
do
local tree = H.everything()
local s = encode(tree)
H.sameTree(t, tree, decode(s), "every type", { loose = true })
t:check(string.find(s, '<roblox version="4">', 1, true) == 1, "rbx-dom's root element")
t:check(string.find(s, "<SharedStrings>", 1, true) ~= nil, "SharedStrings")
local again = encode(decode(s))
t:eq(again, s, "a second write is byte-identical")
local flat = encode(tree, { indent = 0 })
t:check(not string.find(flat, "\n <Item", 1, true) and decode(flat) ~= nil, "indent = 0")
end
-- XML specifics
do
local doc = [==[<?xml version="1.0" encoding="utf-8"?>
<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" version="4">
<Meta name="ExplicitAutoJoints">true</Meta>
<External>null</External>
<Item class="Part" referent="RBXA">
<Properties>
<string name="Name"><![CDATA[Odd <name>]]></string>
<Color3 name="Color">4294934528</Color3>
<float name="Inf">INF</float>
<double name="NegInf">-INF</double>
<float name="Nan">NAN</float>
<Ref name="Self">RBXA</Ref>
<Ref name="None">null</Ref>
<BinaryString name="Data">
AAEC
AwQ=
</BinaryString>
<Content name="Old"><url>rbxasset://textures/a.png</url></Content>
<Content name="OldNull"><null></null></Content>
<FutureType name="Mystery"><A>1</A><B x="2"/></FutureType>
<PhysicalProperties name="Phys"><CustomPhysics>true</CustomPhysics><Density>2</Density><Friction>0.3</Friction><Elasticity>0.5</Elasticity><FrictionWeight>1</FrictionWeight><ElasticityWeight>1</ElasticityWeight></PhysicalProperties>
</Properties>
</Item>
</roblox>]==]
local tree, err = decode(doc)
t:check(tree ~= nil, "a hand-written file: " .. tostring(err))
local p = tree.roots[1]
t:eq(p.name, "Odd <name>", "CDATA name")
local c = p.properties.Color.value
t:check(c[1] == 1 and math.abs(c[2] - 0x80 / 255) < 1e-6 and c[3] == 0, "packed ARGB Color3")
t:eq(p.properties.Inf.value, math.huge, "INF")
t:eq(p.properties.NegInf.value, -math.huge, "-INF")
t:check(p.properties.Nan.value ~= p.properties.Nan.value, "NAN")
t:check(p.properties.Self.value == p, "Ref to itself")
t:check(p.properties.None.type == "Ref" and p.properties.None.value == nil, "Ref null")
t:eq(p.properties.Data.value, "\0\1\2\3\4", "BinaryString with whitespace")
t:eq(p.properties.Old.type, "ContentId", "legacy <Content><url>")
t:eq(p.properties.Old.value, "rbxasset://textures/a.png", "url")
t:eq(p.properties.Mystery.type, "XmlRaw", "unknown tag kept")
t:eq(p.properties.Phys.value[6], 1, "acoustic absorption defaults to 1")
t:eq(tree.metadata.ExplicitAutoJoints, "true", "Meta")
t:eq(#tree.extra, 1, "<External> kept")
local out = encode(tree)
t:check(string.find(out, '<FutureType name="Mystery"><A>1</A><B x="2"></B></FutureType>', 1, true) ~= nil
or string.find(out, "<FutureType", 1, true) ~= nil, "unknown tag written back")
local back = decode(out)
t:eq(back.roots[1].properties.Mystery.type, "XmlRaw", "unknown tag round trip")
t:eq(back.roots[1].properties.Inf.value, math.huge, "INF round trip")
t:check(back.roots[1].properties.Self.value == back.roots[1], "Ref round trip")
t:check(string.find(out, '<Meta name="ExplicitAutoJoints">true</Meta>', 1, true) ~= nil, "Meta written")
-- a String with bytes XML cannot hold is written as a BinaryString
local raw = Rbx.tree()
local f = Rbx.add(raw, Rbx.instance("Folder"))
Rbx.set(f, "Blob", "String", "a\0b\255")
local rs = encode(raw)
t:check(string.find(rs, '<BinaryString name="Blob">', 1, true) ~= nil, "binary bytes as BinaryString")
t:eq(decode(rs).roots[1].properties.Blob.value, "a\0b\255", "binary bytes round trip")
-- floats: the shortest text that reads back exactly
local fl = Rbx.tree()
local g = Rbx.add(fl, Rbx.instance("Folder"))
Rbx.set(g, "A", "Float64", 0.1)
Rbx.set(g, "B", "Float32", 0.1)
Rbx.set(g, "C", "Vector3", { 1 / 3, 1e-30, -2 ^ 100 })
local fs = encode(fl)
t:check(string.find(fs, '<double name="A">0.1</double>', 1, true) ~= nil, "double 0.1")
t:check(string.find(fs, '<float name="B">0.1</float>', 1, true) ~= nil, "float 0.1")
local fb = decode(fs).roots[1].properties
t:eq(fb.A.value, 0.1, "double exact")
local v = buffer.create(4)
buffer.writef32(v, 0, 1 / 3)
t:eq(fb.C.value[1], buffer.readf32(v, 0), "f32 exact")
end
-- sniff, errors
do
local data = Fx.files[2].data
t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff")
t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring("<?xml version='1.0'?>\n<roblox version=\"4\">"))), 1, "sniff with a declaration")
t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring(Fx.files[1].data))), 0, "sniff binary")
t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring("<svg/>"))), 0, "sniff other XML")
local _, e1 = decode("<svg></svg>")
t:check(e1 and e1.code == Err.CORRUPT, "not <roblox>: " .. tostring(e1))
local _, e2 = decode("<roblox version=\"4\"><Item class=\"Part\">")
t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2))
local _, e3 = decode("<roblox><Item><Properties/></Item></roblox>")
t:check(e3 and e3.code == Err.CORRUPT, "an Item without a class: " .. tostring(e3))
local _, e4 = Rbxmx.encode({ kind = "scene" } :: any)
t:check(e4 and e4.code == Err.ARG, "encode a non-tree")
end
do
local samples = { Fx.files[2].data, encode(H.everything()) }
t:fuzz("decode", function(b: buffer)
return Rbxmx.decode(Bytes.reader(b))
end, samples, { mutations = 80, garbage = 300 })
end
t:done()
+202
View File
@@ -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()
+14 -1
View File
@@ -1,7 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
@@ -236,6 +236,19 @@ do
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Lz4 = require("@formats/codecs/compress/Lz4")
local LB = require("@tests/gen/lz4_bench")
local lz = buffer.fromstring(LB.data)
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
bench("lz4 block decompress (hc9)", 5, LB.size, function()
Lz4.decompress(lz, nil, nil, LB.size)
end)
bench("lz4 block compress", 3, LB.size, function()
Lz4.compress(raw)
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
+13
View File
@@ -0,0 +1,13 @@
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
local Lz4 = require("@formats/codecs/compress/Lz4")
local C = require("@tests/gen/lz4_corpora")
for name, data in C do
local b = assert(Lz4.compress(data))
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
print(name .. " " .. table.concat(t))
end
+27
View File
@@ -0,0 +1,27 @@
-- tools/fixtures/_rbx_encode.luau: run by tools/fixtures/rbxmx.py under the luau CLI: decodes every file of
-- tests/gen/rbx_files (model/rbxm or model/rbxmx) and writes it back with both encoders; prints
-- "<file>/rbxm <hex>" and "<file>/rbxmx <hex>" lines for lune to read.
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local Bytes = require("@formats/core/Bytes")
local Fx = require("@tests/gen/rbx_files")
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 _, f in Fx.files do
local fmt: any = if f.xml then Rbxmx else Rbxm
local tree, err = fmt.decode(Bytes.reader(buffer.fromstring(f.data)))
if not tree then
error(f.name .. ": " .. tostring(err))
end
local a = assert(Rbxm.encode(tree))
print(f.name .. "/rbxm " .. hex(a))
local b = assert(Rbxmx.encode(tree))
print(f.name .. "/rbxmx " .. hex(b))
end
+30
View File
@@ -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 "<case>/<version> <hex>" 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
+90
View File
@@ -0,0 +1,90 @@
# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
import json, os, random, shutil, subprocess, zlib
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
REF = r"""
import json, sys, lz4.block
req = json.load(sys.stdin)
out = {}
if req["op"] == "compress":
for name, hexdata in req["corpora"].items():
data = bytes.fromhex(hexdata)
res = {}
for acc in (1, 4, 16):
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
for lv in (4, 9, 12):
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
out[name] = res
else:
for name, item in req["blocks"].items():
try:
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
out[name] = got.hex() == item["want"]
except Exception as e:
out[name] = False
print(json.dumps(out))
"""
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) >= 300000:
break
text = bytes(text[:300000])
far = rng.randbytes(9000)
return {
"empty": b"",
"one": b"a",
"twelve": b"abcabcabcabc",
"thirteen": b"abcabcabcabca",
"short": b"hello, hello, hello lz4 world\n",
"text": text[:150000],
"random": rng.randbytes(20000),
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
"zeros": b"\0" * 100000,
"far": far + rng.randbytes(60000) + far,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(41)
cs = corpora(rng)
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
cases = []
for name, res in ref.items():
for mode, hexdata in res.items():
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
# our encoder's blocks, read back by the reference
ctx.emit("lz4_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
blocks = {}
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
ctx.emit("lz4", {"cases": cases, "ours": ours})
bench = bytearray()
while len(bench) < 6_000_000:
bench += cs["text"] + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
bench = bytes(bench[:6_000_000])
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})
+492
View File
@@ -0,0 +1,492 @@
# Roblox model / place fixtures (tools/fixtures.py) for model/rbxm (binary) and model/rbxmx (XML); one generator for
# both (named rbxmx so that both test filters, "rbxm" and "rbxmx", run it).
# Reference files: rojo 7.7 builds of a model project (a Folder with an explicitly typed property of every type, real
# instances with Refs / SharedStrings / attributes / tags, 120 parts with random and axis-aligned CFrames) and of a
# place project (DataModel services) to .rbxm / .rbxmx / .rbxl / .rbxlx; lune 0.11 (rbx-dom) builds a model of real
# properties of every type lune can set to .rbxm / .rbxmx; variants of the binary model with Zstandard chunks (zstd),
# raw chunks, and an unknown chunk + an unknown property type (python-lz4 / python-zstandard re-pack the chunks).
# Dumps: lune reads every reference file and prints each property the file holds (the names come from the XML twin)
# in a canonical form; the tests compare our decode against it.
# Ours: tools/fixtures/_rbx_encode.luau (luau CLI) decodes every file and writes it back as rbxm and rbxmx; lune
# reads our files and the dumps must equal the reference dumps (verdicts).
# tests/gen/rbx_files.luau { files = { { name, data, xml, place, dump = JSON text of { [path] = { class, props =
# { [name] = canon }, attrs, tags } } } } }
# tests/gen/rbx_ours.luau { { name, ok, detail } }
import json, math, os, random, shutil, struct, subprocess, tempfile
import xml.etree.ElementTree as ET
INPUTS = ["src/Formats/model/rbxm", "src/Formats/model/rbxmx", "src/Formats/codecs/model/Rbx", "tools/fixtures/_rbx_encode.luau"]
# ---------------------------------------------------------------------------------------------------- rojo projects
def cframe(pos, rows):
return {"CFrame": {"position": pos, "orientation": rows}}
def random_rotation(rng):
q = [rng.gauss(0, 1) for _ in range(4)]
n = math.sqrt(sum(c * c for c in q))
x, y, z, w = (c / n for c in q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
AXES = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (-1, 0, 0), (0, -1, 0), (0, 0, -1)]
def axis_rotation(rng):
while True:
r, u = rng.choice(AXES), rng.choice(AXES)
if any(a * b for a, b in zip(r, u)) == 0 and r != u and tuple(-c for c in r) != u:
break
k = (r[1] * u[2] - r[2] * u[1], r[2] * u[0] - r[0] * u[2], r[0] * u[1] - r[1] * u[0])
return [[r[0], u[0], k[0]], [r[1], u[1], k[1]], [r[2], u[2], k[2]]]
TYPES_FOLDER = {
"PString": {"String": "hello <world> & \"quotes\" é日"},
"PBinary": {"BinaryString": "AAECAwT/"},
"PBool": {"Bool": True},
"PInt32": {"Int32": -123},
"PInt64": {"Int64": -1234567890123},
"PFloat32": {"Float32": 1.5},
"PFloat64": {"Float64": 3.141592653589793},
"PUDim": {"UDim": [0.5, 10]},
"PUDim2": {"UDim2": [[0.5, 10], [0.25, -3]]},
"PRay": {"Ray": {"origin": [1, 2, 3], "direction": [4, 5, 6]}},
"PFaces": {"Faces": ["Right", "Top", "Front"]},
"PAxes": {"Axes": ["X", "Z"]},
"PBrickColor": {"BrickColor": 21},
"PColor3": {"Color3": [0.25, 0.5, 1]},
"PVector2": {"Vector2": [1.5, -2]},
"PVector3": {"Vector3": [1, -2, 3.25]},
"PVector3int16": {"Vector3int16": [-1, 2, 300]},
"PCFrame": cframe([1, 2, 3], [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]),
"PCFrame2": cframe([4, 5, 6], [[0.36, 0.48, -0.8], [-0.8, 0.6, 0], [0.48, 0.64, 0.6]]),
"POptCFrame": {"OptionalCFrame": {"position": [1, 2, 3], "orientation": [[1, 0, 0], [0, 1, 0], [0, 0, 1]]}},
"POptNone": {"OptionalCFrame": None},
"PEnum": {"Enum": 3},
"PNumberSequence": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0.5}, {"time": 0.5, "value": -3, "envelope": 0}, {"time": 1, "value": 2, "envelope": 0}]}},
"PColorSequence": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 0, 0]}, {"time": 1, "color": [0, 0.5, 1]}]}},
"PNumberRange": {"NumberRange": [1, 5]},
"PRect": {"Rect": [[1, 2], [3, 4]]},
"PPhys": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 0.75}},
"PPhysDefault": {"PhysicalProperties": "Default"},
"PFont": {"Font": {"family": "rbxasset://fonts/families/Arial.json", "weight": "Bold", "style": "Italic"}},
"PUniqueId": {"UniqueId": "44b188dace632b4702e9c68d004815fc"},
"PUniqueId2": {"UniqueId": "7fb188dace632b4702e9c68d004815fd"},
"PSecurity": {"SecurityCapabilities": 12345},
"PContent": {"Content": {"Uri": "rbxassetid://1234"}},
"PContentNone": {"Content": "None"},
"PContentId": {"ContentId": "rbxassetid://99"},
"PShared": {"SharedString": "AAECAw=="},
}
def model_project(rng):
parts = {}
for i in range(120):
rows = axis_rotation(rng) if i % 3 else random_rotation(rng)
pos = [round(rng.uniform(-500, 500), 3) for _ in range(3)]
parts["P%03d" % i] = {"$className": "Part", "$properties": {
"CFrame": cframe(pos, rows),
"Size": [rng.choice([1, 2, 4, 0.5]), rng.uniform(0.2, 20), 2],
"Color": [rng.random(), rng.random(), rng.random()],
"Anchored": rng.random() < 0.5,
"Transparency": rng.choice([0, 0.25, 0.5]),
}}
tree = {
"$className": "Model",
"Types": {"$className": "Folder", "$properties": TYPES_FOLDER, "$attributes": {"Num": 5, "Str": "x", "Flag": True}},
"Types2": {"$className": "Folder", "$properties": {"PString": {"String": ""}, "PShared": {"SharedString": "AAECAw=="}, "PInt32": {"Int32": 2147483647}}},
"Base": {"$className": "Part", "$properties": {
"Size": [4, 1, 2], "CFrame": cframe([1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]), "Color": [0.2, 0.4, 0.6],
"Anchored": True, "Material": {"Enum": 288},
"CustomPhysicalProperties": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 1}},
"UniqueId": {"UniqueId": "0123456789abcdef0011223344556677"},
"Capabilities": {"SecurityCapabilities": 12345},
"Tags": ["Enemy", "Boss"],
}, "$attributes": {"Rojo_Id": "base", "Hp": 100}},
"Pointer": {"$className": "ObjectValue", "$attributes": {"Rojo_Target_Value": "base"}},
"Empty": {"$className": "ObjectValue"},
"Code": {"$className": "Script", "$properties": {"Source": "print('hi')\n-- <xml> & \"quotes\" ]]>\n"}},
"Emitter": {"$className": "ParticleEmitter", "$properties": {
"Size": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0}, {"time": 1, "value": 3, "envelope": 0}]}},
"Color": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 1, 0]}, {"time": 1, "color": [0, 1, 1]}]}},
"Lifetime": {"NumberRange": [1, 2]}}},
"Gui": {"$className": "ScreenGui", "Frame": {"$className": "Frame", "$properties": {"Size": {"UDim2": [[0.5, 10], [0.25, -3]]}, "BackgroundColor3": [1, 0.5, 0]},
"Label": {"$className": "TextLabel", "$properties": {"Text": "label", "FontFace": {"Font": {"family": "rbxasset://fonts/families/Ubuntu.json", "weight": "Light", "style": "Normal"}}}}}},
"Mesh": {"$className": "MeshPart", "$properties": {"MeshContent": {"Content": {"Uri": "rbxassetid://777"}}}},
"Same": {"$className": "Folder"},
"Same2": {"$className": "Folder", "$properties": {"Name": {"String": "Same"}}},
"Parts": dict({"$className": "Folder"}, **parts),
}
return {"name": "Kit", "tree": tree}
def place_project():
return {"name": "Place", "tree": {
"$className": "DataModel",
"Workspace": {"$className": "Workspace", "$properties": {"Gravity": 100},
"Floor": {"$className": "Part", "$properties": {"Size": [64, 1, 64], "Anchored": True, "Color": [0.3, 0.6, 0.3]}}},
"Lighting": {"$className": "Lighting", "$properties": {"Ambient": [0.1, 0.2, 0.3], "ClockTime": 12.5, "Brightness": 2}},
"ReplicatedStorage": {"$className": "ReplicatedStorage", "Lib": {"$className": "ModuleScript", "$properties": {"Source": "return { answer = 42 }\n"}}},
"ServerScriptService": {"$className": "ServerScriptService", "Main": {"$className": "Script", "$properties": {"Source": "print(require(game.ReplicatedStorage.Lib).answer)\n"}}},
"StarterGui": {"$className": "StarterGui"},
}}
# ---------------------------------------------------------------------------------------------------- lune scripts
LUNE_GEN = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local process = require("@lune/process")
local I = roblox.Instance.new
local V3, CF = roblox.Vector3.new, roblox.CFrame.new
local m = I("Model"); m.Name = "Kit"
local p = I("Part"); p.Name = "Base"; p.Parent = m
p.CFrame = CF(1, 2, 3) * roblox.CFrame.Angles(0.3, 0.2, 0.1)
p.Size = V3(4, 1, 2)
p.Color = roblox.Color3.fromRGB(10, 20, 255)
p.Anchored = true
p.Transparency = 0.25
p.Material = roblox.Enum.Material.Neon
p.CustomPhysicalProperties = roblox.PhysicalProperties.new(1, 0.5, 0.25, 2, 3)
p:SetAttribute("Hp", 5); p:SetAttribute("Label", "x"); p:SetAttribute("Pos", V3(1, 2, 3))
p:AddTag("Enemy"); p:AddTag("Boss")
m.PrimaryPart = p
local function add(cls, name, f) local i = I(cls); i.Name = name; i.Parent = m; f(i); return i end
add("StringValue", "Str", function(i) i.Value = "hello\nworld <&>" end)
add("IntValue", "Int", function(i) i.Value = -1234567890123 end)
add("NumberValue", "Num", function(i) i.Value = math.pi end)
add("ObjectValue", "Obj", function(i) i.Value = p end)
add("ObjectValue", "ObjNil", function(i) end)
add("RayValue", "Ray", function(i) i.Value = roblox.Ray.new(V3(1, 2, 3), V3(4, 5, 6)) end)
add("BrickColorValue", "Brick", function(i) i.Value = roblox.BrickColor.new(21) end)
add("Color3Value", "Col", function(i) i.Value = roblox.Color3.new(0.25, 0.5, 1) end)
add("CFrameValue", "Cf", function(i) i.Value = CF(5, 6, 7) * roblox.CFrame.Angles(0, math.pi / 2, 0) end)
add("Vector3Value", "Vec", function(i) i.Value = V3(1, -2, 3.25) end)
add("Sky", "Sky", function(i) i.StarCount = 1234 end)
add("Handles", "Handles", function(i) i.Faces = roblox.Faces.new(roblox.Enum.NormalId.Top, roblox.Enum.NormalId.Front) end)
add("ArcHandles", "Arcs", function(i) i.Axes = roblox.Axes.new(roblox.Enum.Axis.X, roblox.Enum.Axis.Z) end)
add("TerrainRegion", "Region", function(i) i.ExtentsMax = roblox.Vector3int16.new(-1, 2, 300) end)
add("Script", "Code", function(i) i.Source = "print('hi')\n" end)
add("Decal", "Decal", function(i) i.Texture = "rbxassetid://55" end)
local pe = I("ParticleEmitter"); pe.Parent = p
pe.Size = roblox.NumberSequence.new({roblox.NumberSequenceKeypoint.new(0, 1, 0.5), roblox.NumberSequenceKeypoint.new(1, 2)})
pe.Color = roblox.ColorSequence.new(roblox.Color3.new(1, 0, 0), roblox.Color3.new(0, 0, 1))
pe.Lifetime = roblox.NumberRange.new(1, 5)
local sg = I("ScreenGui"); sg.Parent = m
local fr = I("Frame"); fr.Parent = sg; fr.Size = roblox.UDim2.new(0.5, 10, 0.25, -3)
local ul = I("UIListLayout"); ul.Parent = fr; ul.Padding = roblox.UDim.new(0.1, 4)
local il = I("ImageLabel"); il.Parent = fr; il.SliceCenter = roblox.Rect.new(1, 2, 3, 4); il.ImageRectOffset = roblox.Vector2.new(1.5, -2)
local tl = I("TextLabel"); tl.Parent = fr; tl.FontFace = roblox.Font.new("rbxasset://fonts/families/Arial.json", roblox.Enum.FontWeight.Bold, roblox.Enum.FontStyle.Italic)
local sm = I("SpecialMesh"); sm.Parent = p; sm.MeshContent = roblox.Content.fromUri("rbxassetid://1234")
m.ModelMeshData = "\0\1\2\3"
local folder = I("Folder"); folder.Name = "Many"; folder.Parent = m
local seed = 12345
local function rnd() seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648 end
for k = 1, 150 do
local q = I("Part"); q.Name = "Q" .. k; q.Parent = folder
local rot = if k % 2 == 0 then roblox.CFrame.Angles(0, math.pi / 2 * (k % 4), 0) else roblox.CFrame.Angles(rnd() * 6, rnd() * 6, rnd() * 6)
q.CFrame = CF(rnd() * 1000 - 500, rnd() * 100, rnd() * 1000 - 500) * rot
q.Size = V3(1 + rnd() * 10, 1, 1 + rnd() * 3)
q.Color = roblox.Color3.new(rnd(), rnd(), rnd())
q.Anchored = k % 3 == 0
if k % 5 == 0 then q.Transparency = rnd() end
end
local dir = process.args[1]
fs.writeFile(dir .. "/lune.rbxm", roblox.serializeModel({m}))
fs.writeFile(dir .. "/lune.rbxmx", roblox.serializeModel({m}, true))
"""
LUNE_DUMP = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local serde = require("@lune/serde")
local process = require("@lune/process")
local req = serde.decode("json", fs.readFile(process.args[1]))
local ALIAS = { size = "Size", Color3uint8 = "Color", shape = "Shape", formFactorRaw = "FormFactor", MaxPlayersInternal = "MaxPlayers" }
local function hex(s)
return (string.gsub(s, ".", function(c) return string.format("%02x", string.byte(c)) end))
end
local paths = {}
local function walk(list, prefix)
local seen = {}
for _, inst in list do
local n = inst.Name
seen[n] = (seen[n] or 0) + 1
local p = prefix .. (if prefix == "" then "" else "/") .. n .. (if seen[n] > 1 then "#" .. seen[n] else "")
paths[inst] = p
walk(inst:GetChildren(), p)
end
end
local function bits(v, names)
local b, k = 0, 1
for _, n in names do
if v[n] then b += k end
k *= 2
end
return b
end
local function canon(v)
local t = typeof(v)
if v == nil then return { t = "nil" } end
if t == "string" then return { t = "string", s = hex(v) } end
if t == "boolean" then return { t = "bool", b = v } end
if t == "number" then return { t = "number", n = { v } } end
if t == "Vector3" or t == "Vector3int16" then return { t = t, n = { v.X, v.Y, v.Z } } end
if t == "Vector2" or t == "Vector2int16" then return { t = t, n = { v.X, v.Y } } end
if t == "CFrame" then return { t = t, n = { v:GetComponents() } } end
if t == "Color3" then return { t = t, n = { v.R, v.G, v.B } } end
if t == "UDim" then return { t = t, n = { v.Scale, v.Offset } } end
if t == "UDim2" then return { t = t, n = { v.X.Scale, v.X.Offset, v.Y.Scale, v.Y.Offset } } end
if t == "Rect" then return { t = t, n = { v.Min.X, v.Min.Y, v.Max.X, v.Max.Y } } end
if t == "NumberRange" then return { t = t, n = { v.Min, v.Max } } end
if t == "Ray" then return { t = t, n = { v.Origin.X, v.Origin.Y, v.Origin.Z, v.Direction.X, v.Direction.Y, v.Direction.Z } } end
if t == "NumberSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value); table.insert(n, k.Envelope) end
return { t = t, n = n }
end
if t == "ColorSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value.R); table.insert(n, k.Value.G); table.insert(n, k.Value.B) end
return { t = t, n = n }
end
if t == "PhysicalProperties" then return { t = t, n = { v.Density, v.Friction, v.Elasticity, v.FrictionWeight, v.ElasticityWeight, v.AcousticAbsorption } } end
if t == "BrickColor" then return { t = t, n = { v.Number } } end
if t == "EnumItem" then return { t = t, n = { v.Value } } end
if t == "Faces" then return { t = t, n = { bits(v, { "Right", "Top", "Back", "Left", "Bottom", "Front" }) } } end
if t == "Axes" then return { t = t, n = { bits(v, { "X", "Y", "Z" }) } } end
if t == "Font" then return { t = t, s = v.Family, n = { v.Weight.Value }, style = v.Style.Name } end
if t == "Instance" then return { t = t, s = paths[v] or "?" } end
if t == "Content" then
local st = v.SourceType.Name
return { t = t, kind = st, s = if st == "Uri" then v.Uri elseif st == "Object" then (paths[v.Object] or "?") else "" }
end
if t == "UniqueId" then return { t = t, s = string.lower((string.gsub(tostring(v), "[^%x]", ""))) } end
return { t = t, s = tostring(v) }
end
local out = {}
for _, f in req.files do
local data = fs.readFile(f.path)
paths = {}
local roots
local ok, err = pcall(function()
if f.place then roots = roblox.deserializePlace(data):GetChildren() else roots = roblox.deserializeModel(data) end
end)
if not ok then
out[f.key] = { error = tostring(err) }
else
walk(roots, "")
local d = {}
for inst, p in paths do
local want = f.names[p]
local e = { class = inst.ClassName, props = {} }
if want then
for _, name in want do
local okv, v = pcall(function() return inst[ALIAS[name] or name] end)
if okv then e.props[name] = canon(v) end
end
end
local attrs = {}
for k, v in inst:GetAttributes() do attrs[k] = canon(v) end
e.attrs = attrs
e.tags = inst:GetTags()
d[p] = e
end
out[f.key] = d
end
end
print(serde.encode("json", out))
"""
# ---------------------------------------------------------------------------------------------------- chunk re-packing
REPACK = r"""
import json, struct, sys, lz4.block, zstandard
req = json.load(sys.stdin)
data = bytes.fromhex(req["data"])
mode = req["mode"]
out = bytearray(data[:32])
p = 32
while p < len(data):
name = data[p:p + 4]
cl, ul, res = struct.unpack_from("<III", data, p + 4)
p += 16
if cl == 0:
body = data[p:p + ul]; p += ul
else:
body = lz4.block.decompress(data[p:p + cl], uncompressed_size=ul); p += cl
if mode == "unknown" and name == b"END\0":
# an unknown chunk, and a PROP of an unknown type (0x7f) for class 0 (n instances, 3 bytes each)
extra = b"just some bytes the format does not know"
out += b"ZZZZ" + struct.pack("<III", 0, len(extra), 0) + extra
n = req["class0"]
prop = struct.pack("<i", 0) + struct.pack("<I", 7) + b"Mystery" + bytes([0x7f]) + bytes((i * 7 + k) % 256 for i in range(n) for k in range(3))
out += b"PROP" + struct.pack("<III", 0, len(prop), 0) + prop
if name == b"END\0" or mode in ("raw", "unknown"):
out += name + struct.pack("<III", 0, len(body), 0) + body
else:
z = zstandard.ZstdCompressor(level=3, write_content_size=True).compress(body)
out += name + struct.pack("<III", len(z), len(body), 0) + z
sys.stdout.write(out.hex())
"""
# ---------------------------------------------------------------------------------------------------- names from XML
def xml_names(xml_bytes):
"""{ path: [property names] } from an rbxmx / rbxlx (the same path scheme as the lune dump)"""
root = ET.fromstring(xml_bytes)
names = {}
def walk(items, prefix):
seen = {}
for it in items:
props = it.find("Properties")
nm = None
plist = []
if props is not None:
for pr in props:
pn = pr.get("name")
if pn == "Name":
nm = pr.text or ""
elif pn is not None:
plist.append(pn)
nm = nm if nm is not None else it.get("class")
seen[nm] = seen.get(nm, 0) + 1
path = prefix + ("" if prefix == "" else "/") + nm + ("#%d" % seen[nm] if seen[nm] > 1 else "")
names[path] = ["Name"] + [n for n in plist if n not in ("AttributesSerialize", "Tags")]
walk(it.findall("Item"), path)
walk(root.findall("Item"), "")
return names
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="formats-rbx-")
try:
_generate(ctx, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def lune(ctx, script, args, tmp):
path = os.path.join(tmp, "script_%d.luau" % abs(hash(script)))
with open(path, "w") as f:
f.write(script)
try:
return subprocess.run(["nix", "shell", "nixpkgs#lune", "-c", "lune", "run", path] + args, capture_output=True, check=True, cwd=tmp).stdout
except subprocess.CalledProcessError as e:
raise RuntimeError("lune: " + e.stderr.decode(errors="replace")[-3000:])
def _generate(ctx, tmp):
rng = random.Random(77)
with open(os.path.join(tmp, "model.project.json"), "w") as f:
json.dump(model_project(rng), f)
with open(os.path.join(tmp, "place.project.json"), "w") as f:
json.dump(place_project(), f)
for proj, outs in (("model", ("model.rbxm", "model.rbxmx")), ("place", ("place.rbxl", "place.rbxlx"))):
for o in outs:
ctx.nix("rojo", ["rojo", "build", os.path.join(tmp, proj + ".project.json"), "-o", os.path.join(tmp, o)])
lune(ctx, LUNE_GEN, [tmp], tmp)
def read(n):
with open(os.path.join(tmp, n), "rb") as f:
return f.read()
files = []
for name, twin, place in (("model.rbxm", "model.rbxmx", False), ("model.rbxmx", "model.rbxmx", False),
("place.rbxl", "place.rbxlx", True), ("place.rbxlx", "place.rbxlx", True),
("lune.rbxm", "lune.rbxmx", False), ("lune.rbxmx", "lune.rbxmx", False)):
files.append({"name": name, "data": read(name), "xml": name.endswith("x"), "place": place, "names": xml_names(read(twin))})
# re-packed variants of the binary model
model = read("model.rbxm")
n0 = None
for mode in ("zstd", "raw", "unknown"):
req = {"data": model.hex(), "mode": mode, "class0": n0 or 0}
if mode == "unknown":
# class 0's instance count: from the raw variant's first INST chunk
raw = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps({"data": model.hex(), "mode": "raw", "class0": 0}).encode()).decode())
p = 32
while True:
size = struct.unpack_from("<I", raw, p + 8)[0]
if raw[p:p + 4] == b"INST":
body = raw[p + 16:p + 16 + size]
cid, nl = struct.unpack_from("<iI", body, 0)
if cid == 0:
n0 = struct.unpack_from("<I", body, 8 + nl + 1)[0]
break
p += 16 + size
req["class0"] = n0
data = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps(req).encode()).decode())
fn = "model-%s.rbxm" % mode
with open(os.path.join(tmp, fn), "wb") as f:
f.write(data)
files.append({"name": fn, "data": data, "xml": False, "place": False, "names": files[0]["names"]})
for f in files:
f["path"] = os.path.join(tmp, f["name"])
f["key"] = f["name"]
req = {"files": [{"key": f["key"], "path": f["path"], "place": f["place"], "names": f["names"]} for f in files]}
with open(os.path.join(tmp, "dump.json"), "w") as fh:
json.dump(req, fh)
dumps = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump.json")], tmp))
for f in files:
d = dumps[f["key"]]
assert "error" not in d, (f["name"], d)
f["dump"] = d
# the dumps as JSON text (a deep Luau table literal is too complex for luau-analyze)
ctx.emit("rbx_files", {"files": [dict({k: f[k] for k in ("name", "data", "xml", "place")}, dump=json.dumps(f["dump"], sort_keys=True)) for f in files]})
# ours: every file decoded and written back as rbxm and rbxmx, read by lune
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_rbx_encode.luau")], capture_output=True, cwd=ctx.root)
if enc.returncode != 0:
raise RuntimeError("_rbx_encode: " + enc.stderr.decode(errors="replace")[-3000:])
ours = []
byname = {f["name"]: f for f in files}
for line in enc.stdout.decode().split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
src, fmt = label.split("/")
fn = "ours-%s.%s" % (src.replace(".", "_"), ("rbxl" if byname[src]["place"] else "rbxm") + ("x" if fmt == "rbxmx" else ""))
with open(os.path.join(tmp, fn), "wb") as fh:
fh.write(bytes.fromhex(hexdata.strip()))
ours.append((label, fn, byname[src]))
req = {"files": [{"key": label, "path": os.path.join(tmp, fn), "place": f["place"], "names": f["names"]} for label, fn, f in ours]}
with open(os.path.join(tmp, "dump2.json"), "w") as fh:
json.dump(req, fh)
got = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump2.json")], tmp))
verdicts = []
for label, fn, f in ours:
d = got[label]
ok, detail = True, "%d instances" % len(d)
if "error" in d:
ok, detail = False, "lune: " + d["error"][:300]
else:
want = f["dump"]
if set(d) != set(want):
ok, detail = False, "instance paths differ: %s" % sorted(set(d) ^ set(want))[:5]
else:
for path in sorted(want):
a, b = want[path], d[path]
if a["class"] != b["class"]:
ok, detail = False, "%s: class %s, want %s" % (path, b["class"], a["class"])
break
diff = [k for k in a["props"] if a["props"][k] != b["props"].get(k)]
if diff:
k = diff[0]
ok, detail = False, "%s.%s: %s, want %s" % (path, k, json.dumps(b["props"].get(k))[:200], json.dumps(a["props"][k])[:200])
break
if a["attrs"] != b["attrs"] or sorted(a["tags"]) != sorted(b["tags"]):
ok, detail = False, "%s: attributes / tags differ" % path
break
verdicts.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("rbx_ours", verdicts)
+461
View File
@@ -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("<f", struct.pack("<f", x))[0]
def pk(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def crc(b):
return zlib.crc32(b)
def sbyte(v):
return v - 256 if v >= 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("<IHHf", idx, 0xFFFF if b["parent"] is None else b["parent"], b["lodParent"], b["culling"]) + pk("f", b["cf"])
return out, names
def subset_bytes(subsets):
out = b""
for s in subsets:
ids = s["bones"] + [0xFFFF] * (26 - len(s["bones"]))
out += struct.pack("<IIIII", s["facesBegin"], s["facesLength"], s["vertsBegin"], s["vertsLength"], len(s["bones"])) + pk("H", ids)
return out
# ---------------------------------------------------------------------------------------------------- writers
def write_v1(version, verts, faces):
scale = 2.0 if version == "1.00" else 1.0
parts = []
exp_verts = []
for f in faces:
for vi in f:
v = verts[vi]
fp = [c * scale for c in v["pos"]]
fv = 1 - v["uv"][1]
parts.append("[%r,%r,%r][%r,%r,%r][%r,%r,0]" % tuple(fp + v["nrm"] + [v["uv"][0], fv]))
exp_verts.append({"pos": [f32(c * (0.5 if version == "1.00" else 1)) for c in fp], "nrm": v["nrm"], "uv": [v["uv"][0], f32(1 - fv)], "tan": [0, 0, 0, 0], "col": [255] * 4})
data = ("version %s\n%d\n" % (version, len(faces)) + "".join(parts)).encode()
exp_faces = [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(len(faces))]
return data, expect_core(exp_verts, exp_faces, [0, len(faces)], False, tangents=False)
def write_v2(verts, faces, colors):
vs = 40 if colors else 36
data = b"version 2.00\n" + struct.pack("<HBBII", 12, vs, 12, len(verts), len(faces)) + b"".join(vbytes(v, vs) for v in verts) + fbytes(faces)
return data, expect_core(verts, faces, [0, len(faces)], colors)
def write_v3(version, verts, faces, lods):
data = (("version %s\n" % version).encode() + struct.pack("<HBBHHII", 16, 40, 12, 4, len(lods), len(verts), len(faces))
+ b"".join(vbytes(v, 40) for v in verts) + fbytes(faces) + pk("I", lods))
return data, expect_core(verts, faces, lods, True)
def write_v45(version, verts, faces, lods, bones, subsets, env, facs=None):
bb, names = bone_bytes(bones)
head = struct.pack("<HHIIHHIHBB", 32 if version == "5.00" else 24, 3, len(verts), len(faces), len(lods), len(bones), len(names), len(subsets), 1, 0)
if version == "5.00":
head += struct.pack("<II", 1 if facs else 0, len(facs or b""))
data = (("version %s\n" % version).encode() + head + b"".join(vbytes(v, 40) for v in verts) + (b"".join(env) if bones else b"")
+ fbytes(faces) + pk("I", lods) + bb + names + subset_bytes(subsets) + (facs or b""))
return data, expect_core(verts, faces, lods, True)
def chunk(name, version, body):
return name.ljust(8, b"\0") + struct.pack("<II", version, len(body)) + body
def write_v67(version, verts, faces, lods, bones, subsets, env, facs, hsr, draco=False):
if draco:
core = chunk(b"COREMESH", 2, struct.pack("<I", 16) + bytes(range(16)))
else:
core = chunk(b"COREMESH", 1, struct.pack("<I", len(verts)) + b"".join(vbytes(v, 40) for v in verts) + struct.pack("<I", len(faces)) + fbytes(faces))
lodc = chunk(b"LODS", 1, struct.pack("<HBI", 3, 1, len(lods)) + pk("I", lods))
bb, names = bone_bytes(bones)
skin = chunk(b"SKINNING", 1, struct.pack("<I", len(verts)) + b"".join(env) + struct.pack("<I", len(bones)) + bb + struct.pack("<I", len(names)) + names
+ struct.pack("<I", len(subsets)) + subset_bytes(subsets))
out = ("version %s\n" % version).encode() + core + lodc + skin
if facs:
out += chunk(b"FACS", 1, struct.pack("<I", len(facs)) + facs)
if hsr:
out += chunk(b"HSRAVIS", 1, struct.pack("<I", 10) + b"\x55\x01")
return out, expect_core(verts, faces, lods, True)
def skin_expect(exp, bones, joints, weights):
exp["joints"] = crc(b"".join(pk("H", j) for j in joints))
exp["weights"] = crc(b"".join(bytes(w) for w in weights))
exp["bones"] = [dict({"name": b["name"], "cf": b["cf"], "culling": b["culling"]}, **({"parent": b["parent"]} if b["parent"] is not None else {})) for b in bones]
return exp
# ---------------------------------------------------------------------------------------------------- reader (for our output)
def read_mesh(data):
line, rest = data.split(b"\n", 1)
version = line.decode().split()[1]
if version == "2.00":
hs, vs, fs, nv, nf = struct.unpack_from("<HBBII", rest, 0)
p = hs
nb = nsub = names_size = 0
lods = [0, nf]
elif version == "4.00":
hs, lod_type, nv, nf, nl, nb, names_size, nsub, hq, _ = struct.unpack_from("<HHIIHHIHBB", rest, 0)
vs, fs, p = 40, 12, hs
else:
raise ValueError("version " + version)
verts = []
for i in range(nv):
q = p + i * vs
v = struct.unpack_from("<8f", rest, q)
t = [sbyte(c) for c in rest[q + 32:q + 36]]
col = list(rest[q + 36:q + 40]) if vs >= 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("<IHHf", rest, p + 60 * i)
bones.append({"ni": ni, "parent": None if par == 0xFFFF else par, "cf": list(struct.unpack_from("<12f", rest, p + 60 * i + 12))})
p += 60 * nb
names = rest[p:p + names_size]
for b in bones:
b["name"] = names[b["ni"]:].split(b"\0", 1)[0].decode()
p += names_size
subsets = []
for i in range(nsub):
fb, fl, vb, vl, n = struct.unpack_from("<5I", rest, p + 72 * i)
ids = list(struct.unpack_from("<26H", rest, p + 72 * i + 20))[:n]
subsets.append({"facesBegin": fb, "facesLength": fl, "vertsBegin": vb, "vertsLength": vl, "bones": ids})
p += 72 * nsub
assert p == len(rest), "trailing bytes: %d of %d" % (p, len(rest))
return {"version": version, "verts": verts, "faces": faces, "lods": lods, "bones": bones, "subsets": subsets, "env": env}
def corners(m, lod=0):
"""the LOD's triangles as tuples of vertex values (position, uv) - comparable across vertex duplication"""
out = []
for f in m["faces"][m["lods"][lod]:m["lods"][lod + 1]]:
out.append(tuple(tuple(m["verts"][v]["pos"] + m["verts"][v]["uv"]) for v in f))
return out
def vertex_influences(m):
"""per vertex: { global bone: weight byte } through the subsets"""
infl = [None] * len(m["verts"])
for s in m["subsets"]:
assert len(s["bones"]) <= 26
for v in range(s["vertsBegin"], s["vertsBegin"] + s["vertsLength"]):
e = m["env"][v]
d = {}
for k in range(4):
if e[4 + k]:
d[s["bones"][e[k]]] = d.get(s["bones"][e[k]], 0) + e[4 + k]
assert sum(e[4:8]) == 255, "weights sum to %d" % sum(e[4:8])
infl[v] = d
return infl
def check_ours(src, out):
"""our re-encoding of a fixture (src: the original read as a v4-style record) -> 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("<HBBHHII", rest, 0)
head = struct.pack("<HHIIHHIHBB", 24, 0, nv, nf, nl, 0, 0, 0, 0, 0)
return read_mesh(b"version 4.00\n" + head + rest[hs:])
if version in ("4.00", "4.01", "5.00"):
hs = struct.unpack_from("<H", rest, 0)[0]
fields = list(struct.unpack_from("<HHIIHHIHBB", rest, 0))
fields[0] = 24
body = rest[hs:]
if version == "5.00":
body = body[:len(body) - struct.unpack_from("<I", rest, 28)[0]]
return read_mesh(b"version 4.00\n" + struct.pack("<HHIIHHIHBB", *fields) + body)
# 6.00 / 7.00: chunks to the 4.00 layout
p, parts = 0, {}
while p < len(rest):
name = rest[p:p + 8].rstrip(b"\0").decode()
cv, size = struct.unpack_from("<II", rest, p + 8)
parts[name] = rest[p + 16:p + 16 + size]
p += 16 + size
core = parts["COREMESH"]
nv = struct.unpack_from("<I", core, 0)[0]
verts = core[4:4 + 40 * nv]
nf = struct.unpack_from("<I", core, 4 + 40 * nv)[0]
faces = core[8 + 40 * nv:8 + 40 * nv + 12 * nf]
lc = parts["LODS"]
nl = struct.unpack_from("<I", lc, 3)[0]
lods = lc[7:7 + 4 * nl]
sk = parts["SKINNING"]
q = 4
env = sk[q:q + 8 * nv]
q += 8 * nv
nb = struct.unpack_from("<I", sk, q)[0]
q += 4
bones = sk[q:q + 60 * nb]
q += 60 * nb
ns = struct.unpack_from("<I", sk, q)[0]
names = sk[q + 4:q + 4 + ns]
q += 4 + ns
nsub = struct.unpack_from("<I", sk, q)[0]
subs = sk[q + 4:q + 4 + 72 * nsub]
head = struct.pack("<HHIIHHIHBB", 24, 3, nv, nf, nl, nb, ns, nsub, 1, 0)
return read_mesh(b"version 4.00\n" + head + verts + env + faces + lods + bones + names + subs)