ws-game: codecs/model/Rig (morph targets + weights animations, skeletons + skins, influences, joint TRS animations for the game model formats); codecs/image/Pixels.palette (RGB / BGR triples -> u32 palette; additive)

This commit is contained in:
4DBug committed 2026-10-31 13:54:43 -05:00
1 parent d41d64219a
commit 5af4aa361e
4 files changed
+338

No files matched your search

+21
View File
@@ -13,6 +13,27 @@ local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lsh
local Pixels = {}
-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..],
-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL,
-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures).
function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer
local pal = buffer.create(1024)
local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0
for i = 0, 255 do
local v = 0xFF000000
if i < m then
local o = base + i * 3
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
if bgr then
r, b = b, r
end
v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r)
end
writeu32(pal, i * 4, v)
end
return pal
end
-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal)
function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
topDown: boolean, pal: buffer)
+223
View File
@@ -0,0 +1,223 @@
--!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
-- ------------------------------------------------------------------------------------------------ skeletons
local function trs(j: Joint): { number }
return Mat4.compose(j.translation, j.rotation, j.scale)
end
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): 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)
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
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); 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 } } = {}
for k = 1, #l - 1, 2 do
if l[k + 1] > 0 then
table.insert(pairs_, { l[k], l[k + 1] })
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