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

+1
View File
@@ -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` |
+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
+4 -3
View File
@@ -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
+155
View File
@@ -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()
+261
View File
@@ -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("<f", struct.pack("<f", x))[0]
def palette(rng):
return bytes(rng.randrange(256) for _ in range(768))
def rgba(pix, pal):
return b"".join(pal[i * 3:i * 3 + 3] + b"\xff" for i in pix)
# ------------------------------------------------------------------------------------------------ Quake 1
def quake(rng, pal, nverts=24, ntris=30, sw=32, sh=16, frames=("stand1", "stand2", "walk1", "walk2", "walk3"), group=("death1", "death2")):
scale = tuple(f32(rng.uniform(0.05, 0.3)) for _ in range(3))
origin = tuple(f32(rng.uniform(-20, 20)) for _ in range(3))
nframes = len(frames) + (1 if group else 0)
out = struct.pack("<4si3f3ff3fiiiiiiiif", b"IDPO", 6, *scale, *origin, 10.0, 0, 0, 0, 2, sw, sh, nverts, ntris, nframes, 0, 0, 1.0)
skins = []
s1 = bytes(rng.randrange(256) for _ in range(sw * sh))
out += struct.pack("<i", 0) + s1
skins.append(s1)
s2 = [bytes(rng.randrange(256) for _ in range(sw * sh)) for _ in range(2)]
out += struct.pack("<ii2f", 1, 2, 0.1, 0.2) + s2[0] + s2[1]
skins.append(s2[0])
st = [(rng.randrange(2), rng.randrange(sw // 2), rng.randrange(sh)) for _ in range(nverts)]
for s in st:
out += struct.pack("<3i", *s)
tris = [(rng.randrange(2), tuple(rng.sample(range(nverts), 3))) for _ in range(ntris)]
for front, v in tris:
out += struct.pack("<4i", front, *v)
allframes = []
def simple(name):
vs = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(162)) for _ in range(nverts)]
allframes.append((name, vs))
return bytes(4) + bytes(4) + name.encode().ljust(16, b"\0") + b"".join(bytes(v) for v in vs)
for f in frames:
out += struct.pack("<i", 0) + simple(f)
if group:
out += struct.pack("<ii", 1, len(group)) + bytes(8) + struct.pack("<%df" % len(group), *[0.1] * len(group))
for f in group:
out += simple(f)
crcs = []
for name, vs in allframes:
soup = b""
for front, v in tris:
for c in (2, 1, 0):
p = vs[v[c]]
soup += struct.pack("<3f", *(p[k] * scale[k] + origin[k] for k in range(3)))
crcs.append(zlib.crc32(soup))
uv = []
for front, v in tris:
for c in (2, 1, 0):
onseam, s, t = st[v[c]]
if onseam and not front:
s += sw / 2
uv += [f32((s + 0.5) / sw), f32((t + 0.5) / sh)]
# assimp 6 misreads skin groups (the intervals): its reference copy has the first skin only
plain = bytearray(out[:84 + 4 + sw * sh] + out[84 + 4 + sw * sh + 16 + 2 * sw * sh:])
struct.pack_into("<i", plain, 48, 1)
return out, {"plain": bytes(plain), "crcs": crcs, "names": [n for n, _ in allframes], "skins": [zlib.crc32(rgba(s, pal)) for s in skins],
"grey": zlib.crc32(b"".join(bytes([i, i, i, 255]) for i in skins[0])), "tris": ntris, "uv": uv}
# ------------------------------------------------------------------------------------------------ Half-Life 1
def angle_quat(x, y, z):
sy, cy = math.sin(z / 2), math.cos(z / 2)
sp, cp = math.sin(y / 2), math.cos(y / 2)
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)
def rle(values):
# mstudioanimvalue runs: (valid, total) then `valid` values; a run repeats its last value for total - valid frames
out, i = b"", 0
while i < len(values):
j = i + 1
while j < len(values) and j - i < 4 and values[j] != values[j - 1]:
j += 1
run = values[i:j]
k = j
while k < len(values) and values[k] == run[-1] and k - i < 250:
k += 1
out += bytes([len(run), k - i]) + struct.pack("<%dh" % len(run), *run)
i = k
return out
def halflife(rng):
bones = [("root", -1, [0.0, 0.0, 10.0, 0.0, 0.0, 0.3]), ("spine", 0, [5.0, 0.0, 0.0, 0.2, 0.1, 0.0]),
("head", 1, [0.0, 4.0, 1.0, 0.0, 0.5, -0.2])]
scales = [f32(rng.uniform(0.001, 0.01)) for _ in range(6)]
nb = len(bones)
# geometry: verts in bone space
nverts, nnorms = 12, 12
verts = [tuple(f32(rng.uniform(-8, 8)) for _ in range(3)) for _ in range(nverts)]
vbone = [rng.randrange(nb) for _ in range(nverts)]
norms = []
for _ in range(nnorms):
v = [rng.uniform(-1, 1) for _ in range(3)]
l = math.sqrt(sum(c * c for c in v))
norms.append(tuple(f32(c / l) for c in v))
nbone = [rng.randrange(nb) for _ in range(nnorms)]
texs = [("skin_a.bmp", 16, 8), ("skin_b.bmp", 8, 8)]
# two meshes: a strip of 5 and a fan of 4 (+ a strip of 3) per mesh, texels per corner
def cmds(tw, th):
out, corners = b"", []
for kind, n in (("strip", 5), ("fan", 4), ("strip", 3)):
vs = [(rng.randrange(nverts), rng.randrange(nnorms), rng.randrange(tw), rng.randrange(th)) for _ in range(n)]
out += struct.pack("<h", n if kind == "strip" else -n) + b"".join(struct.pack("<4h", *v) for v in vs)
corners.append((kind, vs))
return out + struct.pack("<h", 0), corners
meshes = [cmds(16, 8) + (0,), cmds(8, 8) + (1,)]
seqs = [("idle", 10.0, 6), ("walk", 15.0, 9)]
# anim values per sequence, bone, channel
animvals = []
for name, fps, nf in seqs:
per = []
for bi in range(nb):
ch = []
for k in range(6):
if rng.random() < 0.3:
ch.append(None) # offset 0: the bone default
else:
ch.append([rng.randrange(-300, 300) if rng.random() < 0.6 or f == 0 else None for f in range(nf)])
for f in range(1, nf):
if ch[-1][f] is None:
ch[-1][f] = ch[-1][f - 1]
per.append(ch)
animvals.append(per)
# --- layout
hdr = 244
o_bones = hdr
o_seq = o_bones + 112 * nb
o_anim = o_seq + 176 * len(seqs)
anim_blobs, anim_offsets = b"", []
for per in animvals:
anim_offsets.append(o_anim + len(anim_blobs))
table = bytearray(12 * nb)
data = b""
for bi, ch in enumerate(per):
for k, vals in enumerate(ch):
if vals is None:
continue
off = 12 * nb - 12 * bi + len(data) # from this bone's mstudioanim_t
struct.pack_into("<H", table, bi * 12 + k * 2, off)
data += rle(vals)
anim_blobs += bytes(table) + data
if len(anim_blobs) % 2:
anim_blobs += b"\0"
o_groups = o_anim + len(anim_blobs)
o_parts = o_groups + 104
o_models = o_parts + 76
o_meshes = o_models + 112
o_vinfo = o_meshes + 20 * len(meshes)
o_ninfo = o_vinfo + nverts
o_verts = (o_ninfo + nnorms + 3) // 4 * 4
o_norms = o_verts + 12 * nverts
o_cmds = o_norms + 12 * nnorms
cmd_offsets, cmd_blob = [], b""
for c, corners, tex in meshes:
cmd_offsets.append(o_cmds + len(cmd_blob))
cmd_blob += c
o_tex = o_cmds + len(cmd_blob)
o_skin = o_tex + 80 * len(texs)
o_texdata = o_skin + 2 * 2 * 2 # 2 families x 2 refs
tex_blob, tex_offsets, tex_pix = b"", [], []
for name, w, h in texs:
tex_offsets.append(o_texdata + len(tex_blob))
pix = bytes(rng.randrange(256) for _ in range(w * h))
pal = palette(rng)
tex_blob += pix + pal
tex_pix.append(zlib.crc32(rgba(pix, pal)))
length = o_texdata + len(tex_blob)
out = bytearray(length)
struct.pack_into("<4si64si", out, 0, b"IDST", 10, b"test/model.mdl", length)
struct.pack_into("<ii", out, 140, nb, o_bones)
struct.pack_into("<ii", out, 164, len(seqs), o_seq)
struct.pack_into("<iii", out, 180, len(texs), o_tex, o_texdata)
struct.pack_into("<iii", out, 192, 2, 2, o_skin)
struct.pack_into("<ii", out, 204, 1, o_parts)
struct.pack_into("<ii", out, 172, 1, o_groups)
struct.pack_into("<32s64sii", out, o_groups, b"default", b"", 0, 0)
for i, (name, parent, value) in enumerate(bones):
struct.pack_into("<32sii6i6f6f", out, o_bones + 112 * i, name.encode(), parent, 0, *([-1] * 6), *value, *scales)
for i, (name, fps, nf) in enumerate(seqs):
o = o_seq + 176 * i
struct.pack_into("<32sf", out, o, name.encode(), fps)
struct.pack_into("<i", out, o + 56, nf)
struct.pack_into("<ii", out, o + 120, 1, anim_offsets[i])
struct.pack_into("<i", out, o + 156, 0)
out[o_anim:o_anim + len(anim_blobs)] = anim_blobs
struct.pack_into("<64siii", out, o_parts, b"body", 1, 0, o_models)
struct.pack_into("<64sif10i", out, o_models, b"body_ref", 0, 20.0, len(meshes), o_meshes, nverts, o_vinfo, o_verts, nnorms, o_ninfo, o_norms, 0, 0)
for i, (c, corners, tex) in enumerate(meshes):
ntris = sum(n - 2 for kind, vs in corners for n in [len(vs)])
struct.pack_into("<5i", out, o_meshes + 20 * i, ntris, cmd_offsets[i], tex, 0, 0)
out[o_vinfo:o_vinfo + nverts] = bytes(vbone)
out[o_ninfo:o_ninfo + nnorms] = bytes(nbone)
for i, v in enumerate(verts):
struct.pack_into("<3f", out, o_verts + 12 * i, *v)
for i, n in enumerate(norms):
struct.pack_into("<3f", out, o_norms + 12 * i, *n)
out[o_cmds:o_cmds + len(cmd_blob)] = cmd_blob
for i, (name, w, h) in enumerate(texs):
struct.pack_into("<64siiii", out, o_tex + 80 * i, name.encode(), 0, w, h, tex_offsets[i])
# skin families: family 0 = (0, 1), family 1 = (1, 0)
struct.pack_into("<4h", out, o_skin, 0, 1, 1, 0)
out[o_texdata:] = tex_blob
# expected animation values: bone default + value * scale
expect = []
for si, (name, fps, nf) in enumerate(seqs):
per = []
for bi, (bname, parent, value) in enumerate(bones):
frames = []
for f in range(nf):
v = []
for k in range(6):
vals = animvals[si][bi][k]
v.append(value[k] + (vals[f] if vals else 0) * scales[k])
frames.append({"t": v[:3], "q": list(angle_quat(*v[3:]))})
per.append(frames)
expect.append({"name": name, "fps": fps, "frames": nf, "bones": per})
ntris = [sum(len(vs) - 2 for kind, vs in corners) for c, corners, tex in meshes]
return bytes(out), {"bones": [{"name": n, "parent": p + 1, "t": v[:3], "q": list(angle_quat(*v[3:]))} for n, p, v in bones],
"sequences": expect, "textures": [{"name": n, "width": w, "height": h, "crc": tex_pix[i]} for i, (n, w, h) in enumerate(texs)],
"tris": ntris}
def generate(ctx):
rng = ctx.rng(71)
R = ref(ctx)
pal = palette(rng)
qdata, qinfo = quake(rng, pal)
qinfo.update({"data": qdata, "palette": pal, "assimp": R.assimp_soup(ctx, qinfo.pop("plain"), "mdl")})
hdata, hinfo = halflife(rng)
hinfo.update({"data": hdata, "assimp": R.assimp_soup(ctx, hdata, "mdl")})
ctx.emit("mdl", {"quake": qinfo, "halflife": hinfo})