ws-3d2/fbx: model/fbx (binary 7.x + ASCII read, binary 7.4 / 7.5 + ASCII write): node tree, Objects / Connections -> Scene (full transform model, layer elements, materials, textures, skins, blend shapes, animation stacks, cameras, lights); tests against assimp + Blender, round trips, fuzz; bench lines
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
75c677074a
commit
8e2e96e198
14 files changed
+4403
No files matched your search
@@ -194,6 +194,18 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/wav")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "fbx",
|
||||
category = "model",
|
||||
path = "model/fbx",
|
||||
extensions = { "fbx" },
|
||||
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
|
||||
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
|
||||
load = function()
|
||||
return require("@formats/model/fbx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gltf",
|
||||
category = "model",
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
--!strict
|
||||
-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';'
|
||||
-- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary
|
||||
-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws.
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
|
||||
local Ascii = {}
|
||||
|
||||
type Node = { name: string, props: { any }, children: { Node } }
|
||||
|
||||
local sbyte, sfind, ssub = string.byte, string.find, string.sub
|
||||
local MAX_DEPTH = 128
|
||||
|
||||
local function isNameStart(c: number): boolean
|
||||
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
|
||||
end
|
||||
|
||||
-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset
|
||||
function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 30
|
||||
local n = #text
|
||||
local i = 1
|
||||
local total = 0
|
||||
|
||||
local function skip()
|
||||
while i <= n do
|
||||
local c = sbyte(text, i)
|
||||
if c == 59 then -- ; comment
|
||||
local e = sfind(text, "\n", i, true)
|
||||
i = if e then e + 1 else n + 1
|
||||
elseif c == 32 or c == 9 or c == 10 or c == 13 then
|
||||
i += 1
|
||||
else
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- at i: a name followed by ':'? -> name, the index after ':'
|
||||
local function nameAt(): (string?, number)
|
||||
local c = sbyte(text, i)
|
||||
if not c or not isNameStart(c) then
|
||||
return nil, i
|
||||
end
|
||||
local s, e = sfind(text, "^[%w_|%-]+", i)
|
||||
if not s then
|
||||
return nil, i
|
||||
end
|
||||
local j = (e :: number) + 1
|
||||
while j <= n do
|
||||
local d = sbyte(text, j)
|
||||
if d == 32 or d == 9 then
|
||||
j += 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if sbyte(text, j) == 58 then
|
||||
return ssub(text, i, e :: number), j + 1
|
||||
end
|
||||
return nil, i
|
||||
end
|
||||
|
||||
-- the values of one node (after the ':'), up to a new name, '{' or '}'
|
||||
local function values(): ({ any }?, string?)
|
||||
local props = {}
|
||||
while true do
|
||||
skip()
|
||||
if i > n then
|
||||
return props
|
||||
end
|
||||
local c = sbyte(text, i)
|
||||
if c == 44 then -- ,
|
||||
i += 1
|
||||
elseif c == 123 or c == 125 then
|
||||
return props
|
||||
elseif c == 34 then -- "
|
||||
local e = sfind(text, "\"", i + 1, true)
|
||||
if not e then
|
||||
return nil, "unterminated string"
|
||||
end
|
||||
local s = ssub(text, i + 1, e - 1)
|
||||
if sfind(s, "&", 1, true) then
|
||||
s = string.gsub(s, """, "\"")
|
||||
end
|
||||
table.insert(props, s)
|
||||
i = e + 1
|
||||
elseif c == 42 then -- *N
|
||||
local s, e = sfind(text, "^%*%d+", i)
|
||||
if not s then
|
||||
return nil, "bad array length"
|
||||
end
|
||||
table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) })
|
||||
i = (e :: number) + 1
|
||||
elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
|
||||
local s, e = sfind(text, "^[-+%deE.]+", i)
|
||||
local tok = ssub(text, i, e :: number)
|
||||
local v = tonumber(tok)
|
||||
if v == nil then
|
||||
-- "1.#INF", "-1.#IND", "nan": special floats
|
||||
local s2, e2 = sfind(text, "^[-+%w.#]+", i)
|
||||
tok = ssub(text, i, e2 :: number)
|
||||
local low = string.lower(tok)
|
||||
if sfind(low, "inf", 1, true) then
|
||||
v = if sbyte(tok, 1) == 45 then -math.huge else math.huge
|
||||
else
|
||||
v = 0 / 0
|
||||
end
|
||||
e = e2
|
||||
local _ = s2
|
||||
elseif #tok > 15 and not sfind(tok, "[.eE]") then
|
||||
v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any
|
||||
end
|
||||
local _ = s
|
||||
table.insert(props, v)
|
||||
i = (e :: number) + 1
|
||||
else
|
||||
local nm = nameAt()
|
||||
if nm then
|
||||
return props
|
||||
end
|
||||
local s, e = sfind(text, "^[%w_]+", i)
|
||||
if not s then
|
||||
return nil, string.format("unexpected character %q", ssub(text, i, i))
|
||||
end
|
||||
table.insert(props, ssub(text, i, e :: number))
|
||||
i = (e :: number) + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function nodes(depth: number, into: { Node }): string?
|
||||
while true do
|
||||
skip()
|
||||
if i > n then
|
||||
return if depth > 0 then "unterminated {" else nil
|
||||
end
|
||||
if sbyte(text, i) == 125 then
|
||||
if depth == 0 then
|
||||
return "unbalanced }"
|
||||
end
|
||||
i += 1
|
||||
return nil
|
||||
end
|
||||
local name, j = nameAt()
|
||||
if not name then
|
||||
return string.format("expected a node name at %q", ssub(text, i, i + 10))
|
||||
end
|
||||
i = j
|
||||
local props, err = values()
|
||||
if not props then
|
||||
return err
|
||||
end
|
||||
local node: Node = { name = name, props = props, children = {} }
|
||||
skip()
|
||||
if sbyte(text, i) == 123 then
|
||||
if depth >= MAX_DEPTH then
|
||||
return "nodes nested too deep"
|
||||
end
|
||||
i += 1
|
||||
local e = nodes(depth + 1, node.children)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
-- "*N { a: v, v, ... }" -> an Array
|
||||
local p1 = props[1]
|
||||
if #props == 1 and type(p1) == "table" and p1.star then
|
||||
local a = node.children[1]
|
||||
local count = if a and a.name == "a" then #a.props else 0
|
||||
total += count * 8
|
||||
if total > maxBytes then
|
||||
return "limit:arrays over " .. maxBytes .. " bytes"
|
||||
end
|
||||
local data = buffer.create(count * 8)
|
||||
for k = 1, count do
|
||||
local v = (a :: Node).props[k]
|
||||
buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0))
|
||||
end
|
||||
node.props = { { array = true, type = "d", count = count, data = data } }
|
||||
node.children = {}
|
||||
end
|
||||
table.insert(into, node)
|
||||
end
|
||||
end
|
||||
|
||||
local root: Node = { name = "", props = {}, children = {} }
|
||||
local err = nodes(0, root.children)
|
||||
if err then
|
||||
return nil, err, i - 1
|
||||
end
|
||||
local version = nil
|
||||
for _, c in root.children do
|
||||
if c.name == "FBXHeaderExtension" then
|
||||
for _, d in c.children do
|
||||
if d.name == "FBXVersion" then
|
||||
version = d.props[1]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return root, version, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer
|
||||
local function fmt(v: number): string
|
||||
if v == math.floor(v) and math.abs(v) < 1e15 then
|
||||
return string.format("%d", v)
|
||||
end
|
||||
if v ~= v then
|
||||
return "0"
|
||||
end
|
||||
return string.format("%.17g", v)
|
||||
end
|
||||
|
||||
-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes)
|
||||
function Ascii.write(root: any, version: number?): string
|
||||
local out = { string.format("; FBX %d.%d.0 project file\n; Created by formats-luau\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) }
|
||||
local function node(nd: any, indent: string)
|
||||
local parts = {}
|
||||
local arr = nil
|
||||
for _, v in nd.props do
|
||||
local tv = type(v)
|
||||
if tv == "number" then
|
||||
table.insert(parts, fmt(v))
|
||||
elseif tv == "boolean" then
|
||||
table.insert(parts, if v then "T" else "F")
|
||||
elseif tv == "string" then
|
||||
if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then
|
||||
table.insert(parts, string.sub(v, 2))
|
||||
else
|
||||
local nm, cls = string.match(v, "^(.-)%z\1(.*)$")
|
||||
local sv = if nm then cls .. "::" .. nm else v
|
||||
table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"")
|
||||
end
|
||||
elseif tv == "table" and v.array then
|
||||
arr = v
|
||||
elseif tv == "buffer" then
|
||||
-- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them
|
||||
local b64 = Base64.encode(v)
|
||||
local chunks = {}
|
||||
for k = 1, #b64, 2048 do
|
||||
table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"")
|
||||
end
|
||||
table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"")
|
||||
end
|
||||
end
|
||||
if arr then
|
||||
local vals = table.create(arr.count)
|
||||
for k = 0, arr.count - 1 do
|
||||
vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8))
|
||||
end
|
||||
table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent))
|
||||
return
|
||||
end
|
||||
table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", "))
|
||||
local ch = nd.children
|
||||
if ch and #ch > 0 then
|
||||
table.insert(out, " {\n")
|
||||
for _, c in ch do
|
||||
node(c, indent .. "\t")
|
||||
end
|
||||
table.insert(out, indent .. "}\n")
|
||||
else
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
end
|
||||
for _, c in root.children do
|
||||
node(c, "")
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
return Ascii
|
||||
@@ -0,0 +1,461 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit
|
||||
-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's
|
||||
-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array
|
||||
-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become
|
||||
-- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset).
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
|
||||
local Binary = {}
|
||||
|
||||
export type Node = { name: string, props: { any }, children: { Node } }
|
||||
export type Array = { array: true, type: string, count: number, data: buffer }
|
||||
|
||||
local MAGIC = "Kaydara FBX Binary \0"
|
||||
Binary.MAGIC = MAGIC
|
||||
local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126"
|
||||
local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11"
|
||||
local MAX_DEPTH = 128
|
||||
|
||||
local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16
|
||||
local writef64 = buffer.writef64
|
||||
|
||||
-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>"
|
||||
local function i64(b: buffer, p: number, asString: boolean): any
|
||||
local lo, hi = readu32(b, p), readu32(b, p + 4)
|
||||
if hi >= 0x80000000 then
|
||||
local v = (hi - 4294967296) * 4294967296 + lo
|
||||
if v >= -9007199254740991 or not asString then
|
||||
return v
|
||||
end
|
||||
else
|
||||
if hi < 0x200000 or not asString then
|
||||
return hi * 4294967296 + lo
|
||||
end
|
||||
end
|
||||
return string.format("L%08x%08x", hi, lo)
|
||||
end
|
||||
Binary.i64 = i64
|
||||
|
||||
local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 }
|
||||
|
||||
-- the elements of a raw array (n elements of type t at p) as f64s
|
||||
local function toF64(t: string, src: buffer, p: number, n: number): buffer
|
||||
local out = buffer.create(n * 8)
|
||||
if t == "d" then
|
||||
buffer.copy(out, 0, src, p, n * 8)
|
||||
elseif t == "f" then
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readf32(src, p + k * 4))
|
||||
end
|
||||
elseif t == "i" then
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readi32(src, p + k * 4))
|
||||
end
|
||||
elseif t == "l" then
|
||||
for k = 0, n - 1 do
|
||||
local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4)
|
||||
writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo)
|
||||
end
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readu8(src, p + k))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset
|
||||
function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 30
|
||||
if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then
|
||||
return nil, "not a binary FBX", base
|
||||
end
|
||||
local version = readu32(b, base + 23)
|
||||
if version < 7000 or version >= 10000 then
|
||||
return nil, "unsupported:FBX version " .. version, base + 23
|
||||
end
|
||||
local wide = version >= 7500
|
||||
local head = if wide then 25 else 13
|
||||
local total = 0
|
||||
|
||||
local function props(p: number, n: number, stop: number): ({ any }?, any)
|
||||
local out = table.create(math.min(n, 64))
|
||||
for k = 1, n do
|
||||
if p >= stop then
|
||||
return nil, "property list runs past its record"
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
local v: any
|
||||
if c == 89 then -- Y
|
||||
if p + 2 > stop then return nil, "truncated property" end
|
||||
v = readi16(b, p)
|
||||
p += 2
|
||||
elseif c == 67 then -- C
|
||||
if p + 1 > stop then return nil, "truncated property" end
|
||||
v = readu8(b, p) ~= 0
|
||||
p += 1
|
||||
elseif c == 73 then -- I
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
v = readi32(b, p)
|
||||
p += 4
|
||||
elseif c == 70 then -- F
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
v = readf32(b, p)
|
||||
p += 4
|
||||
elseif c == 68 then -- D
|
||||
if p + 8 > stop then return nil, "truncated property" end
|
||||
v = readf64(b, p)
|
||||
p += 8
|
||||
elseif c == 76 then -- L
|
||||
if p + 8 > stop then return nil, "truncated property" end
|
||||
v = i64(b, p, true)
|
||||
p += 8
|
||||
elseif c == 83 or c == 82 then -- S, R
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
local len = readu32(b, p)
|
||||
p += 4
|
||||
if len > stop - p then return nil, "string runs past its record" end
|
||||
if c == 83 then
|
||||
v = buffer.readstring(b, p, len)
|
||||
else
|
||||
local raw = buffer.create(len)
|
||||
buffer.copy(raw, 0, b, p, len)
|
||||
v = raw
|
||||
end
|
||||
p += len
|
||||
elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c
|
||||
if p + 12 > stop then return nil, "truncated array header" end
|
||||
local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8)
|
||||
p += 12
|
||||
local t = string.char(c)
|
||||
local es = ELEM[t]
|
||||
if clen > stop - p then return nil, "array runs past its record" end
|
||||
total += count * 8
|
||||
if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end
|
||||
local data: buffer
|
||||
if enc == 0 then
|
||||
if clen < count * es then return nil, "raw array shorter than its count" end
|
||||
data = toF64(t, b, p, count)
|
||||
elseif enc == 1 then
|
||||
local raw, err = Deflate.zlib(b, p, clen, count * es)
|
||||
if not raw then
|
||||
return nil, "array: " .. tostring(if type(err) == "table" then err.message else err)
|
||||
end
|
||||
data = toF64(t, raw, 0, count)
|
||||
else
|
||||
return nil, "unknown array encoding " .. enc
|
||||
end
|
||||
p += clen
|
||||
v = { array = true, type = t, count = count, data = data }
|
||||
else
|
||||
return nil, string.format("unknown property type 0x%02x", c)
|
||||
end
|
||||
out[k] = v
|
||||
end
|
||||
return out, p
|
||||
end
|
||||
|
||||
-- one node record at p: node | false (the null record), next offset | nil, message, offset
|
||||
local function node(p: number, stop: number, depth: number): (any, any, number?)
|
||||
if p + head > stop then
|
||||
return nil, "truncated node record", p
|
||||
end
|
||||
local endOff, nprops, plen, nlen
|
||||
if wide then
|
||||
endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296
|
||||
nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296
|
||||
plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296
|
||||
nlen = readu8(b, p + 24)
|
||||
else
|
||||
endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12)
|
||||
end
|
||||
if endOff == 0 then
|
||||
return false, p + head
|
||||
end
|
||||
local e = base + endOff
|
||||
if e > stop or e < p + head + nlen + plen then
|
||||
return nil, "node end offset out of range", p
|
||||
end
|
||||
if nprops > plen then
|
||||
return nil, "more properties than bytes", p
|
||||
end
|
||||
local q = p + head
|
||||
local name = buffer.readstring(b, q, nlen)
|
||||
q += nlen
|
||||
local pl, nq = props(q, nprops, q + plen)
|
||||
if not pl then
|
||||
return nil, nq, q
|
||||
end
|
||||
q += plen
|
||||
local children: { Node } = {}
|
||||
if q < e then
|
||||
if depth >= MAX_DEPTH then
|
||||
return nil, "nodes nested too deep", p
|
||||
end
|
||||
while q < e do
|
||||
local child, nx, off = node(q, e, depth + 1)
|
||||
if child == nil then
|
||||
return nil, nx, off
|
||||
end
|
||||
q = nx
|
||||
if child == false then
|
||||
break
|
||||
end
|
||||
table.insert(children, child)
|
||||
end
|
||||
end
|
||||
return { name = name, props = pl, children = children }, e
|
||||
end
|
||||
|
||||
local root: Node = { name = "", props = {}, children = {} }
|
||||
local p = base + 27
|
||||
while p < limit do
|
||||
local n, nx, off = node(p, limit, 0)
|
||||
if n == nil then
|
||||
if #root.children > 0 and p + head > limit then
|
||||
break -- a file cut right after its last node: keep what was read
|
||||
end
|
||||
return nil, nx, off
|
||||
end
|
||||
if n == false then
|
||||
break
|
||||
end
|
||||
table.insert(root.children, n)
|
||||
p = nx
|
||||
end
|
||||
return root, version, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer
|
||||
-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit
|
||||
-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint
|
||||
-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their
|
||||
-- type (compressed with zlib when longer than 32 elements, unless compress = false).
|
||||
export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
|
||||
|
||||
local function sizeHint(n: WNode): number
|
||||
local s = 32 + #n.name
|
||||
for _, v in n.props do
|
||||
if type(v) == "string" then
|
||||
s += 5 + #v
|
||||
elseif type(v) == "buffer" then
|
||||
s += 5 + buffer.len(v)
|
||||
elseif type(v) == "table" then
|
||||
s += 13 + (v.count or 0) * 8
|
||||
else
|
||||
s += 9
|
||||
end
|
||||
end
|
||||
for _, c in n.children or {} do
|
||||
s += sizeHint(c)
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
function Binary.write(root: WNode, version: number?, compress: boolean?): buffer
|
||||
local zip = compress ~= false
|
||||
local ver = version or 7400
|
||||
local wide = ver >= 7500
|
||||
local head = if wide then 25 else 13
|
||||
local cap = sizeHint(root) + 256
|
||||
local out = buffer.create(cap)
|
||||
local pos = 0
|
||||
local function ensure(n: number)
|
||||
if pos + n > cap then
|
||||
while pos + n > cap do
|
||||
cap *= 2
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, out, 0, pos)
|
||||
out = nb
|
||||
end
|
||||
end
|
||||
local function u8(v: number)
|
||||
ensure(1)
|
||||
buffer.writeu8(out, pos, v)
|
||||
pos += 1
|
||||
end
|
||||
local function u32(v: number)
|
||||
ensure(4)
|
||||
buffer.writeu32(out, pos, v)
|
||||
pos += 4
|
||||
end
|
||||
local function i64w(v: number)
|
||||
ensure(8)
|
||||
local hi = math.floor(v / 4294967296)
|
||||
local lo = v - hi * 4294967296
|
||||
buffer.writeu32(out, pos, lo)
|
||||
buffer.writeu32(out, pos + 4, hi % 4294967296)
|
||||
pos += 8
|
||||
end
|
||||
local function str(s: string)
|
||||
ensure(#s)
|
||||
buffer.writestring(out, pos, s)
|
||||
pos += #s
|
||||
end
|
||||
local function bytes(src: buffer)
|
||||
local n = buffer.len(src)
|
||||
ensure(n)
|
||||
buffer.copy(out, pos, src, 0, n)
|
||||
pos += n
|
||||
end
|
||||
local function array(a: any)
|
||||
local t, n, d = a.type, a.count, a.data
|
||||
local es = ELEM[t] or 8
|
||||
local raw = buffer.create(n * es)
|
||||
if a.raw then
|
||||
buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es))
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
local v = readf64(d, k * 8)
|
||||
if t == "d" then
|
||||
writef64(raw, k * 8, v)
|
||||
elseif t == "f" then
|
||||
buffer.writef32(raw, k * 4, v)
|
||||
elseif t == "i" then
|
||||
buffer.writei32(raw, k * 4, v)
|
||||
elseif t == "b" then
|
||||
buffer.writeu8(raw, k, if v ~= 0 then 1 else 0)
|
||||
else
|
||||
local hi = math.floor(v / 4294967296)
|
||||
buffer.writeu32(raw, k * 8, v - hi * 4294967296)
|
||||
buffer.writeu32(raw, k * 8 + 4, hi % 4294967296)
|
||||
end
|
||||
end
|
||||
end
|
||||
u8(string.byte(t))
|
||||
u32(n)
|
||||
if zip and n > 32 then
|
||||
local z = Deflate.zlibCompress(raw, { level = 6 })
|
||||
if z then
|
||||
u32(1)
|
||||
u32(buffer.len(z))
|
||||
bytes(z)
|
||||
return
|
||||
end
|
||||
end
|
||||
u32(0)
|
||||
u32(n * es)
|
||||
bytes(raw)
|
||||
end
|
||||
local function setOff(at: number, v: number)
|
||||
if wide then
|
||||
buffer.writeu32(out, at, v % 4294967296)
|
||||
buffer.writeu32(out, at + 4, math.floor(v / 4294967296))
|
||||
else
|
||||
buffer.writeu32(out, at, v)
|
||||
end
|
||||
end
|
||||
local function nullRecord()
|
||||
ensure(head)
|
||||
buffer.fill(out, pos, 0, head)
|
||||
pos += head
|
||||
end
|
||||
local function node(n: WNode)
|
||||
local start = pos
|
||||
ensure(head)
|
||||
buffer.fill(out, pos, 0, head)
|
||||
pos += head
|
||||
buffer.writeu8(out, start + head - 1, #n.name)
|
||||
str(n.name)
|
||||
local pstart = pos
|
||||
local hints = n.types or ""
|
||||
for k, v in n.props do
|
||||
local h = string.sub(hints, k, k)
|
||||
local tv = type(v)
|
||||
if tv == "number" then
|
||||
if h == "I" then
|
||||
u8(73)
|
||||
ensure(4)
|
||||
buffer.writei32(out, pos, v)
|
||||
pos += 4
|
||||
elseif h == "L" then
|
||||
u8(76)
|
||||
i64w(v)
|
||||
elseif h == "F" then
|
||||
u8(70)
|
||||
ensure(4)
|
||||
buffer.writef32(out, pos, v)
|
||||
pos += 4
|
||||
elseif h == "Y" then
|
||||
u8(89)
|
||||
ensure(2)
|
||||
buffer.writei16(out, pos, v)
|
||||
pos += 2
|
||||
else
|
||||
u8(68)
|
||||
ensure(8)
|
||||
writef64(out, pos, v)
|
||||
pos += 8
|
||||
end
|
||||
elseif tv == "boolean" then
|
||||
u8(67)
|
||||
u8(if v then 1 else 0)
|
||||
elseif tv == "string" then
|
||||
if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then
|
||||
u8(76)
|
||||
local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0
|
||||
u32(lo)
|
||||
u32(hi)
|
||||
else
|
||||
u8(83)
|
||||
u32(#v)
|
||||
str(v)
|
||||
end
|
||||
elseif tv == "buffer" then
|
||||
u8(82)
|
||||
u32(buffer.len(v))
|
||||
bytes(v)
|
||||
elseif tv == "table" and v.array then
|
||||
array(v)
|
||||
else
|
||||
u8(83)
|
||||
u32(0)
|
||||
end
|
||||
end
|
||||
local plen = pos - pstart
|
||||
local children = n.children
|
||||
if children and #children > 0 then
|
||||
for _, c in children do
|
||||
node(c)
|
||||
end
|
||||
nullRecord()
|
||||
elseif #n.props == 0 then
|
||||
nullRecord()
|
||||
end
|
||||
setOff(start, pos)
|
||||
if wide then
|
||||
setOff(start + 8, #n.props)
|
||||
setOff(start + 16, plen)
|
||||
else
|
||||
buffer.writeu32(out, start + 4, #n.props)
|
||||
buffer.writeu32(out, start + 8, plen)
|
||||
end
|
||||
end
|
||||
str(MAGIC)
|
||||
u8(0x1A)
|
||||
u8(0)
|
||||
u32(ver)
|
||||
for _, c in root.children or {} do
|
||||
node(c)
|
||||
end
|
||||
nullRecord()
|
||||
str(FOOT_ID)
|
||||
str("\0\0\0\0")
|
||||
local pad = ((pos + 15) // 16) * 16 - pos
|
||||
if pad == 0 then
|
||||
pad = 16
|
||||
end
|
||||
str(string.rep("\0", pad))
|
||||
u32(ver)
|
||||
str(string.rep("\0", 120))
|
||||
str(FOOT_MAGIC)
|
||||
local res = buffer.create(pos)
|
||||
buffer.copy(res, 0, out, 0, pos)
|
||||
return res
|
||||
end
|
||||
|
||||
return Binary
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,996 @@
|
||||
--!strict
|
||||
-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types
|
||||
-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f).
|
||||
-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one
|
||||
-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals
|
||||
-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material;
|
||||
-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets ->
|
||||
-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Xform = require("@formats/model/fbx/Xform")
|
||||
|
||||
local Write = {}
|
||||
|
||||
type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
|
||||
|
||||
local TICKS = 46186158000
|
||||
local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } }
|
||||
|
||||
local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode
|
||||
return { name = name, types = types, props = props, children = children }
|
||||
end
|
||||
local function arr(t: string, list: { number }): any
|
||||
local n = #list
|
||||
local d = buffer.create(n * 8)
|
||||
for k = 1, n do
|
||||
buffer.writef64(d, (k - 1) * 8, list[k])
|
||||
end
|
||||
return { array = true, type = t, count = n, data = d }
|
||||
end
|
||||
-- P: name, type, label, flags, values (vt: one type character per value)
|
||||
local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode
|
||||
return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } }
|
||||
end
|
||||
local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode
|
||||
return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3])
|
||||
end
|
||||
local function Pcolor(name: string, v: { number }): WNode
|
||||
return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0)
|
||||
end
|
||||
local function Pnum(name: string, v: number): WNode
|
||||
return P(name, "Number", "", "A", "D", v)
|
||||
end
|
||||
local function Pint(name: string, v: number): WNode
|
||||
return P(name, "int", "Integer", "", "I", v)
|
||||
end
|
||||
local function Penum(name: string, v: number): WNode
|
||||
return P(name, "enum", "", "", "I", v)
|
||||
end
|
||||
local function Pdouble(name: string, v: number): WNode
|
||||
return P(name, "double", "Number", "", "D", v)
|
||||
end
|
||||
local function Ptime(name: string, v: number): WNode
|
||||
return P(name, "KTime", "Time", "", "L", v)
|
||||
end
|
||||
local function cls(name: string?, class: string): string
|
||||
return (name or "") .. "\0\1" .. class
|
||||
end
|
||||
|
||||
local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)?
|
||||
if not acc then
|
||||
return nil
|
||||
end
|
||||
return Types.Scene.reader(acc)
|
||||
end
|
||||
|
||||
-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based)
|
||||
local function faces(prim: Types.Primitive): { { number } }?
|
||||
local pos = prim.attributes.POSITION
|
||||
if not pos then
|
||||
return nil
|
||||
end
|
||||
local n = pos.count
|
||||
local idx = accessorReader(prim.indices)
|
||||
local count = if prim.indices then prim.indices.count else n
|
||||
local function I(k: number): number
|
||||
return if idx then idx(k, 0) else k
|
||||
end
|
||||
local out: { { number } } = {}
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "triangles" then
|
||||
for k = 0, count // 3 - 1 do
|
||||
table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) })
|
||||
end
|
||||
elseif mode == "polygons" and prim.faces then
|
||||
local f = accessorReader(prim.faces)
|
||||
local p = 0
|
||||
if f then
|
||||
for k = 0, prim.faces.count - 1 do
|
||||
local sz = f(k, 0)
|
||||
if p + sz > count then
|
||||
break
|
||||
end
|
||||
local poly = table.create(sz)
|
||||
for q = 0, sz - 1 do
|
||||
poly[q + 1] = I(p + q)
|
||||
end
|
||||
p += sz
|
||||
table.insert(out, poly)
|
||||
end
|
||||
end
|
||||
elseif mode == "triangle_strip" then
|
||||
for k = 0, count - 3 do
|
||||
local a, b, c = I(k), I(k + 1), I(k + 2)
|
||||
if k % 2 == 1 then
|
||||
a, b = b, a
|
||||
end
|
||||
table.insert(out, { a, b, c })
|
||||
end
|
||||
elseif mode == "triangle_fan" then
|
||||
for k = 1, count - 2 do
|
||||
table.insert(out, { I(0), I(k), I(k + 1) })
|
||||
end
|
||||
else
|
||||
return nil -- points / lines: not written
|
||||
end
|
||||
for _, f in out do
|
||||
for q, v in f do
|
||||
if v < 0 or v >= n then
|
||||
f[q] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
|
||||
local flipV = not (opts and opts.flipV == false)
|
||||
local embed = not (opts and opts.embedTextures == false)
|
||||
local nextId = 1000000
|
||||
local function id(): number
|
||||
nextId += 1
|
||||
return nextId
|
||||
end
|
||||
local objects: { WNode } = {}
|
||||
local conns: { WNode } = {}
|
||||
local counts: { [string]: number } = {}
|
||||
local function add(class: string, node: WNode)
|
||||
table.insert(objects, node)
|
||||
counts[class] = (counts[class] or 0) + 1
|
||||
end
|
||||
local function OO(child: number, parent: number)
|
||||
table.insert(conns, N("C", "SLL", { "OO", child, parent }))
|
||||
end
|
||||
local function OP(child: number, parent: number, prop: string)
|
||||
table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop }))
|
||||
end
|
||||
local nodes = scene.nodes or {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ textures
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" }
|
||||
local texIds: { [number]: number } = {}
|
||||
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
|
||||
for ti, tex in scene.textures or {} do
|
||||
local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png"))
|
||||
local tname = tex.name or ("Texture" .. ti)
|
||||
local vid, tid = id(), id()
|
||||
local vchildren = {
|
||||
N("Type", "S", { "Clip" }),
|
||||
N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }),
|
||||
N("UseMipMap", "I", { 0 }),
|
||||
N("Filename", "S", { file }),
|
||||
N("RelativeFilename", "S", { file }),
|
||||
}
|
||||
if embed and tex.data then
|
||||
table.insert(vchildren, N("Content", "R", { tex.data }))
|
||||
end
|
||||
add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren))
|
||||
local tp = { P("UseMaterial", "bool", "", "", "I", 1) }
|
||||
local smp = tex.sampler
|
||||
if smp and smp.wrapS == "clamp" then
|
||||
table.insert(tp, Penum("WrapModeU", 1))
|
||||
end
|
||||
if smp and smp.wrapT == "clamp" then
|
||||
table.insert(tp, Penum("WrapModeV", 1))
|
||||
end
|
||||
add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, {
|
||||
N("Type", "S", { "TextureVideoClip" }),
|
||||
N("Version", "I", { 202 }),
|
||||
N("TextureName", "S", { cls(tname, "Texture") }),
|
||||
N("Properties70", "", {}, tp),
|
||||
N("Media", "S", { cls(tname, "Video") }),
|
||||
N("FileName", "S", { file }),
|
||||
N("RelativeFilename", "S", { file }),
|
||||
N("ModelUVTranslation", "DD", { 0, 0 }),
|
||||
N("ModelUVScaling", "DD", { 1, 1 }),
|
||||
N("Texture_Alpha_Source", "S", { "None" }),
|
||||
N("Cropping", "IIII", { 0, 0, 0, 0 }),
|
||||
}))
|
||||
OO(vid, tid)
|
||||
texIds[ti] = tid
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ materials
|
||||
local matIds: { [number]: number } = {}
|
||||
for mi, m in scene.materials or {} do
|
||||
local x = m.extras and (m.extras :: any).fbx or {}
|
||||
local bc = m.baseColor or { 1, 1, 1, 1 }
|
||||
local alpha = bc[4] or 1
|
||||
local rough = math.clamp(m.roughness or 1, 0.02, 1)
|
||||
local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2
|
||||
local em = m.emissive or { 0, 0, 0 }
|
||||
local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 }
|
||||
local pid = id()
|
||||
local props = {
|
||||
Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }),
|
||||
Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1),
|
||||
Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }),
|
||||
Pnum("DiffuseFactor", 1),
|
||||
Pcolor("EmissiveColor", em),
|
||||
Pnum("EmissiveFactor", 1),
|
||||
Pcolor("SpecularColor", spec),
|
||||
Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1),
|
||||
Pnum("Shininess", shin),
|
||||
Pnum("ShininessExponent", shin),
|
||||
Pcolor("TransparentColor", { 1, 1, 1 }),
|
||||
Pnum("TransparencyFactor", 1 - alpha),
|
||||
Pnum("Opacity", alpha),
|
||||
Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }),
|
||||
Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0),
|
||||
}
|
||||
add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, {
|
||||
N("Version", "I", { 102 }),
|
||||
N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }),
|
||||
N("MultiLayer", "I", { 0 }),
|
||||
N("Properties70", "", {}, props),
|
||||
}))
|
||||
matIds[mi] = pid
|
||||
local function link(ref: Types.TextureRef?, prop: string)
|
||||
local t = ref and texIds[ref.texture]
|
||||
if t then
|
||||
OP(t, pid, prop)
|
||||
end
|
||||
end
|
||||
link(m.baseColorTexture, "DiffuseColor")
|
||||
link(m.normalTexture, "NormalMap")
|
||||
link(m.emissiveTexture, "EmissiveColor")
|
||||
-- the other textures the FBX material had (specular, metalness, ... maps), under their property names
|
||||
local linked = {
|
||||
[m.baseColorTexture and m.baseColorTexture.texture or -1] = true,
|
||||
[m.normalTexture and m.normalTexture.texture or -1] = true,
|
||||
[m.emissiveTexture and m.emissiveTexture.texture or -1] = true,
|
||||
}
|
||||
if type(x.textures) == "table" then
|
||||
local props = {}
|
||||
for prop in x.textures do
|
||||
table.insert(props, prop)
|
||||
end
|
||||
table.sort(props)
|
||||
for _, prop in props do
|
||||
local ti = x.textures[prop]
|
||||
if type(ti) == "number" and not linked[ti] and texIds[ti] then
|
||||
linked[ti] = true
|
||||
OP(texIds[ti], pid, prop)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ models
|
||||
local modelIds: { [number]: number } = {}
|
||||
local skip: { [number]: boolean } = {}
|
||||
local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there)
|
||||
local parentOf: { [number]: number } = {}
|
||||
for i, nd in nodes do
|
||||
for _, c in nd.children or {} do
|
||||
if parentOf[c] == nil and c ~= i then
|
||||
parentOf[c] = i
|
||||
end
|
||||
end
|
||||
end
|
||||
local jointSet: { [number]: boolean } = {}
|
||||
for _, s in scene.skins or {} do
|
||||
for _, j in s.joints do
|
||||
jointSet[j] = true
|
||||
end
|
||||
end
|
||||
for i, nd in nodes do
|
||||
local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation
|
||||
local p = parentOf[i]
|
||||
if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then
|
||||
skip[i] = true
|
||||
attrHost[i] = p
|
||||
end
|
||||
end
|
||||
-- world matrices (rest pose) for clusters and the bind pose
|
||||
local worldM: { [number]: Xform.M4 } = {}
|
||||
local visiting: { [number]: boolean } = {}
|
||||
local function world(i: number): Xform.M4
|
||||
if worldM[i] then
|
||||
return worldM[i]
|
||||
end
|
||||
if visiting[i] then
|
||||
return Xform.identity()
|
||||
end
|
||||
visiting[i] = true
|
||||
local nd = nodes[i]
|
||||
local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale)
|
||||
local p = parentOf[i]
|
||||
local w = if p then Xform.mul(world(p), l) else l
|
||||
worldM[i] = w
|
||||
return w
|
||||
end
|
||||
local function trs(nd: Types.Node): ({ number }, { number }, { number })
|
||||
if nd.matrix and #nd.matrix == 16 then
|
||||
return Xform.decompose(nd.matrix)
|
||||
end
|
||||
return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 }
|
||||
end
|
||||
local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number
|
||||
local mid = id()
|
||||
add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, {
|
||||
N("Version", "I", { 232 }),
|
||||
N("Properties70", "", {}, {
|
||||
Penum("RotationOrder", 0),
|
||||
Penum("InheritType", 1),
|
||||
Pint("DefaultAttributeIndex", 0),
|
||||
Pvec("Lcl Translation", "Lcl Translation", "", t),
|
||||
Pvec("Lcl Rotation", "Lcl Rotation", "", r),
|
||||
Pvec("Lcl Scaling", "Lcl Scaling", "", s),
|
||||
}),
|
||||
N("Shading", "C", { true }),
|
||||
N("Culling", "S", { "CullingOff" }),
|
||||
}))
|
||||
return mid
|
||||
end
|
||||
local function attribute(nd: Types.Node, mid: number, nodeName: string)
|
||||
if nd.camera and scene.cameras[nd.camera] then
|
||||
local c = scene.cameras[nd.camera]
|
||||
local aid = id()
|
||||
local aspect = c.aspect or 4 / 3
|
||||
local fh = 0.612
|
||||
local fw = fh * aspect
|
||||
local props
|
||||
if c.type == "orthographic" then
|
||||
props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) }
|
||||
else
|
||||
local yfov = c.yfov or 0.8
|
||||
local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect)
|
||||
local focal = fw * 25.4 / (2 * math.tan(hfov / 2))
|
||||
props = {
|
||||
Penum("CameraProjectionType", 0),
|
||||
Penum("ApertureMode", 1),
|
||||
P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi),
|
||||
P("FocalLength", "Number", "", "A", "D", focal),
|
||||
Pdouble("FilmWidth", fw),
|
||||
Pdouble("FilmHeight", fh),
|
||||
Penum("AspectRatioMode", 0),
|
||||
Pdouble("AspectWidth", aspect * 100),
|
||||
Pdouble("AspectHeight", 100),
|
||||
Pdouble("NearPlane", c.znear or 0.1),
|
||||
Pdouble("FarPlane", c.zfar or 1000),
|
||||
}
|
||||
end
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, {
|
||||
N("Properties70", "", {}, props),
|
||||
N("TypeFlags", "S", { "Camera" }),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
}))
|
||||
OO(aid, mid)
|
||||
elseif nd.light and scene.lights[nd.light] then
|
||||
local l = scene.lights[nd.light]
|
||||
local aid = id()
|
||||
local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0
|
||||
local props = {
|
||||
Penum("LightType", lt),
|
||||
Pcolor("Color", l.color or { 1, 1, 1 }),
|
||||
Pnum("Intensity", (l.intensity or 1) * 100),
|
||||
P("CastLight", "bool", "", "", "I", 1),
|
||||
}
|
||||
if lt == 2 then
|
||||
table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi))
|
||||
table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi))
|
||||
end
|
||||
if l.range then
|
||||
table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1))
|
||||
table.insert(props, Pnum("FarAttenuationEnd", l.range))
|
||||
end
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, {
|
||||
N("Properties70", "", {}, props),
|
||||
N("TypeFlags", "S", { "Light" }),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
}))
|
||||
OO(aid, mid)
|
||||
end
|
||||
end
|
||||
for i, nd in nodes do
|
||||
if not skip[i] then
|
||||
local t, r, s = trs(nd)
|
||||
local euler = Xform.eulerXYZ(r)
|
||||
local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type
|
||||
local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null"
|
||||
-- an orientation child folded into this node gives it its attribute
|
||||
local folded: number? = nil
|
||||
for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array)
|
||||
if host == i then
|
||||
folded = c
|
||||
end
|
||||
end
|
||||
if not nd.mesh and folded then
|
||||
sub = if nodes[folded].camera then "Camera" else "Light"
|
||||
end
|
||||
local mid = model(nd.name or ("Node" .. i), sub, t, euler, s)
|
||||
modelIds[i] = mid
|
||||
if sub == "LimbNode" then
|
||||
local aid = id()
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) }))
|
||||
OO(aid, mid)
|
||||
end
|
||||
if folded then
|
||||
attribute(nodes[folded], mid, nd.name or "")
|
||||
end
|
||||
if nd.camera or nd.light then
|
||||
-- a glTF-oriented camera / light: an FBX-oriented child model carries it
|
||||
local kind = if nd.camera then "camera" else "light"
|
||||
local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 })
|
||||
OO(cmid, mid)
|
||||
attribute(nd, cmid, nd.name or "")
|
||||
end
|
||||
end
|
||||
end
|
||||
for i in nodes do
|
||||
local mid = modelIds[i]
|
||||
if mid then
|
||||
local p = parentOf[i]
|
||||
local pm = p and modelIds[p]
|
||||
OO(mid, pm or 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ geometry
|
||||
local geoIds: { [number]: number } = {}
|
||||
local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot
|
||||
local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {}
|
||||
local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation)
|
||||
local geoCount: { [number]: number } = {}
|
||||
local function geometry(mi: number): number?
|
||||
if geoIds[mi] then
|
||||
return geoIds[mi]
|
||||
end
|
||||
local mesh = scene.meshes[mi]
|
||||
if not mesh then
|
||||
return nil
|
||||
end
|
||||
local V, PVI, NRM, MATS = {}, {}, {}, {}
|
||||
local UV: { [number]: { number } } = {}
|
||||
local UVI: { [number]: { number } } = {}
|
||||
local COL: { [number]: { number } } = {}
|
||||
local COLI: { [number]: { number } } = {}
|
||||
local slots: { number } = {}
|
||||
local slotOf: { [number]: number } = {}
|
||||
local hasN = false
|
||||
local nuv, ncol = 0, 0
|
||||
for _, prim in mesh.primitives do
|
||||
for k = 0, 7 do
|
||||
if prim.attributes["TEXCOORD_" .. k] then
|
||||
nuv = math.max(nuv, k + 1)
|
||||
end
|
||||
if prim.attributes["COLOR_" .. k] then
|
||||
ncol = math.max(ncol, k + 1)
|
||||
end
|
||||
end
|
||||
if prim.attributes.NORMAL then
|
||||
hasN = true
|
||||
end
|
||||
end
|
||||
for k = 1, nuv do
|
||||
UV[k], UVI[k] = {}, {}
|
||||
end
|
||||
for k = 1, ncol do
|
||||
COL[k], COLI[k] = {}, {}
|
||||
end
|
||||
local layout = {}
|
||||
local offset = 0
|
||||
for _, prim in mesh.primitives do
|
||||
local fs = faces(prim)
|
||||
local pos = prim.attributes.POSITION
|
||||
local R = accessorReader(pos)
|
||||
if fs and R and pos then
|
||||
table.insert(layout, { prim = prim, offset = offset })
|
||||
local n = pos.count
|
||||
for v = 0, n - 1 do
|
||||
table.insert(V, R(v, 0))
|
||||
table.insert(V, R(v, 1))
|
||||
table.insert(V, R(v, 2))
|
||||
end
|
||||
local NR = accessorReader(prim.attributes.NORMAL)
|
||||
if hasN then
|
||||
for v = 0, n - 1 do
|
||||
if NR then
|
||||
table.insert(NRM, NR(v, 0))
|
||||
table.insert(NRM, NR(v, 1))
|
||||
table.insert(NRM, NR(v, 2))
|
||||
else
|
||||
table.insert(NRM, 0)
|
||||
table.insert(NRM, 0)
|
||||
table.insert(NRM, 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local uvBase: { number } = {}
|
||||
for k = 1, nuv do
|
||||
uvBase[k] = #UV[k] // 2
|
||||
local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)])
|
||||
for v = 0, n - 1 do
|
||||
local u, w = 0, 0
|
||||
if T then
|
||||
u, w = T(v, 0), T(v, 1)
|
||||
end
|
||||
table.insert(UV[k], u)
|
||||
table.insert(UV[k], if flipV then 1 - w else w)
|
||||
end
|
||||
end
|
||||
local colBase: { number } = {}
|
||||
for k = 1, ncol do
|
||||
colBase[k] = #COL[k] // 4
|
||||
local acc = prim.attributes["COLOR_" .. (k - 1)]
|
||||
local C = accessorReader(acc)
|
||||
local comps = acc and acc.components or 4
|
||||
for v = 0, n - 1 do
|
||||
table.insert(COL[k], if C then C(v, 0) else 1)
|
||||
table.insert(COL[k], if C then C(v, 1) else 1)
|
||||
table.insert(COL[k], if C then C(v, 2) else 1)
|
||||
table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1)
|
||||
end
|
||||
end
|
||||
local mat = prim.material or 0
|
||||
local slot = slotOf[mat]
|
||||
if slot == nil then
|
||||
table.insert(slots, mat)
|
||||
slot = #slots - 1
|
||||
slotOf[mat] = slot
|
||||
end
|
||||
for _, f in fs do
|
||||
for q, v in f do
|
||||
local cp = v + offset
|
||||
table.insert(PVI, if q == #f then -cp - 1 else cp)
|
||||
for k = 1, nuv do
|
||||
table.insert(UVI[k], uvBase[k] + v)
|
||||
end
|
||||
for k = 1, ncol do
|
||||
table.insert(COLI[k], colBase[k] + v)
|
||||
end
|
||||
end
|
||||
table.insert(MATS, slot)
|
||||
end
|
||||
offset += n
|
||||
end
|
||||
end
|
||||
if #PVI == 0 then
|
||||
return nil
|
||||
end
|
||||
local gid = id()
|
||||
local ch: { WNode } = {
|
||||
N("Properties70", "", {}, {}),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
N("Vertices", "", { arr("d", V) }),
|
||||
N("PolygonVertexIndex", "", { arr("i", PVI) }),
|
||||
}
|
||||
local layer0: { WNode } = { N("Version", "I", { 100 }) }
|
||||
if hasN then
|
||||
table.insert(ch, N("LayerElementNormal", "I", { 0 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "" }),
|
||||
N("MappingInformationType", "S", { "ByVertice" }),
|
||||
N("ReferenceInformationType", "S", { "Direct" }),
|
||||
N("Normals", "", { arr("d", NRM) }),
|
||||
}))
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
local extraLayers: { WNode } = {}
|
||||
local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {}
|
||||
for k = 1, nuv do
|
||||
table.insert(ch, N("LayerElementUV", "I", { k - 1 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }),
|
||||
N("MappingInformationType", "S", { "ByPolygonVertex" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("UV", "", { arr("d", UV[k]) }),
|
||||
N("UVIndex", "", { arr("i", UVI[k]) }),
|
||||
}))
|
||||
local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) })
|
||||
if k == 1 then
|
||||
table.insert(layer0, le)
|
||||
else
|
||||
table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le }))
|
||||
end
|
||||
end
|
||||
for k = 1, ncol do
|
||||
table.insert(ch, N("LayerElementColor", "I", { k - 1 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }),
|
||||
N("MappingInformationType", "S", { "ByPolygonVertex" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("Colors", "", { arr("d", COL[k]) }),
|
||||
N("ColorIndex", "", { arr("i", COLI[k]) }),
|
||||
}))
|
||||
if k == 1 then
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
end
|
||||
local anyMat = false
|
||||
for _, m in slots do
|
||||
if m ~= 0 and matIds[m] then
|
||||
anyMat = true
|
||||
end
|
||||
end
|
||||
if anyMat then
|
||||
local allSame = #slots == 1
|
||||
table.insert(ch, N("LayerElementMaterial", "I", { 0 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "" }),
|
||||
N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }),
|
||||
}))
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
table.insert(ch, N("Layer", "I", { 0 }, layer0))
|
||||
for _, l in extraLayers do
|
||||
table.insert(ch, l)
|
||||
end
|
||||
add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch))
|
||||
geoIds[mi] = gid
|
||||
geoSlots[mi] = if anyMat then slots else {}
|
||||
geoVerts[mi] = layout
|
||||
geoCount[mi] = offset
|
||||
-- morph targets
|
||||
local prims = mesh.primitives
|
||||
local ntargets = 0
|
||||
for _, l in layout do
|
||||
ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0)
|
||||
end
|
||||
if ntargets > 0 then
|
||||
local bsid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) }))
|
||||
OO(bsid, gid)
|
||||
local names = mesh.extras and (mesh.extras :: any).targetNames or {}
|
||||
for t = 1, ntargets do
|
||||
local IDX, DV, DN = {}, {}, {}
|
||||
local anyN = false
|
||||
for _, l in layout do
|
||||
local tg = l.prim.targets and (l.prim.targets :: any)[t]
|
||||
if tg and tg.NORMAL then
|
||||
anyN = true
|
||||
end
|
||||
end
|
||||
for _, l in layout do
|
||||
local tg = l.prim.targets and (l.prim.targets :: any)[t]
|
||||
local TP = tg and accessorReader(tg.POSITION)
|
||||
local TN = tg and accessorReader(tg.NORMAL)
|
||||
if TP then
|
||||
for v = 0, l.prim.attributes.POSITION.count - 1 do
|
||||
local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2)
|
||||
local nx, ny, nz = 0, 0, 0
|
||||
if TN then
|
||||
nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2)
|
||||
end
|
||||
if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then
|
||||
table.insert(IDX, l.offset + v)
|
||||
table.insert(DV, x)
|
||||
table.insert(DV, y)
|
||||
table.insert(DV, z)
|
||||
if anyN then
|
||||
table.insert(DN, nx)
|
||||
table.insert(DN, ny)
|
||||
table.insert(DN, nz)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t)
|
||||
local chid, shid = id(), id()
|
||||
local w = mesh.weights and mesh.weights[t] or 0
|
||||
add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, {
|
||||
N("Version", "I", { 100 }),
|
||||
N("DeformPercent", "D", { w * 100 }),
|
||||
N("FullWeights", "", { arr("d", { 100 }) }),
|
||||
N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }),
|
||||
}))
|
||||
local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) }
|
||||
if anyN then
|
||||
table.insert(shch, N("Normals", "", { arr("d", DN) }))
|
||||
end
|
||||
add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch))
|
||||
OO(chid, bsid)
|
||||
OO(shid, chid)
|
||||
local gc: any = geoChannels
|
||||
gc[mi] = gc[mi] or {}
|
||||
gc[mi][t] = chid
|
||||
end
|
||||
end
|
||||
local _ = prims
|
||||
return gid
|
||||
end
|
||||
|
||||
local poseNodes: { WNode } = {}
|
||||
local posed: { [number]: boolean } = {}
|
||||
local function pose(mid: number, m: Xform.M4)
|
||||
if posed[mid] then
|
||||
return
|
||||
end
|
||||
posed[mid] = true
|
||||
table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) }))
|
||||
end
|
||||
local skinned: { [string]: boolean } = {}
|
||||
for i, nd in nodes do
|
||||
local mid = modelIds[i]
|
||||
if nd.mesh and mid then
|
||||
local gid = geometry(nd.mesh)
|
||||
if gid then
|
||||
OO(gid, mid)
|
||||
for _, m in geoSlots[nd.mesh] do
|
||||
local pm = matIds[m]
|
||||
if pm then
|
||||
OO(pm, mid)
|
||||
end
|
||||
end
|
||||
-- skin: one Skin per (geometry, skin)
|
||||
local skin = nd.skin and scene.skins[nd.skin]
|
||||
local key = tostring(gid) .. ":" .. tostring(nd.skin)
|
||||
if skin and not skinned[key] then
|
||||
skinned[key] = true
|
||||
local sid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) }))
|
||||
OO(sid, gid)
|
||||
local meshWorld = world(i)
|
||||
pose(mid, meshWorld)
|
||||
local ibm = accessorReader(skin.inverseBindMatrices)
|
||||
-- per joint: control points and weights
|
||||
local perJoint: { { idx: { number }, w: { number } } } = {}
|
||||
for j in skin.joints do
|
||||
perJoint[j] = { idx = {}, w = {} }
|
||||
end
|
||||
for _, l in geoVerts[nd.mesh] do
|
||||
local J = accessorReader(l.prim.attributes.JOINTS_0)
|
||||
local W = accessorReader(l.prim.attributes.WEIGHTS_0)
|
||||
if J and W then
|
||||
for v = 0, l.prim.attributes.POSITION.count - 1 do
|
||||
for q = 0, 3 do
|
||||
local j, w = J(v, q), W(v, q)
|
||||
local pj = perJoint[j + 1]
|
||||
if w > 0 and pj then
|
||||
table.insert(pj.idx, l.offset + v)
|
||||
table.insert(pj.w, w)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for j, ji in skin.joints do
|
||||
local jm = modelIds[ji]
|
||||
if jm then
|
||||
local IB = Xform.identity()
|
||||
if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then
|
||||
for k = 1, 16 do
|
||||
IB[k] = ibm(j - 1, k - 1)
|
||||
end
|
||||
end
|
||||
local inv = Xform.inverse(IB) or Xform.identity()
|
||||
local link = Xform.mul(meshWorld, inv)
|
||||
local cid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, {
|
||||
N("Version", "I", { 100 }),
|
||||
N("UserData", "SS", { "", "" }),
|
||||
N("Indexes", "", { arr("i", perJoint[j].idx) }),
|
||||
N("Weights", "", { arr("d", perJoint[j].w) }),
|
||||
N("Transform", "", { arr("d", meshWorld) }),
|
||||
N("TransformLink", "", { arr("d", link) }),
|
||||
}))
|
||||
OO(cid, sid)
|
||||
OO(jm, cid)
|
||||
pose(jm, link)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #poseNodes > 0 then
|
||||
local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) }
|
||||
for _, pn in poseNodes do
|
||||
table.insert(pch, pn)
|
||||
end
|
||||
add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ animations
|
||||
local tmin, tmax = math.huge, -math.huge
|
||||
local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean)
|
||||
local cnid = id()
|
||||
local p = {}
|
||||
for k, lab in labels do
|
||||
table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0))
|
||||
end
|
||||
add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) }))
|
||||
OO(cnid, layer)
|
||||
OP(cnid, target, prop)
|
||||
local ticks = table.create(#times, 0)
|
||||
for k, t in times do
|
||||
ticks[k] = math.floor(t * TICKS + 0.5)
|
||||
end
|
||||
for k, lab in labels do
|
||||
local cid = id()
|
||||
local df = buffer.create(32)
|
||||
buffer.writeu32(df, 8, 218434821)
|
||||
local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) }
|
||||
buffer.writef64(dfa.data, 16, buffer.readf32(df, 8))
|
||||
add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, {
|
||||
N("Default", "D", { comps[k][1] or 0 }),
|
||||
N("KeyVer", "I", { 4009 }),
|
||||
N("KeyTime", "", { arr("l", ticks) }),
|
||||
N("KeyValueFloat", "", { arr("f", comps[k]) }),
|
||||
N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }),
|
||||
N("KeyAttrDataFloat", "", { dfa }),
|
||||
N("KeyAttrRefCount", "", { arr("i", { #times }) }),
|
||||
}))
|
||||
OP(cid, cnid, "d|" .. lab)
|
||||
end
|
||||
end
|
||||
local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } }
|
||||
for ai, anim in scene.animations or {} do
|
||||
local stid, lid = id(), id()
|
||||
local astart, astop = math.huge, -math.huge
|
||||
local layerNodes = {}
|
||||
for _, ch in anim.channels do
|
||||
local mid = modelIds[ch.node]
|
||||
local IN = accessorReader(ch.input)
|
||||
local OUT = accessorReader(ch.output)
|
||||
local spec = PATH[ch.path]
|
||||
if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then
|
||||
local n = ch.input.count
|
||||
local times = table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
times[k + 1] = IN(k, 0)
|
||||
astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1])
|
||||
end
|
||||
local cubic = ch.interpolation == "CUBICSPLINE"
|
||||
local step = ch.interpolation == "STEP"
|
||||
if spec then
|
||||
local comps = spec[3]
|
||||
local function val(k: number, c: number): number
|
||||
local e = if cubic then k * 3 + 1 else k
|
||||
if e >= ch.output.count then
|
||||
return 0
|
||||
end
|
||||
return OUT(e, c)
|
||||
end
|
||||
local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0)
|
||||
local prev: { number }? = nil
|
||||
for k = 0, n - 1 do
|
||||
local v
|
||||
if comps == 4 then
|
||||
local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) }
|
||||
local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
|
||||
if ql > 0 then
|
||||
q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql }
|
||||
else
|
||||
q = { 0, 0, 0, 1 }
|
||||
end
|
||||
v = Xform.eulerXYZ(q)
|
||||
if prev then
|
||||
for a = 1, 3 do
|
||||
while v[a] - prev[a] > 180 do
|
||||
v[a] -= 360
|
||||
end
|
||||
while v[a] - prev[a] < -180 do
|
||||
v[a] += 360
|
||||
end
|
||||
end
|
||||
end
|
||||
prev = v
|
||||
else
|
||||
v = { val(k, 0), val(k, 1), val(k, 2) }
|
||||
end
|
||||
X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3]
|
||||
end
|
||||
table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step })
|
||||
else
|
||||
-- weights: one DeformPercent curve per blend shape channel of the node's mesh
|
||||
local nd = nodes[ch.node]
|
||||
local gc: any = geoChannels
|
||||
local chans = nd.mesh and gc[nd.mesh]
|
||||
if chans then
|
||||
local nt = #chans
|
||||
for t = 1, nt do
|
||||
local vals = table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1)
|
||||
vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0
|
||||
end
|
||||
table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if astart > astop then
|
||||
astart, astop = 0, 0
|
||||
end
|
||||
tmin, tmax = math.min(tmin, astart), math.max(tmax, astop)
|
||||
add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, {
|
||||
N("Properties70", "", {}, {
|
||||
Ptime("LocalStart", math.floor(astart * TICKS + 0.5)),
|
||||
Ptime("LocalStop", math.floor(astop * TICKS + 0.5)),
|
||||
Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)),
|
||||
Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)),
|
||||
}),
|
||||
}))
|
||||
add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) }))
|
||||
OO(lid, stid)
|
||||
for _, ln in layerNodes do
|
||||
curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8])
|
||||
end
|
||||
end
|
||||
if tmin > tmax then
|
||||
tmin, tmax = 0, 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ document
|
||||
local meta = scene.meta or {}
|
||||
local src = type(meta.source) == "table" and meta.source or {}
|
||||
local up = if meta.up == "z" then 2 else 1
|
||||
local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1
|
||||
if up == 2 then
|
||||
front, frontSign = 1, -1
|
||||
end
|
||||
if src.format == "fbx" and src.upAxis == up then
|
||||
upSign = src.upAxisSign or upSign
|
||||
front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign
|
||||
coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign
|
||||
end
|
||||
local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1
|
||||
local creator = opts and opts.creator or "formats-luau"
|
||||
local defs: { WNode } = { N("Version", "I", { 100 }) }
|
||||
local total = 1
|
||||
local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" }
|
||||
for _, c in CLASSES do
|
||||
total += counts[c] or 0
|
||||
end
|
||||
table.insert(defs, N("Count", "I", { total }))
|
||||
table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) }))
|
||||
for _, c in CLASSES do
|
||||
if counts[c] then
|
||||
table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) }))
|
||||
end
|
||||
end
|
||||
local docId = id()
|
||||
local root: WNode = { name = "", props = {}, children = {
|
||||
N("FBXHeaderExtension", "", {}, {
|
||||
N("FBXHeaderVersion", "I", { 1003 }),
|
||||
N("FBXVersion", "I", { opts and opts.version or 7400 }),
|
||||
N("CreationTimeStamp", "", {}, {
|
||||
N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }),
|
||||
N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }),
|
||||
}),
|
||||
N("Creator", "S", { creator }),
|
||||
}),
|
||||
N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }),
|
||||
N("CreationTime", "S", { "1970-01-01 10:00:00:000" }),
|
||||
N("Creator", "S", { creator }),
|
||||
N("GlobalSettings", "", {}, {
|
||||
N("Version", "I", { 1000 }),
|
||||
N("Properties70", "", {}, {
|
||||
Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign),
|
||||
Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign),
|
||||
Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale),
|
||||
P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0),
|
||||
P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"),
|
||||
Penum("TimeMode", 6),
|
||||
Penum("TimeProtocol", 2),
|
||||
Penum("SnapOnFrameMode", 0),
|
||||
Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)),
|
||||
Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)),
|
||||
Pdouble("CustomFrameRate", -1),
|
||||
}),
|
||||
}),
|
||||
N("Documents", "", {}, {
|
||||
N("Count", "I", { 1 }),
|
||||
N("Document", "LSS", { docId, "Scene", "Scene" }, {
|
||||
N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }),
|
||||
N("RootNode", "L", { 0 }),
|
||||
}),
|
||||
}),
|
||||
N("References", "", {}, {}),
|
||||
N("Definitions", "", {}, defs),
|
||||
N("Objects", "", {}, objects),
|
||||
N("Connections", "", {}, conns),
|
||||
N("Takes", "", {}, { N("Current", "S", { "" }) }),
|
||||
} }
|
||||
local _ = Err
|
||||
return root, nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,200 @@
|
||||
--!strict
|
||||
-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model
|
||||
-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six
|
||||
-- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse,
|
||||
-- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer).
|
||||
local Xform = {}
|
||||
|
||||
export type M4 = { number }
|
||||
|
||||
local rad = math.pi / 180
|
||||
|
||||
function Xform.identity(): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
function Xform.mul(a: M4, b: M4): M4
|
||||
local m = table.create(16, 0)
|
||||
for col = 0, 3 do
|
||||
for row = 0, 3 do
|
||||
m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4]
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
function Xform.translate(x: number, y: number, z: number): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
|
||||
end
|
||||
|
||||
function Xform.scale(x: number, y: number, z: number): M4
|
||||
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
local function rx(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
local function ry(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
local function rz(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ)
|
||||
local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" }
|
||||
function Xform.euler(x: number, y: number, z: number, order: number?): M4
|
||||
local o = ORDERS[order or 0] or "xyz"
|
||||
local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) }
|
||||
local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3)
|
||||
return Xform.mul(R[c], Xform.mul(R[b], R[a]))
|
||||
end
|
||||
|
||||
-- inverse of an affine matrix (general 3x3 part) | nil when singular
|
||||
function Xform.inverse(m: M4): M4?
|
||||
local a, b, c = m[1], m[5], m[9]
|
||||
local d, e, f = m[2], m[6], m[10]
|
||||
local g, h, i = m[3], m[7], m[11]
|
||||
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
|
||||
local det = a * A + b * B + c * C
|
||||
if det == 0 or det ~= det then
|
||||
return nil
|
||||
end
|
||||
local k = 1 / det
|
||||
local r = {
|
||||
A * k, B * k, C * k, 0,
|
||||
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
|
||||
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
local tx, ty, tz = m[13], m[14], m[15]
|
||||
r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz)
|
||||
r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz)
|
||||
r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz)
|
||||
return r
|
||||
end
|
||||
|
||||
-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers
|
||||
export type Props = {
|
||||
T: { number }, R: { number }, S: { number },
|
||||
Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number },
|
||||
order: number,
|
||||
}
|
||||
local function isZero(v: { number }): boolean
|
||||
return v[1] == 0 and v[2] == 0 and v[3] == 0
|
||||
end
|
||||
function Xform.localMatrix(p: Props): M4
|
||||
local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3])
|
||||
if not isZero(p.Rpre) then
|
||||
m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0))
|
||||
end
|
||||
m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order))
|
||||
if not isZero(p.Rpost) then
|
||||
local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0)
|
||||
-- the inverse of a rotation is its transpose
|
||||
local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 }
|
||||
m = Xform.mul(m, tr)
|
||||
end
|
||||
m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3]))
|
||||
m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3]))
|
||||
if not isZero(p.Sp) then
|
||||
m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3]))
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- quaternion (x, y, z, w) of a pure rotation matrix
|
||||
local function quat(m: M4): { number }
|
||||
local m00, m01, m02 = m[1], m[5], m[9]
|
||||
local m10, m11, m12 = m[2], m[6], m[10]
|
||||
local m20, m21, m22 = m[3], m[7], m[11]
|
||||
local tr = m00 + m11 + m22
|
||||
local x, y, z, w
|
||||
if tr > 0 then
|
||||
local s = math.sqrt(tr + 1) * 2
|
||||
w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
|
||||
elseif m00 > m11 and m00 > m22 then
|
||||
local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
|
||||
elseif m11 > m22 then
|
||||
local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
|
||||
else
|
||||
local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2
|
||||
w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
|
||||
end
|
||||
local n = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
if n == 0 or n ~= n then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
return { x / n, y / n, z / n, w / n }
|
||||
end
|
||||
Xform.quat = quat
|
||||
|
||||
-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale)
|
||||
function Xform.decompose(m: M4): ({ number }, { number }, { number })
|
||||
local t = { m[13], m[14], m[15] }
|
||||
local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3])
|
||||
local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7])
|
||||
local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
|
||||
local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
|
||||
if det < 0 then
|
||||
sx = -sx
|
||||
end
|
||||
local ix = if sx ~= 0 then 1 / sx else 0
|
||||
local iy = if sy ~= 0 then 1 / sy else 0
|
||||
local iz = if sz ~= 0 then 1 / sz else 0
|
||||
local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 }
|
||||
return t, quat(r), { sx, sy, sz }
|
||||
end
|
||||
|
||||
-- the rotation matrix of a quaternion
|
||||
function Xform.fromQuat(q: { number }): M4
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
return {
|
||||
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
|
||||
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
-- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion
|
||||
function Xform.eulerXYZ(q: { number }): { number }
|
||||
local m = Xform.fromQuat(q)
|
||||
-- m[3] = r20 = -sin(y)
|
||||
local sy = -m[3]
|
||||
sy = math.clamp(sy, -1, 1)
|
||||
local y = math.asin(sy)
|
||||
local x, z
|
||||
if math.abs(sy) < 0.9999999 then
|
||||
x = math.atan2(m[7], m[11])
|
||||
z = math.atan2(m[2], m[1])
|
||||
else
|
||||
x = math.atan2(-m[10], m[6])
|
||||
z = 0
|
||||
end
|
||||
return { x / rad, y / rad, z / rad }
|
||||
end
|
||||
|
||||
-- TRS -> matrix (glTF semantics)
|
||||
function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4
|
||||
local m = if r then Xform.fromQuat(r) else Xform.identity()
|
||||
if s then
|
||||
for k = 0, 2 do
|
||||
m[k * 4 + 1] *= s[k + 1]
|
||||
m[k * 4 + 2] *= s[k + 1]
|
||||
m[k * 4 + 3] *= s[k + 1]
|
||||
end
|
||||
end
|
||||
if t then
|
||||
m[13], m[14], m[15] = t[1], t[2], t[3]
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
return Xform
|
||||
@@ -0,0 +1,177 @@
|
||||
--!strict
|
||||
-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays
|
||||
-- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and
|
||||
-- assimp's FBX importer, and the FBX SDK's documentation of the transform model.
|
||||
-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl
|
||||
-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms
|
||||
-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals,
|
||||
-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference
|
||||
-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR
|
||||
-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins
|
||||
-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets
|
||||
-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and
|
||||
-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for
|
||||
-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated).
|
||||
-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives
|
||||
-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields),
|
||||
-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster +
|
||||
-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler
|
||||
-- XYZ curves). Readable by assimp, Blender and the FBX SDK.
|
||||
-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered
|
||||
-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Binary = require("@formats/model/fbx/Binary")
|
||||
local Ascii = require("@formats/model/fbx/Ascii")
|
||||
local Read = require("@formats/model/fbx/Read")
|
||||
local Write = require("@formats/model/fbx/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Fbx = {
|
||||
name = "fbx",
|
||||
category = "model",
|
||||
extensions = { "fbx" },
|
||||
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
|
||||
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention)
|
||||
sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only)
|
||||
resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by name
|
||||
maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30)
|
||||
maxVertices: number?, -- refuse more polygon corners (default 2^25)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
ascii: boolean?, -- write ASCII FBX (default binary)
|
||||
version: number?, -- 7400 (default) or 7500 (64-bit records)
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
embedTextures: boolean?, -- embed texture.data as Video content (default true)
|
||||
compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger)
|
||||
name: string?, -- the destination's file name (names textures without a uri)
|
||||
creator: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = Binary.MAGIC
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Fbx.sniff(r: Bytes.Reader): number
|
||||
if r:peek(21) == MAGIC then
|
||||
return 1
|
||||
end
|
||||
local head = r:peek(2048)
|
||||
if string.find(head, "FBXHeaderExtension:", 1, true) then
|
||||
return 0.95
|
||||
end
|
||||
if string.find(head, "^; FBX %d") then
|
||||
return 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetcher(opts: DecodeOptions?): Read.Fetch
|
||||
return function(uri: string): buffer?
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
end
|
||||
|
||||
local function toErr(msg: any, offset: number?): Err.Err
|
||||
local s = tostring(msg)
|
||||
local code = Err.CORRUPT
|
||||
if string.sub(s, 1, 12) == "unsupported:" then
|
||||
code, s = Err.UNSUPPORTED, string.sub(s, 13)
|
||||
elseif string.sub(s, 1, 6) == "limit:" then
|
||||
code, s = Err.LIMIT, string.sub(s, 7)
|
||||
elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then
|
||||
code = Err.TRUNCATED
|
||||
end
|
||||
return Err.new(code, s, offset)
|
||||
end
|
||||
|
||||
-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err.
|
||||
-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }.
|
||||
function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?)
|
||||
if r:peek(21) == MAGIC then
|
||||
local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts)
|
||||
if not root then
|
||||
return nil, toErr(version, off)
|
||||
end
|
||||
return root, version, true
|
||||
end
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
local root, version, off = Ascii.parse(text, opts)
|
||||
if not root then
|
||||
return nil, toErr(version, off and r.base + off)
|
||||
end
|
||||
if type(version) ~= "number" then
|
||||
return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion")
|
||||
end
|
||||
if version < 7000 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)")
|
||||
end
|
||||
return root, version, false
|
||||
end
|
||||
|
||||
function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local root, version, binary = Fbx.tree(r, opts)
|
||||
if not root then
|
||||
return nil, version
|
||||
end
|
||||
-- the scene builder is plain (not native) code: a bug there must not escape as an error
|
||||
local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, err
|
||||
end
|
||||
scene.meta.source.binary = binary
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Fbx.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
local version = opts and opts.version or 7400
|
||||
if version ~= 7400 and version ~= 7500 then
|
||||
return nil, Err.new(Err.ARG, "version must be 7400 or 7500")
|
||||
end
|
||||
local ok, root, err = pcall(Write.tree, scene, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root))
|
||||
end
|
||||
if not root then
|
||||
return nil, err
|
||||
end
|
||||
if opts and opts.ascii then
|
||||
return buffer.fromstring(Ascii.write(root, version)), nil
|
||||
end
|
||||
return Binary.write(root, version, not (opts and opts.compress == false)), nil
|
||||
end
|
||||
|
||||
return Fbx
|
||||
Reference in new issue
Block a user