ws-3d3-b: model/iqm (Inter-Quake Model v2 read + write: meshes, every vertex array format, joints -> skin, poses / frames / anims -> channels, bounds; writer merges skins, samples and quantizes animations); new codecs/model/Sampler (channel evaluation STEP / LINEAR + slerp / CUBICSPLINE, animation poses at a time) with tests

mrfixit.iqm matches assimp and an independent Python IQM reader (its skinning reproduces the bounds the IQM tool stored; ours matches it to 1e-4); round trips and glTF skinned models written by us are skinned identically by the Python reader.
This commit is contained in:
4DBug committed 2026-10-31 14:39:22 -05:00
1 parent 4f05c89f01
commit 51daa00a67
11 files changed
+1953

No files matched your search

+12
View File
@@ -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",
+173
View File
@@ -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
+359
View File
@@ -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
+706
View File
@@ -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
+82
View File
@@ -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 _<name>), 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