From f14d5ac4efa9008156327c00eb0286de8864d85c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:33 -0500 Subject: [PATCH] ws-game: model/mdl (Quake 1 IDPO: skins via palette, frames as morph targets; Half-Life 1 IDST: bones, skin, body parts, strips / fans, textures with palettes, sequences as animations); Rig.angles, Rig.skeleton returns world matrices --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/model/Rig.luau | 15 +- src/Formats/model/mdl/HalfLife.luau | 340 ++++++++++++++++++++++++++++ src/Formats/model/mdl/Quake.luau | 222 ++++++++++++++++++ src/Formats/model/mdl/init.luau | 98 ++++++++ tests/model/_soup.luau | 7 +- tests/model/mdl.luau | 155 +++++++++++++ tools/fixtures/mdl.py | 261 +++++++++++++++++++++ 9 files changed, 1105 insertions(+), 6 deletions(-) create mode 100644 src/Formats/model/mdl/HalfLife.luau create mode 100644 src/Formats/model/mdl/Quake.luau create mode 100644 src/Formats/model/mdl/init.luau create mode 100644 tests/model/mdl.luau create mode 100644 tools/fixtures/mdl.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index bb053cf..2c36dcb 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -40,6 +40,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` | | model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` | +| model | mdl | .mdl | yes | - | variants: "quake", "halflife", morph: true, skins: true, animation: true | `tests/model/mdl.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` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 0f1e601..23ca4cf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -434,6 +434,18 @@ local list: { Entry } = { return require("@formats/model/md3") end, }, + { + name = "mdl", + category = "model", + path = "model/mdl", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, + load = function() + return require("@formats/model/mdl") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau index 89bd35f..3c01612 100644 --- a/src/Formats/codecs/model/Rig.luau +++ b/src/Formats/codecs/model/Rig.luau @@ -139,11 +139,20 @@ 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 +-- 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) +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 } = {} @@ -185,7 +194,7 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w 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 + return nodes, #scene.skins, world end -- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with diff --git a/src/Formats/model/mdl/HalfLife.luau b/src/Formats/model/mdl/HalfLife.luau new file mode 100644 index 0000000..53dbc01 --- /dev/null +++ b/src/Formats/model/mdl/HalfLife.luau @@ -0,0 +1,340 @@ +--!strict +-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h +-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. +-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> +-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans +-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = +-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> +-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). +-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone +-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "t.mdl" (pass it +-- as opts.textures = that file's bytes). +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Pixels = require("@formats/codecs/image/Pixels") +local Rig = require("@formats/codecs/model/Rig") + +local HalfLife = {} + +local Scene = Types.Scene +local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32 +local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16 + +type Bone = { name: string, parent: number, value: { number }, scale: { number } } +export type Options = { bodies: { number }?, textures: buffer?, maxPixels: number?, maxVertices: number? } + +local function str(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message +local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) + local n, at = readi32(b, base + 180), readi32(b, base + 184) + if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then + return nil, "bad texture table" + end + local out: { Types.Image } = {} + local names: { string } = {} + for i = 0, n - 1 do + local o = base + at + i * 80 + local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76) + if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then + return nil, "bad texture " .. i + end + local img = Types.Image.new(w, h) + local pal = Pixels.palette(b, base + data + w * h, 256) + Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal) + local flags = readi32(b, o + 64) + img.meta.source = { format = "mdl", flags = flags } + out[i + 1] = img + names[i + 1] = str(b, o, 64) + end + return out, names +end + +-- one animation value: bone default + stored value * scale (frame f, 0-based) +local function animValue(b: buffer, at: number, limit: number, f: number): number? + local p = at + local k = f + for _ = 1, 65536 do + if p + 2 > limit then + return nil + end + local valid, total = readu8(b, p), readu8(b, p + 1) + if total == 0 then + return nil + end + if total > k then + local idx = if valid > k then k + 1 else valid + if p + idx * 2 + 2 > limit then + return nil + end + return readi16(b, p + idx * 2) + end + k -= total + p += (valid + 1) * 2 + end + return nil +end + +-- decode(b, base, size, opts) -> Scene | nil, message +function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) + if size < 244 then + return nil, "truncated header" + end + local limit = base + size + local function hdr(o: number): number + return readi32(b, base + o) + end + local nBones, oBones = hdr(140), hdr(144) + local nSeq, oSeq = hdr(164), hdr(168) + local nTex = hdr(180) + local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200) + local nParts, oParts = hdr(204), hdr(208) + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then + return nil, "bad bone table" + end + if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then + return nil, "bad sequence table" + end + if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then + return nil, "bad body part table" + end + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + -- bones + local bones: { Bone } = {} + local joints: { Rig.Joint } = {} + for i = 0, nBones - 1 do + local o = base + oBones + i * 112 + local value, scale = {}, {} + for k = 0, 5 do + value[k + 1] = readf32(b, o + 64 + k * 4) + scale[k + 1] = readf32(b, o + 88 + k * 4) + end + local parent = readi32(b, o + 32) + bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale } + joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) } + end + local root: Types.Node = { name = str(b, base + 8, 64), children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) + -- textures and skins + local texSrc, texBase, texSize = b, base, size + if nTex == 0 and opts and opts.textures then + texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) + if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then + return nil, "opts.textures is not a studio texture file" + end + nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200) + end + local images, texNames = textures(texSrc, texBase, texSize, maxPixels) + if not images then + return nil, texNames :: string + end + local names = texNames :: { string } + for i, img in images do + table.insert(scene.textures, { name = names[i], image = img, uri = names[i] }) + local mat = Scene.material(names[i]) + mat.metallic = 0 + mat.baseColorTexture = { texture = i } + table.insert(scene.materials, mat) + end + local skinMap: { number } = {} + if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then + for r = 0, nSkinRef - 1 do + skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 + end + end + -- body parts + local totalVerts = 0 + for part = 0, nParts - 1 do + local po = base + oParts + part * 76 + local pname = str(b, po, 64) + local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72) + local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1 + if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then + local mo = base + oModels + (pick - 1) * 112 + local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76) + local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88) + local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100) + if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then + return nil, "body part " .. pname .. ": bad model tables" + end + local mesh: Types.Mesh = { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } } + for m = 0, nMesh - 1 do + local me = base + oMesh + m * 20 + local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8) + local tex = skinMap[skinref + 1] or (skinref + 1) + local img = images[tex] + local tw, th = if img then img.width else 1, if img then img.height else 1 + -- triangle commands + local weld: { [string]: number } = {} + local corners: { { number } } = {} + local indices: { number } = {} + local p = base + oTri + if oTri < 0 or oTri >= size then + return nil, "bad triangle command offset" + end + while true do + if p + 2 > limit then + return nil, "truncated triangle commands" + end + local n = readi16(b, p) + p += 2 + if n == 0 then + break + end + local fan = n < 0 + n = math.abs(n) + if p + n * 8 > limit then + return nil, "truncated triangle commands" + end + local ids: { number } = {} + for k = 0, n - 1 do + local o = p + k * 8 + local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6) + if vi >= nVerts or ni >= nNorms then + return nil, "triangle command vertex out of range" + end + local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t + local id = weld[key] + if not id then + table.insert(corners, { vi, ni, s, t }) + id = #corners - 1 + weld[key] = id + end + ids[k + 1] = id + end + p += n * 8 + for k = 3, n do + local a, c2, c3 + if fan then + a, c2, c3 = ids[1], ids[k - 1], ids[k] + elseif k % 2 == 1 then + a, c2, c3 = ids[k - 2], ids[k - 1], ids[k] + else + a, c2, c3 = ids[k - 1], ids[k - 2], ids[k] + end + -- studio models wind clockwise: reverse + table.insert(indices, c3) + table.insert(indices, c2) + table.insert(indices, a) + end + end + local nv = #corners + totalVerts += nv + if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for i, c in corners do + local o = (i - 1) * 12 + local bone = readu8(b, base + oVertInfo + c[1]) + local nbone = readu8(b, base + oNormInfo + c[2]) + local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12 + local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8) + local m4 = world[bone + 1] + if m4 then + x, y, z = Mat4.point(m4, x, y, z) + end + writef32(pos, o, x) + writef32(pos, o + 4, y) + writef32(pos, o + 8, z) + local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8) + local n4 = world[nbone + 1] + if n4 then + nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz + end + writef32(nrm, o, nx) + writef32(nrm, o + 4, ny) + writef32(nrm, o + 8, nz) + writef32(uv, (i - 1) * 8, c[3] / tw) + writef32(uv, (i - 1) * 8 + 4, c[4] / th) + writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1))) + writef32(wb, (i - 1) * 16, 1) + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if nBones > 0 then + attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv) + end + table.insert(mesh.primitives, { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles" :: any, + material = if img then tex else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = if nBones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + end + -- sequences + local seqs: { any } = {} + for s = 0, nSeq - 1 do + local so = base + oSeq + s * 176 + local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56) + local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156) + table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group }) + if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then + local rate = if fps > 0 then fps else 30 + local times: { number } = {} + for f = 0, nFrames - 1 do + times[f + 1] = f / rate + end + local tracks: { [number]: Rig.Track } = {} + for j = 1, nBones do + local bn = bones[j] + local ao = base + oAnim + (j - 1) * 12 + local tr, rot = {}, {} + for f = 0, nFrames - 1 do + local v: { number } = {} + for k = 0, 5 do + local off = readu16(b, ao + k * 2) + local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil + v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for k = 1, 4 do + table.insert(rot, q[k]) + end + end + tracks[j] = { translation = tr, rotation = rot } + end + Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR") + end + end + scene.meta.source = { + format = "mdl", + variant = "halflife", + name = root.name, + bones = nBones, + sequences = seqs, + textures = #images, + skinFamilies = nFamilies, + hitboxes = hdr(156), + attachments = hdr(212), + } + return scene, nil +end + +return HalfLife diff --git a/src/Formats/model/mdl/Quake.luau b/src/Formats/model/mdl/Quake.luau new file mode 100644 index 0000000..c13a77e --- /dev/null +++ b/src/Formats/model/mdl/Quake.luau @@ -0,0 +1,222 @@ +--!strict +-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et +-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. +-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; +-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per +-- side); simple and grouped frames become morph targets with one animation per frame-name group. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") +local Rig = require("@formats/codecs/model/Rig") + +local Quake = {} + +local Scene = Types.Scene +local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32 + +export type Options = { frame: number?, morph: boolean?, fps: number?, maxVertices: number?, maxPixels: number? } + +local function name16(b: buffer, at: number): string + return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string +end + +-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) +function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) + if size < 84 then + return nil, "truncated header" + end + local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) } + local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) } + local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56) + local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68) + if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then + return nil, "bad counts" + end + if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: skin too big" + end + if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local p = 84 + local function need(n: number): boolean + return n >= 0 and p + n <= size + end + -- skins + local pal = if palette then Pixels.palette(palette, 0, 256) else nil + local skins: { Types.Image } = {} + local px = sw * sh + for _ = 1, nSkins do + if not need(4) then + return nil, "truncated skins" + end + local group = readi32(b, base + p) + p += 4 + local count = 1 + if group ~= 0 then + if not need(4) then + return nil, "truncated skin group" + end + count = readi32(b, base + p) + p += 4 + if count <= 0 or count > 256 or not need(count * 4) then + return nil, "bad skin group" + end + p += count * 4 + end + if not need(count * px) then + return nil, "truncated skin pixels" + end + local img = Types.Image.new(sw, sh) + if pal then + Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal) + else + for i = 0, px - 1 do + local v = readu8(b, base + p + i) + writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101) + end + end + img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count } + table.insert(skins, img) + p += count * px + end + -- texture coordinates and triangles + if not need(nVerts * 12 + nTris * 16) then + return nil, "truncated vertices / triangles" + end + local stAt = p + p += nVerts * 12 + local weld: { [number]: number } = {} + local src: { number }, uvs: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + p + t * 16 + local front = readi32(b, o) ~= 0 + local c: { number } = {} + for k = 1, 3 do + local v = readi32(b, o + k * 4) + if v < 0 or v >= nVerts then + return nil, "triangle vertex out of range" + end + local so = base + stAt + v * 12 + local seam = readi32(b, so) ~= 0 and not front + local key = v * 2 + (if seam then 1 else 0) + local id = weld[key] + if not id then + table.insert(src, v) + local s = readi32(b, so + 4) + (if seam then sw / 2 else 0) + table.insert(uvs, (s + 0.5) / math.max(sw, 1)) + table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1)) + id = #src - 1 + weld[key] = id + end + c[k] = id + end + -- Quake's front faces are clockwise + table.insert(indices, c[3]) + table.insert(indices, c[2]) + table.insert(indices, c[1]) + end + p += nTris * 16 + -- frames: simple (type 0) or groups of simple frames + local frameAt: { number } = {} + local names: { string } = {} + local fsize = 24 + nVerts * 4 + for _ = 1, nFrames do + if not need(4) then + return nil, "truncated frames" + end + local kind = readi32(b, base + p) + p += 4 + if kind == 0 then + if not need(fsize) then + return nil, "truncated frame" + end + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + else + if not need(12) then + return nil, "truncated frame group" + end + local count = readi32(b, base + p) + if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then + return nil, "bad frame group" + end + p += 12 + count * 4 + for _ = 1, count do + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + end + end + end + local nv = #src + local total = #frameAt + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total) + local positions: { buffer }, normals: { buffer } = {}, {} + for f, at in frameAt do + if morph or f == want then + local pos = buffer.create(nv * 12) + local vo = base + at + 16 + for i, v in src do + for k = 0, 2 do + writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1]) + end + end + positions[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local uvb = buffer.create(nv * 8) + for i, v in uvs do + writef32(uvb, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(positions[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + for i, img in skins do + table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" :: any } }) + end + if #skins > 0 then + local mat = Scene.material("skin") + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + scene.materials[1] = mat + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + Rig.morph(prim, positions, normals) + scene.meshes[1].weights = table.create(total, 0) + local ranges: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)%d*$") or n + local last = ranges[#ranges] + if last and last.name == stem then + last.last = i + else + table.insert(ranges, { name = if stem ~= "" then stem else n, first = i, last = i, fps = opts and opts.fps or 10 }) + end + end + Rig.morphAnimation(scene, 1, total, ranges, "LINEAR") + end + scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil } + return scene, nil +end + +return Quake diff --git a/src/Formats/model/mdl/init.luau b/src/Formats/model/mdl/init.luau new file mode 100644 index 0000000..3dfd8f0 --- /dev/null +++ b/src/Formats/model/mdl/init.luau @@ -0,0 +1,98 @@ +--!strict +-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: +-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the +-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), +-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = +-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx +-- files) is UNSUPPORTED. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Quake = require("@formats/model/mdl/Quake") +local HalfLife = require("@formats/model/mdl/HalfLife") + +-- ------------------------------------------------------------------------------------------------ contract +local Mdl = { + name = "mdl", + category = "model", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey) + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + frame: number?, -- Quake: the frame used as the base POSITION (default 1) + morph: boolean?, -- Quake: frames as morph targets + animations (default true) + fps: number?, -- Quake: animation frame rate (default 10) + bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1) + textures: (buffer | string)?, -- Half-Life: the "t.mdl" texture file of a model without textures + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mdl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + local v = r:peekU8(4) + if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts: DecodeOptions?, uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, got = pcall(opts.resolve, uri) + v = if ok then got else nil + end + return Bytes.toBuffer(v) +end + +function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4) + local scene: Types.Scene?, msg: string? + if magic == "IDPO" then + if version ~= 6 then + return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4) + end + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else fetch(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Quake.decode(r.buf, r.base, size, pal, opts :: any) + elseif magic == "IDST" then + if version ~= 10 then + return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4) + end + local o: any = opts and table.clone(opts :: any) or {} + o.textures = if opts and opts.textures then Bytes.toBuffer(opts.textures) else nil + scene, msg = HalfLife.decode(r.buf, r.base, size, o) + else + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +return Mdl diff --git a/tests/model/_soup.luau b/tests/model/_soup.luau index 10c6d1e..ae41da3 100644 --- a/tests/model/_soup.luau +++ b/tests/model/_soup.luau @@ -20,15 +20,16 @@ function Soup.positions(prim: any, target: number?): buffer return out end --- uvs(prim, set?, flip?) -> { u, v, ... } of the corners in index order (flip: v -> 1 - v, assimp's convention) -function Soup.uvs(prim: any, set: number?, flip: boolean?): { number } +-- uvs(prim, set?, flip?) -> { u, v, ... } of the corners in index order (flip: v -> 1 - v, assimp's convention; +-- "neg": v -> -v, assimp's Half-Life loader) +function Soup.uvs(prim: any, set: number?, flip: (boolean | string)?): { number } local tc = Types.Scene.reader(prim.attributes["TEXCOORD_" .. (set or 0)]) :: any local idx = prim.indices local out = {} for k = 0, idx.count - 1 do local v = buffer.readu32(idx.data, k * 4) table.insert(out, tc(v, 0)) - table.insert(out, if flip then 1 - tc(v, 1) else tc(v, 1)) + table.insert(out, if flip == "neg" then -tc(v, 1) elseif flip then 1 - tc(v, 1) else tc(v, 1)) end return out end diff --git a/tests/model/mdl.luau b/tests/model/mdl.luau new file mode 100644 index 0000000..6371cd2 --- /dev/null +++ b/tests/model/mdl.luau @@ -0,0 +1,155 @@ +-- model/mdl tests: a Quake 1 and a Half-Life 1 model written by tools/fixtures/mdl.py. Quake: assimp's frame-0 +-- triangle soup (positions, texture coordinates), every frame exact, skins through opts.palette / opts.resolve / +-- the grey ramp, frame-name animations. Half-Life: assimp's bind-pose soup per mesh (positions, texture +-- coordinates), the bones' TRS, the skin, every sequence's animation values against the writer's, textures with +-- their palettes, the skin family. Errors and the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Mdl = require("@formats/model/mdl") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/mdl") + +local t = T.suite("mdl") +t:eq(Mdl.name, "mdl", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol then + return false + end + end + return true +end + +-- assimp mesh mi of a soup -> positions, uvs +local function assimpMesh(a: any, mi: number): ({ number }, { number }, number) + local m = a.per[mi] + local nextStart = if a.per[mi + 1] then a.per[mi + 1].start else a.faces + local nf = nextStart - m.start + return Soup.slice(a.pos, m.start * 9 + 1, nf * 9), Soup.slice(a.uv, m.start * 6 + 1, nf * 6), nf +end + +-- 1. Quake +do + local q = Fx.quake + local s, err = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { palette = q.palette }) + t:check(s, "quake: " .. tostring(err)) + t:eq(F.detect(q.data), "mdl", "quake: F.detect") + local prim = s.meshes[1].primitives[1] + local apos, auv = assimpMesh(q.assimp, 1) + t:check(Soup.triangles(Soup.list(Soup.positions(prim)), apos, 1e-5), "quake: positions against assimp") + t:check(Soup.triangles(Soup.uvs(prim, 0, true), auv, 1e-5, 2), "quake: texture coordinates against assimp") + t:check(Soup.close(Soup.uvs(prim, 0), q.uv, 1e-6), "quake: texture coordinates (seam) against the writer") + t:eq(#q.crcs, s.meta.source.frames, "quake: frames (groups unrolled)") + for k, crc in q.crcs do + local f = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { frame = k, morph = false, palette = q.palette }) :: any + t:eq(Crc32.of(Soup.positions(f.meshes[1].primitives[1])), crc, "quake: frame " .. k) + end + t:eq(#prim.targets, #q.crcs, "quake: morph targets") + local groups = {} + for _, a in s.animations do + table.insert(groups, a.name) + end + t:eq(table.concat(groups, ","), "stand,walk,death", "quake: animation groups") + t:eq(#s.textures, #q.skins, "quake: skins") + for i, crc in q.skins do + t:eq(Crc32.of(s.textures[i].image.pixels), crc, "quake: skin " .. i .. " through the palette") + end + local viaResolve = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { + resolve = function(uri: string): string? + return if uri == "gfx/palette.lmp" then q.palette else nil + end, + }) :: any + t:eq(Crc32.of(viaResolve.textures[1].image.pixels), q.skins[1], "quake: palette through opts.resolve") + local grey = Mdl.decode(Bytes.reader(buffer.fromstring(q.data))) :: any + t:eq(Crc32.of(grey.textures[1].image.pixels), q.grey, "quake: grey ramp without a palette") + t:eq(grey.meta.source.palette, false, "quake: meta.source.palette") +end + +-- 2. Half-Life +do + local h = Fx.halflife + local s, err = Mdl.decode(Bytes.reader(buffer.fromstring(h.data))) + t:check(s, "halflife: " .. tostring(err)) + t:eq(F.detect(h.data), "mdl", "halflife: F.detect") + local mesh = s.meshes[1] + t:eq(#mesh.primitives, #h.tris, "halflife: a primitive per mesh") + t:eq(h.assimp.meshes, #h.tris, "halflife: assimp meshes") + local matched = 0 + for mi = 1, h.assimp.meshes do + local apos, auv, nf = assimpMesh(h.assimp, mi) + for _, p in mesh.primitives do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-4) then + -- assimp's Half-Life loader stores v = -t / height + t:check(Soup.triangles(Soup.uvs(p, 0, "neg"), auv, 1e-5, 2), "halflife: texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #h.tris, "halflife: every mesh matches assimp's bind-pose positions") + for i, p in mesh.primitives do + t:eq(p.indices.count, h.tris[i] * 3, "halflife: mesh " .. i .. " triangles") + t:check(p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "halflife: skinned") + end + -- bones + local skin = s.skins[1] + t:eq(#skin.joints, #h.bones, "halflife: joints") + for i, bn in h.bones do + local node = s.nodes[skin.joints[i]] + t:eq(node.name, bn.name, "halflife: bone name " .. i) + t:check(near(node.translation, bn.t, 1e-6) and near(node.rotation, bn.q, 1e-6), "halflife: bone " .. bn.name .. " TRS") + end + -- animations + t:eq(#s.animations, #h.sequences, "halflife: sequences") + for si, sq in h.sequences do + local a = s.animations[si] + t:eq(a.name, sq.name, "halflife: sequence name") + local byNode = {} + for _, ch in a.channels do + byNode[ch.node .. ch.path] = ch + end + local ok = true + for bi, frames in sq.bones do + local node = skin.joints[bi] + local tch, rch = byNode[node .. "translation"], byNode[node .. "rotation"] + for f, fr in frames do + for k = 1, 3 do + ok = ok and math.abs(buffer.readf32(tch.output.data, ((f - 1) * 3 + k - 1) * 4) - fr.t[k]) < 1e-4 + end + for k = 1, 4 do + ok = ok and math.abs(buffer.readf32(rch.output.data, ((f - 1) * 4 + k - 1) * 4) - fr.q[k]) < 1e-5 + end + end + t:eq(tch.input.count, sq.frames, "halflife: " .. sq.name .. " keys") + t:check(math.abs(buffer.readf32(tch.input.data, 4) - 1 / sq.fps) < 1e-6, "halflife: " .. sq.name .. " fps") + end + t:check(ok, "halflife: " .. sq.name .. ": every value against the writer") + end + -- textures, skin family 0 + for i, tx in h.textures do + t:eq(s.textures[i].name, tx.name, "halflife: texture name") + t:eq(Crc32.of(s.textures[i].image.pixels), tx.crc, "halflife: texture " .. i .. " through its palette") + end + t:eq(mesh.primitives[1].material, 1, "halflife: mesh 1 -> skin ref 0 -> texture 1") + t:eq(mesh.primitives[2].material, 2, "halflife: mesh 2 -> skin ref 1 -> texture 2") +end + +-- 3. errors, fuzz +do + local _, e1 = Mdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.quake.data, 1, 200)))) + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "quake truncated: " .. tostring(e1)) + local _, e2 = Mdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.halflife.data, 1, 300)))) + t:check(e2 ~= nil, "halflife truncated: " .. tostring(e2)) + local src = buffer.fromstring(Fx.halflife.data) + buffer.writei32(src, 4, 48) + local _, e3 = Mdl.decode(Bytes.reader(src)) + t:check(e3 and e3.code == Err.UNSUPPORTED, "Source engine MDL") +end +t:fuzz("decode", function(b: buffer) + return Mdl.decode(Bytes.reader(b), { palette = Fx.quake.palette }) +end, { Fx.quake.data, Fx.halflife.data }, { mutations = 200 }) +t:done() diff --git a/tools/fixtures/mdl.py b/tools/fixtures/mdl.py new file mode 100644 index 0000000..bdaeaca --- /dev/null +++ b/tools/fixtures/mdl.py @@ -0,0 +1,261 @@ +# MDL fixtures (tools/fixtures.py). Quake 1 ("IDPO" 6) and Half-Life 1 ("IDST" 10) models written here from the +# Quake specs / studio.h layouts, with random data; references: assimp's triangle soup (frame 0 / bind pose: +# positions, texture coordinates; for Quake from a copy without the skin group, which assimp 6 misreads) and this writer's own exact values: +# quake: every frame's positions (CRC-32 of the f32 soup in our corner order), the skins through a test palette +# (CRC-32 of the RGBA pixels), frame names; +# halflife: bones (bind pose), body parts / meshes / triangle strips and fans, two textures with their own +# palettes and a skin family, two sequences with run-length coded animation values (the values per frame +# and bone, computed here). +# tests/gen/mdl.luau { quake = { ... }, halflife = { ... } } +import importlib.util, math, os, struct, zlib + +INPUTS = ["tools/fixtures/_quake_ref.py"] + + +def ref(ctx): + spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def f32(x): + return struct.unpack("