diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ce760a5..0af45e9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -39,6 +39,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | ms3d | .ms3d | yes | yes | materials: true, skins: true, animation: true | `tests/model/ms3d.luau` | | 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` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 211ff7b..6dc5fb7 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -290,7 +290,7 @@ the binary container. | glTF | `external = true` writes `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | | OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | | STL | | `ascii = true` (default binary), `normals = "attribute"` | -| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS | see [FORMATS.md](../FORMATS.md) and the format's options | | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS, MS3D | see [FORMATS.md](../FORMATS.md) and the format's options | | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -408,6 +408,36 @@ assert(back.materials[prim.material].baseColor[1] == 1) assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the node transform ``` +## MilkShape 3D (MS3D) + +Each group loads as a node with one mesh (per-corner normals and uvs, so vertices are split per corner); joints become +nodes with a skin (`JOINTS_0` / `WEIGHTS_0`, up to four bones from the 1.8 vertex extras) and their keys one +animation. Comments, joint colours and the other MilkShape fields stay in `extras.ms3d` / `meta.source`. The writer +puts every placed primitive in a group, the first skin's joints plus every node the first animation moves (meshes +under them are bound rigidly) into the skeleton, and the weights in percent. + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") +-- spin the node a quarter turn about z in one second +local times = S.accessor(nil, "f32", 1, 2) +buffer.writef32(times.data, 4, 1) +local turns = S.accessor(nil, "f32", 4, 2) +for i, v in { 0, 0, 0, 1, 0, 0, math.sqrt(0.5), math.sqrt(0.5) } do + buffer.writef32(turns.data, (i - 1) * 4, v) +end +scene.animations[1] = { channels = { { node = 1, path = "rotation", input = times, output = turns, interpolation = "LINEAR" } } } +local back = assert(F.load(assert(F.save(scene, nil, { format = "ms3d" })))) +assert(back.meta.source.format == "ms3d" and #back.skins == 1) -- the animated node became a joint +local prim = back.meshes[1].primitives[1] +assert(prim.attributes.JOINTS_0 and prim.attributes.NORMAL) +assert(back.animations[1].channels[1].path == "rotation") +``` + ## Formats | Format | Read | Write | Notes | @@ -423,6 +453,7 @@ assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | | 3DS | yes | yes | keyframer hierarchy and animation, Phong materials, texture names, cameras, lights; Z up | +| MS3D (MilkShape 3D) | yes | yes | groups, materials, joints -> skin + animation, comments | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 8fbf340..3906190 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/model/ms3d/Read.luau b/src/Formats/model/ms3d/Read.luau new file mode 100644 index 0000000..2470edd --- /dev/null +++ b/src/Formats/model/ms3d/Read.luau @@ -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 diff --git a/src/Formats/model/ms3d/Write.luau b/src/Formats/model/ms3d/Write.luau new file mode 100644 index 0000000..3cef5bd --- /dev/null +++ b/src/Formats/model/ms3d/Write.luau @@ -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 diff --git a/src/Formats/model/ms3d/init.luau b/src/Formats/model/ms3d/init.luau new file mode 100644 index 0000000..e9db7b7 --- /dev/null +++ b/src/Formats/model/ms3d/init.luau @@ -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 diff --git a/tests/model/ms3d.luau b/tests/model/ms3d.luau new file mode 100644 index 0000000..fc2b59c --- /dev/null +++ b/tests/model/ms3d.luau @@ -0,0 +1,430 @@ +-- model/ms3d tests: assimp's MilkShape 3D test models (groups, materials, textures, version 4 with and without the +-- sub-versioned blocks) against assimp (meshes, faces, corners, materials, world bounds); round trips through our +-- writer, of those files and of glTF sample models (world triangles, materials, textures, skins: joints, inverse bind +-- matrices, skinned vertices; animation sampled through the skeleton); assimp reading our files (meshes, faces, +-- bones, animations, bounds: ms3d_xcheck); comments and extras; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/ms3d.py. +local T = require("@tests/T") +local F = require("@formats") +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") +local Xcheck = require("@tests/gen/ms3d_xcheck") + +local t = T.suite("ms3d") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ms3d.decode(Bytes.reader(b), opts) +end + +t:eq(Ms3d.name, "ms3d", "name") +t:eq(Ms3d.category, "model", "category") +t:check(Ms3d.caps.decode and Ms3d.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function counts(scene: any): (number, number, number) + local prims, faces, corners = 0, 0, 0 + for _, pl in S.flatten(scene) do + prims += 1 + faces += pl.primitive.indices.count // 3 + corners += pl.primitive.indices.count + end + return prims, faces, corners +end + +local function bstr(lo: any, hi: any): string + if not lo then + return "-" + end + return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +local function boundsEq(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end + +-- the bones assimp makes: per group, the distinct strongest joints of its vertices +local function bones(scene: any): number + local n = 0 + for _, pl in S.flatten(scene) do + local A = pl.primitive.attributes + if A.JOINTS_0 then + local J, W = S.reader(A.JOINTS_0) :: any, S.reader(A.WEIGHTS_0) :: any + local seen = {} + for v = 0, A.JOINTS_0.count - 1 do + local best, bw = -1, 0 + for c = 0, 3 do + if W(v, c) > bw then + best, bw = J(v, c), W(v, c) + end + end + if best >= 0 and not seen[best] then + seen[best] = true + n += 1 + end + end + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +for i, c in Cases do + local scene, err = decode(c.data) + local a = c.assimp + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + if scene and not a.failed then + local prims, faces, corners = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + t:eq(bones(scene), a.bones, c.name .. ": bones (assimp)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + end +end +t:note("%d files against assimp", #Cases) + +-- ------------------------------------------------------------------------------------------------ round trips +-- skinned world positions at a time: the skeleton posed by animations[1], vertices blended by their joints +local function skinnedPositions(s: any, time: number): { number } + local byNode: { [number]: { [string]: any } } = {} + for _, ch in (if s.animations[1] then s.animations[1].channels else {}) :: { any } do + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + local function eval(ch: any, comps: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + local u = if t1 > t0 then (time - t0) / (t1 - t0) else 1 + local a0, a1 = v(k), v(k + 1) + if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + end + return v(n - 1) + end + local world: { [number]: { number } } = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local chs = byNode[i] + local m = S.nodeMatrix(n) + if chs then + m = Mat4.compose(if chs.translation then eval(chs.translation, 3) else n.translation, + if chs.rotation then eval(chs.rotation, 4) else n.rotation, n.scale) + end + world[i] = S.mul(parent, m) + for _, c in n.children do + visit(c, world[i]) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + local out = {} + for _, pl in S.flatten(s) do + local prim = pl.primitive + local P = S.reader(prim.attributes.POSITION) :: any + local I = S.reader(prim.indices) :: any + local node = s.nodes[pl.node] + local skin = node.skin and s.skins[node.skin] + local J = prim.attributes.JOINTS_0 and S.reader(prim.attributes.JOINTS_0) :: any + local W = prim.attributes.WEIGHTS_0 and S.reader(prim.attributes.WEIGHTS_0) :: any + local IBM = skin and skin.inverseBindMatrices and S.reader(skin.inverseBindMatrices) :: any + local tri = {} + for k = 0, prim.indices.count - 1 do + local v = I(k, 0) + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + local wx, wy, wz = 0, 0, 0 + if skin and J and W then + for c = 0, 3 do + local w = W(v, c) + if w > 0 then + local j = J(v, c) + local ibm = {} + for q = 1, 16 do + ibm[q] = IBM(j, q - 1) + end + local m = S.mul(world[skin.joints[j + 1]], ibm) + local px, py, pz = Mat4.point(m, x, y, z) + wx, wy, wz = wx + px * w, wy + py * w, wz + pz * w + end + end + else + wx, wy, wz = Mat4.point(world[pl.node] or pl.matrix, x, y, z) + end + table.insert(tri, { wx, wy, wz }) + if #tri == 3 then + -- each triangle's corners in a fixed order (a mirrored node's winding is flipped on write) + local function r(x: number): number + return math.floor(x * 100 + 0.5) + end + table.sort(tri, function(p: { number }, q: { number }): boolean + if r(p[1]) ~= r(q[1]) then + return r(p[1]) < r(q[1]) + elseif r(p[2]) ~= r(q[2]) then + return r(p[2]) < r(q[2]) + end + return r(p[3]) < r(q[3]) + end) + for _, c in tri do + table.move(c, 1, 3, #out + 1, out) + end + tri = {} + end + end + end + return out +end + +local function compare(a: any, b: any, label: string, eps: number) + local _, fa = counts(a) + local _, fb = counts(b) + t:eq(fb, fa, label .. ": triangles") + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + local ta = m.baseColorTexture and a.textures[m.baseColorTexture.texture] + local tb = m2.baseColorTexture and b.textures[m2.baseColorTexture.texture] + t:check((ta == nil) == (tb == nil) and (ta == nil or ta.uri == nil or ta.uri == tb.uri), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.skins, if #a.skins > 0 or #a.animations > 0 then 1 else 0, label .. ": skins (animated nodes become joints)") + if a.skins[1] then + t:eq(#b.skins[1].joints, #a.skins[1].joints, label .. ": joints") + end + -- the same posed triangles (the corners in order) at a few times + for _, time in { 0, 0.3, 0.75, 1.2, 2.5, 4 } do + local pa, pb = skinnedPositions(a, time), skinnedPositions(b, time) + local ok = #pa == #pb + local worst = 0 + if ok then + for k = 1, #pa do + local d = math.abs(pa[k] - pb[k]) / math.max(1, math.abs(pa[k])) + worst = math.max(worst, d) + end + end + t:check(ok and worst <= eps, string.format("%s: posed vertices at %.2f s (worst %.3g)", label, time, worst)) + if #a.animations == 0 then + break + end + end +end + +for i, c in Cases do + local scene = scenes[i] + if scene then + local out, err = Ms3d.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name, 1e-6) + t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes") + local same = true + for mi, m in scene.meshes do + same = same and back.meshes[mi].primitives[1].attributes.POSITION.count == m.primitives[1].attributes.POSITION.count + end + t:check(same, c.name .. ": vertices kept") + end + end +end + +local gltfScenes = {} +local ng = 0 +for gi, g in Picks do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + gltfScenes[gi] = scene + local out, err = Ms3d.encode(scene) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + local lines = false + for _, m in scene.meshes do + for _, p in m.primitives do + lines = lines or p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" + end + end + if not lines then + -- weights are stored in percent + compare(scene, back, "glTF " .. g.name, if #scene.skins > 0 then 1e-2 else 1e-4) + end + ng += 1 + end + end +end +t:note("%d reference files and %d glTF models through our writer and back", #Cases, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +local nx = 0 +for _, x in Xcheck do + local a = x.assimp + t:check(not a.failed, x.name .. ": assimp reads our file") + local scene = if x.case then scenes[x.case] else gltfScenes[x.gltf] + if scene and not a.failed then + local back = decode(Ms3d.encode(scene) :: buffer) + local prims, faces, corners = counts(back) + t:eq(a.meshes, prims, x.name .. ": assimp meshes of our file") + t:eq(a.faces, faces, x.name .. ": assimp faces of our file") + t:eq(a.vertices, corners, x.name .. ": assimp corners of our file") + t:eq(a.bones, bones(back), x.name .. ": assimp bones of our file") + t:eq(a.animations, if #back.nodes > #back.meshes then 1 else 0, x.name .. ": assimp animations of our file (it makes one for any joint)") + t:eq(a.materials, math.max(#back.materials, 1), x.name .. ": assimp materials of our file") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(back)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + nx += 1 + end +end +t:note("%d of our files read back by assimp", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local jeep = byName["assimp/jeep1.ms3d"] + if jeep then + local m = jeep.materials[1] + t:check(m.baseColorTexture and jeep.textures[1].uri ~= nil and jeep.textures[1].data == nil, "texture -> uri, not loaded: " .. tostring(jeep.textures[1].uri)) + t:eq(#jeep.meshes, 7, "jeep: 7 groups") + t:eq(jeep.meta.up, "y", "MilkShape is Y up") + t:check(jeep.meta.source.vertexVersion == nil, "jeep: no sub-versioned blocks") + end + local mats = byName["assimp/twospheres_withmats.ms3d"] + if mats then + t:eq(mats.meta.source.commentVersion, 1, "comment block") + t:eq(mats.meta.source.vertexVersion, 3, "vertex extras subversion 3") + t:check(mats.materials[2].extras.ms3d.shininess > 0, "shininess in extras") + end + -- a skinned scene by hand: two joints, comments, weights split between them + local gl = gltfScenes[3] + if gl then + local out = Ms3d.encode(gl) :: buffer + local back = decode(out) + t:check(back.skins[1] and #back.skins[1].joints == #gl.skins[1].joints, "joints written") + local W = back.meshes[1].primitives[1].attributes.WEIGHTS_0 + local R = S.reader(W) :: any + local split = false + for v = 0, W.count - 1 do + split = split or (R(v, 1) > 0.05) + t:check(math.abs(R(v, 0) + R(v, 1) + R(v, 2) + R(v, 3) - 1) < 1e-6, "weights sum to 1") + end + t:check(split, "vertex extras: second bone weights") + back.nodes[1].extras.ms3d.comment = "the root" + back.materials[1] = F.Types.Scene.material("m") + back.materials[1].extras = { ms3d = { comment = "a material" } } + back.meta.source.comment = "made by a test" + local again = decode(Ms3d.encode(back) :: buffer) + t:eq(again.nodes[1].extras.ms3d.comment, "the root", "joint comment") + t:eq(again.materials[1].extras.ms3d.comment, "a material", "material comment") + t:eq(again.meta.source.comment, "made by a test", "model comment") + end + local s = F.load(Cases[1].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "ms3d", "F.load detects MS3D") + local viaApi = F.save(s, nil, { format = "ms3d" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 10) == "MS3D000000", "F.save format ms3d") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local data = Cases[2].data + local _, e1 = decode(string.sub(data, 1, 100)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("MS3D000000\9\0\0\0") + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 9: " .. tostring(e2)) + local _, e3 = decode("MS3D000001") + t:check(e3 and e3.code == Err.CORRUPT, "bad magic: " .. tostring(e3)) + local _, e4 = decode(data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Ms3d.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + t:eq(Ms3d.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + for gi, g in gltfScenes do + if gi <= 4 then + table.insert(samples, buffer.tostring(Ms3d.encode(g) :: buffer)) + end + end + t:fuzz("decode", function(b: buffer) + local s = Ms3d.decode(Bytes.reader(b)) + if s then + Ms3d.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 14 }) +end + +t:done() diff --git a/tools/fixtures/_ms3d_encode.luau b/tools/fixtures/_ms3d_encode.luau new file mode 100644 index 0000000..15977f6 --- /dev/null +++ b/tools/fixtures/_ms3d_encode.luau @@ -0,0 +1,44 @@ +-- tools/fixtures/_ms3d_encode: run by tools/fixtures/ms3d.py (luau CLI, repo root): decodes every MS3D case and every +-- glTF sample model with our readers and writes them with our MS3D writer, printing "\t" lines for assimp +-- to read back. Files: case_.ms3d, gltf_.ms3d. +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function emit(name: string, scene: any) + local out, err = Ms3d.encode(scene) + if out then + print(name .. "\t" .. hex(out)) + else + print("encode failed " .. name .. ": " .. tostring(err)) + end +end + +for i, c in Cases do + local scene, err = Ms3d.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + emit(string.format("case_%d.ms3d", i), scene) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end +for i, g in Picks do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + if scene then + emit(string.format("gltf_%d.ms3d", i), scene) + end +end diff --git a/tools/fixtures/ms3d.py b/tools/fixtures/ms3d.py new file mode 100644 index 0000000..611a48a --- /dev/null +++ b/tools/fixtures/ms3d.py @@ -0,0 +1,68 @@ +# MS3D fixtures (tools/fixtures.py): assimp's MilkShape 3D test models (test/models/MS3D: groups, materials, textures, +# version 4 with and without the sub-versioned blocks; read from the nixpkgs assimp source, never committed), with +# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, bones; world bounds +# from its PreTransformVertices export). No tool writes MS3D with joints, so skins and animation are checked through +# our writer: glTF sample models (skins, animation, textures) written by tools/fixtures/_ms3d_encode.luau and read +# back by assimp. +# tests/gen/ms3d_cases.luau { name, data, assimp } +# tests/gen/ms3d_gltf.luau glTF sample models: { name, data, files } +# tests/gen/ms3d_xcheck.luau { name, case? | gltf?, assimp } +import importlib.util, os + +INPUTS = ["src/Formats/model/ms3d", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/3ds.py", "tools/fixtures/_ms3d_encode.luau"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +GLTF = ("Box", "BoxTextured", "SimpleSkin", "RiggedSimple", "SimpleMeshes", "MultiUVTest", "NegativeScaleTest", + "AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes") + + +def generate(ctx): + M = load(ctx, "_model_ref") + X = load(ctx, "fbx") + R = load(ctx, "3ds") + tmp = M.tempdir() + d = os.path.join(X.assimp_src(ctx), "test", "models", "MS3D") + cases = [{"name": "assimp/" + f, "path": os.path.join(d, f)} for f in sorted(os.listdir(d)) if f.lower().endswith(".ms3d")] + for c, a in zip(cases, R.reference(ctx, M, X, [c["path"] for c in cases], tmp)): + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("ms3d_cases", cases) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + dd = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(dd)) if f.endswith(".gltf") or f.endswith(".glb")] if os.path.isdir(dd) else [] + if mains: + picks.append({"name": model + "/" + variant, "data": open(os.path.join(dd, mains[0]), "rb").read(), + "files": {f: open(os.path.join(dd, f), "rb").read() for f in sorted(os.listdir(dd)) if f != mains[0]}}) + break + ctx.emit("ms3d_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_ms3d_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".ms3d")) + paths = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + paths.append(p) + xs = [] + for n, a in zip(names, R.reference(ctx, M, X, paths, xtmp)): + kind, idx = n[:-5].split("_") + e = {"name": n, "assimp": a} + e["case" if kind == "case" else "gltf"] = int(idx) + xs.append(e) + ctx.emit("ms3d_xcheck", xs)