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
This commit is contained in:
1 parent
646d18f056
commit
d4affd565e
14 files changed
+4403
No files matched your search
@@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
|
||||
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
|
||||
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
|
||||
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
|
||||
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,542 @@
|
||||
-- model/fbx tests: assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 - 7.7, embedded textures, skeletons,
|
||||
-- animation), Blender's exporter (materials, textures, colours, skin, shape keys, animation, camera, lights) and
|
||||
-- assimp's exporters (binary and ASCII), against assimp (meshes, polygons, vertices, world bounds, materials,
|
||||
-- animations, cameras, lights) and Blender's importer (meshes, polygons, materials, bones, shape keys, cameras,
|
||||
-- lights, images); round trips through our writer (binary and ASCII) and glTF sample models through FBX (world
|
||||
-- triangles, materials, textures, skins, morph targets, sampled animation, cameras, lights); assimp and Blender
|
||||
-- reading our files like the originals (fbx_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/fbx.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/fbx_cases")
|
||||
local Xcheck = require("@tests/gen/fbx_xcheck")
|
||||
local GltfCases = require("@tests/gen/fbx_gltf")
|
||||
|
||||
local t = T.suite("fbx")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Fbx.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Fbx.name, "fbx", "name")
|
||||
t:eq(Fbx.category, "model", "category")
|
||||
t:check(Fbx.caps.decode and Fbx.caps.encode, "contract")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
local function triArea(prim: any): number
|
||||
local pos, ind = prim.attributes.POSITION, prim.indices
|
||||
if not ind then
|
||||
return 0
|
||||
end
|
||||
local area = 0
|
||||
local function P(i: number, k: number): number
|
||||
return buffer.readf32(pos.data, (i * 3 + k) * 4)
|
||||
end
|
||||
for tri = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8)
|
||||
local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) }
|
||||
local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) }
|
||||
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
end
|
||||
return area
|
||||
end
|
||||
|
||||
-- assimp-like counts: placed primitives, polygons, corners
|
||||
local function counts(scene: any): (number, number, number)
|
||||
local prims, faces, verts = 0, 0, 0
|
||||
local seen = {}
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
if not seen[pl.primitive] then
|
||||
seen[pl.primitive] = true
|
||||
prims += 1
|
||||
faces += if pl.primitive.faces then pl.primitive.faces.count else pl.primitive.indices.count // 3
|
||||
verts += pl.primitive.attributes.POSITION.count
|
||||
end
|
||||
end
|
||||
return prims, faces, verts
|
||||
end
|
||||
|
||||
local function noMaterial(scene: any): boolean
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.material == nil then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function stats(scene: any): { [string]: number }
|
||||
local s = { meshNodes = 0, limbs = 0, shapes = 0, textures = #scene.textures, cameras = #scene.cameras, lights = #scene.lights }
|
||||
for _, n in scene.nodes do
|
||||
if n.mesh then
|
||||
s.meshNodes += 1
|
||||
end
|
||||
if n.extras and n.extras.fbx and n.extras.fbx.type == "LimbNode" then
|
||||
s.limbs += 1
|
||||
end
|
||||
end
|
||||
for _, m in scene.meshes do
|
||||
s.shapes += if m.weights then #m.weights else 0
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- world bounds, also under assimp's Z-up -> Y-up root conversion (x, z, -y)
|
||||
local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean
|
||||
local function eq(a: { number }, b: { number }, c: { number }, d: { number }): boolean
|
||||
for k = 1, 3 do
|
||||
if not near(a[k], c[k], eps) or not near(b[k], d[k], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if eq(lo, hi, want.min, want.max) then
|
||||
return true
|
||||
end
|
||||
return eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }, want.min, want.max)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reference files
|
||||
local checked = { assimp = 0, blender = 0, roundTrips = 0, failed = 0 }
|
||||
local scenes = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files, triangulate = false })
|
||||
local a = c.assimp
|
||||
if a.failed then
|
||||
t:check(scene == nil and err ~= nil, c.name .. ": assimp rejects it, so do we")
|
||||
checked.failed += 1
|
||||
else
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
scenes[i] = scene
|
||||
local prims, faces, verts = counts(scene)
|
||||
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, a.faces, c.name .. ": polygons (assimp)")
|
||||
t:eq(verts, a.vertices, c.name .. ": vertices (assimp)")
|
||||
t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)")
|
||||
t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)")
|
||||
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
|
||||
t:eq(#scene.materials + (if noMaterial(scene) then 1 else 0), a.materials, c.name .. ": materials (assimp, + its default)")
|
||||
if a.min then
|
||||
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
|
||||
t:check(lo and boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
|
||||
end
|
||||
checked.assimp += 1
|
||||
local b = c.blender
|
||||
if b and not b.failed then
|
||||
local s = stats(scene)
|
||||
t:eq(s.meshNodes, b.meshes, c.name .. ": mesh objects (Blender)")
|
||||
t:eq(faces, b.polygons, c.name .. ": polygons (Blender)")
|
||||
t:eq(#scene.materials, b.materials, c.name .. ": materials (Blender)")
|
||||
t:eq(s.limbs, b.bones, c.name .. ": bones (Blender)")
|
||||
t:eq(s.shapes, b.shapeKeys, c.name .. ": shape keys (Blender)")
|
||||
t:eq(s.cameras, b.cameras, c.name .. ": cameras (Blender)")
|
||||
t:eq(s.lights, b.lights, c.name .. ": lights (Blender)")
|
||||
t:eq(s.textures, b.images, c.name .. ": textures (Blender)")
|
||||
t:check((#scene.animations > 0) == (b.actions > 0), c.name .. ": animated (Blender)")
|
||||
checked.blender += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files: %d against assimp, %d against Blender, %d rejected by both", #Cases, checked.assimp, checked.blender, checked.failed)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips
|
||||
-- world triangles (area, count, bounds), materials, textures, skins, morph targets, animation samples, cameras, lights
|
||||
local function compare(a: any, b: any, label: string, eps: number)
|
||||
local ma, mb = MeshOps.merge(a), MeshOps.merge(b)
|
||||
local na = if ma and ma.indices then ma.indices.count // 3 else 0
|
||||
local nb = if mb and mb.indices then mb.indices.count // 3 else 0
|
||||
t:eq(nb, na, label .. ": triangles")
|
||||
if na > 0 and nb > 0 then
|
||||
t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb)))
|
||||
local la, ha = MeshOps.bounds(ma)
|
||||
local lb, hb = MeshOps.bounds(mb)
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps)
|
||||
end
|
||||
t:check(ok, label .. ": bounds")
|
||||
end
|
||||
t:eq(#b.materials, #a.materials, label .. ": materials")
|
||||
for k, m in a.materials do
|
||||
local m2 = b.materials[k]
|
||||
if m2 then
|
||||
local ok = true
|
||||
for q = 1, 4 do
|
||||
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
|
||||
end
|
||||
t:check(ok, label .. ": material " .. k .. " colour")
|
||||
t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture")
|
||||
end
|
||||
end
|
||||
t:eq(#b.textures, #a.textures, label .. ": textures")
|
||||
for k, tex in a.textures do
|
||||
local t2 = b.textures[k]
|
||||
if tex.data and t2 then
|
||||
t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), label .. ": texture " .. k .. " bytes")
|
||||
end
|
||||
end
|
||||
t:eq(#b.skins, #a.skins, label .. ": skins")
|
||||
for k, s in a.skins do
|
||||
local s2 = b.skins[k]
|
||||
if s2 then
|
||||
t:eq(#s2.joints, #s.joints, label .. ": skin joints")
|
||||
end
|
||||
end
|
||||
local function targets(s: any): number
|
||||
local n = 0
|
||||
for _, m in s.meshes do
|
||||
n += if m.weights then #m.weights else 0
|
||||
end
|
||||
return n
|
||||
end
|
||||
t:eq(targets(b), targets(a), label .. ": morph targets")
|
||||
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
|
||||
t:eq(#b.lights, #a.lights, label .. ": lights")
|
||||
-- cameras / lights: the same world placement (forward axis included)
|
||||
local function placed(s: any, field: string): { { number } }
|
||||
local out = {}
|
||||
local function visit(i: number, parent: { number }, seen: { [number]: boolean })
|
||||
if seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local n = s.nodes[i]
|
||||
local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(n))
|
||||
if n[field] then
|
||||
out[n[field]] = w
|
||||
end
|
||||
for _, c in n.children do
|
||||
visit(c, w, seen)
|
||||
end
|
||||
end
|
||||
local seen = {}
|
||||
for _, r in s.roots do
|
||||
visit(r, Types.Scene.IDENTITY, seen)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for _, field in { "camera", "light" } do
|
||||
local pa, pb = placed(a, field), placed(b, field)
|
||||
for k, w in pa do
|
||||
local w2 = pb[k]
|
||||
local ok = w2 ~= nil
|
||||
if w2 then
|
||||
for q = 1, 16 do
|
||||
ok = ok and math.abs(w[q] - w2[q]) <= eps * math.max(1, math.abs(w[q]))
|
||||
end
|
||||
end
|
||||
t:check(ok, label .. ": " .. field .. " " .. k .. " world matrix")
|
||||
end
|
||||
end
|
||||
-- animations: every channel of b sampled against a (LINEAR / STEP / CUBICSPLINE values at the keys of b)
|
||||
t:eq(#b.animations, #a.animations, label .. ": animations")
|
||||
local function evalCh(ch: any, time: number, comps: number): { number }
|
||||
local IN, OUT = Types.Scene.reader(ch.input) :: any, Types.Scene.reader(ch.output) :: any
|
||||
local n = ch.input.count
|
||||
local cubic = ch.interpolation == "CUBICSPLINE"
|
||||
local function v(k: number): { number }
|
||||
local e = if cubic then k * 3 + 1 else k
|
||||
local r = {}
|
||||
for q = 0, comps - 1 do
|
||||
r[q + 1] = OUT(e, q)
|
||||
end
|
||||
return r
|
||||
end
|
||||
if time <= IN(0, 0) then
|
||||
return v(0)
|
||||
end
|
||||
for k = 0, n - 2 do
|
||||
local t0, t1 = IN(k, 0), IN(k + 1, 0)
|
||||
if time <= t1 then
|
||||
if ch.interpolation == "STEP" or t1 <= t0 then
|
||||
return if time >= t1 then v(k + 1) else v(k)
|
||||
end
|
||||
local u = (time - t0) / (t1 - t0)
|
||||
local a0, a1 = v(k), v(k + 1)
|
||||
if comps == 4 and ch.path == "rotation" and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then
|
||||
a1 = { -a1[1], -a1[2], -a1[3], -a1[4] }
|
||||
end
|
||||
local r = {}
|
||||
for q = 1, comps do
|
||||
r[q] = a0[q] + (a1[q] - a0[q]) * u
|
||||
end
|
||||
return r
|
||||
end
|
||||
end
|
||||
return v(n - 1)
|
||||
end
|
||||
for ai, an in a.animations do
|
||||
local bn = b.animations[ai]
|
||||
if bn then
|
||||
-- channels by node name + path
|
||||
local byKey = {}
|
||||
for _, ch in an.channels do
|
||||
byKey[(a.nodes[ch.node].name or "") .. "/" .. ch.path] = ch
|
||||
end
|
||||
local bad, n = 0, 0
|
||||
for _, ch in bn.channels do
|
||||
local key = (b.nodes[ch.node].name or "") .. "/" .. ch.path
|
||||
local orig = byKey[key]
|
||||
local comps = if ch.path == "rotation" then 4 elseif ch.path == "weights" then ch.output.count // ch.input.count else 3
|
||||
if orig then
|
||||
local IN = Types.Scene.reader(ch.input) :: any
|
||||
for k = 0, ch.input.count - 1 do
|
||||
local time = IN(k, 0)
|
||||
local want = evalCh(orig, time, comps)
|
||||
local got = evalCh(ch, time, comps)
|
||||
local dot = 0
|
||||
for q = 1, comps do
|
||||
dot += want[q] * got[q]
|
||||
end
|
||||
local sign = if ch.path == "rotation" and dot < 0 then -1 else 1
|
||||
for q = 1, comps do
|
||||
if math.abs(got[q] * sign - want[q]) > 1e-3 * math.max(1, math.abs(want[q])) then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(bad == 0, string.format("%s: animation %d: %d of %d samples differ", label, ai, bad, n))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene = scenes[i]
|
||||
if scene then
|
||||
for _, ascii in { false, true } do
|
||||
local out, err = Fbx.encode(scene, { ascii = ascii })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out :: buffer, { triangulate = false })
|
||||
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
|
||||
if back then
|
||||
compare(scene, back, c.name .. (if ascii then " (ascii)" else ""), 1e-5)
|
||||
t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes")
|
||||
local p1, f1, v1 = counts(scene)
|
||||
local p2, f2, v2 = counts(back)
|
||||
t:check(p1 == p2 and f1 == f2 and v1 == v2, c.name .. ": polygons kept")
|
||||
end
|
||||
end
|
||||
checked.roundTrips += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- glTF sample models through FBX
|
||||
local ng = 0
|
||||
for _, g in GltfCases do
|
||||
local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
|
||||
t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr))
|
||||
if scene then
|
||||
local out, err = Fbx.encode(scene)
|
||||
t:check(out, g.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out :: buffer)
|
||||
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
|
||||
if back then
|
||||
-- glTF points / lines are not written
|
||||
local lines = false
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" then
|
||||
lines = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if not lines then
|
||||
compare(scene, back, "glTF " .. g.name, 2e-5)
|
||||
end
|
||||
ng += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d round trips of the reference files (binary + ASCII), %d glTF models through FBX", checked.roundTrips, ng)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ cross-check
|
||||
-- assimp and Blender read our files like the originals
|
||||
local nx = 0
|
||||
for _, x in Xcheck do
|
||||
local c = Cases[x.case]
|
||||
local a, ca = x.assimp, c.assimp
|
||||
local scene = scenes[x.case]
|
||||
if not ca.failed and scene then
|
||||
local _, faces = counts(scene)
|
||||
t:check(not a.failed, x.name .. ": assimp reads our file")
|
||||
t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file (" .. c.name .. ")")
|
||||
t:eq(a.faces, faces, x.name .. ": assimp polygons of our file (" .. c.name .. ")")
|
||||
t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file")
|
||||
t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file")
|
||||
t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file")
|
||||
t:eq(a.bones, ca.bones, x.name .. ": assimp bones of our file")
|
||||
if a.min and ca.min then
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4)
|
||||
end
|
||||
t:check(ok, x.name .. ": assimp world bounds of our file (" .. c.name .. ")")
|
||||
end
|
||||
local b, cb = x.blender, c.blender
|
||||
if b and cb and not cb.failed then
|
||||
t:check(not b.failed, x.name .. ": Blender reads our file: " .. tostring(b.failed))
|
||||
if not b.failed then
|
||||
for _, k in { "meshes", "polygons", "materials", "bones", "shapeKeys", "cameras", "lights", "images" } do
|
||||
t:eq(b[k], cb[k], x.name .. ": Blender " .. k .. " of our file (" .. c.name .. ")")
|
||||
end
|
||||
t:check((b.actions > 0) == (cb.actions > 0), x.name .. ": Blender actions of our file")
|
||||
end
|
||||
end
|
||||
nx += 1
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read back by assimp / Blender like the originals", nx)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ details
|
||||
do
|
||||
local byName = {}
|
||||
for i, c in Cases do
|
||||
byName[c.name] = scenes[i]
|
||||
end
|
||||
local cube = byName["blender/blender_cube.fbx"]
|
||||
if cube then
|
||||
local tex = cube.textures[1]
|
||||
t:check(tex and tex.data and tex.mime == "image/png", "Blender cube: embedded PNG kept encoded")
|
||||
local _, errs = F.model.loadTextures(cube)
|
||||
t:check(tex.image and tex.image.width == 8 and next(errs) == nil, "F.model.loadTextures decodes the embedded PNG")
|
||||
local red = cube.materials[1]
|
||||
t:check(red.name == "Red" and red.baseColorTexture and red.extras.fbx.shadingModel ~= nil, "material with a texture + Phong extras")
|
||||
local prim = cube.meshes[1].primitives[1]
|
||||
t:check(prim.attributes.COLOR_0 and prim.attributes.TEXCOORD_0 and prim.attributes.NORMAL, "colours, uvs, normals")
|
||||
t:eq(cube.meta.up, "y", "Blender writes Y up")
|
||||
t:check(near(cube.meta.unit, 0.01, 1e-9), "unit: centimetres")
|
||||
end
|
||||
local skin = byName["blender/blender_skin.fbx"]
|
||||
if skin then
|
||||
local m = skin.meshes[1]
|
||||
local p = m.primitives[1]
|
||||
t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "skin: joints and weights")
|
||||
t:check(m.weights and #m.weights == 1 and m.weights[1] >= 0 and m.weights[1] <= 1 and p.targets and p.targets[1].POSITION, "shape key: a morph target and its weight")
|
||||
local paths = {}
|
||||
for _, ch in skin.animations[1].channels do
|
||||
paths[ch.path] = true
|
||||
end
|
||||
t:check(paths.rotation and paths.weights, "animation: rotation and morph weights channels")
|
||||
-- weights sum to 1
|
||||
local W = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any
|
||||
local ok = true
|
||||
for v = 0, p.attributes.WEIGHTS_0.count - 1 do
|
||||
local s = W(v, 0) + W(v, 1) + W(v, 2) + W(v, 3)
|
||||
ok = ok and (math.abs(s - 1) < 1e-5 or s == 0)
|
||||
end
|
||||
t:check(ok, "skin weights normalized")
|
||||
end
|
||||
local cl = byName["blender/blender_camlight.fbx"]
|
||||
if cl then
|
||||
local types = {}
|
||||
for _, l in cl.lights do
|
||||
types[l.type] = true
|
||||
end
|
||||
t:check(types.point and types.directional and types.spot, "point, directional, spot lights")
|
||||
local cam = cl.cameras[1]
|
||||
-- Blender's 35 mm lens on a 36 mm sensor, 16:9 render
|
||||
t:check(cam.type == "perspective" and cam.yfov > 0.3 and cam.yfov < 1.2, "camera fov " .. cam.yfov)
|
||||
end
|
||||
local pbr = byName["assimp/maxPbrMaterial_metalRough.fbx"]
|
||||
if pbr then
|
||||
local m = pbr.materials[1]
|
||||
t:check(near(m.metallic, 0.25, 1e-6) and near(m.roughness, 0.5, 1e-6), "3ds Max PBR material: metalness / roughness")
|
||||
end
|
||||
local emb = byName["assimp/embedded_ascii/box.FBX"]
|
||||
if emb then
|
||||
t:check(emb.textures[1] and emb.textures[1].data and emb.meta.source.binary == false, "ASCII: base64 embedded texture")
|
||||
t:eq(emb.meta.up, "z", "3ds Max: Z up")
|
||||
end
|
||||
-- polygons kept / triangulated
|
||||
local box = decode(Cases[2].data)
|
||||
t:check(box.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
|
||||
-- through the api
|
||||
local s = F.load(Cases[2].data)
|
||||
t:check(s and s.kind == "scene" and s.meta.source.format == "fbx", "F.load detects binary FBX")
|
||||
local viaApi = F.save(s, nil, { format = "fbx" })
|
||||
t:check(viaApi and buffer.readstring(viaApi, 0, 18) == "Kaydara FBX Binary", "F.save format fbx")
|
||||
-- a 7.5 (64-bit records) file
|
||||
local v75 = Fbx.encode(s, { version = 7500 }) :: buffer
|
||||
local b75 = decode(v75)
|
||||
t:check(b75 and b75.meta.source.version == 7500 and #b75.meshes == #s.meshes, "7.5 records")
|
||||
-- a scene made by hand: a quad as polygons, written and read back as one polygon
|
||||
local p = Types.Scene.accessor(nil, "f32", 3, 4)
|
||||
for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do
|
||||
for k = 1, 3 do
|
||||
buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k])
|
||||
end
|
||||
end
|
||||
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
|
||||
buffer.writeu32(faces.data, 0, 4)
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, 4)
|
||||
for k = 0, 3 do
|
||||
buffer.writeu32(ind.data, k * 4, k)
|
||||
end
|
||||
local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad")
|
||||
local qb = decode(Fbx.encode(quad) :: buffer, { triangulate = false })
|
||||
t:check(qb and qb.meshes[1].primitives[1].faces.count == 1 and qb.meshes[1].primitives[1].indices.count == 4, "a quad stays one polygon")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("; FBX 6.1.0 project file\nFBXHeaderExtension: {\n\tFBXVersion: 6100\n}\n")
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "FBX 6: " .. tostring(e1))
|
||||
local bin = Cases[2].data
|
||||
local _, e2 = decode(string.sub(bin, 1, 200))
|
||||
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated: " .. tostring(e2))
|
||||
local _, e3 = decode(string.sub(bin, 1, 23) .. "\100\25\0\0" .. string.sub(bin, 28))
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "binary version 6500: " .. tostring(e3))
|
||||
local _, e4 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\nObjects: {")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "unterminated ASCII: " .. tostring(e4))
|
||||
local _, e5 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\n")
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "no Objects: " .. tostring(e5))
|
||||
local _, e6 = decode(bin, { maxBytes = 100 })
|
||||
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
|
||||
local _, e7 = Fbx.encode({} :: any)
|
||||
t:check(e7 and e7.code == Err.ARG, "encode junk")
|
||||
local _, e8 = Fbx.encode(Types.Scene.new(), { version = 6100 })
|
||||
t:check(e8 and e8.code == Err.ARG, "encode version 6100")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if #c.data < 60000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
local s = scenes[i]
|
||||
if s and #samples < 24 then
|
||||
local a = Fbx.encode(s, { ascii = true })
|
||||
if a and buffer.len(a) < 60000 then
|
||||
table.insert(samples, buffer.tostring(a))
|
||||
end
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = Fbx.decode(Bytes.reader(b))
|
||||
if s then
|
||||
Fbx.encode(s)
|
||||
MeshOps.merge(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 12, keepHeader = 27 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -451,6 +451,21 @@ do
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local fbx = assert(Fbx.encode(scene))
|
||||
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
|
||||
Fbx.decode(Bytes.reader(fbx))
|
||||
end)
|
||||
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
|
||||
Fbx.encode(scene)
|
||||
end)
|
||||
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
|
||||
Fbx.encode(scene, { compress = false })
|
||||
end)
|
||||
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
|
||||
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
|
||||
Fbx.decode(Bytes.reader(fbxa))
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# tools/fixtures/_fbx_blender: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <outdir>): builds
|
||||
# test scenes (textured cube with two materials, vertex colours and a child; a skinned, animated cylinder with a
|
||||
# shape key; a camera and three lights) and exports each to binary FBX 7.4.
|
||||
import bpy, sys, os, math
|
||||
out = sys.argv[sys.argv.index("--") + 1]
|
||||
def reset():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
def export(name, **kw):
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(out, name), **kw)
|
||||
|
||||
# 1. textured cube: material, uv, vertex colours, packed image
|
||||
reset()
|
||||
bpy.ops.mesh.primitive_cube_add(size=2, location=(1, 2, 3), rotation=(0.3, 0.2, 0.1))
|
||||
cube = bpy.context.object
|
||||
cube.name = "Cube"
|
||||
mesh = cube.data
|
||||
mesh.color_attributes.new("Col", "BYTE_COLOR", "CORNER")
|
||||
for i, d in enumerate(mesh.color_attributes["Col"].data):
|
||||
d.color = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6, 1)
|
||||
img = bpy.data.images.new("checker", 8, 8)
|
||||
img.pixels = [((x + y) % 2) * 1.0 if c < 3 else 1.0 for y in range(8) for x in range(8) for c in range(4)]
|
||||
img.filepath_raw = os.path.join(out, "checker.png")
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
img.pack()
|
||||
mat = bpy.data.materials.new("Red")
|
||||
mat.use_nodes = True
|
||||
bsdf = mat.node_tree.nodes["Principled BSDF"]
|
||||
bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1)
|
||||
bsdf.inputs["Roughness"].default_value = 0.4
|
||||
tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
|
||||
tex.image = img
|
||||
mat.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
|
||||
mesh.materials.append(mat)
|
||||
mat2 = bpy.data.materials.new("Blue")
|
||||
mat2.diffuse_color = (0.1, 0.1, 0.9, 1)
|
||||
mesh.materials.append(mat2)
|
||||
for i, p in enumerate(mesh.polygons):
|
||||
p.material_index = i % 2
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=6, location=(-3, 0, 0))
|
||||
bpy.context.object.name = "Sphere"
|
||||
bpy.context.object.parent = cube
|
||||
export("blender_cube.fbx", path_mode="COPY", embed_textures=True)
|
||||
|
||||
# 2. skinned, animated mesh with shape keys
|
||||
reset()
|
||||
bpy.ops.object.armature_add(location=(0, 0, 0))
|
||||
arm = bpy.context.object
|
||||
arm.name = "Rig"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
b0 = arm.data.edit_bones[0]
|
||||
b0.name = "root"
|
||||
b0.head, b0.tail = (0, 0, 0), (0, 0, 1)
|
||||
b1 = arm.data.edit_bones.new("tip")
|
||||
b1.head, b1.tail, b1.parent = (0, 0, 1), (0, 0, 2), b0
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=8, depth=2, radius=0.3, location=(0, 0, 1))
|
||||
cyl = bpy.context.object
|
||||
cyl.name = "Body"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
bpy.ops.mesh.subdivide(number_cuts=3)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
cyl.shape_key_add(name="Basis")
|
||||
sk = cyl.shape_key_add(name="Fat")
|
||||
for v in sk.data:
|
||||
v.co.x *= 1.5
|
||||
v.co.y *= 1.5
|
||||
sk.value = 0.25
|
||||
cyl.select_set(True)
|
||||
arm.select_set(True)
|
||||
bpy.context.view_layer.objects.active = arm
|
||||
bpy.ops.object.parent_set(type="ARMATURE_AUTO")
|
||||
bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 20
|
||||
bpy.ops.object.mode_set(mode="POSE")
|
||||
pb = arm.pose.bones["tip"]
|
||||
pb.rotation_mode = "XYZ"
|
||||
for f, a in ((1, 0), (10, 0.8), (20, 0)):
|
||||
pb.rotation_euler = (a, 0, 0)
|
||||
pb.keyframe_insert("rotation_euler", frame=f)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
for f, v in ((1, 0), (20, 1)):
|
||||
sk.value = v
|
||||
sk.keyframe_insert("value", frame=f)
|
||||
export("blender_skin.fbx", add_leaf_bones=False, bake_anim=True)
|
||||
|
||||
# 3. camera and lights
|
||||
reset()
|
||||
bpy.ops.object.camera_add(location=(0, -5, 1), rotation=(math.pi / 2, 0, 0))
|
||||
bpy.context.object.data.lens = 35
|
||||
for kind, loc in (("POINT", (1, 0, 3)), ("SUN", (0, 0, 5)), ("SPOT", (2, 2, 2))):
|
||||
bpy.ops.object.light_add(type=kind, location=loc)
|
||||
bpy.context.object.data.energy = 10
|
||||
bpy.ops.mesh.primitive_plane_add(size=4)
|
||||
export("blender_camlight.fbx")
|
||||
@@ -0,0 +1,31 @@
|
||||
# tools/fixtures/_fbx_blender_stats: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <json
|
||||
# list of paths>): imports each FBX with Blender's importer and prints one JSON line "STATS <list>" with per file
|
||||
# counts: mesh objects, polygons, vertices, materials, bones, actions, shape keys, cameras, lights, images; or
|
||||
# {"failed": message}.
|
||||
import bpy, sys, json
|
||||
paths = json.loads(sys.argv[sys.argv.index("--") + 1])
|
||||
res = []
|
||||
for p in paths:
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
try:
|
||||
r = bpy.ops.import_scene.fbx(filepath=p)
|
||||
if "FINISHED" not in r:
|
||||
raise RuntimeError(str(r))
|
||||
except Exception as e:
|
||||
res.append({"failed": str(e)[:200]})
|
||||
continue
|
||||
obs = bpy.context.scene.objects
|
||||
meshes = [o for o in obs if o.type == "MESH"]
|
||||
res.append({
|
||||
"meshes": len(meshes),
|
||||
"polygons": sum(len(o.data.polygons) for o in meshes),
|
||||
"vertices": sum(len(o.data.vertices) for o in meshes),
|
||||
"materials": len([m for m in bpy.data.materials if m.users > 0]),
|
||||
"bones": sum(len(o.data.bones) for o in obs if o.type == "ARMATURE"),
|
||||
"actions": len(bpy.data.actions),
|
||||
"shapeKeys": sum(len(o.data.shape_keys.key_blocks) - 1 for o in meshes if o.data.shape_keys),
|
||||
"cameras": len([o for o in obs if o.type == "CAMERA"]),
|
||||
"lights": len([o for o in obs if o.type == "LIGHT"]),
|
||||
"images": len([i for i in bpy.data.images if i.users > 0]),
|
||||
})
|
||||
print("STATS " + json.dumps(res))
|
||||
@@ -0,0 +1,38 @@
|
||||
-- tools/fixtures/_fbx_encode: run by tools/fixtures/fbx.py (luau CLI, repo root): decodes every FBX case with our
|
||||
-- reader and writes it back with our writer (binary 7.4, and ASCII for every third case), printing "<file>\t<hex>"
|
||||
-- lines for assimp and Blender to read back. Files: rt_<case>.fbx (binary), rt_<case>.a.fbx (ASCII).
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/fbx_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene, err = Fbx.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
|
||||
if scene then
|
||||
local bin, e2 = Fbx.encode(scene)
|
||||
if bin then
|
||||
print(string.format("rt_%d.fbx\t%s", i, hex(bin)))
|
||||
else
|
||||
print("encode failed " .. c.name .. ": " .. tostring(e2))
|
||||
end
|
||||
if i % 3 == 0 then
|
||||
local a = Fbx.encode(scene, { ascii = true })
|
||||
if a then
|
||||
print(string.format("rt_%d.a.fbx\t%s", i, hex(a)))
|
||||
end
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,179 @@
|
||||
# FBX fixtures (tools/fixtures.py): assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 / 7.5 / 7.7, embedded
|
||||
# textures, skeletons, animation; read from the nixpkgs assimp source, never committed), scenes exported by Blender
|
||||
# (tools/fixtures/_fbx_blender.py: materials, textures, vertex colours, skin, shape keys, animation, camera, lights)
|
||||
# and by assimp's FBX exporters (binary and ASCII), with reference values from assimp (`assimp info -r`: meshes,
|
||||
# faces, vertices, bounds, materials, animations, cameras, lights, bones) and Blender's importer
|
||||
# (tools/fixtures/_fbx_blender_stats.py). Then our encoder's output (tools/fixtures/_fbx_encode.luau) read back by
|
||||
# assimp and Blender.
|
||||
# tests/gen/fbx_cases.luau { name, data, files = { name -> bytes }, assimp, blender? }
|
||||
# tests/gen/fbx_xcheck.luau { name, case, assimp, blender? }
|
||||
# tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files }
|
||||
import importlib.util, json, os, shutil, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/Deflate", "tools/fixtures/_model_ref.py",
|
||||
"tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_extra(ctx, path):
|
||||
import re
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {}
|
||||
out = {}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones", "Animation Channels"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
out[label.lower().replace(" ", "_")] = int(m.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def ptv_bounds(ctx, path, tmp):
|
||||
# world-space bounds: assimp's PreTransformVertices output (`assimp info` multiplies node matrices in the wrong
|
||||
# order for nested nodes, so its own bounds are not used)
|
||||
out = os.path.join(tmp, "ptv.obj")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
with open(out) as f:
|
||||
for line in f:
|
||||
if line.startswith("v "):
|
||||
v = [float(x) for x in line.split()[1:4]]
|
||||
lo = [min(a, b) for a, b in zip(lo, v)]
|
||||
hi = [max(a, b) for a, b in zip(hi, v)]
|
||||
os.remove(out)
|
||||
return {"min": lo, "max": hi} if lo[0] <= hi[0] else {}
|
||||
except (subprocess.CalledProcessError, OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def blender():
|
||||
return shutil.which("blender")
|
||||
|
||||
|
||||
def blender_stats(ctx, paths):
|
||||
exe = blender()
|
||||
if not exe or not paths:
|
||||
return [None] * len(paths)
|
||||
script = os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender_stats.py")
|
||||
try:
|
||||
res = subprocess.run([exe, "-b", "--factory-startup", "--python", script, "--", json.dumps(paths)],
|
||||
capture_output=True, timeout=900)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
return [None] * len(paths)
|
||||
for line in res.stdout.decode("utf-8", "replace").split("\n"):
|
||||
if line.startswith("STATS "):
|
||||
return json.loads(line[6:])
|
||||
return [None] * len(paths)
|
||||
|
||||
|
||||
def assimp_src(ctx):
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
# assimp's test models (read only)
|
||||
src = os.path.join(assimp_src(ctx), "test", "models", "FBX")
|
||||
for root, _, files in sorted(os.walk(src)):
|
||||
for f in sorted(files):
|
||||
if f.lower().endswith(".fbx"):
|
||||
p = os.path.join(root, f)
|
||||
cases.append({"name": "assimp/" + os.path.relpath(p, src), "path": p, "files": {}})
|
||||
# Blender's exporter
|
||||
exe = blender()
|
||||
if exe:
|
||||
bdir = os.path.join(tmp, "blender")
|
||||
os.makedirs(bdir)
|
||||
subprocess.run([exe, "-b", "--factory-startup", "--python", os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender.py"), "--", bdir],
|
||||
capture_output=True, check=True, timeout=600)
|
||||
for f in sorted(os.listdir(bdir)):
|
||||
if f.endswith(".fbx"):
|
||||
cases.append({"name": "blender/" + f, "path": os.path.join(bdir, f), "files": {}})
|
||||
# assimp's exporters: binary and ASCII, from a few glTF sample models (skin, morph, textures) and a PLY torus
|
||||
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"),
|
||||
("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), ("Cameras", "glTF", "Cameras.gltf"),
|
||||
("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb")):
|
||||
inp = os.path.join(gl, model, variant, main)
|
||||
if not os.path.exists(inp):
|
||||
continue
|
||||
for fmt in ("fbx", "fbxa"):
|
||||
out = os.path.join(tmp, "%s_%s.fbx" % (model, fmt))
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", inp, out, "-f" + fmt])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
cases.append({"name": "assimp-export/%s.%s" % (model, fmt), "path": out, "files": {}})
|
||||
paths = [c["path"] for c in cases]
|
||||
infos = M.assimp_info(ctx, paths, raw=True)
|
||||
bl = blender_stats(ctx, paths)
|
||||
for c, a, b in zip(cases, infos, bl):
|
||||
a.update(assimp_extra(ctx, c["path"]))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, c["path"], tmp))
|
||||
c["assimp"] = a
|
||||
if b:
|
||||
c["blender"] = b
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
# sibling files a model refers to (textures next to it)
|
||||
d = os.path.dirname(c["path"])
|
||||
for f in sorted(os.listdir(d)):
|
||||
if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga")) and os.path.getsize(os.path.join(d, f)) < 300000:
|
||||
c["files"][f] = open(os.path.join(d, f), "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("fbx_cases", cases)
|
||||
|
||||
# glTF sample models for the writer round trips (glTF -> FBX -> Scene, compared with the glTF scene)
|
||||
picks = []
|
||||
for model in ("Box", "BoxTextured", "BoxVertexColors", "SimpleSkin", "RiggedSimple", "SimpleMorph", "AnimatedMorphCube",
|
||||
"Cameras", "MultiUVTest", "InterpolationTest", "NegativeScaleTest", "PointLightIntensityTest",
|
||||
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes", "SimpleMeshes"):
|
||||
d0 = os.path.join(gl, model)
|
||||
if not os.path.isdir(d0):
|
||||
continue
|
||||
for variant in sorted(os.listdir(d0)):
|
||||
d = os.path.join(d0, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
|
||||
if mains:
|
||||
picks.append({"name": model + "/" + variant, "data": open(os.path.join(d, mains[0]), "rb").read(),
|
||||
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
|
||||
break
|
||||
ctx.emit("fbx_gltf", picks)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_fbx_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(n for n in ours if n.endswith(".fbx"))
|
||||
for name, data in ours.items():
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
xpaths = [os.path.join(xtmp, n) for n in names]
|
||||
xi = M.assimp_info(ctx, xpaths, raw=True)
|
||||
bin_paths = [p for p in xpaths if not p.endswith(".a.fbx")] # Blender reads binary FBX only
|
||||
xb_bin = dict(zip(bin_paths, blender_stats(ctx, bin_paths)))
|
||||
xb = [xb_bin.get(p) for p in xpaths]
|
||||
out = []
|
||||
for n, p, a, b in zip(names, xpaths, xi, xb):
|
||||
a.update(assimp_extra(ctx, p))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, p, xtmp))
|
||||
e = {"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a}
|
||||
if b:
|
||||
e["blender"] = b
|
||||
out.append(e)
|
||||
ctx.emit("fbx_xcheck", out)
|
||||
Reference in new issue
Block a user