From 8f26e32a716eced11e9cb60e79c0da5bc514af20 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 19:25:15 -0600 Subject: [PATCH] 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). --- README.md | 6 +- docs/FORMATS.md | 3 + docs/STYLE.md | 2 +- docs/guide/data.md | 24 + docs/guide/scene.md | 35 ++ licenses/NOTICE.md | 1 + licenses/godot-LICENSE.txt | 20 + src/Rosetta/Registry.luau | 24 + src/Rosetta/codecs/text/GodotVariant.luau | 657 ++++++++++++++++++++++ src/Rosetta/data/tres/init.luau | 143 +++++ src/Rosetta/model/godot/Build.luau | 540 ++++++++++++++++++ src/Rosetta/model/godot/Primitives.luau | 273 +++++++++ src/Rosetta/model/godot/Surface.luau | 483 ++++++++++++++++ src/Rosetta/model/godot/Write.luau | 327 +++++++++++ src/Rosetta/model/godot/init.luau | 89 +++ tests/codecs/godotvariant.luau | 47 ++ tests/data/tres.luau | 100 ++++ tests/model/godot.luau | 356 ++++++++++++ tools/fixtures/_godot_dump.gd | 80 +++ tools/fixtures/_godot_encode.luau | 45 ++ tools/fixtures/_godot_make.gd | 120 ++++ tools/fixtures/_godot_tres.gd | 15 + tools/fixtures/docs_engines.py | 40 +- tools/fixtures/godot.py | 224 ++++++++ 24 files changed, 3649 insertions(+), 5 deletions(-) create mode 100644 licenses/godot-LICENSE.txt create mode 100644 src/Rosetta/codecs/text/GodotVariant.luau create mode 100644 src/Rosetta/data/tres/init.luau create mode 100644 src/Rosetta/model/godot/Build.luau create mode 100644 src/Rosetta/model/godot/Primitives.luau create mode 100644 src/Rosetta/model/godot/Surface.luau create mode 100644 src/Rosetta/model/godot/Write.luau create mode 100644 src/Rosetta/model/godot/init.luau create mode 100644 tests/codecs/godotvariant.luau create mode 100644 tests/data/tres.luau create mode 100644 tests/model/godot.luau create mode 100644 tools/fixtures/_godot_dump.gd create mode 100644 tools/fixtures/_godot_encode.luau create mode 100644 tools/fixtures/_godot_make.gd create mode 100644 tools/fixtures/_godot_tres.gd create mode 100644 tools/fixtures/godot.py diff --git a/README.md b/README.md index 2cb925b..143cb55 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -178 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +180 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -114,6 +114,7 @@ adds each format's capabilities. | 3D models | dae | .dae .zae | yes | yes | | 3D models | fbx | .fbx | yes | yes | | 3D models | gltf | .gltf .glb | yes | yes | +| 3D models | godot | .tscn .escn | yes | yes | | 3D models | iqm | .iqm | yes | yes | | 3D models | ldraw | .ldr .mpd .dat | yes | - | | 3D models | lwo | .lwo .lxo | yes | - | @@ -192,6 +193,7 @@ adds each format's capabilities. | Data | plist | .plist | yes | yes | | Data | snbt | .snbt | yes | yes | | Data | toml | .toml | yes | yes | +| Data | tres | .tres | yes | yes | | Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | | Data | yaml | .yaml .yml | yes | yes | | Vector graphics and tile maps | ldtk | .ldtk | yes | yes | @@ -243,7 +245,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs//` | font | Bitmap, Cff, GlyphNames, TrueType | | image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | | model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | -| text | Json, Nbt, Text, Url, Xml | +| text | GodotVariant, Json, Nbt, Text, Url, Xml | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 245e1dd..e47a002 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -70,6 +70,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` | +| model | godot | .tscn .escn | yes | yes | text: true, materials: true, cameras: true, lights: true, instances: true | `tests/model/godot.luau` | | model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | @@ -148,6 +149,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | | data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | +| data | tres | .tres | yes | yes | ordered: true | `tests/data/tres.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | | vector | ldtk | .ldtk | yes | yes | levels: true, worlds: true, intGrid: true, entities: true | `tests/vector/ldtk.luau` | @@ -259,6 +261,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. - codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. - **text** + - codecs/text/GodotVariant: Godot's text resource syntax (.tscn / .tres / .escn, formats 2-4; Godot's - 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 SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. diff --git a/docs/STYLE.md b/docs/STYLE.md index b1a40f4..aa6f630 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -33,7 +33,7 @@ src/Rosetta/ audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) - text/ Json Nbt Text Url Xml + text/ GodotVariant Json Nbt Text Url Xml font/ Bitmap Cff GlyphNames TrueType model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml host/ host (layer 2) runtime adapters; only the api uses them diff --git a/docs/guide/data.md b/docs/guide/data.md index faa0a32..de0b935 100644 --- a/docs/guide/data.md +++ b/docs/guide/data.md @@ -306,6 +306,29 @@ local xml = assert(F.saveString(p, { format = "plist" })) assert(string.find(xml, "CFBundleName\n\tDemo", 1, true)) ``` +## Godot resources (.tres) + +Godot text resources load as a table: `type` (the resource class), `format`, `uid`, `scriptClass`, `external` (the +`ext_resource` list: `id`, `type`, `path`, `uid`), `subresources` (`id`, `type`, `properties`) and `properties` (the +`[resource]` section, in file order). Godot values that Luau lacks are `{ type, args }` tables: `Vector3(1, 2, 3)` is +`{ type = "Vector3", args = { 1, 2, 3 } }`, likewise `Color`, `Transform3D`, `PackedFloat32Array`, `NodePath`, +`&"StringName"` (`type = "StringName"`), `SubResource("id")` and `ExtResource("id")`; `Object(Class, ...)` has `class` +and its properties in `args[1]`. Godot dictionaries keep their order and may have number keys. Godot tells integers +from floats, so integral floats read from a file (`1.0`) are written back as floats. +`F.format("tres")` and the codec `F._internal("codecs/text/GodotVariant")` (`value`, `format`, `isCtor`, `ctor`) +help with the values. Scenes (`.tscn`) are models: see [the scene guide](scene.md). + +```luau +local res = assert(F.data.load(tresText)) +assert(res.type == "StandardMaterial3D" and res.external[1].path == "res://brick.png") +local c = res.properties.albedo_color +assert(c.type == "Color" and c.args[1] == 0.8) +assert(res.properties.albedo_texture.type == "ExtResource") +res.properties.metallic = 0.5 +local text = assert(F.saveString(res, { format = "tres" })) +assert(string.find(text, "metallic = 0.5", 1, true) and string.find(text, "roughness = 1.0", 1, true)) +``` + ## Save and convert Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): @@ -341,6 +364,7 @@ is an error there), CSV needs rows, INI needs sections of scalars, JSON has no b | cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values | | plist (`.plist`) | XML + binary | XML | values, buffers, Dates | | nbt (`.nbt`, `.dat`, `.mcstructure`), snbt (`.snbt`) | yes | yes | typed values: see [Minecraft and voxels](voxel.md) | +| tres (`.tres`) | yes | yes | Godot resources: sections, Variant values as `{ type, args }` | Full capability list: [FORMATS.md](../FORMATS.md). diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 4650d39..145ca1b 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -739,6 +739,40 @@ local again = assert(F.load(F.save(scene, nil, { format = "ase" }))) assert(#again.meshes[again.nodes[2].mesh].primitives == 2) ``` +## Godot scenes (TSCN / ESCN) + +Godot text scenes load as a Y-up Scene (one node per `[node]`, the scene root first), checked against Godot 4's own +loader. Node3D transforms come from `transform = Transform3D(...)` (or `position` / `rotation` / `scale`); a +MeshInstance3D gets its ArrayMesh sub-resource (Godot 4.2+ surfaces, and the `"arrays"` surfaces of Godot 3 / Blender +`.escn` files) or its primitive mesh (Box, Plane, Quad, Sphere and Cylinder are built as Godot builds them), with +`surface_material_override/N` applied. StandardMaterial3D / SpatialMaterial become PBR materials (Godot's sRGB +albedo and emission converted to linear; the raw values in `material.extras.godot`); textures are `ExtResource` +paths (`res://` dropped) with their bytes through `opts.resolve`. Camera3D (`fov` is vertical) and Omni / Spot / +Directional lights map to cameras and lights (`intensity` = `light_energy`). Instanced scenes +(`instance=ExtResource(...)`) are read through `opts.resolve` and grafted under their node. Godot's front faces are +clockwise: indices are reversed into glTF's counter-clockwise winding (and back on save). Every node keeps its Godot +type and raw properties in `node.extras.godot`, so 2D trees (Node2D, Sprite2D, Control) are kept there too. + +```luau +local scene = assert(F.load(tscnText, { resolve = function(path) return nil end })) +assert(scene.meta.source.format == "godot" and scene.meta.up == "y") +local box = scene.nodes[2] +assert(box.name == "Box" and box.extras.godot.type == "MeshInstance3D") +assert(box.matrix[13] == 2) -- Transform3D origin x +local mat = scene.materials[scene.meshes[box.mesh].primitives[1].material] +assert(mat.extras.godot.albedo[1] == 1 and mat.metallic == 0.5) +assert(scene.cameras[1].type == "perspective" and math.abs(math.deg(scene.cameras[1].yfov) - 60) < 1e-9) +local hud = scene.nodes[4] +assert(hud.extras.godot.type == "Node2D" and hud.extras.godot.properties.position.args[1] == 10) +local tscn = assert(F.saveString(scene, { format = "godot" })) -- Godot 4 text, format 3 +assert(string.find(tscn, '[node name="Box" type="MeshInstance3D" parent="."]', 1, true)) +``` + +The writer makes Node3D / MeshInstance3D / Camera3D / light nodes, ArrayMesh sub-resources (uncompressed format 2 +surfaces with positions, normals, tangents, colours, two UV sets) and StandardMaterial3D, plus a `Texture2D` +`ext_resource` per texture with a `uri`. Skins, animations and morph targets are not written. Godot resources +(`.tres`) are data: see [data.md](data.md). + ## Formats | Format | Read | Write | Notes | @@ -769,6 +803,7 @@ assert(#again.meshes[again.nodes[2].mesh].primitives == 2) | STEP | via the CAD plug-in | | see [cad.md](cad.md) | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | SMD | yes | yes | Valve studiomdl data | +| Godot `.tscn` / `.escn` | yes | yes (`.tscn`) | Node3D trees, ArrayMesh and primitive meshes, StandardMaterial3D, cameras, lights, instances; 2D nodes in extras | | ASE (3ds Max ASCII) | yes | yes | Multi/Sub-Object materials, texture channels, vertex colours, normals, helpers, cameras, lights; no animation; Z up | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index f3d8a08..26dd01b 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -59,6 +59,7 @@ | `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data | | `src/Rosetta/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | | `src/Rosetta/image/exr/Piz.luau`, `src/Rosetta/image/exr/Codec.luau` (the PIZ Huffman / wavelet / LUT steps and the ZIP / RLE byte predictor, re-implemented in Luau after the OpenEXR algorithms) | OpenEXR 3.x (ImfPizCompressor, ImfHuf, ImfWav, ImfZip, ImfRle) | BSD-3-Clause: [openexr-LICENSE.md](openexr-LICENSE.md) | +| `src/Rosetta/model/godot/Primitives.luau` (BoxMesh, PlaneMesh, QuadMesh, SphereMesh, CylinderMesh generation, ported to Luau without UV2) | Godot Engine 4.4 `scene/resources/3d/primitive_meshes.cpp` | MIT: [godot-LICENSE.txt](godot-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/godot-LICENSE.txt b/licenses/godot-LICENSE.txt new file mode 100644 index 0000000..0e3ba08 --- /dev/null +++ b/licenses/godot-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). +Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 999cca5..7be9095 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -794,6 +794,18 @@ local list: { Entry } = { return require("@rosetta/model/gltf") end, }, + { + name = "godot", + category = "model", + path = "model/godot", + extensions = { "tscn", "escn" }, + mime = { "application/x-godot-scene" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, instances = true }, + load = function() + return require("@rosetta/model/godot") + end, + }, { name = "iqm", category = "model", @@ -1730,6 +1742,18 @@ local list: { Entry } = { return require("@rosetta/data/toml") end, }, + { + name = "tres", + category = "data", + path = "data/tres", + extensions = { "tres" }, + mime = { "application/x-godot-resource" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return require("@rosetta/data/tres") + end, + }, { name = "xml", category = "data", diff --git a/src/Rosetta/codecs/text/GodotVariant.luau b/src/Rosetta/codecs/text/GodotVariant.luau new file mode 100644 index 0000000..ed49696 --- /dev/null +++ b/src/Rosetta/codecs/text/GodotVariant.luau @@ -0,0 +1,657 @@ +--!strict +-- codecs/text/GodotVariant: Godot's text resource syntax (.tscn / .tres / .escn, formats 2-4; Godot's +-- variant_parser.cpp and resource_format_text.cpp): [section key=value ...] headers with `key = value` properties, +-- and the Variant text syntax (numbers, strings, &"StringName", ^"NodePath", arrays, dictionaries, constructors such +-- as Vector3(...), Transform3D(...), PackedFloat32Array(...), SubResource("id"), Object(Class, "k": v)). +-- Constructor values are { type, args } tables (GodotVariant.isCtor); dictionaries keep their key order. +local Types = require("@rosetta/Types") +local Base64 = require("@rosetta/core/Base64") + +local GodotVariant = {} + +GodotVariant.null = Types.null + +local CTOR = { __godot = true } + +-- integral numbers written as floats ("1.0"): Godot keeps int and float apart (Curve._data mixes them), so the keys +-- holding them are remembered per container (array, dictionary, property table) and written back with ".0" +local FLOATS: { [any]: { [any]: boolean } } = setmetatable({}, { __mode = "k" }) :: any +local lastFloat = false + +local function mark(t: any, k: any, v: any) + if lastFloat and type(v) == "number" and v == math.floor(v) then + local m = FLOATS[t] + if not m then + m = {} + FLOATS[t] = m + end + m[k] = true + end +end + +function GodotVariant.isFloat(t: any, k: any): boolean + local m = FLOATS[t] + return m ~= nil and m[k] == true +end + +function GodotVariant.markFloat(t: any, k: any) + local m = FLOATS[t] + if not m then + m = {} + FLOATS[t] = m + end + m[k] = true +end + +function GodotVariant.copyFloats(from: any, to: any) + local m = FLOATS[from] + if m then + FLOATS[to] = table.clone(m) + end +end + +export type Ctor = { type: string, args: { any }, class: string? } +export type Section = { tag: string, attrs: { [string]: any }, attrOrder: { string }, props: { [string]: any }, order: { string } } +export type Document = { sections: { Section } } + +function GodotVariant.ctor(name: string, args: { any }?): Ctor + return setmetatable({ type = name, args = args or {} }, CTOR) :: any +end + +function GodotVariant.isCtor(v: any): boolean + return type(v) == "table" and getmetatable(v) == CTOR +end + +-- the numbers of a constructor, or nil when an argument is not a number +function GodotVariant.numbers(v: any, name: string?): { number }? + if not GodotVariant.isCtor(v) or (name and v.type ~= name) then + return nil + end + for _, x in v.args do + if type(x) ~= "number" then + return nil + end + end + return v.args :: { number } +end + +-- PackedByteArray(1, 2, ...) or PackedByteArray("base64") (Godot 4.3+), PoolByteArray / ByteArray (format 2) +function GodotVariant.bytes(v: any): buffer? + if not GodotVariant.isCtor(v) then + return nil + end + local a = v.args + if #a == 1 and type(a[1]) == "string" then + return (Base64.decode(a[1])) + end + local b = buffer.create(#a) + for i, x in a do + if type(x) ~= "number" then + return nil + end + buffer.writeu8(b, i - 1, x % 256) + end + return b +end + +-- ------------------------------------------------------------------------------------------------ parse +type P = { s: string, i: number, n: number, depth: number, maxDepth: number } + +local NUMERIC_ARRAYS: { [string]: boolean } = { + PackedByteArray = true, PackedInt32Array = true, PackedInt64Array = true, PackedFloat32Array = true, + PackedFloat64Array = true, PackedVector2Array = true, PackedVector3Array = true, PackedVector4Array = true, + PackedColorArray = true, PoolByteArray = true, PoolIntArray = true, PoolRealArray = true, PoolVector2Array = true, + PoolVector3Array = true, PoolColorArray = true, ByteArray = true, IntArray = true, FloatArray = true, RealArray = true, + Vector2Array = true, Vector3Array = true, ColorArray = true, +} +local WORDS: { [string]: any } = { ["true"] = true, ["false"] = false, ["inf"] = math.huge, ["-inf"] = -math.huge, inf_neg = -math.huge, nan = 0 / 0 } + +local function skip(p: P) + local s, i = p.s, p.i + while true do + local a = string.find(s, "[^ \t\r\n]", i) + if not a then + p.i = p.n + 1 + return + end + if string.byte(s, a) == 59 then -- ';' comment to the end of the line + local e = string.find(s, "\n", a, true) + if not e then + p.i = p.n + 1 + return + end + i = e + 1 + else + p.i = a + return + end + end +end + +local ESC: { [string]: string } = { n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", ["\""] = "\"", ["\\"] = "\\", ["'"] = "'", ["/"] = "/" } + +local function utf8char(c: number): string + return utf8.char(math.clamp(c, 0, 0x10FFFF)) +end + +local function str(p: P): (string?, string?) + local s = p.s + local i = p.i + 1 + local parts = {} + while true do + local a = string.find(s, "[\"\\]", i) + if not a then + return nil, "unterminated string" + end + table.insert(parts, string.sub(s, i, a - 1)) + if string.byte(s, a) == 34 then + p.i = a + 1 + return table.concat(parts), nil + end + local c = string.sub(s, a + 1, a + 1) + if c == "u" or c == "U" then + local len = if c == "u" then 4 else 6 + local h = tonumber(string.sub(s, a + 2, a + 1 + len), 16) + if not h then + return nil, "bad \\u escape" + end + -- surrogate pairs + if h >= 0xD800 and h < 0xDC00 and string.sub(s, a + 6, a + 7) == "\\u" then + local lo = tonumber(string.sub(s, a + 8, a + 11), 16) + if lo and lo >= 0xDC00 and lo < 0xE000 then + h = 0x10000 + (h - 0xD800) * 1024 + (lo - 0xDC00) + len += 6 + end + end + table.insert(parts, utf8char(h)) + i = a + 2 + len + else + table.insert(parts, ESC[c] or c) + i = a + 2 + end + end +end + +local value: (p: P) -> (any, string?) + +local function numberList(p: P, name: string): (any, string?) + local s = p.s + local close = string.find(s, ")", p.i, true) + if not close then + return nil, "unterminated " .. name + end + local body = string.sub(s, p.i, close - 1) + -- base64 PackedByteArray, or a list of plain numbers + local q = string.match(body, "^%s*\"([^\"]*)\"%s*$") + if q then + p.i = close + 1 + return GodotVariant.ctor(name, { q }), nil + end + local out = {} + local k = 0 + for tok in string.gmatch(body, "[^,%s]+") do + local v = tonumber(tok) + if v == nil then + v = WORDS[tok] + if type(v) ~= "number" then + return nil, nil -- not purely numeric: parse it generically + end + end + k += 1 + out[k] = v + end + p.i = close + 1 + return GodotVariant.ctor(name, out), nil +end + +local function list(p: P, close: number, into: { any }): string? + skip(p) + if string.byte(p.s, p.i) == close then + p.i += 1 + return nil + end + while true do + local v, err = value(p) + if err then + return err + end + table.insert(into, v) + mark(into, #into, v) + skip(p) + local c = string.byte(p.s, p.i) + if c == 44 then -- ',' + p.i += 1 + skip(p) + if string.byte(p.s, p.i) == close then + p.i += 1 + return nil + end + elseif c == close then + p.i += 1 + return nil + else + return "expected ',' or '" .. string.char(close) .. "' at byte " .. (p.i - 1) + end + end +end + +local function dict(p: P): (any, string?) + p.i += 1 + local t, keys = {}, {} + skip(p) + if string.byte(p.s, p.i) == 125 then + p.i += 1 + return Types.object(t, keys), nil + end + while true do + local k, err = value(p) + if err then + return nil, err + end + skip(p) + if string.byte(p.s, p.i) ~= 58 then + return nil, "expected ':' at byte " .. (p.i - 1) + end + p.i += 1 + local v, verr = value(p) + if verr then + return nil, verr + end + local key = if type(k) == "string" or type(k) == "number" then k else GodotVariant.format(k) + if t[key] == nil then + table.insert(keys, key) + end + t[key] = v + mark(t, key, v) + skip(p) + local c = string.byte(p.s, p.i) + if c == 44 then + p.i += 1 + skip(p) + if string.byte(p.s, p.i) == 125 then + p.i += 1 + break + end + elseif c == 125 then + p.i += 1 + break + else + return nil, "expected ',' or '}' at byte " .. (p.i - 1) + end + end + return Types.object(t, keys), nil +end + +value = function(p: P): (any, string?) + skip(p) + if p.i > p.n then + return nil, "truncated: value expected" + end + p.depth += 1 + if p.depth > p.maxDepth then + return nil, "limit: nested deeper than " .. p.maxDepth + end + local s = p.s + local c = string.byte(s, p.i) + local v: any, err: string? = nil, nil + local isFloat = false + if c == 34 then + v, err = str(p) + elseif c == 38 or c == 94 then -- &"StringName", ^"NodePath" + p.i += 1 + local x, e = str(p) + v, err = if x then GodotVariant.ctor(if c == 38 then "StringName" else "NodePath", { x }) else nil, e + elseif c == 91 then -- '[' + p.i += 1 + local out = {} + err = list(p, 93, out) + v = out + elseif c == 123 then -- '{' + v, err = dict(p) + else + local num = string.match(s, "^[-+]?%d[%w%.+-]*", p.i) or string.match(s, "^[-+]?%.%d[%w%.+-]*", p.i) + if num then + -- 1e-05, 0x1F, 1.5; a trailing "f" is not Godot's + local x = tonumber(num) + if x == nil then + local m = string.match(num, "^[-+]?[%d%.]+[eE][-+]?%d+") or string.match(num, "^[-+]?[%d%.]+") + x = if m then tonumber(m) else nil + num = m or num + end + if x == nil then + return nil, "bad number " .. num .. " at byte " .. (p.i - 1) + end + p.i += #num + v = x + isFloat = string.find(num, "[%.eE]") ~= nil and string.sub(num, 1, 2) ~= "0x" + else + local word = string.match(s, "^[%a_][%w_]*", p.i) or string.match(s, "^%-inf", p.i) + if not word then + return nil, "unexpected character at byte " .. (p.i - 1) + end + p.i += #word + if word == "null" or word == "nil" then + v = Types.null + elseif WORDS[word] ~= nil then + v = WORDS[word] + else + -- typed array: Array[int]([...]); Dictionary[String, int]({...}) + local typed = string.match(s, "^%[[%w_, ]*%]", p.i) + if typed and (word == "Array" or word == "Dictionary") then + word = word .. typed + p.i += #typed + end + skip(p) + if string.byte(s, p.i) ~= 40 then + return nil, "expected '(' after " .. word .. " at byte " .. (p.i - 1) + end + p.i += 1 + if NUMERIC_ARRAYS[word] then + local save = p.i + v, err = numberList(p, word) + if v == nil and err == nil then + p.i = save + local args = {} + err = list(p, 41, args) + v = GodotVariant.ctor(word, args) + end + elseif word == "Object" then + skip(p) + local cls = string.match(s, "^[%w_]+", p.i) + if not cls then + return nil, "Object without a class at byte " .. (p.i - 1) + end + p.i += #cls + local props, keys = {}, {} + skip(p) + while string.byte(s, p.i) == 44 do + p.i += 1 + local k, kerr = value(p) + if kerr then + return nil, kerr + end + skip(p) + if string.byte(s, p.i) ~= 58 then + return nil, "expected ':' in Object at byte " .. (p.i - 1) + end + p.i += 1 + local x, xerr = value(p) + if xerr then + return nil, xerr + end + if type(k) == "string" then + props[k] = x + table.insert(keys, k) + end + skip(p) + end + if string.byte(s, p.i) ~= 41 then + return nil, "expected ')' after Object at byte " .. (p.i - 1) + end + p.i += 1 + local o = GodotVariant.ctor("Object", { Types.object(props, keys) }) + o.class = cls + v = o + else + local args = {} + err = list(p, 41, args) + v = GodotVariant.ctor(word, args) + end + end + end + end + p.depth -= 1 + lastFloat = isFloat + return v, err +end + +function GodotVariant.value(text: string, maxDepth: number?): (any, string?) + local p: P = { s = text, i = 1, n = #text, depth = 0, maxDepth = maxDepth or 256 } + return value(p) +end + +-- a property key: up to '=' (keys hold '/', ':', '.', or are quoted) +local function key(p: P): string? + local s = p.s + if string.byte(s, p.i) == 34 then + local k = str(p) + return k + end + local k = string.match(s, "^[^=\n%[]+", p.i) + if not k then + return nil + end + p.i += #k + return (string.gsub(k, "%s+$", "")) +end + +function GodotVariant.parse(text: string, opts: { maxDepth: number?, maxSections: number? }?): (Document?, string?) + local o: { maxDepth: number?, maxSections: number? } = opts or {} + if string.sub(text, 1, 3) == "\239\187\191" then + text = string.sub(text, 4) + end + local p: P = { s = text, i = 1, n = #text, depth = 0, maxDepth = o.maxDepth or 256 } + local maxSections = o.maxSections or 2 ^ 22 + local sections: { Section } = {} + local cur: Section? = nil + local s = text + while true do + skip(p) + if p.i > p.n then + break + end + if string.byte(s, p.i) == 91 then + p.i += 1 + skip(p) + local tag = string.match(s, "^[%w_]+", p.i) + if not tag then + return nil, "bad section header at byte " .. (p.i - 1) + end + p.i += #tag + local sec: Section = { tag = tag, attrs = {}, attrOrder = {}, props = {}, order = {} } + while true do + skip(p) + local c = string.byte(s, p.i) + if c == 93 then + p.i += 1 + break + end + local k = string.match(s, "^[%w_/]+", p.i) + if not k then + return nil, "bad attribute in [" .. tag .. "] at byte " .. (p.i - 1) + end + p.i += #k + skip(p) + if string.byte(s, p.i) ~= 61 then + return nil, "expected '=' in [" .. tag .. "] at byte " .. (p.i - 1) + end + p.i += 1 + local v, err = value(p) + if err then + return nil, err + end + if sec.attrs[k] == nil then + table.insert(sec.attrOrder, k) + end + sec.attrs[k] = v + end + if #sections >= maxSections then + return nil, "limit: over " .. maxSections .. " sections" + end + table.insert(sections, sec) + cur = sec + else + local at = p.i + local k = key(p) + if not k or k == "" then + return nil, "bad property at byte " .. (at - 1) + end + skip(p) + if string.byte(s, p.i) ~= 61 then + return nil, "expected '=' after " .. k .. " at byte " .. (p.i - 1) + end + p.i += 1 + local v, err = value(p) + if err then + return nil, err + end + if not cur then + cur = { tag = "", attrs = {}, attrOrder = {}, props = {}, order = {} } + table.insert(sections, cur :: Section) + end + local c = cur :: Section + if c.props[k] == nil then + table.insert(c.order, k) + end + c.props[k] = v + mark(c.props, k, v) + end + end + return { sections = sections }, nil +end + +-- ------------------------------------------------------------------------------------------------ format +local function num(x: number): string + if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for d = 6, 17 do + local s = string.format("%." .. d .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end +GodotVariant.number = num + +local function quote(s: string): string + return "\"" .. string.gsub(s, "[\\\"\n\t\r]", { ["\\"] = "\\\\", ["\""] = "\\\"", ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) .. "\"" +end +GodotVariant.quote = quote + +local format: (v: any, depth: number, indent: boolean) -> string + +local function item(t: any, k: any, depth: number, indent: boolean): string + local v = t[k] + if type(v) == "number" and v == math.floor(v) and math.abs(v) < 2 ^ 53 and GodotVariant.isFloat(t, k) then + return string.format("%d", v) .. ".0" + end + return format(v, depth, indent) +end +GodotVariant.item = function(t: any, k: any): string + return item(t, k, 0, false) +end + +format = function(v: any, depth: number, indent: boolean): string + if depth > 256 then + return "null" + end + local t = type(v) + if t == "number" then + return num(v) + elseif t == "string" then + return quote(v) + elseif t == "boolean" then + return if v then "true" else "false" + elseif v == nil or v == Types.null then + return "null" + elseif t == "buffer" then + local parts = table.create(buffer.len(v)) + for i = 0, buffer.len(v) - 1 do + parts[i + 1] = tostring(buffer.readu8(v, i)) + end + return "PackedByteArray(" .. table.concat(parts, ", ") .. ")" + elseif t ~= "table" then + return "null" + end + if GodotVariant.isCtor(v) then + if v.type == "StringName" and type(v.args[1]) == "string" then + return "&" .. quote(v.args[1]) + elseif v.type == "Object" then + local props = v.args[1] + local parts = { tostring(v.class or "Object") } + if type(props) == "table" then + for _, k in Types.keys(props) do + table.insert(parts, quote(tostring(k)) .. ": " .. format(props[k], depth + 1, false)) + end + end + return "Object(" .. table.concat(parts, ",") .. ")" + end + local parts: { string } = table.create(#v.args) :: any + for i, x in v.args do + parts[i] = format(x, depth + 1, false) + end + local vt: string = tostring(v.type) + if string.match(vt, "^(%a+)%[") then + local inner: string = parts[1] or "[]" + return vt .. "(" .. inner .. ")" + end + return vt .. "(" .. table.concat(parts, ", ") .. ")" + end + if Types.isObject(v) or not Types.isArray(v) then + local keys = Types.keys(v) + if #keys == 0 then + return "{}" + end + local parts = {} + for _, k in keys do + local ks = if type(k) == "string" then quote(k) else format(k, depth + 1, false) + table.insert(parts, ks .. ": " .. item(v, k, depth + 1, false)) + end + if indent then + return "{\n" .. table.concat(parts, ",\n") .. "\n}" + end + return "{\n" .. table.concat(parts, ",\n") .. "\n}" + end + local parts = table.create(#v) + for i in v do + parts[i] = item(v, i, depth + 1, true) + end + return "[" .. table.concat(parts, ", ") .. "]" +end + +function GodotVariant.format(v: any): string + return format(v, 0, false) +end + +function GodotVariant.encode(doc: Document): string + local out = {} + for i, sec in doc.sections do + if sec.tag ~= "" then + local parts = { "[" .. sec.tag } + local order = sec.attrOrder + if #order == 0 then + order = Types.keys(sec.attrs) + end + for _, k in order do + if sec.attrs[k] ~= nil then + table.insert(parts, k .. "=" .. GodotVariant.format(sec.attrs[k])) + end + end + if i > 1 then + table.insert(out, "") + end + table.insert(out, table.concat(parts, " ") .. "]") + end + local order = sec.order + if #order == 0 then + order = Types.keys(sec.props) + end + for _, k in order do + if sec.props[k] ~= nil then + local ks = if string.find(k, "^[%w_/:%.]+$") then k else quote(k) + table.insert(out, ks .. " = " .. item(sec.props, k, 0, false)) + end + end + end + return table.concat(out, "\n") .. "\n" +end + +return GodotVariant diff --git a/src/Rosetta/data/tres/init.luau b/src/Rosetta/data/tres/init.luau new file mode 100644 index 0000000..36086e0 --- /dev/null +++ b/src/Rosetta/data/tres/init.luau @@ -0,0 +1,143 @@ +--!strict +-- data/tres: Godot text resources (.tres, formats 2-4) as data, read + write (codecs/text/GodotVariant). The value: +-- { type, format, uid?, scriptClass?, loadSteps?, external = { { id, type, path, uid? } }, subresources = { { id, +-- type, properties } }, properties } with Variant values (Vector3, Color, SubResource, ... as { type, args } tables; +-- dictionaries and property tables keep their order). Not supported: binary .res files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Sniff = require("@rosetta/core/Sniff") +local Types = require("@rosetta/Types") +local GodotVariant = require("@rosetta/codecs/text/GodotVariant") + +-- ------------------------------------------------------------------------------------------------ contract +local Tres = { + name = "tres", + category = "data", + extensions = { "tres" }, + mime = { "application/x-godot-resource" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant" }, + caps = { decode = true, encode = true, ordered = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- default 2^28 + maxDepth: number?, -- value nesting, default 256 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Tres.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 256) + if string.match(h, "^%s*%[gd_resource[%s%]]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function props(sec: GodotVariant.Section): { [string]: any } + local out = {} + for _, k in sec.order do + out[k] = sec.props[k] + end + GodotVariant.copyFloats(sec.props, out) + return Types.object(out, table.clone(sec.order) :: { any }) +end + +function Tres.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if r.limit - r.base > (o.maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local ok, doc, perr = pcall(function(): (GodotVariant.Document?, string?) + return GodotVariant.parse(text, { maxDepth = o.maxDepth }) + end) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(doc)) + end + if not doc then + return nil, Err.from(perr) + end + local head = doc.sections[1] + if not head or head.tag ~= "gd_resource" then + return nil, Err.new(if head and head.tag == "gd_scene" then Err.UNSUPPORTED else Err.CORRUPT, if head and head.tag == "gd_scene" then "a scene (model/godot), not a resource" else "no [gd_resource] header") + end + local a = head.attrs + local value: { [string]: any } = { + type = a.type, + format = a.format, + uid = a.uid, + scriptClass = a.script_class, + loadSteps = a.load_steps, + external = {}, + subresources = {}, + properties = Types.object({}), + } + for i = 2, #doc.sections do + local sec = doc.sections[i] + local sa = sec.attrs + if sec.tag == "ext_resource" then + table.insert(value.external, { id = sa.id, type = sa.type, path = sa.path, uid = sa.uid }) + elseif sec.tag == "sub_resource" then + table.insert(value.subresources, { id = sa.id, type = sa.type, properties = props(sec) }) + elseif sec.tag == "resource" then + value.properties = props(sec) + end + end + return value, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function section(tag: string, pairs_: { any }, properties: any?): GodotVariant.Section + local attrs, order = {}, {} + local i = 1 + while pairs_[i] ~= nil do + if pairs_[i + 1] ~= nil then + attrs[pairs_[i]] = pairs_[i + 1] + table.insert(order, pairs_[i]) + end + i += 2 + end + local p, po = {}, {} + if type(properties) == "table" then + for _, k in Types.keys(properties) do + if type(k) == "string" then + p[k] = properties[k] + table.insert(po, k) + end + end + GodotVariant.copyFloats(properties, p) + end + return { tag = tag, attrs = attrs, attrOrder = order, props = p, order = po } +end + +function Tres.encode(value: any, opts: any?): (buffer?, Err.Err?) + if type(value) ~= "table" or type(value.type) ~= "string" then + return nil, Err.new(Err.ARG, "needs a resource table with a type") + end + local ext = if type(value.external) == "table" then value.external else {} + local sub = if type(value.subresources) == "table" then value.subresources else {} + local format = if type(value.format) == "number" then value.format else 3 + local steps = if type(value.loadSteps) == "number" then value.loadSteps elseif #ext + #sub > 0 then #ext + #sub + 1 else nil + local sections = { section("gd_resource", { "type", value.type, "script_class", value.scriptClass, "load_steps", steps, "format", format, "uid", value.uid }) } + for _, e in ext do + if type(e) == "table" then + table.insert(sections, section("ext_resource", { "type", e.type, "uid", e.uid, "path", e.path, "id", e.id })) + end + end + for _, s in sub do + if type(s) == "table" then + table.insert(sections, section("sub_resource", { "type", s.type, "id", s.id }, s.properties)) + end + end + table.insert(sections, section("resource", {}, value.properties)) + local ok, s = pcall(GodotVariant.encode, { sections = sections }) + if not ok then + return nil, Err.new(Err.ARG, "cannot encode: " .. tostring(s)) + end + return buffer.fromstring(s), nil +end + +return Tres diff --git a/src/Rosetta/model/godot/Build.luau b/src/Rosetta/model/godot/Build.luau new file mode 100644 index 0000000..c49a7fa --- /dev/null +++ b/src/Rosetta/model/godot/Build.luau @@ -0,0 +1,540 @@ +--!strict +-- model/godot/Build: a parsed Godot text scene (codecs/text/GodotVariant) into a Scene. Transform3D / Transform text +-- is the basis rows then the origin; Node3D position / rotation (Euler YXZ, radians) / scale / quaternion are used when +-- there is no transform. Colours (albedo, emission, lights) are sRGB in Godot and linear in the Scene (raw values in +-- extras.godot). Non-3D nodes (Node2D trees, Control, plain Node) are nodes with their properties in extras.godot. +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local GodotVariant = require("@rosetta/codecs/text/GodotVariant") +local Surface = require("@rosetta/model/godot/Surface") +local Primitives = require("@rosetta/model/godot/Primitives") + +local Build = {} + +local S = Types.Scene +local isCtor = GodotVariant.isCtor + +type Ctx = { + scene: Types.Scene, + doc: GodotVariant.Document, + format: number, + ext: { [string]: any }, + sub: { [string]: any }, + meshes: { [string]: number }, + materials: { [string]: number }, + textures: { [string]: number }, + opts: any, + depth: number, + warnings: { string }, +} + +local function idOf(v: any): string? + if isCtor(v) and (v.type == "SubResource" or v.type == "ExtResource") then + local a = v.args[1] + if type(a) == "string" or type(a) == "number" then + return tostring(a) + end + end + return nil +end + +local function num(v: any, d: number): number + return if type(v) == "number" and v == v then v else d +end + +local function srgb(c: number): number + if c <= 0.04045 then + return c / 12.92 + end + return ((c + 0.055) / 1.055) ^ 2.4 +end + +local function color(v: any, d: { number }): { number } + local a = GodotVariant.numbers(v, "Color") + if a and #a >= 3 then + return { a[1], a[2], a[3], a[4] or 1 } + end + return d +end + +local function linear(c: { number }): { number } + return { srgb(c[1]), srgb(c[2]), srgb(c[3]), c[4] } +end + +-- ------------------------------------------------------------------------------------------------ transforms +function Build.transform(v: any): { number }? + local a = if isCtor(v) and (v.type == "Transform3D" or v.type == "Transform") then GodotVariant.numbers(v) else nil + if not a or #a ~= 12 then + return nil + end + return { a[1], a[4], a[7], 0, a[2], a[5], a[8], 0, a[3], a[6], a[9], 0, a[10], a[11], a[12], 1 } +end + +-- Basis::from_euler (YXZ): Ry * Rx * Rz +local function euler(x: number, y: number, z: number): { number } + local rx, ry, rz = Mat4.rotation(1, math.deg(x)), Mat4.rotation(2, math.deg(y)), Mat4.rotation(3, math.deg(z)) + return S.mul(ry, S.mul(rx, rz)) +end + +local function nodeMatrix(props: any): { number }? + local m = Build.transform(props.transform) + if m then + return m + end + local pos = GodotVariant.numbers(props.position, "Vector3") or GodotVariant.numbers(props.translation, "Vector3") + local rot = GodotVariant.numbers(props.rotation, "Vector3") + local deg = GodotVariant.numbers(props.rotation_degrees, "Vector3") + local quat = GodotVariant.numbers(props.quaternion, "Quaternion") + local sc = GodotVariant.numbers(props.scale, "Vector3") + if not (pos or rot or deg or quat or sc) then + return nil + end + local r: { number } + if quat and #quat == 4 then + r = Mat4.fromQuat(quat) + elseif rot and #rot == 3 then + r = euler(rot[1], rot[2], rot[3]) + elseif deg and #deg == 3 then + r = euler(math.rad(deg[1]), math.rad(deg[2]), math.rad(deg[3])) + else + r = Mat4.identity() + end + local s = if sc and #sc == 3 then Mat4.scaling(sc[1], sc[2], sc[3]) else Mat4.identity() + local out = S.mul(r, s) + if pos and #pos == 3 then + out[13], out[14], out[15] = pos[1], pos[2], pos[3] + end + return out +end + +-- ------------------------------------------------------------------------------------------------ resources +local function path(ext: any): string? + if type(ext) ~= "table" then + return nil + end + local p = ext.attrs.path + return if type(p) == "string" then p else nil +end + +local function texture(ctx: Ctx, v: any): Types.TextureRef? + local id = idOf(v) + if not id or not isCtor(v) or v.type ~= "ExtResource" then + return nil + end + local key = "ext:" .. id + local idx = ctx.textures[key] + if not idx then + local p = path(ctx.ext[id]) + if not p then + return nil + end + local rel = string.gsub(p, "^res://", "") + local tex: Types.Texture = { name = rel, uri = rel } + local resolve = ctx.opts.resolve + if type(resolve) == "function" then + local ok, b = pcall(resolve, rel) + if ok and type(b) == "buffer" then + tex.data = b + end + end + table.insert(ctx.scene.textures, tex) + idx = #ctx.scene.textures + ctx.textures[key] = idx + end + return { texture = idx :: number } +end + +local MATERIALS = { StandardMaterial3D = true, ORMMaterial3D = true, SpatialMaterial = true } + +local function material(ctx: Ctx, v: any): number? + local id = idOf(v) + if not id or not isCtor(v) then + return nil + end + local key = v.type .. ":" .. id + if ctx.materials[key] then + return ctx.materials[key] + end + local sec = if v.type == "SubResource" then ctx.sub[id] else nil + local typ = if sec then sec.attrs.type else (if ctx.ext[id] then ctx.ext[id].attrs.type else nil) + local p = if sec then sec.props else {} + local m = S.material(if type(p.resource_name) == "string" then p.resource_name else nil) + local albedo = color(p.albedo_color, { 1, 1, 1, 1 }) + m.baseColor = linear(albedo) + m.metallic = num(p.metallic, 0) + m.roughness = num(p.roughness, 1) + local extras: { [string]: any } = { type = typ, albedo = albedo } + if MATERIALS[typ or ""] then + m.baseColorTexture = texture(ctx, p.albedo_texture) + m.metallicRoughnessTexture = texture(ctx, p.metallic_texture) or texture(ctx, p.roughness_texture) + if p.normal_enabled == true or p.normal_enabled == nil and p.normal_texture ~= nil then + m.normalTexture = texture(ctx, p.normal_texture) + if m.normalTexture and type(p.normal_scale) == "number" then + m.normalTexture.scale = p.normal_scale + end + end + if p.ao_enabled == true then + m.occlusionTexture = texture(ctx, p.ao_texture) + end + local emission = p.emission_enabled == true or p.flags_emission == true + if emission then + local e = color(p.emission, { 0, 0, 0, 1 }) + local energy = num(p.emission_energy_multiplier, num(p.emission_energy, 1)) + local le = linear(e) + m.emissive = { le[1], le[2], le[3] } + m.emissiveTexture = texture(ctx, p.emission_texture) + extras.emission = e + if energy ~= 1 then + m.extensions = { KHR_materials_emissive_strength = { emissiveStrength = energy } } + end + end + local transparency = num(p.transparency, if p.flags_transparent == true then 1 else 0) + if transparency == 1 or transparency == 4 then + m.alphaMode = "blend" + elseif transparency == 2 or transparency == 3 then + m.alphaMode = "mask" + m.alphaCutoff = num(p.alpha_scissor_threshold, 0.5) + end + m.doubleSided = num(p.cull_mode, num(p.params_cull_mode, 0)) == 2 + if num(p.shading_mode, 1) == 0 or p.flags_unshaded == true then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_unlit = {} + end + local uv = GodotVariant.numbers(p.uv1_scale, "Vector3") + local off = GodotVariant.numbers(p.uv1_offset, "Vector3") + if m.baseColorTexture and (uv or off) then + m.baseColorTexture.transform = { scale = if uv then { uv[1], uv[2] } else { 1, 1 }, offset = if off then { off[1], off[2] } else { 0, 0 } } + end + elseif not sec then + extras.path = path(ctx.ext[id]) + end + m.extras = { godot = extras } + table.insert(ctx.scene.materials, m) + ctx.materials[key] = #ctx.scene.materials + return #ctx.scene.materials +end + +-- a mesh resource (ArrayMesh or a primitive mesh) as a Scene mesh; overrides: surface index -> material value +local function mesh(ctx: Ctx, v: any, overrides: { [number]: any }?): (number?, string?) + local id = idOf(v) + if not id or not isCtor(v) then + return nil, nil + end + local key = v.type .. ":" .. id + if not overrides and ctx.meshes[key] then + return ctx.meshes[key], nil + end + local sec = if v.type == "SubResource" then ctx.sub[id] else nil + local out: Types.Mesh = { primitives = {} } + if not sec then + out.extras = { godot = { path = path(ctx.ext[id]) } } + else + local typ = sec.attrs.type + local p = sec.props + out.name = if type(p.resource_name) == "string" then p.resource_name else nil + local maxV = ctx.opts.maxVertices or 2 ^ 24 + if typ == "ArrayMesh" or typ == "Mesh" then + local surfaces: { any } = {} + if type(p._surfaces) == "table" then + surfaces = p._surfaces + else + for k = 0, 4096 do + local s = p["surfaces/" .. k] + if s == nil then + break + end + surfaces[k + 1] = s + end + end + local blend = 0 + for i, sd in surfaces do + local L, err = Surface.lists(sd, maxV) + if not L then + return nil, err + end + local prim = Surface.primitive(L) + local mv = if overrides and overrides[i - 1] ~= nil then overrides[i - 1] else (if type(sd) == "table" then sd.material else nil) + prim.material = material(ctx, mv) + if type(sd) == "table" and type(sd.name) == "string" then + prim.extras = { name = sd.name } + end + if type(sd) == "table" and type(sd.blend_shapes) == "table" then + blend = math.max(blend, #sd.blend_shapes) + end + table.insert(out.primitives, prim) + end + if blend > 0 then + out.extras = { godot = { blendShapes = blend } } + end + elseif Primitives.KINDS[typ] then + local a = Primitives.build(typ, p) + if a then + local prim = Surface.primitive(Surface.fromPrimitiveArrays(a)) + prim.material = material(ctx, if overrides and overrides[0] ~= nil then overrides[0] else p.material) + table.insert(out.primitives, prim) + end + out.extras = { godot = { primitive = typ } } + else + out.extras = { godot = { type = typ } } + end + end + table.insert(ctx.scene.meshes, out) + if not overrides then + ctx.meshes[key] = #ctx.scene.meshes + end + return #ctx.scene.meshes, nil +end + +-- ------------------------------------------------------------------------------------------------ nodes +local LIGHT: { [string]: "point" | "spot" | "directional" } = { + OmniLight3D = "point", SpotLight3D = "spot", DirectionalLight3D = "directional", + OmniLight = "point", SpotLight = "spot", DirectionalLight = "directional", +} +local CAMERA = { Camera3D = true, Camera = true, ClippedCamera = true, InterpolatedCamera = true, XRCamera3D = true } +local MESH = { MeshInstance3D = true, MeshInstance = true, CSGMesh3D = true, SoftBody3D = true } + +local THREE_D = { + Node3D = true, Spatial = true, MeshInstance3D = true, MeshInstance = true, Camera3D = true, Camera = true, + OmniLight3D = true, SpotLight3D = true, DirectionalLight3D = true, OmniLight = true, SpotLight = true, DirectionalLight = true, + Skeleton3D = true, Skeleton = true, BoneAttachment3D = true, Marker3D = true, Position3D = true, CollisionShape3D = true, + StaticBody3D = true, RigidBody3D = true, CharacterBody3D = true, Area3D = true, StaticBody = true, RigidBody = true, + KinematicBody = true, Area = true, CollisionShape = true, VisibleOnScreenNotifier3D = true, GPUParticles3D = true, + CPUParticles3D = true, Sprite3D = true, Label3D = true, Path3D = true, PathFollow3D = true, RemoteTransform3D = true, + CSGBox3D = true, CSGSphere3D = true, CSGCylinder3D = true, CSGMesh3D = true, CSGCombiner3D = true, XROrigin3D = true, + XRCamera3D = true, VehicleBody3D = true, VehicleWheel3D = true, NavigationRegion3D = true, ReflectionProbe = true, + GridMap = true, AnimatableBody3D = true, ClippedCamera = true, InterpolatedCamera = true, SoftBody3D = true, +} + +local function plainProps(sec: any): { [string]: any } + local out: { [string]: any } = {} + for _, k in sec.order do + out[k] = sec.props[k] + end + return out +end + +local function camera(ctx: Ctx, typ: string, p: any): number + local fmt2 = ctx.format <= 2 + local cam: Types.Camera + if num(p.projection, 0) == 1 then + local size = num(p.size, 1) + cam = { type = "orthographic", xmag = size / 2, ymag = size / 2, znear = num(p.near, 0.05), zfar = num(p.far, if fmt2 then 100 else 4000) } :: any + else + cam = { type = "perspective", yfov = math.rad(num(p.fov, if fmt2 then 70 else 75)), znear = num(p.near, 0.05), zfar = num(p.far, if fmt2 then 100 else 4000) } :: any + end + table.insert(ctx.scene.cameras, cam) + return #ctx.scene.cameras +end + +local function light(ctx: Ctx, typ: string, p: any): number + local kind = LIGHT[typ] + local c = color(p.light_color, { 1, 1, 1, 1 }) + local lc = linear(c) + local l: Types.Light = { type = kind, color = { lc[1], lc[2], lc[3] }, intensity = num(p.light_energy, 1) } + if kind == "point" then + l.range = num(p.omni_range, 5) + elseif kind == "spot" then + l.range = num(p.spot_range, 5) + l.outerCone = math.rad(num(p.spot_angle, 45)) + l.innerCone = 0 + end + table.insert(ctx.scene.lights, l) + return #ctx.scene.lights +end + +local scene: (ctx: Ctx, doc: GodotVariant.Document, into: number?) -> (number?, string?) + +-- an instanced scene (instance=ExtResource) through opts.resolve; its root becomes the instancing node +local function instance(ctx: Ctx, v: any, node: number): string? + local id = idOf(v) + local p = if id then path(ctx.ext[id]) else nil + local resolve = ctx.opts.resolve + if not p or type(resolve) ~= "function" or ctx.depth >= 8 then + return nil + end + local rel = string.gsub(p, "^res://", "") + local ok, b = pcall(resolve, rel) + if not ok or type(b) ~= "buffer" then + table.insert(ctx.warnings, "instance " .. rel .. " not resolved") + return nil + end + local doc, err = GodotVariant.parse(buffer.tostring(b), { maxDepth = ctx.opts.maxDepth }) + if not doc then + return "instance " .. rel .. ": " .. tostring(err) + end + local sub: Ctx = { + scene = ctx.scene, + doc = doc, + format = 3, + ext = {}, + sub = {}, + meshes = {}, + materials = {}, + textures = {}, + opts = ctx.opts, + depth = ctx.depth + 1, + warnings = ctx.warnings, + } + local _, serr = scene(sub, doc, node) + return serr +end + +scene = function(ctx: Ctx, doc: GodotVariant.Document, into: number?): (number?, string?) + local sc = ctx.scene + local header = doc.sections[1] + ctx.format = if header and type(header.attrs.format) == "number" then header.attrs.format else 3 + for _, sec in doc.sections do + local id = sec.attrs.id + if id ~= nil and (type(id) == "string" or type(id) == "number") then + if sec.tag == "ext_resource" then + ctx.ext[tostring(id)] = sec + elseif sec.tag == "sub_resource" then + ctx.sub[tostring(id)] = sec + end + end + end + local byPath: { [string]: number } = {} + local root: number? = nil + local connections = {} + for _, sec in doc.sections do + if sec.tag == "node" then + local a = sec.attrs + local name = if type(a.name) == "string" then a.name else "Node" + local parent = a.parent + local typ = if type(a.type) == "string" then a.type else nil + local p = sec.props + local idx: number + local isRoot = parent == nil + if isRoot and into then + idx = into + else + table.insert(sc.nodes, { name = name, children = {} }) + idx = #sc.nodes + end + local node = sc.nodes[idx] + if not (isRoot and into) then + node.name = name + end + if isRoot then + if root then + return nil, "two root nodes" + end + root = idx + byPath["."] = idx + if not into then + table.insert(sc.roots, idx) + end + else + local pp = if type(parent) == "string" then parent else "." + local pi = byPath[pp] + if not pi then + return nil, "node " .. name .. ": no parent " .. pp + end + table.insert(sc.nodes[pi].children, idx) + byPath[if pp == "." then name else pp .. "/" .. name] = idx + end + if a.instance ~= nil then + local err = instance(ctx, a.instance, idx) + if err then + return nil, err + end + end + local m = nodeMatrix(p) + if m then + node.matrix = m + end + local extras: { [string]: any } = node.extras and node.extras.godot or {} + extras.type = typ or extras.type + extras.properties = plainProps(sec) + if a.instance ~= nil then + extras.instance = path(ctx.ext[idOf(a.instance) or ""] ) + end + if type(a.groups) == "table" then + extras.groups = a.groups + end + if p.visible == false then + extras.visible = false + end + node.extras = { godot = extras } + if typ and not THREE_D[typ] then + extras.is2D = string.find(typ, "2D$") ~= nil or typ == "Node2D" or nil + end + if typ and MESH[typ] or p.mesh ~= nil then + local overrides: { [number]: any }? = nil + for k, v in p do + local si = string.match(k, "^surface_material_override/(%d+)$") or string.match(k, "^material/(%d+)$") + if si and v ~= GodotVariant.null then + overrides = overrides or {} + ;(overrides :: any)[tonumber(si) :: number] = v + end + end + if p.material_override ~= nil and p.material_override ~= GodotVariant.null then + overrides = overrides or {} + for k = 0, 63 do + if (overrides :: any)[k] == nil then + (overrides :: any)[k] = p.material_override + end + end + end + if p.mesh ~= nil then + local mi, err = mesh(ctx, p.mesh, overrides) + if err then + return nil, err + end + node.mesh = mi + end + end + if typ and CAMERA[typ] then + node.camera = camera(ctx, typ, p) + elseif typ and LIGHT[typ] then + node.light = light(ctx, typ, p) + extras.lightColor = color(p.light_color, { 1, 1, 1, 1 }) + end + elseif sec.tag == "connection" then + table.insert(connections, sec.attrs) + end + end + if #connections > 0 and not into then + (sc.meta.source :: any).connections = connections + end + return root, nil +end + +function Build.scene(doc: GodotVariant.Document, opts: any): (Types.Scene?, string?) + local sc = S.new() + sc.meta.up = "y" + sc.meta.unit = 1 + local header = doc.sections[1] + sc.meta.source = { + format = "godot", + tag = if header then header.tag else nil, + version = if header then header.attrs.format else nil, + uid = if header then header.attrs.uid else nil, + } + local ctx: Ctx = { + scene = sc, + doc = doc, + format = 3, + ext = {}, + sub = {}, + meshes = {}, + materials = {}, + textures = {}, + opts = opts or {}, + depth = 0, + warnings = {}, + } + if header and header.tag ~= "gd_scene" then + return nil, "unsupported: a " .. header.tag .. " file is a resource, not a scene (data/tres)" + end + local _, err = scene(ctx, doc, nil) + if err then + return nil, err + end + if #ctx.warnings > 0 then + (sc.meta.source :: any).warnings = ctx.warnings + end + return sc, nil +end + +return Build diff --git a/src/Rosetta/model/godot/Primitives.luau b/src/Rosetta/model/godot/Primitives.luau new file mode 100644 index 0000000..a019fb5 --- /dev/null +++ b/src/Rosetta/model/godot/Primitives.luau @@ -0,0 +1,273 @@ +--!strict +-- model/godot/Primitives: Godot's primitive meshes (BoxMesh, PlaneMesh, QuadMesh, SphereMesh, CylinderMesh) as Godot +-- builds them. Ported from Godot 4.4 scene/resources/3d/primitive_meshes.cpp (MIT, licenses/godot-LICENSE.txt): the +-- same vertex order, normals, tangents, UVs and (clockwise, Godot's front face) indices; no UV2. +local Primitives = {} + +export type Arrays = { points: { number }, normals: { number }, tangents: { number }, uvs: { number }, indices: { number } } + +local TAU = math.pi * 2 + +local function num(v: any, d: number): number + return if type(v) == "number" and v == v then v else d +end + +local function vec(v: any, n: number, d: { number }): { number } + if type(v) == "table" and type(v.args) == "table" and #v.args >= n then + local out = {} + for i = 1, n do + out[i] = num(v.args[i], d[i]) + end + return out + end + return d +end + +local function new(): Arrays + return { points = {}, normals = {}, tangents = {}, uvs = {}, indices = {} } +end + +local function add(a: Arrays, px: number, py: number, pz: number, nx: number, ny: number, nz: number, tx: number, ty: number, tz: number, u: number, v: number) + local p, nn, t, uv = a.points, a.normals, a.tangents, a.uvs + p[#p + 1], p[#p + 2], p[#p + 3] = px, py, pz + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz + t[#t + 1], t[#t + 2], t[#t + 3], t[#t + 4] = tx, ty, tz, 1 + uv[#uv + 1], uv[#uv + 2] = u, v +end + +-- the two triangles of a grid cell: p0 p1 t0, p1 t1 t0 (prev row, this row) +local function quad(a: Arrays, p0: number, p1: number, t0: number, t1: number) + local ix = a.indices + local n = #ix + ix[n + 1], ix[n + 2], ix[n + 3], ix[n + 4], ix[n + 5], ix[n + 6] = p0, p1, t0, p1, t1, t0 +end + +-- BoxMesh::create_mesh_array +local function box(props: any): Arrays + local size = vec(props.size, 3, { 1, 1, 1 }) + local sw, sh, sd = math.max(0, num(props.subdivide_width, 0)), math.max(0, num(props.subdivide_height, 0)), math.max(0, num(props.subdivide_depth, 0)) + local a = new() + local onethird, twothirds = 1 / 3, 2 / 3 + local sx, sy, sz = -size[1] / 2, -size[2] / 2, -size[3] / 2 + local point = 0 + local function faces(rows: number, cols: number, step: (number, number) -> ()) + local thisrow, prevrow = point, 0 + for j = 0, rows + 1 do + for i = 0, cols + 1 do + step(i, j) + point += 2 + if i > 0 and j > 0 then + local i2 = i * 2 + quad(a, prevrow + i2 - 2, prevrow + i2, thisrow + i2 - 2, thisrow + i2) + quad(a, prevrow + i2 - 1, prevrow + i2 + 1, thisrow + i2 - 1, thisrow + i2 + 1) + end + end + prevrow = thisrow + thisrow = point + end + end + -- front + back + faces(sh, sw, function(i: number, j: number) + local v = j / (2 * (sh + 1)) + local u = i / (3 * (sw + 1)) + local x = sx + i * size[1] / (sw + 1) + local y = sy + j * size[2] / (sh + 1) + add(a, x, -y, -sz, 0, 0, 1, 1, 0, 0, u, v) + add(a, -x, -y, sz, 0, 0, -1, -1, 0, 0, twothirds + u, v) + end) + -- left + right + faces(sh, sd, function(i: number, j: number) + local v = j / (2 * (sh + 1)) + local u = i / (3 * (sd + 1)) + local z = sz + i * size[3] / (sd + 1) + local y = sy + j * size[2] / (sh + 1) + add(a, -sx, -y, -z, 1, 0, 0, 0, 0, -1, onethird + u, v) + add(a, sx, -y, z, -1, 0, 0, 0, 0, 1, u, 0.5 + v) + end) + -- top + bottom + faces(sd, sw, function(i: number, j: number) + local v = j / (2 * (sd + 1)) + local u = i / (3 * (sw + 1)) + local x = sx + i * size[1] / (sw + 1) + local z = sz + j * size[3] / (sd + 1) + add(a, -x, -sy, -z, 0, 1, 0, -1, 0, 0, onethird + u, 0.5 + v) + add(a, x, sy, -z, 0, -1, 0, 1, 0, 0, twothirds + u, 0.5 + v) + end) + return a +end + +-- PlaneMesh::_create_mesh_array (QuadMesh: FACE_Z, size 1 x 1) +local function plane(props: any, isQuad: boolean): Arrays + local size = vec(props.size, 2, if isQuad then { 1, 1 } else { 2, 2 }) + local sw, sd = math.max(0, num(props.subdivide_width, 0)), math.max(0, num(props.subdivide_depth, 0)) + local off = vec(props.center_offset, 3, { 0, 0, 0 }) + local orient = num(props.orientation, if isQuad then 2 else 1) + local a = new() + local nx, ny, nz = 0, 1, 0 + if orient == 0 then + nx, ny, nz = 1, 0, 0 + elseif orient == 2 then + nx, ny, nz = 0, 0, 1 + end + local point, thisrow, prevrow = 0, 0, 0 + local z = -size[2] / 2 + for j = 0, sd + 1 do + local x = -size[1] / 2 + for i = 0, sw + 1 do + local u, v = i / (sw + 1), j / (sd + 1) + local px: number, py: number, pz: number = 0, 0, 0 + if orient == 0 then + px, py, pz = 0, z, x + elseif orient == 2 then + px, py, pz = -x, z, 0 + else + px, py, pz = -x, 0, -z + end + if orient == 0 then + add(a, px + off[1], py + off[2], pz + off[3], nx, ny, nz, 0, 0, -1, 1 - u, 1 - v) + else + add(a, px + off[1], py + off[2], pz + off[3], nx, ny, nz, 1, 0, 0, 1 - u, 1 - v) + end + point += 1 + if i > 0 and j > 0 then + quad(a, prevrow + i - 1, prevrow + i, thisrow + i - 1, thisrow + i) + end + x += size[1] / (sw + 1) + end + z += size[2] / (sd + 1) + prevrow = thisrow + thisrow = point + end + return a +end + +-- SphereMesh::create_mesh_array +local function sphere(props: any): Arrays + local radius, height = num(props.radius, 0.5), num(props.height, 1) + local radial, rings = math.max(1, num(props.radial_segments, 64)), math.max(1, num(props.rings, 32)) + local hemi = props.is_hemisphere == true + local scale = height / radius * (if hemi then 1 else 0.5) + local a = new() + local point, thisrow, prevrow = 0, 0, 0 + for j = 0, rings + 1 do + local v = j / (rings + 1) + local w: number, y: number = 0, -1 + if j ~= rings + 1 then + w = math.sin(math.pi * v) + y = math.cos(math.pi * v) + end + for i = 0, radial do + local u = i / radial + local x: number, z: number = 0, 1 + if i ~= radial then + x = math.sin(u * TAU) + z = math.cos(u * TAU) + end + if hemi and y < 0 then + add(a, x * radius * w, 0, z * radius * w, 0, -1, 0, z, 0, -x, u, v) + else + local nx, ny, nz = x * w * scale, y, z * w * scale + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + add(a, x * w * radius, y * scale * radius, z * w * radius, nx, ny, nz, z, 0, -x, u, v) + end + point += 1 + if i > 0 and j > 0 then + quad(a, prevrow + i - 1, prevrow + i, thisrow + i - 1, thisrow + i) + end + end + prevrow = thisrow + thisrow = point + end + return a +end + +-- CylinderMesh::create_mesh_array +local function cylinder(props: any): Arrays + local top, bottom, height = num(props.top_radius, 0.5), num(props.bottom_radius, 0.5), num(props.height, 2) + local radial, rings = math.max(1, num(props.radial_segments, 64)), math.max(0, num(props.rings, 4)) + local a = new() + local point, thisrow, prevrow = 0, 0, 0 + local sideY = (bottom - top) / height + for j = 0, rings + 1 do + local v = j / (rings + 1) + local radius = top + (bottom - top) * v + local y = height * 0.5 - height * v + for i = 0, radial do + local u = i / radial + local x: number, z: number = 0, 1 + if i ~= radial then + x = math.sin(u * TAU) + z = math.cos(u * TAU) + end + local l = math.sqrt(x * x + sideY * sideY + z * z) + add(a, x * radius, y, z * radius, x / l, sideY / l, z / l, z, 0, -x, u, v * 0.5) + point += 1 + if i > 0 and j > 0 then + quad(a, prevrow + i - 1, prevrow + i, thisrow + i - 1, thisrow + i) + end + end + prevrow = thisrow + thisrow = point + end + local ix = a.indices + for _, cap in { { top, height * 0.5, 1 }, { bottom, height * -0.5, -1 } } do + local r: number, y: number, ny: number = cap[1] :: number, cap[2] :: number, cap[3] :: number + local enabled = if ny > 0 then props.cap_top ~= false else props.cap_bottom ~= false + if enabled and r > 0 then + thisrow = point + add(a, 0, y, 0, 0, ny, 0, 1, 0, 0, if ny > 0 then 0.25 else 0.75, 0.75) + point += 1 + for i = 0, radial do + local t = i / radial + local x: number, z: number = 0, 1 + if i ~= radial then + x = math.sin(t * TAU) + z = math.cos(t * TAU) + end + local u = if ny > 0 then (x + 1) * 0.25 else 0.5 + (x + 1) * 0.25 + local v = if ny > 0 then 0.5 + (z + 1) * 0.25 else 1 - (z + 1) * 0.25 + add(a, x * r, y, z * r, 0, ny, 0, 1, 0, 0, u, v) + point += 1 + if i > 0 then + if ny > 0 then + ix[#ix + 1], ix[#ix + 2], ix[#ix + 3] = thisrow, point - 1, point - 2 + else + ix[#ix + 1], ix[#ix + 2], ix[#ix + 3] = thisrow, point - 2, point - 1 + end + end + end + end + end + return a +end + +Primitives.KINDS = ({ BoxMesh = true, PlaneMesh = true, QuadMesh = true, SphereMesh = true, CylinderMesh = true, CubeMesh = true }) :: { [string]: boolean } + +function Primitives.build(kind: string, props: any): Arrays? + local a: Arrays + if kind == "BoxMesh" or kind == "CubeMesh" then + a = box(props) + elseif kind == "PlaneMesh" then + a = plane(props, false) + elseif kind == "QuadMesh" then + a = plane(props, true) + elseif kind == "SphereMesh" then + a = sphere(props) + elseif kind == "CylinderMesh" then + a = cylinder(props) + else + return nil + end + if props.flip_faces == true then + local ix = a.indices + for k = 1, #ix - 2, 3 do + ix[k + 1], ix[k + 2] = ix[k + 2], ix[k + 1] + end + end + return a +end + +return Primitives diff --git a/src/Rosetta/model/godot/Surface.luau b/src/Rosetta/model/godot/Surface.luau new file mode 100644 index 0000000..8f0637d --- /dev/null +++ b/src/Rosetta/model/godot/Surface.luau @@ -0,0 +1,483 @@ +--!strict +-- model/godot/Surface: ArrayMesh surfaces <-> Scene primitives. Godot 4.2+ surfaces (format version 2: vertex_data = +-- positions then octahedral normal / tangent pairs, attribute_data = colour / UV / UV2 / custom per vertex, +-- skin_data = bones + weights, index_data u16 / u32; RenderingServer mesh_create_surface_data_from_arrays), and the +-- "arrays" surfaces of format-2 .escn files (Godot 3 ArrayType order). Godot's front faces are clockwise: triangle +-- winding is reversed both ways. Not supported: compressed attributes, format version 1 (Godot 4.0 / 4.1), Godot 3 +-- binary array_data, blend shapes (counted in extras). +local Types = require("@rosetta/Types") +local GodotVariant = require("@rosetta/codecs/text/GodotVariant") +local Primitives = require("@rosetta/model/godot/Primitives") + +local Surface = {} + +local S = Types.Scene + +local function arr(n: number): { number } + return table.create(n) :: any +end + +local function bit(f: number, i: number): boolean + return math.floor(f / 2 ^ i) % 2 == 1 +end + +-- Vector3::octahedron_decode +local function octDecode(x: number, y: number): (number, number, number) + local fx, fy = x * 2 - 1, y * 2 - 1 + local nz = 1 - math.abs(fx) - math.abs(fy) + local t = math.clamp(-nz, 0, 1) + fx += if fx >= 0 then -t else t + fy += if fy >= 0 then -t else t + local l = math.sqrt(fx * fx + fy * fy + nz * nz) + if l == 0 then + return 0, 0, 1 + end + return fx / l, fy / l, nz / l +end + +-- Vector3::octahedron_encode +local function octEncode(x: number, y: number, z: number): (number, number) + local s = math.abs(x) + math.abs(y) + math.abs(z) + if s == 0 then + return 0.5, 0.5 + end + x, y, z = x / s, y / s, z / s + local ox, oy + if z >= 0 then + ox, oy = x, y + else + ox = (1 - math.abs(y)) * (if x >= 0 then 1 else -1) + oy = (1 - math.abs(x)) * (if y >= 0 then 1 else -1) + end + return ox * 0.5 + 0.5, oy * 0.5 + 0.5 +end + +local function u16(v: number): number + return math.clamp(math.floor(v * 65535), 0, 65535) +end + +local CUSTOM_SIZE = { [0] = 4, 4, 4, 8, 4, 8, 12, 16 } + +export type Lists = { + points: { number }, + normals: { number }?, + tangents: { number }?, + colors: buffer?, + uvs: { number }?, + uv2s: { number }?, + joints: { number }?, + weights: { number }?, + jointsPer: number, + indices: { number }?, + mode: string, +} + +-- a Godot 4 surface dictionary (format version 2) into lists +local function binary(d: any, maxVertices: number): (Lists?, string?) + local f = tonumber(d.format) or 0 + local vc = tonumber(d.vertex_count) or 0 + if vc < 0 or vc > maxVertices or vc % 1 ~= 0 then + return nil, "limit: vertex count " .. tostring(d.vertex_count) + end + if bit(f, 29) then + return nil, "unsupported: compressed surface attributes" + end + if not bit(f, 35) then + return nil, "unsupported: surface format version 1 (Godot 4.0 / 4.1)" + end + local vd = GodotVariant.bytes(d.vertex_data) + if not vd then + return nil, "surface without vertex_data" + end + local is2D = bit(f, 25) + local pstride = if is2D then 8 else 12 + local hasN, hasT = bit(f, 1), bit(f, 2) + local ntStride = (if hasN then 4 else 0) + (if hasT then 4 else 0) + if buffer.len(vd) < vc * (pstride + ntStride) then + return nil, "truncated vertex_data" + end + local L: Lists = { points = arr(vc * 3), jointsPer = 4, mode = "triangles" } + local P = L.points + for i = 0, vc - 1 do + local o = i * pstride + P[i * 3 + 1] = buffer.readf32(vd, o) + P[i * 3 + 2] = buffer.readf32(vd, o + 4) + P[i * 3 + 3] = if is2D then 0 else buffer.readf32(vd, o + 8) + end + if ntStride > 0 then + local base = vc * pstride + local N, T = if hasN then arr(vc * 3) else nil, if hasT then arr(vc * 4) else nil + for i = 0, vc - 1 do + local o = base + i * ntStride + if N then + local x, y, z = octDecode(buffer.readu16(vd, o) / 65535, buffer.readu16(vd, o + 2) / 65535) + N[i * 3 + 1], N[i * 3 + 2], N[i * 3 + 3] = x, y, z + o += 4 + end + if T then + local tx = buffer.readu16(vd, o) / 65535 + local ty = buffer.readu16(vd, o + 2) / 65535 * 2 - 1 + local sign = if ty >= 0 then 1 else -1 + local x, y, z = octDecode(tx, math.abs(ty)) + T[i * 4 + 1], T[i * 4 + 2], T[i * 4 + 3], T[i * 4 + 4] = x, y, z, sign + end + end + L.normals, L.tangents = N, T + end + -- attribute stream + local hasC, hasUV, hasUV2 = bit(f, 3), bit(f, 4), bit(f, 5) + local astride = (if hasC then 4 else 0) + (if hasUV then 8 else 0) + (if hasUV2 then 8 else 0) + for k = 0, 3 do + if bit(f, 6 + k) then + astride += CUSTOM_SIZE[math.floor(f / 2 ^ (13 + 3 * k)) % 8] + end + end + if astride > 0 then + local ad = GodotVariant.bytes(d.attribute_data) + if not ad or buffer.len(ad) < vc * astride then + return nil, "truncated attribute_data" + end + local C = if hasC then buffer.create(vc * 4) else nil + local UV, UV2 = if hasUV then arr(vc * 2) else nil, if hasUV2 then arr(vc * 2) else nil + for i = 0, vc - 1 do + local o = i * astride + if C then + buffer.writeu32(C, i * 4, buffer.readu32(ad, o)) + o += 4 + end + if UV then + UV[i * 2 + 1], UV[i * 2 + 2] = buffer.readf32(ad, o), buffer.readf32(ad, o + 4) + o += 8 + end + if UV2 then + UV2[i * 2 + 1], UV2[i * 2 + 2] = buffer.readf32(ad, o), buffer.readf32(ad, o + 4) + end + end + L.colors, L.uvs, L.uv2s = C, UV, UV2 + end + -- skin stream: bones then weights per vertex + local hasB, hasW = bit(f, 10), bit(f, 11) + if hasB and hasW then + local per = if bit(f, 27) then 8 else 4 + local sd = GodotVariant.bytes(d.skin_data) + if sd and buffer.len(sd) >= vc * per * 4 then + local J, W = arr(vc * per), arr(vc * per) + for i = 0, vc - 1 do + local o = i * per * 4 + for c = 0, per - 1 do + J[i * per + c + 1] = buffer.readu16(sd, o + c * 2) + W[i * per + c + 1] = buffer.readu16(sd, o + per * 2 + c * 2) / 65535 + end + end + L.joints, L.weights, L.jointsPer = J, W, per + end + end + local ic = tonumber(d.index_count) or 0 + if bit(f, 12) and ic > 0 then + local id = GodotVariant.bytes(d.index_data) + local size = if vc <= 65536 then 2 else 4 + if not id or buffer.len(id) < ic * size then + return nil, "truncated index_data" + end + local I = arr(ic) + for i = 0, ic - 1 do + local v = if size == 2 then buffer.readu16(id, i * 2) else buffer.readu32(id, i * 4) + if v >= vc then + return nil, "index out of range" + end + I[i + 1] = v + end + L.indices = I + end + local prim = tonumber(d.primitive) or 3 + L.mode = if prim == 0 then "points" elseif prim == 1 then "lines" elseif prim == 2 then "line_strip" elseif prim == 4 then "triangle_strip" else "triangles" + return L, nil +end + +local function nums(v: any): { number }? + return GodotVariant.numbers(v) +end + +-- a format-2 "arrays" surface (Godot 3 Mesh::ArrayType: vertex, normal, tangent, color, uv, uv2, bones, weights, index) +local function arrays(d: any, maxVertices: number): (Lists?, string?) + local a = d.arrays + local P = nums(a[1]) + if not P or #P % 3 ~= 0 then + return nil, "surface without a vertex array" + end + local vc = #P // 3 + if vc > maxVertices then + return nil, "limit: vertex count " .. vc + end + local L: Lists = { points = P, jointsPer = 4, mode = "triangles" } + local N, T = nums(a[2]), nums(a[3]) + L.normals = if N and #N == vc * 3 then N else nil + L.tangents = if T and #T == vc * 4 then T else nil + local C = nums(a[4]) + if C and #C == vc * 4 then + local cb = buffer.create(vc * 4) + for i = 1, #C do + buffer.writeu8(cb, i - 1, math.clamp(math.floor(C[i] * 255 + 0.5), 0, 255)) + end + L.colors = cb + end + local UV, UV2 = nums(a[5]), nums(a[6]) + L.uvs = if UV and #UV == vc * 2 then UV else nil + L.uv2s = if UV2 and #UV2 == vc * 2 then UV2 else nil + local B, W = nums(a[7]), nums(a[8]) + if B and W and #B == vc * 4 and #W == vc * 4 then + L.joints, L.weights = B, W + end + local I = nums(a[9]) + if I and #I > 0 then + for _, v in I do + if v < 0 or v >= vc then + return nil, "index out of range" + end + end + L.indices = I + end + local prim = tonumber(d.primitive) or 4 + L.mode = if prim == 0 then "points" elseif prim == 1 then "lines" elseif prim == 2 then "line_strip" elseif prim == 3 then "line_loop" elseif prim == 5 then "triangle_strip" elseif prim == 6 then "triangle_fan" else "triangles" + return L, nil +end + +function Surface.lists(d: any, maxVertices: number): (Lists?, string?) + if type(d) ~= "table" then + return nil, "bad surface" + end + if type(d.arrays) == "table" then + return arrays(d, maxVertices) + end + if d.array_data ~= nil then + return nil, "unsupported: Godot 3 binary surface (array_data)" + end + return binary(d, maxVertices) +end + +function Surface.fromPrimitiveArrays(a: Primitives.Arrays): Lists + return { points = a.points, normals = a.normals, tangents = a.tangents, uvs = a.uvs, indices = a.indices, jointsPer = 4, mode = "triangles" } +end + +local function acc(list: { number }, comps: number, t: string?): Types.Accessor + local count = #list // comps + local typ = t or "f32" + local a = S.accessor(nil, typ :: any, comps, count) + local d = a.data + for i, v in list do + if typ == "f32" then + buffer.writef32(d, (i - 1) * 4, v) + elseif typ == "u16" then + buffer.writeu16(d, (i - 1) * 2, v) + end + end + return a +end + +-- lists into a Primitive; triangles (and strips / fans, made into triangles) get counter-clockwise winding +function Surface.primitive(L: Lists): Types.Primitive + local n = #L.points // 3 + local attrs: { [string]: Types.Accessor } = { POSITION = acc(L.points, 3) } + if L.normals then + attrs.NORMAL = acc(L.normals :: { number }, 3) + end + if L.tangents then + attrs.TANGENT = acc(L.tangents :: { number }, 4) + end + if L.colors then + attrs.COLOR_0 = S.accessor(L.colors, "unorm8", 4, n) + end + if L.uvs then + attrs.TEXCOORD_0 = acc(L.uvs :: { number }, 2) + end + if L.uv2s then + attrs.TEXCOORD_1 = acc(L.uv2s :: { number }, 2) + end + if L.joints and L.weights then + local per = L.jointsPer + for set = 0, per // 4 - 1 do + local J, W = arr(n * 4), arr(n * 4) + for i = 0, n - 1 do + for c = 0, 3 do + J[i * 4 + c + 1] = (L.joints :: { number })[i * per + set * 4 + c + 1] or 0 + W[i * 4 + c + 1] = (L.weights :: { number })[i * per + set * 4 + c + 1] or 0 + end + end + attrs["JOINTS_" .. set] = acc(J, 4, "u16") + attrs["WEIGHTS_" .. set] = acc(W, 4) + end + end + local mode = L.mode + local idx = L.indices + if mode == "triangles" or mode == "triangle_strip" or mode == "triangle_fan" then + local src: { number } + if idx then + src = idx + else + src = arr(n) + for i = 1, n do + src[i] = i - 1 + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #src - 2, 3 do + table.insert(out, src[k]) + table.insert(out, src[k + 2]) + table.insert(out, src[k + 1]) + end + elseif mode == "triangle_strip" then + for k = 1, #src - 2 do + local a, b, c = src[k], src[k + 1], src[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(out, a) + table.insert(out, c) + table.insert(out, b) + end + else + for k = 2, #src - 1 do + table.insert(out, src[1]) + table.insert(out, src[k + 1]) + table.insert(out, src[k]) + end + end + idx = out + mode = "triangles" + end + local prim: Types.Primitive = { attributes = attrs, mode = mode :: any } + if idx then + prim.indices = acc(idx :: { number }, 1, "u32") + local d = (prim.indices :: Types.Accessor).data + for i, v in idx :: { number } do + buffer.writeu32(d, (i - 1) * 4, v) + end + end + return prim +end + +-- ------------------------------------------------------------------------------------------------ write +local function perpendicular(x: number, y: number, z: number): (number, number, number) + local ax, ay, az = if math.abs(y) < 0.9 then 0 else 1, if math.abs(y) < 0.9 then 1 else 0, 0 + local tx, ty, tz = ay * z - az * y, az * x - ax * z, ax * y - ay * x + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l == 0 then + return 1, 0, 0 + end + return tx / l, ty / l, tz / l +end + +-- a triangle Primitive as a Godot 4 surface dictionary (format version 2, uncompressed); nil for other modes +function Surface.encode(prim: Types.Primitive, triangles: { number }): any + local a = prim.attributes + local pos = a.POSITION + local rp = S.reader(pos) + if not rp then + return nil + end + local vc = pos.count + local an: any, at: any, ac: any, a0: any, a1: any = a.NORMAL, a.TANGENT, a.COLOR_0, a.TEXCOORD_0, a.TEXCOORD_1 + local rn = if an then S.reader(an) else nil + local rt = if at then S.reader(at) else nil + local rc = if ac then S.reader(ac) else nil + local cc = if ac then ac.components else 0 + local ru = if a0 then S.reader(a0) else nil + local ru2 = if a1 then S.reader(a1) else nil + local flags = 1 + 2 ^ 35 + if rn then + flags += 2 + 4 + end + local ntStride = if rn then 8 else 0 + local vd = buffer.create(vc * (12 + ntStride)) + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, vc - 1 do + for c = 0, 2 do + local v = rp(i, c) + buffer.writef32(vd, i * 12 + c * 4, v) + lo[c + 1], hi[c + 1] = math.min(lo[c + 1], v), math.max(hi[c + 1], v) + end + if rn then + local nx, ny, nz = rn(i, 0), rn(i, 1), rn(i, 2) + local o = vc * 12 + i * 8 + local ox, oy = octEncode(nx, ny, nz) + buffer.writeu16(vd, o, u16(ox)) + buffer.writeu16(vd, o + 2, u16(oy)) + local tx, ty, tz, sign + if rt then + tx, ty, tz, sign = rt(i, 0), rt(i, 1), rt(i, 2), if at.components >= 4 then rt(i, 3) else 1 + else + tx, ty, tz = perpendicular(nx, ny, nz) + sign = 1 + end + -- Vector3::octahedron_tangent_encode + local qx, qy = octEncode(tx, ty, tz) + qy = math.max(qy, 1 / 32767) * 0.5 + 0.5 + qy = if sign >= 0 then qy else 1 - qy + buffer.writeu16(vd, o + 4, u16(qx)) + buffer.writeu16(vd, o + 6, u16(qy)) + end + end + local astride = (if rc then 4 else 0) + (if ru then 8 else 0) + (if ru2 then 8 else 0) + local ad: buffer? = nil + if astride > 0 then + flags += (if rc then 8 else 0) + (if ru then 16 else 0) + (if ru2 then 32 else 0) + local b = buffer.create(vc * astride) + for i = 0, vc - 1 do + local o = i * astride + if rc then + for c = 0, 3 do + local v = if c < cc then rc(i, c) else 1 + buffer.writeu8(b, o + c, math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + o += 4 + end + if ru then + buffer.writef32(b, o, ru(i, 0)) + buffer.writef32(b, o + 4, ru(i, 1)) + o += 8 + end + if ru2 then + buffer.writef32(b, o, ru2(i, 0)) + buffer.writef32(b, o + 4, ru2(i, 1)) + end + end + ad = b + end + local isize = if vc <= 65536 then 2 else 4 + local id = buffer.create(#triangles * isize) + -- counter-clockwise -> Godot's clockwise + for k = 0, #triangles // 3 - 1 do + local t = { triangles[k * 3 + 1], triangles[k * 3 + 3], triangles[k * 3 + 2] } + for c = 0, 2 do + if isize == 2 then + buffer.writeu16(id, (k * 3 + c) * 2, t[c + 1]) + else + buffer.writeu32(id, (k * 3 + c) * 4, t[c + 1]) + end + end + end + flags += 4096 + if vc == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local keys = { "aabb" } + local out: { [string]: any } = { aabb = GodotVariant.ctor("AABB", { lo[1], lo[2], lo[3], hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) } + if ad then + out.attribute_data = ad + table.insert(keys, "attribute_data") + end + out.format = flags + out.index_count = #triangles + out.index_data = id + out.primitive = 3 + out.uv_scale = GodotVariant.ctor("Vector4", { 0, 0, 0, 0 }) + out.vertex_count = vc + out.vertex_data = vd + for _, k in { "format", "index_count", "index_data", "material", "primitive", "uv_scale", "vertex_count", "vertex_data" } do + table.insert(keys, k) + end + return Types.object(out, keys) +end + +return Surface diff --git a/src/Rosetta/model/godot/Write.luau b/src/Rosetta/model/godot/Write.luau new file mode 100644 index 0000000..94f9c96 --- /dev/null +++ b/src/Rosetta/model/godot/Write.luau @@ -0,0 +1,327 @@ +--!strict +-- model/godot/Write: a Scene as a Godot 4 text scene (format 3): Node3D / MeshInstance3D / Camera3D / light nodes +-- with Transform3D transforms, ArrayMesh sub-resources (model/godot/Surface), StandardMaterial3D (linear colours back +-- to sRGB) and Texture2D ext_resources for textures with a uri. Several scene roots go under a "Root" Node3D. +local Types = require("@rosetta/Types") +local GodotVariant = require("@rosetta/codecs/text/GodotVariant") +local Surface = require("@rosetta/model/godot/Surface") + +local Write = {} + +local S = Types.Scene +local ctor = GodotVariant.ctor + +type Section = GodotVariant.Section + +local function section(tag: string, attrs: { any }): Section + local a, order = {}, {} + local i = 1 + while attrs[i] ~= nil do + if attrs[i + 1] ~= nil then + a[attrs[i]] = attrs[i + 1] + table.insert(order, attrs[i]) + end + i += 2 + end + return { tag = tag, attrs = a, attrOrder = order, props = {}, order = {} } +end + +local function prop(sec: Section, k: string, v: any) + if v == nil then + return + end + if sec.props[k] == nil then + table.insert(sec.order, k) + end + sec.props[k] = v +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + if c <= 0.0031308 then + return c * 12.92 + end + return 1.055 * c ^ (1 / 2.4) - 0.055 +end + +local function srgbColor(c: { number }?, alpha: number?): any + local v = c or { 1, 1, 1 } + return ctor("Color", { toSrgb(v[1] or 1), toSrgb(v[2] or 1), toSrgb(v[3] or 1), alpha or v[4] or 1 }) +end + +local function transform(m: { number }): any + return ctor("Transform3D", { 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 + +local function isIdentity(m: { number }): boolean + for i = 1, 16 do + if math.abs(m[i] - S.IDENTITY[i]) > 1e-12 then + return false + end + end + return true +end + +local function safeName(s: string?, fallback: string): string + local n = string.gsub(s or "", "[%.:@/\"%%]", "_") + return if n == "" then fallback else n +end + +local function triangles(prim: any): { number }? + local mode = prim.mode or "triangles" + local pos = prim.attributes and prim.attributes.POSITION + if type(pos) ~= "table" then + return nil + end + local idx: { number } = {} + if prim.indices then + local rd = S.reader(prim.indices) + if not rd then + return nil + end + for i = 0, prim.indices.count - 1 do + idx[i + 1] = rd(i, 0) + end + else + for i = 0, pos.count - 1 do + idx[i + 1] = i + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b = idx[k], idx[k + 1] + if k % 2 == 0 then + a, b = b, a + end + table.insert(out, a) + table.insert(out, b) + table.insert(out, idx[k + 2]) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + elseif mode == "polygons" and prim.faces then + local rd = S.reader(prim.faces) + local at = 1 + if rd then + for f = 0, prim.faces.count - 1 do + local size = rd(f, 0) + for k = 1, size - 2 do + table.insert(out, idx[at]) + table.insert(out, idx[at + k]) + table.insert(out, idx[at + k + 1]) + end + at += size + end + end + else + return nil + end + for _, v in out do + if v < 0 or v >= pos.count then + return nil + end + end + return out +end + +function Write.document(scene: any): (GodotVariant.Document?, string?) + local sections: { Section } = {} + local ext: { Section } = {} + local sub: { Section } = {} + local nodes: { Section } = {} + local texId: { [number]: string } = {} + local matId: { [number]: string } = {} + local meshId: { [number]: string } = {} + local textures = scene.textures or {} + local function textureRef(ref: any): any + if type(ref) ~= "table" then + return nil + end + local i = ref.texture + local tex = textures[i] + if not tex or type(tex.uri) ~= "string" or tex.uri == "" or string.sub(tex.uri, 1, 5) == "data:" then + return nil + end + if not texId[i] then + local id = (#ext + 1) .. "_tex" + texId[i] = id + local p = if string.find(tex.uri, "^res://") then tex.uri else "res://" .. tex.uri + table.insert(ext, section("ext_resource", { "type", "Texture2D", "path", p, "id", id })) + end + return ctor("ExtResource", { texId[i] }) + end + for i, m in scene.materials or {} do + local id = "StandardMaterial3D_" .. i + matId[i] = id + local sec = section("sub_resource", { "type", "StandardMaterial3D", "id", id }) + if type(m.name) == "string" then + prop(sec, "resource_name", m.name) + end + local mode = m.alphaMode + if mode == "blend" then + prop(sec, "transparency", 1) + elseif mode == "mask" then + prop(sec, "transparency", 2) + prop(sec, "alpha_scissor_threshold", m.alphaCutoff or 0.5) + end + if m.doubleSided then + prop(sec, "cull_mode", 2) + end + local unlit = type(m.extensions) == "table" and m.extensions.KHR_materials_unlit ~= nil + if unlit then + prop(sec, "shading_mode", 0) + end + local bc = if type(m.baseColor) == "table" then m.baseColor else { 1, 1, 1, 1 } + prop(sec, "albedo_color", srgbColor(bc, bc[4] or 1)) + prop(sec, "albedo_texture", textureRef(m.baseColorTexture)) + prop(sec, "metallic", m.metallic or 0) + prop(sec, "roughness", m.roughness or 1) + local mr = textureRef(m.metallicRoughnessTexture) + if mr then + prop(sec, "metallic_texture", mr) + prop(sec, "metallic_texture_channel", 2) + prop(sec, "roughness_texture", mr) + prop(sec, "roughness_texture_channel", 1) + end + local e = m.emissive + if type(e) == "table" and ((e[1] or 0) > 0 or (e[2] or 0) > 0 or (e[3] or 0) > 0) or m.emissiveTexture then + prop(sec, "emission_enabled", true) + prop(sec, "emission", srgbColor(e, 1)) + local strength = type(m.extensions) == "table" and m.extensions.KHR_materials_emissive_strength + if type(strength) == "table" and type(strength.emissiveStrength) == "number" then + prop(sec, "emission_energy_multiplier", strength.emissiveStrength) + end + prop(sec, "emission_texture", textureRef(m.emissiveTexture)) + end + local nt = textureRef(m.normalTexture) + if nt then + prop(sec, "normal_enabled", true) + prop(sec, "normal_texture", nt) + end + local ao = textureRef(m.occlusionTexture) + if ao then + prop(sec, "ao_enabled", true) + prop(sec, "ao_texture", ao) + end + table.insert(sub, sec) + end + for i, mesh in scene.meshes or {} do + local surfaces = {} + for _, prim in mesh.primitives or {} do + local tris = triangles(prim) + if tris then + local sd = Surface.encode(prim, tris) + if sd then + if prim.material and matId[prim.material] then + Types.set(sd, "material", ctor("SubResource", { matId[prim.material] })) + end + table.insert(surfaces, sd) + end + end + end + if #surfaces > 0 then + local id = "ArrayMesh_" .. i + meshId[i] = id + local sec = section("sub_resource", { "type", "ArrayMesh", "id", id }) + if type(mesh.name) == "string" then + prop(sec, "resource_name", mesh.name) + end + prop(sec, "_surfaces", surfaces) + table.insert(sub, sec) + end + end + local all = scene.nodes or {} + local roots = scene.roots or {} + local single = #roots == 1 and all[roots[1]] ~= nil + local visited: { [number]: boolean } = {} + local function emit(i: number, parent: string?, used: { [string]: boolean }, depth: number) + local node = all[i] + if not node or visited[i] or depth > 512 then + return + end + visited[i] = true + local base = safeName(node.name, "Node" .. i) + local name, k = base, 1 + while used[name] do + k += 1 + name = base .. k + end + used[name] = true + local cam = if node.camera then (scene.cameras or {})[node.camera] else nil + local li = if node.light then (scene.lights or {})[node.light] else nil + local typ = if node.mesh and meshId[node.mesh] then "MeshInstance3D" + elseif cam then "Camera3D" + elseif li then (if li.type == "spot" then "SpotLight3D" elseif li.type == "directional" then "DirectionalLight3D" else "OmniLight3D") + else "Node3D" + local sec = section("node", { "name", name, "type", typ, "parent", parent }) + local m = S.nodeMatrix(node) + if not isIdentity(m) then + prop(sec, "transform", transform(m)) + end + if typ == "MeshInstance3D" then + prop(sec, "mesh", ctor("SubResource", { meshId[node.mesh] })) + elseif typ == "Camera3D" then + if cam.type == "orthographic" then + prop(sec, "projection", 1) + prop(sec, "size", (cam.ymag or 0.5) * 2) + else + prop(sec, "fov", math.deg(cam.yfov or math.rad(75))) + end + prop(sec, "near", cam.znear or 0.05) + prop(sec, "far", cam.zfar or 4000) + elseif li then + prop(sec, "light_color", srgbColor(li.color, 1)) + prop(sec, "light_energy", li.intensity or 1) + if li.type == "point" then + prop(sec, "omni_range", li.range or 5) + elseif li.type == "spot" then + prop(sec, "spot_range", li.range or 5) + prop(sec, "spot_angle", math.deg(li.outerCone or math.pi / 4)) + end + end + local g = type(node.extras) == "table" and node.extras.godot + if type(g) == "table" and g.visible == false then + prop(sec, "visible", false) + end + table.insert(nodes, sec) + local path = if parent == nil then "." elseif parent == "." then name else parent .. "/" .. name + local childUsed = {} + for _, c in node.children or {} do + emit(c, path, childUsed, depth + 1) + end + end + if single then + emit(roots[1], nil, {}, 0) + else + table.insert(nodes, section("node", { "name", "Root", "type", "Node3D" })) + local used = {} + for _, r in roots do + emit(r, ".", used, 1) + end + end + local steps = #ext + #sub + 1 + table.insert(sections, section("gd_scene", { "load_steps", steps, "format", 3 })) + for _, s in ext do + table.insert(sections, s) + end + for _, s in sub do + table.insert(sections, s) + end + for _, s in nodes do + table.insert(sections, s) + end + return { sections = sections }, nil +end + +return Write diff --git a/src/Rosetta/model/godot/init.luau b/src/Rosetta/model/godot/init.luau new file mode 100644 index 0000000..47fee77 --- /dev/null +++ b/src/Rosetta/model/godot/init.luau @@ -0,0 +1,89 @@ +--!strict +-- model/godot: Godot text scenes (.tscn, .escn; formats 2-4) as a Scene, read + write (format 3); checked against +-- Godot 4's own loader. Supports: Node3D trees (transforms or position / rotation / scale), MeshInstance3D with +-- ArrayMesh surfaces and primitive meshes (Box, Plane, Quad, Sphere, Cylinder), StandardMaterial3D / SpatialMaterial +-- as PBR, surface material overrides, Camera3D, Omni / Spot / Directional lights, instanced scenes through +-- opts.resolve, non-3D nodes in extras.godot. Not supported: compressed or Godot 3 binary surfaces, skeletons and +-- animations (AnimationPlayer libraries stay sub-resources), blend shapes, other mesh / material resource types. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Sniff = require("@rosetta/core/Sniff") +local Types = require("@rosetta/Types") +local GodotVariant = require("@rosetta/codecs/text/GodotVariant") +local Build = require("@rosetta/model/godot/Build") +local Write = require("@rosetta/model/godot/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Godot = { + name = "godot", + category = "model", + extensions = { "tscn", "escn" }, + mime = { "application/x-godot-scene" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant", "codecs/model/Mat4" }, + caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, instances = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxBytes: number?, -- default 2^28 + maxVertices: number?, -- per surface, default 2^24 + maxDepth: number?, -- value nesting, default 256 + resolve: ((string) -> buffer?)?, -- res:// paths without the prefix: textures, instanced scenes +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Godot.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 256) + if string.match(h, "^%s*%[gd_scene[%s%]]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Godot.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = opts or {} + if r.limit - r.base > (o.maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local ok, doc, perr = pcall(function(): (GodotVariant.Document?, string?) + return GodotVariant.parse(text, { maxDepth = o.maxDepth }) + end) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(doc)) + end + if not doc then + return nil, Err.from(perr) + end + if #doc.sections == 0 then + return nil, Err.new(Err.CORRUPT, "empty file") + end + local ok2, scene, msg = pcall(Build.scene, doc, o) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Godot.encode(scene: Types.Scene, opts: any?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, doc, msg = pcall(Write.document, scene) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(doc)) + end + if not doc then + return nil, Err.new(Err.ARG, msg or "bad scene") + end + return buffer.fromstring(GodotVariant.encode(doc)), nil +end + +return Godot diff --git a/tests/codecs/godotvariant.luau b/tests/codecs/godotvariant.luau new file mode 100644 index 0000000..22c3c0b --- /dev/null +++ b/tests/codecs/godotvariant.luau @@ -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() diff --git a/tests/data/tres.luau b/tests/data/tres.luau new file mode 100644 index 0000000..b92a503 --- /dev/null +++ b/tests/data/tres.luau @@ -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() diff --git a/tests/model/godot.luau b/tests/model/godot.luau new file mode 100644 index 0000000..24151e8 --- /dev/null +++ b/tests/model/godot.luau @@ -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() diff --git a/tools/fixtures/_godot_dump.gd b/tools/fixtures/_godot_dump.gd new file mode 100644 index 0000000..61d565b --- /dev/null +++ b/tools/fixtures/_godot_dump.gd @@ -0,0 +1,80 @@ +# tools/fixtures/_godot_dump.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- ...): 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() diff --git a/tools/fixtures/_godot_encode.luau b/tools/fixtures/_godot_encode.luau new file mode 100644 index 0000000..0587d8a --- /dev/null +++ b/tools/fixtures/_godot_encode.luau @@ -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_.tscn\t" lines for Godot to +-- load, and every .tres case through data/tres ("ours_.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 diff --git a/tools/fixtures/_godot_make.gd b/tools/fixtures/_godot_make.gd new file mode 100644 index 0000000..536adc2 --- /dev/null +++ b/tools/fixtures/_godot_make.gd @@ -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() diff --git a/tools/fixtures/_godot_tres.gd b/tools/fixtures/_godot_tres.gd new file mode 100644 index 0000000..05abaf3 --- /dev/null +++ b/tools/fixtures/_godot_tres.gd @@ -0,0 +1,15 @@ +# tools/fixtures/_godot_tres.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- ...): 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() diff --git a/tools/fixtures/docs_engines.py b/tools/fixtures/docs_engines.py index 9ea2794..7aa9653 100644 --- a/tools/fixtures/docs_engines.py +++ b/tools/fixtures/docs_engines.py @@ -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) diff --git a/tools/fixtures/godot.py b/tools/fixtures/godot.py new file mode 100644 index 0000000..5a3d872 --- /dev/null +++ b/tools/fixtures/godot.py @@ -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)