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

This commit is contained in:
4DBug committed 2026-10-31 14:41:33 -05:00
1 parent 50eb827897
commit f14d5ac4ef
9 files changed
+1105 -6

No files matched your search

+12
View File
@@ -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",
+12 -3
View File
@@ -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
+340
View File
@@ -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 "<name>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
+222
View File
@@ -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
+98
View File
@@ -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 "<name>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