diff --git a/docs/FORMATS.md b/docs/FORMATS.md index a4a82dd..185c694 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -88,7 +88,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | | model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | | model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` | -| model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | **missing** | +| model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | `tests/model/sourcemdl.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | diff --git a/src/Rosetta/model/sourcemdl/Build.luau b/src/Rosetta/model/sourcemdl/Build.luau index 2189900..c587185 100644 --- a/src/Rosetta/model/sourcemdl/Build.luau +++ b/src/Rosetta/model/sourcemdl/Build.luau @@ -417,6 +417,7 @@ function Build.scene(h: Mdl.Header, b: buffer, base: number, size: number, inp: nodes = h.nodes, rootLod = h.rootLod, lods = if vtx then vtx.lods else 0, + lodVertices = if vvd then vvd.lodCounts else nil, lodReplacements = if vtx then vtx.replacements else nil, physics = phy, warnings = inp.warnings, diff --git a/tests/model/sourcemdl.luau b/tests/model/sourcemdl.luau new file mode 100644 index 0000000..e6f23a2 --- /dev/null +++ b/tests/model/sourcemdl.luau @@ -0,0 +1,285 @@ +-- model/sourcemdl tests: generated MDL v44 / v48 / v49 + VVD / VTX / PHY / ANI against the writer's exact values and +-- srctools' reading of the same files. Fixtures: tools/fixtures/sourcemdl.py. +local T = require("@tests/T") +local F = require("@rosetta") +local SourceMdl = require("@rosetta/model/sourcemdl") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/sourcemdl") + +local t = T.suite("sourcemdl") +t:eq(SourceMdl.name, "sourcemdl", "name") +t:eq(SourceMdl.category, "model", "category") + +local function floats(acc: any): { number } + local rd = Types.Scene.reader(acc) :: any + local out = {} + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + table.insert(out, rd(i, c)) + end + end + return out +end + +local function near(a: { number }, b: { number }, tol: number): boolean + if #a ~= #b then + return false + end + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol then + return false + end + end + return true +end + +local function decode(c: any, extra: { [string]: any }?): (any, any) + local o: { [string]: any } = { files = c.files } + for k, v in extra or {} do + o[k] = v + end + return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), o :: any) +end + +local function normDir(s: string): string + local d = string.gsub(s, "\\", "/") + d = string.gsub(d, "^/+", "") + if d ~= "" and string.sub(d, -1) ~= "/" then + d ..= "/" + end + return d +end + +for _, c in Fx.cases do + local tag = "v" .. c.version .. ": " + local e = c.expect + local st = c.srctools + local s, err = decode(c) + t:check(s, tag .. tostring(err)) + if not s then + continue + end + local src = s.meta.source + t:eq(F.detect(c.mdl), "sourcemdl", tag .. "F.detect") + t:eq(#src.warnings, 0, tag .. "no warnings (" .. table.concat(src.warnings, "; ") .. ")") + t:eq(src.vtx, "model.dx90.vtx", tag .. "the dx90 strips") + + -- header against srctools + t:eq(src.name, st.name, tag .. "name (srctools)") + t:eq(src.version, st.version, tag .. "version (srctools)") + t:eq(src.surfaceProp, st.surfaceprop, tag .. "surfaceprop (srctools)") + t:eq(src.keyValues, st.keyvalues, tag .. "keyvalues (srctools)") + t:check(math.abs(src.mass - st.mass) < 1e-6, tag .. "mass (srctools)") + t:check(near(src.eye, st.eye, 1e-6) and near(src.hull[1], st.hull[1], 1e-6) and near(src.hull[2], st.hull[2], 1e-6), tag .. "eye / hull (srctools)") + for i, d in src.cdmaterials do + t:eq(normDir(d), st.cdmaterials[i], tag .. "cdmaterials " .. i .. " (srctools)") + end + t:eq(#src.includeModels, #st.included, tag .. "include models (srctools)") + t:eq(src.includeModels[1].file, st.included[1][2], tag .. "include model file (srctools)") + t:eq(#src.skins, #st.skins, tag .. "skin families (srctools)") + for f, fam in src.skins do + local names = {} + for r, mi in fam do + names[r] = s.materials[mi].name + end + t:eq(table.concat(names, ","), table.concat(st.skins[f], ","), tag .. "skin family " .. f .. " (srctools)") + end + t:eq(#src.sequences, #st.sequences, tag .. "sequences (srctools)") + for i, q in st.sequences do + local ours = src.sequences[i] + t:eq(ours.name, q.label, tag .. "sequence " .. i .. " label (srctools)") + t:eq(ours.activity, q.act, tag .. "sequence " .. i .. " activity (srctools)") + t:eq(ours.flags, q.flags, tag .. "sequence " .. i .. " flags (srctools)") + t:eq(ours.weight, q.weight, tag .. "sequence " .. i .. " weight (srctools)") + t:eq(ours.keyValues, q.keyvalues, tag .. "sequence " .. i .. " keyvalues (srctools)") + t:check(near(ours.bboxMin, q.bbox[1], 1e-6) and near(ours.bboxMax, q.bbox[2], 1e-6), tag .. "sequence " .. i .. " bbox (srctools)") + t:eq(#ours.events, #q.events, tag .. "sequence " .. i .. " events (srctools)") + for k, ev in q.events do + t:check(math.abs(ours.events[k].cycle - ev[1]) < 1e-6 and ours.events[k].options == ev[2], tag .. "sequence " .. i .. " event " .. k .. " (srctools)") + end + end + local total = 0 + for _, p in src.bodyParts do + for _, m in p.models do + total += m.vertices + end + end + t:eq(total, st.total_verts, tag .. "total vertices (srctools)") + t:check(string.find(src.physics.text, '"mass" "12.5', 1, true) ~= nil and st.phys_mass == 12.5, tag .. "phy keyvalues (srctools)") + + -- skeleton + local skin = s.skins[1] + t:eq(#skin.joints, #e.bones, tag .. "joints") + local ibm = floats(skin.inverseBindMatrices) + for i, b in e.bones do + local node = s.nodes[skin.joints[i]] + t:eq(node.name, b.name, tag .. "bone " .. i .. " name") + t:check(near(node.translation, b.pos, 0) and near(node.rotation, b.quat, 0), tag .. "bone " .. i .. " rest pose") + if b.parent >= 0 then + t:check(table.find(s.nodes[skin.joints[b.parent + 1]].children, skin.joints[i]) ~= nil, tag .. "bone " .. i .. " parent") + end + local m = Mat4.fromRows(b.poseToBone) + local got = table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, {}) + t:check(near(got, m, 1e-6), tag .. "bone " .. i .. " poseToBone as the inverse bind matrix") + end + t:eq(s.nodes[skin.joints[5]].extras.procedural.type, "jiggle", tag .. "jiggle bone") + t:eq(s.nodes[skin.joints[6]].extras.procedural.type, "aimatbone", tag .. "aim-at bone") + t:check(near(src.lodVertices, e.lodCounts, 0) or (src.lodVertices[1] == e.lodCounts[1] and src.lodVertices[2] == e.lodCounts[2]), tag .. "vvd LOD vertex counts") + + -- meshes + for p, part in e.parts do + for m, model in part.models do + local info = src.bodyParts[p].models[m] + t:eq(info.name, model.name, tag .. "model " .. model.name) + if #model.meshes == 0 then + t:check(info.mesh == nil, tag .. model.name .. ": no mesh") + continue + end + local mesh = s.meshes[info.mesh] + t:eq(#mesh.primitives, #model.meshes, tag .. model.name .. ": primitives") + for k, x in model.meshes do + local prim = mesh.primitives[k] + local lab = tag .. model.name .. " mesh " .. k .. ": " + t:check(near(floats(prim.attributes.POSITION), x.positions, 0), lab .. "positions") + t:check(near(floats(prim.attributes.NORMAL), x.normals, 0), lab .. "normals") + t:check(near(floats(prim.attributes.TEXCOORD_0), x.uvs, 0), lab .. "uvs") + t:check(near(floats(prim.attributes.TANGENT), x.tangents, 0), lab .. "tangents") + t:check(near(floats(prim.attributes.WEIGHTS_0), x.weights, 0), lab .. "weights") + t:check(near(floats(prim.attributes.JOINTS_0), x.joints, 0), lab .. "joints") + t:check(near(floats(prim.indices), x.lods[1], 0), lab .. "LOD 0 triangles (strips, groups, winding)") + t:check(near(floats(prim.extras.lods[2].indices), x.lods[2], 0), lab .. "LOD 1 triangles") + t:eq(prim.extras.lods[2].switchPoint, 40, lab .. "LOD 1 switch point") + t:eq(prim.material, x.material, lab .. "material through skin family 1") + t:eq(prim.extras.skinRef, x.skinRef, lab .. "skin reference") + local names = mesh.extras.targetNames + local want = 0 + for d, verts in x.targets do + local slot = table.find(names, e.flexdescs[tonumber(d) :: number + 1]) + t:check(slot ~= nil, lab .. "flex target " .. d) + if slot then + local pos, nrm = floats(prim.targets[slot].POSITION), floats(prim.targets[slot].NORMAL) + local ok = true + for v, dd in verts do + local vi = tonumber(v) :: number + for cc = 1, 3 do + ok = ok and math.abs(pos[vi * 3 + cc] - dd[cc]) < 1e-6 and math.abs(nrm[vi * 3 + cc] - dd[cc + 3]) < 1e-6 + end + want += 1 + end + t:check(ok, lab .. "flex " .. names[slot] .. " deltas") + end + end + if names then + t:eq(#prim.targets, #names, lab .. "a target per flex") + end + end + end + end + t:eq(s.nodes[s.roots[1]].name, src.name, tag .. "root node") + + -- attachments + for i, a in e.attachments do + local at = src.attachments[i] + local node = s.nodes[at.node] + t:eq(node.name, a.name, tag .. "attachment " .. i .. " name") + t:check(table.find(s.nodes[skin.joints[a.bone + 1]].children, at.node) ~= nil, tag .. "attachment " .. i .. " parent bone") + local m = Mat4.compose(node.translation, node.rotation, node.scale) + t:check(near(m, Mat4.fromRows(a.matrix), 1e-5), tag .. "attachment " .. i .. " matrix") + end + t:eq(#src.hitboxSets[1].boxes, 2, tag .. "hitboxes") + t:eq(src.hitboxSets[1].boxes[2].name, "head_box", tag .. "hitbox name") + + -- animations + for _, a in e.anims do + local anim + for _, x in s.animations do + if x.name == a.name then + anim = x + end + end + t:check(anim, tag .. "animation " .. a.name) + if not anim then + continue + end + for bone, want in a.bones do + local node = skin.joints[tonumber(bone) :: number] + local tr, rot + for _, ch in anim.channels do + if ch.node == node then + if ch.path == "translation" then + tr = ch + elseif ch.path == "rotation" then + rot = ch + end + end + end + t:check(tr and rot, tag .. a.name .. " bone " .. bone .. ": channels") + if tr and rot then + t:eq(tr.input.count, a.frames, tag .. a.name .. ": frames") + t:check(math.abs(floats(tr.input)[2] - 1 / a.fps) < 1e-6, tag .. a.name .. ": fps") + t:check(near(floats(tr.output), want.pos, 1e-4), tag .. a.name .. " bone " .. bone .. ": positions per frame") + t:check(near(floats(rot.output), want.rot, 1e-5), tag .. a.name .. " bone " .. bone .. ": rotations per frame") + end + end + end + if c.version == 49 then + t:check(c.files["model.ani"] ~= nil, tag .. "an .ani block") + end + + -- physics + local soup = {} + for _, sol in src.physics.solids do + for _, h in sol.hulls do + for _, v in h.indices do + for cc = 1, 3 do + table.insert(soup, h.positions[v * 3 + cc]) + end + end + end + end + t:check(near(soup, e.physics, 1e-3), tag .. "phy convex hulls") + + -- options + local s2 = decode(c, { bodies = { 2, 2 }, lod = 2 }) :: any + local names = {} + for _, ni in s2.nodes[s2.roots[1]].children do + if s2.nodes[ni].mesh then + table.insert(names, s2.meshes[s2.nodes[ni].mesh].name) + end + end + t:eq(table.concat(names, ","), "body_lo,hat", tag .. "opts.bodies") + t:check(near(floats(s2.meshes[1].primitives[1].indices), e.parts[1].models[1].meshes[1].lods[2], 0), tag .. "opts.lod") + local s3 = SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl))) :: any + t:check(s3 and #s3.meshes == 0 and #s3.meta.source.warnings > 0 and #s3.skins == 1, tag .. "no siblings: skeleton only, with warnings") + local s4 = decode(c, { name = "renamed.mdl", files = { ["renamed.vvd"] = c.files["model.vvd"], ["renamed.sw.vtx"] = c.files["model.dx90.vtx"] } }) :: any + t:check(s4 and #s4.meshes == 3 and s4.meta.source.vtx == "renamed.sw.vtx", tag .. "siblings named after opts.name") + + -- fuzz: the mdl, and each sibling file + local samples = { c.mdl } + t:fuzz(tag .. "mdl", function(b: buffer) + return SourceMdl.decode(Bytes.reader(b), { files = c.files }) + end, samples, { mutations = 40 }) + for _, name in { "model.vvd", "model.dx90.vtx", "model.phy" } do + t:fuzz(tag .. name, function(b: buffer) + local files = table.clone(c.files) + files[name] = buffer.tostring(b) + return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), { files = files }) + end, { c.files[name] }, { mutations = 30, garbage = 20 }) + end +end + +-- errors +local bad = buffer.fromstring(Fx.cases[1].mdl) +buffer.writei32(bad, 4, 52) +local _, e1 = SourceMdl.decode(Bytes.reader(bad)) +t:check(e1 and e1.code == Err.UNSUPPORTED, "version 52: UNSUPPORTED") +local _, e2 = SourceMdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.cases[1].mdl, 1, 100)))) +t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated header") +local s5 = SourceMdl.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl)), { files = { ["model.vvd"] = "IDSV" } }) +t:check(s5 == nil, "a broken .vvd is an error") +t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl))), 1, "sniff") +t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring("IDST\10\0\0\0"))), 0, "sniff: GoldSrc is model/mdl") +t:done() diff --git a/tools/fixtures/sourcemdl.py b/tools/fixtures/sourcemdl.py new file mode 100644 index 0000000..a5658ce --- /dev/null +++ b/tools/fixtures/sourcemdl.py @@ -0,0 +1,816 @@ +# Source MDL fixtures (tools/fixtures.py). Models written here from the Source SDK 2013 studio.h / optimize.h / +# phyfile.h layouts with random data (no Valve assets): MDL v44 / v48 / v49 with .vvd (LOD fixups, file order +# shuffled), .dx90.vtx (trilists, a tristrip, two LODs, a material replacement; v49 uses the 33 / 35-byte strip +# headers), .phy (VPHY, two convex leaves, KeyValues text), .ani (an external animation block) and .vmt materials. +# References: the writer's exact values (vertices, triangles, bones, poseToBone, flex deltas, per-frame bone poses from +# RLE values / Quaternion48 / Quaternion64 / Vector48, sections, delta animation) and srctools (nixpkgs python +# srctools.mdl.Model: header, cdmaterials, skins, sequences, events, included models, phy keyvalues, iter_textures; +# srctools.vmt.Material: $basetexture / $bumpmap). +# tests/gen/sourcemdl.luau { cases = { { version, mdl, vvd, vtx, phy, ani, files, expect, srctools }, ... } } +import json, math, os, shutil, struct, tempfile + +INPUTS = [] + + +def f32(x): + return struct.unpack("= 48 + scale = f32(1 / 4096.0) + + def deltas(nv, count, wrinkle=False): + out = [] + for idx in sorted(rng.sample(range(nv), count)): + d = [rng.uniform(-2, 2) for _ in range(6)] + out.append({"index": idx, "speed": rng.randrange(256), "side": rng.randrange(256), "d": d, "wrinkle": rng.randrange(-32767, 32768) if wrinkle else 0}) + return out + m0["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 0.25, 0.75, 1.0], "verts": deltas(m0["nv"], 8)}) + m0["flexes"].append({"desc": 0, "partner": 1, "kind": 1, "targets": [0.0, 0.5, 0.5, 1.0], "verts": deltas(m0["nv"], 6, True)}) + hi["meshes"][1]["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 1.0, 1.0, 1.0], "verts": deltas(hi["meshes"][1]["nv"], 5)}) + for m in (m0, hi["meshes"][1]): + for f in m["flexes"]: + for v in f["verts"]: + if fixed: + v["raw"] = [max(-32768, min(32767, int(round(c / scale)))) for c in v["d"]] + v["val"] = [r * scale for r in v["raw"]] + else: + v["val"] = [f16(c) for c in v["d"]] + # animations + nf = {"idle": 6, "walk": 12, "gesture": 4, "fromani": 3} + anims = [] + + # per-anim per-bone specs (full length), split into sections by the writer + def make_specs(n, delta): + specs = [] + r = [rng.randrange(-2000, 2000) for _ in range(3)] + specs.append((0, {"rot": "anim", "rv": [[rng.randrange(-3000, 3000) for _ in range(n)], [r[1]] * n, [rng.choice((5, 5, 9)) for _ in range(n)]], + "pos": "anim", "pv": [[rng.randrange(-500, 500) for _ in range(n)], None, [7] * n]})) + specs.append((1, {"rot": "raw48", "q": [f32(c) for c in normalize([rng.uniform(-1, 1) for _ in range(4)])], "pos": "raw48", "p": [f16(rng.uniform(-10, 10)) for _ in range(3)]})) + specs.append((3, {"rot": "raw64", "q": normalize([rng.uniform(-1, 1) for _ in range(4)]), "pos": None})) + specs.append((4, {"rot": None, "pos": "anim", "pv": [None, [rng.randrange(-100, 100) for _ in range(n)], None]})) + return specs + for name, delta in (("idle", False), ("walk", False), ("gesture", True), ("fromani", False)): + anims.append({"name": "@" + name, "seq": name, "frames": nf[name], "delta": delta, "specs": make_specs(nf[name], delta), + "fps": f32(rng.choice((24.0, 30.0))), "sections": 5 if name == "walk" else 0, "ani": name == "fromani"}) + if version < 49: + anims.pop() + # expected poses per anim: { bone -> { pos = [...], rot = [...] } } + for a in anims: + n = a["frames"] + exp = {} + for bi, sp in a["specs"]: + b = bones[bi] + pos, rot = [], [] + for fr in range(n): + if sp["rot"] == "anim": + ang = [(0 if a["delta"] else b["rot"][k]) + (sp["rv"][k][fr] * b["rotscale"][k] if sp["rv"][k] else 0) for k in range(3)] + q = angles(*ang) + elif sp["rot"] == "raw48": + q = quat48(sp["q"])[1] + elif sp["rot"] == "raw64": + q = quat64(sp["q"])[1] + else: + q = [0, 0, 0, 1] if a["delta"] else b["quat"] + if sp["pos"] == "anim": + p = [(0 if a["delta"] else b["pos"][k]) + (sp["pv"][k][fr] * b["posscale"][k] if sp["pv"][k] else 0) for k in range(3)] + elif sp["pos"] == "raw48": + p = list(sp["p"]) + else: + p = [0, 0, 0] if a["delta"] else list(b["pos"]) + if a["delta"]: + p = [b["pos"][k] + p[k] for k in range(3)] + q = qmul(b["quat"], q) + pos += p + rot += q + exp[bi] = {"pos": pos, "rot": rot} + a["expect"] = exp + return {"version": version, "ext": ext, "bones": bones, "textures": textures, "cdmats": cdmats, "families": families, "nref": nref, + "parts": parts, "vertices": vertices, "flexdescs": flexdescs, "fixed": fixed, "scale": scale, "anims": anims} + + +def normalize(q): + l = math.sqrt(sum(c * c for c in q)) + return [c / l for c in q] + + +def anim_chain(b, a, bones, first, count): + # mstudioanim_t records for frames [first, first + count) of every spec + out = bytearray() + recs = [] + for i, (bi, sp) in enumerate(a["specs"]): + flags = 0 + body = bytearray() + later = [] + if sp["rot"] == "raw48": + flags |= 0x02 + body += quat48(sp["q"])[0] + elif sp["rot"] == "raw64": + flags |= 0x20 + body += quat64(sp["q"])[0] + elif sp["rot"] == "anim": + flags |= 0x08 + later.append((len(body), sp["rv"])) + body += bytes(6) + if sp["pos"] == "raw48": + flags |= 0x01 + body += struct.pack("<3e", *sp["p"]) + elif sp["pos"] == "anim": + flags |= 0x04 + later.append((len(body), sp["pv"])) + body += bytes(6) + if a["delta"]: + flags |= 0x10 + for vp, chans in later: + for k in range(3): + if chans[k] is not None: + off = 4 + len(body) - (4 + vp) + struct.pack_into("= l) for l in range(2)] + [0] * 6 + vdata, tdata = bytearray(), bytearray() + for ci in order: + s, c = chunks[ci] + for vv in verts[s:s + c]: + vdata += struct.pack("<3f3BB3f3f2f", *vv["w"], *vv["b"], vv["n"], *vv["pos"], *vv["nrm"], *vv["uv"]) + tdata += struct.pack("<4f", *vv["tan"]) + fix = b"".join(struct.pack("<3i", lods[i], filepos[i], chunks[i][1]) for i in range(len(chunks))) + off_fix = 64 + off_v = off_fix + len(fix) + off_v += (16 - off_v % 16) % 16 + off_t = off_v + len(vdata) + out = struct.pack("<4siii8iiiii", b"IDSV", 4, checksum, 2, *counts, len(chunks), off_fix, off_v, off_t) + out += fix + out += bytes(off_v - len(out)) + return out + vdata + tdata, counts + + +def write_vtx(m, rng, checksum, ext): + w = Buf() + w.raw(bytes(36)) + nlod = 2 + parts = m["parts"] + bp = w.tell() + for p in parts: + w.put("ii", len(p["models"]), 0) + expect = {} + for pi, p in enumerate(parts): + pat = bp + pi * 8 + mo = w.tell() + w.patch(pat + 4, "i", mo - pat) + for md in p["models"]: + w.put("ii", nlod, 0) + for mi, md in enumerate(p["models"]): + mat = mo + mi * 8 + lo = w.tell() + w.patch(mat + 4, "i", lo - mat) + for l in range(nlod): + w.put("iif", len(md["meshes"]), 0, [0.0, 40.0][l]) + for l in range(nlod): + la = lo + l * 12 + me = w.tell() + w.patch(la + 4, "i", me - la) + for sm in md["meshes"]: + w.put("iiB", 0, 0, 0) + for k, sm in enumerate(md["meshes"]): + mea = me + k * 9 + tris = sm["tris"] if l == 0 else sm["tris"][:max(1, len(sm["tris"]) // 2)] + # LOD 0 of the first mesh: two strip groups, the second one a tristrip + groups = [] + if l == 0 and k == 0 and pi == 0 and mi == 0: + half = len(tris) // 2 + groups.append(("list", tris[:half])) + strip = [tris[half][0], tris[half][1], tris[half][2]] + for t in tris[half + 1:half + 4]: + strip.append(t[0]) + groups.append(("strip", strip)) + groups.append(("list", tris[half + 4:])) + else: + groups.append(("list", tris)) + decoded = [] + sga = w.tell() + w.patch(mea, "ii", len(groups), sga - mea) + sgstride = 33 if ext else 25 + w.raw(bytes(sgstride * len(groups))) + for gi, (kind, data) in enumerate(groups): + ids = data if kind == "strip" else [c for t in data for c in t] + uniq = [] + for c in ids: + if c not in uniq: + uniq.append(c) + rng.shuffle(uniq) + local = [uniq.index(c) for c in ids] + if kind == "strip": + for i in range(len(ids) - 2): + a, b, c = ids[i], ids[i + 1], ids[i + 2] + if a != b and b != c and a != c: + decoded += [a, b, c] if i % 2 == 0 else [b, a, c] + else: + decoded += ids + ga = sga + gi * sgstride + vo = w.tell() + for c in uniq: + w.put("3BBH3b", 0, 1, 2, 1, c, 0, 0, 0) + io = w.tell() + w.put("%dH" % len(local), *local) + w.align() + so = w.tell() + stflags = 2 if kind == "strip" else 1 + w.put("iiiihBii", len(local), 0, len(uniq), 0, 3, stflags, 0, 0) + if ext: + w.put("ii", 0, 0) + w.patch(ga, "iiiiiiB", len(uniq), vo - ga, len(local), io - ga, 1, so - ga, 0) + expect["%d_%d_%d_%d" % (pi, mi, l, k)] = decoded + rl = w.tell() + for l in range(nlod): + w.put("ii", 0, 0) + ra = w.tell() + w.put("hi", 1, 0) + w.patch(rl + 8, "ii", 1, ra - (rl + 8)) + w.string(ra + 2, ra, "models/test/skin_b_lod1") + w.flush_strings() + w.patch(0, "iiHHiiiiii", 7, 24, 53, 9, 3, checksum, nlod, rl, len(parts), bp) + return bytes(w.b), expect + + +def write_phy(rng, checksum): + def ledge_bytes(points, tris): + hdr = 16 + body = bytearray() + for t in tris: + body += struct.pack(" 64: + files["model.ani"] = ani + for path, text in VMTS.items(): + files[path] = text + return { + "version": version, "mdl": mdl, "files": files, "srctools": st, + "expect": {"parts": expect_parts, "bones": bones, "anims": anims, "attachments": atts, "sequences": seqs, "physics": soup, + "flexdescs": m["flexdescs"], "lodCounts": lodcounts[:2], "checksum": checksum, "fixed": m["fixed"]}, + } + + +def generate(ctx): + rng = ctx.rng(4449) + ctx.emit("sourcemdl", {"cases": [case(ctx, rng, v) for v in (44, 48, 49)]})