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

+1
View File
@@ -45,6 +45,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
| model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` |
| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
+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
+312
View File
@@ -0,0 +1,312 @@
-- model/x tests: assimp's DirectX test models (text, binary 32-bit, MSZIP-compressed binary) and variants made by
-- tools/fixtures/x.py (binary with 64-bit floats, MSZIP-compressed text), against assimp (meshes per material, faces,
-- corners, materials, animations, bones, world bounds); frames, materials and textures, vertex colours, skins
-- (influences, inverse bind matrices against the bind pose), animation keys (the rotation convention against the
-- bind pose); an inline text file; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x.py.
local T = require("@tests/T")
local X = require("@formats/model/x")
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/x_cases")
local t = T.suite("x")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return X.decode(Bytes.reader(b), opts)
end
t:eq(X.name, "x", "name")
t:eq(X.category, "model", "category")
t:check(X.caps.decode and not X.caps.encode, "caps")
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
-- assimp's counts: meshes (one per material), faces, corners, bones (joints with weight in each mesh)
local function counts(scene: any): (number, number, number, number)
local meshes, faces, corners, bones = 0, 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
meshes += 1
corners += p.indices.count
faces += if p.mode == "polygons" then p.faces.count else p.indices.count // 3
local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0
if J and W then
local used = {}
local gj, gw = assert(Types.Scene.reader(J)), assert(Types.Scene.reader(W))
for k = 0, p.indices.count - 1 do
local v = buffer.readu32(p.indices.data, k * 4)
for c = 0, 3 do
if gw(v, c) > 0 then
used[gj(v, c)] = true
end
end
end
for _ in used do
bones += 1
end
end
end
end
return meshes, faces, corners, bones
end
local function bounds(scene: any): ({ number }?, { number }?)
local merged = MeshOps.merge(scene)
if not merged then
return nil, nil
end
return MeshOps.bounds(merged)
end
local function boundsMatch(lo: { number }?, hi: { number }?, a: any, eps: number): boolean
if not lo or not hi then
return false
end
for k = 1, 3 do
if not near(lo[k], a.min[k], eps) or not near(hi[k], a.max[k], eps) then
return false
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ assimp
local scenes, byName = {}, {}
local checked = 0
for i, c in Cases do
byName[c.name] = c
local a = c.assimp
local scene, err = decode(c.data, { triangulate = false })
if a.failed then
t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[c.name] = scene
local meshes, faces, corners, bones = counts(scene)
t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces + scene.meta.source.skippedFaces, a.faces, c.name .. ": faces (assimp)")
if scene.meta.source.skippedFaces == 0 then
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
end
t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp, its default when none)")
t:eq(#scene.animations, a.animations or 0, c.name .. ": animations (assimp)")
t:eq(bones, a.bones or 0, c.name .. ": bones (assimp)")
if a.min then
local lo, hi = bounds(scene)
t:check(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 += 1
end
end
t:note("%d files checked against assimp", checked)
-- variants decode like their originals
for _, c in Cases do
if c.of then
local a, b = scenes[c.name], scenes[c.of]
if a and b then
local m1, f1, c1 = counts(a)
local m2, f2, c2 = counts(b)
t:check(m1 == m2 and f1 == f2 and c1 == c2, c.name .. ": same counts as " .. c.of)
local la, ha = bounds(a)
local lb, hb = bounds(b)
t:check(la and lb and boundsMatch(la, ha, { min = lb, max = hb }, 1e-5), c.name .. ": same bounds as " .. c.of)
t:eq(#a.animations, #b.animations, c.name .. ": same animations")
end
end
end
-- ------------------------------------------------------------------------------------------------ details
do
local s = scenes["models/kwxport_test_cubewithvcolors.x"]
local p = s.meshes[1].primitives[1]
t:check(p.attributes.COLOR_0 and p.attributes.COLOR_0.components == 4, "vertex colours -> COLOR_0")
t:eq(s.meta.source.encoding, "text", "text encoding")
local b = scenes["models/test_cube_binary.x"]
t:eq(b.meta.source.encoding, "binary", "binary encoding")
local z = scenes["models/test_cube_compressed.x"]
t:check(z.meta.source.compressed, "bzip")
local v = scenes["variant/test_cube_text.bin64.x"]
t:eq(v.meta.source.floatSize, 64, "64-bit floats")
end
do
-- textures: uri names, TEXCOORD_0
local s = scenes["models/test.x"]
local any = false
for _, m in s.materials do
if m.baseColorTexture then
local tex = s.textures[m.baseColorTexture.texture]
any = any or (type(tex.uri) == "string" and #tex.uri > 0)
end
end
t:check(any, "test.x: a texture file name")
t:check(s.meshes[1].primitives[1].attributes.TEXCOORD_0, "test.x: TEXCOORD_0")
end
do
-- skins: the inverse bind matrix of each joint times the joint's world bind matrix is about the same for all
-- joints (the mesh node's world matrix): checks the matrix layout and the handedness conversion together
local checkedSkins, consistent = 0, 0
for name, s in scenes do
for _, node in s.nodes do
if node.skin then
local skin = s.skins[node.skin]
local world = {}
local function worldOf(i: number): { number }
if world[i] then
return world[i]
end
local m = Types.Scene.nodeMatrix(s.nodes[i])
for pi, pn in s.nodes do
if table.find(pn.children, i) then
m = Types.Scene.mul(worldOf(pi), m)
break
end
end
world[i] = m
return m
end
local get = assert(Types.Scene.reader(skin.inverseBindMatrices))
local ref: { number }? = nil
local ok, total = 0, 0
for j, joint in skin.joints do
local inv = {}
for k = 1, 16 do
inv[k] = get(j - 1, k - 1)
end
local m = Types.Scene.mul(worldOf(joint), inv)
total += 1
if not ref then
ref = m
ok += 1
else
local same = true
for k = 1, 16 do
same = same and math.abs(m[k] - (ref :: any)[k]) < 1e-2 * math.max(1, math.abs(m[k]))
end
ok += if same then 1 else 0
end
end
t:note("%s: skin %d: bind pose consistent for %d / %d joints", name, node.skin, ok, total)
checkedSkins += 1
consistent += if ok >= total * 0.9 then 1 else 0
end
end
end
-- (anim_test.x's frames are not in the bind pose)
t:check(checkedSkins >= 4 and consistent >= checkedSkins * 0.7, string.format("skins consistent with the frames (%d / %d)", consistent, checkedSkins))
end
do
-- the rotation key convention: an animation's first rotation key mostly equals the bone's bind rotation
local same, total = 0, 0
for _, s in scenes do
for _, anim in s.animations do
for _, ch in anim.channels do
if ch.path == "rotation" then
local node = s.nodes[ch.node]
local r = node.rotation
if r then
local get = assert(Types.Scene.reader(ch.output))
local dot = 0
for k = 0, 3 do
dot += get(0, k) * r[k + 1]
end
total += 1
same += if math.abs(dot) > 0.999 then 1 else 0
end
end
end
end
end
t:check(total > 0 and same >= total * 0.5, string.format("first rotation keys match the bind pose (%d / %d)", same, total))
end
-- ------------------------------------------------------------------------------------------------ inline file
local CUBE = [[xof 0303txt 0032
// a quad and a triangle, two materials, one animated frame
Material Red { 1.0; 0.0; 0.0; 1.0;; 10.0; 0.5; 0.5; 0.5;; 0.0; 0.0; 0.0;; TextureFilename { "tex\\red.png"; } }
AnimTicksPerSecond { 100; }
Frame Root {
FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 1,2,3,1;; }
Mesh Shape {
5;
0;0;0;, 1;0;0;, 1;1;0;, 0;1;0;, 2;0;0;;
2;
4;0,1,2,3;,
3;1,4,2;;
MeshMaterialList { 2; 2; 0, 1;; { Red } Material Blue { 0;0;1;0.5;; 1; 0;0;0;; 0;0;0;; } }
MeshNormals { 1; 0;0;-1;; 2; 4;0,0,0,0;, 3;0,0,0;; }
MeshTextureCoords { 5; 0;0;, 1;0;, 1;1;, 0;1;, 0.5;0.5;; }
}
}
AnimationSet Move {
Animation { { Root } AnimationKey { 2; 2; 0; 3; 1;2;3;;, 100; 3; 1;2;5;;; } }
}
]]
do
local s, err = decode(CUBE, { triangulate = false })
t:check(s, "inline: " .. tostring(err))
t:eq(#s.nodes, 1, "inline: one frame")
local root = s.nodes[1]
t:check(root.translation and root.translation[1] == 1 and root.translation[3] == -3, "inline: translation, z negated")
t:eq(#s.materials, 2, "inline: global + inline material")
t:eq(s.materials[1].name, "Red", "inline: material name")
t:eq(s.textures[1].uri, "tex/red.png", "inline: texture uri (backslash -> slash)")
t:eq(s.materials[2].alphaMode, "blend", "inline: alpha < 1 -> blend")
local prims = s.meshes[1].primitives
t:eq(#prims, 2, "inline: one primitive per material")
t:eq(prims[1].material, 1, "inline: first face -> Red (referenced)")
t:eq(prims[2].material, 2, "inline: second face -> Blue")
t:eq(prims[1].faces.count, 1, "inline: the quad kept")
local N = assert(Types.Scene.reader(prims[1].attributes.NORMAL))
t:eq(N(0, 2), 1, "inline: normal z negated")
local anim = s.animations[1]
t:eq(anim.name, "Move", "inline: animation name")
local ch = anim.channels[1]
t:eq(ch.path, "translation", "inline: position key")
local ti, to = assert(Types.Scene.reader(ch.input)), assert(Types.Scene.reader(ch.output))
t:eq(ti(1, 0), 1, "inline: ticks -> seconds")
t:eq(to(1, 2), -5, "inline: key z negated")
local tri = decode(CUBE)
t:eq(tri.meshes[1].primitives[1].indices.count, 6, "inline: quad fan-triangulated")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("xof 0303txt 00")
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local _, e2 = decode("xof 0303zzz 0032")
t:check(e2 and e2.code == Err.UNSUPPORTED, "encoding: " .. tostring(e2))
local _, e3 = decode("xof 0303txt 0016 Frame {}")
t:check(e3 and e3.code == Err.CORRUPT, "float size: " .. tostring(e3))
local _, e4 = decode("xof 0303txt 0032 Frame A { Mesh { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3; 0,1,7;; } }")
t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4))
local _, e5 = decode("xof 0303txt 0032 Frame A { ")
t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5))
local _, e6 = decode(CUBE, { maxValues = 10 })
t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6))
t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = { CUBE }
for _, c in Cases do
if #c.data < 12000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = X.decode(Bytes.reader(b), { triangulate = false })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+126
View File
@@ -0,0 +1,126 @@
# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary;
# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the
# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with
# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners,
# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too.
# tests/gen/x_cases.luau { name, data, assimp = { ... } }
import importlib.util, os, re, struct, zlib
INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+')
def to_binary64(text):
"""a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)"""
body = text[16:]
out = bytearray(b"xof 0303bin 0064")
toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))]
i, nums = 0, []
def flush():
while nums:
isf = nums[0][0]
run = []
while nums and nums[0][0] == isf:
run.append(nums.pop(0)[1])
if isf:
out.extend(struct.pack("<HI", 7, len(run)) + b"".join(struct.pack("<d", v) for v in run))
else:
out.extend(struct.pack("<HI", 6, len(run)) + b"".join(struct.pack("<I", int(v) & 0xFFFFFFFF) for v in run))
while i < len(toks):
t = toks[i]
if t == b"template":
flush()
depth = 0
while i < len(toks):
if toks[i] == b"{":
depth += 1
elif toks[i] == b"}":
depth -= 1
if depth == 0:
break
i += 1
elif t in (b";", b","):
pass
elif t[:1] in b"0123456789-+.":
try:
v = float(t)
except ValueError:
v = 0.0
nums.append((b"." in t or b"e" in t.lower() or b"#" in t, v))
else:
flush()
if t == b"{":
out.extend(struct.pack("<H", 0x0A))
elif t == b"}":
out.extend(struct.pack("<H", 0x0B))
elif t.startswith(b'"'):
s = t[1:-1]
out.extend(struct.pack("<HI", 2, len(s)) + s + struct.pack("<H", 0x14))
elif t.startswith(b"<"):
pass
else:
out.extend(struct.pack("<HI", 1, len(t)) + t)
i += 1
flush()
return bytes(out)
def to_tzip(text):
"""a text .x file -> "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary"""
body = text[16:]
out = bytearray(b"xof 0303tzip0032") + struct.pack("<I", 0)
data = body
prev = b""
for p in range(0, len(data), 32768):
blk = data[p:p + 32768]
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
z = c.compress(blk) + c.flush(zlib.Z_FINISH)
out.extend(struct.pack("<HH", len(blk), len(z) + 2) + b"CK" + z)
prev = blk
struct.pack_into("<I", out, 16, len(data) + 16) # the size counts the 16-byte header (D3DX)
return bytes(out)
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/X", "models-nonbsd/X"):
d0 = os.path.join(src, "test", sub)
for f in sorted(os.listdir(d0)):
p = os.path.join(d0, f)
if os.path.isfile(p) and open(p, "rb").read(4) == b"xof ":
cases.append({"name": sub.split("/")[0] + "/" + f, "path": p})
# variants of the small text files: binary 64-bit floats and tzip
for name in ("test_cube_text.x", "kwxport_test_cubewithvcolors.x", "test.x", "anim_test.x"):
p = os.path.join(src, "test", "models", "X", name)
text = open(p, "rb").read()
for kind, data in (("bin64", to_binary64(text)), ("tzip", to_tzip(text))):
q = os.path.join(tmp, "%s.%s.x" % (name[:-2], kind))
open(q, "wb").write(data)
cases.append({"name": "variant/%s.%s.x" % (name[:-2], kind), "path": q, "of": "models/" + name})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.assimp_extra(ctx, c["path"]))
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("x_cases", cases)