model/sourcemdl: Source MDL v44-49 with .vvd / .vtx / .phy / .ani (WIP, no tests yet); codecs/model/SourceAnim shared with model/mdl's GoldSrc animation values
This commit is contained in:
1 parent
01c044805f
commit
c7e0639913
12 files changed
+1752
-31
No files matched your search
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
|
||||
## Formats
|
||||
|
||||
<!-- formats:begin -->
|
||||
174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
adds each format's capabilities.
|
||||
|
||||
| Category | Format | Extensions | Read | Write |
|
||||
@@ -132,6 +132,7 @@ adds each format's capabilities.
|
||||
| 3D models | robloxmesh | .mesh | yes | yes |
|
||||
| 3D models | schematic | .schem .schematic .litematic | yes | yes |
|
||||
| 3D models | smd | .smd | yes | yes |
|
||||
| 3D models | sourcemdl | .mdl | yes | - |
|
||||
| 3D models | stl | .stl | yes | yes |
|
||||
| 3D models | usda | .usda .usd .usdz | yes | yes |
|
||||
| 3D models | vox | .vox | yes | yes |
|
||||
@@ -238,7 +239,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`
|
||||
| entropy | Huffman, RangeCoder |
|
||||
| font | Bitmap, Cff, GlyphNames, TrueType |
|
||||
| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv |
|
||||
| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml |
|
||||
| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml |
|
||||
| text | Json, Nbt, Text, Url, Xml |
|
||||
| video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video |
|
||||
| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip |
|
||||
|
||||
@@ -88,6 +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 | 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` |
|
||||
@@ -253,6 +254,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx.
|
||||
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code.
|
||||
- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code.
|
||||
- codecs/model/SourceAnim: studio model animation data: the run-length coded mstudioanimvalue_t shorts (GoldSrc and
|
||||
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
|
||||
- **text**
|
||||
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
|
||||
|
||||
@@ -872,7 +872,7 @@ local list: { Entry } = {
|
||||
path = "model/mdl",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/mdl")
|
||||
@@ -1010,6 +1010,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/smd")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sourcemdl",
|
||||
category = "model",
|
||||
path = "model/sourcemdl",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-source-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/sourcemdl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "stl",
|
||||
category = "model",
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/model/SourceAnim: studio model animation data: the run-length coded mstudioanimvalue_t shorts (GoldSrc and
|
||||
-- Source), Source mstudioanim_t bone records with Quaternion48 / Quaternion64 / Vector48, from the Source SDK 2013
|
||||
-- studio.h / bone_setup.cpp layouts and SourceIO (MIT) notes; no code taken.
|
||||
local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local SourceAnim = {}
|
||||
|
||||
local readu8, readi16, readu16, readu32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readu32
|
||||
local sqrt, sin, cos = math.sqrt, math.sin, math.cos
|
||||
local HALF = Half.TABLE
|
||||
|
||||
export type Bone = {
|
||||
pos: { number },
|
||||
quat: { number },
|
||||
rot: { number }, -- radian euler x, y, z
|
||||
posScale: { number },
|
||||
rotScale: { number },
|
||||
}
|
||||
export type Track = { pos: { number }, rot: { number } } -- frames * 3 / frames * 4 (quaternion x, y, z, w)
|
||||
|
||||
-- ExtractAnimValue: frame k of a run list ({ valid, total } then valid shorts); a frame past valid repeats
|
||||
-- value[valid] (with valid = 0 that is the run header itself, as the engine reads it)
|
||||
function SourceAnim.value(b: buffer, at: number, limit: number, k: number): number?
|
||||
local p = at
|
||||
for _ = 1, 65536 do
|
||||
if p + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local valid, total = readu8(b, p), readu8(b, p + 1)
|
||||
if total == 0 then
|
||||
return nil
|
||||
end
|
||||
if total > k then
|
||||
local idx = if valid > k then k + 1 else valid
|
||||
if p + idx * 2 + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
return readi16(b, p + idx * 2)
|
||||
end
|
||||
k -= total
|
||||
p += (valid + 1) * 2
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function SourceAnim.values(b: buffer, at: number, limit: number, count: number): { number }?
|
||||
local out = table.create(count, 0)
|
||||
local p, f = at, 0
|
||||
while f < count do
|
||||
if p + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local valid, total = readu8(b, p), readu8(b, p + 1)
|
||||
if total == 0 or p + 2 + valid * 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local n = math.min(total, count - f)
|
||||
for i = 0, n - 1 do
|
||||
local idx = if i < valid then i + 1 else valid
|
||||
out[f + i + 1] = readi16(b, p + idx * 2)
|
||||
end
|
||||
f += n
|
||||
p += (valid + 1) * 2
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Quaternion48: x, y u16 (bias 32768), z 15 bits (bias 16384), w sign bit
|
||||
function SourceAnim.quat48(b: buffer, o: number): (number, number, number, number)
|
||||
local x = (readu16(b, o) - 32768) / 32768
|
||||
local y = (readu16(b, o + 2) - 32768) / 32768
|
||||
local zw = readu16(b, o + 4)
|
||||
local z = (zw % 32768 - 16384) / 16384
|
||||
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
|
||||
return x, y, z, if zw >= 32768 then -w else w
|
||||
end
|
||||
|
||||
-- Quaternion64: x, y, z 21 bits each (bias 1048576, scale 1 / 1048576.5), w sign bit 63
|
||||
function SourceAnim.quat64(b: buffer, o: number): (number, number, number, number)
|
||||
local lo, hi = readu32(b, o), readu32(b, o + 4)
|
||||
local xs = lo % 2097152
|
||||
local ys = (hi % 1024) * 2048 + (lo - xs) / 2097152
|
||||
local zs = math.floor(hi / 1024) % 2097152
|
||||
local x, y, z = (xs - 1048576) / 1048576.5, (ys - 1048576) / 1048576.5, (zs - 1048576) / 1048576.5
|
||||
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
|
||||
return x, y, z, if hi >= 0x80000000 then -w else w
|
||||
end
|
||||
|
||||
function SourceAnim.vec48(b: buffer, o: number): (number, number, number)
|
||||
return HALF[readu16(b, o)], HALF[readu16(b, o + 2)], HALF[readu16(b, o + 4)]
|
||||
end
|
||||
|
||||
-- AngleQuaternion (RadianEuler: x roll, y pitch, z yaw)
|
||||
function SourceAnim.angles(x: number, y: number, z: number): (number, number, number, number)
|
||||
local sy, cy = sin(z / 2), cos(z / 2)
|
||||
local sp, cp = sin(y / 2), cos(y / 2)
|
||||
local sr, cr = sin(x / 2), 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
|
||||
end
|
||||
|
||||
local RAWPOS, RAWROT, ANIMPOS, ANIMROT, DELTA, RAWROT2 = 0x01, 0x02, 0x04, 0x08, 0x10, 0x20
|
||||
|
||||
local function channels(b: buffer, vp: number, limit: number, frames: number, scale: { number }): ({ { number }? }?)
|
||||
if vp + 6 > limit then
|
||||
return nil
|
||||
end
|
||||
local out: { { number }? } = {}
|
||||
for k = 0, 2 do
|
||||
local off = readi16(b, vp + k * 2)
|
||||
if off > 0 then
|
||||
local v = SourceAnim.values(b, vp + off, limit, frames)
|
||||
if not v then
|
||||
return nil
|
||||
end
|
||||
local s = scale[k + 1]
|
||||
for i = 1, frames do
|
||||
v[i] *= s
|
||||
end
|
||||
out[k + 1] = v
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- mstudioanim_t chain at `at` (bone u8, flags u8, next i16, data): `frames` frames of every bone it lists, as the
|
||||
-- engine's CalcBoneQuaternion / CalcBonePosition (delta records add nothing of the bone's rest pose)
|
||||
function SourceAnim.decode(b: buffer, at: number, limit: number, bones: { Bone }, frames: number): ({ [number]: Track }?, string?)
|
||||
local out: { [number]: Track } = {}
|
||||
local p = at
|
||||
for _ = 1, #bones + 1 do
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated animation"
|
||||
end
|
||||
local bone, flags, nxt = readu8(b, p), readu8(b, p + 1), readi16(b, p + 2)
|
||||
if bone == 255 then
|
||||
break
|
||||
end
|
||||
local bn = bones[bone + 1]
|
||||
if not bn then
|
||||
return nil, "animation bone out of range"
|
||||
end
|
||||
local delta = bit32.band(flags, DELTA) ~= 0
|
||||
local d = p + 4
|
||||
local rot = table.create(frames * 4, 0)
|
||||
if bit32.band(flags, RAWROT) ~= 0 then
|
||||
if d + 6 > limit then
|
||||
return nil, "truncated animation"
|
||||
end
|
||||
local x, y, z, w = SourceAnim.quat48(b, d)
|
||||
for f = 0, frames - 1 do
|
||||
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
|
||||
end
|
||||
d += 6
|
||||
elseif bit32.band(flags, RAWROT2) ~= 0 then
|
||||
if d + 8 > limit then
|
||||
return nil, "truncated animation"
|
||||
end
|
||||
local x, y, z, w = SourceAnim.quat64(b, d)
|
||||
for f = 0, frames - 1 do
|
||||
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
|
||||
end
|
||||
d += 8
|
||||
elseif bit32.band(flags, ANIMROT) ~= 0 then
|
||||
local ch = channels(b, d, limit, frames, bn.rotScale)
|
||||
if not ch then
|
||||
return nil, "bad rotation values"
|
||||
end
|
||||
local bx, by, bz = if delta then 0 else bn.rot[1], if delta then 0 else bn.rot[2], if delta then 0 else bn.rot[3]
|
||||
local cx, cy, cz = ch[1], ch[2], ch[3]
|
||||
for f = 0, frames - 1 do
|
||||
local x, y, z, w = SourceAnim.angles(bx + (if cx then cx[f + 1] else 0), by + (if cy then cy[f + 1] else 0), bz + (if cz then cz[f + 1] else 0))
|
||||
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
|
||||
end
|
||||
d += 6
|
||||
else
|
||||
local q = if delta then { 0, 0, 0, 1 } else bn.quat
|
||||
for f = 0, frames - 1 do
|
||||
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = q[1], q[2], q[3], q[4]
|
||||
end
|
||||
end
|
||||
local pos = table.create(frames * 3, 0)
|
||||
if bit32.band(flags, RAWPOS) ~= 0 then
|
||||
if d + 6 > limit then
|
||||
return nil, "truncated animation"
|
||||
end
|
||||
local x, y, z = SourceAnim.vec48(b, d)
|
||||
for f = 0, frames - 1 do
|
||||
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = x, y, z
|
||||
end
|
||||
elseif bit32.band(flags, ANIMPOS) ~= 0 then
|
||||
local ch = channels(b, d, limit, frames, bn.posScale)
|
||||
if not ch then
|
||||
return nil, "bad position values"
|
||||
end
|
||||
local bx, by, bz = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3]
|
||||
local cx, cy, cz = ch[1], ch[2], ch[3]
|
||||
for f = 0, frames - 1 do
|
||||
pos[f * 3 + 1] = bx + (if cx then cx[f + 1] else 0)
|
||||
pos[f * 3 + 2] = by + (if cy then cy[f + 1] else 0)
|
||||
pos[f * 3 + 3] = bz + (if cz then cz[f + 1] else 0)
|
||||
end
|
||||
elseif not delta then
|
||||
for f = 0, frames - 1 do
|
||||
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = bn.pos[1], bn.pos[2], bn.pos[3]
|
||||
end
|
||||
end
|
||||
out[bone + 1] = { pos = pos, rot = rot }
|
||||
if nxt <= 0 then
|
||||
break
|
||||
end
|
||||
p += nxt
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
|
||||
return SourceAnim
|
||||
@@ -6,6 +6,7 @@ local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Pixels = require("@rosetta/codecs/image/Pixels")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
|
||||
|
||||
local HalfLife = {}
|
||||
|
||||
@@ -44,31 +45,6 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number
|
||||
return out, names
|
||||
end
|
||||
|
||||
-- bone default + stored value * scale
|
||||
local function animValue(b: buffer, at: number, limit: number, f: number): number?
|
||||
local p = at
|
||||
local k = f
|
||||
for _ = 1, 65536 do
|
||||
if p + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
local valid, total = readu8(b, p), readu8(b, p + 1)
|
||||
if total == 0 then
|
||||
return nil
|
||||
end
|
||||
if total > k then
|
||||
local idx = if valid > k then k + 1 else valid
|
||||
if p + idx * 2 + 2 > limit then
|
||||
return nil
|
||||
end
|
||||
return readi16(b, p + idx * 2)
|
||||
end
|
||||
k -= total
|
||||
p += (valid + 1) * 2
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 244 then
|
||||
return nil, "truncated header"
|
||||
@@ -293,7 +269,7 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
local v: { number } = {}
|
||||
for k = 0, 5 do
|
||||
local off = readu16(b, ao + k * 2)
|
||||
local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil
|
||||
local raw = if off ~= 0 then SourceAnim.value(b, ao + off, limit, f) else nil
|
||||
v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1]
|
||||
end
|
||||
table.insert(tr, v[1])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
--!strict
|
||||
-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins
|
||||
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+).
|
||||
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Source MDL (v44+) is model/sourcemdl.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -16,7 +16,7 @@ local Mdl = {
|
||||
category = "model",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
--!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,
|
||||
lodReplacements = if vtx then vtx.replacements else nil,
|
||||
physics = phy,
|
||||
warnings = inp.warnings,
|
||||
}
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,525 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Mdl: the studiohdr_t tables of Source MDL v44-49 (Source SDK 2013 public/studio.h layouts, SourceIO
|
||||
-- (MIT) and srctools (MIT) notes; no code taken). Geometry lives in the .vvd / .vtx files.
|
||||
local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local Mdl = {}
|
||||
|
||||
local readi32, readu32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readu32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32
|
||||
local HALF = Half.TABLE
|
||||
|
||||
export type Bone = {
|
||||
name: string,
|
||||
parent: number, -- 0-based, -1 = none
|
||||
pos: { number },
|
||||
quat: { number },
|
||||
rot: { number },
|
||||
posScale: { number },
|
||||
rotScale: { number },
|
||||
poseToBone: { number }, -- 3x4 rows
|
||||
flags: number,
|
||||
contents: number,
|
||||
surfaceProp: string,
|
||||
physicsBone: number,
|
||||
controllers: { number },
|
||||
procedural: { [string]: any }?,
|
||||
}
|
||||
export type Flex = {
|
||||
desc: number, -- 0-based flexdesc
|
||||
partner: number,
|
||||
targets: { number },
|
||||
kind: number, -- 0 normal, 1 wrinkle
|
||||
deltas: { { number } }, -- { index (mesh vertex), dx, dy, dz, nx, ny, nz, side, speed, wrinkle }
|
||||
}
|
||||
export type Mesh = { material: number, vertexOffset: number, vertexCount: number, materialType: number, materialParam: number, id: number, center: { number }, flexes: { Flex }, lodVertices: { number } }
|
||||
export type Model = { name: string, kind: number, radius: number, vertexIndex: number, vertexCount: number, tangentIndex: number, meshes: { Mesh }, eyeballs: number }
|
||||
export type BodyPart = { name: string, base: number, models: { Model } }
|
||||
export type AnimDesc = { name: string, fps: number, flags: number, frames: number, block: number, index: number, sectionIndex: number, sectionFrames: number, at: number, movements: number, ikRules: number }
|
||||
export type Header = {
|
||||
version: number,
|
||||
checksum: number,
|
||||
name: string,
|
||||
length: number,
|
||||
eye: { number },
|
||||
illum: { number },
|
||||
hullMin: { number },
|
||||
hullMax: { number },
|
||||
viewMin: { number },
|
||||
viewMax: { number },
|
||||
flags: number,
|
||||
bones: { Bone },
|
||||
controllers: { any },
|
||||
hitboxSets: { any },
|
||||
anims: { AnimDesc },
|
||||
sequences: { any },
|
||||
textures: { { name: string, flags: number } },
|
||||
cdmaterials: { string },
|
||||
skins: { { number } }, -- families of 0-based texture indices per skin reference
|
||||
skinRefs: number,
|
||||
bodyParts: { BodyPart },
|
||||
attachments: { any },
|
||||
flexDescs: { string },
|
||||
flexControllers: { any },
|
||||
flexRules: { any },
|
||||
poseParameters: { any },
|
||||
includeModels: { any },
|
||||
surfaceProp: string,
|
||||
keyValues: string,
|
||||
mass: number,
|
||||
contents: number,
|
||||
animBlockName: string,
|
||||
animBlocks: { { number } }, -- { datastart, dataend }
|
||||
vertAnimScale: number,
|
||||
rootLod: number,
|
||||
allowedRootLods: number,
|
||||
ikChains: number,
|
||||
nodes: { string },
|
||||
}
|
||||
|
||||
local PROCEDURAL = { "axisinterp", "quatinterp", "aimatbone", "aimatattach", "jiggle" }
|
||||
local JIGGLE = {
|
||||
"length", "tipMass", "yawStiffness", "yawDamping", "pitchStiffness", "pitchDamping", "alongStiffness", "alongDamping",
|
||||
"angleLimit", "minYaw", "maxYaw", "yawFriction", "yawBounce", "minPitch", "maxPitch", "pitchFriction", "pitchBounce",
|
||||
"baseMass", "baseStiffness", "baseDamping", "baseMinLeft", "baseMaxLeft", "baseLeftFriction", "baseMinUp", "baseMaxUp",
|
||||
"baseUpFriction", "baseMinForward", "baseMaxForward", "baseForwardFriction",
|
||||
}
|
||||
|
||||
function Mdl.parse(b: buffer, base: number, size: number, opts: { maxVertices: number? }?): (Header?, string?)
|
||||
if size < 408 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local function i32(o: number): number
|
||||
return readi32(b, base + o)
|
||||
end
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
local function table_(count: number, at: number, stride: number, max: number, what: string): string?
|
||||
if count < 0 or count > max or (count > 0 and not inside(at, count * stride)) then
|
||||
return "bad " .. what .. " table"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local function str(o: number): string
|
||||
if o < 0 or o >= size then
|
||||
return ""
|
||||
end
|
||||
local n = math.min(size - o, 4096)
|
||||
return (string.match(buffer.readstring(b, base + o, n), "^[^%z]*")) :: string
|
||||
end
|
||||
local function vec(o: number, n: number?): { number }
|
||||
local v = {}
|
||||
for k = 0, (n or 3) - 1 do
|
||||
v[k + 1] = readf32(b, base + o + k * 4)
|
||||
end
|
||||
return v
|
||||
end
|
||||
local h: any = {
|
||||
version = i32(4),
|
||||
checksum = readu32(b, base + 8),
|
||||
name = (string.match(buffer.readstring(b, base + 12, 64), "^[^%z]*")) :: string,
|
||||
length = i32(76),
|
||||
eye = vec(80),
|
||||
illum = vec(92),
|
||||
hullMin = vec(104),
|
||||
hullMax = vec(116),
|
||||
viewMin = vec(128),
|
||||
viewMax = vec(140),
|
||||
flags = readu32(b, base + 152),
|
||||
mass = readf32(b, base + 328),
|
||||
contents = i32(332),
|
||||
rootLod = readu8(b, base + 377),
|
||||
allowedRootLods = readu8(b, base + 378),
|
||||
vertAnimScale = readf32(b, base + 392),
|
||||
ikChains = i32(284),
|
||||
}
|
||||
local hdr2 = i32(400)
|
||||
if hdr2 > 0 and inside(hdr2, 24) then
|
||||
local long = readi32(b, base + hdr2 + 20)
|
||||
if long > 0 then
|
||||
local s = str(hdr2 + long)
|
||||
if s ~= "" then
|
||||
h.name = s
|
||||
end
|
||||
end
|
||||
end
|
||||
local nBones, oBones = i32(156), i32(160)
|
||||
local e = table_(nBones, oBones, 216, 4096, "bone")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.bones = {}
|
||||
for i = 0, nBones - 1 do
|
||||
local o = oBones + i * 216
|
||||
local bone: Bone = {
|
||||
name = str(o + i32(o)),
|
||||
parent = i32(o + 4),
|
||||
controllers = {},
|
||||
pos = vec(o + 32),
|
||||
quat = vec(o + 44, 4),
|
||||
rot = vec(o + 60),
|
||||
posScale = vec(o + 72),
|
||||
rotScale = vec(o + 84),
|
||||
poseToBone = vec(o + 96, 12),
|
||||
flags = readu32(b, base + o + 160),
|
||||
physicsBone = i32(o + 172),
|
||||
surfaceProp = str(o + i32(o + 176)),
|
||||
contents = i32(o + 180),
|
||||
}
|
||||
for k = 0, 5 do
|
||||
bone.controllers[k + 1] = i32(o + 8 + k * 4)
|
||||
end
|
||||
if bone.parent < -1 or bone.parent >= i then
|
||||
return nil, "bone " .. i .. ": bad parent"
|
||||
end
|
||||
local ptype, pidx = i32(o + 164), i32(o + 168)
|
||||
if ptype > 0 and pidx ~= 0 then
|
||||
local po = o + pidx
|
||||
local rule: { [string]: any } = { type = PROCEDURAL[ptype] or ptype }
|
||||
if ptype == 1 and inside(po, 176) then
|
||||
rule.control = i32(po)
|
||||
rule.axis = i32(po + 4)
|
||||
rule.pos, rule.quat = {}, {}
|
||||
for k = 0, 5 do
|
||||
rule.pos[k + 1] = vec(po + 8 + k * 12)
|
||||
rule.quat[k + 1] = vec(po + 80 + k * 16, 4)
|
||||
end
|
||||
elseif ptype == 2 and inside(po, 12) then
|
||||
rule.control = i32(po)
|
||||
local n, t = i32(po + 4), i32(po + 8)
|
||||
rule.triggers = {}
|
||||
if n > 0 and n <= 256 and inside(po + t, n * 48) then
|
||||
for k = 0, n - 1 do
|
||||
local to = po + t + k * 48
|
||||
rule.triggers[k + 1] = { invTolerance = readf32(b, base + to), trigger = vec(to + 4, 4), pos = vec(to + 20), quat = vec(to + 32, 4) }
|
||||
end
|
||||
end
|
||||
elseif (ptype == 3 or ptype == 4) and inside(po, 44) then
|
||||
rule.parent = i32(po)
|
||||
rule.aim = i32(po + 4)
|
||||
rule.aimVector = vec(po + 8)
|
||||
rule.upVector = vec(po + 20)
|
||||
rule.basePos = vec(po + 32)
|
||||
elseif ptype == 5 and inside(po, 120) then
|
||||
rule.flags = i32(po)
|
||||
for k, key in JIGGLE do
|
||||
rule[key] = readf32(b, base + po + k * 4)
|
||||
end
|
||||
end
|
||||
bone.procedural = rule
|
||||
end
|
||||
h.bones[i + 1] = bone
|
||||
end
|
||||
local nCtl, oCtl = i32(164), i32(168)
|
||||
e = table_(nCtl, oCtl, 56, 4096, "bone controller")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.controllers = {}
|
||||
for i = 0, nCtl - 1 do
|
||||
local o = oCtl + i * 56
|
||||
h.controllers[i + 1] = { bone = i32(o), type = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), rest = i32(o + 16), input = i32(o + 20) }
|
||||
end
|
||||
local nSets, oSets = i32(172), i32(176)
|
||||
e = table_(nSets, oSets, 12, 256, "hitbox set")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.hitboxSets = {}
|
||||
for i = 0, nSets - 1 do
|
||||
local o = oSets + i * 12
|
||||
local n, at = i32(o + 4), i32(o + 8)
|
||||
local set = { name = str(o + i32(o)), boxes = {} }
|
||||
if n > 0 and n <= 65536 and inside(o + at, n * 68) then
|
||||
for k = 0, n - 1 do
|
||||
local bo = o + at + k * 68
|
||||
local nameOff = i32(bo + 32)
|
||||
table.insert(set.boxes, { bone = i32(bo), group = i32(bo + 4), min = vec(bo + 8), max = vec(bo + 20), name = if nameOff ~= 0 then str(bo + nameOff) else "" })
|
||||
end
|
||||
end
|
||||
h.hitboxSets[i + 1] = set
|
||||
end
|
||||
local nAnim, oAnim = i32(180), i32(184)
|
||||
e = table_(nAnim, oAnim, 100, 65536, "animation")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.anims = {}
|
||||
for i = 0, nAnim - 1 do
|
||||
local o = oAnim + i * 100
|
||||
h.anims[i + 1] = {
|
||||
at = o,
|
||||
name = str(o + i32(o + 4)),
|
||||
fps = readf32(b, base + o + 8),
|
||||
flags = i32(o + 12),
|
||||
frames = i32(o + 16),
|
||||
movements = i32(o + 20),
|
||||
block = i32(o + 52),
|
||||
index = i32(o + 56),
|
||||
ikRules = i32(o + 60),
|
||||
sectionIndex = i32(o + 80),
|
||||
sectionFrames = i32(o + 84),
|
||||
}
|
||||
end
|
||||
local nSeq, oSeq = i32(188), i32(192)
|
||||
e = table_(nSeq, oSeq, 212, 65536, "sequence")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.sequences = {}
|
||||
for i = 0, nSeq - 1 do
|
||||
local o = oSeq + i * 212
|
||||
local g0, g1 = i32(o + 68), i32(o + 72)
|
||||
local anims = {}
|
||||
local ai = i32(o + 60)
|
||||
if g0 > 0 and g1 > 0 and g0 * g1 <= 4096 and inside(o + ai, g0 * g1 * 2) then
|
||||
for k = 0, g0 * g1 - 1 do
|
||||
anims[k + 1] = readi16(b, base + o + ai + k * 2)
|
||||
end
|
||||
end
|
||||
local events = {}
|
||||
local ne, eo = i32(o + 24), i32(o + 28)
|
||||
if ne > 0 and ne <= 4096 and inside(o + eo, ne * 80) then
|
||||
for k = 0, ne - 1 do
|
||||
local ev = o + eo + k * 80
|
||||
local nameOff = i32(ev + 76)
|
||||
table.insert(events, {
|
||||
cycle = readf32(b, base + ev),
|
||||
event = i32(ev + 4),
|
||||
type = i32(ev + 8),
|
||||
options = (string.match(buffer.readstring(b, base + ev + 12, 64), "^[^%z]*")) :: string,
|
||||
name = if nameOff ~= 0 then str(ev + nameOff) else "",
|
||||
})
|
||||
end
|
||||
end
|
||||
local kvSize = i32(o + 176)
|
||||
h.sequences[i + 1] = {
|
||||
name = str(o + i32(o + 4)),
|
||||
activity = str(o + i32(o + 8)),
|
||||
flags = i32(o + 12),
|
||||
activityId = i32(o + 16),
|
||||
weight = i32(o + 20),
|
||||
events = events,
|
||||
bboxMin = vec(o + 32),
|
||||
bboxMax = vec(o + 44),
|
||||
blends = i32(o + 56),
|
||||
groupSize = { g0, g1 },
|
||||
anims = anims,
|
||||
paramIndex = { i32(o + 76), i32(o + 80) },
|
||||
paramStart = vec(o + 84, 2),
|
||||
paramEnd = vec(o + 92, 2),
|
||||
fadeIn = readf32(b, base + o + 104),
|
||||
fadeOut = readf32(b, base + o + 108),
|
||||
nextSequence = i32(o + 136),
|
||||
keyValues = if kvSize > 0 then str(o + i32(o + 172)) else "",
|
||||
}
|
||||
end
|
||||
local nTex, oTex = i32(204), i32(208)
|
||||
e = table_(nTex, oTex, 64, 65536, "texture")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.textures = {}
|
||||
for i = 0, nTex - 1 do
|
||||
local o = oTex + i * 64
|
||||
h.textures[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4) }
|
||||
end
|
||||
local nCd, oCd = i32(212), i32(216)
|
||||
e = table_(nCd, oCd, 4, 4096, "cdmaterials")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.cdmaterials = {}
|
||||
for i = 0, nCd - 1 do
|
||||
h.cdmaterials[i + 1] = str(i32(oCd + i * 4))
|
||||
end
|
||||
local nRef, nFam, oSkin = i32(220), i32(224), i32(228)
|
||||
if nRef < 0 or nFam < 0 or nRef * nFam > 1048576 or (nRef * nFam > 0 and not inside(oSkin, nRef * nFam * 2)) then
|
||||
return nil, "bad skin table"
|
||||
end
|
||||
h.skins, h.skinRefs = {}, nRef
|
||||
for f = 0, nFam - 1 do
|
||||
local fam = {}
|
||||
for r = 0, nRef - 1 do
|
||||
fam[r + 1] = readi16(b, base + oSkin + (f * nRef + r) * 2)
|
||||
end
|
||||
h.skins[f + 1] = fam
|
||||
end
|
||||
local nParts, oParts = i32(232), i32(236)
|
||||
e = table_(nParts, oParts, 16, 4096, "body part")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
local maxVerts = opts and opts.maxVertices or 2 ^ 24
|
||||
local totalFlex = 0
|
||||
h.bodyParts = {}
|
||||
for p = 0, nParts - 1 do
|
||||
local po = oParts + p * 16
|
||||
local nModels, oModels = i32(po + 4), i32(po + 12)
|
||||
local part: BodyPart = { name = str(po + i32(po)), base = i32(po + 8), models = {} }
|
||||
if nModels < 0 or nModels > 4096 or (nModels > 0 and not inside(po + oModels, nModels * 148)) then
|
||||
return nil, "body part " .. p .. ": bad model table"
|
||||
end
|
||||
for m = 0, nModels - 1 do
|
||||
local mo = po + oModels + m * 148
|
||||
local nMesh, oMesh = i32(mo + 72), i32(mo + 76)
|
||||
local model: Model = {
|
||||
name = (string.match(buffer.readstring(b, base + mo, 64), "^[^%z]*")) :: string,
|
||||
kind = i32(mo + 64),
|
||||
radius = readf32(b, base + mo + 68),
|
||||
vertexCount = i32(mo + 80),
|
||||
vertexIndex = i32(mo + 84),
|
||||
tangentIndex = i32(mo + 88),
|
||||
eyeballs = i32(mo + 100),
|
||||
meshes = {},
|
||||
}
|
||||
if nMesh < 0 or nMesh > 4096 or (nMesh > 0 and not inside(mo + oMesh, nMesh * 116)) or model.vertexCount < 0 or model.vertexCount > maxVerts or model.vertexIndex < 0 then
|
||||
return nil, "model " .. model.name .. ": bad mesh table"
|
||||
end
|
||||
for k = 0, nMesh - 1 do
|
||||
local me = mo + oMesh + k * 116
|
||||
local mesh: Mesh = {
|
||||
material = i32(me),
|
||||
vertexCount = i32(me + 8),
|
||||
vertexOffset = i32(me + 12),
|
||||
materialType = i32(me + 24),
|
||||
materialParam = i32(me + 28),
|
||||
id = i32(me + 32),
|
||||
center = vec(me + 36),
|
||||
flexes = {},
|
||||
lodVertices = {},
|
||||
}
|
||||
for l = 0, 7 do
|
||||
mesh.lodVertices[l + 1] = i32(me + 52 + l * 4)
|
||||
end
|
||||
if mesh.vertexCount < 0 or mesh.vertexOffset < 0 or mesh.vertexOffset + mesh.vertexCount > model.vertexCount then
|
||||
return nil, "mesh " .. k .. ": vertex range outside its model"
|
||||
end
|
||||
local nFlex, oFlex = i32(me + 16), i32(me + 20)
|
||||
if nFlex < 0 or nFlex > 4096 or (nFlex > 0 and not inside(me + oFlex, nFlex * 60)) then
|
||||
return nil, "mesh " .. k .. ": bad flex table"
|
||||
end
|
||||
for f = 0, nFlex - 1 do
|
||||
local fo = me + oFlex + f * 60
|
||||
local nv, vo = i32(fo + 20), i32(fo + 24)
|
||||
local kind = readu8(b, base + fo + 32)
|
||||
local stride = if kind == 1 then 18 else 16
|
||||
totalFlex += math.max(nv, 0)
|
||||
if nv < 0 or totalFlex > maxVerts or (nv > 0 and not inside(fo + vo, nv * stride)) then
|
||||
return nil, "flex " .. f .. ": bad vertex animation table"
|
||||
end
|
||||
local flex: Flex = { desc = i32(fo), targets = vec(fo + 4, 4), partner = i32(fo + 28), kind = kind, deltas = {} }
|
||||
local fixed = bit32.band(h.flags, 0x200000) ~= 0
|
||||
local scale = h.vertAnimScale
|
||||
for v = 0, nv - 1 do
|
||||
local a = base + fo + vo + v * stride
|
||||
local d = { readu16(b, a) }
|
||||
for c = 0, 5 do
|
||||
d[c + 2] = if fixed then readi16(b, a + 4 + c * 2) * scale else HALF[readu16(b, a + 4 + c * 2)]
|
||||
end
|
||||
d[8] = readu8(b, a + 3) / 255
|
||||
d[9] = readu8(b, a + 2) / 255
|
||||
d[10] = if kind == 1 then readi16(b, a + 16) / 32767 else 0
|
||||
flex.deltas[v + 1] = d
|
||||
end
|
||||
table.insert(mesh.flexes, flex)
|
||||
end
|
||||
table.insert(model.meshes, mesh)
|
||||
end
|
||||
table.insert(part.models, model)
|
||||
end
|
||||
h.bodyParts[p + 1] = part
|
||||
end
|
||||
local nAtt, oAtt = i32(240), i32(244)
|
||||
e = table_(nAtt, oAtt, 92, 4096, "attachment")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.attachments = {}
|
||||
for i = 0, nAtt - 1 do
|
||||
local o = oAtt + i * 92
|
||||
h.attachments[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), bone = i32(o + 8), matrix = vec(o + 12, 12) }
|
||||
end
|
||||
local nNodes, oNodeNames = i32(248), i32(256)
|
||||
h.nodes = {}
|
||||
if nNodes > 0 and nNodes <= 1024 and inside(oNodeNames, nNodes * 4) then
|
||||
for i = 0, nNodes - 1 do
|
||||
h.nodes[i + 1] = str(i32(oNodeNames + i * 4))
|
||||
end
|
||||
end
|
||||
local nDesc, oDesc = i32(260), i32(264)
|
||||
e = table_(nDesc, oDesc, 4, 65536, "flex description")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexDescs = {}
|
||||
for i = 0, nDesc - 1 do
|
||||
local o = oDesc + i * 4
|
||||
h.flexDescs[i + 1] = str(o + i32(o))
|
||||
end
|
||||
local nFc, oFc = i32(268), i32(272)
|
||||
e = table_(nFc, oFc, 20, 65536, "flex controller")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexControllers = {}
|
||||
for i = 0, nFc - 1 do
|
||||
local o = oFc + i * 20
|
||||
h.flexControllers[i + 1] = { type = str(o + i32(o)), name = str(o + i32(o + 4)), localToGlobal = i32(o + 8), min = readf32(b, base + o + 12), max = readf32(b, base + o + 16) }
|
||||
end
|
||||
local nRule, oRule = i32(276), i32(280)
|
||||
e = table_(nRule, oRule, 12, 65536, "flex rule")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexRules = {}
|
||||
for i = 0, nRule - 1 do
|
||||
local o = oRule + i * 12
|
||||
local n, at = i32(o + 4), i32(o + 8)
|
||||
local ops = {}
|
||||
if n > 0 and n <= 65536 and inside(o + at, n * 8) then
|
||||
for k = 0, n - 1 do
|
||||
local oo = o + at + k * 8
|
||||
local op = i32(oo)
|
||||
ops[k + 1] = { op = op, value = if op == 1 then readf32(b, base + oo + 4) else i32(oo + 4) }
|
||||
end
|
||||
end
|
||||
h.flexRules[i + 1] = { flex = i32(o), ops = ops }
|
||||
end
|
||||
local nPose, oPose = i32(300), i32(304)
|
||||
e = table_(nPose, oPose, 20, 4096, "pose parameter")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.poseParameters = {}
|
||||
for i = 0, nPose - 1 do
|
||||
local o = oPose + i * 20
|
||||
h.poseParameters[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), loop = readf32(b, base + o + 16) }
|
||||
end
|
||||
h.surfaceProp = str(i32(308))
|
||||
local kvAt, kvSize = i32(312), i32(316)
|
||||
h.keyValues = if kvSize > 0 and inside(kvAt, 1) then string.sub(str(kvAt), 1, kvSize) else ""
|
||||
local nInc, oInc = i32(336), i32(340)
|
||||
e = table_(nInc, oInc, 8, 4096, "include model")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.includeModels = {}
|
||||
for i = 0, nInc - 1 do
|
||||
local o = oInc + i * 8
|
||||
local l, f = i32(o), i32(o + 4)
|
||||
h.includeModels[i + 1] = { label = if l ~= 0 then str(o + l) else "", file = if f ~= 0 then str(o + f) else "" }
|
||||
end
|
||||
local nameAt = i32(348)
|
||||
h.animBlockName = if nameAt > 0 then str(nameAt) else ""
|
||||
local nBlk, oBlk = i32(352), i32(356)
|
||||
h.animBlocks = {}
|
||||
if nBlk > 0 and nBlk <= 65536 and inside(oBlk, nBlk * 8) then
|
||||
for i = 0, nBlk - 1 do
|
||||
h.animBlocks[i + 1] = { i32(oBlk + i * 8), i32(oBlk + i * 8 + 4) }
|
||||
end
|
||||
end
|
||||
return h :: Header, nil
|
||||
end
|
||||
|
||||
return Mdl
|
||||
@@ -0,0 +1,121 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Phy: ".phy" collision models (phyheader_t; "VPHY" or legacy IVP compact surfaces: the ledge tree's
|
||||
-- leaf convex hulls; the trailing KeyValues text), from Source SDK 2013 public/phyfile.h, the IVP compact surface
|
||||
-- layout (ivp_compact_surface.hxx, ivp_compact_ledge.hxx) and SourceIO (MIT) notes; no code taken.
|
||||
local Phy = {}
|
||||
|
||||
local readi32, readu32, readu16, readi16, readf32 = buffer.readi32, buffer.readu32, buffer.readu16, buffer.readi16, buffer.readf32
|
||||
|
||||
export type Hull = { positions: { number }, indices: { number }, bone: number }
|
||||
export type Solid = { hulls: { Hull }, version: number?, kind: number? }
|
||||
export type Physics = { checksum: number, solids: { Solid }, text: string }
|
||||
|
||||
local METERS = 1 / 0.0254
|
||||
|
||||
local function surface(b: buffer, at: number, limit: number, out: Solid, budget: { number }): string?
|
||||
if at + 48 > limit then
|
||||
return "truncated collision surface"
|
||||
end
|
||||
local root = readi32(b, at + 32)
|
||||
local seen = 0
|
||||
local function ledge(lo: number): string?
|
||||
if lo + 16 > limit then
|
||||
return "truncated ledge"
|
||||
end
|
||||
local pts, client, nTri = readi32(b, lo), readi32(b, lo + 4), readi16(b, lo + 12)
|
||||
if nTri < 0 or lo + 16 + nTri * 16 > limit then
|
||||
return "bad ledge"
|
||||
end
|
||||
budget[1] -= nTri
|
||||
if budget[1] < 0 then
|
||||
return "limit: too many collision triangles"
|
||||
end
|
||||
local map: { [number]: number } = {}
|
||||
local hull: Hull = { positions = {}, indices = {}, bone = client }
|
||||
for t = 0, nTri - 1 do
|
||||
local to = lo + 16 + t * 16
|
||||
for e = 0, 2 do
|
||||
local id = readu16(b, to + 4 + e * 4)
|
||||
local v = map[id]
|
||||
if not v then
|
||||
local po = lo + pts + id * 16
|
||||
if po < 0 or po + 12 > limit then
|
||||
return "collision vertex out of range"
|
||||
end
|
||||
local x, y, z = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
|
||||
table.insert(hull.positions, x * METERS)
|
||||
table.insert(hull.positions, z * METERS)
|
||||
table.insert(hull.positions, -y * METERS)
|
||||
v = #hull.positions // 3 - 1
|
||||
map[id] = v
|
||||
end
|
||||
table.insert(hull.indices, v)
|
||||
end
|
||||
end
|
||||
table.insert(out.hulls, hull)
|
||||
return nil
|
||||
end
|
||||
local function node(no: number, depth: number): string?
|
||||
seen += 1
|
||||
if depth > 64 or seen > 65536 or no + 28 > limit or no < at then
|
||||
return "bad ledge tree"
|
||||
end
|
||||
local right, led = readi32(b, no), readi32(b, no + 4)
|
||||
if right == 0 then
|
||||
if led == 0 then
|
||||
return nil
|
||||
end
|
||||
return ledge(no + led)
|
||||
end
|
||||
local e = node(no + 28, depth + 1)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
return node(no + right, depth + 1)
|
||||
end
|
||||
if root <= 0 then
|
||||
return "bad ledge tree root"
|
||||
end
|
||||
return node(at + root, 0)
|
||||
end
|
||||
|
||||
function Phy.parse(b: buffer, maxTriangles: number?): (Physics?, string?)
|
||||
local size = buffer.len(b)
|
||||
if size < 16 then
|
||||
return nil, "truncated phy header"
|
||||
end
|
||||
local hsize, nSolids = readi32(b, 0), readi32(b, 8)
|
||||
if hsize < 16 or hsize > size or nSolids < 0 or nSolids > 1024 then
|
||||
return nil, "bad phy header"
|
||||
end
|
||||
local out: Physics = { checksum = readu32(b, 12), solids = {}, text = "" }
|
||||
local budget = { maxTriangles or 2 ^ 22 }
|
||||
local p = hsize
|
||||
for _ = 1, nSolids do
|
||||
if p + 4 > size then
|
||||
return nil, "truncated phy solid"
|
||||
end
|
||||
local n = readi32(b, p)
|
||||
if n < 0 or p + 4 + n > size then
|
||||
return nil, "truncated phy solid"
|
||||
end
|
||||
local s: Solid = { hulls = {} }
|
||||
local at = p + 4
|
||||
if n >= 28 and buffer.readstring(b, at, 4) == "VPHY" then
|
||||
s.version, s.kind = readu16(b, at + 4), readu16(b, at + 6)
|
||||
at += 28
|
||||
end
|
||||
local e = surface(b, at, p + 4 + n, s, budget)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
table.insert(out.solids, s)
|
||||
p += 4 + n
|
||||
end
|
||||
if p < size then
|
||||
out.text = (string.match(buffer.readstring(b, p, size - p), "^[^%z]*")) :: string
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Phy
|
||||
@@ -0,0 +1,180 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Vtx: ".vtx" optimized strips (version 7: body part / model / LOD / mesh / strip group / strip
|
||||
-- headers, 9-byte vertices, u16 indices; the 33 / 35-byte strip group / strip headers of later branches too), from
|
||||
-- Source SDK 2013 public/optimize.h.
|
||||
local Vtx = {}
|
||||
|
||||
local readi32, readu16, readu8, readi16, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readi16, buffer.readf32
|
||||
|
||||
export type Mesh = { flags: number, indices: { number } } -- triangles of mesh-relative vertex ids, file winding
|
||||
export type Lod = { switchPoint: number, meshes: { Mesh } }
|
||||
export type Strips = {
|
||||
checksum: number,
|
||||
lods: number,
|
||||
parts: { { { Lod } } }, -- parts[p][m][lod]
|
||||
replacements: { { { material: number, name: string } } }, -- per LOD
|
||||
maxBonesPerStrip: number,
|
||||
extended: boolean,
|
||||
}
|
||||
|
||||
local function walk(b: buffer, ext: boolean, maxIndices: number): (Strips?, string?)
|
||||
local size = buffer.len(b)
|
||||
local sgStride, stStride = if ext then 33 else 25, if ext then 35 else 27
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
local nParts, oParts = readi32(b, 28), readi32(b, 32)
|
||||
if nParts < 0 or nParts > 4096 or not inside(oParts, nParts * 8) then
|
||||
return nil, "bad vtx body part table"
|
||||
end
|
||||
local total = 0
|
||||
local parts = {}
|
||||
for p = 0, nParts - 1 do
|
||||
local po = oParts + p * 8
|
||||
local nModels, oModels = readi32(b, po), readi32(b, po + 4)
|
||||
if nModels < 0 or nModels > 4096 or not inside(po + oModels, nModels * 8) then
|
||||
return nil, "bad vtx model table"
|
||||
end
|
||||
local models = {}
|
||||
for m = 0, nModels - 1 do
|
||||
local mo = po + oModels + m * 8
|
||||
local nLods, oLods = readi32(b, mo), readi32(b, mo + 4)
|
||||
if nLods < 0 or nLods > 8 or not inside(mo + oLods, nLods * 12) then
|
||||
return nil, "bad vtx lod table"
|
||||
end
|
||||
local lods = {}
|
||||
for l = 0, nLods - 1 do
|
||||
local lo = mo + oLods + l * 12
|
||||
local nMesh, oMesh = readi32(b, lo), readi32(b, lo + 4)
|
||||
if nMesh < 0 or nMesh > 4096 or not inside(lo + oMesh, nMesh * 9) then
|
||||
return nil, "bad vtx mesh table"
|
||||
end
|
||||
local meshes = {}
|
||||
for k = 0, nMesh - 1 do
|
||||
local me = lo + oMesh + k * 9
|
||||
local nGroups, oGroups = readi32(b, me), readi32(b, me + 4)
|
||||
if nGroups < 0 or nGroups > 4096 or not inside(me + oGroups, nGroups * sgStride) then
|
||||
return nil, "bad vtx strip group table"
|
||||
end
|
||||
local tris: { number } = {}
|
||||
for g = 0, nGroups - 1 do
|
||||
local go = me + oGroups + g * sgStride
|
||||
local nv, ov, ni, oi = readi32(b, go), readi32(b, go + 4), readi32(b, go + 8), readi32(b, go + 12)
|
||||
local ns, os = readi32(b, go + 16), readi32(b, go + 20)
|
||||
if not inside(go + ov, nv * 9) or not inside(go + oi, ni * 2) or ns < 0 or ns > 65536 or not inside(go + os, ns * stStride) then
|
||||
return nil, "bad vtx strip group"
|
||||
end
|
||||
total += ni
|
||||
if total > maxIndices then
|
||||
return nil, "limit: too many indices"
|
||||
end
|
||||
local vbase, ibase = go + ov, go + oi
|
||||
local function vid(i: number): number?
|
||||
if i < 0 or i >= ni then
|
||||
return nil
|
||||
end
|
||||
local v = readu16(b, ibase + i * 2)
|
||||
if v >= nv then
|
||||
return nil
|
||||
end
|
||||
return readu16(b, vbase + v * 9 + 4)
|
||||
end
|
||||
local function strip(first: number, count: number, list: boolean): boolean
|
||||
if list then
|
||||
for i = first, first + count - 3, 3 do
|
||||
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
|
||||
if not a or not c or not d then
|
||||
return false
|
||||
end
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, d)
|
||||
end
|
||||
else
|
||||
for i = first, first + count - 3 do
|
||||
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
|
||||
if not a or not c or not d then
|
||||
return false
|
||||
end
|
||||
if a ~= c and c ~= d and a ~= d then
|
||||
if (i - first) % 2 == 0 then
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, d)
|
||||
else
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if ns == 0 then
|
||||
if not strip(0, ni, true) then
|
||||
return nil, "bad vtx index"
|
||||
end
|
||||
end
|
||||
for s = 0, ns - 1 do
|
||||
local so = go + os + s * stStride
|
||||
local sni, sio = readi32(b, so), readi32(b, so + 4)
|
||||
local flags = readu8(b, so + 18)
|
||||
if sni < 0 or sio < 0 or sio + sni > ni then
|
||||
return nil, "bad vtx strip"
|
||||
end
|
||||
if not strip(sio, sni, bit32.band(flags, 2) == 0) then
|
||||
return nil, "bad vtx index"
|
||||
end
|
||||
end
|
||||
end
|
||||
meshes[k + 1] = { flags = readu8(b, me + 8), indices = tris }
|
||||
end
|
||||
lods[l + 1] = { switchPoint = readf32(b, lo + 8), meshes = meshes }
|
||||
end
|
||||
models[m + 1] = lods
|
||||
end
|
||||
parts[p + 1] = models
|
||||
end
|
||||
local nLods = readi32(b, 20)
|
||||
local reps = {}
|
||||
local oRep = readi32(b, 24)
|
||||
if nLods > 0 and nLods <= 8 and inside(oRep, nLods * 8) then
|
||||
for l = 0, nLods - 1 do
|
||||
local ro = oRep + l * 8
|
||||
local n, at = readi32(b, ro), readi32(b, ro + 4)
|
||||
local list = {}
|
||||
if n > 0 and n <= 4096 and inside(ro + at, n * 6) then
|
||||
for k = 0, n - 1 do
|
||||
local eo = ro + at + k * 6
|
||||
local no = eo + readi32(b, eo + 2)
|
||||
local name = if no >= 0 and no < size then (string.match(buffer.readstring(b, no, math.min(size - no, 1024)), "^[^%z]*")) :: string else ""
|
||||
list[k + 1] = { material = readi16(b, eo), name = name }
|
||||
end
|
||||
end
|
||||
reps[l + 1] = list
|
||||
end
|
||||
end
|
||||
return { checksum = readi32(b, 16), lods = nLods, parts = parts, replacements = reps, maxBonesPerStrip = readu16(b, 8), extended = ext }, nil
|
||||
end
|
||||
|
||||
function Vtx.parse(b: buffer, maxIndices: number?): (Strips?, string?)
|
||||
if buffer.len(b) < 36 then
|
||||
return nil, "truncated vtx header"
|
||||
end
|
||||
local version = readi32(b, 0)
|
||||
if version ~= 7 then
|
||||
return nil, "unsupported: vtx version " .. version
|
||||
end
|
||||
local s, err = walk(b, false, maxIndices or 2 ^ 26)
|
||||
if s then
|
||||
return s, nil
|
||||
end
|
||||
local s2 = walk(b, true, maxIndices or 2 ^ 26)
|
||||
if s2 then
|
||||
return s2, nil
|
||||
end
|
||||
return nil, err
|
||||
end
|
||||
|
||||
return Vtx
|
||||
@@ -0,0 +1,92 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Vvd: ".vvd" vertex data ("IDSV" v4: 48-byte mstudiovertex_t records, 16-byte tangents, the LOD
|
||||
-- fixup table), from Source SDK 2013 public/studio.h (vertexFileHeader_t) and Studio_LoadVertexes.
|
||||
local Vvd = {}
|
||||
|
||||
local readi32, readu32 = buffer.readi32, buffer.readu32
|
||||
|
||||
export type Vertices = {
|
||||
checksum: number,
|
||||
lods: number,
|
||||
lodCounts: { number },
|
||||
count: number,
|
||||
data: buffer, -- count * 48: weight f32[3], bone u8[3], numbones u8, position f32[3], normal f32[3], uv f32[2]
|
||||
tangents: buffer?, -- count * 16: x, y, z, w
|
||||
fixups: number,
|
||||
}
|
||||
|
||||
-- the vertices of LOD `lod` and above, in fixup order (lod 0: every vertex, the layout the MDL meshes index)
|
||||
function Vvd.parse(b: buffer, lod: number?, maxVertices: number?): (Vertices?, string?)
|
||||
local size = buffer.len(b)
|
||||
if size < 64 then
|
||||
return nil, "truncated vvd header"
|
||||
end
|
||||
if buffer.readstring(b, 0, 4) ~= "IDSV" then
|
||||
return nil, "not a vvd file"
|
||||
end
|
||||
local version = readi32(b, 4)
|
||||
if version ~= 4 then
|
||||
return nil, "unsupported: vvd version " .. version
|
||||
end
|
||||
local nLods = readi32(b, 12)
|
||||
local counts = {}
|
||||
for i = 0, 7 do
|
||||
counts[i + 1] = readi32(b, 16 + i * 4)
|
||||
end
|
||||
local nFix, oFix, oVert, oTan = readi32(b, 48), readi32(b, 52), readi32(b, 56), readi32(b, 60)
|
||||
local total = counts[1]
|
||||
if nLods < 1 or nLods > 8 or total < 0 or total > (maxVertices or 2 ^ 24) then
|
||||
return nil, "bad vvd vertex counts"
|
||||
end
|
||||
if oVert < 64 or oVert + total * 48 > size then
|
||||
return nil, "truncated vvd vertex data"
|
||||
end
|
||||
local hasTan = oTan > 0 and oTan + total * 16 <= size
|
||||
local want = math.clamp(lod or 0, 0, nLods - 1)
|
||||
local out: Vertices = { checksum = readu32(b, 8), lods = nLods, lodCounts = counts, count = 0, data = buffer.create(0), fixups = nFix }
|
||||
if nFix <= 0 then
|
||||
out.count = total
|
||||
out.data = buffer.create(total * 48)
|
||||
buffer.copy(out.data, 0, b, oVert, total * 48)
|
||||
if hasTan then
|
||||
local t = buffer.create(total * 16)
|
||||
buffer.copy(t, 0, b, oTan, total * 16)
|
||||
out.tangents = t
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
if nFix > 65536 or oFix < 0 or oFix + nFix * 12 > size then
|
||||
return nil, "bad vvd fixup table"
|
||||
end
|
||||
local n = 0
|
||||
for i = 0, nFix - 1 do
|
||||
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
|
||||
if first < 0 or cnt < 0 or first + cnt > total then
|
||||
return nil, "vvd fixup " .. i .. " out of range"
|
||||
end
|
||||
if fl >= want then
|
||||
n += cnt
|
||||
end
|
||||
end
|
||||
if n > total * 8 then
|
||||
return nil, "bad vvd fixup table"
|
||||
end
|
||||
out.count = n
|
||||
out.data = buffer.create(n * 48)
|
||||
local tan = if hasTan then buffer.create(n * 16) else nil
|
||||
local at = 0
|
||||
for i = 0, nFix - 1 do
|
||||
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
|
||||
if fl >= want then
|
||||
buffer.copy(out.data, at * 48, b, oVert + first * 48, cnt * 48)
|
||||
if tan then
|
||||
buffer.copy(tan, at * 16, b, oTan + first * 16, cnt * 16)
|
||||
end
|
||||
at += cnt
|
||||
end
|
||||
end
|
||||
out.tangents = tan
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Vvd
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- model/sourcemdl: Source engine studio models ("IDST" v44-49) with their .vvd vertices (LOD fixups), .vtx strips
|
||||
-- (.dx90 / .dx80 / .sw), optional .phy collision and .ani animation blocks, all through opts.resolve / opts.files.
|
||||
-- Skeleton, procedural bones, skin families, body parts, LODs, flexes, attachments, hitboxes, sequences and
|
||||
-- animations; layouts from Source SDK 2013 studio.h / optimize.h, cross-checked with srctools and SourceIO (both MIT).
|
||||
-- Not supported: v52+ frame animations, IK rules, movement, eyeball shading, $includemodel animations.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Input = require("@rosetta/core/Input")
|
||||
local Types = require("@rosetta/Types")
|
||||
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 = require("@rosetta/model/sourcemdl/Build")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local SourceMdl = {
|
||||
name = "sourcemdl",
|
||||
category = "model",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-source-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
name: string?, -- the .mdl file name: its stem names the sibling files (default: the stem of the header name)
|
||||
vvd: (buffer | string)?,
|
||||
vtx: (buffer | string)?,
|
||||
phy: (buffer | string)?,
|
||||
ani: (buffer | string)?,
|
||||
bodies: { number }?, -- 1-based model per body part, default 1
|
||||
lod: number?, -- 1-based LOD for the primitive indices, default 1
|
||||
animations: boolean?, -- default true
|
||||
physics: boolean?, -- default true: read the .phy
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxFrames: number?, -- per animation, default 65536
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local VTX = { "dx90.vtx", "dx80.vtx", "sw.vtx", "vtx" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function SourceMdl.sniff(r: Bytes.Reader): number
|
||||
if r.limit - r.base < 8 or r:peek(4) ~= "IDST" then
|
||||
return 0
|
||||
end
|
||||
local v = buffer.readi32(r.buf, r.base + 4)
|
||||
return if v >= 44 and v <= 49 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function stems(opts: DecodeOptions?, header: string): { string }
|
||||
local out: { string } = {}
|
||||
local function add(s: string?)
|
||||
if s and s ~= "" and not table.find(out, s) then
|
||||
table.insert(out, s)
|
||||
end
|
||||
end
|
||||
local n = opts and opts.name
|
||||
if type(n) == "string" then
|
||||
add((string.gsub(string.match(n, "([^/\\]+)$") or n, "%.[mM][dD][lL]$", "")))
|
||||
end
|
||||
local h = string.gsub(header, "\\", "/")
|
||||
add((string.gsub(string.match(h, "([^/]+)$") or h, "%.[mM][dD][lL]$", "")))
|
||||
add("models/" .. (string.gsub(h, "%.[mM][dD][lL]$", "")))
|
||||
return out
|
||||
end
|
||||
|
||||
local function sibling(opts: DecodeOptions?, direct: (buffer | string)?, names: { string }, exts: { string }): (buffer?, string?)
|
||||
if direct then
|
||||
return Bytes.toBuffer(direct), nil
|
||||
end
|
||||
for _, s in names do
|
||||
for _, e in exts do
|
||||
local uri = s .. "." .. e
|
||||
local b = Input.sibling(opts, uri)
|
||||
if b then
|
||||
return b, uri
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
function SourceMdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
if r:peek(4) ~= "IDST" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local version = buffer.readi32(r.buf, r.base + 4)
|
||||
if version < 44 or version > 49 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version, 4)
|
||||
end
|
||||
local h, perr = Mdl.parse(r.buf, r.base, size, opts)
|
||||
if not h then
|
||||
return nil, Err.from(perr)
|
||||
end
|
||||
local warnings: { string } = {}
|
||||
local names = stems(opts, h.name)
|
||||
local inp: Build.Inputs = { warnings = warnings }
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
local vvdBuf = sibling(opts, opts and opts.vvd, names, { "vvd" })
|
||||
if vvdBuf then
|
||||
local v, e = Vvd.parse(vvdBuf, 0, maxV)
|
||||
if not v then
|
||||
return nil, Err.from("vvd: " .. tostring(e))
|
||||
end
|
||||
if v.checksum ~= h.checksum then
|
||||
table.insert(warnings, "vvd checksum differs from the mdl")
|
||||
end
|
||||
inp.vvd = v
|
||||
else
|
||||
table.insert(warnings, "no .vvd: no geometry")
|
||||
end
|
||||
local vtxBuf, vtxName = sibling(opts, opts and opts.vtx, names, VTX)
|
||||
if vtxBuf then
|
||||
local s, e = Vtx.parse(vtxBuf, maxV * 8)
|
||||
if not s then
|
||||
return nil, Err.from("vtx: " .. tostring(e))
|
||||
end
|
||||
if bit32.band(s.checksum, 0xFFFFFFFF) ~= h.checksum then
|
||||
table.insert(warnings, "vtx checksum differs from the mdl")
|
||||
end
|
||||
inp.vtx = s
|
||||
else
|
||||
table.insert(warnings, "no .vtx: no geometry")
|
||||
end
|
||||
if not (opts and opts.physics == false) then
|
||||
local phyBuf = sibling(opts, opts and opts.phy, names, { "phy" })
|
||||
if phyBuf then
|
||||
local p, e = Phy.parse(phyBuf)
|
||||
if p then
|
||||
inp.phy = p
|
||||
else
|
||||
table.insert(warnings, "phy: " .. tostring(e))
|
||||
end
|
||||
end
|
||||
end
|
||||
if #h.animBlocks > 1 and not (opts and opts.animations == false) then
|
||||
local ani: buffer? = if opts and opts.ani then Bytes.toBuffer(opts.ani) else nil
|
||||
local an = string.gsub(h.animBlockName, "\\", "/")
|
||||
if not ani and an ~= "" then
|
||||
ani = Input.sibling(opts, an) or Input.sibling(opts, string.match(an, "([^/]+)$") or an)
|
||||
end
|
||||
inp.ani = ani
|
||||
end
|
||||
local scene, berr = Build.scene(h, r.buf, r.base, size, inp, opts)
|
||||
if not scene then
|
||||
return nil, Err.from(berr)
|
||||
end
|
||||
local src = scene.meta.source :: { [string]: any }
|
||||
src.vtx = vtxName
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return SourceMdl
|
||||
Reference in new issue
Block a user