--!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