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

+12
View File
@@ -422,6 +422,18 @@ local list: { Entry } = {
return require("@formats/model/gltf")
end,
},
{
name = "ms3d",
category = "model",
path = "model/ms3d",
extensions = { "ms3d" },
mime = { "application/x-ms3d" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true },
load = function()
return require("@formats/model/ms3d")
end,
},
{
name = "obj",
category = "model",
+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
+486
View File
@@ -0,0 +1,486 @@
--!strict
-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped,
-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first
-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2);
-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each
-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's
-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials:
-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and
-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment),
-- joint colours and model extras are written in their sub-versioned blocks.
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Write = {}
local S = Types.Scene
local sqrt = math.sqrt
export type Options = { fps: number?, name: string?, files: { [string]: any }? }
local function fixedString(w: Bytes.Writer, s: string, n: number)
local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1)
w:string(v)
for _ = #v + 1, n do
w:u8(0)
end
end
local function msg(s: any): string
return if type(s) == "string" then s else ""
end
-- ------------------------------------------------------------------------------------------------ tree
type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } }
local function tree(scene: Types.Scene): Tree
local t: Tree = { world = {}, parent = {}, order = {} }
local function visit(i: number, p: number, pm: { number }, depth: number)
local n = scene.nodes[i]
if type(n) ~= "table" or t.world[i] or depth > 256 then
return
end
t.world[i] = S.mul(pm, S.nodeMatrix(n))
t.parent[i] = p
table.insert(t.order, i)
for _, c in n.children or {} do
visit(c, i, t.world[i], depth + 1)
end
end
for _, r in scene.roots do
visit(r, 0, S.IDENTITY, 0)
end
return t
end
-- ------------------------------------------------------------------------------------------------ joints
type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } }
-- the rigid part (rotation and translation) of a matrix
local function rigid(m: { number }): { number }
local t, r = Mat4.decompose(m)
return Mat4.compose(t, r, nil)
end
-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order;
-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices
local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number })
local skin = scene.skins[1]
local anim = scene.animations[1]
local out: { Joint } = {}
local bySkin: { [number]: number } = {}
local byNode: { [number]: number } = {}
local skinIndex: { [number]: number } = {}
local isJoint: { [number]: boolean } = {}
for k, ni in (if skin then skin.joints else {}) :: { number } do
skinIndex[ni] = k - 1
isJoint[ni] = true
end
local chans: { [number]: { Types.Channel } } = {}
for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do
if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then
isJoint[ch.node] = true
chans[ch.node] = chans[ch.node] or {}
table.insert(chans[ch.node], ch)
end
end
-- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix
local B = S.IDENTITY
local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil
if skin and IBM and tr.world[skin.joints[1]] then
local m = table.create(16, 0)
for c = 1, 16 do
m[c] = (IBM :: any)(0, c - 1)
end
B = S.mul(tr.world[skin.joints[1]], m)
end
local names: { [string]: boolean } = {}
for _, ni in tr.order do
if not isJoint[ni] or #out >= 127 then
continue
end
local p = tr.parent[ni]
while p ~= 0 and byNode[p] == nil do
p = tr.parent[p]
end
-- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the
-- joint and its joint parent (C) carry over to the keys
local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity()
local gp = tr.parent[ni]
local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY)
local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni])))
local e = Mat4.eulerXYZ(r)
local base = string.sub(msg(scene.nodes[ni].name), 1, 27)
local name = if base ~= "" then base else "joint" .. #out
local n = 1
while names[name] do
n += 1
name = base .. "_" .. n
end
names[name] = true
local j: Joint = {
node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t,
rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {},
}
table.insert(out, j)
byNode[ni] = #out - 1
if skinIndex[ni] then
bySkin[skinIndex[ni]] = #out - 1
end
-- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest
local _, rc = Mat4.decompose(C)
local inv = Mat4.transpose3(Mat4.fromQuat(r))
for _, ch in chans[ni] or {} do
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
local cubic = ch.interpolation == "CUBICSPLINE"
for k = 0, ch.input.count - 1 do
local v = if cubic then k * 3 + 1 else k
local time = IN(k, 0)
if ch.path == "rotation" then
local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) }
local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 }
local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q)))))
table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) })
else
local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2))
table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] })
end
end
end
end
return out, bySkin, byNode, B
end
-- ------------------------------------------------------------------------------------------------ geometry
type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } }
type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number }
type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? }
-- every placed primitive as a group: vertices, triangles; or nil, message
local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?)
local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {}
for _, pl in S.flatten(scene) do
local prim: any = pl.primitive
local node = scene.nodes[pl.node]
local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean
return false
end, { triangulate = true })
if not merged then
return verts, tris, groups, err
end
local corners = merged.corners
if #corners == 0 then
continue
end
local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil
-- a rigid mesh follows its nearest joint
local rigid = -1
if not skinned then
local p = pl.node
while p and p ~= 0 do
if byNode[p] then
rigid = byNode[p]
break
end
p = tr.parent[p]
end
end
local M = if skinned then B else pl.matrix
local NM = Mat4.normalMatrix(M)
local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0
local A = prim.attributes
local POS = S.reader(A.POSITION) :: any
local zero = function(_: number, _: number): number
return 0
end
type Get = (number, number) -> number
local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil
local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero
local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero
local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero
local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero
local base = #verts
local nv = A.POSITION.count
if base + nv > 65535 then
return verts, tris, groups, "more than 65535 vertices"
end
for v = 0, nv - 1 do
local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2))
local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 }
if skinned then
local inf = {}
for c = 0, 3 do
local w = WE(v, c)
local j = bySkin[JO(v, c)]
if w > 0 and j then
table.insert(inf, { j, w })
end
end
table.sort(inf, function(a: { number }, b: { number }): boolean
return a[2] > b[2]
end)
local sum = 0
for _, e in inf do
sum += e[2]
end
for c = 1, 4 do
local e = inf[c]
bones[c] = if e then e[1] else -1
weights[c] = if e and sum > 0 then e[2] / sum else 0
end
end
table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights })
end
local gi = #groups
if gi >= 255 then
return verts, tris, groups, "more than 255 groups"
end
local name = msg(node.name)
if name == "" then
name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name)
end
local x = node.extras and node.extras.ms3d
local g: Group = {
name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0,
material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1,
comment = x and x.comment,
}
local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing
if type(saved) ~= "table" or #saved ~= #corners // 3 then
saved = nil
end
for f = 0, #corners // 3 - 1 do
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
if mirror then
b, c = c, b
end
local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi }
-- the face normal for primitives without normals
local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1]
local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z
local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z
local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x
for _, v in { a, b, c } do
local nx, ny, nz = fx, fy, fz
if hasN then
local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2)
nx = NM[1] * ox + NM[5] * oy + NM[9] * oz
ny = NM[2] * ox + NM[6] * oy + NM[10] * oz
nz = NM[3] * ox + NM[7] * oy + NM[11] * oz
end
local l = sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 then
nx, ny, nz = nx / l, ny / l, nz / l
end
table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n)
table.insert(t.uv, UV(v, 0))
table.insert(t.uv, UV(v, 1))
end
table.insert(tris, t)
table.insert(g.tris, #tris - 1)
end
if #tris > 65535 then
return verts, tris, groups, "more than 65535 triangles"
end
table.insert(groups, g)
end
return verts, tris, groups, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
local o: Options = opts or {}
local tr = tree(scene)
local js, bySkin, byNode, B = joints(scene, tr)
local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B)
if gerr then
return nil, gerr
end
if #scene.materials > 127 then
return nil, "more than 127 materials"
end
local src: any = scene.meta.source
local fromMs3d = src ~= nil and src.format == "ms3d"
local w = Bytes.writer(65536)
w:string("MS3D000000")
w:u32le(4)
w:u16le(#verts)
for _, v in verts do
w:u8(0)
w:f32le(v.x)
w:f32le(v.y)
w:f32le(v.z)
w:i8(v.bones[1] % 256)
w:u8(1)
end
w:u16le(#tris)
for _, t in tris do
w:u16le(0)
for k = 1, 3 do
w:u16le(t.v[k])
end
for k = 1, 9 do
w:f32le(t.n[k])
end
for k = 1, 3 do
w:f32le(t.uv[k * 2 - 1])
end
for k = 1, 3 do
w:f32le(t.uv[k * 2])
end
w:u8(math.clamp(t.sg, 0, 255))
w:u8(t.group)
end
w:u16le(#groups)
for _, g in groups do
w:u8(g.flags % 256)
fixedString(w, g.name, 32)
w:u16le(#g.tris)
for _, ti in g.tris do
w:u16le(ti)
end
w:i8(g.material % 256)
end
-- materials
w:u16le(#scene.materials)
local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture"
for i, m in scene.materials do
local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any }
local bc = m.baseColor or { 1, 1, 1, 1 }
fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32)
local e = m.emissive or { 0, 0, 0 }
for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do
for k = 1, 4 do
w:f32le(c[k] or 1)
end
end
local r = math.max(m.roughness or 1, 0.1)
w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128))
w:f32le(bc[4] or 1)
w:i8((tonumber(x.mode) or 0) % 256)
local file = ""
local ref: any = m.baseColorTexture
local tex: any = ref and scene.textures[ref.texture]
if tex then
file = tex.uri or ""
if file == "" or string.sub(file, 1, 5) == "data:" then
file = base .. "_" .. ref.texture .. ".png"
if o.files and tex.data then
o.files[file] = tex.data
end
end
end
fixedString(w, file, 128)
fixedString(w, msg(x.alphamap), 128)
end
-- the animation header and joints
local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24)
local last = 0
for _, j in js do
for _, k in j.rotKeys do
last = math.max(last, k[1])
end
for _, k in j.posKeys do
last = math.max(last, k[1])
end
end
w:f32le(fps)
w:f32le(0)
w:u32le(math.max(1, math.ceil(last * fps)))
w:u16le(#js)
for _, j in js do
local x = scene.nodes[j.node].extras
local jx = x and x.ms3d
w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0)
fixedString(w, j.name, 32)
fixedString(w, j.parent, 32)
for k = 1, 3 do
w:f32le(j.rot[k])
end
for k = 1, 3 do
w:f32le(j.pos[k])
end
w:u16le(#j.rotKeys)
w:u16le(#j.posKeys)
for _, list in { j.rotKeys, j.posKeys } do
for _, k in list do
for c = 1, 4 do
w:f32le(k[c])
end
end
end
end
-- comments
w:u32le(1)
local function comments(list: { any }, get: (any) -> string?)
local found = {}
for i, item in list do
local c = get(item)
if type(c) == "string" and c ~= "" then
table.insert(found, { i - 1, c })
end
end
w:u32le(#found)
for _, f in found do
w:u32le(f[1])
w:u32le(#f[2])
w:string(f[2])
end
end
comments(groups, function(g: any): string?
return g.comment
end)
comments(scene.materials, function(m: any): string?
return m.extras and m.extras.ms3d and m.extras.ms3d.comment
end)
comments(js, function(j: any): string?
local x: any = scene.nodes[j.node].extras
return x and x.ms3d and x.ms3d.comment
end)
local mc = if fromMs3d then msg(src.comment) else ""
w:u32le(if mc ~= "" then 1 else 0)
if mc ~= "" then
w:u32le(#mc)
w:string(mc)
end
-- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32
w:u32le(2)
for _, v in verts do
local p = table.create(3, 0)
local left = 100
for c = 1, 3 do
p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left)
left -= p[c]
end
if v.bones[2] < 0 and v.bones[1] >= 0 then
p = { 100, 0, 0 }
end
for c = 2, 4 do
w:i8(v.bones[c] % 256)
end
for c = 1, 3 do
w:u8(p[c])
end
w:u32le(0)
end
-- joint colours, model extras
w:u32le(1)
for _, j in js do
local x: any = scene.nodes[j.node].extras
local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 }
for k = 1, 3 do
w:f32le(c[k] or 1)
end
end
w:u32le(1)
w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1)
w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0)
w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5)
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out, nil
end
return Write
+82
View File
@@ -0,0 +1,82 @@
--!strict
-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of
-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested
-- against (no code ported).
-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and
-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in
-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive;
-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use
-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse
-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes
-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d,
-- the model comment / fps / frames / joint size in meta.source. meta.up = "y".
-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex),
-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127
-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/ms3d/Read")
local Write = require("@formats/model/ms3d/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Ms3d = {
name = "ms3d",
category = "model",
extensions = { "ms3d" },
mime = { "application/x-ms3d" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- refuse more triangle corners (default 2^20)
}
export type EncodeOptions = {
fps: number?, -- the animation's frames per second (default: the source's, else 24)
name: string?, -- the destination's file name (names textures that have no uri)
files: { [string]: any }?, -- receives the bytes of textures that have data but no uri
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ms3d.sniff(r: Bytes.Reader): number
local h = r:peek(14)
if string.sub(h, 1, 10) ~= Read.MAGIC then
return 0
end
local v = string.byte(h, 11)
return if v == 3 or v == 4 then 1 else 0.6
end
-- ------------------------------------------------------------------------------------------------ decode
function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, at)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ms3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local ok, out, err = pcall(Write.encode, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out))
end
if not out then
return nil, Err.new(Err.ARG, tostring(err))
end
return out, nil
end
return Ms3d