Files

262 lines
12 KiB
Python

# 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})