ws-3d3-b: model/x (DirectX .x read: text, binary, MSZIP tzip / bzip, 32 / 64-bit floats; frames, meshes with normals / uvs / colours, materials and textures, skins, animation sets); assimp's test models plus bin 0064 / tzip variants match assimp's counts, bones, animations and world bounds

This commit is contained in:
4DBug committed 2026-10-31 14:17:28 -05:00
1 parent 29be8113b4
commit 4f05c89f01
7 files changed
+1469

No files matched your search

+12
View File
@@ -494,6 +494,18 @@ local list: { Entry } = {
return require("@formats/model/vox")
end,
},
{
name = "x",
category = "model",
path = "model/x",
extensions = { "x" },
mime = { "model/x-directx", "text/x-directx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true },
load = function()
return require("@formats/model/x")
end,
},
{
name = "step",
category = "cad",
+560
View File
@@ -0,0 +1,560 @@
--!strict
-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is
-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding
-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same).
-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep
-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Rig = require("@formats/codecs/model/Rig")
local Parse = require("@formats/model/x/Parse")
local Build = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
type Node = Parse.Node
-- a cursor over an object's flattened values
type Vals = { v: { any }, i: number }
local function num(c: Vals): number
local x = c.v[c.i]
c.i += 1
if type(x) ~= "number" then
error("expected a number in the data", 0)
end
return x
end
local function str(c: Vals): string
local x = c.v[c.i]
c.i += 1
if type(x) ~= "string" then
error("expected a string in the data", 0)
end
return x
end
local function count(c: Vals, limit: number): number
local n = num(c)
if n < 0 or n ~= math.floor(n) or n > limit then
error("bad count " .. n, 0)
end
return n
end
-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1)
local function mirror(m: { number }): { number }
local o = table.clone(m)
for _, k in { 3, 7, 9, 10, 12, 15 } do
o[k] = -o[k]
end
return o
end
local function matrix(c: Vals): { number }
local m = table.create(16) :: { number }
for k = 1, 16 do
m[k] = num(c)
end
return mirror(m)
end
-- ------------------------------------------------------------------------------------------------ materials
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material
local c: Vals = { v = node.vals, i = 1 }
local mat = Scene.material(node.name)
local r, g, b, a = num(c), num(c), num(c), num(c)
local power = num(c)
local sr, sg, sb = num(c), num(c), num(c)
local er, eg, eb = num(c), num(c), num(c)
mat.baseColor = { r, g, b, a }
if a < 1 then
mat.alphaMode = "blend"
end
mat.metallic = 0
mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1)
mat.emissive = { er, eg, eb }
local textures = {}
for _, k in node.kids do
local lt = string.lower(k.type)
if lt == "texturefilename" or lt == "normalmapfilename" then
local path = k.vals[1]
if type(path) == "string" and path ~= "" then
path = string.gsub(path, "\\\\", "\\")
local uri = string.gsub(path, "\\", "/")
local ti = texCache[uri]
if not ti then
local base = string.match(uri, "([^/]+)$") or uri
local ext = string.lower(string.match(base, "%.(%w+)$") or "")
table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] })
ti = #scene.textures
texCache[uri] = ti
end
table.insert(textures, uri)
if lt == "normalmapfilename" then
mat.normalTexture = mat.normalTexture or { texture = ti }
else
mat.baseColorTexture = mat.baseColorTexture or { texture = ti }
end
end
end
end
mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } }
return mat
end
-- ------------------------------------------------------------------------------------------------ meshes
type Bones = { { name: string, matrix: { number } } }
type Ctx = {
scene: Types.Scene,
globalMats: { [string]: number },
texCache: { [string]: number },
nodeByName: { [string]: number },
pendingSkins: { { node: number, bones: Bones } },
maxVertices: number,
skippedFaces: number,
}
local function accessorF32(values: { number }, comps: number): Types.Accessor
local n = #values
local b = buffer.create(n * 4)
for i = 1, n do
writef32(b, (i - 1) * 4, values[i])
end
return Scene.accessor(b, "f32", comps, n // comps)
end
-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces)
local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
local scene = ctx.scene
local c: Vals = { v = m.vals, i = 1 }
local nv = count(c, ctx.maxVertices)
local pos = table.create(nv * 3) :: { number }
for k = 1, nv * 3 do
pos[k] = num(c)
end
local nf = count(c, ctx.maxVertices)
local faces = table.create(nf) :: { { number } }
local corners = 0
for f = 1, nf do
local n = count(c, ctx.maxVertices)
corners += n
if corners > ctx.maxVertices then
error("limit: more than " .. ctx.maxVertices .. " face corners", 0)
end
local face = table.create(n) :: { number }
for k = 1, n do
local idx = count(c, 2 ^ 32)
if idx >= nv then
error("face index " .. idx .. " out of range", 0)
end
face[k] = idx
end
faces[f] = face
end
-- the optional data objects
local normals: { number }? = nil
local nfaces: { { number } }? = nil
local uvSets: { { number } } = {}
local colors: { { number } } = {}
local faceMat: { number } = {}
local mats: { number } = {}
local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {}
for _, k in m.kids do
local kc: Vals = { v = k.vals, i = 1 }
if k.type == "MeshNormals" then
local nn = count(kc, ctx.maxVertices)
local nr = table.create(nn * 3) :: { number }
for q = 1, nn * 3 do
nr[q] = num(kc)
end
local nnf = count(kc, ctx.maxVertices)
local nfs = table.create(nnf) :: { { number } }
for f = 1, nnf do
local n = count(kc, ctx.maxVertices)
local face = table.create(n) :: { number }
for q = 1, n do
face[q] = count(kc, 2 ^ 32)
end
nfs[f] = face
end
normals, nfaces = nr, nfs
elseif k.type == "MeshTextureCoords" then
local n = count(kc, ctx.maxVertices)
local uv = table.create(n * 2) :: { number }
for q = 1, n * 2 do
uv[q] = num(kc)
end
if n == nv then
table.insert(uvSets, uv)
end
elseif k.type == "MeshVertexColors" then
local n = count(kc, ctx.maxVertices)
local col = table.create(nv * 4, 1) :: { number }
for _ = 1, n do
local idx = count(kc, 2 ^ 32)
local r, g, b, a = num(kc), num(kc), num(kc), num(kc)
if idx < nv then
col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a
end
end
table.insert(colors, col)
elseif k.type == "MeshMaterialList" then
count(kc, 2 ^ 20) -- material count (the objects below are authoritative)
local ni = count(kc, ctx.maxVertices)
for q = 1, ni do
faceMat[q] = count(kc, 2 ^ 20)
end
for _, mk in k.kids do
if mk.type == "@ref" then
table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0)
elseif mk.type == "Material" then
table.insert(scene.materials, material(scene, mk, ctx.texCache))
table.insert(mats, #scene.materials)
end
end
elseif k.type == "SkinWeights" then
local name = str(kc)
local n = count(kc, ctx.maxVertices)
local verts = table.create(n) :: { number }
for q = 1, n do
verts[q] = count(kc, 2 ^ 32)
end
local weights = table.create(n) :: { number }
for q = 1, n do
weights[q] = num(kc)
end
table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) })
end
end
-- material per face (a single index applies to every face)
local function matOf(f: number): number
local mi = if #faceMat == 1 then faceMat[1] else faceMat[f]
return if mi then mi + 1 else 1
end
-- unique vertices per (position, normal index)
local key: { [number]: number } = {}
local srcPos: { number } = {}
local srcNrm: { number } = {}
local groups: { [number]: { number } } = {}
local order: { number } = {}
local faceSizes: { [number]: { number } } = {}
local nNormals = if normals then #normals // 3 else 0
for f, face in faces do
local n = #face
if n < 3 then
ctx.skippedFaces += 1
else
local nface = nfaces and nfaces[f]
local vs = table.create(n) :: { number }
for k = 1, n do
local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept
local p = face[src]
local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1
local kk = p * (nNormals + 1) + q + 1
local v = key[kk]
if not v then
table.insert(srcPos, p)
table.insert(srcNrm, q)
v = #srcPos - 1
key[kk] = v
end
vs[k] = v
end
local mi = matOf(f)
local g = groups[mi]
if not g then
g = {}
groups[mi] = g
faceSizes[mi] = {}
table.insert(order, mi)
end
if triangulate then
for k = 2, n - 1 do
table.insert(g, vs[1])
table.insert(g, vs[k])
table.insert(g, vs[k + 1])
end
else
table.move(vs, 1, n, #g + 1, g)
table.insert(faceSizes[mi], n)
end
end
end
if #order == 0 then
return nil, nil
end
table.sort(order)
-- shared vertex attributes (one vertex buffer for every primitive of the mesh)
local nout = #srcPos
local P = table.create(nout * 3) :: { number }
for v = 1, nout do
local p = srcPos[v] * 3
P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3]
end
local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) }
if normals then
local N = table.create(nout * 3, 0) :: { number }
for v = 1, nout do
local q = srcNrm[v]
if q >= 0 then
N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3]
end
end
attributes.NORMAL = accessorF32(N, 3)
end
for s, uv in uvSets do
local U = table.create(nout * 2) :: { number }
for v = 1, nout do
local p = srcPos[v] * 2
U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2]
end
attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2)
end
for s, col in colors do
local C = table.create(nout * 4) :: { number }
for v = 1, nout do
local p = srcPos[v] * 4
C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4]
end
attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4)
end
if #bones > 0 then
local lists = table.create(nout) :: { { number } }
local byPos: { [number]: { number } } = {}
for j, bone in bones do
for q, vi in bone.verts do
local l = byPos[vi]
if not l then
l = {}
byPos[vi] = l
end
table.insert(l, j - 1)
table.insert(l, bone.weights[q] or 0)
end
end
for v = 1, nout do
lists[v] = byPos[srcPos[v]] or {}
end
attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists)
end
local skinBones: Bones? = nil
if #bones > 0 then
local list: Bones = {}
for _, bone in bones do
table.insert(list, { name = bone.name, matrix = bone.matrix })
end
skinBones = list
end
local prims: { Types.Primitive } = {}
for _, mi in order do
local idx = groups[mi]
local ib = buffer.create(#idx * 4)
for k, x in idx do
writeu32(ib, (k - 1) * 4, x)
end
local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" }
local mat = mats[mi]
prim.material = if mat and mat > 0 then mat else nil
if not triangulate then
prim.mode = "polygons"
local fs = faceSizes[mi]
local fb = buffer.create(#fs * 4)
for k, x in fs do
writeu32(fb, (k - 1) * 4, x)
end
prim.faces = Scene.accessor(fb, "u32", 1, #fs)
end
table.insert(prims, prim)
end
table.insert(scene.meshes, { name = m.name, primitives = prims })
return #scene.meshes, skinBones
end
-- ------------------------------------------------------------------------------------------------ frames
local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number)
if depth > 200 then
error("frames nested too deep", 0)
end
local scene = ctx.scene
local node: Types.Node = { name = f.name, children = {} }
table.insert(scene.nodes, node)
local ni = #scene.nodes
if f.name and ctx.nodeByName[f.name] == nil then
ctx.nodeByName[f.name] = ni
end
if parent then
table.insert(scene.nodes[parent].children, ni)
else
table.insert(scene.roots, ni)
end
local first = true
for _, k in f.kids do
if k.type == "FrameTransformMatrix" then
local m = matrix({ v = k.vals, i = 1 })
local t, r, s = Mat4.decomposeStrict(m)
if t and r and s then
node.translation, node.rotation, node.scale = t, r, s
else
node.matrix = m
end
elseif k.type == "Mesh" then
-- the first mesh on the frame's node, more as child nodes
local mi, bones = mesh(ctx, k, triangulate)
if mi then
local holder = ni
if first then
node.mesh = mi
first = false
else
table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi })
holder = #scene.nodes
table.insert(node.children, holder)
end
if bones then
table.insert(ctx.pendingSkins, { node = holder, bones = bones })
end
end
elseif k.type == "Frame" then
frame(ctx, k, ni, triangulate, depth + 1)
end
end
end
-- ------------------------------------------------------------------------------------------------ animations
local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel
return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" }
end
local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation?
local channels: { Types.Channel } = {}
for _, a in set.kids do
if a.type == "Animation" then
local target: string? = nil
for _, k in a.kids do
if k.type == "@ref" then
target = k.name
end
end
local node = target and ctx.nodeByName[target]
if node then
for _, k in a.kids do
if k.type == "AnimationKey" then
local c: Vals = { v = k.vals, i = 1 }
local kind = num(c)
local nk = count(c, ctx.maxVertices)
local times = table.create(nk) :: { number }
local T, R, S = {}, {}, {}
for q = 1, nk do
times[q] = num(c) / tps
local nvals = count(c, 16)
if kind == 0 and nvals == 4 then
local w, x, y, z = num(c), num(c), num(c), num(c)
-- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y
table.move({ x, y, -z, w }, 1, 4, #R + 1, R)
elseif (kind == 1 or kind == 2) and nvals == 3 then
local x, y, z = num(c), num(c), num(c)
if kind == 1 then
table.move({ x, y, z }, 1, 3, #S + 1, S)
else
table.move({ x, y, -z }, 1, 3, #T + 1, T)
end
elseif (kind == 3 or kind == 4) and nvals == 16 then
local t, r, s = Mat4.decompose(matrix(c))
table.move(t, 1, 3, #T + 1, T)
table.move(r, 1, 4, #R + 1, R)
table.move(s, 1, 3, #S + 1, S)
else
error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0)
end
end
if #T == nk * 3 and nk > 0 then
table.insert(channels, channel(times, T, 3, node, "translation"))
end
if #R == nk * 4 and nk > 0 then
table.insert(channels, channel(times, R, 4, node, "rotation"))
end
if #S == nk * 3 and nk > 0 then
table.insert(channels, channel(times, S, 3, node, "scale"))
end
end
end
end
end
end
if #channels == 0 then
return nil
end
return { name = set.name, channels = channels }
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?)
local triangulate = not (opts and opts.triangulate == false)
local scene = Scene.new()
scene.meta.up = "y"
local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 }
local tps = 4800
for _, k in root.kids do
if k.type == "Material" then
table.insert(scene.materials, material(scene, k, ctx.texCache))
if k.name then
ctx.globalMats[k.name] = #scene.materials
end
elseif k.type == "AnimTicksPerSecond" then
local v = k.vals[1]
if type(v) == "number" and v > 0 then
tps = v
end
end
end
for _, k in root.kids do
if k.type == "Frame" then
frame(ctx, k, nil, triangulate, 0)
elseif k.type == "Mesh" then
local mi, bones = mesh(ctx, k, triangulate)
table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi })
table.insert(scene.roots, #scene.nodes)
if bones then
table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones })
end
end
end
-- skins: bone names -> frames
for _, ps in ctx.pendingSkins do
local joints: { number } = {}
local ibm = buffer.create(#ps.bones * 64)
for j, bone in ps.bones do
local ni = ctx.nodeByName[bone.name]
if not ni then
-- a bone without a frame: an extra root node keeps the joint numbering
table.insert(scene.nodes, { name = bone.name, children = {} })
ni = #scene.nodes
table.insert(scene.roots, ni)
ctx.nodeByName[bone.name] = ni
end
joints[j] = ni
for k = 1, 16 do
writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k])
end
end
local acc = Scene.accessor(ibm, "f32", 16, #ps.bones)
acc.matrix = true
table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc })
scene.nodes[ps.node].skin = #scene.skins
end
for _, k in root.kids do
if k.type == "AnimationSet" then
local anim = animationSet(ctx, k, tps)
if anim then
table.insert(scene.animations, anim)
end
end
end
scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces }
return scene, nil
end
return Build
+306
View File
@@ -0,0 +1,306 @@
--!strict
-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the
-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and
-- binary tokens), checked against what assimp's XFileParser accepts (no code taken).
-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and
-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout),
-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped.
-- Text: ; and , separators, // and # comments, quoted strings, <guid>s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0).
-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and
-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message.
local Parse = {}
export type Node = { type: string, name: string?, vals: { any }, kids: { Node } }
local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring
-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }),
-- "punct", "eof"; err holds a message after a bad token
type Lexer = { next: () -> (string, any), err: string? }
local KEYWORDS: { [number]: string } = {
[0x1F] = "template",
[0x28] = "WORD",
[0x29] = "DWORD",
[0x2A] = "FLOAT",
[0x2B] = "DOUBLE",
[0x2C] = "CHAR",
[0x2D] = "UCHAR",
[0x2E] = "SWORD",
[0x2F] = "SDWORD",
[0x30] = "void",
[0x31] = "string",
[0x32] = "unicode",
[0x33] = "cstring",
[0x34] = "array",
}
-- ------------------------------------------------------------------------------------------------ text
local function textLexer(s: string): Lexer
local lex: Lexer = { next = nil :: any, err = nil }
local p = 1
local n = #s
lex.next = function(): (string, any)
while true do
local _, e = string.find(s, "^[%s,;]+", p)
if e then
p = e + 1
end
if p > n then
return "eof", nil
end
local c = string.byte(s, p)
if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or #
local nl = string.find(s, "[\r\n]", p)
p = if nl then nl + 1 else n + 1
else
break
end
end
local c = string.byte(s, p)
if c == 123 then
p += 1
return "{", nil
elseif c == 125 then
p += 1
return "}", nil
elseif c == 34 then
local q = string.find(s, '"', p + 1, true)
if not q then
lex.err = "unterminated string"
p = n + 1
return "eof", nil
end
local v = string.sub(s, p + 1, q - 1)
p = q + 1
return "str", v
elseif c == 60 then
local q = string.find(s, ">", p + 1, true) or n
local v = string.sub(s, p + 1, q - 1)
p = q + 1
return "guid", v
end
local _, e = string.find(s, '^[^%s,;{}"]+', p)
local tok = string.sub(s, p, e :: number)
p = (e :: number) + 1
if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
return "num", tonumber(tok) or 0
end
return "id", tok
end
return lex
end
-- ------------------------------------------------------------------------------------------------ binary
local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer
local lex: Lexer = { next = nil :: any, err = nil }
local p = from
local function fail(msg: string): (string, any)
lex.err = msg
p = limit
return "eof", nil
end
lex.next = function(): (string, any)
if p + 2 > limit then
return "eof", nil
end
local tok = readu16(b, p)
p += 2
if tok == 0x0A then
return "{", nil
elseif tok == 0x0B then
return "}", nil
elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token)
if p + 4 > limit then
return fail("truncated name")
end
local len = readu32(b, p)
p += 4
if len > limit - p then
return fail("truncated name")
end
local v = readstring(b, p, len)
p += len
if tok == 2 then
p = math.min(p + 2, limit)
return "str", v
end
return "id", v
elseif tok == 3 then
if p + 4 > limit then
return fail("truncated integer")
end
local v = readu32(b, p)
p += 4
return "num", v
elseif tok == 5 then
if p + 16 > limit then
return fail("truncated guid")
end
p += 16
return "guid", ""
elseif tok == 6 or tok == 7 then
if p + 4 > limit then
return fail("truncated list")
end
local count = readu32(b, p)
p += 4
local size = if tok == 6 then 4 else floatSize
if count > (limit - p) // size then
return fail("truncated list")
end
local out = table.create(count) :: { number }
if tok == 6 then
for i = 1, count do
out[i] = readu32(b, p)
p += 4
end
elseif size == 8 then
for i = 1, count do
out[i] = readf64(b, p)
p += 8
end
else
for i = 1, count do
out[i] = readf32(b, p)
p += 4
end
end
return "list", out
elseif tok >= 0x0C and tok <= 0x14 then
return "punct", nil
elseif KEYWORDS[tok] then
return "id", KEYWORDS[tok]
end
return fail(string.format("unknown binary token 0x%x", tok))
end
return lex
end
-- ------------------------------------------------------------------------------------------------ tree
local function tree(lex: Lexer, maxValues: number): (Node?, string?)
local queue: { { any } } = {}
local function take(): (string, any)
local q = table.remove(queue, 1)
if q then
return q[1], q[2]
end
return lex.next()
end
local function peek(k: number): string
while #queue < k do
local kind, v = lex.next()
table.insert(queue, { kind, v })
if kind == "eof" then
break
end
end
local q = queue[k]
return if q then q[1] else "eof"
end
local budget = maxValues
-- skips a template / unknown block whose "{" was just read
local function skipBlock(): string?
local depth = 1
while depth > 0 do
local kind = take()
if kind == "eof" then
return "unexpected end of file in a template"
elseif kind == "{" then
depth += 1
elseif kind == "}" then
depth -= 1
end
end
return nil
end
local body: (Node, number) -> string?
-- an object whose type token was read: [name] { ... }
local function object(parent: Node, typ: string, depth: number): string?
local name: string? = nil
local kind, v = take()
if kind ~= "{" then
name = if v ~= nil then tostring(v) else nil
kind = take()
if kind ~= "{" then
return "expected { after " .. typ
end
end
if typ == "template" then
return skipBlock()
end
local node: Node = { type = typ, name = name, vals = {}, kids = {} }
table.insert(parent.kids, node)
return body(node, depth + 1)
end
body = function(node: Node, depth: number): string?
if depth > 200 then
return "objects nested too deep"
end
local vals = node.vals
while true do
local kind, v = take()
if kind == "}" then
return nil
elseif kind == "eof" then
return if depth == 0 then nil else "unexpected end of file in " .. node.type
elseif kind == "num" or kind == "str" then
budget -= 1
if budget < 0 then
return "limit: more than " .. maxValues .. " values"
end
vals[#vals + 1] = v
elseif kind == "list" then
budget -= #v
if budget < 0 then
return "limit: more than " .. maxValues .. " values"
end
table.move(v, 1, #v, #vals + 1, vals)
elseif kind == "{" then
-- a reference: { name [guid] }
local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} }
while true do
local k2, v2 = take()
if k2 == "}" then
break
elseif k2 == "eof" then
return "unexpected end of file in a reference"
elseif (k2 == "id" or k2 == "num") and ref.name == nil then
ref.name = tostring(v2)
end
end
table.insert(node.kids, ref)
elseif kind == "id" then
local k1 = peek(1)
if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then
local err = object(node, v, depth)
if err then
return err
end
end
-- a lone identifier (an enum value): ignored
end
-- guid / punct: ignored
if lex.err then
return lex.err
end
end
end
local root: Node = { type = "@root", name = nil, vals = {}, kids = {} }
local err = body(root, 0)
if err then
return nil, err
end
if lex.err then
return nil, lex.err
end
return root, nil
end
-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message
function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?)
local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from))
return tree(lex, maxValues)
end
return Parse
+152
View File
@@ -0,0 +1,152 @@
--!strict
-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip",
-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format
-- specification and the standard templates, checked against assimp's X importer and test models.
-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per
-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal
-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global
-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture,
-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x),
-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four
-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale,
-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped.
-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does.
-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in
-- meta.source.skippedFaces).
-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key
-- interpolation options (keys are linear).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/compress/Deflate")
local Parse = require("@formats/model/x/Parse")
local Build = require("@formats/model/x/Build")
-- ------------------------------------------------------------------------------------------------ contract
local X = {
name = "x",
category = "model",
extensions = { "x" },
mime = { "model/x-directx", "text/x-directx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25)
maxValues: number?, -- refuse files with more numbers than this (default 2^27)
maxBytes: number?, -- refuse compressed files inflating to more (default 2^30)
}
-- ------------------------------------------------------------------------------------------------ constants
local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" }
local WINDOW = 32768
-- ------------------------------------------------------------------------------------------------ sniff
function X.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "xof " then
return 0
end
return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
-- MSZIP: a u32 total size (with the header), then blocks (u16 uncompressed size, u16 compressed size, "CK", deflate data); each block
-- may refer back into the previous block's output. That history is handed to the inflater as a stored block in
-- front of the compressed one (both start on a byte boundary), and cut off the output again.
local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?)
if p + 4 > limit then
return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p)
end
local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p)
end
p += 4
local out = buffer.create(total)
local o = 0
while p + 6 <= limit and o < total do
local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2)
if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then
return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p)
end
local data, dlen = p + 6, math.min(csize - 2, limit - p - 6)
local hist = math.min(o, WINDOW)
local src = buffer.create(5 + hist + dlen)
buffer.writeu8(src, 0, 0) -- BFINAL 0, stored
buffer.writeu16(src, 1, hist)
buffer.writeu16(src, 3, bit32.bxor(hist, 0xFFFF))
buffer.copy(src, 5, out, o - hist, hist)
buffer.copy(src, 5 + hist, b, data, dlen)
local inflated, err = Deflate.inflate(src)
if not inflated then
return nil, Err.new(err.code, "MSZIP block: " .. err.message, p)
end
local got = buffer.len(inflated) - hist
if got ~= usize or o + got > total then
return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p)
end
buffer.copy(out, o, inflated, hist, got)
o += got
p = data + csize - 2
end
if o < total then
return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p)
end
return out, nil
end
function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 16 then
return nil, Err.new(Err.TRUNCATED, "shorter than the header", base)
end
if buffer.readstring(b, base, 4) ~= "xof " then
return nil, Err.new(Err.CORRUPT, "no xof header", base)
end
local enc = buffer.readstring(b, base + 8, 4)
local kind = ENCODINGS[enc]
if not kind then
return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8)
end
local bits = buffer.readstring(b, base + 12, 4)
local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0
if floatSize == 0 then
return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12)
end
local data: buffer, from: number, to: number = b, base + 16, limit
if enc == "tzip" or enc == "bzip" then
local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30)
if not inflated then
return nil, err
end
data, from, to = inflated, 0, buffer.len(inflated)
end
local maxValues: number = opts and opts.maxValues or 2 ^ 27
local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root))
end
if not root then
return nil, Err.from(msg)
end
local ok2, scene, msg2 = pcall(Build.scene, root, opts)
if not ok2 then
return nil, Err.from(tostring(scene))
end
if not scene then
return nil, Err.from(msg2)
end
local src = scene.meta.source :: { [string]: any }
src.version = buffer.readstring(b, base + 4, 4)
src.encoding = kind
src.compressed = enc == "tzip" or enc == "bzip"
src.floatSize = floatSize * 8
return scene, nil
end
return X