--!strict -- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each -- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies -- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and -- keyframed joint TRS tracks as animation channels. New in formats-luau. -- -- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base -- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") -- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } -- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } -- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } -- -- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. local Types = require("@formats/Types") local Mat4 = require("@formats/codecs/model/Mat4") local Rig = {} local Scene = Types.Scene local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 export type Joint = { name: string?, parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) translation: { number }, rotation: { number }, -- quaternion x, y, z, w scale: { number }?, } export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time -- ------------------------------------------------------------------------------------------------ morph targets -- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL -- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as -- many f32 x3 as the base; shorter ones are skipped (false is returned). function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean local pos = prim.attributes.POSITION if not pos or pos.type ~= "f32" or pos.components ~= 3 then return false end local nrm = prim.attributes.NORMAL local n = pos.count * 3 local targets: { { [string]: Types.Accessor } } = {} local ok = true for k, f in frames do if buffer.len(f) < n * 4 then ok = false break end local t: { [string]: Types.Accessor } = {} local d = buffer.create(n * 4) local base = pos.data for i = 0, n - 1 do writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) end t.POSITION = Scene.accessor(d, "f32", 3, pos.count) local fn = normals and normals[k] if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then local dn = buffer.create(n * 4) for i = 0, n - 1 do writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) end t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) end targets[k] = t end if ok then prim.targets = targets end return ok end -- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on -- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR -- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) for _, rg in ranges do local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) if last >= first then local keys = last - first + 1 local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 local times = buffer.create(keys * 4) local weights = buffer.create(keys * targets * 4) for k = 0, keys - 1 do writef32(times, k * 4, k / fps) writef32(weights, (k * targets + first - 1 + k) * 4, 1) end table.insert(scene.animations, { name = rg.name, channels = { { node = node, path = "weights" :: any, input = Scene.accessor(times, "f32", 1, keys), output = Scene.accessor(weights, "f32", 1, keys * targets), interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, }, }, }) end end end -- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a -- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored -- normals cannot be used (Quake's precomputed normal table is not redistributable here). function Rig.normals(pos: buffer, count: number, indices: { number }): buffer local out = buffer.create(count * 12) local acc = table.create(count * 3, 0) for k = 1, #indices - 2, 3 do local a, b, c = indices[k], indices[k + 1], indices[k + 2] if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx for _, v in { a, b, c } do acc[v * 3 + 1] += nx acc[v * 3 + 2] += ny acc[v * 3 + 3] += nz end end end for v = 0, count - 1 do local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] local l = math.sqrt(x * x + y * y + z * z) if l > 0 then x, y, z = x / l, y / l, z / l end writef32(out, v * 12, x) writef32(out, v * 12 + 4, y) writef32(out, v * 12 + 8, z) end return out end -- ------------------------------------------------------------------------------------------------ skeletons local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) end -- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z -- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) function Rig.angles(x: number, y: number, z: number): { number } local sy, cy = math.sin(z / 2), math.cos(z / 2) local sp, cp = math.sin(y / 2), math.cos(y / 2) local sr, cr = math.sin(x / 2), math.cos(x / 2) return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } end -- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its -- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse -- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's -- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) local n = #joints local world: { { number } } = {} local nodes: { number } = {} for i, j in joints do local p = if j.parent >= 1 and j.parent < i then j.parent else 0 local m = trs(j) local lt, lr, ls = j.translation, j.rotation, j.scale if space == "world" then world[i] = m if p > 0 then local inv = Mat4.inverse(world[p]) if inv then local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) lt, lr, ls = t, r, s end end else world[i] = if p > 0 then Mat4.mul(world[p], m) else m end local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } table.insert(scene.nodes, node) local idx = #scene.nodes nodes[i] = idx if p > 0 then table.insert(scene.nodes[nodes[p]].children, idx) elseif root and scene.nodes[root] then table.insert(scene.nodes[root].children, idx) else table.insert(scene.roots, idx) end end local ibm = buffer.create(n * 64) for i = 1, n do local inv = Mat4.inverseFull(world[i]) or Mat4.identity() for k = 1, 16 do writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) end end local acc = Scene.accessor(ibm, "f32", 16, n) acc.matrix = true table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) return nodes, #scene.skins, world end -- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with -- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept -- and normalised to sum 1. function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) for v, l in lists do local pairs_: { { number } } = {} local at: { [number]: { number } } = {} for k = 1, #l - 1, 2 do if l[k + 1] > 0 then local same = at[l[k]] if same then same[2] += l[k + 1] -- the same joint twice: one influence else local e = { l[k], l[k + 1] } at[l[k]] = e table.insert(pairs_, e) end end end table.sort(pairs_, function(a: { number }, b: { number }): boolean return a[2] > b[2] end) local sum = 0 for k = 1, math.min(4, #pairs_) do sum += pairs_[k][2] end for k = 1, math.min(4, #pairs_) do writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) end end return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) end -- ------------------------------------------------------------------------------------------------ animations local function floats(t: { number }, count: number, comps: number): Types.Accessor? if #t < count * comps then return nil end local b = buffer.create(count * comps * 4) for i = 1, count * comps do writef32(b, (i - 1) * 4, t[i]) end return Scene.accessor(b, "f32", comps, count) end -- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into -- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks -- with too few keys are skipped. Default interpolation "LINEAR". function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number local count = #times local input = floats(times, count, 1) local channels: { Types.Channel } = {} local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" if input then for j, tr in tracks do local node = nodes[j] if node then for _, path in { "translation", "rotation", "scale" } do local keys = (tr :: any)[path] local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) if acc then table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) end end end end end table.insert(scene.animations, { name = name, channels = channels }) return #scene.animations end return Rig