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

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

No files matched your search

+540
View File
@@ -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
+273
View File
@@ -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
+483
View File
@@ -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
+327
View File
@@ -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
+89
View File
@@ -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