ws-3d3: model/ms3d (MilkShape 3D) read + write

Groups, materials (texture uri), joints -> nodes + skin + one animation,
version 4 sub-versioned blocks (comments, vertex extras with up to four
bones, joint colours, model extras). Writer: groups per placed primitive,
the first skin plus animated nodes as joints (rigid meshes bound to them),
weights in percent. Tested against assimp and through glTF skin models.
This commit is contained in:
4DBug committed 2026-10-31 14:33:46 -05:00
1 parent a43d81538e
commit 730820d1f6
9 files changed
+1620 -2

No files matched your search

+464
View File
@@ -0,0 +1,464 @@
--!strict
-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h
-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a
-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess
-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and
-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds
-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model),
-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3),
-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference).
-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices
-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest +
-- key positions). Never throws on bad data: returns nil, message, offset.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Read = {}
local S = Types.Scene
local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring
local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32
Read.MAGIC = "MS3D000000"
export type Options = { maxVertices: number? }
-- ------------------------------------------------------------------------------------------------ helpers
local function fixed(b: buffer, p: number, n: number): string
local s = readstring(b, p, n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local function floats(values: { number }, comps: number): Types.Accessor
local n = #values // comps
local a = S.accessor(nil, "f32", comps, n)
for i = 1, n * comps do
writef32(a.data, (i - 1) * 4, values[i])
end
return a
end
local function color(b: buffer, p: number): { number }
return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) }
end
-- the texture file name as a relative uri (MilkShape writes ".\name.jpg")
local function uri(s: string): string
local u = string.gsub(s, "\\", "/")
u = string.gsub(u, "^%./", "")
return u
end
-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion
local function euler(x: number, y: number, z: number): { number }
return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z)))
end
-- ------------------------------------------------------------------------------------------------ parse
type Vertex = { pos: { number }, bones: { number }, weights: { number } }
type Joint = {
name: string, parent: string, flags: number, rot: { number }, pos: { number },
rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?,
}
-- scene(b, base, limit, opts) -> Scene | nil, message, offset
function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?)
local p = base
local function need(n: number): boolean
return p + n <= limit
end
if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then
return nil, "not a MilkShape 3D file", base
end
local version = readi32(b, p + 10)
if version ~= 3 and version ~= 4 then
return nil, "unsupported: version " .. version, p + 10
end
p += 14
local maxV = opts and opts.maxVertices or 2 ^ 20
-- vertices
if not need(2) then
return nil, "truncated vertex count", p
end
local nv = readu16(b, p)
p += 2
if not need(nv * 15) then
return nil, "truncated vertices", p
end
local verts: { Vertex } = {}
for i = 1, nv do
local q = p + (i - 1) * 15
verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } }
end
p += nv * 15
-- triangles
if not need(2) then
return nil, "truncated triangle count", p
end
local nt = readu16(b, p)
p += 2
if not need(nt * 70) then
return nil, "truncated triangles", p
end
if nt * 3 > maxV then
return nil, "limit: more than " .. maxV .. " triangle corners", p
end
local triAt = p
p += nt * 70
-- groups
if not need(2) then
return nil, "truncated group count", p
end
local ng = readu16(b, p)
p += 2
local groups = {}
for _ = 1, ng do
if not need(35) then
return nil, "truncated group", p
end
local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? }
local n = readu16(b, p + 33)
p += 35
if not need(n * 2 + 1) then
return nil, "truncated group triangles", p
end
for k = 0, n - 1 do
local ti = readu16(b, p + k * 2)
if ti >= nt then
return nil, "group triangle " .. ti .. " out of range", p + k * 2
end
table.insert(g.tris, ti)
end
p += n * 2
g.material = readi8(b, p)
p += 1
table.insert(groups, g)
end
-- materials
if not need(2) then
return nil, "truncated material count", p
end
local nm = readu16(b, p)
p += 2
if not need(nm * 361) then
return nil, "truncated materials", p
end
local mats = {}
for i = 0, nm - 1 do
local q = p + i * 361
table.insert(mats, {
name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64),
emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100),
mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?,
})
end
p += nm * 361
-- animation header and joints (version 3 files may end here)
local fps, current, frames = 24, 0, 0
local joints: { Joint } = {}
if need(12) then
fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8)
p += 12
if not need(2) then
return nil, "truncated joint count", p
end
local nj = readu16(b, p)
p += 2
for _ = 1, nj do
if not need(93) then
return nil, "truncated joint", p
end
local j: Joint = {
flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32),
rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) },
pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) },
rotKeys = {}, posKeys = {},
}
local nr, np = readu16(b, p + 89), readu16(b, p + 91)
p += 93
if not need((nr + np) * 16) then
return nil, "truncated joint keys", p
end
for k = 0, nr + np - 1 do
local q = p + k * 16
local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) }
table.insert(if k < nr then j.rotKeys else j.posKeys, key)
end
p += (nr + np) * 16
table.insert(joints, j)
end
end
-- sub-versioned blocks
local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames }
local function comments(list: { any }): string?
if not need(4) then
return "truncated comments"
end
local n = readi32(b, p)
p += 4
for _ = 1, math.max(n, 0) do
if not need(8) then
return "truncated comment"
end
local index, len = readi32(b, p), readi32(b, p + 4)
p += 8
if len < 0 or not need(len) then
return "comment runs past the end"
end
if list[index + 1] then
list[index + 1].comment = readstring(b, p, len)
end
p += len
end
return nil
end
if need(4) then
local sub = readi32(b, p)
p += 4
source.commentVersion = sub
if sub == 1 then
for _, list in { groups, mats, joints } :: { { any } } do
local e = comments(list)
if e then
return nil, e, p
end
end
if not need(4) then
return nil, "truncated model comment", p
end
local has = readi32(b, p)
p += 4
if has ~= 0 then
if not need(4) then
return nil, "truncated model comment", p
end
local len = readi32(b, p)
p += 4
if len < 0 or not need(len) then
return nil, "model comment runs past the end", p
end
source.comment = readstring(b, p, len)
p += len
end
end
end
if need(4) then
local sub = readi32(b, p)
p += 4
source.vertexVersion = sub
local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0
if size > 0 and need(nv * size) then
for i = 1, nv do
local q = p + (i - 1) * size
local v = verts[i]
local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5)
if w0 + w1 + w2 > 0 then
local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100
v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) }
v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) }
end
end
p += nv * size
end
end
if need(4) then
local sub = readi32(b, p)
p += 4
if (sub == 1 or sub == 2) and need(#joints * 12) then
for _, j in joints do
j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }
p += 12
end
end
end
if need(16) and readi32(b, p) >= 1 then
source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12)
end
return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil
end
-- ------------------------------------------------------------------------------------------------ build
function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene
local scene = S.new()
scene.meta.up = "y"
scene.meta.source = source :: any
-- materials, textures
for _, m in mats do
local mat = S.material(m.name)
local d = m.diffuse
mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) }
mat.metallic = 0
mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1)
mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] }
mat.alphaMode = if m.transparency < 1 then "blend" else "opaque"
if m.texture ~= "" then
local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) }
table.insert(scene.textures, tex)
mat.baseColorTexture = { texture = #scene.textures }
end
mat.extras = {
ms3d = {
ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess,
transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment,
},
}
table.insert(scene.materials, mat)
end
-- joints: nodes, rest pose, skin
local nj = #joints
local jointNode: { [number]: number } = {}
local byName: { [string]: number } = {}
local abs: { { number } } = {}
for i, j in joints do
local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) }
node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } }
table.insert(scene.nodes, node)
jointNode[i] = #scene.nodes
if byName[j.name] == nil then
byName[j.name] = i
end
end
for i, j in joints do
local pi = byName[j.parent]
-- parents must come first (MilkShape writes them in that order); others become roots
local local_ = S.nodeMatrix(scene.nodes[jointNode[i]])
if pi and pi < i then
table.insert(scene.nodes[jointNode[pi]].children, jointNode[i])
abs[i] = S.mul(abs[pi], local_)
else
table.insert(scene.roots, jointNode[i])
abs[i] = local_
end
end
local skinned = false
for _, v in verts do
for k = 1, 4 do
if v.bones[k] >= nj then
v.bones[k] = -1
end
end
skinned = skinned or (nj > 0 and v.bones[1] >= 0)
end
if nj > 0 then
local ibm = S.accessor(nil, "f32", 16, nj)
ibm.matrix = true
for i = 1, nj do
local inv = Mat4.inverse(abs[i]) or Mat4.identity()
for k = 1, 16 do
writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k])
end
end
local list = table.create(nj, 0)
for i = 1, nj do
list[i] = jointNode[i]
end
scene.skins[1] = { joints = list, inverseBindMatrices = ibm }
end
-- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner
local nv = #verts
for gi, g in groups do
local remap: { [string]: number } = {}
local P, N, U, J, W = {}, {}, {}, {}, {}
local idx: { number } = {}
local sgs: { number } = {}
local count = 0
for _, ti in g.tris do
local q = triAt + ti * 70
-- a triangle with an out-of-range vertex is dropped
if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then
continue
end
table.insert(sgs, readu8(b, q + 68))
for k = 0, 2 do
local vi = readu16(b, q + 2 + k * 2)
local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4)
local o = remap[key]
if o == nil then
o = count
count += 1
remap[key] = o
local v = verts[vi + 1]
table.move(v.pos, 1, 3, o * 3 + 1, P)
N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12)
U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4)
-- influences: the valid bones, weights normalized
local sum = 0
for c = 1, 4 do
if v.bones[c] >= 0 then
sum += v.weights[c]
end
end
for c = 1, 4 do
local ok = v.bones[c] >= 0 and sum > 0
J[o * 4 + c] = if ok then v.bones[c] else 0
W[o * 4 + c] = if ok then v.weights[c] / sum else 0
end
end
table.insert(idx, o :: number)
end
end
local prim: Types.Primitive = {
attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) },
mode = "triangles",
material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil,
extras = { ms3d = { smoothing = sgs } },
}
local ind = S.accessor(nil, "u32", 1, #idx)
for i, v in idx do
writeu32(ind.data, (i - 1) * 4, v)
end
prim.indices = ind
local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } }
if skinned then
local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count)
for i = 1, count * 4 do
if nj > 255 then
writeu16(ja.data, (i - 1) * 2, J[i])
else
writeu8(ja.data, i - 1, J[i])
end
end
prim.attributes.JOINTS_0 = ja
prim.attributes.WEIGHTS_0 = floats(W, 4)
node.skin = 1
end
local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } }
scene.meshes[gi] = mesh
node.mesh = gi
table.insert(scene.nodes, node)
table.insert(scene.roots, #scene.nodes)
end
-- the animation: rest * key rotations, rest + key positions
local channels: { Types.Channel } = {}
for i, j in joints do
if #j.rotKeys > 0 then
local times, vals = {}, {}
local rest = scene.nodes[jointNode[i]].rotation :: { number }
for _, k in j.rotKeys do
table.insert(times, k[1])
local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4]))))
table.move(q, 1, 4, #vals + 1, vals)
end
local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" }
table.insert(channels, ch)
end
if #j.posKeys > 0 then
local times, vals = {}, {}
for _, k in j.posKeys do
table.insert(times, k[1])
table.insert(vals, j.pos[1] + k[2])
table.insert(vals, j.pos[2] + k[3])
table.insert(vals, j.pos[3] + k[4])
end
local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" }
table.insert(channels, ch)
end
end
if #channels > 0 then
table.insert(scene.animations, { name = "ms3d", channels = channels })
end
return scene
end
return Read