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:
1 parent
897a386c4f
commit
50eb827897
7 files changed
+500
-3
No files matched your search
@@ -39,6 +39,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| 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 | 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` |
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
@@ -48,4 +48,51 @@ function Soup.close(a: any, b: { number }, tol: number): (boolean, number?)
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- triangles(a, b, tol, stride?) -> true when the triangle lists a and b (flat numbers, stride per corner: 3 for
|
||||
-- positions, 2 for texture coordinates) hold the same triangles in the same order, each up to a cyclic rotation of
|
||||
-- its corners (assimp rotates them); false, the first differing triangle otherwise
|
||||
function Soup.triangles(a: { number }, b: { number }, tol: number, stride: number?): (boolean, number?)
|
||||
local s = stride or 3
|
||||
if #a ~= #b then
|
||||
return false, -1
|
||||
end
|
||||
local per = 3 * s
|
||||
for t = 0, #a // per - 1 do
|
||||
local found = false
|
||||
for rot = 0, 2 do
|
||||
local same = true
|
||||
for c = 0, 2 do
|
||||
local ca, cb = t * per + c * s, t * per + ((c + rot) % 3) * s
|
||||
for k = 1, s do
|
||||
if math.abs(a[ca + k] - b[cb + k]) > tol * math.max(1, math.abs(b[cb + k])) then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
end
|
||||
if same then
|
||||
found = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not found then
|
||||
return false, t
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- list(buf) -> the f32 values of a buffer as numbers
|
||||
function Soup.list(b: buffer): { number }
|
||||
local out = table.create(buffer.len(b) // 4)
|
||||
for i = 0, buffer.len(b) // 4 - 1 do
|
||||
out[i + 1] = buffer.readf32(b, i * 4)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- slice(list, from, n) -> n values from index from (1-based)
|
||||
function Soup.slice(list: { number }, from: number, n: number): { number }
|
||||
return table.move(list, from, from + n - 1, 1, table.create(n))
|
||||
end
|
||||
|
||||
return Soup
|
||||
@@ -0,0 +1,109 @@
|
||||
-- model/md3 tests: MD3 files written by tools/fixtures/md3.py (several surfaces, frames, tags) decode to assimp's
|
||||
-- frame-0 triangle soup (every surface: positions, texture coordinates) and to the writer's exact positions and
|
||||
-- normals for every frame, shaders as texture URIs, tags as nodes with their per-frame channels, errors, the fuzz
|
||||
-- pass.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Md3 = require("@formats/model/md3")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Soup = require("@tests/model/_soup")
|
||||
local Fx = require("@tests/gen/md3")
|
||||
|
||||
local t = T.suite("md3")
|
||||
t:eq(Md3.name, "md3", "name")
|
||||
|
||||
local function normals(prim: any): buffer
|
||||
local n = Types.Scene.reader(prim.attributes.NORMAL) :: any
|
||||
local idx = prim.indices
|
||||
local out = buffer.create(idx.count * 12)
|
||||
for k = 0, idx.count - 1 do
|
||||
local v = buffer.readu32(idx.data, k * 4)
|
||||
for c = 0, 2 do
|
||||
buffer.writef32(out, k * 12 + c * 4, n(v, c))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local s, err = Md3.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(s, c.name .. ": " .. tostring(err))
|
||||
t:eq(F.detect(c.data), "md3", c.name .. ": F.detect")
|
||||
local prims = s.meshes[1].primitives
|
||||
t:eq(#prims, #c.surfaces, c.name .. ": a primitive per surface")
|
||||
-- assimp: every surface's frame 0 (assimp orders the meshes differently and rotates triangle corners: match each
|
||||
-- assimp mesh to the surface whose triangles it holds)
|
||||
t:eq(c.assimp.meshes, #c.surfaces, c.name .. ": assimp meshes")
|
||||
local matched = 0
|
||||
for mi, m in c.assimp.per do
|
||||
local nextStart = if c.assimp.per[mi + 1] then c.assimp.per[mi + 1].start else c.assimp.faces
|
||||
local nf = nextStart - m.start
|
||||
local apos = Soup.slice(c.assimp.pos, m.start * 9 + 1, nf * 9)
|
||||
local auv = Soup.slice(c.assimp.uv, m.start * 6 + 1, nf * 6)
|
||||
for _, p in prims do
|
||||
if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-5) then
|
||||
t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), c.name .. ": texture coordinates against assimp")
|
||||
matched += 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(matched, #c.surfaces, c.name .. ": every surface matches assimp's positions")
|
||||
for si, w in c.surfaces do
|
||||
t:eq(Crc32.of(Soup.positions(prims[si])), w.crcs[1], c.name .. ": " .. w.name .. " frame 1")
|
||||
t:eq(s.textures[s.materials[prims[si].material].baseColorTexture.texture].uri, w.shader, c.name .. ": shader")
|
||||
for k = 1, c.frames do
|
||||
local fs = Md3.decode(Bytes.reader(buffer.fromstring(c.data)), { frame = k, morph = false }) :: any
|
||||
local fp = fs.meshes[1].primitives[si]
|
||||
t:eq(Crc32.of(Soup.positions(fp)), w.crcs[k], c.name .. ": " .. w.name .. " frame " .. k)
|
||||
local nb = normals(fp)
|
||||
-- normals are computed in double then stored as f32: compare by CRC of the fixture's f32 values
|
||||
t:eq(Crc32.of(nb), w.ncrcs[k], c.name .. ": " .. w.name .. " normals frame " .. k)
|
||||
end
|
||||
if c.frames > 1 then
|
||||
t:eq(#prims[si].targets, c.frames, c.name .. ": morph targets")
|
||||
end
|
||||
end
|
||||
-- tags
|
||||
local ntags = #c.tags // c.frames
|
||||
t:eq(#s.meta.source.tags, ntags, c.name .. ": tags")
|
||||
for _, tg in c.tags do
|
||||
if tg.frame == 1 then
|
||||
local node
|
||||
for _, n in s.nodes do
|
||||
if n.name == tg.name then
|
||||
node = n
|
||||
end
|
||||
end
|
||||
t:check(node and math.abs(node.translation[1] - tg.origin[1]) < 1e-6, c.name .. ": tag " .. tg.name .. " origin")
|
||||
-- the rotation about z by angle
|
||||
t:check(node and math.abs(node.rotation[3] - math.sin(tg.angle / 2)) < 1e-5, c.name .. ": tag " .. tg.name .. " rotation")
|
||||
end
|
||||
end
|
||||
if c.frames > 1 then
|
||||
t:eq(#s.animations, 1, c.name .. ": one animation")
|
||||
t:eq(#s.animations[1].channels, 1 + 2 * ntags, c.name .. ": weights + tag channels")
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local c = Fx[1]
|
||||
local _, e1 = Md3.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 500))))
|
||||
t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "truncated: " .. tostring(e1))
|
||||
local bad = buffer.fromstring(c.data)
|
||||
buffer.writei32(bad, 4, 14)
|
||||
local _, e2 = Md3.decode(Bytes.reader(bad))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 14")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Md3.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 80 })
|
||||
t:done()
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shared helpers for the Quake-family model fixtures (md2.py, md3.py, mdl.py): assimp's triangle soup.
|
||||
# assimp_soup(ctx, data, ext) -> { pos = [floats], uv = [floats], meshes, faces } | { failed = True }: every triangle
|
||||
# mesh of `assimp export -f assjson`, faces in order, each face's corners in assimp's index order (positions x3,
|
||||
# texture coordinates u, v of set 0)
|
||||
# texture coordinates u, v of set 0); per = [ { name, start } ]: each mesh's name and first face
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
|
||||
@@ -18,11 +18,12 @@ def assimp_soup(ctx, data, ext):
|
||||
j = json.load(open(out))
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
pos, uv, faces, meshes = [], [], 0, 0
|
||||
pos, uv, faces, meshes, per = [], [], 0, 0, []
|
||||
for m in j.get("meshes", []):
|
||||
if m.get("primitivetypes") != 4:
|
||||
continue
|
||||
meshes += 1
|
||||
per.append({"name": m.get("name", ""), "start": faces})
|
||||
v = m["vertices"]
|
||||
t = (m.get("texturecoords") or [[]])[0]
|
||||
nc = (m.get("numuvcomponents") or [2])[0]
|
||||
@@ -32,4 +33,4 @@ def assimp_soup(ctx, data, ext):
|
||||
pos += v[i * 3:i * 3 + 3]
|
||||
if t:
|
||||
uv += t[i * nc:i * nc + 2]
|
||||
return {"pos": pos, "uv": uv, "faces": faces, "meshes": meshes}
|
||||
return {"pos": pos, "uv": uv, "faces": faces, "meshes": meshes, "per": per}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Quake III MD3 fixtures (tools/fixtures.py): MD3 files written here from the md3Header_t / md3Surface_t layout
|
||||
# (several surfaces with shaders, frames of 1/64-unit i16 positions with lat / long normals, tags per frame);
|
||||
# references: assimp's triangle soup of frame 0 (every surface: positions, texture coordinates) and this writer's
|
||||
# exact positions and decoded normals of every frame (CRC-32 of the f32 soup in our corner order), tag origins.
|
||||
# tests/gen/md3.luau { { name, data, frames, surfaces = { { name, shader, tris, crcs, ncrcs } }, tags = { ... },
|
||||
# assimp = { pos, uv, meshes } } }
|
||||
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 normal(n):
|
||||
lat = ((n >> 8) & 255) * math.pi / 128
|
||||
lng = (n & 255) * math.pi / 128
|
||||
return (math.cos(lat) * math.sin(lng), math.sin(lat) * math.sin(lng), math.cos(lng))
|
||||
|
||||
|
||||
def surface(rng, name, shader, nframes, nverts, ntris):
|
||||
tris = [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris)]
|
||||
st = [(f32(rng.uniform(0, 1)), f32(rng.uniform(0, 1))) for _ in range(nverts)]
|
||||
xyz = [[(rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(65536)) for _ in range(nverts)] for _ in range(nframes)]
|
||||
o_tri = 108
|
||||
o_sh = o_tri + 12 * ntris
|
||||
o_st = o_sh + 68
|
||||
o_xyz = o_st + 8 * nverts
|
||||
o_end = o_xyz + 8 * nverts * nframes
|
||||
out = struct.pack("<4s64siiiiiiiiii", b"IDP3", name.encode(), 0, nframes, 1, nverts, ntris, o_tri, o_sh, o_st, o_xyz, o_end)
|
||||
for t in tris:
|
||||
out += struct.pack("<3i", *t)
|
||||
out += struct.pack("<64si", shader.encode(), 0)
|
||||
for s in st:
|
||||
out += struct.pack("<2f", *s)
|
||||
for f in xyz:
|
||||
for x, y, z, n in f:
|
||||
out += struct.pack("<3hH", x, y, z, n)
|
||||
crcs, ncrcs = [], []
|
||||
for f in xyz:
|
||||
soup, nsoup = b"", b""
|
||||
for t in tris:
|
||||
for c in (2, 1, 0):
|
||||
x, y, z, n = f[t[c]]
|
||||
soup += struct.pack("<3f", x / 64, y / 64, z / 64)
|
||||
nsoup += struct.pack("<3f", *normal(n))
|
||||
crcs.append(zlib.crc32(soup))
|
||||
ncrcs.append(zlib.crc32(nsoup))
|
||||
return out, {"name": name, "shader": shader, "tris": ntris, "crcs": crcs, "ncrcs": ncrcs}
|
||||
|
||||
|
||||
def md3(rng, nframes, surfs, ntags):
|
||||
frames = b""
|
||||
for i in range(nframes):
|
||||
frames += struct.pack("<10f16s", *([0.0] * 10), b"frame%d" % i)
|
||||
tags, tagref = b"", []
|
||||
for f in range(nframes):
|
||||
for k in range(ntags):
|
||||
o = tuple(f32(rng.uniform(-10, 10)) for _ in range(3))
|
||||
ang = rng.uniform(0, math.pi)
|
||||
ax = ((math.cos(ang), math.sin(ang), 0.0), (-math.sin(ang), math.cos(ang), 0.0), (0.0, 0.0, 1.0))
|
||||
tags += struct.pack("<64s12f", b"tag_%d" % k, *o, *[c for a in ax for c in a])
|
||||
tagref.append({"name": "tag_%d" % k, "frame": f + 1, "origin": list(o), "angle": ang})
|
||||
body, info = b"", []
|
||||
for args in surfs:
|
||||
s, i = surface(rng, args[0], args[1], nframes, args[2], args[3])
|
||||
body += s
|
||||
info.append(i)
|
||||
o_frames = 108
|
||||
o_tags = o_frames + len(frames)
|
||||
o_surf = o_tags + len(tags)
|
||||
o_end = o_surf + len(body)
|
||||
head = struct.pack("<4si64siiiiiiiii", b"IDP3", 15, b"models/test/test.md3", 0, nframes, ntags, len(surfs), 0, o_frames, o_tags, o_surf, o_end)
|
||||
return head + frames + tags + body, info, tagref
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(63)
|
||||
R = ref(ctx)
|
||||
out = []
|
||||
for name, nframes, surfs, ntags in [("two-surfaces", 4, [("body", "models/test/body.tga", 30, 40), ("head", "models/test/head", 12, 10)], 2),
|
||||
("one-frame", 1, [("s", "textures/x.tga", 8, 6)], 0)]:
|
||||
data, info, tags = md3(rng, nframes, surfs, ntags)
|
||||
out.append({"name": name, "data": data, "frames": nframes, "surfaces": info, "tags": tags, "assimp": R.assimp_soup(ctx, data, "md3")})
|
||||
ctx.emit("md3", out)
|
||||
Reference in new issue
Block a user