model/godot + data/tres + codecs/text/GodotVariant: Godot text scenes (.tscn / .escn) read + write against Godot 4's loader, .tres resources as data

docs/STYLE.md: the layout block lists codecs/text/GodotVariant (DOCS lint).
This commit is contained in:
4DBug committed 2026-11-01 19:25:15 -06:00
1 parent 9c02ebdee5
commit 8f26e32a71
24 files changed
+3649 -5

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
-- codecs/text/GodotVariant tests: the Variant text syntax (strings and escapes, StringName / NodePath, arrays,
-- dictionaries with non-string keys, constructors, packed arrays incl. base64 bytes, typed arrays, Object), format
-- round trips, int / float keeping, section documents, limits, fuzz. Godot's own files: tests/model/godot.luau.
local T = require("@tests/T")
local GodotVariant = require("@rosetta/codecs/text/GodotVariant")
local t = T.suite("godotvariant")
local v = assert(GodotVariant.value("{\"a\": [1, 2.5, \"x\\ny\", &\"sn\", ^\"np\"], 3: Vector3(1, -2, 3e-05), \"b\": PackedByteArray(\"AAEC\")}"))
t:check(v.a[2] == 2.5 and v.a[3] == "x\ny" and v.a[4].type == "StringName" and v.a[5].type == "NodePath", "array values")
t:check(v[3].type == "Vector3" and v[3].args[3] == 3e-05, "number keys, constructors")
local b = GodotVariant.bytes(v.b)
t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2, "base64 PackedByteArray")
local again = assert(GodotVariant.value(GodotVariant.format(v)))
t:eq(GodotVariant.format(again), GodotVariant.format(v), "format round trip")
local typed = assert(GodotVariant.value("Array[int]([1, 2])"))
t:check(typed.type == "Array[int]" and #typed.args[1] == 2, "typed array")
t:eq(GodotVariant.format(typed), "Array[int]([1, 2])", "typed array format")
local _, e1 = GodotVariant.value("Vector3(1, 2")
t:check(e1 ~= nil, "unterminated constructor")
local deep = string.rep("[", 300) .. string.rep("]", 300)
local _, e2 = GodotVariant.value(deep)
t:check(e2 and string.find(e2, "limit", 1, true), "depth limit")
do
local doc = assert(GodotVariant.parse("[gd_scene format=3]\n\n; comment\n[node name=\"A\" type=\"Node3D\"]\nmetadata/x = 1.0\n\"quoted key\" = [1, 2.0]\n"))
t:eq(#doc.sections, 2, "sections")
local n = doc.sections[2]
t:check(n.attrs.name == "A" and n.props["metadata/x"] == 1 and n.props["quoted key"][2] == 2, "attributes and properties")
local text = GodotVariant.encode(doc)
t:check(string.find(text, "metadata/x = 1.0", 1, true) ~= nil and string.find(text, "[1, 2.0]", 1, true) ~= nil, "floats keep their .0")
local o = assert(GodotVariant.value("Object(Resource,\"a\":1,\"b\":\"x\")"))
t:check(o.type == "Object" and o.class == "Resource" and o.args[1].b == "x", "Object")
t:eq(GodotVariant.number(0.1), "0.1", "shortest float")
t:eq(GodotVariant.format("a\"b\\c"), "\"a\\\"b\\\\c\"", "string escapes")
local u = assert(GodotVariant.value("\"\\u00e9\\ud83d\\ude00\""))
t:eq(u, "\u{e9}\u{1f600}", "unicode escapes and surrogate pairs")
end
local samples = {
"[gd_scene format=3]\n[node name=\"A\" type=\"Node3D\"]\ntransform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)\n",
"[gd_resource type=\"X\" format=3]\n[resource]\nd = {\n\"k\": [1, &\"s\", NodePath(\"a\"), PackedFloat32Array(1, 2)]\n}\n",
}
t:fuzz("parse", function(b: buffer)
return GodotVariant.parse(buffer.tostring(b))
end, samples)
t:done()
+100
View File
@@ -0,0 +1,100 @@
-- data/tres tests: Godot text resources against Godot 4's loader (every stored property, var_to_str text parsed back
-- by codecs/text/GodotVariant), int / float keeping, our re-encoded files loaded by Godot with the same properties;
-- errors; fuzz. Fixtures: tools/fixtures/godot.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Tres = require("@rosetta/data/tres")
local GodotVariant = require("@rosetta/codecs/text/GodotVariant")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/godot")
local Ours = require("@tests/gen/godot_ours")
local t = T.suite("tres")
local samples = {}
t:eq(Tres.name, "tres", "name")
t:eq(Tres.category, "data", "category")
t:check(Tres.caps.decode and Tres.caps.encode, "caps")
local function same(a: any, b: any): boolean
if type(a) == "number" and type(b) == "number" then
return a == b or math.abs(a - b) <= 1e-6 * math.max(1, math.abs(b)) or (a ~= a and b ~= b)
elseif type(a) == "table" and type(b) == "table" then
if GodotVariant.isCtor(a) ~= GodotVariant.isCtor(b) or (GodotVariant.isCtor(a) and a.type ~= b.type) then
return false
end
if GodotVariant.isCtor(a) and a.type == "Object" then
return a.class == b.class -- Godot lists every stored property of the object
end
local x, y = if GodotVariant.isCtor(a) then a.args else a, if GodotVariant.isCtor(b) then b.args else b
for k, v in x do
if not same(v, y[k]) then
return false
end
end
for k in y do
if x[k] == nil then
return false
end
end
return true
end
return a == b
end
for _, c in Fx.tres do
local v, err = Tres.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(v, c.name .. ": decode: " .. tostring(err))
t:eq(Tres.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
table.insert(samples, c.data)
local g = c.godot
t:check(g.ok, c.name .. ": Godot loads it")
if v and g.ok then
local n = 0
for k, text in g.props do
local mine = v.properties[k]
if mine ~= nil and not (GodotVariant.isCtor(mine) and (mine.type == "SubResource" or mine.type == "ExtResource")) then
local theirs, perr = GodotVariant.value(text)
t:check(perr == nil and same(mine, theirs), c.name .. ": " .. k .. " = Godot's " .. text)
n += 1
end
end
t:note("%s: %d properties against Godot", c.name, n)
local again = assert(Tres.decode(Bytes.reader(assert(Tres.encode(v)))))
t:eq(GodotVariant.format(again.properties), GodotVariant.format(v.properties), c.name .. ": round trip")
end
local ours
for _, o in Ours do
if o.name == "ours_" .. c.name then
ours = o
end
end
t:check(ours and ours.godot.ok, c.name .. ": Godot loads our .tres")
if ours and ours.godot.ok and g.ok then
for k, text in g.props do
t:eq(ours.godot.props[k], text, c.name .. ": our .tres in Godot: " .. k)
end
end
end
local data = assert(Tres.decode(Bytes.reader(buffer.fromstring(Fx.tres[2].data))))
t:check(data.type == "Resource" and data.scriptClass == "Stats" and data.properties.hp == 12, "tres header and values")
t:eq(data.subresources[1].properties.point_count, 2, "sub-resource properties")
t:eq(data.external[1].path, "res://stats.gd", "external resources")
local _, e = Tres.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].data)))
t:check(e and e.code == Err.UNSUPPORTED, "a scene is not a resource")
t:eq(F.detect(Fx.tres[1].data), "tres", "F.detect tres")
do
local v = assert(Tres.decode(Bytes.reader(buffer.fromstring("[gd_resource type=\"Curve\" format=3]\n[resource]\n_data = [Vector2(0, 0), 0.0, 1.0, 0, 0]\nx = 2.0\n"))))
local s = buffer.tostring(assert(Tres.encode(v)))
t:check(string.find(s, "0.0, 1.0, 0, 0", 1, true) ~= nil and string.find(s, "x = 2.0", 1, true) ~= nil, "integral floats stay floats")
local _, e = Tres.decode(Bytes.reader(buffer.fromstring("[gd_resource type=\"X\" format=3]\n[resource]\nx = [1, 2\n")))
t:check(e ~= nil, "truncated array")
local _, e2 = Tres.encode({} :: any)
t:check(e2 and e2.code == Err.ARG, "encode arg")
end
t:fuzz("decode", function(b: buffer)
return Tres.decode(Bytes.reader(b))
end, samples, { mutations = 80, garbage = 20 })
t:done()
+356
View File
@@ -0,0 +1,356 @@
-- model/godot tests: scenes saved by Godot 4 against Godot's own loader (node transforms, surface arrays, materials,
-- cameras, lights, primitive meshes, instanced scenes, 2D nodes); a format-2 .escn; our .tscn writer's output loaded by
-- Godot and compared with the original; codecs/text/GodotVariant values; errors; fuzz. Fixtures: tools/fixtures/godot.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Godot = require("@rosetta/model/godot")
local GodotVariant = require("@rosetta/codecs/text/GodotVariant")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/godot")
local Ours = require("@tests/gen/godot_ours")
local t = T.suite("godot")
local S = Types.Scene
local function decode(s: string | buffer, files: any?, opts: any?): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
local o = opts or {}
o.resolve = function(p: string): buffer?
local f = files and files[p]
return if f then buffer.fromstring(f) else nil
end
return Godot.decode(Bytes.reader(b), o)
end
t:eq(Godot.name, "godot", "name")
t:eq(Godot.category, "model", "category")
t:check(Godot.caps.decode and Godot.caps.encode, "caps")
local function list(acc: any): { number }
if not acc then
return {}
end
local rd = S.reader(acc) :: any
local out = {}
for i = 0, acc.count - 1 do
for c = 0, acc.components - 1 do
table.insert(out, rd(i, c))
end
end
return out
end
-- our Scene in the dump's shape (tools/fixtures/_godot_dump.gd): paths, local transforms as basis rows + origin,
-- surface arrays with Godot's clockwise indices
local function asDump(scene: any): { [string]: any }
local out = {}
local function visit(i: number, path: string)
local n = scene.nodes[i]
local g = n.extras and n.extras.godot or {}
local e: any = { path = path, class = g.type }
local m = S.nodeMatrix(n)
e.xf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }
e.visible = g.visible ~= false
if n.mesh then
local surfs = {}
for _, p in scene.meshes[n.mesh].primitives do
local idx = list(p.indices)
for k = 1, #idx - 2, 3 do
idx[k + 1], idx[k + 2] = idx[k + 2], idx[k + 1]
end
local mat = p.material and scene.materials[p.material]
local md = nil
if mat then
local x = mat.extras.godot
local tex = mat.baseColorTexture and scene.textures[mat.baseColorTexture.texture]
md = {
albedo = x.albedo,
metallic = mat.metallic,
roughness = mat.roughness,
emission = if x.emission then { x.emission[1], x.emission[2], x.emission[3] } else nil,
texture = if tex then "res://" .. tex.uri else nil,
transparency = if mat.alphaMode == "blend" then 1 else 0,
cull = if mat.doubleSided then 2 else 0,
}
end
local colors = {}
for k, v in list(p.attributes.COLOR_0) do
colors[k] = v
end
table.insert(surfs, {
vertex = list(p.attributes.POSITION),
normal = list(p.attributes.NORMAL),
tangent = list(p.attributes.TANGENT),
uv = list(p.attributes.TEXCOORD_0),
uv2 = list(p.attributes.TEXCOORD_1),
color = colors,
index = idx,
material = md,
})
end
e.surfaces = surfs
end
if n.camera then
local c = scene.cameras[n.camera]
e.camera = if c.type == "orthographic" then { projection = 1, size = c.ymag * 2, near = c.znear, far = c.zfar } else { projection = 0, fov = math.deg(c.yfov), near = c.znear, far = c.zfar }
end
if n.light then
local l = scene.lights[n.light]
local raw = g.lightColor or { 1, 1, 1 }
e.light = { color = { raw[1], raw[2], raw[3] }, energy = l.intensity, range = l.range, angle = if l.outerCone then math.deg(l.outerCone) else nil }
end
out[path] = e
for _, c in n.children do
local cn = scene.nodes[c].name
visit(c, if path == "." then cn else path .. "/" .. cn)
end
end
for _, r in scene.roots do
visit(r, ".")
end
return out
end
local function close(a: { number }?, b: { number }?, eps: number): (boolean, string)
a, b = a or {}, b or {}
if #a ~= #b then
return false, "length " .. #a .. " vs " .. #b
end
for i = 1, #a do
if math.abs(a[i] - b[i]) > eps * math.max(1, math.abs(b[i])) then
return false, "[" .. i .. "] " .. a[i] .. " vs " .. b[i]
end
end
return true, ""
end
-- the 3D facts of a dump node `got` against the reference `want`
local function compare(got: any, want: any, label: string, eps: number)
if want.xf then
local ok, why = close(got.xf, want.xf, 1e-5)
t:check(ok, label .. ": transform " .. why)
t:eq(got.visible, want.visible, label .. ": visible")
end
if want.surfaces then
t:eq(#(got.surfaces or {}), #want.surfaces, label .. ": surfaces")
for k, ws in want.surfaces do
local gs = (got.surfaces or {})[k]
if gs then
for _, f in { "vertex", "uv", "uv2" } do
local ok, why = close(gs[f], ws[f], 1e-5)
t:check(ok, label .. ": surface " .. k .. " " .. f .. " " .. why)
end
for _, f in { "normal", "tangent" } do
local ok, why = close(gs[f], ws[f], eps)
t:check(ok, label .. ": surface " .. k .. " " .. f .. " " .. why)
end
local ok, why = close(gs.color, ws.color, 1 / 255 + 1e-6)
t:check(ok, label .. ": surface " .. k .. " color " .. why)
local wi = ws.index
if #wi == 0 then
for i = 0, #ws.vertex // 3 - 1 do
wi[i + 1] = i
end
end
local gi = gs.index
if #gi == 0 then
for i = 0, #gs.vertex // 3 - 1 do
gi[i + 1] = i
end
end
local iok, iwhy = close(gi, wi, 0)
t:check(iok, label .. ": surface " .. k .. " index " .. iwhy)
local wm, gm = ws.material, gs.material
if wm then
t:check(gm ~= nil, label .. ": surface " .. k .. " material")
if gm then
local aok, awhy = close(gm.albedo, wm.albedo, 1e-5)
t:check(aok, label .. ": albedo " .. awhy)
t:check(math.abs(gm.metallic - wm.metallic) < 1e-5 and math.abs(gm.roughness - wm.roughness) < 1e-5, label .. ": metallic / roughness")
local eok, ewhy = close(gm.emission, wm.emission, 1e-5)
t:check(eok, label .. ": emission " .. ewhy)
t:eq(gm.texture, wm.texture, label .. ": albedo texture")
t:eq(gm.transparency, wm.transparency, label .. ": transparency")
t:eq(gm.cull, wm.cull, label .. ": cull")
end
end
end
end
end
if want.camera then
local gc, wc = got.camera or {}, want.camera
t:eq(gc.projection, wc.projection, label .. ": projection")
if wc.projection == 1 then
t:check(math.abs(gc.size - wc.size) < 1e-5, label .. ": ortho size")
else
t:check(math.abs(gc.fov - wc.fov) < 1e-5, label .. ": fov")
end
t:check(math.abs(gc.near - wc.near) < 1e-6 and math.abs(gc.far - wc.far) < 1e-3, label .. ": near / far")
end
if want.light then
local gl, wl = got.light or {}, want.light
local ok, why = close(gl.color, wl.color, 1e-5)
t:check(ok, label .. ": light colour " .. why)
t:check(math.abs((gl.energy or -1) - wl.energy) < 1e-5, label .. ": light energy")
if wl.range then
t:check(math.abs((gl.range or -1) - wl.range) < 1e-5, label .. ": light range")
end
if wl.angle then
t:check(math.abs((gl.angle or -1) - wl.angle) < 1e-4, label .. ": spot angle")
end
end
end
local scenes = {}
local samples = {}
for _, c in Fx.cases do
local scene, err = decode(c.data, c.files)
t:check(scene, c.name .. ": decode: " .. tostring(err))
t:eq(Godot.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
scenes[c.name] = scene
table.insert(samples, c.data)
if scene and c.dump then
t:check(c.dump.ok, c.name .. ": Godot loads it")
local mine = asDump(scene)
local n = 0
for _, want in c.dump.nodes do
local got = mine[want.path]
t:check(got, c.name .. ": node " .. want.path)
if got then
t:eq(got.class, want.class, c.name .. ": " .. want.path .. " class")
compare(got, want, c.name .. ": " .. want.path, 3e-4)
n += 1
end
end
t:note("%s: %d nodes against Godot", c.name, n)
end
end
-- Godot reads what we write
for _, o in Ours do
if not o.dump then
continue
end
t:check(o.dump.ok, o.name .. ": Godot loads our .tscn")
local base = string.match(o.name, "^ours_(.*)%.tscn$")
local ref
for _, c in Fx.cases do
if string.gsub(c.name, "%.%w+$", "") == base then
ref = c
end
end
if ref and ref.dump and o.dump.ok then
local byPath = {}
for _, nd in o.dump.nodes do
byPath[nd.path] = nd
end
local n = 0
for _, want in ref.dump.nodes do
if want.xf then
local got = byPath[want.path]
t:check(got, o.name .. ": node " .. want.path)
if got then
compare(got, want, o.name .. ": " .. want.path, 5e-4)
n += 1
end
end
end
t:note("%s: %d 3D nodes after our writer", o.name, n)
elseif o.dump.ok and base == "hand" then
-- the escn has no Godot reference: compare Godot's reading of ours with our reading of the escn
local mine = asDump(scenes["hand.escn"])
for _, got in o.dump.nodes do
local want = mine[got.path]
t:check(want, o.name .. ": node " .. got.path)
if want and want.xf then
compare(got, want, o.name .. ": " .. got.path, 5e-4)
end
end
end
end
-- details
do
local s = scenes["main.tscn"]
t:eq(s.meta.source.version, 4, "header format")
t:eq(s.meta.up, "y", "up axis")
local shape
for _, n in s.nodes do
if n.name == "Shape" then
shape = n
end
end
local m = s.materials[s.meshes[shape.mesh].primitives[1].material]
t:eq(m.name, "Painted", "material name")
t:check(math.abs(m.baseColor[1] - ((0.8 + 0.055) / 1.055) ^ 2.4) < 1e-6, "albedo sRGB -> linear")
t:eq(m.extensions.KHR_materials_emissive_strength.emissiveStrength, 2, "emission energy")
t:eq(s.textures[m.baseColorTexture.texture].uri, "checker.png", "texture path")
t:check(s.textures[m.baseColorTexture.texture].data ~= nil, "texture bytes through resolve")
local hud
for _, n in s.nodes do
if n.name == "Hud" then
hud = n
end
end
t:check(hud.extras.godot.is2D and hud.extras.godot.properties.rotation == 0.5, "2D node kept in extras")
local pos = hud.extras.godot.properties.position
t:check(GodotVariant.isCtor(pos) and pos.type == "Vector2" and pos.args[2] == 20, "2D position as a Vector2")
-- without resolve: the instance stays an empty node
local bare = assert(decode(Fx.cases[2].data))
local inst
for _, n in bare.nodes do
if n.name == "PartInstance" then
inst = n
end
end
t:check(inst and #inst.children == 0, "unresolved instance")
local e = scenes["hand.escn"]
t:eq(e.meta.source.version, 2, "escn format 2")
t:eq(#e.cameras, 1, "escn camera")
t:check(math.abs(math.deg(e.cameras[1].yfov) - 60) < 1e-9 and e.cameras[1].zfar == 250, "escn camera fov / far")
t:eq(e.lights[1].range, 9, "escn light range")
local cube = e.nodes[2]
local p = e.meshes[cube.mesh].primitives[1]
t:eq(p.indices.count, 6, "escn arrays surface")
t:check(e.materials[1].doubleSided and e.materials[1].metallic == 0.5, "SpatialMaterial")
local strip = e.meshes[e.nodes[3].mesh].primitives[1]
t:check(strip.mode == "triangles" and strip.indices.count == 6 and strip.attributes.COLOR_0 ~= nil, "escn triangle strip -> triangles")
t:check(cube.matrix[14] == 3 and cube.matrix[7] == 1, "Transform (format 2) rows")
end
-- any Scene: through F.save
do
local s = S.new()
local P = S.accessor(nil, "f32", 3, 3)
for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do
buffer.writef32(P.data, (i - 1) * 4, v)
end
s.meshes[1] = { primitives = { { attributes = { POSITION = P }, mode = "triangles" } } }
s.nodes = { { name = "a/b", children = {}, mesh = 1, translation = { 1, 2, 3 } }, { name = "a/b", children = {} } }
s.roots = { 1, 2 }
local out = assert(F.save(s, nil, { format = "godot" }))
local back = assert(decode(out))
t:eq(back.nodes[1].name, "Root", "two roots under Root")
t:check(back.nodes[2].name == "a_b" and back.nodes[3].name == "a_b2", "names sanitised and unique")
t:eq(back.nodes[2].matrix[14], 2, "transform")
t:eq(back.meshes[1].primitives[1].indices.count, 3, "triangle")
t:eq(F.detect(out), "godot", "F.detect")
end
do
local _, e = decode("[gd_resource type=\"Resource\" format=3]\n[resource]\nx = 1\n")
t:check(e and e.code == Err.UNSUPPORTED, "a .tres is not a scene")
local _, e2 = decode("[gd_scene format=3]\n[node name=\"A\" parent=\"missing\"]\n")
t:check(e2 and e2.code == Err.CORRUPT, "missing parent")
local _, e3 = decode("[gd_scene format=3]\nx = Vector3(1,\n")
t:check(e3 ~= nil, "truncated value")
local _, e4 = Godot.encode({} :: any)
t:check(e4 and e4.code == Err.ARG, "encode arg")
end
t:fuzz("decode", function(b: buffer)
return Godot.decode(Bytes.reader(b))
end, samples, { mutations = 80, garbage = 20 })
t:done()