ws-game: model/md3 (Quake III MD3 -> Scene: surfaces as primitives, frames as morph targets, tags as nodes with channels, shaders as URIs)

This commit is contained in:
4DBug committed 2026-10-31 14:32:47 -05:00
1 parent 897a386c4f
commit 50eb827897
7 files changed
+500 -3

No files matched your search

+12
View File
@@ -422,6 +422,18 @@ local list: { Entry } = {
return require("@formats/model/md2")
end,
},
{
name = "md3",
category = "model",
path = "model/md3",
extensions = { "md3" },
mime = { "model/x-md3" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, morph = true, animation = true, tags = true },
load = function()
return require("@formats/model/md3")
end,
},
{
name = "obj",
category = "model",
+234
View File
@@ -0,0 +1,234 @@
--!strict
-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format
-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format"
-- notes (PhaethonH); no code taken.
-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame
-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left
-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all
-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes
-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation).
-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }.
-- Not supported: writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Rig = require("@formats/codecs/model/Rig")
-- ------------------------------------------------------------------------------------------------ contract
local Md3 = {
name = "md3",
category = "model",
extensions = { "md3" },
mime = { "model/x-md3" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, morph = true, animation = true, tags = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1)
morph: boolean?, -- every frame as a morph target + the animation (default true)
fps: number?, -- animation frame rate (default 15)
maxVertices: number?, -- frames x vertices over all surfaces (default 2^24)
}
-- ------------------------------------------------------------------------------------------------ constants
local Scene = Types.Scene
local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32
local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal)
-- ------------------------------------------------------------------------------------------------ sniff
function Md3.sniff(r: Bytes.Reader): number
if r:remaining() < 108 then
return 0
end
return if Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
end
function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local size = r.limit - r.base
if size < 108 then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
if not r:match("IDP3") then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local version = r:i32le()
if version ~= 15 then
return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4)
end
local b, base = r.buf, r.base
local name = cstr(b, base + 8, 64)
r:skip(68)
local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le()
local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le()
if r.err then
return nil, r.err
end
if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then
return nil, Err.new(Err.CORRUPT, "bad counts", 76)
end
local function inside(o: number, n: number): boolean
return o >= 0 and n >= 0 and o + n <= size
end
if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then
return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88)
end
local morph = not (opts and opts.morph == false)
local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames)
local maxV = opts and opts.maxVertices or 2 ^ 24
local scene = Scene.new()
scene.meta.up = "z"
local mesh: Types.Mesh = { name = if name ~= "" then name else nil, primitives = {} }
scene.meshes[1] = mesh
scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 }
scene.roots[1] = 1
local total = 0
local so = oSurf
for s = 1, nSurf do
if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so)
end
local p = base + so
local sname = cstr(b, p + 4, 64)
local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84)
local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104)
if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72)
end
total += nVerts * nFrames
if total > maxV then
return nil, Err.new(Err.LIMIT, "too many vertices")
end
if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then
return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so)
end
local ib = buffer.create(nTris * 12)
local idx = table.create(nTris * 3, 0) :: { number }
for t = 0, nTris - 1 do
for c = 0, 2 do
local v = readi32(b, p + oTri + t * 12 + c * 4)
if v < 0 or v >= nVerts then
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12)
end
idx[t * 3 + 3 - c] = v
end
end
for i, v in idx do
writeu32(ib, (i - 1) * 4, v)
end
local uv = buffer.create(nVerts * 8)
buffer.copy(uv, 0, b, p + oSt, nVerts * 8)
local frames: { buffer }, normals: { buffer } = {}, {}
for f = 1, nFrames do
if morph or f == want then
local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12)
local q = p + oXyz + (f - 1) * nVerts * 8
for v = 0, nVerts - 1 do
local o = q + v * 8
writef32(pos, v * 12, readi16(b, o) / 64)
writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64)
writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64)
local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K
writef32(nrm, v * 12, math.cos(lat) * math.sin(lng))
writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng))
writef32(nrm, v * 12 + 8, math.cos(lng))
end
frames[f], normals[f] = pos, nrm
end
end
local prim: Types.Primitive = {
attributes = {
POSITION = Scene.accessor(frames[want], "f32", 3, nVerts),
NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts),
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts),
},
indices = Scene.accessor(ib, "u32", 1, nTris * 3),
mode = "triangles",
extras = { md3 = { surface = sname } },
}
if morph then
Rig.morph(prim, frames, normals)
end
local shaders: { string } = {}
for k = 0, nShaders - 1 do
table.insert(shaders, cstr(b, p + oSh + k * 68, 64))
end
local mat = Scene.material(sname)
mat.metallic = 0
if shaders[1] and shaders[1] ~= "" then
table.insert(scene.textures, { name = shaders[1], uri = shaders[1] })
mat.baseColorTexture = { texture = #scene.textures }
end
mat.extras = { md3 = { shaders = shaders } }
table.insert(scene.materials, mat)
prim.material = #scene.materials
table.insert(mesh.primitives, prim)
so += oEnd
end
-- frames and tags
local frameNames: { string } = {}
for f = 0, nFrames - 1 do
frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16)
end
local tagNodes: { number } = {}
local tracks: { [number]: Rig.Track } = {}
local tagNames: { string } = {}
for k = 0, nTags - 1 do
local tr: Rig.Track = { translation = {}, rotation = {} }
local first: any = nil
for f = 0, nFrames - 1 do
local o = base + oTags + (f * nTags + k) * 112
local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) }
local a: { number } = {}
for i = 0, 8 do
a[i + 1] = readf32(b, o + 76 + i * 4)
end
local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 }
local q = Mat4.quat(m)
for c = 1, 3 do
table.insert(tr.translation :: { number }, t[c])
end
for c = 1, 4 do
table.insert(tr.rotation :: { number }, q[c])
end
if f == want - 1 then
first = { name = cstr(b, o, 64), t = t, q = q }
end
end
table.insert(tagNames, first.name)
table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } })
table.insert(scene.nodes[1].children, #scene.nodes)
tagNodes[k + 1] = #scene.nodes
tracks[k + 1] = tr
end
if morph and nFrames > 1 then
scene.meshes[1].weights = table.create(nFrames, 0)
local fps = opts and opts.fps or 15
Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR")
if nTags > 0 then
local times: { number } = {}
for f = 1, nFrames do
times[f] = (f - 1) / fps
end
local ai = Rig.animation(scene, "tags", tagNodes, times, tracks)
local tagAnim = table.remove(scene.animations, ai) :: Types.Animation
for _, ch in tagAnim.channels do
table.insert(scene.animations[1].channels, ch)
end
end
end
scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames }
return scene, nil
end
return Md3