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:
1 parent
9c02ebdee5
commit
8f26e32a71
24 files changed
+3649
-5
No files matched your search
@@ -0,0 +1,80 @@
|
||||
# tools/fixtures/_godot_dump.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- <scene.tscn>...): loads
|
||||
# each scene with Godot's own loader and prints one JSON line per scene: every node (path, class, global transform as
|
||||
# 12 numbers: basis rows then origin, visibility), every MeshInstance3D's surfaces (mesh.surface_get_arrays: vertex,
|
||||
# normal, tangent, uv, uv2, color, index; the active material's albedo / metallic / roughness / emission / texture
|
||||
# path / transparency / cull mode), cameras and lights.
|
||||
extends SceneTree
|
||||
|
||||
func xf(t):
|
||||
var b = t.basis
|
||||
return [b.x.x, b.y.x, b.z.x, b.x.y, b.y.y, b.z.y, b.x.z, b.y.z, b.z.z, t.origin.x, t.origin.y, t.origin.z]
|
||||
|
||||
func flat(a):
|
||||
var out = []
|
||||
if a == null:
|
||||
return out
|
||||
for v in a:
|
||||
if v is Vector3:
|
||||
out.append_array([v.x, v.y, v.z])
|
||||
elif v is Vector2:
|
||||
out.append_array([v.x, v.y])
|
||||
elif v is Color:
|
||||
out.append_array([v.r, v.g, v.b, v.a])
|
||||
else:
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
func mat(m):
|
||||
if m == null:
|
||||
return null
|
||||
var d = {"class": m.get_class(), "name": m.resource_name}
|
||||
if m is BaseMaterial3D:
|
||||
d["albedo"] = [m.albedo_color.r, m.albedo_color.g, m.albedo_color.b, m.albedo_color.a]
|
||||
d["metallic"] = m.metallic
|
||||
d["roughness"] = m.roughness
|
||||
d["emission"] = [m.emission.r, m.emission.g, m.emission.b] if m.emission_enabled else null
|
||||
d["emission_energy"] = m.emission_energy_multiplier
|
||||
d["texture"] = m.albedo_texture.resource_path if m.albedo_texture else null
|
||||
d["transparency"] = m.transparency
|
||||
d["cull"] = m.cull_mode
|
||||
return d
|
||||
|
||||
func walk(n, root, out):
|
||||
var e = {"path": str(root.get_path_to(n)), "class": n.get_class()}
|
||||
if n is Node3D:
|
||||
e["xf"] = xf(n.transform)
|
||||
e["visible"] = n.visible
|
||||
if n is MeshInstance3D and n.mesh:
|
||||
var surfs = []
|
||||
for s in n.mesh.get_surface_count():
|
||||
var a = n.mesh.surface_get_arrays(s)
|
||||
surfs.append({
|
||||
"vertex": flat(a[Mesh.ARRAY_VERTEX]), "normal": flat(a[Mesh.ARRAY_NORMAL]), "tangent": flat(a[Mesh.ARRAY_TANGENT]),
|
||||
"uv": flat(a[Mesh.ARRAY_TEX_UV]), "uv2": flat(a[Mesh.ARRAY_TEX_UV2]), "color": flat(a[Mesh.ARRAY_COLOR]),
|
||||
"index": flat(a[Mesh.ARRAY_INDEX]), "material": mat(n.get_active_material(s)),
|
||||
})
|
||||
e["surfaces"] = surfs
|
||||
e["mesh_class"] = n.mesh.get_class()
|
||||
if n is Camera3D:
|
||||
e["camera"] = {"fov": n.fov, "near": n.near, "far": n.far, "projection": n.projection, "size": n.size}
|
||||
if n is Light3D:
|
||||
var l = {"color": [n.light_color.r, n.light_color.g, n.light_color.b], "energy": n.light_energy}
|
||||
if n is OmniLight3D:
|
||||
l["range"] = n.omni_range
|
||||
if n is SpotLight3D:
|
||||
l["range"] = n.spot_range
|
||||
l["angle"] = n.spot_angle
|
||||
e["light"] = l
|
||||
out.append(e)
|
||||
for c in n.get_children():
|
||||
walk(c, root, out)
|
||||
|
||||
func _init():
|
||||
for path in OS.get_cmdline_user_args():
|
||||
var ps = load(path)
|
||||
var res = {"file": path, "ok": ps != null, "nodes": []}
|
||||
if ps:
|
||||
var root = ps.instantiate()
|
||||
walk(root, root, res["nodes"])
|
||||
print("JSON:" + JSON.stringify(res))
|
||||
quit()
|
||||
@@ -0,0 +1,45 @@
|
||||
-- tools/fixtures/_godot_encode: run by tools/fixtures/godot.py (luau CLI, repo root): decodes every Godot scene case
|
||||
-- (files through resolve) and writes it with our .tscn writer, printing "ours_<name>.tscn\t<hex>" lines for Godot to
|
||||
-- load, and every .tres case through data/tres ("ours_<name>.tres").
|
||||
local Godot = require("@rosetta/model/godot")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/godot")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
return (string.gsub(s, ".", function(c: string): string
|
||||
return HEX[string.byte(c)]
|
||||
end))
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local scene, err = Godot.decode(Bytes.reader(buffer.fromstring(c.data)), {
|
||||
resolve = function(p: string): buffer?
|
||||
local f = c.files[p]
|
||||
return if f then buffer.fromstring(f) else nil
|
||||
end,
|
||||
})
|
||||
if scene then
|
||||
local out = Godot.encode(scene)
|
||||
if out then
|
||||
local base = string.gsub(c.name, "%.%w+$", "")
|
||||
print("ours_" .. base .. ".tscn\t" .. hex(buffer.tostring(out)))
|
||||
end
|
||||
else
|
||||
print("decode failed " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
local Tres = require("@rosetta/data/tres")
|
||||
for _, c in Fx.tres do
|
||||
local v = Tres.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if v then
|
||||
local out = Tres.encode(v)
|
||||
if out then
|
||||
print("ours_" .. c.name .. "\t" .. hex(buffer.tostring(out)))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
# tools/fixtures/_godot_make.gd: run by tools/fixtures/godot.py (godot --headless -s): builds test scenes in Godot and
|
||||
# saves them as .tscn (Godot's own writer) into the project folder: meshes from SurfaceTool (normals, tangents, UVs,
|
||||
# UV2, colours, two surfaces, indexed and not), materials (sRGB albedo, metallic, roughness, emission, a texture,
|
||||
# transparency, culling), nested transforms, cameras, lights, primitive meshes, a Node2D subtree, a material override
|
||||
# and an instanced sub-scene.
|
||||
extends SceneTree
|
||||
|
||||
func tri_mesh(mat_a, mat_b):
|
||||
var st = SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
var pts = [Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(1, 1, 0.5)]
|
||||
var uvs = [Vector2(0, 0), Vector2(1, 0), Vector2(0, 1), Vector2(1, 1)]
|
||||
for i in [0, 1, 2, 2, 1, 3]:
|
||||
st.set_normal(Vector3(0.1 * i, 0.2, 1).normalized())
|
||||
st.set_tangent(Plane(Vector3(1, 0, -0.1 * i).normalized(), -1.0 if i == 3 else 1.0))
|
||||
st.set_uv(uvs[i])
|
||||
st.set_uv2(uvs[i] * 0.5)
|
||||
st.set_color(Color(i / 3.0, 1.0 - i / 3.0, 0.25, 1.0))
|
||||
st.add_vertex(pts[i])
|
||||
st.index()
|
||||
st.set_material(mat_a)
|
||||
var mesh = st.commit()
|
||||
var st2 = SurfaceTool.new()
|
||||
st2.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
for p in [Vector3(0, 0, 1), Vector3(0, 2, 1), Vector3(2, 0, 1)]:
|
||||
st2.set_normal(Vector3(0, 0, -1))
|
||||
st2.add_vertex(p)
|
||||
st2.set_material(mat_b)
|
||||
st2.commit(mesh)
|
||||
return mesh
|
||||
|
||||
func scene_main():
|
||||
var root = Node3D.new()
|
||||
root.name = "Root"
|
||||
var tex = load("res://checker.png")
|
||||
var a = StandardMaterial3D.new()
|
||||
a.resource_name = "Painted"
|
||||
a.albedo_color = Color(0.8, 0.4, 0.2, 1.0)
|
||||
a.metallic = 0.25
|
||||
a.roughness = 0.6
|
||||
a.albedo_texture = tex
|
||||
a.emission_enabled = true
|
||||
a.emission = Color(0.1, 0.2, 0.3)
|
||||
a.emission_energy_multiplier = 2.0
|
||||
var b = StandardMaterial3D.new()
|
||||
b.resource_name = "Glass"
|
||||
b.albedo_color = Color(0.2, 0.6, 1.0, 0.5)
|
||||
b.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
||||
b.cull_mode = BaseMaterial3D.CULL_DISABLED
|
||||
var pivot = Node3D.new()
|
||||
pivot.name = "Pivot"
|
||||
pivot.transform = Transform3D(Basis.from_euler(Vector3(0.3, -0.7, 0.2)), Vector3(1, 2, 3))
|
||||
root.add_child(pivot); pivot.owner = root
|
||||
var mi = MeshInstance3D.new()
|
||||
mi.name = "Shape"
|
||||
mi.mesh = tri_mesh(a, b)
|
||||
mi.transform = Transform3D(Basis(Vector3(0, 0, 1), 0.4).scaled(Vector3(2, 1, 0.5)), Vector3(-1, 0.5, 4))
|
||||
pivot.add_child(mi); mi.owner = root
|
||||
var over = MeshInstance3D.new()
|
||||
over.name = "Override"
|
||||
over.mesh = mi.mesh
|
||||
var red = StandardMaterial3D.new()
|
||||
red.albedo_color = Color(1, 0, 0)
|
||||
over.set_surface_override_material(0, red)
|
||||
over.position = Vector3(5, 0, 0)
|
||||
root.add_child(over); over.owner = root
|
||||
var cam = Camera3D.new(); cam.name = "Cam"; cam.fov = 50; cam.near = 0.1; cam.far = 300
|
||||
cam.transform = Transform3D(Basis.looking_at(Vector3(0, -0.5, -1)), Vector3(0, 3, 8))
|
||||
root.add_child(cam); cam.owner = root
|
||||
var ortho = Camera3D.new(); ortho.name = "Ortho"; ortho.projection = Camera3D.PROJECTION_ORTHOGONAL; ortho.size = 6
|
||||
root.add_child(ortho); ortho.owner = root
|
||||
var omni = OmniLight3D.new(); omni.name = "Omni"; omni.light_color = Color(1, 0.5, 0.25); omni.light_energy = 2; omni.omni_range = 7
|
||||
omni.position = Vector3(0, 4, 0)
|
||||
root.add_child(omni); omni.owner = root
|
||||
var spot = SpotLight3D.new(); spot.name = "Spot"; spot.spot_angle = 30; spot.spot_range = 12; spot.light_energy = 3
|
||||
spot.rotation = Vector3(-1.2, 0.3, 0)
|
||||
root.add_child(spot); spot.owner = root
|
||||
var sun = DirectionalLight3D.new(); sun.name = "Sun"; sun.light_energy = 0.8
|
||||
sun.rotation_degrees = Vector3(-45, 30, 0)
|
||||
root.add_child(sun); sun.owner = root
|
||||
var prims = Node3D.new(); prims.name = "Prims"; prims.position = Vector3(0, -3, 0)
|
||||
root.add_child(prims); prims.owner = root
|
||||
var shapes = [BoxMesh.new(), PlaneMesh.new(), QuadMesh.new(), SphereMesh.new(), CylinderMesh.new()]
|
||||
shapes[0].size = Vector3(2, 1, 3)
|
||||
shapes[1].size = Vector2(4, 2)
|
||||
shapes[3].radius = 0.75; shapes[3].height = 1.5
|
||||
shapes[4].top_radius = 0.25; shapes[4].height = 3
|
||||
for i in shapes.size():
|
||||
var p = MeshInstance3D.new(); p.name = "Prim%d" % i; p.mesh = shapes[i]; p.position = Vector3(i * 3, 0, 0)
|
||||
prims.add_child(p); p.owner = root
|
||||
var ui = Node2D.new(); ui.name = "Hud"; ui.position = Vector2(10, 20); ui.rotation = 0.5
|
||||
root.add_child(ui); ui.owner = root
|
||||
var spr = Sprite2D.new(); spr.name = "Icon"; spr.texture = tex; spr.position = Vector2(3, 4)
|
||||
ui.add_child(spr); spr.owner = root
|
||||
var hidden = Node3D.new(); hidden.name = "Hidden"; hidden.visible = false; hidden.scale = Vector3(1, 2, 3)
|
||||
root.add_child(hidden); hidden.owner = root
|
||||
var sub = load("res://part.tscn").instantiate()
|
||||
sub.name = "PartInstance"
|
||||
sub.position = Vector3(0, 0, -6)
|
||||
root.add_child(sub); sub.owner = root
|
||||
return root
|
||||
|
||||
func scene_part():
|
||||
var root = Node3D.new(); root.name = "Part"
|
||||
var m = MeshInstance3D.new(); m.name = "Cube"; var box = BoxMesh.new(); box.size = Vector3(0.5, 0.5, 0.5); m.mesh = box
|
||||
m.position = Vector3(0, 1, 0)
|
||||
root.add_child(m); m.owner = root
|
||||
return root
|
||||
|
||||
func save(root, path):
|
||||
var ps = PackedScene.new()
|
||||
ps.pack(root)
|
||||
var err = ResourceSaver.save(ps, path)
|
||||
if err != OK:
|
||||
printerr("save failed ", path, " ", err)
|
||||
|
||||
func _init():
|
||||
save(scene_part(), "res://part.tscn")
|
||||
save(scene_main(), "res://main.tscn")
|
||||
quit()
|
||||
@@ -0,0 +1,15 @@
|
||||
# tools/fixtures/_godot_tres.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- <file.tres>...): loads each
|
||||
# resource with Godot's loader and prints one JSON line: its class and every stored property as var_to_str text.
|
||||
extends SceneTree
|
||||
|
||||
func _init():
|
||||
for path in OS.get_cmdline_user_args():
|
||||
var r = load(path)
|
||||
var res = {"file": path, "ok": r != null, "props": {}}
|
||||
if r:
|
||||
res["class"] = r.get_class()
|
||||
for p in r.get_property_list():
|
||||
if p.usage & PROPERTY_USAGE_STORAGE and p.name != "script" and p.name != "resource_path":
|
||||
res["props"][p.name] = var_to_str(r.get(p.name))
|
||||
print("JSON:" + JSON.stringify(res))
|
||||
quit()
|
||||
@@ -1,9 +1,43 @@
|
||||
# Docs inputs for the engine / level-editor sections of the scene, tile map, archive and data pages (tools/fixtures.py,
|
||||
# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py),
|
||||
# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo).
|
||||
# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo), a small Godot scene and resource.
|
||||
# tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } }
|
||||
import importlib.util, os
|
||||
|
||||
TSCN = """[gd_scene load_steps=3 format=3]
|
||||
|
||||
[sub_resource type="StandardMaterial3D" id="Mat_1"]
|
||||
albedo_color = Color(1, 0.5, 0, 1)
|
||||
metallic = 0.5
|
||||
|
||||
[sub_resource type="BoxMesh" id="Box_1"]
|
||||
material = SubResource("Mat_1")
|
||||
size = Vector3(1, 2, 1)
|
||||
|
||||
[node name="World" type="Node3D"]
|
||||
|
||||
[node name="Box" type="MeshInstance3D" parent="."]
|
||||
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0, 0)
|
||||
mesh = SubResource("Box_1")
|
||||
|
||||
[node name="Camera" type="Camera3D" parent="."]
|
||||
fov = 60.0
|
||||
|
||||
[node name="Hud" type="Node2D" parent="."]
|
||||
position = Vector2(10, 20)
|
||||
"""
|
||||
|
||||
TRES = """[gd_resource type="StandardMaterial3D" load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Texture2D" path="res://brick.png" id="1"]
|
||||
|
||||
[resource]
|
||||
albedo_color = Color(0.8, 0.4, 0.2, 1)
|
||||
albedo_texture = ExtResource("1")
|
||||
metallic = 0.25
|
||||
roughness = 1.0
|
||||
"""
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py", "tests/fixtures/ogmo"]
|
||||
|
||||
|
||||
@@ -20,5 +54,7 @@ def generate(ctx):
|
||||
files["stamps.ldtk"] = open(os.path.join(mod(ctx, "ldtk").samples_dir(ctx), "AutoLayers_2_stamps.ldtk"), "rb").read()
|
||||
for f in ("turnBasedRPG.ogmo", "room-001.json"):
|
||||
files[f] = ctx.read("tests/fixtures/ogmo/" + f)
|
||||
vars = {"aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"}
|
||||
files["world.tscn"] = TSCN.encode()
|
||||
files["brick.tres"] = TRES.encode()
|
||||
vars = {"tscnText": "world.tscn", "tresText": "brick.tres", "aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"}
|
||||
check.emit_inputs(ctx, files, vars)
|
||||
@@ -0,0 +1,224 @@
|
||||
# Godot fixtures (tools/fixtures.py), with Godot 4 itself (nixpkgs#godot_4, headless) as the reference:
|
||||
# tools/fixtures/_godot_make.gd builds scenes in Godot and saves them with Godot's .tscn writer;
|
||||
# tools/fixtures/_godot_dump.gd loads scenes with Godot's loader and prints every node, mesh surface (the arrays
|
||||
# Godot decoded), material, camera and light as JSON. A hand-written format-2 .escn (the Blender exporter's layout:
|
||||
# "arrays" surfaces, SpatialMaterial, Godot 3 node types) and .tres resources are added. Then our writer's .tscn output
|
||||
# (tools/fixtures/_godot_encode.luau) is loaded and dumped by Godot. Resources are loaded by Godot
|
||||
# (tools/fixtures/_godot_tres.gd: every stored property as var_to_str text), ours too.
|
||||
# tests/gen/godot.luau { cases = { { name, data, files = { [rel] = bytes }, dump? } }, tres = { { name, data, godot } } }
|
||||
# tests/gen/godot_ours.luau { { name, data, dump } }; ours_*.tres entries carry godot (the resource dump) instead
|
||||
import importlib.util, json, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Rosetta/model/godot", "src/Rosetta/data/tres", "src/Rosetta/codecs/text/GodotVariant.luau", "tools/fixtures/_godot_make.gd",
|
||||
"tools/fixtures/_godot_dump.gd", "tools/fixtures/_godot_tres.gd", "tools/fixtures/_godot_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
ESCN = """[gd_scene load_steps=4 format=2]
|
||||
|
||||
[sub_resource id=1 type="SpatialMaterial"]
|
||||
|
||||
resource_name = "Material"
|
||||
albedo_color = Color(0.8, 0.2, 0.1, 1.0)
|
||||
metallic = 0.5
|
||||
roughness = 0.25
|
||||
flags_transparent = false
|
||||
params_cull_mode = 2
|
||||
|
||||
[sub_resource id=2 type="ArrayMesh"]
|
||||
|
||||
resource_name = "Cube"
|
||||
surfaces/0 = {
|
||||
\t"material":SubResource(1),
|
||||
\t"primitive":4,
|
||||
\t"arrays":[
|
||||
\t\tVector3Array(1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0),
|
||||
\t\tVector3Array(0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0),
|
||||
\t\tFloatArray(1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0),
|
||||
\t\tnull, ; no Vertex Colors,
|
||||
\t\tVector2Array(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0),
|
||||
\t\tnull, ; No UV2,
|
||||
\t\tnull, ; No Bones,
|
||||
\t\tnull, ; No Weights,
|
||||
\t\tIntArray(0, 2, 1, 0, 3, 2)
|
||||
\t],
|
||||
\t"morph_arrays":[]
|
||||
}
|
||||
|
||||
[sub_resource id=3 type="ArrayMesh"]
|
||||
|
||||
surfaces/0 = {
|
||||
\t"primitive":5,
|
||||
\t"arrays":[
|
||||
\t\tVector3Array(0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0),
|
||||
\t\tnull, null, ColorArray(1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1), null, null, null, null, null
|
||||
\t],
|
||||
\t"morph_arrays":[]
|
||||
}
|
||||
|
||||
[node type="Spatial" name="Scene"]
|
||||
|
||||
[node name="Cube" type="MeshInstance" parent="."]
|
||||
|
||||
mesh = SubResource(2)
|
||||
visible = true
|
||||
transform = Transform(1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 2.0, 3.0, 4.0)
|
||||
|
||||
[node name="Strip" type="MeshInstance" parent="Cube"]
|
||||
|
||||
mesh = SubResource(3)
|
||||
transform = Transform(2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0)
|
||||
|
||||
[node name="Camera" type="Camera" parent="."]
|
||||
|
||||
fov = 60.0
|
||||
far = 250.0
|
||||
|
||||
[node name="Lamp" type="OmniLight" parent="."]
|
||||
|
||||
light_color = Color(1, 1, 0.5, 1)
|
||||
light_energy = 3.0
|
||||
omni_range = 9.0
|
||||
transform = Transform(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 5, 0)
|
||||
"""
|
||||
|
||||
TRES = [
|
||||
("material.tres", """[gd_resource type="StandardMaterial3D" load_steps=2 format=3 uid="uid://b1x2y3z4"]
|
||||
|
||||
[ext_resource type="Texture2D" path="res://checker.png" id="1_ab"]
|
||||
|
||||
[resource]
|
||||
resource_name = "Brick"
|
||||
albedo_color = Color(0.8, 0.4, 0.2, 1)
|
||||
albedo_texture = ExtResource("1_ab")
|
||||
metallic = 0.25
|
||||
uv1_scale = Vector3(2, 2, 1)
|
||||
"""),
|
||||
("data.tres", """[gd_resource type="Resource" script_class="Stats" load_steps=3 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://stats.gd" id="1"]
|
||||
|
||||
[sub_resource type="Curve" id="Curve_1"]
|
||||
_data = [Vector2(0, 0), 0.0, 1.0, 0, 0, Vector2(1, 1), 1.0, 0.0, 0, 0]
|
||||
point_count = 2
|
||||
|
||||
[resource]
|
||||
script = ExtResource("1")
|
||||
name = "Goblin \\"Grr\\"\\nline two"
|
||||
hp = 12
|
||||
speed = 3.5
|
||||
tags = PackedStringArray("green", "small")
|
||||
weights = PackedFloat32Array(0.5, 0.25, -1e-05, inf)
|
||||
spawn = Vector3i(1, -2, 3)
|
||||
rect = Rect2(0, 0, 32, 16)
|
||||
curve = SubResource("Curve_1")
|
||||
drops = {
|
||||
"gold": 5,
|
||||
"items": [&"sword", NodePath("../Path"), null, true],
|
||||
3: Color(1, 0, 0, 1)
|
||||
}
|
||||
typed = Array[int]([1, 2, 3])
|
||||
basis = Basis(1, 0, 0, 0, 1, 0, 0, 0, 1)
|
||||
quat = Quaternion(0, 0, 0, 1)
|
||||
obj = Object(Resource,"resource_local_to_scene":false,"resource_name":"x")
|
||||
"""),
|
||||
]
|
||||
|
||||
|
||||
def png(w, h):
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
raw = b"".join(b"\0" + bytes(((x + y) % 2) * 255 for x in range(w) for _ in range(3)) for y in range(h))
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def godot(ctx, project, args):
|
||||
cmd = ["nix", "shell", "nixpkgs#godot_4", "-c", "godot", "--headless", "--path", project] + args
|
||||
return subprocess.run(cmd, capture_output=True, timeout=600).stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def dump(ctx, project, files):
|
||||
out = godot(ctx, project, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_dump.gd"), "--"] + ["res://" + f for f in files])
|
||||
res = {}
|
||||
for line in out.split("\n"):
|
||||
if line.startswith("JSON:"):
|
||||
d = json.loads(line[5:])
|
||||
res[d["file"][6:]] = d
|
||||
return res
|
||||
|
||||
|
||||
STATS_GD = """class_name Stats
|
||||
extends Resource
|
||||
@export var name: String
|
||||
@export var hp: int
|
||||
@export var speed: float
|
||||
@export var tags: PackedStringArray
|
||||
@export var weights: PackedFloat32Array
|
||||
@export var spawn: Vector3i
|
||||
@export var rect: Rect2
|
||||
@export var curve: Curve
|
||||
@export var drops: Dictionary
|
||||
@export var typed: Array[int]
|
||||
@export var basis: Basis
|
||||
@export var quat: Quaternion
|
||||
@export var obj: Resource
|
||||
"""
|
||||
|
||||
|
||||
def tres_dump(ctx, project, files):
|
||||
out = godot(ctx, project, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_tres.gd"), "--"] + ["res://" + f for f in files])
|
||||
res = {}
|
||||
for line in out.split("\n"):
|
||||
if line.startswith("JSON:"):
|
||||
d = json.loads(line[5:])
|
||||
res[d["file"][6:]] = d
|
||||
return res
|
||||
|
||||
|
||||
def clean(v):
|
||||
# None cannot sit in a Luau table: drop null fields
|
||||
if isinstance(v, dict):
|
||||
return {k: clean(x) for k, x in v.items() if x is not None}
|
||||
if isinstance(v, list):
|
||||
return [clean(x) for x in v if x is not None]
|
||||
return v
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="rosetta-godot-")
|
||||
try:
|
||||
with open(os.path.join(tmp, "project.godot"), "w") as f:
|
||||
f.write('config_version=5\n[application]\nconfig/name="rosetta"\n')
|
||||
checker = png(4, 4)
|
||||
with open(os.path.join(tmp, "checker.png"), "wb") as f:
|
||||
f.write(checker)
|
||||
godot(ctx, tmp, ["--import"])
|
||||
godot(ctx, tmp, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_make.gd")])
|
||||
made = ["part.tscn", "main.tscn"]
|
||||
dumps = dump(ctx, tmp, made)
|
||||
read = lambda f: open(os.path.join(tmp, f), "rb").read()
|
||||
cases = []
|
||||
for f in made:
|
||||
cases.append({"name": f, "data": read(f), "files": {"part.tscn": read("part.tscn"), "checker.png": checker}, "dump": clean(dumps.get(f, {}))})
|
||||
cases.append({"name": "hand.escn", "data": ESCN.encode(), "files": {}})
|
||||
with open(os.path.join(tmp, "stats.gd"), "w") as f:
|
||||
f.write(STATS_GD)
|
||||
for n, t in TRES:
|
||||
with open(os.path.join(tmp, n), "w") as f:
|
||||
f.write(t)
|
||||
td = tres_dump(ctx, tmp, [n for n, _ in TRES])
|
||||
tres = [{"name": n, "data": t.encode(), "godot": td.get(n, {"ok": False})} for n, t in TRES]
|
||||
ctx.emit("godot", {"cases": cases, "tres": tres})
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
M = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(M)
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_godot_encode.luau")
|
||||
names = sorted(ours)
|
||||
for n in names:
|
||||
with open(os.path.join(tmp, n), "wb") as f:
|
||||
f.write(ours[n])
|
||||
scenes = [n for n in names if n.endswith(".tscn")]
|
||||
od = dump(ctx, tmp, scenes)
|
||||
rd = tres_dump(ctx, tmp, [n for n in names if n.endswith(".tres")])
|
||||
ctx.emit("godot_ours", [{"name": n, "data": ours[n], "dump": clean(od.get(n, {"ok": False}))} for n in scenes] +
|
||||
[{"name": n, "data": ours[n], "godot": rd.get(n, {"ok": False})} for n in names if n.endswith(".tres")])
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
Reference in new issue
Block a user