merge ws/engines
This commit is contained in:
commit
8bd15840d8
66 files changed
+31751
-1331
No files matched your search
@@ -758,6 +758,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/3mf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ase",
|
||||
category = "model",
|
||||
path = "model/ase",
|
||||
extensions = { "ase", "ask" },
|
||||
mime = { "model/x-ase", "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/model/Mat4" },
|
||||
caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, vertexColors = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/ase")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "b3d",
|
||||
category = "model",
|
||||
@@ -854,6 +866,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",
|
||||
@@ -1130,6 +1154,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/stl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "t3d",
|
||||
category = "model",
|
||||
path = "model/t3d",
|
||||
extensions = { "t3d" },
|
||||
mime = { "text/x-unreal-t3d" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Text", "codecs/model/Brush" },
|
||||
caps = { decode = true, encode = false, text = true, brushes = true, actors = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/t3d")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "udmf",
|
||||
category = "model",
|
||||
@@ -1634,6 +1670,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/archive/tar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "unitypackage",
|
||||
category = "archive",
|
||||
path = "archive/unitypackage",
|
||||
extensions = { "unitypackage" },
|
||||
mime = { "application/x-unitypackage" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true },
|
||||
load = function()
|
||||
return require("@rosetta/archive/unitypackage")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "uu",
|
||||
category = "archive",
|
||||
@@ -1898,6 +1946,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 = "vdf",
|
||||
category = "data",
|
||||
@@ -1946,6 +2006,30 @@ local list: { Entry } = {
|
||||
return require("@rosetta/vector/gamemaps")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ldtk",
|
||||
category = "vector",
|
||||
path = "vector/ldtk",
|
||||
extensions = { "ldtk" },
|
||||
mime = { "application/x-ldtk+json" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" },
|
||||
caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true },
|
||||
load = function()
|
||||
return require("@rosetta/vector/ldtk")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ogmo",
|
||||
category = "vector",
|
||||
path = "vector/ogmo",
|
||||
extensions = { "ogmo" },
|
||||
mime = { "application/x-ogmo+json" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" },
|
||||
caps = { decode = true, encode = true, projects = true, entities = true, decals = true },
|
||||
load = function()
|
||||
return require("@rosetta/vector/ogmo")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "svg",
|
||||
category = "vector",
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
--!strict
|
||||
-- archive/unitypackage: Unity asset packages, a gzip'd tar of <guid>/asset, <guid>/asset.meta, <guid>/pathname
|
||||
-- (+ preview.png), read + write as an Archive keyed by the asset paths (Assets/...), each .meta next to its asset as
|
||||
-- in a Unity project. Supports: folders (meta only), lazy entries, guids kept (entry.guid) or made from the path.
|
||||
-- Not supported: pre-5.x packages without pathname files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Md5 = require("@rosetta/core/Md5")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Tar = require("@rosetta/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local UnityPackage = {
|
||||
name = "unitypackage",
|
||||
category = "archive",
|
||||
extensions = { "unitypackage" },
|
||||
mime = { "application/x-unitypackage" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
maxBytes: number?, -- inflated size, default 2^31
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
level: number?, -- deflate 0..9, default 6
|
||||
mtime: number?, -- tar entry time, default 0
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function guidOf(name: string): (string?, string?)
|
||||
local n = string.gsub(name, "^%./", "")
|
||||
local guid, rest = string.match(n, "^(%x+)/?(.*)$")
|
||||
if guid and #guid == 32 then
|
||||
return string.lower(guid), rest
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
function UnityPackage.sniff(r: Bytes.Reader): number
|
||||
if r:peek(3) ~= "\31\139\8" then
|
||||
return 0
|
||||
end
|
||||
local head = Deflate.peek(r.buf, r.pos, r.limit - r.pos, 512)
|
||||
if not head or buffer.len(head) < 512 or not Tar.valid(head, 0) then
|
||||
return 0
|
||||
end
|
||||
local z = 0
|
||||
while z < 100 and buffer.readu8(head, z) ~= 0 do
|
||||
z += 1
|
||||
end
|
||||
return if guidOf(buffer.readstring(head, 0, z)) then 1 else 0 -- ties with archive/gzip go to the extension
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return UnityPackage.encode(archive, opts)
|
||||
end
|
||||
|
||||
type Asset = { asset: Tar.Entry?, meta: Tar.Entry?, pathname: Tar.Entry?, preview: Tar.Entry?, [string]: any }
|
||||
|
||||
local function text(b: buffer, e: Tar.Entry): string
|
||||
return buffer.readstring(b, e.offset, e.size)
|
||||
end
|
||||
|
||||
function UnityPackage.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local tar, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base)
|
||||
if not tar then
|
||||
return nil, err
|
||||
end
|
||||
if buffer.len(tar) > (o.maxBytes or 2 ^ 31) then
|
||||
return nil, Err.new(Err.LIMIT, "inflated size over the byte limit")
|
||||
end
|
||||
local list, terr = Tar.read(tar, 0, buffer.len(tar), { maxEntries = o.maxEntries })
|
||||
if not list then
|
||||
return nil, terr
|
||||
end
|
||||
local byGuid: { [string]: Asset } = {}
|
||||
local order: { string } = {}
|
||||
for _, e in list do
|
||||
local guid, rest = guidOf(e.name)
|
||||
if guid and not e.dir then
|
||||
local a = byGuid[guid]
|
||||
if not a then
|
||||
a = {} :: Asset
|
||||
byGuid[guid] = a
|
||||
table.insert(order, guid)
|
||||
end
|
||||
if rest == "asset" then
|
||||
a.asset = e
|
||||
elseif rest == "asset.meta" then
|
||||
a.meta = e
|
||||
elseif rest == "pathname" then
|
||||
a.pathname = e
|
||||
elseif rest == "preview.png" then
|
||||
a.preview = e
|
||||
end
|
||||
end
|
||||
end
|
||||
local arc = Archive.new("unitypackage", encode)
|
||||
local skipped = 0
|
||||
for _, guid in order do
|
||||
local a = byGuid[guid]
|
||||
local pn = a.pathname
|
||||
if not pn then
|
||||
skipped += 1
|
||||
else
|
||||
-- the first line is the path (Unity 5+ may add a second line, e.g. "00")
|
||||
local path = string.match(text(tar, pn), "^[^\r\n]*") or ""
|
||||
path = string.gsub(path, "\\", "/")
|
||||
if path ~= "" then
|
||||
local asset, meta = a.asset, a.meta
|
||||
local isDir = asset == nil
|
||||
Archive.put(arc, {
|
||||
name = path,
|
||||
size = if asset then asset.size else 0,
|
||||
dir = isDir,
|
||||
mtime = if asset then asset.mtime elseif meta then meta.mtime else nil,
|
||||
method = "deflate",
|
||||
guid = guid,
|
||||
load = if asset and asset.size > 0 then Archive.slice(tar, asset.offset, asset.size) else nil,
|
||||
preview = if a.preview then Archive.slice(tar, a.preview.offset, a.preview.size) else nil,
|
||||
})
|
||||
if meta then
|
||||
Archive.put(arc, {
|
||||
name = path .. ".meta",
|
||||
size = meta.size,
|
||||
dir = false,
|
||||
mtime = meta.mtime,
|
||||
method = "deflate",
|
||||
guid = guid,
|
||||
load = if meta.size > 0 then Archive.slice(tar, meta.offset, meta.size) else nil,
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
arc.meta.source = { format = "unitypackage", assets = #order - skipped, skipped = if skipped > 0 then skipped else nil }
|
||||
return arc, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function metaGuid(b: buffer): string?
|
||||
local s = buffer.readstring(b, 0, math.min(buffer.len(b), 4096))
|
||||
local g = string.match(s, "\nguid:%s*(%x+)") or string.match(s, "^guid:%s*(%x+)")
|
||||
if g and #g == 32 then
|
||||
return string.lower(g)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function defaultMeta(guid: string, dir: boolean): string
|
||||
if dir then
|
||||
return "fileFormatVersion: 2\nguid: " .. guid .. "\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n"
|
||||
end
|
||||
return "fileFormatVersion: 2\nguid: " .. guid .. "\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n"
|
||||
end
|
||||
|
||||
function UnityPackage.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local byName: { [string]: any } = {}
|
||||
for _, it in items do
|
||||
byName[string.gsub(it.entry.name, "\\", "/")] = it
|
||||
end
|
||||
local mtime = o.mtime or 0
|
||||
local list: { Tar.WriteEntry } = {}
|
||||
local used: { [string]: boolean } = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local path = string.gsub((string.gsub(e.name, "\\", "/")), "/+$", "")
|
||||
local metaIt = byName[path .. ".meta"]
|
||||
local isMeta = string.sub(path, -5) == ".meta" and byName[string.sub(path, 1, -6)] ~= nil
|
||||
if path ~= "" and not isMeta then
|
||||
local data: buffer? = nil
|
||||
if not e.dir then
|
||||
local b, rerr = it.read()
|
||||
if not b then
|
||||
return nil, rerr
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local metaData: buffer? = nil
|
||||
if metaIt then
|
||||
local mb, merr = metaIt.read()
|
||||
if not mb then
|
||||
return nil, merr
|
||||
end
|
||||
metaData = mb
|
||||
end
|
||||
local given: string? = if type(e.guid) == "string" and #e.guid == 32 and string.match(e.guid, "^%x+$") then string.lower(e.guid) else nil
|
||||
local g: string = given or (if metaData then metaGuid(metaData) else nil) or Md5.of(buffer.fromstring(path))
|
||||
if used[g] then
|
||||
g = Md5.of(buffer.fromstring(path .. "\0" .. g))
|
||||
end
|
||||
used[g] = true
|
||||
metaData = metaData or buffer.fromstring(defaultMeta(g, e.dir == true))
|
||||
table.insert(list, { name = g .. "/", dir = true, mtime = mtime })
|
||||
if data then
|
||||
table.insert(list, { name = g .. "/asset", data = data, mtime = mtime })
|
||||
end
|
||||
table.insert(list, { name = g .. "/asset.meta", data = metaData, mtime = mtime })
|
||||
table.insert(list, { name = g .. "/pathname", data = buffer.fromstring(path), mtime = mtime })
|
||||
if type(e.preview) == "function" then
|
||||
local ok, pb = pcall(e.preview)
|
||||
if ok and type(pb) == "buffer" then
|
||||
table.insert(list, { name = g .. "/preview.png", data = pb, mtime = mtime })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local tar, terr = Tar.write(list, { format = "ustar" })
|
||||
if not tar then
|
||||
return nil, terr
|
||||
end
|
||||
return Deflate.gzip(tar, { level = o.level or 6 })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
function UnityPackage.new(): any
|
||||
local a = Archive.new("unitypackage", encode)
|
||||
a.meta.source = { format = "unitypackage" }
|
||||
return a
|
||||
end
|
||||
|
||||
return UnityPackage
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,572 @@
|
||||
--!strict
|
||||
-- model/ase/Build: the parsed ASE tree into a Scene. Mesh vertices are stored in world space (3ds Max ASCII export):
|
||||
-- they are moved into the node's frame by the inverse NODE_TM, and node matrices are made relative to *NODE_PARENT.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Parse = require("@rosetta/model/ase/Parse")
|
||||
|
||||
type Item = Parse.Item
|
||||
|
||||
local Build = {}
|
||||
|
||||
local S = Types.Scene
|
||||
|
||||
local function first(kids: { Item }?, key: string): Item?
|
||||
if kids then
|
||||
for _, it in kids do
|
||||
if it.key == key then
|
||||
return it
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function num(it: Item?, i: number?): number?
|
||||
if not it then
|
||||
return nil
|
||||
end
|
||||
local v = tonumber(it.args[i or 1])
|
||||
if v and v == v and v ~= math.huge and v ~= -math.huge then
|
||||
return v
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function get(kids: { Item }?, key: string, i: number?): number?
|
||||
return num(first(kids, key), i)
|
||||
end
|
||||
|
||||
local function str(kids: { Item }?, key: string): string?
|
||||
local it = first(kids, key)
|
||||
return if it then it.args[1] else nil
|
||||
end
|
||||
|
||||
local function triple(kids: { Item }?, key: string): { number }?
|
||||
local it = first(kids, key)
|
||||
if not it then
|
||||
return nil
|
||||
end
|
||||
local a, b, c = num(it, 1), num(it, 2), num(it, 3)
|
||||
if a and b and c then
|
||||
return { a, b, c }
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- *TM_ROW0..2 are the axes, *TM_ROW3 the translation (row vectors): the columns of a column-major matrix
|
||||
local function nodeTm(kids: { Item }?): { number }
|
||||
local tm = first(kids, "NODE_TM")
|
||||
local m = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
if not tm then
|
||||
return m
|
||||
end
|
||||
for r = 0, 3 do
|
||||
local row = triple(tm.kids, "TM_ROW" .. r)
|
||||
if row then
|
||||
m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3] = row[1], row[2], row[3]
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ materials
|
||||
local MAPS = { "MAP_DIFFUSE", "MAP_BUMP", "MAP_OPACITY", "MAP_SELFILLUM", "MAP_SPECULAR", "MAP_SHINE", "MAP_AMBIENT", "MAP_REFLECT", "MAP_REFRACT", "MAP_SHINESTRENGTH", "MAP_FILTERCOLOR" }
|
||||
|
||||
local function textureRef(scene: Types.Scene, map: Item, opts: any): (Types.TextureRef?, { [string]: any })
|
||||
local k = map.kids
|
||||
local info: { [string]: any } = {
|
||||
name = str(k, "MAP_NAME"),
|
||||
class = str(k, "MAP_CLASS"),
|
||||
amount = get(k, "MAP_AMOUNT"),
|
||||
bitmap = str(k, "BITMAP"),
|
||||
uOffset = get(k, "UVW_U_OFFSET"),
|
||||
vOffset = get(k, "UVW_V_OFFSET"),
|
||||
uTiling = get(k, "UVW_U_TILING"),
|
||||
vTiling = get(k, "UVW_V_TILING"),
|
||||
angle = get(k, "UVW_ANGLE"),
|
||||
}
|
||||
local path = info.bitmap
|
||||
if type(path) ~= "string" or path == "" then
|
||||
return nil, info
|
||||
end
|
||||
local tex: Types.Texture = { name = path, uri = path }
|
||||
if opts and type(opts.resolve) == "function" then
|
||||
local ok, data = pcall(opts.resolve, path)
|
||||
if ok and type(data) == "buffer" then
|
||||
tex.data = data
|
||||
end
|
||||
end
|
||||
table.insert(scene.textures, tex)
|
||||
local ref: Types.TextureRef = { texture = #scene.textures }
|
||||
local su, sv = info.uTiling or 1, info.vTiling or 1
|
||||
local ou, ov = info.uOffset or 0, info.vOffset or 0
|
||||
local ang = info.angle or 0
|
||||
if su ~= 1 or sv ~= 1 or ou ~= 0 or ov ~= 0 or ang ~= 0 then
|
||||
ref.transform = { offset = { ou, ov }, scale = { su, sv }, rotation = ang }
|
||||
end
|
||||
return ref, info
|
||||
end
|
||||
|
||||
local function material(scene: Types.Scene, it: Item, opts: any): Types.Material
|
||||
local k = it.kids
|
||||
local m = S.material(str(k, "MATERIAL_NAME"))
|
||||
local diffuse = triple(k, "MATERIAL_DIFFUSE") or { 0.8, 0.8, 0.8 }
|
||||
local transparency = get(k, "MATERIAL_TRANSPARENCY") or 0
|
||||
local shine = get(k, "MATERIAL_SHINE") or 0
|
||||
local selfIllum = get(k, "MATERIAL_SELFILLUM") or 0
|
||||
m.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 - transparency }
|
||||
m.metallic = 0
|
||||
m.roughness = math.clamp(1 - shine, 0, 1)
|
||||
m.emissive = { diffuse[1] * selfIllum, diffuse[2] * selfIllum, diffuse[3] * selfIllum }
|
||||
if transparency > 0 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
m.doubleSided = first(k, "MATERIAL_TWOSIDED") ~= nil
|
||||
local maps: { [string]: any } = {}
|
||||
for _, key in MAPS do
|
||||
local map = first(k, key)
|
||||
if map then
|
||||
local ref, info = textureRef(scene, map, opts)
|
||||
maps[string.lower(string.sub(key, 5))] = info
|
||||
if ref then
|
||||
if key == "MAP_DIFFUSE" then
|
||||
m.baseColorTexture = ref
|
||||
elseif key == "MAP_BUMP" then
|
||||
m.normalTexture = ref
|
||||
elseif key == "MAP_SELFILLUM" then
|
||||
m.emissiveTexture = ref
|
||||
m.emissive = { 1, 1, 1 }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
m.extras = {
|
||||
ambient = triple(k, "MATERIAL_AMBIENT"),
|
||||
diffuse = diffuse,
|
||||
specular = triple(k, "MATERIAL_SPECULAR"),
|
||||
shininess = shine,
|
||||
shineStrength = get(k, "MATERIAL_SHINESTRENGTH"),
|
||||
transparency = transparency,
|
||||
selfIllum = selfIllum,
|
||||
ase = { class = str(k, "MATERIAL_CLASS"), shading = str(k, "MATERIAL_SHADING"), maps = maps },
|
||||
}
|
||||
return m
|
||||
end
|
||||
|
||||
-- ASE material index (0-based) -> { scene material per sub-material } (one entry when it has none)
|
||||
local function materials(scene: Types.Scene, list: Item?, opts: any): { { number } }
|
||||
local out: { { number } } = {}
|
||||
if not list or not list.kids then
|
||||
return out
|
||||
end
|
||||
for _, it in list.kids do
|
||||
if it.key == "MATERIAL" then
|
||||
local subs: { number } = {}
|
||||
for _, sub in it.kids or {} do
|
||||
if sub.key == "SUBMATERIAL" then
|
||||
table.insert(scene.materials, material(scene, sub, opts))
|
||||
table.insert(subs, #scene.materials)
|
||||
end
|
||||
end
|
||||
if #subs == 0 then
|
||||
table.insert(scene.materials, material(scene, it, opts))
|
||||
subs[1] = #scene.materials
|
||||
end
|
||||
table.insert(out, subs)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ meshes
|
||||
type Lists = { v: { number }, n: number }
|
||||
|
||||
local function vectors(kids: { Item }?, listKey: string, itemKey: string, comps: number, max: number): { number }
|
||||
local out: { number } = {}
|
||||
local list = first(kids, listKey)
|
||||
if not list or not list.kids then
|
||||
return out
|
||||
end
|
||||
for _, it in list.kids do
|
||||
if it.key == itemKey then
|
||||
local i = num(it, 1)
|
||||
if i and i >= 0 and i < max and i % 1 == 0 then
|
||||
for c = 1, comps do
|
||||
out[i * comps + c] = num(it, c + 1) or 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function corners(kids: { Item }?, listKey: string, itemKey: string, max: number): { number }
|
||||
local out: { number } = {}
|
||||
local list = first(kids, listKey)
|
||||
if not list or not list.kids then
|
||||
return out
|
||||
end
|
||||
for _, it in list.kids do
|
||||
if it.key == itemKey then
|
||||
local i = num(it, 1)
|
||||
if i and i >= 0 and i < max and i % 1 == 0 then
|
||||
out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = num(it, 2) or 0, num(it, 3) or 0, num(it, 4) or 0
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
type Face = { a: number, b: number, c: number, mtl: number, smoothing: string? }
|
||||
|
||||
-- *MESH_FACE i: A: a B: b C: c AB: e BC: e CA: e, then its *MESH_SMOOTHING / *MESH_MTLID siblings
|
||||
local function faces(list: Item?, nv: number, maxFaces: number): ({ Face }?, string?)
|
||||
local out: { Face } = {}
|
||||
if not list or not list.kids then
|
||||
return out, nil
|
||||
end
|
||||
local last: Face? = nil
|
||||
for _, it in list.kids do
|
||||
if it.key == "MESH_FACE" then
|
||||
local s = table.concat(it.args, " ")
|
||||
local i = tonumber(string.match(s, "^(%d+)"))
|
||||
local a = tonumber(string.match(s, "A:%s*(%d+)"))
|
||||
local b = tonumber(string.match(s, "B:%s*(%d+)"))
|
||||
local c = tonumber(string.match(s, "C:%s*(%d+)"))
|
||||
if not (i and a and b and c) then
|
||||
return nil, "bad *MESH_FACE at byte " .. it.at
|
||||
end
|
||||
if a >= nv or b >= nv or c >= nv then
|
||||
return nil, "face vertex index out of range at byte " .. it.at
|
||||
end
|
||||
if i >= maxFaces then
|
||||
return nil, "limit: face index " .. i
|
||||
end
|
||||
local f: Face = { a = a, b = b, c = c, mtl = 0, smoothing = nil }
|
||||
out[i + 1] = f
|
||||
last = f
|
||||
elseif it.key == "MESH_MTLID" and last then
|
||||
last.mtl = math.max(0, math.floor(num(it) or 0))
|
||||
elseif it.key == "MESH_SMOOTHING" and last then
|
||||
last.smoothing = it.args[1]
|
||||
end
|
||||
end
|
||||
for i = 1, #out do
|
||||
if out[i] == nil then
|
||||
out[i] = { a = 0, b = 0, c = 0, mtl = 0, smoothing = nil }
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
type Channel = { verts: { number }, tf: { number }, comps: number }
|
||||
|
||||
local function channel(kids: { Item }?, numKey: string, listKey: string, vertKey: string, tfKey: string, tfListKey: string, nf: number, maxV: number): Channel?
|
||||
local n = get(kids, numKey) or 0
|
||||
if n <= 0 then
|
||||
return nil
|
||||
end
|
||||
n = math.min(n, maxV)
|
||||
local verts = vectors(kids, listKey, vertKey, 3, n)
|
||||
local tf = corners(kids, tfListKey, tfKey, nf)
|
||||
return { verts = verts, tf = tf, comps = 3 }
|
||||
end
|
||||
|
||||
local function writeVec(acc: Types.Accessor, i: number, x: number, y: number, z: number)
|
||||
local d = acc.data
|
||||
buffer.writef32(d, i * 12, x)
|
||||
buffer.writef32(d, i * 12 + 4, y)
|
||||
buffer.writef32(d, i * 12 + 8, z)
|
||||
end
|
||||
|
||||
local function mesh(scene: Types.Scene, obj: Item, matMap: { { number } }, world: { number }, opts: any): (number?, string?)
|
||||
local m = first(obj.kids, "MESH")
|
||||
if not m or not m.kids then
|
||||
return nil, nil
|
||||
end
|
||||
local k = m.kids
|
||||
local maxV = opts.maxVertices or 2 ^ 24
|
||||
local nv = get(k, "MESH_NUMVERTEX") or 0
|
||||
local nf = get(k, "MESH_NUMFACES") or 0
|
||||
if nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then
|
||||
return nil, "bad vertex or face count"
|
||||
end
|
||||
if nv > maxV or nf * 3 > maxV then
|
||||
return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces"
|
||||
end
|
||||
local pos = vectors(k, "MESH_VERTEX_LIST", "MESH_VERTEX", 3, nv)
|
||||
local fl, ferr = faces(first(k, "MESH_FACE_LIST"), nv, nf)
|
||||
if not fl then
|
||||
return nil, ferr
|
||||
end
|
||||
if #fl == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
local uvs: { Channel } = {}
|
||||
local ch0 = channel(k, "MESH_NUMTVERTEX", "MESH_TVERTLIST", "MESH_TVERT", "MESH_TFACE", "MESH_TFACELIST", #fl, maxV)
|
||||
if ch0 then
|
||||
uvs[1] = ch0
|
||||
end
|
||||
for _, it in k do
|
||||
if it.key == "MESH_MAPPINGCHANNEL" and it.kids then
|
||||
local idx = num(it) or 0
|
||||
local ch = channel(it.kids, "MESH_NUMTVERTEX", "MESH_TVERTLIST", "MESH_TVERT", "MESH_TFACE", "MESH_TFACELIST", #fl, maxV)
|
||||
if ch and idx >= 2 and idx <= 8 then
|
||||
uvs[idx] = ch
|
||||
end
|
||||
end
|
||||
end
|
||||
local colors = channel(k, "MESH_NUMCVERTEX", "MESH_CVERTLIST", "MESH_VERTCOL", "MESH_CFACE", "MESH_CFACELIST", #fl, maxV)
|
||||
-- *MESH_NORMALS: *MESH_FACENORMAL f, then *MESH_VERTEXNORMAL v x y z for each of its corners
|
||||
local normals: { number }? = nil
|
||||
local nlist = first(k, "MESH_NORMALS")
|
||||
if nlist and nlist.kids then
|
||||
local nn: { number } = {}
|
||||
local face = -1
|
||||
for _, it in nlist.kids do
|
||||
if it.key == "MESH_FACENORMAL" then
|
||||
face = num(it) or -1
|
||||
elseif it.key == "MESH_VERTEXNORMAL" and face >= 0 and face < #fl then
|
||||
local f = fl[face + 1]
|
||||
local v = num(it)
|
||||
local corner = if v == f.a then 0 elseif v == f.b then 1 elseif v == f.c then 2 else nil
|
||||
if corner then
|
||||
local o = (face * 3 + corner) * 3
|
||||
nn[o + 1], nn[o + 2], nn[o + 3] = num(it, 2) or 0, num(it, 3) or 0, num(it, 4) or 0
|
||||
end
|
||||
end
|
||||
end
|
||||
normals = nn
|
||||
end
|
||||
-- faces by scene material (sub-material = *MESH_MTLID, the last one when out of range)
|
||||
local ref = get(obj.kids, "MATERIAL_REF")
|
||||
local subs: { number }? = if ref and ref >= 0 then matMap[math.min(ref, #matMap - 1) + 1] else nil
|
||||
local groups: { [number]: { number } } = {}
|
||||
local order: { number } = {}
|
||||
for i, f in fl do
|
||||
local key = 0
|
||||
if subs and #subs > 0 then
|
||||
key = subs[math.min(f.mtl, #subs - 1) + 1]
|
||||
end
|
||||
local g = groups[key]
|
||||
if not g then
|
||||
g = {}
|
||||
groups[key] = g
|
||||
table.insert(order, key)
|
||||
end
|
||||
table.insert(g, i)
|
||||
end
|
||||
table.sort(order)
|
||||
local inv = Mat4.inverse(world)
|
||||
local local_ = inv or S.IDENTITY
|
||||
local nmat = Mat4.normalMatrix(local_)
|
||||
local out: Types.Mesh = { name = str(obj.kids, "NODE_NAME"), primitives = {} }
|
||||
for _, key in order do
|
||||
local list = groups[key]
|
||||
local count = #list * 3
|
||||
local P = S.accessor(nil, "f32", 3, count)
|
||||
local N = if normals then S.accessor(nil, "f32", 3, count) else nil
|
||||
local UV: { [number]: Types.Accessor } = {}
|
||||
for idx in uvs do
|
||||
UV[idx] = S.accessor(nil, "f32", 2, count)
|
||||
end
|
||||
local C = if colors then S.accessor(nil, "f32", 4, count) else nil
|
||||
local I = S.accessor(nil, "u32", 1, count)
|
||||
local w = 0
|
||||
for _, fi in list do
|
||||
local f = fl[fi]
|
||||
local fc = { f.a, f.b, f.c }
|
||||
for corner = 0, 2 do
|
||||
local vi = fc[corner + 1]
|
||||
local x, y, z = Mat4.point(local_, pos[vi * 3 + 1] or 0, pos[vi * 3 + 2] or 0, pos[vi * 3 + 3] or 0)
|
||||
writeVec(P, w, x, y, z)
|
||||
if N and normals then
|
||||
local o = ((fi - 1) * 3 + corner) * 3
|
||||
local nx, ny, nz = normals[o + 1] or 0, normals[o + 2] or 0, normals[o + 3] or 0
|
||||
local tx = nmat[1] * nx + nmat[5] * ny + nmat[9] * nz
|
||||
local ty = nmat[2] * nx + nmat[6] * ny + nmat[10] * nz
|
||||
local tz = nmat[3] * nx + nmat[7] * ny + nmat[11] * nz
|
||||
local len = math.sqrt(tx * tx + ty * ty + tz * tz)
|
||||
if len > 0 then
|
||||
tx, ty, tz = tx / len, ty / len, tz / len
|
||||
end
|
||||
writeVec(N, w, tx, ty, tz)
|
||||
end
|
||||
for idx, ch in uvs do
|
||||
local ti = ch.tf[(fi - 1) * 3 + corner + 1] or 0
|
||||
local u, v = ch.verts[ti * 3 + 1] or 0, ch.verts[ti * 3 + 2] or 0
|
||||
buffer.writef32(UV[idx].data, w * 8, u)
|
||||
buffer.writef32(UV[idx].data, w * 8 + 4, 1 - v) -- 3ds Max v goes up
|
||||
end
|
||||
if C and colors then
|
||||
local ci = colors.tf[(fi - 1) * 3 + corner + 1] or 0
|
||||
local d = C.data
|
||||
buffer.writef32(d, w * 16, colors.verts[ci * 3 + 1] or 1)
|
||||
buffer.writef32(d, w * 16 + 4, colors.verts[ci * 3 + 2] or 1)
|
||||
buffer.writef32(d, w * 16 + 8, colors.verts[ci * 3 + 3] or 1)
|
||||
buffer.writef32(d, w * 16 + 12, 1)
|
||||
end
|
||||
buffer.writeu32(I.data, w * 4, w)
|
||||
w += 1
|
||||
end
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = P }
|
||||
if N then
|
||||
attrs.NORMAL = N
|
||||
end
|
||||
for idx, acc in UV do
|
||||
attrs["TEXCOORD_" .. (idx - 1)] = acc
|
||||
end
|
||||
if C then
|
||||
attrs.COLOR_0 = C
|
||||
end
|
||||
local smoothing: { string } = {}
|
||||
for j, fi in list do
|
||||
smoothing[j] = fl[fi].smoothing or ""
|
||||
end
|
||||
local prim: Types.Primitive = {
|
||||
attributes = attrs,
|
||||
indices = I,
|
||||
mode = "triangles",
|
||||
material = if key > 0 then key else nil,
|
||||
extras = { smoothing = smoothing },
|
||||
}
|
||||
table.insert(out.primitives, prim)
|
||||
end
|
||||
table.insert(scene.meshes, out)
|
||||
return #scene.meshes, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ objects
|
||||
local LIGHTS: { [string]: "directional" | "point" | "spot" } = { Omni = "point", Target = "spot", Free = "spot", Directional = "directional", TargetDirectional = "directional" }
|
||||
|
||||
local function camera(scene: Types.Scene, obj: Item): number
|
||||
local st = first(obj.kids, "CAMERA_SETTINGS")
|
||||
local fov = get(st and st.kids, "CAMERA_FOV") or math.rad(45)
|
||||
local cam: Types.Camera = {
|
||||
name = str(obj.kids, "NODE_NAME"),
|
||||
type = "perspective",
|
||||
yfov = fov, -- 3ds Max stores the horizontal field of view (radians), kept as it is
|
||||
znear = get(st and st.kids, "CAMERA_NEAR") or 0,
|
||||
zfar = get(st and st.kids, "CAMERA_FAR"),
|
||||
}
|
||||
table.insert(scene.cameras, cam)
|
||||
return #scene.cameras
|
||||
end
|
||||
|
||||
local function light(scene: Types.Scene, obj: Item): number
|
||||
local st = first(obj.kids, "LIGHT_SETTINGS")
|
||||
local sk = st and st.kids
|
||||
local typ = LIGHTS[str(obj.kids, "LIGHT_TYPE") or "Omni"] or "point"
|
||||
local l: Types.Light = {
|
||||
name = str(obj.kids, "NODE_NAME"),
|
||||
type = typ,
|
||||
color = triple(sk, "LIGHT_COLOR") or { 1, 1, 1 },
|
||||
intensity = get(sk, "LIGHT_INTENS") or 1,
|
||||
}
|
||||
if typ == "spot" then
|
||||
l.innerCone = math.rad((get(sk, "LIGHT_HOTSPOT") or 43) / 2)
|
||||
l.outerCone = math.rad((get(sk, "LIGHT_FALLOFF") or 45) / 2)
|
||||
end
|
||||
table.insert(scene.lights, l)
|
||||
return #scene.lights
|
||||
end
|
||||
|
||||
local KINDS = { GEOMOBJECT = true, HELPEROBJECT = true, CAMERAOBJECT = true, LIGHTOBJECT = true, SHAPEOBJECT = true }
|
||||
|
||||
local function collect(kids: { Item }, into: { Item }, depth: number)
|
||||
for _, it in kids do
|
||||
if KINDS[it.key] then
|
||||
table.insert(into, it)
|
||||
elseif it.key == "GROUP" and it.kids and depth < 32 then
|
||||
collect(it.kids, into, depth + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Build.scene(root: { Item }, opts: any): (Types.Scene?, string?)
|
||||
local o = opts or {}
|
||||
local scene = S.new()
|
||||
local version = get(root, "3DSMAX_ASCIIEXPORT")
|
||||
local sk = (first(root, "SCENE") or { kids = nil } :: any).kids
|
||||
scene.meta.up = "z"
|
||||
scene.meta.source = {
|
||||
format = "ase",
|
||||
version = version,
|
||||
comment = str(root, "COMMENT"),
|
||||
firstFrame = get(sk, "SCENE_FIRSTFRAME"),
|
||||
lastFrame = get(sk, "SCENE_LASTFRAME"),
|
||||
frameSpeed = get(sk, "SCENE_FRAMESPEED"),
|
||||
ticksPerFrame = get(sk, "SCENE_TICKSPERFRAME"),
|
||||
background = triple(sk, "SCENE_BACKGROUND_STATIC"),
|
||||
ambient = triple(sk, "SCENE_AMBIENT_STATIC"),
|
||||
}
|
||||
local matMap = materials(scene, first(root, "MATERIAL_LIST"), o)
|
||||
local objs: { Item } = {}
|
||||
collect(root, objs, 0)
|
||||
local byName: { [string]: number } = {}
|
||||
local worlds: { { number } } = {}
|
||||
local parents: { string? } = {}
|
||||
local animated = false
|
||||
for i, obj in objs do
|
||||
local name = str(obj.kids, "NODE_NAME")
|
||||
local world = nodeTm(obj.kids)
|
||||
local node: Types.Node = { name = name, children = {} }
|
||||
local extras: { [string]: any } = { class = string.lower((string.gsub(obj.key, "OBJECT$", ""))) }
|
||||
if obj.key == "GEOMOBJECT" then
|
||||
local mi, merr = mesh(scene, obj, matMap, world, o)
|
||||
if merr then
|
||||
return nil, merr
|
||||
end
|
||||
node.mesh = mi
|
||||
elseif obj.key == "CAMERAOBJECT" then
|
||||
node.camera = camera(scene, obj)
|
||||
elseif obj.key == "LIGHTOBJECT" then
|
||||
node.light = light(scene, obj)
|
||||
elseif obj.key == "HELPEROBJECT" then
|
||||
extras.helperClass = str(obj.kids, "HELPER_CLASS")
|
||||
end
|
||||
if first(obj.kids, "TM_ANIMATION") then
|
||||
animated = true
|
||||
end
|
||||
node.extras = { ase = extras }
|
||||
scene.nodes[i] = node
|
||||
worlds[i] = world
|
||||
parents[i] = str(obj.kids, "NODE_PARENT")
|
||||
if name and byName[name] == nil then
|
||||
byName[name] = i
|
||||
end
|
||||
end
|
||||
for i, node in scene.nodes do
|
||||
local pname = parents[i]
|
||||
local p = if pname then byName[pname] else nil
|
||||
if p and p ~= i then
|
||||
-- a parent cycle (or a parent listed later naming this node) falls back to a root
|
||||
local q, steps = p, 0
|
||||
while q and q ~= i and steps < #objs do
|
||||
local pn = parents[q]
|
||||
q = if pn then byName[pn] else nil
|
||||
steps += 1
|
||||
end
|
||||
if q == i then
|
||||
p = nil
|
||||
end
|
||||
else
|
||||
p = nil
|
||||
end
|
||||
local inv = if p then Mat4.inverse(worlds[p :: number]) else nil
|
||||
node.matrix = if inv then S.mul(inv, worlds[i]) else worlds[i]
|
||||
if p then
|
||||
table.insert(scene.nodes[p :: number].children, i)
|
||||
else
|
||||
table.insert(scene.roots, i)
|
||||
end
|
||||
end
|
||||
if animated then
|
||||
(scene.meta.source :: any).animated = true
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,67 @@
|
||||
--!strict
|
||||
-- model/ase/Parse: ASE text into a tree of items (*KEY args { children }). Quoted strings carry no escapes (3ds Max
|
||||
-- ASCII export). Several items may share a line (*MESH_FACE ... *MESH_SMOOTHING 1 *MESH_MTLID 0).
|
||||
local Parse = {}
|
||||
|
||||
export type Item = { key: string, args: { string }, kids: { Item }?, at: number }
|
||||
|
||||
function Parse.tree(text: string, maxItems: number): ({ Item }?, string?)
|
||||
local root: { Item } = {}
|
||||
local stack: { { Item } } = { root }
|
||||
local cur: Item? = nil
|
||||
local p, n = 1, #text
|
||||
local count = 0
|
||||
local find, sub, byte = string.find, string.sub, string.byte
|
||||
while p <= n do
|
||||
local s = find(text, "[^ \t\r\n]", p)
|
||||
if not s then
|
||||
break
|
||||
end
|
||||
local c = byte(text, s)
|
||||
if c == 34 then -- '"'
|
||||
local e = find(text, "\"", s + 1, true)
|
||||
local stop = e or (n + 1)
|
||||
if cur then
|
||||
table.insert(cur.args, sub(text, s + 1, stop - 1))
|
||||
end
|
||||
p = stop + 1
|
||||
elseif c == 123 then -- '{'
|
||||
if not cur then
|
||||
return nil, "'{' without an item at byte " .. s - 1
|
||||
end
|
||||
if #stack > 64 then
|
||||
return nil, "limit: nesting too deep"
|
||||
end
|
||||
local kids: { Item } = {}
|
||||
cur.kids = kids
|
||||
table.insert(stack, kids)
|
||||
cur = nil
|
||||
p = s + 1
|
||||
elseif c == 125 then -- '}'
|
||||
if #stack == 1 then
|
||||
return nil, "unbalanced '}' at byte " .. s - 1
|
||||
end
|
||||
table.remove(stack)
|
||||
cur = nil
|
||||
p = s + 1
|
||||
else
|
||||
local e = find(text, "[ \t\r\n{}\"]", s) or (n + 1)
|
||||
local word = sub(text, s, e - 1)
|
||||
if c == 42 then -- '*'
|
||||
count += 1
|
||||
if count > maxItems then
|
||||
return nil, "limit: over " .. maxItems .. " items"
|
||||
end
|
||||
local it: Item = { key = sub(word, 2), args = {}, kids = nil, at = s - 1 }
|
||||
table.insert(stack[#stack], it)
|
||||
cur = it
|
||||
elseif cur then
|
||||
table.insert(cur.args, word)
|
||||
end
|
||||
p = e
|
||||
end
|
||||
end
|
||||
return root, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,461 @@
|
||||
--!strict
|
||||
-- model/ase/Write: a Scene as ASE text (3DSMAX_ASCIIEXPORT 200). Vertices are written in world space with each node's
|
||||
-- world NODE_TM; every scene material is a sub-material of one Multi/Sub-Object material (faces pick it by
|
||||
-- *MESH_MTLID). Triangles, strips, fans and polygons (fanned) are written; points and lines are skipped.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local S = Types.Scene
|
||||
|
||||
local function f(v: number): string
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
return "0.0000"
|
||||
end
|
||||
if v == math.floor(v) and math.abs(v) < 1e15 then
|
||||
return string.format("%.4f", v)
|
||||
end
|
||||
return string.format("%.9g", v)
|
||||
end
|
||||
|
||||
local function q(s: string): string
|
||||
return "\"" .. string.gsub(s, "\"", "'") .. "\""
|
||||
end
|
||||
|
||||
type Out = { lines: { string } }
|
||||
|
||||
local function put(out: Out, depth: number, s: string)
|
||||
table.insert(out.lines, string.rep("\t", depth) .. s)
|
||||
end
|
||||
|
||||
local function tri(prim: any): { number }?
|
||||
local pos = prim.attributes and prim.attributes.POSITION
|
||||
if type(pos) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local n = pos.count
|
||||
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, n - 1 do
|
||||
idx[i + 1] = i
|
||||
end
|
||||
end
|
||||
local mode = prim.mode or "triangles"
|
||||
local out: { number } = {}
|
||||
if mode == "triangles" then
|
||||
for i = 1, #idx - 2, 3 do
|
||||
table.insert(out, idx[i])
|
||||
table.insert(out, idx[i + 1])
|
||||
table.insert(out, idx[i + 2])
|
||||
end
|
||||
elseif mode == "triangle_strip" then
|
||||
for i = 1, #idx - 2 do
|
||||
if i % 2 == 1 then
|
||||
table.insert(out, idx[i])
|
||||
table.insert(out, idx[i + 1])
|
||||
else
|
||||
table.insert(out, idx[i + 1])
|
||||
table.insert(out, idx[i])
|
||||
end
|
||||
table.insert(out, idx[i + 2])
|
||||
end
|
||||
elseif mode == "triangle_fan" then
|
||||
for i = 2, #idx - 1 do
|
||||
table.insert(out, idx[1])
|
||||
table.insert(out, idx[i])
|
||||
table.insert(out, idx[i + 1])
|
||||
end
|
||||
elseif mode == "polygons" and prim.faces then
|
||||
local rd = S.reader(prim.faces)
|
||||
local at = 1
|
||||
if rd then
|
||||
for fi = 0, prim.faces.count - 1 do
|
||||
local size = rd(fi, 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 >= n then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function material(out: Out, d: number, key: string, index: number, m: any)
|
||||
put(out, d, "*" .. key .. " " .. index .. " {")
|
||||
local c = if type(m.baseColor) == "table" then m.baseColor else { 1, 1, 1, 1 }
|
||||
local x = if type(m.extras) == "table" then m.extras else {}
|
||||
local amb = if type(x.ambient) == "table" then x.ambient else { c[1] or 1, c[2] or 1, c[3] or 1 }
|
||||
local spec = if type(x.specular) == "table" then x.specular else { 0.9, 0.9, 0.9 }
|
||||
put(out, d + 1, "*MATERIAL_NAME " .. q(if type(m.name) == "string" then m.name else "Material #" .. index))
|
||||
put(out, d + 1, "*MATERIAL_CLASS \"Standard\"")
|
||||
put(out, d + 1, "*MATERIAL_AMBIENT " .. f(amb[1] or 0) .. "\t" .. f(amb[2] or 0) .. "\t" .. f(amb[3] or 0))
|
||||
put(out, d + 1, "*MATERIAL_DIFFUSE " .. f(c[1] or 1) .. "\t" .. f(c[2] or 1) .. "\t" .. f(c[3] or 1))
|
||||
put(out, d + 1, "*MATERIAL_SPECULAR " .. f(spec[1] or 0) .. "\t" .. f(spec[2] or 0) .. "\t" .. f(spec[3] or 0))
|
||||
put(out, d + 1, "*MATERIAL_SHINE " .. f(if type(x.shininess) == "number" then x.shininess else 1 - (m.roughness or 1)))
|
||||
put(out, d + 1, "*MATERIAL_SHINESTRENGTH " .. f(if type(x.shineStrength) == "number" then x.shineStrength else 0))
|
||||
put(out, d + 1, "*MATERIAL_TRANSPARENCY " .. f(1 - (c[4] or 1)))
|
||||
put(out, d + 1, "*MATERIAL_WIRESIZE 1.0000")
|
||||
if m.doubleSided then
|
||||
put(out, d + 1, "*MATERIAL_TWOSIDED")
|
||||
end
|
||||
put(out, d + 1, "*MATERIAL_SHADING Blinn")
|
||||
put(out, d + 1, "*MATERIAL_SELFILLUM " .. f(if type(x.selfIllum) == "number" then x.selfIllum else 0))
|
||||
local ref = m.baseColorTexture
|
||||
local tex = if type(ref) == "table" and type(m._textures) == "table" then m._textures[ref.texture] else nil
|
||||
if tex and type(tex.uri) == "string" then
|
||||
local tr = if type(ref.transform) == "table" then ref.transform else {}
|
||||
local off = if type(tr.offset) == "table" then tr.offset else { 0, 0 }
|
||||
local sc = if type(tr.scale) == "table" then tr.scale else { 1, 1 }
|
||||
put(out, d + 1, "*MAP_DIFFUSE {")
|
||||
put(out, d + 2, "*MAP_NAME " .. q(tex.name or tex.uri))
|
||||
put(out, d + 2, "*MAP_CLASS \"Bitmap\"")
|
||||
put(out, d + 2, "*MAP_SUBNO 1")
|
||||
put(out, d + 2, "*MAP_AMOUNT 1.0000")
|
||||
put(out, d + 2, "*BITMAP " .. q(tex.uri))
|
||||
put(out, d + 2, "*MAP_TYPE Screen")
|
||||
put(out, d + 2, "*UVW_U_OFFSET " .. f(off[1] or 0))
|
||||
put(out, d + 2, "*UVW_V_OFFSET " .. f(off[2] or 0))
|
||||
put(out, d + 2, "*UVW_U_TILING " .. f(sc[1] or 1))
|
||||
put(out, d + 2, "*UVW_V_TILING " .. f(sc[2] or 1))
|
||||
put(out, d + 2, "*UVW_ANGLE " .. f(tr.rotation or 0))
|
||||
put(out, d + 1, "}")
|
||||
end
|
||||
put(out, d, "}")
|
||||
end
|
||||
|
||||
local function nodeTm(out: Out, name: string, m: { number })
|
||||
put(out, 1, "*NODE_TM {")
|
||||
put(out, 2, "*NODE_NAME " .. q(name))
|
||||
put(out, 2, "*INHERIT_POS 0 0 0")
|
||||
put(out, 2, "*INHERIT_ROT 0 0 0")
|
||||
put(out, 2, "*INHERIT_SCL 0 0 0")
|
||||
for r = 0, 3 do
|
||||
put(out, 2, "*TM_ROW" .. r .. " " .. f(m[r * 4 + 1]) .. "\t" .. f(m[r * 4 + 2]) .. "\t" .. f(m[r * 4 + 3]))
|
||||
end
|
||||
local t, r, s = Mat4.decompose(m)
|
||||
local w = math.clamp(r[4], -1, 1)
|
||||
local angle = 2 * math.acos(w)
|
||||
local sn = math.sqrt(math.max(0, 1 - w * w))
|
||||
local ax = if sn > 1e-9 then { r[1] / sn, r[2] / sn, r[3] / sn } else { 0, 0, 0 }
|
||||
put(out, 2, "*TM_POS " .. f(t[1]) .. "\t" .. f(t[2]) .. "\t" .. f(t[3]))
|
||||
put(out, 2, "*TM_ROTAXIS " .. f(ax[1]) .. "\t" .. f(ax[2]) .. "\t" .. f(ax[3]))
|
||||
put(out, 2, "*TM_ROTANGLE " .. f(angle))
|
||||
put(out, 2, "*TM_SCALE " .. f(s[1]) .. "\t" .. f(s[2]) .. "\t" .. f(s[3]))
|
||||
put(out, 2, "*TM_SCALEAXIS 0.0000\t0.0000\t0.0000")
|
||||
put(out, 2, "*TM_SCALEAXISANG 0.0000")
|
||||
put(out, 1, "}")
|
||||
end
|
||||
|
||||
local function vec(rd: ((number, number) -> number)?, i: number, n: number, default: number): { number }
|
||||
local v = {}
|
||||
for c = 0, n - 1 do
|
||||
v[c + 1] = if rd then rd(i, c) else default
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local function geom(out: Out, scene: any, mesh: any, world: { number }, matBase: { [number]: number }, hasMulti: boolean): boolean
|
||||
local P: { number } = {}
|
||||
local N: { number } = {}
|
||||
local T: { [number]: { number } } = {}
|
||||
local C: { number } = {}
|
||||
local F: { number } = {}
|
||||
local M: { number } = {}
|
||||
local hasN, hasC = false, false
|
||||
local uvSets: { [number]: boolean } = {}
|
||||
for _, prim in mesh.primitives or {} do
|
||||
for name in prim.attributes or {} do
|
||||
local k = string.match(name, "^TEXCOORD_(%d)$")
|
||||
if k then
|
||||
uvSets[tonumber(k) :: number] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
local nm = Mat4.normalMatrix(world)
|
||||
for _, prim in mesh.primitives or {} do
|
||||
local idx = tri(prim)
|
||||
if idx then
|
||||
local a = prim.attributes
|
||||
local base = #P // 3
|
||||
local rp = S.reader(a.POSITION)
|
||||
local rn = if a.NORMAL then S.reader(a.NORMAL) else nil
|
||||
local rc = if a.COLOR_0 then S.reader(a.COLOR_0) else nil
|
||||
local cc = if a.COLOR_0 then a.COLOR_0.components else 0
|
||||
if rp then
|
||||
for i = 0, a.POSITION.count - 1 do
|
||||
local x, y, z = Mat4.point(world, rp(i, 0), rp(i, 1), rp(i, 2))
|
||||
table.insert(P, x)
|
||||
table.insert(P, y)
|
||||
table.insert(P, z)
|
||||
local nv = vec(rn, i, 3, 0)
|
||||
local tx = nm[1] * nv[1] + nm[5] * nv[2] + nm[9] * nv[3]
|
||||
local ty = nm[2] * nv[1] + nm[6] * nv[2] + nm[10] * nv[3]
|
||||
local tz = nm[3] * nv[1] + nm[7] * nv[2] + nm[11] * nv[3]
|
||||
local len = math.sqrt(tx * tx + ty * ty + tz * tz)
|
||||
if len > 0 then
|
||||
tx, ty, tz = tx / len, ty / len, tz / len
|
||||
end
|
||||
table.insert(N, tx)
|
||||
table.insert(N, ty)
|
||||
table.insert(N, tz)
|
||||
for k in uvSets do
|
||||
local acc = a["TEXCOORD_" .. k]
|
||||
local rt = if acc then S.reader(acc) else nil
|
||||
local list = T[k] or {}
|
||||
T[k] = list
|
||||
table.insert(list, if rt then rt(i, 0) else 0)
|
||||
table.insert(list, if rt then 1 - rt(i, 1) else 0)
|
||||
end
|
||||
local col = vec(rc, i, math.max(cc, 3), 1)
|
||||
table.insert(C, col[1])
|
||||
table.insert(C, col[2])
|
||||
table.insert(C, col[3])
|
||||
end
|
||||
hasN = hasN or rn ~= nil
|
||||
hasC = hasC or rc ~= nil
|
||||
local mid = if prim.material and matBase[prim.material] then matBase[prim.material] else (if hasMulti then #scene.materials else 0)
|
||||
for i = 1, #idx, 3 do
|
||||
table.insert(F, base + idx[i])
|
||||
table.insert(F, base + idx[i + 1])
|
||||
table.insert(F, base + idx[i + 2])
|
||||
table.insert(M, mid)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #F == 0 then
|
||||
return false
|
||||
end
|
||||
local nv, nf = #P // 3, #F // 3
|
||||
put(out, 1, "*MESH {")
|
||||
put(out, 2, "*TIMEVALUE 0")
|
||||
put(out, 2, "*MESH_NUMVERTEX " .. nv)
|
||||
put(out, 2, "*MESH_NUMFACES " .. nf)
|
||||
put(out, 2, "*MESH_VERTEX_LIST {")
|
||||
for i = 0, nv - 1 do
|
||||
put(out, 3, "*MESH_VERTEX " .. i .. "\t" .. f(P[i * 3 + 1]) .. "\t" .. f(P[i * 3 + 2]) .. "\t" .. f(P[i * 3 + 3]))
|
||||
end
|
||||
put(out, 2, "}")
|
||||
put(out, 2, "*MESH_FACE_LIST {")
|
||||
for i = 0, nf - 1 do
|
||||
put(out, 3, string.format("*MESH_FACE %d: A: %d B: %d C: %d AB: 1 BC: 1 CA: 1\t*MESH_SMOOTHING 1\t*MESH_MTLID %d", i, F[i * 3 + 1], F[i * 3 + 2], F[i * 3 + 3], M[i + 1]))
|
||||
end
|
||||
put(out, 2, "}")
|
||||
local function uvBlock(d: number, list: { number })
|
||||
put(out, d, "*MESH_NUMTVERTEX " .. nv)
|
||||
put(out, d, "*MESH_TVERTLIST {")
|
||||
for i = 0, nv - 1 do
|
||||
put(out, d + 1, "*MESH_TVERT " .. i .. "\t" .. f(list[i * 2 + 1] or 0) .. "\t" .. f(list[i * 2 + 2] or 0) .. "\t0.0000")
|
||||
end
|
||||
put(out, d, "}")
|
||||
put(out, d, "*MESH_NUMTVFACES " .. nf)
|
||||
put(out, d, "*MESH_TFACELIST {")
|
||||
for i = 0, nf - 1 do
|
||||
put(out, d + 1, "*MESH_TFACE " .. i .. "\t" .. F[i * 3 + 1] .. "\t" .. F[i * 3 + 2] .. "\t" .. F[i * 3 + 3])
|
||||
end
|
||||
put(out, d, "}")
|
||||
end
|
||||
if T[0] then
|
||||
uvBlock(2, T[0])
|
||||
end
|
||||
for k = 1, 7 do
|
||||
if T[k] then
|
||||
put(out, 2, "*MESH_MAPPINGCHANNEL " .. (k + 1) .. " {")
|
||||
uvBlock(3, T[k])
|
||||
put(out, 2, "}")
|
||||
end
|
||||
end
|
||||
if hasC then
|
||||
put(out, 2, "*MESH_NUMCVERTEX " .. nv)
|
||||
put(out, 2, "*MESH_CVERTLIST {")
|
||||
for i = 0, nv - 1 do
|
||||
put(out, 3, "*MESH_VERTCOL " .. i .. "\t" .. f(C[i * 3 + 1]) .. "\t" .. f(C[i * 3 + 2]) .. "\t" .. f(C[i * 3 + 3]))
|
||||
end
|
||||
put(out, 2, "}")
|
||||
put(out, 2, "*MESH_NUMCVFACES " .. nf)
|
||||
put(out, 2, "*MESH_CFACELIST {")
|
||||
for i = 0, nf - 1 do
|
||||
put(out, 3, "*MESH_CFACE " .. i .. "\t" .. F[i * 3 + 1] .. "\t" .. F[i * 3 + 2] .. "\t" .. F[i * 3 + 3])
|
||||
end
|
||||
put(out, 2, "}")
|
||||
end
|
||||
if hasN then
|
||||
put(out, 2, "*MESH_NORMALS {")
|
||||
for i = 0, nf - 1 do
|
||||
local a, b, c = F[i * 3 + 1], F[i * 3 + 2], F[i * 3 + 3]
|
||||
local ux, uy, uz = P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3]
|
||||
local vx, vy, vz = P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3]
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
local len = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
if len > 0 then
|
||||
nx, ny, nz = nx / len, ny / len, nz / len
|
||||
end
|
||||
put(out, 3, "*MESH_FACENORMAL " .. i .. "\t" .. f(nx) .. "\t" .. f(ny) .. "\t" .. f(nz))
|
||||
for _, v in { a, b, c } do
|
||||
put(out, 4, "*MESH_VERTEXNORMAL " .. v .. "\t" .. f(N[v * 3 + 1]) .. "\t" .. f(N[v * 3 + 2]) .. "\t" .. f(N[v * 3 + 3]))
|
||||
end
|
||||
end
|
||||
put(out, 2, "}")
|
||||
end
|
||||
put(out, 1, "}")
|
||||
return true
|
||||
end
|
||||
|
||||
function Write.scene(scene: any, opts: any): (string?, string?)
|
||||
local out: Out = { lines = {} }
|
||||
local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" then scene.meta.source else {}
|
||||
put(out, 0, "*3DSMAX_ASCIIEXPORT\t200")
|
||||
put(out, 0, "*COMMENT " .. q(if opts and type(opts.comment) == "string" then opts.comment else "AsciiExport-Version 2,00 - rosetta"))
|
||||
put(out, 0, "*SCENE {")
|
||||
put(out, 1, "*SCENE_FILENAME \"\"")
|
||||
put(out, 1, "*SCENE_FIRSTFRAME " .. math.floor(tonumber(src.firstFrame) or 0))
|
||||
put(out, 1, "*SCENE_LASTFRAME " .. math.floor(tonumber(src.lastFrame) or 100))
|
||||
put(out, 1, "*SCENE_FRAMESPEED " .. math.floor(tonumber(src.frameSpeed) or 30))
|
||||
put(out, 1, "*SCENE_TICKSPERFRAME " .. math.floor(tonumber(src.ticksPerFrame) or 160))
|
||||
put(out, 1, "*SCENE_BACKGROUND_STATIC 0.0000\t0.0000\t0.0000")
|
||||
put(out, 1, "*SCENE_AMBIENT_STATIC 0.0000\t0.0000\t0.0000")
|
||||
put(out, 0, "}")
|
||||
local mats = scene.materials or {}
|
||||
local nmat = #mats
|
||||
local matBase: { [number]: number } = {}
|
||||
-- a default sub-material for primitives without one, when other primitives have one
|
||||
local needDefault = false
|
||||
for _, mesh in scene.meshes or {} do
|
||||
for _, prim in mesh.primitives or {} do
|
||||
if not (prim.material and mats[prim.material]) then
|
||||
needDefault = true
|
||||
end
|
||||
end
|
||||
end
|
||||
put(out, 0, "*MATERIAL_LIST {")
|
||||
if nmat > 0 then
|
||||
put(out, 1, "*MATERIAL_COUNT 1")
|
||||
put(out, 1, "*MATERIAL 0 {")
|
||||
put(out, 2, "*MATERIAL_NAME \"Multimaterial\"")
|
||||
put(out, 2, "*MATERIAL_CLASS \"Multi/Sub-Object\"")
|
||||
put(out, 2, "*NUMSUBMTLS " .. (nmat + (if needDefault then 1 else 0)))
|
||||
for i, m in mats do
|
||||
matBase[i] = i - 1
|
||||
local mm = table.clone(m)
|
||||
mm._textures = scene.textures
|
||||
material(out, 2, "SUBMATERIAL", i - 1, mm)
|
||||
end
|
||||
if needDefault then
|
||||
material(out, 2, "SUBMATERIAL", nmat, S.material("Default"))
|
||||
end
|
||||
put(out, 1, "}")
|
||||
else
|
||||
put(out, 1, "*MATERIAL_COUNT 0")
|
||||
end
|
||||
put(out, 0, "}")
|
||||
-- world matrices and unique names
|
||||
local nodes = scene.nodes or {}
|
||||
local worlds: { [number]: { number } } = {}
|
||||
local parentOf: { [number]: number } = {}
|
||||
local order: { number } = {}
|
||||
local function walk(i: number, parent: { number }, depth: number)
|
||||
local node = nodes[i]
|
||||
if not node or worlds[i] or depth > 256 then
|
||||
return
|
||||
end
|
||||
worlds[i] = S.mul(parent, S.nodeMatrix(node))
|
||||
table.insert(order, i)
|
||||
for _, c in node.children or {} do
|
||||
if nodes[c] and not worlds[c] then
|
||||
parentOf[c] = i
|
||||
walk(c, worlds[i], depth + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local roots = scene.roots or {}
|
||||
if #roots == 0 then
|
||||
for i in nodes do
|
||||
table.insert(roots, i)
|
||||
end
|
||||
end
|
||||
for _, r in roots do
|
||||
walk(r, S.IDENTITY, 0)
|
||||
end
|
||||
local names: { [number]: string } = {}
|
||||
local used: { [string]: boolean } = {}
|
||||
for _, i in order do
|
||||
local base = if type(nodes[i].name) == "string" and nodes[i].name ~= "" then nodes[i].name else "Object" .. i
|
||||
local name, k = base, 1
|
||||
while used[name] do
|
||||
k += 1
|
||||
name = base .. "_" .. k
|
||||
end
|
||||
used[name] = true
|
||||
names[i] = name
|
||||
end
|
||||
for _, i in order do
|
||||
local node = nodes[i]
|
||||
local w = worlds[i]
|
||||
local mesh = if node.mesh then (scene.meshes or {})[node.mesh] else nil
|
||||
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 key = if mesh then "GEOMOBJECT" elseif cam then "CAMERAOBJECT" elseif li then "LIGHTOBJECT" else "HELPEROBJECT"
|
||||
put(out, 0, "*" .. key .. " {")
|
||||
put(out, 1, "*NODE_NAME " .. q(names[i]))
|
||||
if parentOf[i] then
|
||||
put(out, 1, "*NODE_PARENT " .. q(names[parentOf[i]]))
|
||||
end
|
||||
if key == "HELPEROBJECT" then
|
||||
put(out, 1, "*HELPER_CLASS \"Dummy\"")
|
||||
elseif key == "CAMERAOBJECT" then
|
||||
put(out, 1, "*CAMERA_TYPE Free")
|
||||
elseif key == "LIGHTOBJECT" then
|
||||
put(out, 1, "*LIGHT_TYPE " .. (if li.type == "spot" then "Free" elseif li.type == "directional" then "Directional" else "Omni"))
|
||||
end
|
||||
nodeTm(out, names[i], w)
|
||||
if mesh then
|
||||
geom(out, scene, mesh, w, matBase, nmat > 0)
|
||||
put(out, 1, "*PROP_MOTIONBLUR 0")
|
||||
put(out, 1, "*PROP_CASTSHADOW 1")
|
||||
put(out, 1, "*PROP_RECVSHADOW 1")
|
||||
if nmat > 0 then
|
||||
put(out, 1, "*MATERIAL_REF 0")
|
||||
end
|
||||
elseif cam then
|
||||
put(out, 1, "*CAMERA_SETTINGS {")
|
||||
put(out, 2, "*TIMEVALUE 0")
|
||||
put(out, 2, "*CAMERA_NEAR " .. f(cam.znear or 0))
|
||||
put(out, 2, "*CAMERA_FAR " .. f(cam.zfar or 1000))
|
||||
put(out, 2, "*CAMERA_FOV " .. f(cam.yfov or math.rad(45)))
|
||||
put(out, 2, "*CAMERA_TDIST 100.0000")
|
||||
put(out, 1, "}")
|
||||
elseif li then
|
||||
local c = if type(li.color) == "table" then li.color else { 1, 1, 1 }
|
||||
put(out, 1, "*LIGHT_SETTINGS {")
|
||||
put(out, 2, "*TIMEVALUE 0")
|
||||
put(out, 2, "*LIGHT_COLOR " .. f(c[1] or 1) .. "\t" .. f(c[2] or 1) .. "\t" .. f(c[3] or 1))
|
||||
put(out, 2, "*LIGHT_INTENS " .. f(li.intensity or 1))
|
||||
put(out, 2, "*LIGHT_HOTSPOT " .. f(math.deg(li.innerCone or 0) * 2))
|
||||
put(out, 2, "*LIGHT_FALLOFF " .. f(math.deg(li.outerCone or math.pi / 4) * 2))
|
||||
put(out, 1, "}")
|
||||
end
|
||||
put(out, 0, "}")
|
||||
end
|
||||
return table.concat(out.lines, "\n") .. "\n", nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,121 @@
|
||||
--!strict
|
||||
-- model/ase: 3ds Max ASCII Scene Export (*3DSMAX_ASCIIEXPORT 200), read + write; checked against assimp's ASE loader.
|
||||
-- Supports: geometry objects (texture channels, vertex colours, explicit normals, Multi/Sub-Object materials by
|
||||
-- *MESH_MTLID), NODE_TM hierarchies, helpers, cameras, lights, material maps (paths; data through opts.resolve),
|
||||
-- UTF-16 files. Not supported: *TM_ANIMATION tracks (meta.source.animated is set), shapes (nodes only), bones.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
local Parse = require("@rosetta/model/ase/Parse")
|
||||
local Build = require("@rosetta/model/ase/Build")
|
||||
local Write = require("@rosetta/model/ase/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ase = {
|
||||
name = "ase",
|
||||
category = "model",
|
||||
extensions = { "ase", "ask" },
|
||||
mime = { "model/x-ase", "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/model/Mat4" },
|
||||
caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, vertexColors = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxItems: number?, -- default 2^24 (*KEY items)
|
||||
maxVertices: number?, -- default 2^24 (per object)
|
||||
resolve: ((string) -> buffer?)?, -- texture bitmaps by path
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
comment: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "*3DSMAX_ASCIIEXPORT"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function utf16(r: Bytes.Reader): (boolean?, boolean)
|
||||
local h = r:peek(2)
|
||||
if h == "\255\254" then
|
||||
return true, false
|
||||
elseif h == "\254\255" then
|
||||
return true, true
|
||||
elseif #h == 2 and string.byte(h, 2) == 0 and string.byte(h, 1) == 42 then
|
||||
return true, false
|
||||
elseif #h == 2 and string.byte(h, 1) == 0 and string.byte(h, 2) == 42 then
|
||||
return true, true
|
||||
end
|
||||
return nil, false
|
||||
end
|
||||
|
||||
local function text(r: Bytes.Reader, n: number?): string
|
||||
local wide, be = utf16(r)
|
||||
local len = r.limit - r.pos
|
||||
if n then
|
||||
len = math.min(len, n)
|
||||
end
|
||||
if wide then
|
||||
local skip = if r:peek(2) == "\255\254" or r:peek(2) == "\254\255" then 2 else 0
|
||||
return Text.utf16(r.buf, r.pos + skip, len - skip, be)
|
||||
end
|
||||
return Text.toUtf8(buffer.readstring(r.buf, r.pos, len))
|
||||
end
|
||||
|
||||
function Ase.sniff(r: Bytes.Reader): number
|
||||
local h = string.match(text(r, 256), "^%s*(%*[%w_]+)")
|
||||
if h == MAGIC then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ase.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
if r.limit - r.pos > (o.maxBytes or 2 ^ 28) then
|
||||
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
|
||||
end
|
||||
local s = text(r)
|
||||
if not string.match(s, "^%s*%*") then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ASE file")
|
||||
end
|
||||
local ok, root, msg = pcall(Parse.tree, s, o.maxItems or 2 ^ 24)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root))
|
||||
end
|
||||
if not root then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
local ok2, scene, msg2 = pcall(Build.scene, root, o)
|
||||
if not ok2 then
|
||||
return nil, Err.from(tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg2)
|
||||
end
|
||||
if #scene.nodes == 0 and (scene.meta.source :: any).version == nil then
|
||||
return nil, Err.new(Err.CORRUPT, "no *3DSMAX_ASCIIEXPORT header and no objects")
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ase.encode(scene: Types.Scene, opts: EncodeOptions?): (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, s, msg = pcall(Write.scene, scene, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(s))
|
||||
end
|
||||
if not s then
|
||||
return nil, Err.new(Err.ARG, msg or "bad scene")
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Ase
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,403 @@
|
||||
--!strict
|
||||
-- model/t3d/Build: parsed T3D blocks into a Scene: one node per actor (Unreal's own Z-up, left-handed coordinates,
|
||||
-- kept as they are), brush polygons as primitives per texture (codecs/model/Brush). Brush transform as UnrealEd's
|
||||
-- ABrush coords: v - PrePivot, MainScale, Rotation, PostScale, + Location. Rotation as FRotationMatrix (Pitch / Yaw /
|
||||
-- Roll: 65536 units per turn, or degrees in UE4 text). Polygon winding follows the stored Normal; subtractive
|
||||
-- brushes face inwards.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Brush = require("@rosetta/codecs/model/Brush")
|
||||
local Parse = require("@rosetta/model/t3d/Parse")
|
||||
|
||||
type Block = Parse.Block
|
||||
|
||||
local Build = {}
|
||||
|
||||
local S = Types.Scene
|
||||
|
||||
local function num(v: any, d: number): number
|
||||
return if type(v) == "number" and v == v then v else d
|
||||
end
|
||||
|
||||
local function vec3(s: string?): { number }?
|
||||
if type(s) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local a, b, c = string.match(s, "^%s*([^,%s]+)%s*,%s*([^,%s]+)%s*,%s*([^,%s]+)")
|
||||
if not a then
|
||||
return nil
|
||||
end
|
||||
local x, y, z = tonumber((string.gsub(a, "^%+", ""))), tonumber((string.gsub(b :: string, "^%+", ""))), tonumber((string.gsub(c :: string, "^%+", "")))
|
||||
if x and y and z then
|
||||
return { x, y, z }
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function xyz(v: any, d: { number }): { number }
|
||||
if type(v) == "table" then
|
||||
return { num(v.X, d[1]), num(v.Y, d[2]), num(v.Z, d[3]) }
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
-- FRotationMatrix rows are the X / Y / Z axes: the columns of a column-major matrix
|
||||
local function rotation(r: any, degrees: boolean): { number }
|
||||
if type(r) ~= "table" then
|
||||
return S.IDENTITY
|
||||
end
|
||||
local k = if degrees then math.pi / 180 else math.pi * 2 / 65536
|
||||
local p, y, ro = num(r.Pitch, 0) * k, num(r.Yaw, 0) * k, num(r.Roll, 0) * k
|
||||
local SP, CP, SY, CY, SR, CR = math.sin(p), math.cos(p), math.sin(y), math.cos(y), math.sin(ro), math.cos(ro)
|
||||
return {
|
||||
CP * CY, CP * SY, SP, 0,
|
||||
SR * SP * CY - CR * SY, SR * SP * SY + CR * CY, -SR * CP, 0,
|
||||
-(CR * SP * CY + SR * SY), CY * SR - CR * SP * SY, CR * CP, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
local function scaling(s: { number }): { number }
|
||||
return { s[1], 0, 0, 0, 0, s[2], 0, 0, 0, 0, s[3], 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
local function translation(t: { number }): { number }
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t[1], t[2], t[3], 1 }
|
||||
end
|
||||
|
||||
local function plain(b: Block): { [string]: any }
|
||||
local out: { [string]: any } = {}
|
||||
for _, k in b.order do
|
||||
out[k] = b.props[k]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the component holding the actor's transform (UE4: RootComponent's Relative* properties)
|
||||
local function component(actor: Block, objects: { [string]: { [string]: any } }): { [string]: any }?
|
||||
local root = actor.props.RootComponent
|
||||
if type(root) == "string" then
|
||||
local name = string.match(root, "'\"?([^'\"]+)\"?'") or root
|
||||
name = string.match(name, "([^%.:]+)$") or name
|
||||
if objects[name] then
|
||||
return objects[name]
|
||||
end
|
||||
end
|
||||
for _, o in objects do
|
||||
if o.RelativeLocation ~= nil or o.RelativeRotation ~= nil or o.RelativeScale3D ~= nil then
|
||||
return o
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function polygons(b: Block, out: { Block })
|
||||
for _, c in b.children do
|
||||
local k = string.lower(c.kind)
|
||||
if k == "polygon" then
|
||||
table.insert(out, c)
|
||||
elseif k == "polylist" or k == "brush" then
|
||||
polygons(c, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
type Ctx = { scene: Types.Scene, materials: { [string]: number }, opts: any, polys: number }
|
||||
|
||||
local function material(ctx: Ctx, name: string): number
|
||||
local m = ctx.materials[name]
|
||||
if m then
|
||||
return m
|
||||
end
|
||||
local mat = S.material(if name ~= "" then name else nil)
|
||||
mat.metallic = 0
|
||||
if name ~= "" then
|
||||
table.insert(ctx.scene.textures, { name = name })
|
||||
mat.baseColorTexture = { texture = #ctx.scene.textures }
|
||||
end
|
||||
mat.extras = { t3d = { texture = name } }
|
||||
table.insert(ctx.scene.materials, mat)
|
||||
ctx.materials[name] = #ctx.scene.materials
|
||||
return #ctx.scene.materials
|
||||
end
|
||||
|
||||
-- the brush's polygons as Scene primitives (local brush space)
|
||||
local function brushMesh(ctx: Ctx, brush: Block, subtract: boolean): (Types.Mesh?, string?)
|
||||
local list: { Block } = {}
|
||||
polygons(brush, list)
|
||||
if #list == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
local faces: { Brush.Face } = {}
|
||||
local polys: { Brush.Polygon } = {}
|
||||
local flags: { number } = {}
|
||||
for _, pb in list do
|
||||
local rec: { [string]: string } = {}
|
||||
local verts: { number } = {}
|
||||
for _, r in pb.records do
|
||||
local name = string.lower(r[1])
|
||||
if name == "vertex" then
|
||||
local v = vec3(r[2])
|
||||
if v then
|
||||
table.insert(verts, v[1])
|
||||
table.insert(verts, v[2])
|
||||
table.insert(verts, v[3])
|
||||
end
|
||||
elseif rec[name] == nil then
|
||||
rec[name] = r[2]
|
||||
end
|
||||
end
|
||||
local nv = #verts // 3
|
||||
if nv >= 3 then
|
||||
ctx.polys += 1
|
||||
if ctx.polys > (ctx.opts.maxPolygons or 2 ^ 20) then
|
||||
return nil, "limit: over " .. (ctx.opts.maxPolygons or 2 ^ 20) .. " polygons"
|
||||
end
|
||||
-- Newell normal of the vertex order
|
||||
local nx, ny, nz = 0, 0, 0
|
||||
for k = 0, nv - 1 do
|
||||
local j = (k + 1) % nv
|
||||
local ax, ay, az = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3]
|
||||
local bx, by, bz = verts[j * 3 + 1], verts[j * 3 + 2], verts[j * 3 + 3]
|
||||
nx += (ay - by) * (az + bz)
|
||||
ny += (az - bz) * (ax + bx)
|
||||
nz += (ax - bx) * (ay + by)
|
||||
end
|
||||
local stated = vec3(rec.normal)
|
||||
local n = stated or { nx, ny, nz }
|
||||
local l = math.sqrt(n[1] * n[1] + n[2] * n[2] + n[3] * n[3])
|
||||
if l > 0 then
|
||||
n = { n[1] / l, n[2] / l, n[3] / l }
|
||||
end
|
||||
local reverse = nx * n[1] + ny * n[2] + nz * n[3] < 0
|
||||
if subtract then
|
||||
reverse = not reverse
|
||||
n = { -n[1], -n[2], -n[3] }
|
||||
end
|
||||
if reverse then
|
||||
local r: { number } = {}
|
||||
for k = nv - 1, 0, -1 do
|
||||
table.insert(r, verts[k * 3 + 1])
|
||||
table.insert(r, verts[k * 3 + 2])
|
||||
table.insert(r, verts[k * 3 + 3])
|
||||
end
|
||||
verts = r
|
||||
end
|
||||
local tex = if type(pb.attrs.Texture) == "string" then pb.attrs.Texture else (if pb.attrs.Texture ~= nil then tostring(pb.attrs.Texture) else "")
|
||||
local o = vec3(rec.origin) or { 0, 0, 0 }
|
||||
local u = vec3(rec.textureu) or { 1, 0, 0 }
|
||||
local v = vec3(rec.texturev) or { 0, 1, 0 }
|
||||
local panU, panV = 0, 0
|
||||
if rec.pan then
|
||||
panU = tonumber(string.match(rec.pan, "U=%s*([-+]?[%d%.]+)")) or 0
|
||||
panV = tonumber(string.match(rec.pan, "V=%s*([-+]?[%d%.]+)")) or 0
|
||||
end
|
||||
-- texel = (p - Origin) . TextureU + PanU
|
||||
local face: Brush.Face = {
|
||||
plane = { n[1], n[2], n[3], n[1] * o[1] + n[2] * o[2] + n[3] * o[3] },
|
||||
texture = tex,
|
||||
vecs = {
|
||||
{ u[1], u[2], u[3], panU - (o[1] * u[1] + o[2] * u[2] + o[3] * u[3]) },
|
||||
{ v[1], v[2], v[3], panV - (o[1] * v[1] + o[2] * v[2] + o[3] * v[3]) },
|
||||
},
|
||||
}
|
||||
table.insert(faces, face)
|
||||
table.insert(polys, { brush = 1, face = #faces, points = verts, normal = n })
|
||||
table.insert(flags, num(pb.attrs.Flags, 0))
|
||||
end
|
||||
end
|
||||
local size = ctx.opts.textureSize
|
||||
local built = Brush.primitives(polys, { faces }, function(name: string): (number, number)
|
||||
if type(size) == "function" then
|
||||
local ok, w, h = pcall(size, name)
|
||||
if ok and type(w) == "number" then
|
||||
return w, if type(h) == "number" then h else w
|
||||
end
|
||||
elseif type(size) == "table" and type(size[name]) == "table" then
|
||||
return num(size[name][1], 256), num(size[name][2], 256)
|
||||
end
|
||||
return 256, 256
|
||||
end)
|
||||
local mesh: Types.Mesh = { name = if type(brush.attrs.Name) == "string" then brush.attrs.Name else nil, primitives = {} }
|
||||
for _, b in built do
|
||||
b.primitive.material = material(ctx, b.texture)
|
||||
table.insert(mesh.primitives, b.primitive)
|
||||
end
|
||||
mesh.extras = { t3d = { polygons = #polys } }
|
||||
return mesh, nil
|
||||
end
|
||||
|
||||
local LIGHTS: { [string]: "point" | "spot" | "directional" } = {
|
||||
Light = "point", PointLight = "point", SpotLight = "spot", DirectionalLight = "directional", TriggerLight = "point",
|
||||
SkyLight = "directional", Spotlight = "spot", SunLight = "directional", DominantDirectionalLight = "directional",
|
||||
PointLightMovable = "point", SpotLightMovable = "spot", DirectionalLightMovable = "directional",
|
||||
}
|
||||
|
||||
-- HSV of UE1 lights: LightHue / LightSaturation (255 = white) / LightBrightness, all 0..255
|
||||
local function hsv(h: number, s: number): { number }
|
||||
local hh = (h % 256) / 256 * 6
|
||||
local i = math.floor(hh)
|
||||
local f = hh - i
|
||||
local p, q, t = 1 - s, 1 - s * f, 1 - s * (1 - f)
|
||||
local rgb = ({ { 1, t, p }, { q, 1, p }, { p, 1, t }, { p, q, 1 }, { t, p, 1 }, { 1, p, q } })[i % 6 + 1]
|
||||
return rgb
|
||||
end
|
||||
|
||||
local function light(ctx: Ctx, class: string, p: { [string]: any }, comp: { [string]: any }?): number
|
||||
local typ = LIGHTS[class]
|
||||
local l: Types.Light = { type = typ, color = { 1, 1, 1 }, intensity = 1 }
|
||||
if p.LightBrightness ~= nil or p.LightHue ~= nil or p.LightSaturation ~= nil then
|
||||
l.color = hsv(num(p.LightHue, 0), 1 - num(p.LightSaturation, 255) / 255)
|
||||
l.intensity = num(p.LightBrightness, 64) / 255
|
||||
end
|
||||
local c: any = comp or {}
|
||||
local col = c.LightColor or p.LightColor
|
||||
if type(col) == "table" then
|
||||
l.color = { num(col.R, 255) / 255, num(col.G, 255) / 255, num(col.B, 255) / 255 }
|
||||
end
|
||||
if c.Intensity ~= nil or c.Brightness ~= nil then
|
||||
l.intensity = num(c.Intensity, num(c.Brightness, 1))
|
||||
end
|
||||
local radius = c.AttenuationRadius or c.Radius
|
||||
if type(radius) == "number" then
|
||||
l.range = radius
|
||||
end
|
||||
if typ == "spot" then
|
||||
l.outerCone = math.rad(num(c.OuterConeAngle, num(p.LightCone, 44)))
|
||||
l.innerCone = math.rad(num(c.InnerConeAngle, 0))
|
||||
end
|
||||
table.insert(ctx.scene.lights, l)
|
||||
return #ctx.scene.lights
|
||||
end
|
||||
|
||||
local function actors(b: Block, out: { Block })
|
||||
for _, c in b.children do
|
||||
local k = string.lower(c.kind)
|
||||
if k == "actor" then
|
||||
table.insert(out, c)
|
||||
elseif k == "map" or k == "level" or k == "surface" then
|
||||
actors(c, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Build.scene(root: Block, opts: any): (Types.Scene?, string?)
|
||||
local sc = S.new()
|
||||
sc.meta.up = "z"
|
||||
sc.meta.handedness = "left"
|
||||
local list: { Block } = {}
|
||||
actors(root, list)
|
||||
local ctx: Ctx = { scene = sc, materials = {}, opts = opts or {}, polys = 0 }
|
||||
local ue4 = false
|
||||
for _, a in list do
|
||||
local rawClass = if a.attrs.Class ~= nil then tostring(a.attrs.Class) else "Actor"
|
||||
local class = string.match(rawClass, "([%w_]+)$") or rawClass
|
||||
if string.find(rawClass, "/Script/", 1, true) then
|
||||
ue4 = true
|
||||
end
|
||||
local p = a.props
|
||||
local objects: { [string]: { [string]: any } } = {}
|
||||
local objectClass: { [string]: string } = {}
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "object" then
|
||||
local name = if c.attrs.Name ~= nil then tostring(c.attrs.Name) else ("Object" .. #a.children)
|
||||
local o = objects[name] or {}
|
||||
for _, k in c.order do
|
||||
o[k] = c.props[k]
|
||||
end
|
||||
objects[name] = o
|
||||
if c.attrs.Class ~= nil then
|
||||
objectClass[name] = tostring(c.attrs.Class)
|
||||
end
|
||||
end
|
||||
end
|
||||
local comp = component(a, objects)
|
||||
local node: Types.Node = { name = if a.attrs.Name ~= nil then tostring(a.attrs.Name) else class, children = {} }
|
||||
local m: { number }
|
||||
if comp and p.Location == nil then
|
||||
local deg = true
|
||||
local loc = xyz(comp.RelativeLocation, { 0, 0, 0 })
|
||||
local sc3 = xyz(comp.RelativeScale3D, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(rotation(comp.RelativeRotation, deg), scaling(sc3)))
|
||||
else
|
||||
local loc = xyz(p.Location, { 0, 0, 0 })
|
||||
local deg = a.degrees.Rotation == true
|
||||
local rot = rotation(p.Rotation, deg)
|
||||
local isBrush = false
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "brush" then
|
||||
isBrush = true
|
||||
end
|
||||
end
|
||||
if isBrush then
|
||||
local pre = xyz(p.PrePivot, { 0, 0, 0 })
|
||||
local main = xyz(type(p.MainScale) == "table" and p.MainScale.Scale, { 1, 1, 1 })
|
||||
local post = xyz(type(p.PostScale) == "table" and p.PostScale.Scale, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(scaling(post), S.mul(rot, S.mul(scaling(main), translation({ -pre[1], -pre[2], -pre[3] })))))
|
||||
else
|
||||
local ds = num(p.DrawScale, 1)
|
||||
local s3 = xyz(p.DrawScale3D, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(rot, scaling({ s3[1] * ds, s3[2] * ds, s3[3] * ds })))
|
||||
end
|
||||
end
|
||||
node.matrix = m
|
||||
local csg = if type(p.CsgOper) == "string" then p.CsgOper
|
||||
elseif p.BrushType == "Brush_Subtract" then "CSG_Subtract"
|
||||
elseif p.BrushType == "Brush_Add" then "CSG_Add"
|
||||
else nil
|
||||
local extras: { [string]: any } = { class = rawClass, properties = plain(a), csg = csg }
|
||||
if next(objects) then
|
||||
extras.objects = objects
|
||||
extras.objectClasses = objectClass
|
||||
end
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "brush" then
|
||||
local builder = csg == "CSG_Active" or (class == "Brush" and csg == nil and node.name == "Brush")
|
||||
extras.builder = if builder then true else nil
|
||||
if not builder or ctx.opts.builder then
|
||||
local mesh, err = brushMesh(ctx, c, csg == "CSG_Subtract")
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
if mesh then
|
||||
table.insert(sc.meshes, mesh)
|
||||
node.mesh = #sc.meshes
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if LIGHTS[class] then
|
||||
local lc: { [string]: any }? = nil
|
||||
for name, o in objects do
|
||||
if string.find(objectClass[name] or name, "Light", 1, true) then
|
||||
lc = o
|
||||
end
|
||||
end
|
||||
node.light = light(ctx, class, p, lc)
|
||||
elseif class == "CameraActor" or class == "Camera" then
|
||||
local fov = num(p.FOVAngle, 90)
|
||||
for _, o in objects do
|
||||
if o.FieldOfView ~= nil then
|
||||
fov = num(o.FieldOfView, fov)
|
||||
end
|
||||
end
|
||||
table.insert(sc.cameras, { type = "perspective", yfov = math.rad(fov), znear = 1 } :: any)
|
||||
node.camera = #sc.cameras
|
||||
end
|
||||
local sm = p.StaticMesh
|
||||
for _, o in objects do
|
||||
if o.StaticMesh ~= nil then
|
||||
sm = o.StaticMesh
|
||||
end
|
||||
end
|
||||
if type(sm) == "string" then
|
||||
extras.staticMesh = string.match(sm, "'\"?([^'\"]+)\"?'") or sm
|
||||
end
|
||||
node.extras = { t3d = extras }
|
||||
table.insert(sc.nodes, node)
|
||||
table.insert(sc.roots, #sc.nodes)
|
||||
end
|
||||
sc.meta.source = { format = "t3d", engine = if ue4 then "ue4" else "ue1-3", actors = #list, polygons = ctx.polys }
|
||||
return sc, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- model/t3d/Parse: Unreal T3D text into nested blocks. A line `Begin <Kind> Key=Value ...` opens a block, `End <Kind>`
|
||||
-- closes it; other lines are `Key=Value` properties or, inside polygons, `Origin x,y,z` / `Vertex x,y,z` style
|
||||
-- records. Values: numbers, quoted strings, structs `(X=1,Y=2)` as tables, object references
|
||||
-- (`Model'MyLevel.Model1'`) as strings.
|
||||
local Parse = {}
|
||||
|
||||
export type Value = any
|
||||
export type Block = {
|
||||
kind: string,
|
||||
attrs: { [string]: Value },
|
||||
props: { [string]: Value },
|
||||
order: { string },
|
||||
records: { { string } },
|
||||
children: { Block },
|
||||
degrees: { [string]: boolean },
|
||||
}
|
||||
|
||||
-- "(X=1.0,Y=2,Z=-3)" / "(Scale=(X=1,Y=1,Z=1),SheerAxis=SHEER_ZX)"; i at '('
|
||||
local function struct(s: string, i: number, depth: number): (any, number)
|
||||
local out: { [any]: any } = {}
|
||||
local n = #s
|
||||
i += 1
|
||||
while i <= n do
|
||||
local c = string.sub(s, i, i)
|
||||
if c == ")" then
|
||||
return out, i + 1
|
||||
elseif c == "," or c == " " or c == "\t" then
|
||||
i += 1
|
||||
else
|
||||
local k, e = string.match(s, "^([^=,()]+)=()", i)
|
||||
if not k then
|
||||
-- an array element without a key: (1,2,3)
|
||||
local v, ni = Parse.value(s, i, depth + 1)
|
||||
table.insert(out, v)
|
||||
i = ni
|
||||
else
|
||||
local key = string.gsub(k :: string, "^%s+", "")
|
||||
local v, ni = Parse.value(s, e :: number, depth + 1)
|
||||
out[key] = v
|
||||
i = ni
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, i
|
||||
end
|
||||
|
||||
-- a value starting at i, up to the next unbracketed ',' / ')' (inside structs) or the end
|
||||
function Parse.value(s: string, i: number, depth: number): (any, number)
|
||||
local n = #s
|
||||
local c = string.sub(s, i, i)
|
||||
if c == "(" and depth < 32 then
|
||||
return struct(s, i, depth)
|
||||
elseif c == "\"" then
|
||||
local e = string.find(s, "\"", i + 1, true) or (n + 1)
|
||||
return string.sub(s, i + 1, e - 1), e + 1
|
||||
end
|
||||
-- a bare token; object references may hold quotes ('...' and "...")
|
||||
local j = i
|
||||
local q: string? = nil
|
||||
while j <= n do
|
||||
local ch = string.sub(s, j, j)
|
||||
if q then
|
||||
if ch == q then
|
||||
q = nil
|
||||
end
|
||||
elseif ch == "'" or ch == "\"" then
|
||||
q = ch
|
||||
elseif depth > 0 and (ch == "," or ch == ")") then
|
||||
break
|
||||
end
|
||||
j += 1
|
||||
end
|
||||
local tok = string.match(string.sub(s, i, j - 1), "^%s*(.-)%s*$") :: string
|
||||
local num = tonumber(tok)
|
||||
if num ~= nil and string.match(tok, "^[-+]?[%d%.]+[eE]?[-+]?%d*$") then
|
||||
return num, j
|
||||
end
|
||||
return tok, j
|
||||
end
|
||||
|
||||
-- Key=Value pairs of a Begin line ("Begin Actor Class=Light Name=Light0"); quoted values may hold spaces
|
||||
local function attrs(rest: string): { [string]: any }
|
||||
local out: { [string]: any } = {}
|
||||
local i, n = 1, #rest
|
||||
while i <= n do
|
||||
local k, e = string.match(rest, "^%s*([%w_%.]+)=()", i)
|
||||
if not k then
|
||||
break
|
||||
end
|
||||
local v: string
|
||||
if string.sub(rest, e :: number, e :: number) == "\"" then
|
||||
local q = string.find(rest, "\"", (e :: number) + 1, true) or (n + 1)
|
||||
v = string.sub(rest, (e :: number) + 1, q - 1)
|
||||
i = q + 1
|
||||
else
|
||||
local stop = string.find(rest, "%s", e :: number) or (n + 1)
|
||||
v = string.sub(rest, e :: number, stop - 1)
|
||||
i = stop
|
||||
end
|
||||
out[k :: string] = tonumber(v) or v
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function block(kind: string, a: { [string]: any }): Block
|
||||
return { kind = kind, attrs = a, props = {}, order = {}, records = {}, children = {}, degrees = {} }
|
||||
end
|
||||
|
||||
function Parse.tree(text: string, maxBlocks: number): (Block?, string?)
|
||||
local root = block("", {})
|
||||
local stack: { Block } = { root }
|
||||
local count = 0
|
||||
local lineNo = 0
|
||||
for raw in string.gmatch(text, "[^\n]*") do
|
||||
lineNo += 1
|
||||
local line = string.match(raw, "^%s*(.-)%s*$") :: string
|
||||
if line ~= "" and string.sub(line, 1, 2) ~= "//" then
|
||||
local cur = stack[#stack]
|
||||
local word, rest = string.match(line, "^(%a+)%s*(.*)$")
|
||||
local lw = if word then string.lower(word) else ""
|
||||
if lw == "begin" then
|
||||
local kind, after = string.match(rest :: string, "^(%S+)%s*(.*)$")
|
||||
if not kind then
|
||||
return nil, "Begin without a kind at line " .. lineNo
|
||||
end
|
||||
count += 1
|
||||
if count > maxBlocks then
|
||||
return nil, "limit: over " .. maxBlocks .. " blocks"
|
||||
end
|
||||
if #stack > 64 then
|
||||
return nil, "limit: blocks nested too deep"
|
||||
end
|
||||
local b = block(kind :: string, attrs(after :: string))
|
||||
table.insert(cur.children, b)
|
||||
table.insert(stack, b)
|
||||
elseif lw == "end" and #stack > 1 and (rest == "" or string.lower(string.match(rest :: string, "^(%S+)") or "") == string.lower(cur.kind)) then
|
||||
table.remove(stack)
|
||||
else
|
||||
local k, e = string.match(line, "^([%w_%(%)%[%]%.]+)%s*=()")
|
||||
if k then
|
||||
local v = Parse.value(line, e :: number, 0)
|
||||
if cur.props[k :: string] == nil then
|
||||
table.insert(cur.order, k :: string)
|
||||
end
|
||||
cur.props[k :: string] = v
|
||||
if string.find(string.sub(line, e :: number), "Pitch=[-+]?%d*%.") or string.find(string.sub(line, e :: number), "Yaw=[-+]?%d*%.") then
|
||||
cur.degrees[k :: string] = true
|
||||
end
|
||||
else
|
||||
-- a record: Origin / Normal / TextureU / TextureV / Vertex / Pan U=0 V=0
|
||||
local name, data = string.match(line, "^(%a+)%s+(.*)$")
|
||||
if name then
|
||||
table.insert(cur.records, { name :: string, data :: string })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #stack > 1 then
|
||||
return nil, "truncated: " .. stack[#stack].kind .. " block not closed"
|
||||
end
|
||||
return root, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,92 @@
|
||||
--!strict
|
||||
-- model/t3d: Unreal T3D text (UnrealEd map / brush export: Begin Map / Level / Actor / Brush / PolyList / Polygon,
|
||||
-- Begin Object components), read only. Supports: brush polygons with texture projection (TextureU / TextureV /
|
||||
-- Origin / Pan; sizes through opts.textureSize, default 256) as primitives per texture, CSG operation in extras
|
||||
-- (subtractive brushes face inwards; the builder brush is skipped), actors as nodes with their properties and
|
||||
-- transforms (UE1-3 Location / Rotation / DrawScale, UE4 RootComponent Relative*), lights, cameras, static mesh
|
||||
-- references. Not supported: BSP CSG between brushes, sheared brush scales, terrain, static mesh geometry.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Text = require("@rosetta/codecs/text/Text")
|
||||
local Parse = require("@rosetta/model/t3d/Parse")
|
||||
local Build = require("@rosetta/model/t3d/Build")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local T3d = {
|
||||
name = "t3d",
|
||||
category = "model",
|
||||
extensions = { "t3d" },
|
||||
mime = { "text/x-unreal-t3d" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Text", "codecs/model/Brush" },
|
||||
caps = { decode = true, encode = false, text = true, brushes = true, actors = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxBlocks: number?, -- default 2^22
|
||||
maxPolygons: number?, -- default 2^20
|
||||
textureSize: ((name: string) -> (number, number))? | { [string]: { number } }?, -- texture width, height (default 256)
|
||||
builder: boolean?, -- include the builder brush's geometry (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function T3d.sniff(r: Bytes.Reader): number
|
||||
local h = Sniff.text(r, 512)
|
||||
local first = string.match(h, "^%s*(Begin%s+%a+)")
|
||||
if first == nil then
|
||||
return 0
|
||||
end
|
||||
local kind = string.lower(string.match(first, "%a+$") or "")
|
||||
if kind == "map" or kind == "actor" or kind == "level" or kind == "brush" or kind == "polylist" then
|
||||
return 0.9
|
||||
end
|
||||
return 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function T3d.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)
|
||||
if string.sub(text, 1, 2) == "\255\254" then
|
||||
text = Text.utf16(r.buf, r.base + 2, r.limit - r.base - 2, false)
|
||||
else
|
||||
text = Text.toUtf8(text)
|
||||
end
|
||||
local ok, root, msg = pcall(Parse.tree, text, o.maxBlocks or 2 ^ 22)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root))
|
||||
end
|
||||
if not root then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
if #root.children == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no Begin blocks")
|
||||
end
|
||||
-- a bare brush export (Begin PolyList / Begin Brush): wrap it in an actor
|
||||
local k = string.lower(root.children[1].kind)
|
||||
if k == "polylist" or k == "brush" then
|
||||
local function block(kind: string, attrs: any, props: any, children: any): Parse.Block
|
||||
return { kind = kind, attrs = attrs, props = props, order = { "CsgOper" }, records = {}, degrees = {}, children = children }
|
||||
end
|
||||
local brush = if k == "brush" then root.children else { block("Brush", { Name = "Brush0" }, {}, root.children) }
|
||||
root = block("", {}, {}, { block("Actor", { Class = "Brush", Name = "Brush0" }, { CsgOper = "CSG_Add" }, brush) })
|
||||
end
|
||||
local ok2, scene, msg2 = pcall(Build.scene, root, o)
|
||||
if not ok2 then
|
||||
return nil, Err.from(tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg2)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return T3d
|
||||
@@ -0,0 +1,334 @@
|
||||
--!strict
|
||||
-- vector/ldtk/Read: an LDtk project (JSON, ldtk.io/json 1.5) into a Types.TileMap: one group layer per level (inside
|
||||
-- one group per world for multi-world projects), the level's layers bottom first. Tile gids are firstGid + the
|
||||
-- LDtk tile id with the f bits as Tiled's flip flags (bit 0 X -> 0x80000000, bit 1 Y -> 0x40000000).
|
||||
local Types = require("@rosetta/Types")
|
||||
local Json = require("@rosetta/codecs/text/Json")
|
||||
|
||||
local Read = {}
|
||||
|
||||
local FLIP_X, FLIP_Y = 0x80000000, 0x40000000
|
||||
|
||||
local function n(v: any, default: number): number
|
||||
return if type(v) == "number" then v else default
|
||||
end
|
||||
local function s(v: any): string?
|
||||
return if type(v) == "string" then v else nil
|
||||
end
|
||||
local NULL = Json.null
|
||||
local function tab(v: any): boolean
|
||||
return type(v) == "table" and v ~= NULL
|
||||
end
|
||||
local function list(v: any): { any }
|
||||
return if tab(v) then v else {}
|
||||
end
|
||||
|
||||
-- every key but the ones listed (the raw part kept for the writer)
|
||||
local function rest(t: any, skip: { [string]: boolean }): { [string]: any }
|
||||
local keys = Json.keys(t)
|
||||
local out: { [string]: any } = {}
|
||||
local order = {}
|
||||
for _, k in keys do
|
||||
if not skip[k] then
|
||||
out[k] = t[k]
|
||||
table.insert(order, k)
|
||||
end
|
||||
end
|
||||
return Json.object(out, order)
|
||||
end
|
||||
|
||||
function Read.fields(v: any): ({ [string]: any }, { [string]: string }?)
|
||||
local props: { [string]: any } = {}
|
||||
local types: { [string]: string }? = nil
|
||||
for _, f in list(v) do
|
||||
if type(f) == "table" and type(f.__identifier) == "string" then
|
||||
props[f.__identifier] = f.__value
|
||||
if type(f.__type) == "string" then
|
||||
types = types or {}
|
||||
;(types :: any)[f.__identifier] = f.__type
|
||||
end
|
||||
end
|
||||
end
|
||||
return props, types
|
||||
end
|
||||
|
||||
type Ctx = { tilesets: { [number]: Types.Tileset }, maxCells: number, layerDefs: { [number]: any } }
|
||||
|
||||
local function tiles(ctx: Ctx, raw: { any }, ts: Types.Tileset?, grid: number, cw: number, ch: number): ({ any }, { number }?)
|
||||
local out = table.create(#raw)
|
||||
local data: { number }? = nil
|
||||
if cw > 0 and ch > 0 then
|
||||
data = table.create(cw * ch, 0)
|
||||
end
|
||||
for i, t in raw do
|
||||
if type(t) == "table" then
|
||||
local px, src = list(t.px), list(t.src)
|
||||
local tile = {
|
||||
x = n(px[1], 0),
|
||||
y = n(px[2], 0),
|
||||
tile = n(t.t, 0),
|
||||
flip = n(t.f, 0),
|
||||
srcX = n(src[1], 0),
|
||||
srcY = n(src[2], 0),
|
||||
alpha = n(t.a, 1),
|
||||
d = t.d,
|
||||
}
|
||||
out[i] = tile
|
||||
if data and ts then
|
||||
local cx, cy = tile.x // grid, tile.y // grid
|
||||
if cx >= 0 and cy >= 0 and cx < cw and cy < ch then
|
||||
local gid = ts.firstGid + tile.tile
|
||||
if bit32.btest(tile.flip, 1) then
|
||||
gid += FLIP_X
|
||||
end
|
||||
if bit32.btest(tile.flip, 2) then
|
||||
gid += FLIP_Y
|
||||
end
|
||||
-- later tiles are drawn over earlier ones
|
||||
data[1 + cx + cy * cw] = gid
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, data
|
||||
end
|
||||
|
||||
local LAYER_SKIP = { __identifier = true, __type = true, __cWid = true, __cHei = true, __gridSize = true, __opacity = true, __pxTotalOffsetX = true, __pxTotalOffsetY = true, __tilesetDefUid = true, __tilesetRelPath = true, visible = true, intGridCsv = true, autoLayerTiles = true, gridTiles = true, entityInstances = true }
|
||||
local ENTITY_SKIP = { __identifier = true, __grid = true, __pivot = true, __tags = true, __tile = true, __smartColor = true, __worldX = true, __worldY = true, width = true, height = true, px = true, fieldInstances = true }
|
||||
|
||||
local function layer(ctx: Ctx, li: any): (Types.TileLayer?, string?)
|
||||
local kind = s(li.__type) or "Tiles"
|
||||
local cw, ch = n(li.__cWid, 0), n(li.__cHei, 0)
|
||||
if cw < 0 or ch < 0 or cw * ch > ctx.maxCells then
|
||||
return nil, "limit: layer of " .. cw .. " x " .. ch .. " cells"
|
||||
end
|
||||
local grid = math.max(1, n(li.__gridSize, 16))
|
||||
local out: Types.TileLayer = {
|
||||
name = s(li.__identifier) or "",
|
||||
type = if kind == "Entities" then "objects" else "tiles",
|
||||
visible = li.visible ~= false,
|
||||
opacity = n(li.__opacity, 1),
|
||||
properties = {},
|
||||
offsetX = n(li.__pxTotalOffsetX, 0),
|
||||
offsetY = n(li.__pxTotalOffsetY, 0),
|
||||
ldtkType = kind,
|
||||
gridSize = grid,
|
||||
ldtk = rest(li, LAYER_SKIP),
|
||||
}
|
||||
if kind == "Entities" then
|
||||
local objs = {}
|
||||
for _, e in list(li.entityInstances) do
|
||||
if type(e) == "table" then
|
||||
local w, h = n(e.width, 0), n(e.height, 0)
|
||||
local pv, px = list(e.__pivot), list(e.px)
|
||||
local pX, pY = n(pv[1], 0), n(pv[2], 0)
|
||||
local props, types = Read.fields(e.fieldInstances)
|
||||
local o: { [string]: any } = {
|
||||
id = s(e.iid),
|
||||
name = s(e.__identifier) or "",
|
||||
class = s(e.__identifier) or "",
|
||||
x = n(px[1], 0) - pX * w,
|
||||
y = n(px[2], 0) - pY * h,
|
||||
width = w,
|
||||
height = h,
|
||||
rotation = 0,
|
||||
visible = true,
|
||||
shape = "rectangle",
|
||||
pivot = { pX, pY },
|
||||
tags = e.__tags,
|
||||
tile = if tab(e.__tile) then e.__tile else nil,
|
||||
color = s(e.__smartColor),
|
||||
properties = props,
|
||||
propertyTypes = types,
|
||||
ldtk = rest(e, ENTITY_SKIP),
|
||||
fieldInstances = e.fieldInstances,
|
||||
}
|
||||
table.insert(objs, o)
|
||||
end
|
||||
end
|
||||
out.objects = objs
|
||||
return out, nil
|
||||
end
|
||||
out.width, out.height = cw, ch
|
||||
local tsUid = li.__tilesetDefUid
|
||||
local ts = if type(tsUid) == "number" then ctx.tilesets[tsUid] else nil
|
||||
if ts then
|
||||
out.tileset = ts.name
|
||||
end
|
||||
out.tilesetPath = s(li.__tilesetRelPath)
|
||||
local raw = if kind == "Tiles" then list(li.gridTiles) else list(li.autoLayerTiles)
|
||||
local tl, data = tiles(ctx, raw, ts, grid, cw, ch)
|
||||
out.tiles = tl
|
||||
out.data = data or {}
|
||||
if kind == "IntGrid" then
|
||||
local csv = list(li.intGridCsv)
|
||||
local grid2 = table.create(cw * ch, 0)
|
||||
for i = 1, math.min(#csv, cw * ch) do
|
||||
grid2[i] = n(csv[i], 0)
|
||||
end
|
||||
out.intGrid = grid2
|
||||
local def = if type(li.layerDefUid) == "number" then ctx.layerDefs[li.layerDefUid] else nil
|
||||
if def then
|
||||
local values = {}
|
||||
for _, v in list(def.intGridValues) do
|
||||
if type(v) == "table" then
|
||||
table.insert(values, { value = n(v.value, 0), identifier = s(v.identifier), color = s(v.color) })
|
||||
end
|
||||
end
|
||||
out.intGridValues = values
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local LEVEL_SKIP = { identifier = true, worldX = true, worldY = true, pxWid = true, pxHei = true, __bgColor = true, fieldInstances = true, layerInstances = true }
|
||||
|
||||
local function level(ctx: Ctx, lv: any, resolve: ((string) -> buffer?)?): (Types.TileLayer?, string?)
|
||||
local layers = lv.layerInstances
|
||||
local external = s(lv.externalRelPath)
|
||||
local unresolved = false
|
||||
if not tab(layers) and external then
|
||||
local data: any = nil
|
||||
if resolve then
|
||||
local ok, b = pcall(resolve, external)
|
||||
data = if ok and type(b) == "buffer" then b else nil
|
||||
end
|
||||
if data then
|
||||
local v, err = Json.decode(data, { ordered = true })
|
||||
if not tab(v) then
|
||||
return nil, "external level " .. external .. ": " .. tostring(err)
|
||||
end
|
||||
lv = v
|
||||
layers = v.layerInstances
|
||||
else
|
||||
unresolved = true
|
||||
end
|
||||
end
|
||||
local props, types = Read.fields(lv.fieldInstances)
|
||||
local g: Types.TileLayer = {
|
||||
name = s(lv.identifier) or "",
|
||||
type = "group",
|
||||
visible = true,
|
||||
opacity = 1,
|
||||
properties = props,
|
||||
propertyTypes = types,
|
||||
offsetX = n(lv.worldX, 0),
|
||||
offsetY = n(lv.worldY, 0),
|
||||
layers = {},
|
||||
level = true,
|
||||
pxWidth = n(lv.pxWid, 0),
|
||||
pxHeight = n(lv.pxHei, 0),
|
||||
backgroundColor = s(lv.__bgColor),
|
||||
external = external,
|
||||
unresolved = if unresolved then true else nil,
|
||||
ldtk = rest(lv, LEVEL_SKIP),
|
||||
}
|
||||
local ls = list(layers)
|
||||
for i = #ls, 1, -1 do
|
||||
local l, err = layer(ctx, ls[i])
|
||||
if not l then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(g.layers :: { any }, l)
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
local PROJECT_SKIP = { levels = true, worlds = true }
|
||||
|
||||
function Read.project(v: any, opts: any): (Types.TileMap?, string?)
|
||||
if not tab(v) or not tab(v.defs) then
|
||||
return nil, "no defs: not an LDtk project"
|
||||
end
|
||||
local grid = math.max(1, n(v.defaultGridSize, 16))
|
||||
local map = Types.TileMap.new(0, 0, grid, grid)
|
||||
local ctx: Ctx = { tilesets = {}, maxCells = opts.maxCells or 2 ^ 26, layerDefs = {} }
|
||||
local gid = 1
|
||||
for _, t in list(v.defs.tilesets) do
|
||||
if type(t) == "table" then
|
||||
local cw, ch = n(t.__cWid, 0), n(t.__cHei, 0)
|
||||
local size = n(t.tileGridSize, grid)
|
||||
local ts: Types.Tileset = {
|
||||
name = s(t.identifier) or ("tileset" .. #map.tilesets),
|
||||
firstGid = gid,
|
||||
tileWidth = size,
|
||||
tileHeight = size,
|
||||
columns = cw,
|
||||
count = cw * ch,
|
||||
imageSource = s(t.relPath),
|
||||
imageWidth = n(t.pxWid, 0),
|
||||
imageHeight = n(t.pxHei, 0),
|
||||
spacing = n(t.spacing, 0),
|
||||
margin = n(t.padding, 0),
|
||||
uid = t.uid,
|
||||
embedAtlas = s(t.embedAtlas),
|
||||
properties = {},
|
||||
}
|
||||
gid += math.max(1, cw * ch)
|
||||
table.insert(map.tilesets, ts)
|
||||
if type(t.uid) == "number" then
|
||||
ctx.tilesets[t.uid] = ts
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, d in list(v.defs.layers) do
|
||||
if type(d) == "table" and type(d.uid) == "number" then
|
||||
ctx.layerDefs[d.uid] = d
|
||||
end
|
||||
end
|
||||
local resolve = opts.resolve
|
||||
local worlds = list(v.worlds)
|
||||
local minX, minY, maxX, maxY = math.huge, math.huge, -math.huge, -math.huge
|
||||
local function addLevels(into: { any }, levels: any): string?
|
||||
for _, lv in list(levels) do
|
||||
if type(lv) == "table" then
|
||||
local g, err = level(ctx, lv, resolve)
|
||||
if not g then
|
||||
return err
|
||||
end
|
||||
local x, y = g.offsetX :: number, g.offsetY :: number
|
||||
minX, minY = math.min(minX, x), math.min(minY, y)
|
||||
maxX, maxY = math.max(maxX, x + (g.pxWidth :: number)), math.max(maxY, y + (g.pxHeight :: number))
|
||||
table.insert(into, g)
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
if #worlds > 0 then
|
||||
for _, w in worlds do
|
||||
if type(w) == "table" then
|
||||
local wg: Types.TileLayer = {
|
||||
name = s(w.identifier) or "",
|
||||
type = "group",
|
||||
visible = true,
|
||||
opacity = 1,
|
||||
properties = {},
|
||||
layers = {},
|
||||
world = true,
|
||||
ldtk = rest(w, { levels = true, identifier = true }),
|
||||
}
|
||||
local err = addLevels(wg.layers :: { any }, w.levels)
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(map.layers, wg)
|
||||
end
|
||||
end
|
||||
else
|
||||
local err = addLevels(map.layers, v.levels)
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
if minX <= maxX then
|
||||
map.width = math.ceil((maxX - math.min(minX, 0)) / grid)
|
||||
map.height = math.ceil((maxY - math.min(minY, 0)) / grid)
|
||||
end
|
||||
map.backgroundColor = s(v.bgColor)
|
||||
map.worldLayout = s(v.worldLayout)
|
||||
map.ldtk = rest(v, PROJECT_SKIP)
|
||||
map.meta.source = { format = "ldtk", version = s(v.jsonVersion), externalLevels = v.externalLevels == true, multiWorld = #worlds > 0 }
|
||||
return map, nil
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,646 @@
|
||||
--!strict
|
||||
-- vector/ldtk/Write: a Types.TileMap as an LDtk project (JSON 1.5). Maps read from LDtk keep their raw defs, project,
|
||||
-- level, layer and entity fields (the .ldtk tables); other maps get definitions made from their layers, tilesets and
|
||||
-- object classes. A tile layer writes its `tiles` list when present, else its gid `data`. Levels are always embedded.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Json = require("@rosetta/codecs/text/Json")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local NULL = Json.null
|
||||
local FLAGS = 0xF0000000
|
||||
|
||||
local function tab(v: any): boolean
|
||||
return type(v) == "table" and v ~= NULL
|
||||
end
|
||||
local function list(v: any): { any }
|
||||
return if tab(v) then v else {}
|
||||
end
|
||||
local function n(v: any, default: number): number
|
||||
return if type(v) == "number" and v == v then v else default
|
||||
end
|
||||
|
||||
type Ctx = {
|
||||
uid: number,
|
||||
iid: number,
|
||||
defs: any,
|
||||
tilesetByName: { [string]: any },
|
||||
tilesetByUid: { [number]: any },
|
||||
layerDefs: { [string]: any },
|
||||
entityDefs: { [string]: any },
|
||||
levelFields: { [string]: any },
|
||||
map: Types.TileMap,
|
||||
}
|
||||
|
||||
local function clone(t: any): any
|
||||
if not tab(t) then
|
||||
return Json.object({})
|
||||
end
|
||||
local keys = Json.keys(t)
|
||||
local out = {}
|
||||
for _, k in keys do
|
||||
out[k] = t[k]
|
||||
end
|
||||
return Json.object(out, keys)
|
||||
end
|
||||
|
||||
local function obj(pairs_: { any }): any
|
||||
local out, keys = {}, {}
|
||||
for i = 1, #pairs_, 2 do
|
||||
local k, v = pairs_[i], pairs_[i + 1]
|
||||
table.insert(keys, k)
|
||||
out[k] = v
|
||||
end
|
||||
return Json.object(out, keys)
|
||||
end
|
||||
|
||||
local function set(t: any, k: string, v: any)
|
||||
Json.set(t, k, if v == nil then NULL else v)
|
||||
end
|
||||
|
||||
local function nextUid(ctx: Ctx): number
|
||||
ctx.uid += 1
|
||||
return ctx.uid
|
||||
end
|
||||
|
||||
local function newIid(ctx: Ctx): string
|
||||
ctx.iid += 1
|
||||
return string.format("%08x-0000-4000-8000-%012x", 0x5ce7a000 + ctx.iid // 0x1000000, ctx.iid)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fields
|
||||
local function hexColor(v: any): number?
|
||||
if type(v) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local h = string.match(v, "^#(%x%x%x%x%x%x)$") or string.match(v, "^#%x%x(%x%x%x%x%x%x)$")
|
||||
return if h then tonumber(h, 16) else nil
|
||||
end
|
||||
|
||||
local function wrap(typ: string, v: any): any
|
||||
if v == nil or v == NULL then
|
||||
return NULL
|
||||
end
|
||||
if typ == "Int" then
|
||||
return obj({ "id", "V_Int", "params", { v } })
|
||||
elseif typ == "Float" then
|
||||
return obj({ "id", "V_Float", "params", { v } })
|
||||
elseif typ == "Bool" then
|
||||
return obj({ "id", "V_Bool", "params", { v == true } })
|
||||
elseif typ == "Color" then
|
||||
local c = hexColor(v)
|
||||
return if c then obj({ "id", "V_Int", "params", { c } }) else NULL
|
||||
elseif typ == "Point" and tab(v) then
|
||||
return obj({ "id", "V_String", "params", { tostring(v.cx) .. "," .. tostring(v.cy) } })
|
||||
elseif type(v) == "string" then
|
||||
return obj({ "id", "V_String", "params", { v } })
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function editorValues(typ: string, v: any): any
|
||||
local inner = string.match(typ, "^Array<(.+)>$")
|
||||
if inner then
|
||||
local out = {}
|
||||
for i, x in list(v) do
|
||||
local w = wrap(inner, x)
|
||||
if w == nil then
|
||||
return nil
|
||||
end
|
||||
out[i] = w
|
||||
end
|
||||
return out
|
||||
end
|
||||
local w = wrap(typ, v)
|
||||
return if w == nil then nil else { w }
|
||||
end
|
||||
|
||||
local function same(a: any, b: any): boolean
|
||||
if a == b then
|
||||
return true
|
||||
end
|
||||
if tab(a) and tab(b) then
|
||||
for k, x in a do
|
||||
if not same(x, b[k]) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
for k in b do
|
||||
if a[k] == nil then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local LDTK_TYPE: { [string]: string } = { int = "Int", float = "Float", bool = "Bool", string = "String", color = "Color", file = "FilePath" }
|
||||
|
||||
local function valueType(v: any): string
|
||||
if type(v) == "number" then
|
||||
return if v % 1 == 0 then "Int" else "Float"
|
||||
elseif type(v) == "boolean" then
|
||||
return "Bool"
|
||||
end
|
||||
return "String"
|
||||
end
|
||||
|
||||
local function fieldDef(ctx: Ctx, name: string, typ: string): any
|
||||
local isArray = string.match(typ, "^Array<") ~= nil
|
||||
local base = string.match(typ, "^Array<(.+)>$") or typ
|
||||
return obj({
|
||||
"identifier", name, "doc", NULL, "__type", typ, "uid", nextUid(ctx), "type", "F_" .. base, "isArray", isArray,
|
||||
"canBeNull", true, "arrayMinLength", NULL, "arrayMaxLength", NULL, "editorDisplayMode", "Hidden",
|
||||
"editorDisplayScale", 1, "editorDisplayPos", "Above", "editorLinkStyle", "StraightArrow", "editorDisplayColor", NULL,
|
||||
"editorAlwaysShow", false, "editorShowInWorld", true, "editorCutLongValues", true, "editorTextSuffix", NULL,
|
||||
"editorTextPrefix", NULL, "useForSmartColor", false, "exportToToc", false, "searchable", false, "min", NULL,
|
||||
"max", NULL, "regex", NULL, "acceptFileTypes", NULL, "defaultOverride", NULL, "textLanguageMode", NULL,
|
||||
"symmetricalRef", false, "autoChainRef", true, "allowOutOfLevelRef", true, "allowedRefs", "OnlySame",
|
||||
"allowedRefsEntityUid", NULL, "allowedRefTags", {}, "tilesetUid", NULL,
|
||||
})
|
||||
end
|
||||
|
||||
-- raw field instances updated from the properties; properties without an instance get one when a definition exists
|
||||
-- (or is made: makeDefs)
|
||||
local function fieldInstances(ctx: Ctx, raw: any, props: any, types: any, defs: { [string]: any }?, makeDefs: { any }?): { any }
|
||||
local out = {}
|
||||
local seen: { [string]: boolean } = {}
|
||||
props = if tab(props) then props else {}
|
||||
types = if tab(types) then types else {}
|
||||
for _, fi in list(raw) do
|
||||
if tab(fi) and type(fi.__identifier) == "string" then
|
||||
local id = fi.__identifier
|
||||
seen[id] = true
|
||||
local f = clone(fi)
|
||||
local v = props[id]
|
||||
if v ~= nil and not same(v, fi.__value) then
|
||||
set(f, "__value", v)
|
||||
local ev = editorValues(if type(fi.__type) == "string" then fi.__type else valueType(v), v)
|
||||
if ev then
|
||||
set(f, "realEditorValues", ev)
|
||||
end
|
||||
end
|
||||
table.insert(out, f)
|
||||
end
|
||||
end
|
||||
local names = {}
|
||||
for k in props do
|
||||
if type(k) == "string" and not seen[k] then
|
||||
table.insert(names, k)
|
||||
end
|
||||
end
|
||||
table.sort(names)
|
||||
for _, k in names do
|
||||
local v = props[k]
|
||||
local def = defs and defs[k]
|
||||
if not def and makeDefs and defs then
|
||||
local typ = if type(types[k]) == "string" then (LDTK_TYPE[types[k]] or types[k]) else valueType(v)
|
||||
def = fieldDef(ctx, k, typ)
|
||||
defs[k] = def
|
||||
table.insert(makeDefs, def)
|
||||
end
|
||||
if def then
|
||||
local typ = if type(def.__type) == "string" then def.__type else valueType(v)
|
||||
table.insert(out, obj({ "__identifier", k, "__type", typ, "__value", v, "__tile", NULL, "defUid", def.uid, "realEditorValues", editorValues(typ, v) or {} }))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ defs
|
||||
local function tilesetOf(ctx: Ctx, gid: number): any
|
||||
local best: any = nil
|
||||
for _, ts in ctx.map.tilesets do
|
||||
if ts.firstGid <= gid and (best == nil or ts.firstGid > best.firstGid) then
|
||||
best = ts
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
local function defsFor(ctx: Ctx, raw: any)
|
||||
local defs = if tab(raw) then clone(raw) else obj({ "layers", {}, "entities", {}, "tilesets", {}, "enums", {}, "externalEnums", {}, "levelFields", {} })
|
||||
for _, k in { "layers", "entities", "tilesets", "enums", "externalEnums", "levelFields" } do
|
||||
if not tab(defs[k]) then
|
||||
set(defs, k, {})
|
||||
end
|
||||
end
|
||||
ctx.defs = defs
|
||||
for _, d in list(defs.tilesets) do
|
||||
if tab(d) and type(d.uid) == "number" then
|
||||
ctx.uid = math.max(ctx.uid, d.uid)
|
||||
ctx.tilesetByUid[d.uid] = d
|
||||
if type(d.identifier) == "string" then
|
||||
ctx.tilesetByName[d.identifier] = d
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, d in list(defs.layers) do
|
||||
if tab(d) and type(d.identifier) == "string" then
|
||||
ctx.uid = math.max(ctx.uid, n(d.uid, 0))
|
||||
ctx.layerDefs[d.identifier] = d
|
||||
end
|
||||
end
|
||||
for _, d in list(defs.entities) do
|
||||
if tab(d) and type(d.identifier) == "string" then
|
||||
ctx.uid = math.max(ctx.uid, n(d.uid, 0))
|
||||
ctx.entityDefs[d.identifier] = d
|
||||
for _, f in list(d.fieldDefs) do
|
||||
ctx.uid = math.max(ctx.uid, n(tab(f) and f.uid, 0))
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, f in list(defs.levelFields) do
|
||||
if tab(f) and type(f.identifier) == "string" then
|
||||
ctx.uid = math.max(ctx.uid, n(f.uid, 0))
|
||||
ctx.levelFields[f.identifier] = f
|
||||
end
|
||||
end
|
||||
for _, d in list(defs.enums) do
|
||||
ctx.uid = math.max(ctx.uid, n(tab(d) and d.uid, 0))
|
||||
end
|
||||
-- tilesets of the map the defs lack
|
||||
for _, ts in ctx.map.tilesets do
|
||||
if type(ts.name) == "string" and not ctx.tilesetByName[ts.name] then
|
||||
local size = n(ts.tileWidth, 16)
|
||||
local cols = math.max(1, n(ts.columns, 1))
|
||||
local d = obj({
|
||||
"__cWid", cols, "__cHei", math.ceil(n(ts.count, cols) / cols), "identifier", ts.name, "uid", nextUid(ctx),
|
||||
"relPath", ts.imageSource or NULL, "embedAtlas", NULL, "pxWid", n(ts.imageWidth, cols * size),
|
||||
"pxHei", n(ts.imageHeight, math.ceil(n(ts.count, cols) / cols) * size), "tileGridSize", size,
|
||||
"spacing", n(ts.spacing, 0), "padding", n(ts.margin, 0), "tags", {}, "tagsSourceEnumUid", NULL,
|
||||
"enumTags", {}, "customData", {}, "savedSelections", {}, "cachedPixelData", NULL,
|
||||
})
|
||||
table.insert(defs.tilesets, d)
|
||||
ctx.tilesetByName[ts.name] = d
|
||||
ctx.tilesetByUid[d.uid] = d
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function layerDef(ctx: Ctx, l: any, kind: string, grid: number, tsUid: number?): any
|
||||
local d = ctx.layerDefs[l.name]
|
||||
if d then
|
||||
return d
|
||||
end
|
||||
local values = {}
|
||||
for _, v in list(l.intGridValues) do
|
||||
table.insert(values, obj({ "value", n(v.value, 1), "identifier", v.identifier or NULL, "color", v.color or "#FFFFFF", "tile", NULL, "groupUid", 0 }))
|
||||
end
|
||||
if kind == "IntGrid" and #values == 0 then
|
||||
local maxV = 0
|
||||
for _, v in list(l.intGrid) do
|
||||
maxV = math.max(maxV, n(v, 0))
|
||||
end
|
||||
for v = 1, maxV do
|
||||
table.insert(values, obj({ "value", v, "identifier", NULL, "color", "#FFFFFF", "tile", NULL, "groupUid", 0 }))
|
||||
end
|
||||
end
|
||||
d = obj({
|
||||
"__type", kind, "identifier", l.name, "type", kind, "uid", nextUid(ctx), "doc", NULL, "uiColor", NULL,
|
||||
"gridSize", grid, "guideGridWid", 0, "guideGridHei", 0, "displayOpacity", n(l.opacity, 1), "inactiveOpacity", 1,
|
||||
"hideInList", false, "hideFieldsWhenInactive", true, "canSelectWhenInactive", true, "renderInWorldView", true,
|
||||
"pxOffsetX", 0, "pxOffsetY", 0, "parallaxFactorX", 0, "parallaxFactorY", 0, "parallaxScaling", true,
|
||||
"requiredTags", {}, "excludedTags", {}, "autoTilesKilledByOtherLayerUid", NULL, "uiFilterTags", {},
|
||||
"useAsyncRender", false, "intGridValues", values, "intGridValuesGroups", {}, "autoRuleGroups", {},
|
||||
"autoSourceLayerDefUid", NULL, "tilesetDefUid", tsUid or NULL, "tilePivotX", 0, "tilePivotY", 0, "biomeFieldUid", NULL,
|
||||
})
|
||||
table.insert(ctx.defs.layers, d)
|
||||
ctx.layerDefs[l.name] = d
|
||||
return d
|
||||
end
|
||||
|
||||
local function entityDef(ctx: Ctx, o: any): any
|
||||
local name = if type(o.class) == "string" and o.class ~= "" then o.class elseif type(o.name) == "string" and o.name ~= "" then o.name else "Entity"
|
||||
local d = ctx.entityDefs[name]
|
||||
if d then
|
||||
return d
|
||||
end
|
||||
local pv = if tab(o.pivot) then o.pivot else { 0, 0 }
|
||||
d = obj({
|
||||
"identifier", name, "uid", nextUid(ctx), "tags", {}, "exportToToc", false, "allowOutOfBounds", false, "doc", NULL,
|
||||
"width", math.max(1, n(o.width, 16)), "height", math.max(1, n(o.height, 16)), "resizableX", false,
|
||||
"resizableY", false, "minWidth", NULL, "maxWidth", NULL, "minHeight", NULL, "maxHeight", NULL,
|
||||
"keepAspectRatio", false, "tileOpacity", 1, "fillOpacity", 0.08, "lineOpacity", 0, "hollow", false,
|
||||
"color", if type(o.color) == "string" then o.color else "#94D9B3", "renderMode", "Rectangle", "showName", true,
|
||||
"tilesetId", NULL, "tileRenderMode", "FitInside", "tileRect", NULL, "uiTileRect", NULL, "nineSliceBorders", {},
|
||||
"maxCount", 0, "limitScope", "PerLevel", "limitBehavior", "MoveLastOne", "pivotX", n(pv[1], 0), "pivotY", n(pv[2], 0),
|
||||
"fieldDefs", {},
|
||||
})
|
||||
table.insert(ctx.defs.entities, d)
|
||||
ctx.entityDefs[name] = d
|
||||
return d
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ layers
|
||||
local function gridTiles(ctx: Ctx, l: any, grid: number, ts: any): { any }
|
||||
local out = {}
|
||||
if tab(l.tiles) then
|
||||
for _, t in l.tiles do
|
||||
local o = obj({ "px", { n(t.x, 0), n(t.y, 0) }, "src", { n(t.srcX, 0), n(t.srcY, 0) }, "f", n(t.flip, 0), "t", n(t.tile, 0) })
|
||||
if tab(t.d) then
|
||||
set(o, "d", t.d)
|
||||
end
|
||||
set(o, "a", n(t.alpha, 1))
|
||||
table.insert(out, o)
|
||||
end
|
||||
return out
|
||||
end
|
||||
local w = n(l.width, 0)
|
||||
for i, raw in list(l.data) do
|
||||
local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS))
|
||||
if gid ~= 0 then
|
||||
local tset = tilesetOf(ctx, gid)
|
||||
if tset and (ts == nil or ctx.tilesetByName[tset.name] == ts) then
|
||||
local id = gid - tset.firstGid
|
||||
local cols = math.max(1, n(tset.columns, 1))
|
||||
local tw, th = n(tset.tileWidth, grid), n(tset.tileHeight, grid)
|
||||
local sp, mg = n(tset.spacing, 0), n(tset.margin, 0)
|
||||
local f = (if bit32.btest(raw, 0x80000000) then 1 else 0) + (if bit32.btest(raw, 0x40000000) then 2 else 0)
|
||||
local cx, cy = (i - 1) % math.max(w, 1), (i - 1) // math.max(w, 1)
|
||||
table.insert(out, obj({
|
||||
"px", { cx * grid, cy * grid }, "src", { mg + (id % cols) * (tw + sp), mg + (id // cols) * (th + sp) },
|
||||
"f", f, "t", id, "d", { cx + cy * w }, "a", 1,
|
||||
}))
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function layerTileset(ctx: Ctx, l: any): any
|
||||
if type(l.tileset) == "string" and ctx.tilesetByName[l.tileset] then
|
||||
return ctx.tilesetByName[l.tileset]
|
||||
end
|
||||
if tab(l.ldtk) and type(l.ldtk.overrideTilesetUid) == "number" and ctx.tilesetByUid[l.ldtk.overrideTilesetUid] then
|
||||
return ctx.tilesetByUid[l.ldtk.overrideTilesetUid]
|
||||
end
|
||||
for _, raw in list(l.data) do
|
||||
local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS))
|
||||
if gid ~= 0 then
|
||||
local tset = tilesetOf(ctx, gid)
|
||||
return if tset then ctx.tilesetByName[tset.name] else nil
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function entities(ctx: Ctx, l: any, levelIid: string, lx: number, ly: number, grid: number): { any }
|
||||
local out = {}
|
||||
for _, o in list(l.objects) do
|
||||
if tab(o) then
|
||||
local d = entityDef(ctx, o)
|
||||
local w, h = n(o.width, n(d.width, 16)), n(o.height, n(d.height, 16))
|
||||
local pv = if tab(o.pivot) then o.pivot else { n(d.pivotX, 0), n(d.pivotY, 0) }
|
||||
local px, py = n(o.x, 0) + n(pv[1], 0) * w, n(o.y, 0) + n(pv[2], 0) * h
|
||||
local e = clone(o.ldtk)
|
||||
set(e, "__identifier", d.identifier)
|
||||
set(e, "__grid", { px // grid, py // grid })
|
||||
set(e, "__pivot", { n(pv[1], 0), n(pv[2], 0) })
|
||||
set(e, "__tags", if tab(o.tags) then o.tags else {})
|
||||
set(e, "__tile", if tab(o.tile) then o.tile else NULL)
|
||||
set(e, "__smartColor", if type(o.color) == "string" then o.color else d.color)
|
||||
if type(e.iid) ~= "string" then
|
||||
set(e, "iid", if type(o.id) == "string" then o.id else newIid(ctx))
|
||||
end
|
||||
set(e, "width", w)
|
||||
set(e, "height", h)
|
||||
set(e, "defUid", d.uid)
|
||||
set(e, "px", { px, py })
|
||||
local fdefs: { [string]: any } = {}
|
||||
for _, f in list(d.fieldDefs) do
|
||||
if tab(f) and type(f.identifier) == "string" then
|
||||
fdefs[f.identifier] = f
|
||||
end
|
||||
end
|
||||
set(e, "fieldInstances", fieldInstances(ctx, o.fieldInstances, o.properties, o.propertyTypes, fdefs, d.fieldDefs))
|
||||
set(e, "__worldX", lx + px)
|
||||
set(e, "__worldY", ly + py)
|
||||
table.insert(out, e)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function layerInstance(ctx: Ctx, l: any, levelUid: number, levelIid: string, lx: number, ly: number, pxW: number, pxH: number): any
|
||||
local kind = if type(l.ldtkType) == "string" then l.ldtkType
|
||||
elseif l.type == "objects" then "Entities"
|
||||
elseif tab(l.intGrid) then "IntGrid"
|
||||
else "Tiles"
|
||||
local grid = math.max(1, n(l.gridSize, ctx.map.tileWidth))
|
||||
local ts = if kind ~= "Entities" then layerTileset(ctx, l) else nil
|
||||
local d = layerDef(ctx, l, kind, grid, if ts then ts.uid else nil)
|
||||
local cw = n(l.width, math.ceil(pxW / grid))
|
||||
local ch = n(l.height, math.ceil(pxH / grid))
|
||||
local li = clone(l.ldtk)
|
||||
set(li, "__identifier", l.name)
|
||||
set(li, "__type", kind)
|
||||
set(li, "__cWid", cw)
|
||||
set(li, "__cHei", ch)
|
||||
set(li, "__gridSize", grid)
|
||||
set(li, "__opacity", n(l.opacity, 1))
|
||||
set(li, "__pxTotalOffsetX", n(l.offsetX, 0))
|
||||
set(li, "__pxTotalOffsetY", n(l.offsetY, 0))
|
||||
set(li, "__tilesetDefUid", if ts then ts.uid else NULL)
|
||||
set(li, "__tilesetRelPath", if ts and type(ts.relPath) == "string" then ts.relPath else NULL)
|
||||
if type(li.iid) ~= "string" then
|
||||
set(li, "iid", newIid(ctx))
|
||||
end
|
||||
set(li, "levelId", levelUid)
|
||||
set(li, "layerDefUid", d.uid)
|
||||
if li.pxOffsetX == nil then
|
||||
set(li, "pxOffsetX", n(l.offsetX, 0) - n(d.pxOffsetX, 0))
|
||||
set(li, "pxOffsetY", n(l.offsetY, 0) - n(d.pxOffsetY, 0))
|
||||
end
|
||||
set(li, "visible", l.visible ~= false)
|
||||
if li.optionalRules == nil then
|
||||
set(li, "optionalRules", {})
|
||||
end
|
||||
local csv = {}
|
||||
if kind == "IntGrid" then
|
||||
local g = list(l.intGrid)
|
||||
for i = 1, cw * ch do
|
||||
csv[i] = n(g[i], 0)
|
||||
end
|
||||
end
|
||||
set(li, "intGridCsv", csv)
|
||||
local tl = if kind ~= "Entities" then gridTiles(ctx, l, grid, ts) else {}
|
||||
set(li, "autoLayerTiles", if kind == "IntGrid" or kind == "AutoLayer" then tl else {})
|
||||
if li.seed == nil then
|
||||
set(li, "seed", 0)
|
||||
end
|
||||
if li.overrideTilesetUid == nil then
|
||||
set(li, "overrideTilesetUid", NULL)
|
||||
end
|
||||
set(li, "gridTiles", if kind == "Tiles" then tl else {})
|
||||
set(li, "entityInstances", if kind == "Entities" then entities(ctx, l, levelIid, lx, ly, grid) else {})
|
||||
return li
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ levels
|
||||
local function flat(layers: { any }, into: { any })
|
||||
for _, l in layers do
|
||||
if l.type == "group" and not l.level and not l.world then
|
||||
flat(list(l.layers), into)
|
||||
elseif l.type ~= "group" and l.type ~= "image" then
|
||||
table.insert(into, l)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function levelValue(ctx: Ctx, g: any, layers: { any }, index: number): any
|
||||
local lv = clone(g.ldtk)
|
||||
local grid = ctx.map.tileWidth
|
||||
local pxW = n(g.pxWidth, 0)
|
||||
local pxH = n(g.pxHeight, 0)
|
||||
if pxW <= 0 or pxH <= 0 then
|
||||
for _, l in layers do
|
||||
local gs = n(l.gridSize, grid)
|
||||
pxW = math.max(pxW, n(l.width, 0) * gs)
|
||||
pxH = math.max(pxH, n(l.height, 0) * gs)
|
||||
end
|
||||
pxW = if pxW > 0 then pxW else ctx.map.width * grid
|
||||
pxH = if pxH > 0 then pxH else ctx.map.height * grid
|
||||
end
|
||||
local uid = if type(lv.uid) == "number" then lv.uid else nextUid(ctx)
|
||||
local iid = if type(lv.iid) == "string" then lv.iid else newIid(ctx)
|
||||
local lx, ly = n(g.offsetX, 0), n(g.offsetY, 0)
|
||||
set(lv, "identifier", if type(g.name) == "string" and g.name ~= "" then g.name else "Level_" .. index)
|
||||
set(lv, "iid", iid)
|
||||
set(lv, "uid", uid)
|
||||
set(lv, "worldX", lx)
|
||||
set(lv, "worldY", ly)
|
||||
if lv.worldDepth == nil then
|
||||
set(lv, "worldDepth", 0)
|
||||
end
|
||||
set(lv, "pxWid", pxW)
|
||||
set(lv, "pxHei", pxH)
|
||||
set(lv, "__bgColor", if type(g.backgroundColor) == "string" then g.backgroundColor elseif type(ctx.map.backgroundColor) == "string" then ctx.map.backgroundColor else "#696A79")
|
||||
for _, k in { "bgColor", "bgRelPath", "bgPos", "__smartColor", "__bgPos" } do
|
||||
if lv[k] == nil then
|
||||
set(lv, k, if k == "__smartColor" then "#ADADB5ff" else NULL)
|
||||
end
|
||||
end
|
||||
if lv.useAutoIdentifier == nil then
|
||||
set(lv, "useAutoIdentifier", false)
|
||||
end
|
||||
if lv.bgPivotX == nil then
|
||||
set(lv, "bgPivotX", 0.5)
|
||||
set(lv, "bgPivotY", 0.5)
|
||||
end
|
||||
set(lv, "externalRelPath", NULL)
|
||||
set(lv, "fieldInstances", fieldInstances(ctx, lv.fieldInstances, g.properties, g.propertyTypes, ctx.levelFields, ctx.defs.levelFields))
|
||||
local out = {}
|
||||
for i = #layers, 1, -1 do
|
||||
table.insert(out, layerInstance(ctx, layers[i], uid, iid, lx, ly, pxW, pxH))
|
||||
end
|
||||
set(lv, "layerInstances", out)
|
||||
if lv.__neighbours == nil then
|
||||
set(lv, "__neighbours", {})
|
||||
end
|
||||
return lv
|
||||
end
|
||||
|
||||
local function levels(ctx: Ctx, layers: { any }): { any }
|
||||
local out = {}
|
||||
local loose = {}
|
||||
for _, l in layers do
|
||||
if l.type == "group" and not l.world then
|
||||
local ls = {}
|
||||
flat(list(l.layers), ls)
|
||||
table.insert(out, levelValue(ctx, l, ls, #out))
|
||||
elseif l.type ~= "group" and l.type ~= "image" then
|
||||
table.insert(loose, l)
|
||||
end
|
||||
end
|
||||
if #loose > 0 then
|
||||
table.insert(out, 1, levelValue(ctx, { name = "Level_0", properties = {}, offsetX = 0, offsetY = 0 }, loose, 0))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local PROJECT: { any } = {
|
||||
"__header__", NULL, "iid", NULL, "jsonVersion", "1.5.3", "appBuildId", 473703, "nextUid", 0, "identifierStyle", "Capitalize",
|
||||
"toc", {}, "worldLayout", "Free", "worldGridWidth", 256, "worldGridHeight", 256, "defaultLevelWidth", 256,
|
||||
"defaultLevelHeight", 256, "defaultPivotX", 0, "defaultPivotY", 0, "defaultGridSize", 16, "defaultEntityWidth", 16,
|
||||
"defaultEntityHeight", 16, "bgColor", "#40465B", "defaultLevelBgColor", "#696A79", "minifyJson", false,
|
||||
"externalLevels", false, "exportTiled", false, "simplifiedExport", false, "imageExportMode", "None",
|
||||
"exportLevelBg", true, "pngFilePattern", NULL, "backupOnSave", false, "backupLimit", 10, "backupRelPath", NULL,
|
||||
"levelNamePattern", "Level_%idx", "tutorialDesc", NULL, "customCommands", {}, "flags", {}, "defs", NULL,
|
||||
"levels", NULL, "worlds", NULL, "dummyWorldIid", NULL,
|
||||
}
|
||||
|
||||
function Write.project(map: Types.TileMap, opts: any): (any, string?)
|
||||
local ctx: Ctx = {
|
||||
uid = 0,
|
||||
iid = 0,
|
||||
defs = nil,
|
||||
tilesetByName = {},
|
||||
tilesetByUid = {},
|
||||
layerDefs = {},
|
||||
entityDefs = {},
|
||||
levelFields = {},
|
||||
map = map,
|
||||
}
|
||||
local raw = if tab(map.ldtk) then map.ldtk else nil
|
||||
local p = if raw then clone(raw) else Json.object({})
|
||||
if not raw then
|
||||
for i = 1, #PROJECT, 2 do
|
||||
set(p, PROJECT[i], PROJECT[i + 1])
|
||||
end
|
||||
set(p, "__header__", obj({ "fileType", "LDtk Project JSON", "app", "LDtk", "doc", "https://ldtk.io/json", "schema", "https://ldtk.io/files/JSON_SCHEMA.json", "appAuthor", "Sebastien 'deepnight' Benard", "appVersion", "1.5.3", "url", "https://ldtk.io" }))
|
||||
set(p, "iid", newIid(ctx))
|
||||
set(p, "defaultGridSize", map.tileWidth)
|
||||
end
|
||||
ctx.uid = math.max(ctx.uid, n(p.nextUid, 1) - 1)
|
||||
defsFor(ctx, p.defs)
|
||||
local worlds = {}
|
||||
local hasWorlds = false
|
||||
for _, l in map.layers do
|
||||
if l.type == "group" and l.world then
|
||||
hasWorlds = true
|
||||
end
|
||||
end
|
||||
local lvls: { any } = {}
|
||||
if hasWorlds then
|
||||
for _, l in map.layers do
|
||||
if l.type == "group" and l.world then
|
||||
local w = clone(l.ldtk)
|
||||
set(w, "identifier", l.name)
|
||||
if type(w.iid) ~= "string" then
|
||||
set(w, "iid", newIid(ctx))
|
||||
end
|
||||
for _, k in { "worldGridWidth", "worldGridHeight" } do
|
||||
if w[k] == nil then
|
||||
set(w, k, 256)
|
||||
end
|
||||
end
|
||||
if w.worldLayout == nil then
|
||||
set(w, "worldLayout", "Free")
|
||||
end
|
||||
set(w, "levels", levels(ctx, list(l.layers)))
|
||||
table.insert(worlds, w)
|
||||
end
|
||||
end
|
||||
else
|
||||
lvls = levels(ctx, map.layers)
|
||||
end
|
||||
if type(map.backgroundColor) == "string" then
|
||||
set(p, "bgColor", map.backgroundColor)
|
||||
end
|
||||
if type(map.worldLayout) == "string" and not hasWorlds then
|
||||
set(p, "worldLayout", map.worldLayout)
|
||||
end
|
||||
set(p, "externalLevels", false)
|
||||
set(p, "defs", ctx.defs)
|
||||
set(p, "levels", lvls)
|
||||
set(p, "worlds", worlds)
|
||||
if type(p.dummyWorldIid) ~= "string" then
|
||||
set(p, "dummyWorldIid", newIid(ctx))
|
||||
end
|
||||
set(p, "nextUid", ctx.uid + 1)
|
||||
return p, nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,90 @@
|
||||
--!strict
|
||||
-- vector/ldtk: LDtk projects (.ldtk JSON, ldtk.io/json, 1.x) as a TileMap, read + write. Supports: IntGrid,
|
||||
-- AutoLayer, Tiles and Entities layers, tilesets as image paths, typed fields (properties), multi-world projects,
|
||||
-- external levels (.ldtkl through opts.resolve). Not supported: auto-layer rules are kept, never run; writing
|
||||
-- external level files (levels are embedded); standalone .ldtkl 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 Json = require("@rosetta/codecs/text/Json")
|
||||
local Read = require("@rosetta/vector/ldtk/Read")
|
||||
local Write = require("@rosetta/vector/ldtk/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ldtk = {
|
||||
name = "ldtk",
|
||||
category = "vector",
|
||||
extensions = { "ldtk" },
|
||||
mime = { "application/x-ldtk+json" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" },
|
||||
caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxCells: number?, -- per layer, default 2^26
|
||||
resolve: ((string) -> buffer?)?, -- external .ldtkl level files by their relative path
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
indent: number?, -- default 2; 0 = compact
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ldtk.sniff(r: Bytes.Reader): number
|
||||
local h = Sniff.text(r, 1024)
|
||||
if not string.match(h, "^%s*{") then
|
||||
return 0
|
||||
end
|
||||
if string.find(h, "\"fileType\"%s*:%s*\"LDtk Project JSON\"") then
|
||||
return 1
|
||||
end
|
||||
if string.find(h, "\"jsonVersion\"", 1, true) and string.find(h, "\"worldLayout\"", 1, true) then
|
||||
return 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ldtk.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, 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 v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true })
|
||||
if v == nil then
|
||||
return nil, jerr
|
||||
end
|
||||
local ok, map, msg = pcall(Read.project, v, o)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad project: " .. tostring(map))
|
||||
end
|
||||
if not map then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return map, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ldtk.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a TileMap value")
|
||||
end
|
||||
local ok, v, msg = pcall(Write.project, map, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad map: " .. tostring(v))
|
||||
end
|
||||
if v == nil then
|
||||
return nil, Err.new(Err.ARG, msg or "bad map")
|
||||
end
|
||||
local indent = if opts and opts.indent == 0 then nil else (opts and opts.indent or 2)
|
||||
local s, jerr = Json.encode(v, { indent = indent })
|
||||
if not s then
|
||||
return nil, jerr
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Ldtk
|
||||
@@ -0,0 +1,403 @@
|
||||
--!strict
|
||||
-- vector/ogmo/Read: Ogmo Editor 3 projects (.ogmo) and levels (.json) into a Types.TileMap (layer save / load as in
|
||||
-- OgmoEditor3-CE src/modules/*/ *Layer.hx). Ogmo's first layer is drawn on top: layers are reversed (bottom first).
|
||||
-- Tile ids -1 are empty; tileFlags 4 / 2 / 1 (flip H / V / diagonal) become Tiled's 0x80000000 / 0x40000000 /
|
||||
-- 0x20000000.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Json = require("@rosetta/codecs/text/Json")
|
||||
local Base64 = require("@rosetta/core/Base64")
|
||||
|
||||
local Read = {}
|
||||
|
||||
local NULL = Json.null
|
||||
local FLIP_H, FLIP_V, FLIP_D = 0x80000000, 0x40000000, 0x20000000
|
||||
|
||||
local function tab(v: any): boolean
|
||||
return type(v) == "table" and v ~= NULL
|
||||
end
|
||||
local function list(v: any): { any }
|
||||
return if tab(v) then v else {}
|
||||
end
|
||||
local function n(v: any, default: number): number
|
||||
return if type(v) == "number" and v == v then v else default
|
||||
end
|
||||
local function s(v: any): string?
|
||||
return if type(v) == "string" then v else nil
|
||||
end
|
||||
local function vec(v: any, dx: number, dy: number): (number, number)
|
||||
if tab(v) then
|
||||
return n(v.x, dx), n(v.y, dy)
|
||||
end
|
||||
return dx, dy
|
||||
end
|
||||
|
||||
-- PNG IHDR width / height of an embedded tileset image (data: URI)
|
||||
local function pngSize(b: buffer): (number?, number?)
|
||||
if buffer.len(b) >= 24 and buffer.readstring(b, 0, 8) == "\137PNG\r\n\26\n" and buffer.readstring(b, 12, 4) == "IHDR" then
|
||||
local function be(o: number): number
|
||||
return buffer.readu8(b, o) * 16777216 + buffer.readu8(b, o + 1) * 65536 + buffer.readu8(b, o + 2) * 256 + buffer.readu8(b, o + 3)
|
||||
end
|
||||
return be(16), be(20)
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
local VALUE_TYPES: { [string]: string } = { Integer = "int", Float = "float", Boolean = "bool", Color = "color", Filepath = "file", String = "string", Text = "string", Enum = "string" }
|
||||
|
||||
function Read.tilesets(project: any): { Types.Tileset }
|
||||
local out: { Types.Tileset } = {}
|
||||
local gid = 1
|
||||
for _, t in list(project and project.tilesets) do
|
||||
if tab(t) then
|
||||
local tw, th = math.max(1, n(t.tileWidth, 16)), math.max(1, n(t.tileHeight, 16))
|
||||
local sx, sy = n(t.tileSeparationX, 0), n(t.tileSeparationY, 0)
|
||||
local mx, my = n(t.tileMarginX, 0), n(t.tileMarginY, 0)
|
||||
local data: buffer? = nil
|
||||
local iw, ih = nil, nil
|
||||
if type(t.image) == "string" and string.sub(t.image, 1, 5) == "data:" then
|
||||
data = Base64.decodeDataUri(t.image)
|
||||
if data then
|
||||
iw, ih = pngSize(data)
|
||||
end
|
||||
end
|
||||
local cols = if iw then math.max(1, (iw - 2 * mx + sx) // (tw + sx)) else 1
|
||||
local rows = if ih then math.max(1, (ih - 2 * my + sy) // (th + sy)) else 1
|
||||
local ts: Types.Tileset = {
|
||||
name = s(t.label) or ("tileset" .. #out),
|
||||
firstGid = gid,
|
||||
tileWidth = tw,
|
||||
tileHeight = th,
|
||||
columns = cols,
|
||||
count = cols * rows,
|
||||
imageSource = s(t.path),
|
||||
imageWidth = iw,
|
||||
imageHeight = ih,
|
||||
imageData = data,
|
||||
spacing = sx,
|
||||
spacingY = if sy ~= sx then sy else nil,
|
||||
margin = mx,
|
||||
marginY = if my ~= mx then my else nil,
|
||||
}
|
||||
gid += ts.count
|
||||
table.insert(out, ts)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function valueTypes(defs: any): { [string]: string }?
|
||||
local out: { [string]: string }? = nil
|
||||
for _, d in list(defs) do
|
||||
if tab(d) and type(d.name) == "string" and type(d.definition) == "string" then
|
||||
local typ = VALUE_TYPES[d.definition]
|
||||
if typ and typ ~= "string" then
|
||||
out = out or {}
|
||||
;(out :: any)[d.name] = typ
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function values(v: any): { [string]: any }
|
||||
local out: { [string]: any } = {}
|
||||
if tab(v) then
|
||||
for k, x in v do
|
||||
if type(k) == "string" then
|
||||
out[k] = x
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
type Ctx = { project: any, tilesets: { Types.Tileset }, byName: { [string]: Types.Tileset }, layerDefs: { [string]: any }, entityDefs: { [string]: any }, radians: boolean, maxCells: number }
|
||||
|
||||
local function cells2D(v: any, w: number, h: number): { any }
|
||||
local out = table.create(w * h)
|
||||
for y, row in list(v) do
|
||||
for x, c in list(row) do
|
||||
if x <= w and y <= h then
|
||||
out[(y - 1) * w + x] = c
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function tileLayer(ctx: Ctx, li: any, l: Types.TileLayer, w: number, h: number)
|
||||
local ts = ctx.byName[s(li.tileset) or ""] or ctx.tilesets[1]
|
||||
l.tileset = s(li.tileset)
|
||||
local exportMode, arrayMode = n(li.exportMode, 0), n(li.arrayMode, 0)
|
||||
local raw: { any }
|
||||
if exportMode == 1 then
|
||||
raw = if arrayMode == 1 then cells2D(li.dataCoords2D, w, h) else list(li.dataCoords)
|
||||
else
|
||||
raw = if arrayMode == 1 then cells2D(li.data2D, w, h) else list(li.data)
|
||||
end
|
||||
local flags = if arrayMode == 1 then cells2D(li.tileFlags2D, w, h) else list(li.tileFlags)
|
||||
local data = table.create(w * h, 0)
|
||||
for i = 1, w * h do
|
||||
local c = raw[i]
|
||||
local id = -1
|
||||
if exportMode == 1 then
|
||||
if tab(c) and n(c[1], -1) >= 0 then
|
||||
id = n(c[2], 0) * (if ts then ts.columns else 1) + n(c[1], 0)
|
||||
end
|
||||
else
|
||||
id = n(c, -1)
|
||||
end
|
||||
if id >= 0 and ts then
|
||||
local gid = ts.firstGid + id
|
||||
local f = n(flags[i], 0)
|
||||
if bit32.btest(f, 4) then
|
||||
gid += FLIP_H
|
||||
end
|
||||
if bit32.btest(f, 2) then
|
||||
gid += FLIP_V
|
||||
end
|
||||
if bit32.btest(f, 1) then
|
||||
gid += FLIP_D
|
||||
end
|
||||
data[i] = gid
|
||||
elseif id >= 0 then
|
||||
data[i] = id + 1
|
||||
end
|
||||
end
|
||||
l.data = data
|
||||
end
|
||||
|
||||
local function entity(ctx: Ctx, e: any): { [string]: any }
|
||||
local def = ctx.entityDefs[s(e.name) or ""]
|
||||
local dw, dh = vec(def and def.size, 16, 16)
|
||||
local dox, doy = vec(def and def.origin, 0, 0)
|
||||
local w, h = n(e.width, dw), n(e.height, dh)
|
||||
local ox, oy = n(e.originX, dox), n(e.originY, doy)
|
||||
local rot = n(e.rotation, 0)
|
||||
if ctx.radians then
|
||||
rot = math.deg(rot)
|
||||
end
|
||||
local nodes = nil
|
||||
if tab(e.nodes) then
|
||||
nodes = {}
|
||||
for i, p in e.nodes do
|
||||
nodes[i] = { n(tab(p) and p.x, 0), n(tab(p) and p.y, 0) }
|
||||
end
|
||||
end
|
||||
return {
|
||||
id = e.id,
|
||||
name = s(e.name) or "",
|
||||
class = s(e.name) or "",
|
||||
x = n(e.x, 0) - ox,
|
||||
y = n(e.y, 0) - oy,
|
||||
width = w,
|
||||
height = h,
|
||||
rotation = rot,
|
||||
visible = true,
|
||||
shape = "rectangle",
|
||||
originX = ox,
|
||||
originY = oy,
|
||||
flippedX = if type(e.flippedX) == "boolean" then e.flippedX else nil,
|
||||
flippedY = if type(e.flippedY) == "boolean" then e.flippedY else nil,
|
||||
color = s(e.color),
|
||||
nodes = nodes,
|
||||
eid = s(e._eid),
|
||||
properties = values(e.values),
|
||||
propertyTypes = if def then valueTypes(def.values) else nil,
|
||||
}
|
||||
end
|
||||
|
||||
local function decal(ctx: Ctx, d: any): { [string]: any }
|
||||
local rot = n(d.rotation, 0)
|
||||
if ctx.radians then
|
||||
rot = math.deg(rot)
|
||||
end
|
||||
return {
|
||||
name = s(d.texture) or "",
|
||||
class = "decal",
|
||||
shape = "decal",
|
||||
texture = s(d.texture),
|
||||
x = n(d.x, 0),
|
||||
y = n(d.y, 0),
|
||||
width = 0,
|
||||
height = 0,
|
||||
originX = n(d.originX, 0.5),
|
||||
originY = n(d.originY, 0.5),
|
||||
scaleX = n(d.scaleX, 1),
|
||||
scaleY = n(d.scaleY, 1),
|
||||
rotation = rot,
|
||||
visible = true,
|
||||
properties = values(d.values),
|
||||
}
|
||||
end
|
||||
|
||||
local function layer(ctx: Ctx, li: any): (Types.TileLayer?, string?)
|
||||
local name = s(li.name) or ""
|
||||
local def = ctx.layerDefs[name]
|
||||
local kind = (def and s(def.definition)) or (if li.entities ~= nil then "entity"
|
||||
elseif li.decals ~= nil then "decal"
|
||||
elseif li.grid ~= nil or li.grid2D ~= nil then "grid"
|
||||
else "tile")
|
||||
local w, h = n(li.gridCellsX, 0), n(li.gridCellsY, 0)
|
||||
if w < 0 or h < 0 or w * h > ctx.maxCells then
|
||||
return nil, "limit: layer of " .. w .. " x " .. h .. " cells"
|
||||
end
|
||||
local l: Types.TileLayer = {
|
||||
name = name,
|
||||
type = if kind == "entity" or kind == "decal" then "objects" else "tiles",
|
||||
visible = true,
|
||||
opacity = 1,
|
||||
properties = {},
|
||||
offsetX = n(li.offsetX, 0),
|
||||
offsetY = n(li.offsetY, 0),
|
||||
ogmoType = kind,
|
||||
cellWidth = n(li.gridCellWidth, 0),
|
||||
cellHeight = n(li.gridCellHeight, 0),
|
||||
eid = s(li._eid),
|
||||
exportMode = if type(li.exportMode) == "number" then li.exportMode else nil,
|
||||
arrayMode = if type(li.arrayMode) == "number" then li.arrayMode else nil,
|
||||
}
|
||||
if kind == "entity" then
|
||||
local objs = {}
|
||||
for _, e in list(li.entities) do
|
||||
if tab(e) then
|
||||
table.insert(objs, entity(ctx, e))
|
||||
end
|
||||
end
|
||||
l.objects = objs
|
||||
elseif kind == "decal" then
|
||||
local objs = {}
|
||||
for _, d in list(li.decals) do
|
||||
if tab(d) then
|
||||
table.insert(objs, decal(ctx, d))
|
||||
end
|
||||
end
|
||||
l.objects = objs
|
||||
l.folder = s(li.folder)
|
||||
elseif kind == "grid" then
|
||||
l.width, l.height = w, h
|
||||
local raw = if n(li.arrayMode, 0) == 1 then cells2D(li.grid2D, w, h) else list(li.grid)
|
||||
local grid = table.create(w * h, "0")
|
||||
local data = table.create(w * h, 0)
|
||||
for i = 1, w * h do
|
||||
local c = raw[i]
|
||||
local v = if type(c) == "string" then c elseif type(c) == "number" then tostring(c) else "0"
|
||||
grid[i] = v
|
||||
data[i] = tonumber(v) or 0
|
||||
end
|
||||
l.grid = grid
|
||||
l.data = data
|
||||
if def and tab(def.legend) then
|
||||
l.legend = values(def.legend)
|
||||
end
|
||||
else
|
||||
l.width, l.height = w, h
|
||||
tileLayer(ctx, li, l, w, h)
|
||||
end
|
||||
return l, nil
|
||||
end
|
||||
|
||||
local function context(project: any, opts: any): Ctx
|
||||
local ts = Read.tilesets(project)
|
||||
local ctx: Ctx = { project = project, tilesets = ts, byName = {}, layerDefs = {}, entityDefs = {}, radians = true, maxCells = opts.maxCells or 2 ^ 26 }
|
||||
for _, t in ts do
|
||||
ctx.byName[t.name] = t
|
||||
end
|
||||
if tab(project) then
|
||||
ctx.radians = project.anglesRadians ~= false
|
||||
for _, d in list(project.layers) do
|
||||
if tab(d) and type(d.name) == "string" then
|
||||
ctx.layerDefs[d.name] = d
|
||||
end
|
||||
end
|
||||
for _, d in list(project.entities) do
|
||||
if tab(d) and type(d.name) == "string" then
|
||||
ctx.entityDefs[d.name] = d
|
||||
end
|
||||
end
|
||||
end
|
||||
return ctx
|
||||
end
|
||||
|
||||
local function gridSize(project: any, layers: { any }): (number, number)
|
||||
if tab(project) and tab(project.layerGridDefaultSize) then
|
||||
local x, y = vec(project.layerGridDefaultSize, 16, 16)
|
||||
return math.max(1, x), math.max(1, y)
|
||||
end
|
||||
for _, l in layers do
|
||||
if tab(l) and type(l.gridCellWidth) == "number" then
|
||||
return math.max(1, l.gridCellWidth), math.max(1, n(l.gridCellHeight, l.gridCellWidth))
|
||||
end
|
||||
end
|
||||
return 16, 16
|
||||
end
|
||||
|
||||
function Read.level(v: any, project: any, opts: any): (Types.TileMap?, string?)
|
||||
if not tab(v) or not tab(v.layers) then
|
||||
return nil, "no layers: not an Ogmo level"
|
||||
end
|
||||
local ctx = context(project, opts)
|
||||
local tw, th = gridSize(project, v.layers)
|
||||
local pw, ph = n(v.width, 0), n(v.height, 0)
|
||||
local map = Types.TileMap.new(math.ceil(pw / tw), math.ceil(ph / th), tw, th)
|
||||
map.tilesets = ctx.tilesets
|
||||
map.pxWidth, map.pxHeight = pw, ph
|
||||
map.offsetX, map.offsetY = n(v.offsetX, 0), n(v.offsetY, 0)
|
||||
map.properties = values(v.values)
|
||||
if tab(project) then
|
||||
map.propertyTypes = valueTypes(project.levelValues)
|
||||
end
|
||||
local ls = v.layers
|
||||
for i = #ls, 1, -1 do
|
||||
if tab(ls[i]) then
|
||||
local l, err = layer(ctx, ls[i])
|
||||
if not l then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(map.layers, l)
|
||||
end
|
||||
end
|
||||
map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), level = true, anglesRadians = ctx.radians }
|
||||
if tab(project) then
|
||||
map.ogmo = project
|
||||
end
|
||||
return map, nil
|
||||
end
|
||||
|
||||
function Read.project(v: any, opts: any): (Types.TileMap?, string?)
|
||||
local ctx = context(v, opts)
|
||||
local tw, th = gridSize(v, {})
|
||||
local lw, lh = vec(v.levelDefaultSize, 0, 0)
|
||||
local map = Types.TileMap.new(math.ceil(lw / tw), math.ceil(lh / th), tw, th)
|
||||
map.tilesets = ctx.tilesets
|
||||
map.name = s(v.name)
|
||||
map.backgroundColor = s(v.backgroundColor)
|
||||
local defs = list(v.layers)
|
||||
for i = #defs, 1, -1 do
|
||||
local d = defs[i]
|
||||
if tab(d) and type(d.name) == "string" then
|
||||
local kind = s(d.definition) or "tile"
|
||||
local gx, gy = vec(d.gridSize, tw, th)
|
||||
local l: Types.TileLayer = {
|
||||
name = d.name,
|
||||
type = if kind == "entity" or kind == "decal" then "objects" else "tiles",
|
||||
visible = true,
|
||||
opacity = 1,
|
||||
properties = {},
|
||||
ogmoType = kind,
|
||||
cellWidth = gx,
|
||||
cellHeight = gy,
|
||||
eid = s(d.exportID),
|
||||
tileset = s(d.defaultTileset),
|
||||
}
|
||||
table.insert(map.layers, l)
|
||||
end
|
||||
end
|
||||
map.entities = list(v.entities)
|
||||
map.ogmo = v
|
||||
map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), project = true, anglesRadians = ctx.radians }
|
||||
map.meta.project = true
|
||||
return map, nil
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,352 @@
|
||||
--!strict
|
||||
-- vector/ogmo/Write: a Types.TileMap as an Ogmo Editor 3 level (.json) or project (.ogmo), in the shapes Ogmo 3.4
|
||||
-- saves (Layer.save / TileLayer.save / GridLayer.save / Entity.save / Decal.save). A project read from Ogmo is
|
||||
-- written back with its own definitions; otherwise layers, tilesets and entity templates are made from the map.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Json = require("@rosetta/codecs/text/Json")
|
||||
local Base64 = require("@rosetta/core/Base64")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local NULL = Json.null
|
||||
local FLAGS = 0xF0000000
|
||||
local VERSION = "3.4.0"
|
||||
|
||||
local function tab(v: any): boolean
|
||||
return type(v) == "table" and v ~= NULL
|
||||
end
|
||||
local function list(v: any): { any }
|
||||
return if tab(v) then v else {}
|
||||
end
|
||||
local function n(v: any, default: number): number
|
||||
return if type(v) == "number" and v == v then v else default
|
||||
end
|
||||
|
||||
-- key / value pairs; a nil value (an absent optional field) is skipped
|
||||
local function obj(pairs_: { any }): any
|
||||
local out, keys = {}, {}
|
||||
local i = 1
|
||||
while pairs_[i] ~= nil do
|
||||
if pairs_[i + 1] ~= nil then
|
||||
table.insert(keys, pairs_[i])
|
||||
out[pairs_[i]] = pairs_[i + 1]
|
||||
end
|
||||
i += 2
|
||||
end
|
||||
return Json.object(out, keys)
|
||||
end
|
||||
|
||||
local function values(props: any): any
|
||||
local out = {}
|
||||
local keys = {}
|
||||
if tab(props) then
|
||||
for k, v in props do
|
||||
if type(k) == "string" then
|
||||
out[k] = v
|
||||
table.insert(keys, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(keys)
|
||||
return Json.object(out, keys)
|
||||
end
|
||||
|
||||
local function eid(l: any, i: number): string
|
||||
return if type(l.eid) == "string" then l.eid else tostring(10000000 + i)
|
||||
end
|
||||
|
||||
local function flat(layers: { any }, into: { any })
|
||||
for _, l in layers do
|
||||
if l.type == "group" then
|
||||
flat(list(l.layers), into)
|
||||
elseif l.type == "tiles" or l.type == "objects" then
|
||||
table.insert(into, l)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function tilesetOf(map: Types.TileMap, gid: number): Types.Tileset?
|
||||
local best: Types.Tileset? = nil
|
||||
for _, ts in map.tilesets do
|
||||
if ts.firstGid <= gid and (best == nil or ts.firstGid > (best :: Types.Tileset).firstGid) then
|
||||
best = ts
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
local function layerTileset(map: Types.TileMap, l: any): Types.Tileset?
|
||||
if type(l.tileset) == "string" then
|
||||
for _, ts in map.tilesets do
|
||||
if ts.name == l.tileset then
|
||||
return ts
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, raw in list(l.data) do
|
||||
local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS))
|
||||
if gid ~= 0 then
|
||||
return tilesetOf(map, gid)
|
||||
end
|
||||
end
|
||||
return map.tilesets[1]
|
||||
end
|
||||
|
||||
local function kindOf(l: any): string
|
||||
if type(l.ogmoType) == "string" then
|
||||
return l.ogmoType
|
||||
elseif l.type == "objects" then
|
||||
for _, o in list(l.objects) do
|
||||
if o.shape == "decal" then
|
||||
return "decal"
|
||||
end
|
||||
end
|
||||
return "entity"
|
||||
elseif tab(l.grid) then
|
||||
return "grid"
|
||||
end
|
||||
return "tile"
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ level
|
||||
local function rows2D(flatList: { any }, w: number, h: number): { any }
|
||||
local out = {}
|
||||
for y = 1, h do
|
||||
local row = {}
|
||||
for x = 1, w do
|
||||
row[x] = flatList[(y - 1) * w + x]
|
||||
end
|
||||
out[y] = row
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function tileLayer(map: Types.TileMap, l: any, i: number, gw: number, gh: number): any
|
||||
local ts = layerTileset(map, l)
|
||||
local w, h = n(l.width, math.ceil(n(map.pxWidth, map.width * map.tileWidth) / gw)), n(l.height, math.ceil(n(map.pxHeight, map.height * map.tileHeight) / gh))
|
||||
local ids, coords, flags = table.create(w * h, -1), table.create(w * h), table.create(w * h, 0)
|
||||
local anyFlag = false
|
||||
local data = list(l.data)
|
||||
for k = 1, w * h do
|
||||
local raw = n(data[k], 0)
|
||||
local gid = bit32.band(raw, bit32.bnot(FLAGS))
|
||||
local id = -1
|
||||
if gid ~= 0 then
|
||||
id = if ts then gid - ts.firstGid else gid - 1
|
||||
if ts and (id < 0 or id >= math.max(ts.count, 1)) then
|
||||
id = -1
|
||||
end
|
||||
end
|
||||
ids[k] = id
|
||||
if id >= 0 then
|
||||
local cols = if ts then math.max(1, ts.columns) else 1
|
||||
coords[k] = { id % cols, id // cols }
|
||||
local f = (if bit32.btest(raw, 0x80000000) then 4 else 0) + (if bit32.btest(raw, 0x40000000) then 2 else 0) + (if bit32.btest(raw, 0x20000000) then 1 else 0)
|
||||
flags[k] = f
|
||||
anyFlag = anyFlag or f ~= 0
|
||||
else
|
||||
coords[k] = { -1 }
|
||||
end
|
||||
end
|
||||
local exportMode, arrayMode = n(l.exportMode, 0), n(l.arrayMode, 0)
|
||||
local fields: { any } = {
|
||||
"name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw,
|
||||
"gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "tileset", if ts then ts.name else "",
|
||||
}
|
||||
local key = if exportMode == 1 then (if arrayMode == 1 then "dataCoords2D" else "dataCoords") else (if arrayMode == 1 then "data2D" else "data")
|
||||
local body = if exportMode == 1 then coords else ids
|
||||
table.insert(fields, key)
|
||||
table.insert(fields, if arrayMode == 1 then rows2D(body, w, h) else body)
|
||||
if anyFlag then
|
||||
table.insert(fields, if arrayMode == 1 then "tileFlags2D" else "tileFlags")
|
||||
table.insert(fields, if arrayMode == 1 then rows2D(flags, w, h) else flags)
|
||||
end
|
||||
table.insert(fields, "exportMode")
|
||||
table.insert(fields, exportMode)
|
||||
table.insert(fields, "arrayMode")
|
||||
table.insert(fields, arrayMode)
|
||||
return obj(fields)
|
||||
end
|
||||
|
||||
local function gridLayer(map: Types.TileMap, l: any, i: number, gw: number, gh: number): any
|
||||
local w, h = n(l.width, map.width), n(l.height, map.height)
|
||||
local cells = table.create(w * h, "0")
|
||||
local grid, data = list(l.grid), list(l.data)
|
||||
for k = 1, w * h do
|
||||
local g = grid[k]
|
||||
cells[k] = if type(g) == "string" then g else tostring(math.floor(n(data[k], 0)))
|
||||
end
|
||||
local arrayMode = n(l.arrayMode, 0)
|
||||
return obj({
|
||||
"name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw,
|
||||
"gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h,
|
||||
if arrayMode == 1 then "grid2D" else "grid", if arrayMode == 1 then rows2D(cells, w, h) else cells,
|
||||
"arrayMode", arrayMode,
|
||||
})
|
||||
end
|
||||
|
||||
local function entities(l: any, i: number, gw: number, gh: number, w: number, h: number, radians: boolean): any
|
||||
local out = {}
|
||||
for k, o in list(l.objects) do
|
||||
local ox, oy = n(o.originX, 0), n(o.originY, 0)
|
||||
local nodes = nil
|
||||
if tab(o.nodes) then
|
||||
nodes = {}
|
||||
for j, p in o.nodes do
|
||||
nodes[j] = obj({ "x", n(p[1], 0), "y", n(p[2], 0) })
|
||||
end
|
||||
end
|
||||
local rot = n(o.rotation, 0)
|
||||
table.insert(out, obj({
|
||||
"name", if type(o.class) == "string" and o.class ~= "" then o.class else (o.name or "entity"),
|
||||
"id", if type(o.id) == "number" then o.id else k - 1,
|
||||
"_eid", if type(o.eid) == "string" then o.eid else tostring(20000000 + k),
|
||||
"x", n(o.x, 0) + ox, "y", n(o.y, 0) + oy, "width", n(o.width, gw), "height", n(o.height, gh),
|
||||
"originX", ox, "originY", oy, "rotation", if radians then math.rad(rot) else rot,
|
||||
"flippedX", o.flippedX, "flippedY", o.flippedY, "color", o.color, "nodes", nodes,
|
||||
"values", if tab(o.properties) and next(o.properties) then values(o.properties) else nil,
|
||||
}))
|
||||
end
|
||||
return obj({
|
||||
"name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw,
|
||||
"gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "entities", out,
|
||||
})
|
||||
end
|
||||
|
||||
local function decals(l: any, i: number, gw: number, gh: number, w: number, h: number, radians: boolean): any
|
||||
local out = {}
|
||||
for _, o in list(l.objects) do
|
||||
local rot = n(o.rotation, 0)
|
||||
table.insert(out, obj({
|
||||
"x", n(o.x, 0), "y", n(o.y, 0), "scaleX", n(o.scaleX, 1), "scaleY", n(o.scaleY, 1),
|
||||
"rotation", if radians then math.rad(rot) else rot, "texture", o.texture or o.name or "",
|
||||
"originX", n(o.originX, 0.5), "originY", n(o.originY, 0.5),
|
||||
"values", if tab(o.properties) and next(o.properties) then values(o.properties) else nil,
|
||||
}))
|
||||
end
|
||||
return obj({
|
||||
"name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw,
|
||||
"gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "decals", out, "folder", l.folder or "",
|
||||
})
|
||||
end
|
||||
|
||||
local function radiansOf(map: any): boolean
|
||||
local src = if tab(map.meta) and tab(map.meta.source) then map.meta.source else {}
|
||||
if type(src.anglesRadians) == "boolean" then
|
||||
return src.anglesRadians
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Write.level(map: Types.TileMap): (any, string?)
|
||||
local layers = {}
|
||||
flat(map.layers, layers)
|
||||
local radians = radiansOf(map)
|
||||
local pw = n(map.pxWidth, map.width * map.tileWidth)
|
||||
local ph = n(map.pxHeight, map.height * map.tileHeight)
|
||||
local out = {}
|
||||
for i = #layers, 1, -1 do
|
||||
local l = layers[i]
|
||||
local gw = n(l.cellWidth, map.tileWidth)
|
||||
local gh = n(l.cellHeight, map.tileHeight)
|
||||
local cw, ch = math.ceil(pw / math.max(gw, 1)), math.ceil(ph / math.max(gh, 1))
|
||||
local kind = kindOf(l)
|
||||
local li
|
||||
if kind == "entity" then
|
||||
li = entities(l, i, gw, gh, cw, ch, radians)
|
||||
elseif kind == "decal" then
|
||||
li = decals(l, i, gw, gh, cw, ch, radians)
|
||||
elseif kind == "grid" then
|
||||
li = gridLayer(map, l, i, gw, gh)
|
||||
else
|
||||
li = tileLayer(map, l, i, gw, gh)
|
||||
end
|
||||
table.insert(out, li)
|
||||
end
|
||||
return obj({
|
||||
"ogmoVersion", if tab(map.meta) and tab(map.meta.source) and type(map.meta.source.version) == "string" then map.meta.source.version else VERSION,
|
||||
"width", pw, "height", ph, "offsetX", n(map.offsetX, 0), "offsetY", n(map.offsetY, 0),
|
||||
"values", if tab(map.properties) and next(map.properties) then values(map.properties) else nil,
|
||||
"layers", out,
|
||||
}), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ project
|
||||
local function tileset(ts: any): any
|
||||
local image = ""
|
||||
if type(ts.imageData) == "buffer" then
|
||||
image = Base64.dataUri(ts.imageData, "image/png")
|
||||
end
|
||||
return obj({
|
||||
"label", ts.name, "path", ts.imageSource or "", "image", image, "tileWidth", n(ts.tileWidth, 16),
|
||||
"tileHeight", n(ts.tileHeight, 16), "tileSeparationX", n(ts.spacing, 0), "tileSeparationY", n(ts.spacingY, n(ts.spacing, 0)),
|
||||
"tileMarginX", n(ts.margin, 0), "tileMarginY", n(ts.marginY, n(ts.margin, 0)),
|
||||
})
|
||||
end
|
||||
|
||||
local function entityTemplate(name: string, o: any, i: number): any
|
||||
local w, h = math.max(1, n(o.width, 16)), math.max(1, n(o.height, 16))
|
||||
return obj({
|
||||
"exportID", tostring(30000000 + i), "name", name, "limit", -1, "size", obj({ "x", w, "y", h }),
|
||||
"origin", obj({ "x", n(o.originX, 0), "y", n(o.originY, 0) }), "originAnchored", true,
|
||||
"shape", obj({ "label", "Rectangle", "points", {
|
||||
obj({ "x", -1, "y", -1 }), obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }),
|
||||
obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }), obj({ "x", 1, "y", 1 }),
|
||||
} }),
|
||||
"color", if type(o.color) == "string" then o.color else "#ff0000ff", "tileX", false, "tileY", false,
|
||||
"tileSize", obj({ "x", 16, "y", 16 }), "resizeableX", true, "resizeableY", true, "rotatable", true,
|
||||
"rotationDegrees", 360, "canFlipX", true, "canFlipY", true, "canSetColor", false, "hasNodes", true,
|
||||
"nodeLimit", 0, "nodeDisplay", 0, "nodeGhost", true, "tags", {}, "values", {},
|
||||
})
|
||||
end
|
||||
|
||||
function Write.project(map: any): (any, string?)
|
||||
if tab(map.ogmo) and map.meta and map.meta.project then
|
||||
return map.ogmo, nil
|
||||
end
|
||||
local layers = {}
|
||||
flat(map.layers, layers)
|
||||
local defs = {}
|
||||
local ents, seen = {}, {}
|
||||
for i = #layers, 1, -1 do
|
||||
local l = layers[i]
|
||||
local kind = kindOf(l)
|
||||
local gs = obj({ "x", n(l.cellWidth, map.tileWidth), "y", n(l.cellHeight, map.tileHeight) })
|
||||
local d: any
|
||||
if kind == "tile" then
|
||||
local ts = layerTileset(map, l)
|
||||
d = obj({ "definition", "tile", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "exportMode", n(l.exportMode, 0), "arrayMode", n(l.arrayMode, 0), "defaultTileset", if ts then ts.name else "" })
|
||||
elseif kind == "grid" then
|
||||
local legend = if tab(l.legend) then values(l.legend) else obj({ "0", "#00000000", "1", "#000000ff" })
|
||||
d = obj({ "definition", "grid", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "arrayMode", n(l.arrayMode, 0), "legend", legend })
|
||||
elseif kind == "decal" then
|
||||
d = obj({ "definition", "decal", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "folder", l.folder or "", "includeImageSequence", true, "scaleable", true, "rotatable", true, "values", {} })
|
||||
else
|
||||
d = obj({ "definition", "entity", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "requiredTags", {}, "excludedTags", {} })
|
||||
for _, o in list(l.objects) do
|
||||
local name = if type(o.class) == "string" and o.class ~= "" then o.class else (o.name or "entity")
|
||||
if not seen[name] then
|
||||
seen[name] = true
|
||||
table.insert(ents, entityTemplate(name, o, #ents))
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(defs, d)
|
||||
end
|
||||
local tss = {}
|
||||
for _, ts in map.tilesets do
|
||||
table.insert(tss, tileset(ts))
|
||||
end
|
||||
local grid = obj({ "x", map.tileWidth, "y", map.tileHeight })
|
||||
local size = obj({ "x", n(map.pxWidth, map.width * map.tileWidth), "y", n(map.pxHeight, map.height * map.tileHeight) })
|
||||
return obj({
|
||||
"name", if type(map.name) == "string" then map.name else "Project", "ogmoVersion", VERSION, "levelPaths", { "." },
|
||||
"backgroundColor", if type(map.backgroundColor) == "string" then map.backgroundColor else "#282c34ff",
|
||||
"gridColor", "#3c4049cc", "anglesRadians", radiansOf(map), "directoryDepth", 5, "layerGridDefaultSize", grid,
|
||||
"levelDefaultSize", size, "levelMinSize", obj({ "x", 128, "y", 128 }), "levelMaxSize", obj({ "x", 4096, "y", 4096 }),
|
||||
"levelValues", {}, "defaultExportMode", ".json", "compactExport", false, "externalScript", "", "playCommand", "",
|
||||
"entityTags", {}, "layers", defs, "entities", ents, "tilesets", tss,
|
||||
}), nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,117 @@
|
||||
--!strict
|
||||
-- vector/ogmo: Ogmo Editor 3 levels (.json) and projects (.ogmo) as a TileMap, read + write (OgmoEditor3-CE 3.x
|
||||
-- save format). Supports: tile layers (ids / coords, 1D / 2D arrays, tile flags), grid layers, entity layers (origin,
|
||||
-- rotation, flips, nodes, values), decal layers, level values; the project through opts.project for tilesets and
|
||||
-- entity templates. Not supported: loading tileset images (embedded PNGs stay bytes: tileset.imageData).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Json = require("@rosetta/codecs/text/Json")
|
||||
local Read = require("@rosetta/vector/ogmo/Read")
|
||||
local Write = require("@rosetta/vector/ogmo/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ogmo = {
|
||||
name = "ogmo",
|
||||
category = "vector",
|
||||
extensions = { "ogmo" },
|
||||
mime = { "application/x-ogmo+json" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" },
|
||||
caps = { decode = true, encode = true, projects = true, entities = true, decals = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxCells: number?, -- per layer, default 2^26
|
||||
project: (string | buffer | { [string]: any })?, -- the .ogmo project of a level (bytes or decoded JSON)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
kind: ("level" | "project")?, -- default: "project" for a map read from a .ogmo, else "level"
|
||||
indent: number?, -- default 2; 0 = compact
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ogmo.sniff(r: Bytes.Reader): number
|
||||
local h = Sniff.text(r, 2048)
|
||||
if not string.match(h, "^%s*{") or not string.find(h, "\"ogmoVersion\"", 1, true) then
|
||||
return 0
|
||||
end
|
||||
if string.find(h, "\"layerGridDefaultSize\"", 1, true) or string.find(h, "\"levelPaths\"", 1, true) then
|
||||
return 1
|
||||
end
|
||||
return 0.9
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function json(src: any): (any, Err.Err?)
|
||||
if type(src) == "table" then
|
||||
return src, nil
|
||||
end
|
||||
if type(src) ~= "string" and type(src) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "project must be bytes or a table")
|
||||
end
|
||||
return Json.decode(src, { ordered = true })
|
||||
end
|
||||
|
||||
function Ogmo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, 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 v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true })
|
||||
if v == nil then
|
||||
return nil, jerr
|
||||
end
|
||||
if type(v) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a JSON object")
|
||||
end
|
||||
local isProject = v.layerGridDefaultSize ~= nil or v.levelPaths ~= nil or v.tilesets ~= nil and v.layers ~= nil and v.width == nil
|
||||
local project: any = nil
|
||||
if not isProject and o.project ~= nil then
|
||||
local p, perr = json(o.project)
|
||||
if p == nil then
|
||||
return nil, perr
|
||||
end
|
||||
project = p
|
||||
end
|
||||
local run: (any, any) -> (any, string?) = if isProject then Read.project else function(x: any, oo: any): (any, string?)
|
||||
return Read.level(x, project, oo)
|
||||
end
|
||||
local ok, map, msg = pcall(run, v, o)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(map))
|
||||
end
|
||||
if not map then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return map, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ogmo.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a TileMap value")
|
||||
end
|
||||
local kind = opts and opts.kind or (if type(map.meta) == "table" and map.meta.project then "project" else "level")
|
||||
if kind ~= "level" and kind ~= "project" then
|
||||
return nil, Err.new(Err.ARG, "kind must be level or project")
|
||||
end
|
||||
local ok, v, msg = pcall(if kind == "project" then Write.project else Write.level, map)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad map: " .. tostring(v))
|
||||
end
|
||||
if v == nil then
|
||||
return nil, Err.new(Err.ARG, msg or "bad map")
|
||||
end
|
||||
local indent = if opts and opts.indent == 0 then nil else (opts and opts.indent or 2)
|
||||
local s, jerr = Json.encode(v, { indent = indent })
|
||||
if not s then
|
||||
return nil, jerr
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Ogmo
|
||||
Reference in new issue
Block a user