diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2c36dcb..ac7dc66 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -44,6 +44,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.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/Formats/Registry.luau b/src/Formats/Registry.luau index 23ca4cf..2a9611b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -482,6 +482,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "smd", + category = "model", + path = "model/smd", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, + load = function() + return require("@formats/model/smd") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau index 3c01612..ce01dd8 100644 --- a/src/Formats/codecs/model/Rig.luau +++ b/src/Formats/codecs/model/Rig.luau @@ -198,15 +198,24 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w end -- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with --- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1. +-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept +-- and normalised to sum 1. function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) for v, l in lists do local pairs_: { { number } } = {} + local at: { [number]: { number } } = {} for k = 1, #l - 1, 2 do if l[k + 1] > 0 then - table.insert(pairs_, { l[k], l[k + 1] }) + local same = at[l[k]] + if same then + same[2] += l[k + 1] -- the same joint twice: one influence + else + local e = { l[k], l[k + 1] } + at[l[k]] = e + table.insert(pairs_, e) + end end end table.sort(pairs_, function(a: { number }, b: { number }): boolean diff --git a/src/Formats/model/smd/Read.luau b/src/Formats/model/smd/Read.luau new file mode 100644 index 0000000..7d1c725 --- /dev/null +++ b/src/Formats/model/smd/Read.luau @@ -0,0 +1,275 @@ +--!strict +-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, +-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone +-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px +-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). +-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material +-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, +-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond +-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Options = { fps: number?, name: string?, maxVertices: number? } + +type Bone = { id: number, name: string, parent: number } +local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } + +-- read(text, opts) -> Scene | nil, message +function Read.read(text: string, opts: Options?): (Types.Scene?, string?) + local lines: { string } = {} + for line in string.gmatch(text, "[^\r\n]*") do + table.insert(lines, line) + end + local i = 1 + local n = #lines + local function nextLine(): string? + while i <= n do + local l = lines[i] + i += 1 + local s = string.match(l, "^%s*(.-)%s*$") :: string + s = string.gsub(s, "%s*//.*$", "") :: string + if s ~= "" then + return s + end + end + return nil + end + local bones: { Bone } = {} + local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based) + local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz } + local times: { number } = {} + type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } } + local batches: { Batch } = {} + local byMat: { [string]: Batch } = {} + local version: number? = nil + local vertexAnimations = 0 + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + while true do + local l = nextLine() + if not l then + break + end + local kw = string.lower(string.match(l, "^(%S+)") or "") + if kw == "version" then + version = tonumber(string.match(l, "^%S+%s+(%S+)")) + elseif kw == "nodes" then + while true do + local s = nextLine() + if not s then + return nil, "truncated: nodes without end" + end + if string.lower(s) == "end" then + break + end + local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)') + if not id then + id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)") + end + if not id then + return nil, "bad node line: " .. s + end + table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number }) + byId[tonumber(id) :: number] = #bones + end + elseif kw == "skeleton" then + local cur: { [number]: { number } }? = nil + while true do + local s = nextLine() + if not s then + return nil, "truncated: skeleton without end" + end + local low = string.lower(s) + if low == "end" then + break + end + local tm = string.match(low, "^time%s+(%-?[%d%.]+)") + if tm then + local prev = frames[#frames] + local f: { [number]: { number } } = {} + if prev then + for k, v in prev do + f[k] = v + end + end + table.insert(frames, f) + table.insert(times, tonumber(tm) :: number) + cur = f + else + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + table.insert(nums, tonumber(tok) or 0 / 0) + end + local bi = byId[nums[1]] + if not cur or #nums < 7 or not bi then + return nil, "bad skeleton line: " .. s + end + cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] } + end + end + elseif kw == "triangles" then + while true do + local mat = nextLine() + if not mat then + return nil, "truncated: triangles without end" + end + if string.lower(mat) == "end" then + break + end + local b = byMat[mat] + if not b then + b = { name = mat, keys = {}, verts = {}, indices = {} } + byMat[mat] = b + table.insert(batches, b) + end + for _ = 1, 3 do + local s = nextLine() + if not s then + return nil, "truncated triangle" + end + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + local v = tonumber(tok) + if not v then + return nil, "bad vertex line: " .. s + end + table.insert(nums, v) + end + if #nums < 9 then + return nil, "short vertex line: " .. s + end + local id = b.keys[s] + if not id then + total += 1 + if total > maxV then + return nil, "limit: too many vertices" + end + table.insert(b.verts, nums) + id = #b.verts - 1 + b.keys[s] = id + end + table.insert(b.indices, id) + end + end + elseif kw == "vertexanimation" then + vertexAnimations += 1 + while true do + local s = nextLine() + if not s or string.lower(s) == "end" then + break + end + end + else + return nil, "unknown section " .. kw + end + end + if version ~= 1 then + return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version) + end + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = opts and opts.name or "smd", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + -- skeleton (bind pose: the first frame) + local joints: { Rig.Joint } = {} + local bind: { [number]: { number } } = frames[1] or {} + for k, bn in bones do + local v: { number } = bind[k] or ZERO + local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0 + joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } + end + local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) + -- meshes + if #batches > 0 then + local mesh: Types.Mesh = { primitives = {} } + for _, b in batches do + local nv = #b.verts + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi, v in b.verts do + local o = (vi - 1) * 12 + writef32(pos, o, v[2]) + writef32(pos, o + 4, v[3]) + writef32(pos, o + 8, v[4]) + writef32(nrm, o, v[5]) + writef32(nrm, o + 4, v[6]) + writef32(nrm, o + 8, v[7]) + writef32(uv, (vi - 1) * 8, v[8]) + writef32(uv, (vi - 1) * 8 + 4, 1 - v[9]) + local l: { number } = {} + local sum = 0 + local nl = if #v >= 10 then math.floor(v[10]) else 0 + for k = 0, nl - 1 do + local bi, w = byId[v[11 + k * 2]], v[12 + k * 2] + if bi and w then + table.insert(l, bi - 1) + table.insert(l, w) + sum += w + end + end + local parent = byId[v[1]] + if parent and sum < 0.999 then + table.insert(l, parent - 1) + table.insert(l, 1 - sum) + end + lists[vi] = l + end + local ib = buffer.create(#b.indices * 4) + for k, id in b.indices do + writeu32(ib, (k - 1) * 4, id) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #bones > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(b.name) + mat.metallic = 0 + table.insert(scene.textures, { name = b.name, uri = b.name }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + -- animation + if #frames > 1 or (#frames == 1 and #batches == 0) then + local fps = opts and opts.fps or 30 + local t: { number } = {} + for k, tm in times do + t[k] = (tm - times[1]) / fps + end + local tracks: { [number]: Rig.Track } = {} + for k = 1, #bones do + local tr: { number }, rot: { number } = {}, {} + for _, f in frames do + local v: { number } = f[k] or bind[k] or ZERO + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + tracks[k] = { translation = tr, rotation = rot } + end + Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR") + end + scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" } + return scene, nil +end + +return Read diff --git a/src/Formats/model/smd/Write.luau b/src/Formats/model/smd/Write.luau new file mode 100644 index 0000000..ed5c2bc --- /dev/null +++ b/src/Formats/model/smd/Write.luau @@ -0,0 +1,250 @@ +--!strict +-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node +-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose +-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled +-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every +-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material +-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the +-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless +-- opts.triangles is true. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") + +local Write = {} + +export type Options = { animation: number?, links: boolean?, triangles: boolean? } + +local fmt = string.format + +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local s = fmt("%.6f", v) + if s == "-0.000000" then + return "0.000000" + end + return s +end + +-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x) +local function angles(q: { number }): (number, number, number) + local m = Mat4.fromQuat(q) + local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1] + local y = math.asin(math.clamp(-r31, -1, 1)) + local x, z + if math.abs(r31) < 0.9999999 then + x = math.atan2(r32, r33) + z = math.atan2(r21, r11) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return x, y, z +end + +local function lerp(a: { number }, b: { number }, t: number): { number } + local out: { number } = {} + for i = 1, #a do + out[i] = a[i] + (b[i] - a[i]) * t + end + return out +end + +-- the value of channel ch at time tm (nil when the channel has no keys) +local function sample(ch: Types.Channel, tm: number): { number }? + local input, output = ch.input, ch.output + local n = input.count + if n == 0 then + return nil + end + local comps = if ch.path == "rotation" then 4 else 3 + local function key(k: number): { number } + local out: { number } = {} + for c = 0, comps - 1 do + out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4) + end + return out + end + local times = input.data + if tm <= buffer.readf32(times, 0) then + return key(0) + end + for k = 1, n - 1 do + local t1 = buffer.readf32(times, k * 4) + if tm <= t1 then + local t0 = buffer.readf32(times, (k - 1) * 4) + local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0) + local a, b = key(k - 1), key(k) + if comps == 4 then + if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + local q = lerp(a, b, f) + local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a + end + return lerp(a, b, f) + end + end + return key(n - 1) +end + +-- write(scene, opts) -> text | nil, message +function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, "expected a Scene" + end + local out: { string } = { "version 1", "nodes" } + local skin = scene.skins and scene.skins[1] + local joints: { number } = if skin then skin.joints else {} + local jointOf: { [number]: number } = {} -- node index -> bone id (0-based) + for k, nd in joints do + jointOf[nd] = k - 1 + end + local parentOf: { [number]: number } = {} + for ni, nd in scene.nodes do + for _, c in nd.children do + parentOf[c] = ni + end + end + if #joints == 0 then + table.insert(out, '0 "root" -1') + else + for k, nd in joints do + local p = parentOf[nd] + while p and jointOf[p] == nil do + p = parentOf[p] + end + local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1)) + table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1)) + end + end + table.insert(out, "end") + table.insert(out, "skeleton") + local function pose(tr: { number }?, rot: { number }?): string + local t = tr or { 0, 0, 0 } + local x, y, z = angles(rot or { 0, 0, 0, 1 }) + return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ") + end + local animIndex = opts and opts.animation + local anim = animIndex and scene.animations[animIndex] + if animIndex and not anim then + return nil, "no animation " .. tostring(animIndex) + end + if anim then + local keyset: { [number]: boolean } = {} + for _, ch in anim.channels do + for k = 0, ch.input.count - 1 do + keyset[buffer.readf32(ch.input.data, k * 4)] = true + end + end + local keys: { number } = {} + for tm in keyset do + table.insert(keys, tm) + end + table.sort(keys) + local byNode: { [number]: { [string]: Types.Channel } } = {} + for _, ch in anim.channels do + local m = byNode[ch.node] or {} + byNode[ch.node] = m + m[ch.path] = ch + end + for f, tm in keys do + table.insert(out, "time " .. (f - 1)) + for k, nd in joints do + local node = scene.nodes[nd] + local chs: { [string]: Types.Channel } = byNode[nd] or {} + local tch, rch = chs.translation, chs.rotation + local tr = if tch then sample(tch, tm) else node.translation + local rot = if rch then sample(rch, tm) else node.rotation + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + else + table.insert(out, "time 0") + if #joints == 0 then + table.insert(out, "0 " .. pose(nil, nil)) + else + for k, nd in joints do + local node = scene.nodes[nd] + local tr, rot = node.translation, node.rotation + if node.matrix then + local t, r = Mat4.decompose(node.matrix) + tr, rot = t, r + end + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + end + table.insert(out, "end") + -- triangles + if not anim or (opts and opts.triangles) then + local m, err = Flatten.merge(scene, function(name: string): boolean + return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" + end, { triangulate = true }) + if not m then + return nil, err + end + local A = m.attrs + local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0 + local links = not (opts and opts.links == false) + local nbones = math.max(1, #joints) + if #m.corners > 0 then + table.insert(out, "triangles") + for _, part in m.parts do + local mat = part.prim.material and scene.materials[part.prim.material] + local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default" + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + table.insert(out, mname) + for c = 0, 2 do + local v = m.corners[f * 3 + c + 1] + local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3] + local nx, ny, nz = 0, 0, 1 + if N then + nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3] + end + local u, w = 0, 0 + if UV then + local k = UV.components + u, w = UV.values[v * k + 1], UV.values[v * k + 2] + end + local parent = 0 + local lk: { string } = {} + if J and W and #joints > 0 then + local jk, wk = J.components, W.components + local best, bestW = 0, -1 + local count = 0 + for c2 = 1, math.min(4, jk, wk) do + local jw = W.values[v * wk + c2] + local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1) + if jw and jw > 0 then + count += 1 + table.insert(lk, fmt("%d %s", jj, num(jw))) + if jw > bestW then + best, bestW = jj, jw + end + end + end + parent = best + if count > 0 then + table.insert(lk, 1, tostring(count)) + end + end + local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w)) + if links and #lk > 0 then + line ..= " " .. table.concat(lk, " ") + end + table.insert(out, line) + end + end + end + table.insert(out, "end") + end + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write diff --git a/src/Formats/model/smd/init.luau b/src/Formats/model/smd/init.luau new file mode 100644 index 0000000..8df0ce5 --- /dev/null +++ b/src/Formats/model/smd/init.luau @@ -0,0 +1,69 @@ +--!strict +-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the +-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a +-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation +-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, +-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. +-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Read = require("@formats/model/smd/Read") +local Write = require("@formats/model/smd/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Smd = { + name = "smd", + category = "model", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + fps: number?, -- skeleton frames per second (default 30) + name: string?, -- the root node / animation name (the api passes the file name) + maxVertices: number?, -- default 2^24 +} +export type EncodeOptions = Write.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Smd.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + local o: any = opts and table.clone(opts :: any) or {} + if type(o.name) == "string" then + o.name = string.match(o.name, "([^/\\]+)$") or o.name + o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "") + end + local scene, msg = Read.read(text, o) + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local text, msg = Write.write(scene, opts) + if not text then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return buffer.fromstring(text), nil +end + +return Smd diff --git a/tests/model/smd.luau b/tests/model/smd.luau new file mode 100644 index 0000000..7b384c0 --- /dev/null +++ b/tests/model/smd.luau @@ -0,0 +1,176 @@ +-- model/smd tests: SMD files written by tools/fixtures/smd.py decode to assimp's triangle soup (positions, texture +-- coordinates per material) and to the writer's exact values (bind pose TRS, per-vertex weights and joints, every +-- skeleton frame of the animation); an animation-only SMD; our writer's output re-read by us (same soup, weights, +-- poses) and by assimp (faces, bones); errors; the fuzz pass. Fixtures: tools/fixtures/smd.py. +local T = require("@tests/T") +local F = require("@formats") +local Smd = require("@formats/model/smd") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/smd") + +local t = T.suite("smd") +t:eq(Smd.name, "smd", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol then + return false + end + end + return true +end +-- same rotation (q or -q) +local function sameQ(a: { number }, b: { number }): boolean + return near(a, b, 1e-5) or near(a, { -b[1], -b[2], -b[3], -b[4] }, 1e-5) +end + +local function check(s: any, c: any, label: string) + local skin = s.skins[1] + t:eq(#skin.joints, #c.bones, label .. ": joints") + for i, bn in c.bones do + local node = s.nodes[skin.joints[i]] + t:eq(node.name, bn.name, label .. ": bone name " .. i) + local pose = c.frames[1][i] + t:check(near(node.translation, pose.t, 1e-5) and sameQ(node.rotation, pose.q), label .. ": bind pose " .. bn.name) + end + if #c.tris > 0 then + local prims = s.meshes[1].primitives + t:eq(#prims, #c.materials, label .. ": a primitive per material") + -- every triangle of the writer, in file order per material + for pi, p in prims do + local mat = s.materials[p.material].name + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any + local jr = Types.Scene.reader(p.attributes.JOINTS_0) :: any + local wr = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any + local k = 0 + local ok, wok = true, true + for _, tri in c.tris do + if tri.material == mat then + for ci, cn in tri.corners do + local v = buffer.readu32(p.indices.data, (k * 3 + ci - 1) * 4) + ok = ok and near({ pos(v, 0), pos(v, 1), pos(v, 2) }, cn.p, 1e-5) and near({ uv(v, 0), 1 - uv(v, 1) }, cn.uv, 1e-6) + local got = {} + for wi = 0, 3 do + if wr(v, wi) > 0 then + got[jr(v, wi)] = wr(v, wi) + end + end + for _, w in cn.w do + wok = wok and got[w[1]] ~= nil and math.abs(got[w[1]] - w[2]) < 1e-5 + end + end + k += 1 + end + end + t:check(ok, label .. ": " .. mat .. " positions / texture coordinates") + t:check(wok, label .. ": " .. mat .. " joints / weights") + t:eq(p.indices.count, k * 3, label .. ": " .. mat .. " triangles") + local _ = pi + end + end + if #c.frames > 1 then + local a = s.animations[1] + local byNode = {} + for _, ch in a.channels do + byNode[ch.node .. ch.path] = ch + end + local ok = true + for f, pose in c.frames do + for i, bp in pose do + local node = skin.joints[i] + local tr, rot = byNode[node .. "translation"], byNode[node .. "rotation"] + local tv, qv = {}, {} + for k = 1, 3 do + tv[k] = buffer.readf32(tr.output.data, ((f - 1) * 3 + k - 1) * 4) + end + for k = 1, 4 do + qv[k] = buffer.readf32(rot.output.data, ((f - 1) * 4 + k - 1) * 4) + end + ok = ok and near(tv, bp.t, 1e-5) and sameQ(qv, bp.q) + end + end + t:check(ok, label .. ": every skeleton frame") + t:eq(a.channels[1].input.count, #c.frames, label .. ": keys") + end +end + +for _, c in Fx.cases do + local s, err = Smd.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(s, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "smd", c.name .. ": F.detect") + check(s, c, c.name) + if not c.assimp.failed then + local matched = 0 + for mi, m in c.assimp.per do + local nextStart = if c.assimp.per[mi + 1] then c.assimp.per[mi + 1].start else c.assimp.faces + local nf = nextStart - m.start + local apos = Soup.slice(c.assimp.pos, m.start * 9 + 1, nf * 9) + local auv = Soup.slice(c.assimp.uv, m.start * 6 + 1, nf * 6) + for _, p in s.meshes[1].primitives do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-5) then + t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), c.name .. ": texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #c.materials, c.name .. ": every material mesh matches assimp's positions") + end + -- our writer, read back by us + local out = Smd.encode(s) :: buffer + local back, berr = Smd.decode(Bytes.reader(out)) + t:check(back, c.name .. ": re-read our SMD: " .. tostring(berr)) + local again = table.clone(c) + again.frames = { c.frames[1] } + check(back, again, c.name .. " (written)") + if #c.frames > 1 then + local anim = Smd.decode(Bytes.reader(Smd.encode(s, { animation = 1 }) :: buffer)) :: any + local only = table.clone(c) + only.tris = {} + check(anim, only, c.name .. " (written animation)") + end + -- assimp reads our output + local ours = Fx.ours[c.name] + if ours and #c.tris > 0 then + t:eq(ours.faces, #c.tris, c.name .. ": assimp reads our triangles") + local soupOk = ours.soup and not ours.soup.failed and ours.soup.faces == #c.tris + t:check(soupOk, c.name .. ": assimp soup of our file") + end +end + +-- a scene without a skin writes one root bone +do + local prim: any = { + attributes = { POSITION = Types.Scene.accessor(buffer.create(36), "f32", 3, 3) }, + mode = "triangles", + } + buffer.writef32(prim.attributes.POSITION.data, 12, 1) + buffer.writef32(prim.attributes.POSITION.data, 28, 1) + local text = buffer.tostring(Smd.encode(Types.Scene.fromPrimitive(prim)) :: buffer) + t:check(string.find(text, '0 "root" -1', 1, true) ~= nil, "static scene: a root bone") + local back = Smd.decode(Bytes.reader(buffer.fromstring(text))) :: any + t:eq(back.meshes[1].primitives[1].indices.count, 3, "static scene round trip") + local _, e1 = Smd.encode({ kind = "image" } :: any) + t:check(e1 and e1.code == Err.ARG, "encode a non-scene") + local _, e2 = Smd.decode(Bytes.reader(buffer.fromstring("version 1\nnodes\n0 \"a\" -1\n"))) + t:check(e2 and e2.code == Err.TRUNCATED, "nodes without end: " .. tostring(e2)) + local _, e3 = Smd.decode(Bytes.reader(buffer.fromstring("version 2\nnodes\nend\n"))) + t:check(e3 and e3.code == Err.UNSUPPORTED, "version 2") +end + +local samples = {} +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local s = Smd.decode(Bytes.reader(b)) + if s then + Smd.encode(s) + end + return s +end, samples, { mutations = 60 }) +t:done() diff --git a/tools/fixtures/_smd_encode.luau b/tools/fixtures/_smd_encode.luau new file mode 100644 index 0000000..2e9bde2 --- /dev/null +++ b/tools/fixtures/_smd_encode.luau @@ -0,0 +1,22 @@ +-- tools/fixtures/_smd_encode.luau: run by tools/fixtures/smd.py under the luau CLI: decodes the reference SMDs of +-- tests/gen/smd_src and writes them back with our encoder (bind pose; links; and the animation as an animation SMD), +-- printing "\t" lines for assimp to read back. +local Smd = require("@formats/model/smd") +local Bytes = require("@formats/core/Bytes") +local Src = require("@tests/gen/smd_src") + +local function hex(b: buffer): string + return (string.gsub(buffer.tostring(b), ".", function(c: string): string + return string.format("%02x", string.byte(c)) + end)) +end + +for _, c in Src do + local s = Smd.decode(Bytes.reader(buffer.fromstring(c.data))) + if s then + print(c.name .. "\t" .. hex(Smd.encode(s) :: buffer)) + if #s.animations > 0 then + print(c.name .. "-anim\t" .. hex(Smd.encode(s, { animation = 1 }) :: buffer)) + end + end +end diff --git a/tools/fixtures/smd.py b/tools/fixtures/smd.py new file mode 100644 index 0000000..bd7df84 --- /dev/null +++ b/tools/fixtures/smd.py @@ -0,0 +1,122 @@ +# Valve SMD fixtures (tools/fixtures.py): SMD files written here (a skeleton of random bones, triangles with Source +# links / GoldSrc parent-only vertices, several materials, a multi-frame skeleton, comments, quoted names; an +# animation-only SMD); references: assimp's triangle soup (positions and texture coordinates per material mesh) +# and the writer's own values (bind pose TRS, per-vertex weights, frame poses); our encoder's output +# (tools/fixtures/_smd_encode.luau) read back by assimp (vertex / face counts, bounds). +# tests/gen/smd_src.luau { { name, data } } +# tests/gen/smd.luau { cases = { { name, data, bones, frames, tris, materials, verts, assimp } }, ours = { [name] = assimp info } } +import importlib.util, json, math, os, shutil, struct, subprocess, tempfile + +INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_smd_encode.luau", "src/Formats/model/smd"] + + +def mod(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def angle_quat(x, y, z): + sy, cy = math.sin(z / 2), math.cos(z / 2) + sp, cp = math.sin(y / 2), math.cos(y / 2) + sr, cr = math.sin(x / 2), math.cos(x / 2) + return [sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy] + + +def r6(v): + return float("%.6f" % v) + + +def smd(rng, nbones, nframes, ntris, materials, links=True, anim_only=False): + lines = ["// written by tools/fixtures/smd.py", "version 1", "nodes"] + bones = [] + for i in range(nbones): + parent = -1 if i == 0 else rng.randrange(i) + bones.append({"name": "bone %d" % i if i % 2 else "bone_%d" % i, "parent": parent + 1}) + lines.append('%d "%s" %d' % (i, bones[-1]["name"], parent)) + lines.append("end") + lines.append("skeleton") + frames = [] + for f in range(nframes): + lines.append("time %d" % f) + pose = [] + for i in range(nbones): + v = [r6(rng.uniform(-5, 5)) for _ in range(3)] + [r6(rng.uniform(-math.pi, math.pi)) for _ in range(3)] + lines.append("%d %s" % (i, " ".join("%.6f" % x for x in v))) + pose.append({"t": v[:3], "q": angle_quat(*v[3:])}) + frames.append(pose) + lines.append("end") + tris = [] + if not anim_only: + lines.append("triangles") + for t in range(ntris): + mat = materials[t % len(materials)] + lines.append(mat) + corners = [] + for c in range(3): + parent = rng.randrange(nbones) + p = [r6(rng.uniform(-20, 20)) for _ in range(3)] + n = [rng.uniform(-1, 1) for _ in range(3)] + ln = math.sqrt(sum(x * x for x in n)) + n = [r6(x / ln) for x in n] + uv = [r6(rng.random()), r6(rng.random())] + s = "%d %s" % (parent, " ".join("%.6f" % x for x in p + n + uv)) + weights = {parent: 1.0} + if links and rng.random() < 0.7: + k = rng.randrange(1, 3) + picks = rng.sample(range(nbones), min(k, nbones)) + ws = [r6(rng.uniform(0.1, 0.45)) for _ in picks] + s += " %d %s" % (len(picks), " ".join("%d %.6f" % (b, w) for b, w in zip(picks, ws))) + weights = {} + for b, w in zip(picks, ws): + weights[b] = weights.get(b, 0) + w + rest = 1 - sum(ws) + if rest > 0.001: + weights[parent] = weights.get(parent, 0) + rest + lines.append(s) + corners.append({"p": p, "n": n, "uv": uv, "w": [[b, w] for b, w in sorted(weights.items(), key=lambda x: -x[1])]}) + tris.append({"material": mat, "corners": corners}) + lines.append("end") + return "\r\n".join(lines) + "\r\n", {"bones": bones, "frames": frames, "tris": tris} + + +def assimp_info(ctx, data, Q): + tmp = tempfile.mkdtemp(prefix="formats-smd-") + try: + p = os.path.join(tmp, "in.smd") + open(p, "wb").write(data) + try: + txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {"failed": True} + finally: + shutil.rmtree(tmp) + import re + def num(label): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + return int(m.group(1)) if m else -1 + return {"faces": num("Faces"), "bones": num("Bones"), "animations": num("Animations")} + + +def generate(ctx): + rng = ctx.rng(83) + Q = mod(ctx, "_quake_ref") + specs = [("source", 5, 3, 12, ["skin.bmp", "metal.vtf"], True, False), ("goldsrc", 3, 1, 8, ["chrome.bmp"], False, False), + ("animation", 4, 6, 0, [], True, True)] + cases, src = [], [] + for name, nb, nf, nt, mats, links, anim in specs: + text, info = smd(rng, nb, nf, nt, mats, links, anim) + data = text.encode() + src.append({"name": name, "data": data}) + info.update({"name": name, "data": data, "assimp": Q.assimp_soup(ctx, data, "smd") if not anim else {"failed": True}, + "materials": mats}) + cases.append(info) + ctx.emit("smd_src", src) + import importlib + ours = {} + m = mod(ctx, "_model_ref") + for k, b in m.luau_encode(ctx, "tools/fixtures/_smd_encode.luau").items(): + ours[k] = assimp_info(ctx, b, Q) + ours[k]["soup"] = Q.assimp_soup(ctx, b, "smd") if not k.endswith("-anim") else {"failed": True} + ctx.emit("smd", {"cases": cases, "ours": ours})