diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 998e47b..a352671 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | @@ -130,6 +131,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each + - codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d44f2b4..397a3f7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return require("@formats/model/iqm") + end, + }, { name = "lwo", category = "model", diff --git a/src/Formats/codecs/model/Sampler.luau b/src/Formats/codecs/model/Sampler.luau new file mode 100644 index 0000000..df866b9 --- /dev/null +++ b/src/Formats/codecs/model/Sampler.luau @@ -0,0 +1,173 @@ +--!strict +-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for +-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold +-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames +-- (IQM, MD5, BVH, ...). New in formats-luau. +-- +-- local sample = Sampler.channel(ch) -- nil for an unreadable channel +-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights +-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique +-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } +-- +-- Never throws on bad data: unreadable channels are skipped. +local Types = require("@formats/Types") + +local Sampler = {} + +export type Sample = (t: number) -> { number } +export type Pose = { [number]: { [string]: { number } } } + +local function normalize(q: { number }): { number } + local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a: { number }, b: { number }, s: number): { number } + local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +-- channel(ch) -> sample(t) | nil +function Sampler.channel(ch: Types.Channel): Sample? + local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = if cubic then 3 else 1 + local comps: number + if ch.path == "weights" then + comps = (out.count * out.components) // (n * per) + else + comps = if ch.path == "rotation" then 4 else 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = table.create(n) :: { number } + for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + -- element e (0-based, of comps values) of the flat output + local function get(e: number): { number } + local v = table.create(comps) :: { number } + for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(flat // oc, flat % oc) + end + return v + end + local function value(k: number): { number } -- key k (1-based) + return get(if cubic then (k - 1) * 3 + 1 else k - 1) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t: number): { number } + if t <= times[1] or n == 1 then + return if rot then normalize(value(1)) else value(1) + end + if t >= times[n] then + return if rot then normalize(value(n)) else value(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = if dt > 0 then (t - times[lo]) / dt else 0 + if step then + return if rot then normalize(value(lo)) else value(lo) + end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return if rot then normalize(v) else v + end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +-- times(anim) -> every key time, sorted and unique +function Sampler.times(anim: Types.Animation): { number } + local seen: { [number]: boolean } = {} + local out: { number } = {} + for _, ch in anim.channels do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table +-- (reuse it across calls for the same animation) +function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose + local cache: { [any]: any } = samplers or {} + local pose: Pose = {} + for _, ch in anim.channels do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s: Sample? = cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler diff --git a/src/Formats/model/iqm/Read.luau b/src/Formats/model/iqm/Read.luau new file mode 100644 index 0000000..599091a --- /dev/null +++ b/src/Formats/model/iqm/Read.luau @@ -0,0 +1,359 @@ +--!strict +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and +-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). +-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h: number): number + local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } + local out = table.create(n) :: { number } + local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v: number + if format == 0 then + v = readi8(b, p) + v = if normalized then math.max(v / 127, -1) else v + elseif format == 1 then + v = readu8(b, p) + v = if normalized then v / 255 else v + elseif format == 2 then + v = readi16(b, p) + v = if normalized then math.max(v / 32767, -1) else v + elseif format == 3 then + v = readu16(b, p) + v = if normalized then v / 65535 else v + elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals: { number }, comps: number): Types.Accessor + local d = buffer.create(#vals * 4) + for i, v in vals do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, #vals // comps) +end + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +-- scene(b, base, limit, opts) -> Scene | nil, message +function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) + local size = limit - base + local H: { [string]: number } = {} + for i, name in Read.HEADER do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs: number, count: number, each: number, what: string): string? + if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" + local function str(ofs: number): string + if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + -- vertex arrays (the whole model's vertices; meshes are ranges of them) + local nv = H.num_vertexes + type Array = { kind: string, name: string, format: number, comps: number, offset: number } + local arrays: { Array } = {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) + table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + -- joints -> nodes + a skin + local jointNodes: { number } = {} + local skin: number? = nil + if H.num_joints > 0 then + local joints: { Rig.Joint } = {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = table.create(10) :: { number } + for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM names its texture there) + local matOf: { [string]: number } = {} + local function material(name: string): number? + if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + -- meshes + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes: { [string]: Types.Accessor } = {} + for _, a in arrays do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (if big then 2 else 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 + x = math.clamp(math.floor(x), 0, if big then 65535 else 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 + writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name + local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps + if want ~= a.comps then + local fixed = table.create(cv * want, 0) :: { number } + for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 + end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses: { { mask: number, offset: { number }, scale: { number } } } = {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = table.create(10) :: { number }, table.create(10) :: { number } + for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels += 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes: number = H.num_framechannels * 2 + local framesAt: number = base + H.ofs_frames + local function frame(f: number): { { number } } + local out = table.create(np) :: { { number } } + local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = table.create(10) :: { number } + for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k: number = ps.scale[c + 1] + x += readu16(b, q) * k + q += 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims: { any } = {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = if rate > 0 and rate == rate then rate else 30 + local times = table.create(count) :: { number } + local tracks: { [number]: Rig.Track } = {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in tracks do + local v = fr[j] + local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } + table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = if ql > 0 then ql else 1 + table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read diff --git a/src/Formats/model/iqm/Write.luau b/src/Formats/model/iqm/Write.luau new file mode 100644 index 0000000..df6eaf9 --- /dev/null +++ b/src/Formats/model/iqm/Write.luau @@ -0,0 +1,706 @@ +--!strict +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines +-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights +-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins +-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse +-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world +-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are +-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), +-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. +-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). +-- Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Mat4 = require("@formats/codecs/model/Mat4") +local Sampler = require("@formats/codecs/model/Sampler") +local Read = require("@formats/model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene +type M4 = { number } + +-- ------------------------------------------------------------------------------------------------ scene walk +-- world matrices (rest pose, or with a pose's overrides) and the parent of every node +local function parents(scene: Types.Scene): { [number]: number } + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4 + if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 } + local world: { [number]: M4 } = {} + local function get(i: number, depth: number): M4 + local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in scene.nodes do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points +local function triangles(prim: Types.Primitive): { number }? + local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = if fget then fget(f, 0) else 0 + for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at += n + end + else + return nil + end + for _, v in out do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }? + if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = table.create(nv * comps) :: { number } + for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1] + end + end + return out +end + +-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } + local pairs_: { { number } } = {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, pr in pairs_ do + sum += pr[2] + end + local q: { number } = {} + local left = 255 + for k, pr in pairs_ do + q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0 + left -= q[k] + end + if #pairs_ > 0 then + q[1] += left + end + local list: { number } = {} + for k, pr in pairs_ do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +-- appends a flat influence list to the blend index / weight arrays (4 slots) +local function push4(bi: { number }, bw: { number }, list: { number }) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end + +-- ------------------------------------------------------------------------------------------------ writer +type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number } + +function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) + local parent = parents(scene) + local rest = worlds(scene, parent, nil) + -- the skeleton: every skin joint, parents first + local isJoint: { [number]: boolean } = {} + local ibmOf: { [number]: M4 } = {} + for _, skin in scene.skins do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in skin.joints do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = table.create(16) :: M4 + for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + local jointList: { number } = {} + local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local function add(n: number, depth: number) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard += 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in scene.skins do + for _, n in skin.joints do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n: number): number + local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard += 1 + end + return -1 + end + local bindWorld: { [number]: M4 } = {} + for _, n in jointList do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number }) + local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1]]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + -- the meshes + local nodeOfMesh: { [number]: number } = {} + local placed: { { node: number, mesh: number } } = {} + local seen: { [number]: boolean } = {} + local function visit(i: number, depth: number) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in node.children or {} do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in scene.nodes do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in roots do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in scene.meshes do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris: { number } = {} + local meshes: { MeshOut } = {} + -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds + local skinOf: { { number } } = {} + local nvTotal = 0 + for _, pl in placed do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY + local nrmM = Mat4.normalMatrix(world) + for pi, prim in mesh.primitives do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number } + local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = if pl.node > 0 then pl.node else nil + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard += 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + local list: { number } + if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- triangles back to IQM's clockwise order + local tfirst = #tris // 3 + for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else "" + end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name ..= "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 }) + nvTotal += nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + -- animation frames + local frames: { { { number } } } = {} -- frames[f][joint] = 10 values + local anims: { { name: string, first: number, count: number, rate: number } } = {} + local frameWorld: { { [number]: M4 } } = {} + if hasJoints then + for ai, anim in scene.animations do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second + local dt = if #keys > 1 then keys[2] - keys[1] else 0 + local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = if uniform then 1 / dt else 30 + end + local fps: number = math.clamp(rate :: number, 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ: { [number]: { number } } = {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = table.create(#jointList) :: { { number } } + for j, n in jointList do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + -- quantization per pose channel + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in frames do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels += 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + -- text + local text = { "\0" } + local textLen = 1 + local textAt: { [string]: number } = { [""] = 0 } + local function str(s: string): number + local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen += #s + 1 + textAt[s] = at + return at + end + for _, m in meshes do + str(m.name) + str(m.material) + end + for _, n in jointList do + str(scene.nodes[n].name or "") + end + for _, a in anims do + str(a.name) + end + local comment = opts and opts.comment + -- layout + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H: { [string]: number } = {} + local function at(): number + return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text += 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in meshes do + for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do + w:u32le(v) + end + end + -- vertex arrays: headers, then data + type Arr = { typ: number, format: number, comps: number, data: { number } } + local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt: { number } = {} + for i, a in arrs do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in a.data do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in a.data do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in a.data do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in a.data do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), #tris // 3 + for _, v in tris do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in jointList do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le(if p < 0 then p + 2 ^ 32 else p) + for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in jointList do + local jp = jointParent(n) + w:u32le(if jp < 0 then jp + 2 ^ 32 else jp) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in anims do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in frames do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + -- bounds of the skinned vertices per frame + H.ofs_bounds = at() + local skinM = table.create(#jointList) :: { M4 } + for f, world in frameWorld do + for j, n in jointList do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in Read.HEADER do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in arrs do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write diff --git a/src/Formats/model/iqm/init.luau b/src/Formats/model/iqm/init.luau new file mode 100644 index 0000000..c46a61b --- /dev/null +++ b/src/Formats/model/iqm/init.luau @@ -0,0 +1,82 @@ +--!strict +-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / +-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). +-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as +-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as +-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints +-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels +-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in +-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's +-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). +-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and +-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/iqm/Read") +local Write = require("@formats/model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more vertices or triangles (default 2^25) +} +export type EncodeOptions = { + framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) + comment: string?, -- stored in the comment block +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r: Bytes.Reader): number + return if r:peek(16) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message) + end + return out, nil +end + +return Iqm diff --git a/tests/codecs/sampler.luau b/tests/codecs/sampler.luau new file mode 100644 index 0000000..bfdb746 --- /dev/null +++ b/tests/codecs/sampler.luau @@ -0,0 +1,92 @@ +-- codecs/model/Sampler tests: STEP / LINEAR / CUBICSPLINE channels (glTF's Hermite definition), quaternion slerp +-- (shortest path, unit length), clamping outside the keys, weights channels, Sampler.times and Sampler.pose; glTF's +-- InterpolationTest sample model (every interpolation) sampled at its keys gives the key values; bad channels. +local T = require("@tests/T") +local Sampler = require("@formats/codecs/model/Sampler") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Picks = require("@tests/gen/iqm_gltf") + +local t = T.suite("codecs/sampler") +local S = Types.Scene + +local function acc(list: { number }, comps: number): Types.Accessor + local b = buffer.create(#list * 4) + for i, v in list do + buffer.writef32(b, (i - 1) * 4, v) + end + return S.accessor(b, "f32", comps, #list // comps) +end +local function near(a: number, b: number, eps: number?): boolean + return math.abs(a - b) < (eps or 1e-5) +end + +do + local ch: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 1, 3 }, 1), output = acc({ 0, 0, 0, 2, 4, 6, 2, 0, 0 }, 3), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(0.5)[1], 1) and near(s(0.5)[2], 2), "linear: halfway") + t:check(near(s(2)[1], 2) and near(s(2)[2], 2), "linear: second span") + t:check(near(s(-1)[2], 0) and near(s(9)[1], 2), "linear: clamped outside the keys") + ch.interpolation = "STEP" + local st = assert(Sampler.channel(ch)) + t:check(near(st(0.99)[1], 0) and near(st(1)[1], 2), "step") +end +do + -- rotation: 0 -> 90 degrees about z, and a key stored with the opposite sign (shortest path) + local h = math.sqrt(0.5) + local ch: Types.Channel = { node = 1, path = "rotation", input = acc({ 0, 1, 2 }, 1), output = acc({ 0, 0, 0, 1, 0, 0, h, h, 0, 0, -h, -h }, 4), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local q = s(0.5) + local a = 2 * math.acos(q[4]) + t:check(near(a, math.pi / 4, 1e-4) and near(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2, 1), "slerp: 45 degrees, unit length") + local q2 = s(1.5) + t:check(near(math.abs(q2[3]), h, 1e-4), "slerp: the same orientation stored negated stays put") +end +do + -- cubic spline: in-tangent, value, out-tangent per key; p(t) for p0 = 0, p1 = 1, m0 = m1 = 0 is smoothstep + local ch: Types.Channel = { node = 1, path = "scale", input = acc({ 0, 2 }, 1), output = acc({ 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 9, 9, 9 }, 3), interpolation = "CUBICSPLINE" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(1)[1], 0.5) and near(s(0.5)[1], 3 * 0.25 ^ 2 - 2 * 0.25 ^ 3), "cubic: smoothstep") + t:check(near(s(2)[2], 1), "cubic: the last value") + -- tangents scale with the key spacing + local ch2: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 2 }, 1), output = acc({ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 3), interpolation = "CUBICSPLINE" } + local s2 = assert(Sampler.channel(ch2)) + -- h10(0.5) * dt * m0 = 0.125 * 2 * 1 + t:check(near(s2(1)[1], 0.25), "cubic: tangents times the key spacing") +end +do + local ch: Types.Channel = { node = 2, path = "weights", input = acc({ 0, 1 }, 1), output = acc({ 1, 0, 0, 1 }, 1), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local w = s(0.25) + t:check(#w == 2 and near(w[1], 0.75) and near(w[2], 0.25), "weights") + local anim: Types.Animation = { name = "a", channels = { ch, { node = 1, path = "translation", input = acc({ 0.5, 1 }, 1), output = acc({ 0, 0, 0, 1, 1, 1 }, 3), interpolation = "STEP" } } } + local times = Sampler.times(anim) + t:eq(table.concat(times, " "), "0 0.5 1", "times: sorted, unique") + local pose = Sampler.pose(S.new(), anim, 1) + t:check(pose[2].weights and pose[1].translation and near(pose[1].translation[1], 1), "pose") + t:check(Sampler.channel({ node = 1, path = "translation", input = acc({ 0, 1 }, 1), output = acc({ 1, 2 }, 1), interpolation = "LINEAR" }) == nil, "short output: nil") + t:check(Sampler.channel({ node = 1, path = "translation", input = {} :: any, output = {} :: any, interpolation = "LINEAR" }) == nil, "junk: nil") +end +do + -- a real file: sampling a glTF sample model's skin animation at its own keys returns the key values + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[1].data)), { files = Picks[1].files })) + local ok, total = true, 0 + for _, anim in g.animations do + for _, ch in anim.channels do + local s = assert(Sampler.channel(ch)) + local IN, OUT = assert(S.reader(ch.input)), assert(S.reader(ch.output)) + local comps = if ch.path == "rotation" then 4 else 3 + for k = 0, ch.input.count - 1 do + local v = s(IN(k, 0)) + for c = 1, comps do + ok = ok and near(v[c], OUT(k, c - 1), 1e-4) + end + total += 1 + end + end + end + t:check(ok and total > 0, Picks[1].name .. ": samples at the keys are the keys (" .. total .. ")") +end + +t:done() diff --git a/tests/model/iqm.luau b/tests/model/iqm.luau new file mode 100644 index 0000000..588320e --- /dev/null +++ b/tests/model/iqm.luau @@ -0,0 +1,319 @@ +-- model/iqm tests: assimp's mrfixit.iqm against assimp (meshes, triangles, vertices, materials, bind pose bounds), an +-- independent Python reader (joints, anims) and the bounds the IQM tool stored per frame (our decoded skeleton and +-- animation, skinned here, must reproduce them); writer round trips (mrfixit, glTF sample models with and without +-- skins) read back by our reader, by assimp and by the Python reader, whose skinning of our files must match ours; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/iqm.py. +local T = require("@tests/T") +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Sampler = require("@formats/codecs/model/Sampler") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") +local Xcheck = require("@tests/gen/iqm_xcheck") + +local t = T.suite("iqm") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Iqm.decode(Bytes.reader(b), opts) +end + +t:eq(Iqm.name, "iqm", "name") +t:eq(Iqm.category, "model", "category") +t:check(Iqm.caps.decode and Iqm.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 +-- the largest coordinate difference between two boxes +local function boxDiff(lo: { number }, hi: { number }, want: any): number + local d = 0 + for k = 1, 3 do + d = math.max(d, math.abs(lo[k] - want.min[k]), math.abs(hi[k] - want.max[k])) + end + return d +end +local function boxNear(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end +-- assimp's IQM root turns z-up into y-up: (x, y, z) -> (x, z, -y) +local function zUpToY(lo: { number }, hi: { number }): ({ number }, { number }) + return { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] } +end + +local function counts(scene: any): (number, number, number) + local prims, tris, verts = 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + prims += 1 + tris += p.indices.count // 3 + verts += p.attributes.POSITION.count + end + end + return prims, tris, verts +end + +-- the bounding box of every mesh vertex, skinned with the scene's skins at time t of anim (nil: the rest pose) +local function skinnedBounds(scene: any, anim: any?, time: number): ({ number }, { number }) + local pose = if anim then Sampler.pose(scene, anim, time) else nil + local parent = {} + for i, n in scene.nodes do + for _, c in n.children do + parent[c] = i + end + end + local world = {} + local function W(i: number): { number } + if world[i] then + return world[i] + end + local node = scene.nodes[i] + local over = pose and pose[i] + local m + if over then + m = Mat4.compose(over.translation or node.translation, over.rotation or node.rotation, over.scale or node.scale) + else + m = S.nodeMatrix(node) + end + if parent[i] then + m = S.mul(W(parent[i]), m) + end + world[i] = m + return m + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for ni, node in scene.nodes do + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + local skin = node.skin and scene.skins[node.skin] + local mats = {} + if skin then + local ibm = assert(S.reader(skin.inverseBindMatrices)) + for j, jn in skin.joints do + local inv = {} + for k = 1, 16 do + inv[k] = ibm(j - 1, k - 1) + end + mats[j - 1] = S.mul(W(jn), inv) + end + end + local LINES = { points = true, lines = true, line_strip = true, line_loop = true } + for _, p in mesh.primitives do + if LINES[p.mode] then + continue + end + local P = assert(S.reader(p.attributes.POSITION)) + local J = p.attributes.JOINTS_0 and S.reader(p.attributes.JOINTS_0) + local Wt = p.attributes.WEIGHTS_0 and S.reader(p.attributes.WEIGHTS_0) + for v = 0, p.attributes.POSITION.count - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if skin and J and Wt then + local sx, sy, sz = 0, 0, 0 + for c = 0, 3 do + local w = Wt(v, c) + if w > 0 then + local qx, qy, qz = Mat4.point(mats[J(v, c)], x, y, z) + sx, sy, sz = sx + w * qx, sy + w * qy, sz + w * qz + end + end + x, y, z = sx, sy, sz + else + x, y, z = Mat4.point(W(ni), x, y, z) + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + end + end + end + end + return lo, hi +end + +local function xcheck(name: string): any + for _, x in Xcheck do + if x.name == name then + return x + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ mrfixit +local fixit = Cases[1] +local scene, err = decode(fixit.data) +t:check(scene, "mrfixit: decode " .. tostring(err)) +do + local a, ref = fixit.assimp, fixit.ref + local prims, tris, verts = counts(scene) + t:eq(prims, a.meshes, "mrfixit: meshes (assimp)") + t:eq(tris, a.faces, "mrfixit: triangles (assimp)") + t:eq(verts, a.vertices, "mrfixit: vertices (assimp)") + t:eq(#scene.materials, a.materials, "mrfixit: materials (assimp)") + t:eq(scene.textures[scene.materials[1].baseColorTexture.texture].uri, "Body.jpg", "mrfixit: material string -> texture uri") + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local ylo, yhi = zUpToY(lo, hi) + t:check(boxNear(ylo, yhi, a, 1e-4), string.format("mrfixit: bind pose bounds (assimp) %s / %s", table.concat(ylo, " "), table.concat(yhi, " "))) + t:eq(#scene.skins, 1, "mrfixit: one skin") + t:eq(#scene.skins[1].joints, ref.joints, "mrfixit: joints (Python reader)") + for j, n in scene.skins[1].joints do + t:eq(scene.nodes[n].name, ref.jointNames[j], "mrfixit: joint name " .. j) + end + t:eq(#scene.animations, #ref.anims, "mrfixit: animations") + t:eq(scene.animations[1].name, ref.anims[1].name, "mrfixit: animation name") + t:eq(scene.meta.source.animations[1].frames, ref.anims[1].frames, "mrfixit: frames") + local prim = scene.meshes[1].primitives[1] + t:check(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0.type == "unorm8", "mrfixit: blend indexes / weights") + t:check(prim.attributes.TANGENT and prim.attributes.TANGENT.components == 4, "mrfixit: tangents") + -- the bounds the IQM tool stored, from our skeleton + animation (and the Python reader's skinning agrees) + local fps = ref.anims[1].framerate + -- (the tool computed its bounds before quantizing the frames: up to 0.1% off the quantized animation) + local worst, worstPy = 0, 0 + for f = 1, ref.frames, 5 do + local l, h = skinnedBounds(scene, scene.animations[1], (f - 1) / fps) + worst = math.max(worst, boxDiff(l, h, ref.stored[f])) + worstPy = math.max(worstPy, boxDiff(l, h, ref.skinned[f])) + t:check(boxDiff(ref.skinned[f].min, ref.skinned[f].max, ref.stored[f]) < 1e-2, "mrfixit: the Python reader reproduces the stored bounds, frame " .. f) + end + t:check(worst < 1e-2, "mrfixit: skinned bounds per frame match the IQM tool's (worst " .. worst .. ")") + t:check(worstPy < 1e-4, "mrfixit: skinned bounds per frame match the Python reader's (worst " .. worstPy .. ")") + t:check(scene.meta.source.bounds and #scene.meta.source.bounds == ref.frames, "mrfixit: bounds block read") +end + +-- ------------------------------------------------------------------------------------------------ round trips +do + local out = assert(Iqm.encode(scene)) + local back = assert(decode(out)) + local p1, t1, v1 = counts(scene) + local p2, t2, v2 = counts(back) + t:check(p1 == p2 and t1 == t2 and v1 == v2, "round trip: counts") + -- positions and indices exact + local same = true + for mi, m in scene.meshes do + local a, b = m.primitives[1], back.meshes[mi].primitives[1] + t:check(buffer.tostring(a.attributes.POSITION.data) == buffer.tostring(b.attributes.POSITION.data), "round trip: positions exact, mesh " .. mi) + t:check(buffer.tostring(a.indices.data) == buffer.tostring(b.indices.data), "round trip: triangles exact, mesh " .. mi) + -- influences: the same (joint, weight) pairs (unused slots and their order may differ) + local ja, wa, jb, wb = S.reader(a.attributes.JOINTS_0), S.reader(a.attributes.WEIGHTS_0), S.reader(b.attributes.JOINTS_0), S.reader(b.attributes.WEIGHTS_0) + for v = 0, a.attributes.POSITION.count - 1 do + local inf = {} + for c = 0, 3 do + if (wa :: any)(v, c) > 0 then + inf[(ja :: any)(v, c)] = (inf[(ja :: any)(v, c)] or 0) + (wa :: any)(v, c) + end + end + for c = 0, 3 do + local w = (wb :: any)(v, c) + if w > 0 then + local j = (jb :: any)(v, c) + same = same and inf[j] ~= nil and math.abs(inf[j] - w) < 1.5 / 255 + inf[j] = nil + end + end + same = same and next(inf) == nil + end + end + t:check(same, "round trip: the same influences") + t:eq(#back.skins[1].joints, #scene.skins[1].joints, "round trip: joints") + t:eq(back.meta.source.animations[1].frames, scene.meta.source.animations[1].frames, "round trip: frames") + local worst = 0 + for _, time in { 0, 0.5, 1.5, 3 } do + local l1, h1 = skinnedBounds(scene, scene.animations[1], time) + local l2, h2 = skinnedBounds(back, back.animations[1], time) + for k = 1, 3 do + worst = math.max(worst, math.abs(l1[k] - l2[k]), math.abs(h1[k] - h2[k])) + end + end + t:check(worst < 2e-3, "round trip: the animation skins the same (worst " .. worst .. ")") + -- assimp and the Python reader on our file + local x = assert(xcheck("rt_mrfixit.iqm"), "xcheck rt_mrfixit") + t:eq(x.assimp.faces, fixit.assimp.faces, "round trip: assimp triangles") + t:eq(x.assimp.vertices, fixit.assimp.vertices, "round trip: assimp vertices") + t:check(boxNear(x.assimp.min, x.assimp.max, fixit.assimp, 1e-4), "round trip: assimp bounds") + local w2, w3 = 0, 0 + for f, box in fixit.ref.skinned do + local mine = x.ref.skinned[f] + w2 = math.max(w2, boxDiff(mine.min, mine.max, box)) + w3 = math.max(w3, boxDiff(x.ref.stored[f].min, x.ref.stored[f].max, mine)) + end + t:check(w2 < 2e-3, "round trip: the Python reader skins our file like the original (worst " .. w2 .. ")") + t:check(w3 < 1e-4, "round trip: our bounds block matches the Python skinning (worst " .. w3 .. ")") +end + +-- glTF sample models through the writer +for _, p in Picks do + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })) + local out, e = Iqm.encode(g) + t:check(out, p.name .. ": encode " .. tostring(e)) + local back = assert(decode(out)) + local x = assert(xcheck("gltf_" .. p.name .. ".iqm"), "xcheck " .. p.name) + local _, tris, verts = counts(back) + t:eq(x.assimp.faces, tris, p.name .. ": assimp reads our triangles") + t:eq(x.assimp.vertices, verts, p.name .. ": assimp reads our vertices") + -- unskinned: the glTF scene's world bounds (skinned: IQM's rest pose is the bind pose, checked by the frames below) + local l2, h2 = skinnedBounds(back, nil, 0) + if #g.skins == 0 then + local lo, hi = skinnedBounds(g, nil, 0) + t:check(boxNear(l2, h2, { min = lo, max = hi }, 1e-4), p.name .. ": world bounds kept") + end + local yl, yh = zUpToY(l2, h2) + t:check(boxNear(yl, yh, x.assimp, 1e-3), p.name .. ": assimp bounds of our file") + if #g.skins > 0 and #g.animations > 0 then + local anim = x.ref.anims[1] + local worst = 0 + for f = 1, x.ref.frames do + local l, h = skinnedBounds(g, g.animations[1], (f - 1) / anim.framerate) + local py = x.ref.skinned[f] + for k = 1, 3 do + worst = math.max(worst, math.abs(l[k] - py.min[k]), math.abs(h[k] - py.max[k])) + end + end + t:check(worst < 5e-3, p.name .. ": the Python reader skins our file like the glTF animation (worst " .. worst .. ")") + t:eq(#back.skins[1].joints, #g.skins[1].joints, p.name .. ": joints") + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("INTERQUAKEMODEL\0") + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local bad = buffer.fromstring(fixit.data) + buffer.writeu32(bad, 16, 1) + local _, e2 = decode(bad) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 1: " .. tostring(e2)) + local cut = buffer.fromstring(string.sub(fixit.data, 1, 5000)) + local _, e3 = decode(cut) + t:check(e3 and e3.code == Err.TRUNCATED, "cut: " .. tostring(e3)) + local _, e4 = decode(fixit.data, { maxVertices = 100 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Iqm.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + local _, e6 = Iqm.encode(S.new()) + t:check(e6 and e6.code == Err.ARG, "encode an empty scene: " .. tostring(e6)) + t:eq(Iqm.sniff(Bytes.reader(buffer.fromstring(fixit.data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local small = assert(Iqm.encode(assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[2].data)), { files = Picks[2].files })))) + local samples = { small, string.sub(fixit.data, 1, 20000) } + t:fuzz("decode", function(b: buffer) + local s = Iqm.decode(Bytes.reader(b)) + if s then + Iqm.encode(s) + end + return s + end, samples, { mutations = 24, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/_iqm_encode.luau b/tools/fixtures/_iqm_encode.luau new file mode 100644 index 0000000..388e77f --- /dev/null +++ b/tools/fixtures/_iqm_encode.luau @@ -0,0 +1,38 @@ +-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our +-- reader and writer, and every glTF pick through our writer, printing "\t" lines for assimp and the +-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_.iqm. +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +for _, c in Cases do + local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data)))) + print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene)))) +end +for _, p in Picks do + local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files }) + if scene then + local out, e2 = Iqm.encode(scene) + if out then + print("gltf_" .. p.name .. ".iqm\t" .. hex(out)) + else + print("encode failed " .. p.name .. ": " .. tostring(e2)) + end + else + print("skipped " .. p.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/_iqm_reference.py b/tools/fixtures/_iqm_reference.py new file mode 100644 index 0000000..b2525a6 --- /dev/null +++ b/tools/fixtures/_iqm_reference.py @@ -0,0 +1,113 @@ +# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its +# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the +# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds +# block, which it returns too for comparison). +import math, struct + +HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays " + "num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames " + "num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split() +FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)} + + +def mat(t, q, s): + x, y, z, w = q + n = math.sqrt(x * x + y * y + z * z + w * w) or 1 + x, y, z, w = x / n, y / n, z / n, w / n + r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], + [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], + [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]] + return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]] + + +def mul(a, b): + return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)] + + +def inv(m): + # general 4x4 inverse (Gauss-Jordan) + a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)] + for c in range(4): + p = max(range(c, 4), key=lambda r: abs(a[r][c])) + a[c], a[p] = a[p], a[c] + d = a[c][c] or 1e-30 + a[c] = [v / d for v in a[c]] + for r in range(4): + if r != c: + f = a[r][c] + a[r] = [v - f * w for v, w in zip(a[r], a[c])] + return [row[4:] for row in a] + + +def read(data): + h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16))) + text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]] + + def s(o): + return text[o:text.index(b"\0", o)].decode("latin1") + arrays = {} + for i in range(h["num_vertexarrays"]): + typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20) + c, n = FMT[fmt] + vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs) + arrays[typ] = (fmt, size, vals) + joints = [] + for j in range(h["num_joints"]): + v = struct.unpack_from("= 0 else m) + invbind = [inv(m) for m in bind] + poses = [] + for p in range(h["num_poses"]): + v = struct.unpack_from("= 0 else m) + skin = [mul(world[j], invbind[j]) for j in range(len(world))] + lo, hi = [1e30] * 3, [-1e30] * 3 + for v in range(h["num_vertexes"]): + x, y, z = pos[v * 3:v * 3 + 3] + if bi and bw: + sx = sy = sz = 0.0 + tot = 0.0 + for c in range(4): + w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c] + if w > 0: + m = skin[bi[2][v * 4 + c]] + sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3]) + sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3]) + sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3]) + tot += w + if tot > 0: + x, y, z = sx, sy, sz + lo = [min(a, b) for a, b in zip(lo, (x, y, z))] + hi = [max(a, b) for a, b in zip(hi, (x, y, z))] + boxes.append({"min": lo, "max": hi}) + stored = [] + if h["ofs_bounds"]: + for f in range(h["num_frames"]): + v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32) + stored.append({"min": list(v[0:3]), "max": list(v[3:6])}) + return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"], + "jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored} diff --git a/tools/fixtures/iqm.py b/tools/fixtures/iqm.py new file mode 100644 index 0000000..ae2559d --- /dev/null +++ b/tools/fixtures/iqm.py @@ -0,0 +1,57 @@ +# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp +# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent +# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed +# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf) +# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader. +# tests/gen/iqm_cases.luau { name, data, assimp, ref } +# tests/gen/iqm_gltf.luau { name, data, files } +# tests/gen/iqm_xcheck.luau { name, assimp, ref } +import importlib.util, os + +INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"] + + +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 + + +def info(ctx, M, fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + for k in ("min", "max", "perMesh"): + a.pop(k, None) + if not a.get("failed"): + a.update(fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = module(ctx, "_model_ref") + fbx = module(ctx, "fbx") + R = module(ctx, "_iqm_reference") + tmp = M.tempdir() + p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm") + data = open(p, "rb").read() + ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}]) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"): + d0 = os.path.join(gl, model) + for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []: + d = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else [] + if mains: + picks.append({"name": model, "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + ctx.emit("iqm_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau") + out = [] + for name in sorted(ours): + q = os.path.join(tmp, name) + open(q, "wb").write(ours[name]) + out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])}) + ctx.emit("iqm_xcheck", out)