--!strict -- model/sourcemdl/Build: the parsed MDL / VVD / VTX / PHY into a Scene: bones (poseToBone as inverse bind matrices), -- body part models as meshes (one primitive per studio mesh, LOD 0 indices; LODs 1+ in primitive extras), flexes as -- morph targets, attachments as nodes, animations through codecs/model/SourceAnim. Source front faces wind clockwise. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Rig = require("@rosetta/codecs/model/Rig") local SourceAnim = require("@rosetta/codecs/model/SourceAnim") local Mdl = require("@rosetta/model/sourcemdl/Mdl") local Vvd = require("@rosetta/model/sourcemdl/Vvd") local Vtx = require("@rosetta/model/sourcemdl/Vtx") local Phy = require("@rosetta/model/sourcemdl/Phy") local Build = {} local Scene = Types.Scene local readf32, readu8, readi32, writef32, writeu16, writeu32 = buffer.readf32, buffer.readu8, buffer.readi32, buffer.writef32, buffer.writeu16, buffer.writeu32 export type Options = { bodies: { number }?, -- 1-based model per body part, default 1 lod: number?, -- 1-based LOD for the primitives' indices, default 1 animations: boolean?, -- default true maxVertices: number?, maxFrames: number?, -- per animation, default 65536 } export type Inputs = { vvd: Vvd.Vertices?, vtx: Vtx.Strips?, phy: Phy.Physics?, ani: buffer?, warnings: { string } } local STUDIO_DELTA, STUDIO_FRAMEANIM = 0x04, 0x40 local function u32s(list: { number }): Types.Accessor local b = buffer.create(#list * 4) for i, v in list do writeu32(b, (i - 1) * 4, v) end return Scene.accessor(b, "u32", 1, #list) end local function reversed(tris: { number }, count: number): { number }? local out: { number } = {} for i = 1, #tris - 2, 3 do local a, b, c = tris[i], tris[i + 1], tris[i + 2] if a >= count or b >= count or c >= count then return nil end out[i], out[i + 1], out[i + 2] = c, b, a end return out end local function qmul(a: { number }, b: { number }): { number } local ax, ay, az, aw = a[1], a[2], a[3], a[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] return { aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz } end local function primitive(h: Mdl.Header, vvd: Vvd.Vertices, first: number, mesh: Mdl.Mesh, nBones: number): Types.Primitive local n = mesh.vertexCount local pos, nrm, uv = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8) local jb, wb = buffer.create(n * 8), buffer.create(n * 16) local src = vvd.data for i = 0, n - 1 do local o = (first + i) * 48 local cnt = readu8(src, o + 15) for k = 0, 2 do if k < cnt then writef32(wb, i * 16 + k * 4, readf32(src, o + k * 4)) writeu16(jb, i * 8 + k * 2, math.min(readu8(src, o + 12 + k), math.max(nBones - 1, 0))) end end for k = 0, 2 do writef32(pos, i * 12 + k * 4, readf32(src, o + 16 + k * 4)) writef32(nrm, i * 12 + k * 4, readf32(src, o + 28 + k * 4)) end writef32(uv, i * 8, readf32(src, o + 40)) writef32(uv, i * 8 + 4, readf32(src, o + 44)) end local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, n), NORMAL = Scene.accessor(nrm, "f32", 3, n), TEXCOORD_0 = Scene.accessor(uv, "f32", 2, n), } if nBones > 0 then attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, n) attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n) end local tan = vvd.tangents if tan then local t = buffer.create(n * 16) buffer.copy(t, 0, tan, first * 16, n * 16) attrs.TANGENT = Scene.accessor(t, "f32", 4, n) end local fam = h.skins[1] local tex = if fam then fam[mesh.material + 1] else mesh.material return { attributes = attrs, mode = "triangles" :: any, material = if tex and tex >= 0 and tex < #h.textures then tex + 1 else nil, extras = { skinRef = mesh.material, materialType = mesh.materialType, materialParam = mesh.materialParam, id = mesh.id }, } end local function flexTargets(meshes: { Mdl.Mesh }, prims: { Types.Primitive }, names: { string }): { string }? local used: { [number]: boolean } = {} local order: { number } = {} for _, m in meshes do for _, f in m.flexes do for _, d in { f.desc, if f.partner > 0 then f.partner else -1 } do if d >= 0 and not used[d] then used[d] = true table.insert(order, d) end end end end if #order == 0 then return nil end table.sort(order) local slot: { [number]: number } = {} for i, d in order do slot[d] = i end for k, m in meshes do local prim = prims[k] local n = m.vertexCount local targets: { { [string]: Types.Accessor } } = {} for i = 1, #order do targets[i] = { POSITION = Scene.accessor(nil, "f32", 3, n), NORMAL = Scene.accessor(nil, "f32", 3, n) } end for _, f in m.flexes do local stereo = f.partner > 0 for _, d in f.deltas do local v = d[1] if v < n then for side = 0, if stereo then 1 else 0 do local w = if not stereo then 1 elseif side == 0 then d[8] else 1 - d[8] local t = targets[slot[if side == 0 then f.desc else f.partner]] if t and w ~= 0 then local pb, nb = t.POSITION.data, t.NORMAL.data for c = 0, 2 do writef32(pb, v * 12 + c * 4, readf32(pb, v * 12 + c * 4) + d[2 + c] * w) writef32(nb, v * 12 + c * 4, readf32(nb, v * 12 + c * 4) + d[5 + c] * w) end end end end end end prim.targets = targets end local out = {} for i, d in order do out[i] = names[d + 1] or ("flex" .. d) end return out end local function animate(scene: Types.Scene, h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, jointNodes: { number }, opts: Options?) local bones: { SourceAnim.Bone } = h.bones :: any local maxFrames = opts and opts.maxFrames or 65536 local firstSeq: { [number]: string } = {} for _, s in h.sequences do local a = s.anims[1] if a and a >= 0 and not firstSeq[a + 1] then firstSeq[a + 1] = s.name end end local list = {} for i, a in h.anims do local info: { [string]: any } = { name = a.name, fps = a.fps, frames = a.frames, flags = a.flags, delta = bit32.band(a.flags, STUDIO_DELTA) ~= 0 } list[i] = info local frames = a.frames if bit32.band(a.flags, STUDIO_FRAMEANIM) ~= 0 then info.skipped = "frame animation (v52+)" elseif frames <= 0 or frames > maxFrames then info.skipped = "frame count" elseif #bones == 0 then info.skipped = "no bones" else local function locate(block: number, index: number): (buffer?, number, number) if block == 0 then return b, base + a.at + index, base + size end local ani, blk = inp.ani, h.animBlocks[block + 1] if not ani or not blk then return nil, 0, 0 end local lim = math.min(blk[2], buffer.len(ani)) return ani, blk[1] + index, lim end local nSections = 0 if a.sectionFrames > 0 and a.sectionIndex ~= 0 then nSections = frames // a.sectionFrames + 2 local so = a.at + a.sectionIndex if so < 0 or so + nSections * 8 > size then info.skipped = "bad section table" nSections = -1 end end local per: { [number]: { frames: number, block: number, index: number } } = {} local where: { { number } } = {} if nSections >= 0 then for f = 0, frames - 1 do local sec, loc = 0, f if nSections > 0 then if frames > a.sectionFrames and f == frames - 1 then sec, loc = frames // a.sectionFrames + 1, 0 else sec = f // a.sectionFrames loc = f - sec * a.sectionFrames end end local e = per[sec] if not e then if nSections > 0 then local so = base + a.at + a.sectionIndex + sec * 8 e = { frames = 0, block = readi32(b, so), index = readi32(b, so + 4) } else e = { frames = 0, block = a.block, index = a.index } end per[sec] = e end e.frames = math.max(e.frames, loc + 1) where[f + 1] = { sec, loc } end end local decoded: { [number]: { [number]: SourceAnim.Track } } = {} for sec, e in per do local src, at, lim = locate(e.block, e.index) if e.block < 0 or not src then info.skipped = if e.block < 0 then "missing animation block" else "animation block " .. e.block .. " not resolved (" .. h.animBlockName .. ")" break end local tr, err = SourceAnim.decode(src, at, lim, bones, e.frames) if not tr then info.skipped = err break end decoded[sec] = tr end if not info.skipped then local animated: { [number]: boolean } = {} for _, tr in decoded do for j in tr do animated[j] = true end end local fps = if a.fps > 0 then a.fps else 30 local times = table.create(frames, 0) local tracks: { [number]: Rig.Track } = {} for j in animated do tracks[j] = { translation = table.create(frames * 3, 0), rotation = table.create(frames * 4, 0) } end local delta = info.delta for f = 0, frames - 1 do times[f + 1] = f / fps local w = where[f + 1] local tr = decoded[w[1]] for j, out in tracks do local bn = bones[j] local t = tr[j] local tt, rr = out.translation :: { number }, out.rotation :: { number } local px, py, pz, q if t then px, py, pz = t.pos[w[2] * 3 + 1], t.pos[w[2] * 3 + 2], t.pos[w[2] * 3 + 3] q = { t.rot[w[2] * 4 + 1], t.rot[w[2] * 4 + 2], t.rot[w[2] * 4 + 3], t.rot[w[2] * 4 + 4] } else px, py, pz, q = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3], if delta then { 0, 0, 0, 1 } else bn.quat end if delta then px, py, pz = bn.pos[1] + px, bn.pos[2] + py, bn.pos[3] + pz q = qmul(bn.quat, q) end tt[f * 3 + 1], tt[f * 3 + 2], tt[f * 3 + 3] = px, py, pz for c = 1, 4 do rr[f * 4 + c] = q[c] end end end info.animation = Rig.animation(scene, firstSeq[i] or a.name, jointNodes, times, tracks, "LINEAR") end end end return list end function Build.scene(h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, opts: Options?): (Types.Scene?, string?) local scene = Scene.new() scene.meta.up = "z" local root: Types.Node = { name = h.name, children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 local joints: { Rig.Joint } = {} for i, bn in h.bones do joints[i] = { name = bn.name, parent = bn.parent + 1, translation = table.clone(bn.pos), rotation = table.clone(bn.quat) } end local nBones = #h.bones local jointNodes, skinIndex = {}, nil if nBones > 0 then local nodes, si = Rig.skeleton(scene, joints, "local", 1) jointNodes, skinIndex = nodes, si local ibm = (scene.skins[si].inverseBindMatrices :: Types.Accessor).data for i, bn in h.bones do local m = Mat4.fromRows(bn.poseToBone) for k = 1, 16 do writef32(ibm, ((i - 1) * 16 + k - 1) * 4, m[k]) end local ex: { [string]: any } = { bone = i - 1, flags = bn.flags, surfaceProp = bn.surfaceProp, contents = bn.contents, physicsBone = bn.physicsBone } if bn.procedural then ex.procedural = bn.procedural end scene.nodes[nodes[i]].extras = ex end end for _, t in h.textures do local mat = Scene.material(t.name) mat.metallic = 0 table.insert(scene.materials, mat) end local vvd, vtx = inp.vvd, inp.vtx local lodPick = math.max(1, opts and opts.lod or 1) local bodyInfo = {} for p, part in h.bodyParts do local pick = (opts and opts.bodies and opts.bodies[p]) or 1 local info = { name = part.name, base = part.base, models = {}, selected = pick } bodyInfo[p] = info for m, model in part.models do local minfo: { [string]: any } = { name = model.name, vertices = model.vertexCount, eyeballs = model.eyeballs } info.models[m] = minfo local vlods = vtx and vtx.parts[p] and vtx.parts[p][m] if #model.meshes > 0 and vvd and vlods and #vlods > 0 then local first = model.vertexIndex // 48 if first + model.vertexCount > vvd.count then return nil, "model " .. model.name .. ": vertices outside the vvd" end local mesh: Types.Mesh = { name = model.name, primitives = {}, extras = { bodyPart = part.name, lods = #vlods } } for k, sm in model.meshes do local prim = primitive(h, vvd, first + sm.vertexOffset, sm, nBones) local lods = {} for l, lod in vlods do local vm = lod.meshes[k] local idx = if vm then reversed(vm.indices, sm.vertexCount) else {} if not idx then return nil, "vtx index outside mesh " .. (k - 1) .. " of " .. model.name end lods[l] = { indices = u32s(idx), switchPoint = lod.switchPoint } end local use = lods[math.min(lodPick, #lods)] prim.indices = use.indices local ex = prim.extras :: { [string]: any } ex.lods = lods table.insert(mesh.primitives, prim) end local names = flexTargets(model.meshes, mesh.primitives, h.flexDescs) if names then mesh.weights = table.create(#names, 0) local mex = mesh.extras :: { [string]: any } mex.targetNames = names end table.insert(scene.meshes, mesh) minfo.mesh = #scene.meshes if m == pick then table.insert(scene.nodes, { name = part.name, children = {}, mesh = #scene.meshes, skin = skinIndex }) table.insert(root.children, #scene.nodes) end end end end local attachments = {} for i, a in h.attachments do local t, r, s = Mat4.decompose(Mat4.fromRows(a.matrix)) local node: Types.Node = { name = a.name, children = {}, translation = t, rotation = r, scale = if math.abs(s[1] - 1) + math.abs(s[2] - 1) + math.abs(s[3] - 1) > 1e-5 then s else nil, extras = { attachment = i - 1, flags = a.flags } } table.insert(scene.nodes, node) local parent = jointNodes[a.bone + 1] table.insert(scene.nodes[parent or 1].children, #scene.nodes) attachments[i] = { name = a.name, bone = a.bone, flags = a.flags, node = #scene.nodes } end local anims = if opts and opts.animations == false then {} else animate(scene, h, b, base, size, inp, jointNodes, opts) local skins = {} for f, fam in h.skins do local list = {} for r, t in fam do list[r] = t + 1 end skins[f] = list end local phy = inp.phy scene.meta.source = { format = "sourcemdl", version = h.version, checksum = h.checksum, name = h.name, flags = h.flags, eye = h.eye, illum = h.illum, hull = { h.hullMin, h.hullMax }, view = { h.viewMin, h.viewMax }, mass = h.mass, contents = h.contents, surfaceProp = h.surfaceProp, keyValues = h.keyValues, cdmaterials = h.cdmaterials, textures = h.textures, skins = skins, bodyParts = bodyInfo, attachments = attachments, hitboxSets = h.hitboxSets, boneControllers = h.controllers, sequences = h.sequences, animations = anims, poseParameters = h.poseParameters, flexDescs = h.flexDescs, flexControllers = h.flexControllers, flexRules = h.flexRules, includeModels = h.includeModels, animBlockName = h.animBlockName, 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, } return scene, nil end return Build