178 lines
8.2 KiB
Luau
178 lines
8.2 KiB
Luau
--!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; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not 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 :: { [string]: any }).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
|