ws-roblox: codecs/model/Rbx (RbxTree, typed values, CFrame rotation ids, binary property columns), model/rbxm (binary rbxm / rbxl read + write; LZ4 / Zstd / raw chunks; unknown chunks and property types round trip raw), model/rbxmx (XML rbxmx / rbxlx read + write); tests vs rojo 7.7 + lune 0.11 both ways

init.luau: KIND_CATEGORY gains rbxtree = model (F.save of an RbxTree finds the model category).
This commit is contained in:
4DBug committed 2026-10-31 14:19:46 -05:00
1 parent ba4b20e20b
commit 42727199d7
12 files changed
+3563

No files matched your search

+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
+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)