model formats (3ds..lwo): comments are specs only

This commit is contained in:
4DBug committed 2026-11-01 01:53:16 -05:00
1 parent 0bd7b87d2b
commit 3bddd582bc
35 files changed
+233 -697

No files matched your search

+3 -9
View File
@@ -1,7 +1,6 @@
--!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.
-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays,
-- " in strings); integers longer than 15 digits stay strings so ids are exact.
local Base64 = require("@rosetta/core/Base64")
local Ascii = {}
@@ -15,7 +14,6 @@ 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
@@ -36,7 +34,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
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
@@ -61,7 +58,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
return nil, i
end
-- the values of one node (after the ':'), up to a new name, '{' or '}'
local function values(): ({ any }?, string?)
local props: { any } = {}
while true do
@@ -163,7 +159,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
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]
@@ -213,7 +208,6 @@ local function fmt(v: number): string
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 rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) }
local function node(nd: any, indent: string)
@@ -236,7 +230,7 @@ function Ascii.write(root: any, version: number?): string
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
-- 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
+5 -13
View File
@@ -1,10 +1,7 @@
--!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/compress/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).
-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by
-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L<hex>" so ids stay exact.
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Binary = {}
@@ -21,7 +18,7 @@ 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>"
-- signed 64-bit: a number when |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
@@ -40,7 +37,6 @@ Binary.i64 = i64
local ELEM: { [string]: number } = { 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
@@ -66,7 +62,6 @@ local function toF64(t: string, src: buffer, p: number, n: number): buffer
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
@@ -158,7 +153,6 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes:
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
@@ -230,10 +224,8 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes:
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).
-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per
-- property; arrays over 32 elements are zlib-compressed
export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
local function sizeHint(n: WNode): number
+15 -39
View File
@@ -1,15 +1,6 @@
--!strict
-- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections ->
-- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric
-- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in
-- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one
-- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the
-- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file
-- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind
-- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's
-- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or
-- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node
-- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults.
-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice,
-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
@@ -50,7 +41,7 @@ local function isArray(v: any): boolean
return type(v) == "table" and v.array == true
end
-- the array under n.<name> (or inline numbers: old ASCII files)
-- old ASCII files have inline numbers
local function array(n: Node?, name: string): Array?
local c = child(n, name)
if not c then
@@ -87,7 +78,7 @@ local function at(a: Array, i: number): number
return buffer.readf64(a.data, i * 8)
end
-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name
-- "Name\0\1Class" (binary) / "Class::Name" (ASCII)
local function objectName(s: any): string
if type(s) ~= "string" then
return ""
@@ -104,7 +95,7 @@ local function objectName(s: any): string
end
Read.objectName = objectName
-- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } }
-- Properties70: P: name, type, label, flags, values...
local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } }
local out = into or {}
local p70 = child(n, "Properties70")
@@ -155,7 +146,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
local maxVertices = opts and opts.maxVertices or 2 ^ 25
local scene = Types.Scene.new()
-- property templates (Definitions/ObjectType/PropertyTemplate) by object class
-- Definitions/ObjectType/PropertyTemplate
local templates: { [string]: { [string]: { any } } } = {}
local defs = child(root, "Definitions")
if defs then
@@ -169,7 +160,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
-- objects
local objects: { [any]: Obj } = {}
local order: { Obj } = {}
local objs = child(root, "Objects")
@@ -187,7 +177,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
-- connections: children (sources) of each parent, parents of each child, in file order
local kids: { [any]: { Conn } } = {}
local parents: { [any]: { Conn } } = {}
local conns = child(root, "Connections")
@@ -236,7 +225,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
return out
end
-- global settings
local gs = properties(child(root, "GlobalSettings"))
local upAxis = pnum(gs, "UpAxis", 1)
local unitScale = pnum(gs, "UnitScaleFactor", 1)
@@ -280,7 +268,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
return p
end
end
-- ASCII: base64 strings (possibly split into several)
-- ASCII: base64, possibly split into several strings
local parts = {}
for _, p in c.props do
if type(p) == "string" then
@@ -384,7 +372,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
if opacity < 1 then
m.alphaMode = "blend"
end
-- 3ds Max Physical / PBR materials
local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"]
if pbr then
local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|"
@@ -504,7 +491,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
nd.scale = s
end
nd.extras = { fbx = { type = o.sub, id = o.id } }
-- parent
local parentModel: Obj? = nil
for _, t2 in targets(o.id, "Model") do
parentModel = t2.obj
@@ -517,7 +503,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
table.insert(scene.roots, ni)
end
end
-- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed
-- break parent cycles: cut children already placed
do
local placed: { [number]: boolean } = {}
local function visit(i: number)
@@ -537,13 +523,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
for i in scene.nodes do
if not placed[i] then
-- part of a parent cycle: make it a root
table.insert(scene.roots, i)
visit(i)
end
end
end
-- world matrices (rest pose)
local worldM: { [number]: Mat4.M4 } = {}
local function world(i: number, parent: Mat4.M4)
worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity())
@@ -559,7 +543,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
-- ------------------------------------------------------------------------------------------ meshes
local corners = 0
-- per geometry: skin (control point -> { joint node, weight }) and blend shape channels
local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?)
local skin = sources(geo.id, "Deformer", "Skin")[1]
if not skin then
@@ -645,7 +628,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
local meshCache: { [string]: number } = {}
local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves)
local shapeChannels: { [number]: { Obj } } = {}
local nodeSkin: { [number]: number } = {}
local skinCache: { [any]: number } = {}
@@ -662,7 +645,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
if corners > maxVertices or ncp > maxVertices then
return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices")
end
-- polygons: corner -> control point, polygon of each corner, polygon starts
local cp = table.create(nc, 0)
local polyOf = table.create(nc, 0)
local starts: { number } = { 0 }
@@ -688,7 +670,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
np += 1
starts[np + 1] = nc
end
-- layer elements
type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number }
local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem }
local out: { Elem } = {}
@@ -711,7 +692,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end)
return out
end
-- the data element of a corner (c 0-based), or -1
local function lookup(e: Elem, c: number): number
local m = e.mapping
local i
@@ -742,7 +722,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4)
local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3)
local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1]
-- the normals index name varies ("NormalsIndex" / "NormalIndex")
-- "NormalsIndex" / "NormalIndex"
for _, e in normals do
if not e.index then
local c = nil
@@ -758,7 +738,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
-- polygons by material slot
local groups: { [number]: { number } } = {}
local slots: { number } = {}
for p = 0, np - 1 do
@@ -785,7 +764,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
table.sort(slots)
local perCp, skin = skinOf(geo)
local shapes = shapesOf(geo)
local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G)
local N3: Mat4.M4? = nil -- inverse transpose of G
if G then
local inv = Mat4.inverse(G)
if inv then
@@ -1004,12 +983,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
for _, o in models do
local ni = nodeOf[o.id]
local nd = scene.nodes[ni]
-- materials of the model, in connection order
local mats: { number } = {}
for _, m in sources(o.id, "Material") do
table.insert(mats, material(m))
end
-- geometric transform (not inherited: baked into the mesh)
-- geometric transform: not inherited, baked into the mesh
local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 })
local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 })
local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 })
@@ -1047,7 +1025,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
-- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis
-- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis
for _, a in sources(o.id, "NodeAttribute") do
local p = a.props
if a.sub == "Camera" then
@@ -1120,7 +1098,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
times[k + 1] = at(kt, k) / TICKS
values[k + 1] = at(kv, k)
end
-- per-key attribute flags (expanded through KeyAttrRefCount)
-- expanded through KeyAttrRefCount
local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat")
local flags = table.create(n, 4)
local slopes: { { number } } = {}
@@ -1223,11 +1201,10 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
for _, stack in order do
if stack.class == "AnimationStack" then
local anim: Types.Animation = { name = stack.name, channels = {} }
-- model id -> { T/R/S -> { axis -> curve } , defaults }
type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } }
local tracks: { [any]: Track } = {}
local trackOrder: { any } = {}
local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve
local morph: { [any]: Curve } = {}
local layers = sources(stack.id, "AnimationLayer")
for _, layer in layers do
for _, cn in sources(layer.id, "AnimationCurveNode") do
@@ -1328,7 +1305,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
-- morph target weights: every node whose mesh has an animated blend shape channel
if next(morph) then
for ni, nd in scene.nodes do
local chans = nd.mesh and shapeChannels[nd.mesh]
+6 -19
View File
@@ -1,11 +1,6 @@
--!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.
-- model/fbx/Write: Scene -> an FBX 7.4 node tree. 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); rotations as Euler XYZ degrees.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
@@ -28,7 +23,7 @@ local function arr(t: string, list: { number }): any
end
return { array = true, type = t, count = n, data = d }
end
-- P: name, type, label, flags, values (vt: one type character per value)
-- P: name, type, label, flags, values
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
@@ -64,7 +59,6 @@ local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) ->
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
@@ -235,7 +229,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
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,
@@ -260,7 +253,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
-- ------------------------------------------------------------------------------------------ models
local modelIds: { [number]: number } = {}
local skip: { [number]: boolean } = {}
local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there)
local attrHost: { [number]: number } = {}
local parentOf: { [number]: number } = {}
for i, nd in nodes do
for _, c in nd.children or {} do
@@ -283,7 +276,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
attrHost[i] = p
end
end
-- world matrices (rest pose) for clusters and the bind pose
local worldM: { [number]: Mat4.M4 } = {}
local visiting: { [number]: boolean } = {}
local function world(i: number): Mat4.M4
@@ -390,7 +382,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local euler = Mat4.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
@@ -430,9 +421,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
-- ------------------------------------------------------------------------------------------ geometry
local geoIds: { [number]: number } = {}
local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot
local geoSlots: { [number]: { number } } = {}
local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {}
local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation)
local geoChannels: any = {}
local geoCount: { [number]: number } = {}
local function geometry(mi: number): number?
if geoIds[mi] then
@@ -625,7 +616,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
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
@@ -717,7 +707,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
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
@@ -728,7 +717,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
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 = {} }
@@ -878,7 +866,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
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]
+2 -5
View File
@@ -1,7 +1,6 @@
--!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, with FBX's numbered Euler orders. The
-- matrix / quaternion arithmetic is codecs/model/Mat4.
-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"):
-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Xform = {}
@@ -12,7 +11,6 @@ function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4
return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz")
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 },
@@ -28,7 +26,6 @@ function Xform.localMatrix(p: Props): Mat4.M4
end
m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order))
if not isZero(p.Rpost) then
-- the inverse of a rotation is its transpose
m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0)))
end
m = Mat4.mul(m, Mat4.translation(-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]))
+15 -35
View File
@@ -1,24 +1,7 @@
--!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/compress/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).
-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs.
-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras.
-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,21 +24,21 @@ local Fbx = {
-- ------------------------------------------------------------------------------------------------ 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)
triangulate: boolean?, -- default true
flipV: boolean?, -- default true
sampleRate: number?, -- samples per second (default: the keys only)
resolve: ((uri: string) -> any)?, -- external texture files
files: { [string]: any }?,
maxBytes: number?, -- default 2^30 bytes of arrays
maxVertices: number?, -- default 2^25 polygon corners
}
export type EncodeOptions = {
ascii: boolean?, -- write ASCII FBX (default binary)
ascii: boolean?, -- 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)
flipV: boolean?, -- default true
embedTextures: boolean?, -- default true
compress: boolean?, -- arrays over 32 elements (default true)
name: string?,
creator: string?,
}
@@ -100,8 +83,6 @@ end
local toErr = Err.from
-- 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)
@@ -129,7 +110,6 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
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))