diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index b22a2cb..2df730e 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
+| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.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 | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index a0eb883..7aa19d3 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -194,6 +194,18 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
+ {
+ name = "3mf",
+ category = "model",
+ path = "model/3mf",
+ extensions = { "3mf" },
+ mime = { "model/3mf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
+ caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
+ load = function()
+ return require("@formats/model/3mf")
+ end,
+ },
{
name = "fbx",
category = "model",
diff --git a/src/Formats/model/3mf/Read.luau b/src/Formats/model/3mf/Read.luau
new file mode 100644
index 0000000..710de1c
--- /dev/null
+++ b/src/Formats/model/3mf/Read.luau
@@ -0,0 +1,598 @@
+--!strict
+-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first
+-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items),
+-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension
+-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry,
+-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit.
+-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and
+-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ.
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+local Zip = require("@formats/containers/Zip")
+
+local Read = {}
+
+local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
+local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
+Read.UNITS = UNITS
+local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" }
+local MAX_DEPTH = 64
+
+local localName = Xml.localName
+
+-- an attribute by local name (namespaced attributes such as p:path)
+local function attr(node: any, name: string): string?
+ local a = node.attrs
+ local v = a[name]
+ if v ~= nil then
+ return v
+ end
+ for k, x in next, a do
+ if type(k) == "string" and localName(k) == name then
+ return x
+ end
+ end
+ return nil
+end
+
+local function int(s: string?): number?
+ local n = if s then tonumber(s) else nil
+ if n and n == math.floor(n) and n >= 0 then
+ return n
+ end
+ return nil
+end
+
+-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1
+local function hexColor(s: string?): { number }?
+ if type(s) ~= "string" then
+ return nil
+ end
+ local h = string.match(s, "^%s*#(%x+)%s*$")
+ if not h or (#h ~= 6 and #h ~= 8) then
+ return nil
+ end
+ local function c(i: number): number
+ return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255
+ end
+ return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 }
+end
+Read.hexColor = hexColor
+
+function Read.toLinear(c: number): number
+ if c <= 0.04045 then
+ return c / 12.92
+ end
+ return ((c + 0.055) / 1.055) ^ 2.4
+end
+local toLinear = Read.toLinear
+
+-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid
+local function transform(s: string?): ({ number }?, boolean)
+ if not s then
+ return nil, true
+ end
+ local v = {}
+ for w in string.gmatch(s, "%S+") do
+ local n = tonumber(w)
+ if not n or n ~= n or n == math.huge or n == -math.huge then
+ return nil, false
+ end
+ table.insert(v, n)
+ end
+ if #v ~= 12 then
+ return nil, false
+ end
+ local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 }
+ for i = 1, 16 do
+ if m[i] ~= Types.Scene.IDENTITY[i] then
+ return m, true
+ end
+ end
+ return nil, true
+end
+
+local function normPath(p: string): string
+ p = string.gsub(p, "\\", "/")
+ p = string.gsub(p, "^/+", "")
+ return p
+end
+
+-- one model part parsed into its resources and build
+type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? }
+
+local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?)
+ local doc, err = Xml.decode(text, { parents = false })
+ if not doc then
+ return nil, err
+ end
+ local root = (doc :: any).root
+ if not root or localName(root.name) ~= "model" then
+ return nil, Err.new(Err.CORRUPT, path .. ": the root element is not ")
+ end
+ local maxV = opts.maxVertices or 2 ^ 25
+ local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") }
+ local resources: any = nil
+ local build: any = nil
+ for _, ch in Xml.children(root) do
+ local ln = localName(ch.name)
+ if ln == "metadata" then
+ local n = attr(ch, "name")
+ if n then
+ model.metadata[n] = Xml.text(ch)
+ end
+ elseif ln == "resources" then
+ resources = ch
+ elseif ln == "build" then
+ build = ch
+ end
+ end
+ local total = 0
+ if resources then
+ for _, r in Xml.children(resources) do
+ local ln = localName(r.name)
+ local id = int(attr(r, "id"))
+ if id == nil then
+ continue
+ end
+ if ln == "object" then
+ local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") }
+ local mesh = Xml.child(r, "mesh")
+ local comps = Xml.child(r, "components")
+ if mesh then
+ local verts = Xml.child(mesh, "vertices")
+ local tris = Xml.child(mesh, "triangles")
+ local vl = if verts then Xml.children(verts, "vertex") else {}
+ local tl = if tris then Xml.children(tris, "triangle") else {}
+ total += #vl + #tl * 3
+ if total > maxV then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners")
+ end
+ local nv = #vl
+ local pos = table.create(nv * 3, 0)
+ for i, v in vl do
+ local a = v.attrs
+ local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z)
+ if not x or not y or not z then
+ return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i)
+ end
+ pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z
+ end
+ local nt = #tl
+ local tv = table.create(nt * 3, 0)
+ local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none)
+ for i, tri in tl do
+ local a = tri.attrs
+ local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3)
+ if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then
+ return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index")
+ end
+ tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3
+ local b = i * 4 - 4
+ local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3)
+ tp[b + 1] = pid or -1
+ tp[b + 2] = p1 or -1
+ tp[b + 3] = p2 or p1 or -1
+ tp[b + 4] = p3 or p1 or -1
+ end
+ o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt
+ end
+ if comps then
+ o.components = {}
+ for _, c in Xml.children(comps, "component") do
+ local oid = int(attr(c, "objectid"))
+ local m, ok = transform(attr(c, "transform"))
+ if oid and ok then
+ table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") })
+ end
+ end
+ end
+ model.res[id] = o
+ elseif ln == "basematerials" then
+ local items = {}
+ for _, b in Xml.children(r, "base") do
+ table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") })
+ end
+ model.res[id] = { kind = "base", id = id, items = items }
+ elseif ln == "colorgroup" then
+ local items = {}
+ for _, c in Xml.children(r, "color") do
+ table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 })
+ end
+ model.res[id] = { kind = "color", id = id, items = items }
+ elseif ln == "texture2d" then
+ model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") }
+ elseif ln == "texture2dgroup" then
+ local uvs = {}
+ for _, c in Xml.children(r, "tex2coord") do
+ table.insert(uvs, tonumber(attr(c, "u")) or 0)
+ table.insert(uvs, tonumber(attr(c, "v")) or 0)
+ end
+ model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 }
+ elseif ln == "compositematerials" then
+ local mats = {}
+ for w in string.gmatch(attr(r, "matindices") or "", "%S+") do
+ table.insert(mats, tonumber(w) or 0)
+ end
+ local items = {}
+ for _, c in Xml.children(r, "composite") do
+ local vals = {}
+ for w in string.gmatch(attr(c, "values") or "", "%S+") do
+ table.insert(vals, tonumber(w) or 0)
+ end
+ table.insert(items, vals)
+ end
+ model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items }
+ elseif ln == "multiproperties" then
+ local pids = {}
+ for w in string.gmatch(attr(r, "pids") or "", "%S+") do
+ table.insert(pids, tonumber(w) or -1)
+ end
+ local items = {}
+ for _, c in Xml.children(r, "multi") do
+ local ix = {}
+ for w in string.gmatch(attr(c, "pindices") or "", "%S+") do
+ table.insert(ix, tonumber(w) or 0)
+ end
+ table.insert(items, ix)
+ end
+ model.res[id] = { kind = "multi", id = id, pids = pids, items = items }
+ end
+ end
+ end
+ if build then
+ for _, it in Xml.children(build, "item") do
+ local oid = int(attr(it, "objectid"))
+ local m, ok = transform(attr(it, "transform"))
+ if oid and ok then
+ table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") })
+ end
+ end
+ end
+ return model, nil
+end
+
+-- the root model part's path
+local function rootPath(zip: any): string?
+ local rels = zip:readString("_rels/.rels")
+ if rels then
+ local doc = Xml.decode(rels, { parents = false })
+ if doc then
+ for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do
+ local t, target = attr(rel, "Type"), attr(rel, "Target")
+ if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then
+ return normPath(target)
+ end
+ end
+ end
+ end
+ for _, e in zip:list() do
+ if not e.isDir and string.find(string.lower(e.name), "%.model$") then
+ return e.name
+ end
+ end
+ return nil
+end
+
+function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
+ local rootP = rootPath(zip)
+ if not rootP then
+ return nil, Err.new(Err.CORRUPT, "no 3D model part in the package")
+ end
+ local models: { [string]: Model } = {}
+ local function getModel(path: string): (Model?, Err.Err?)
+ local p = normPath(path)
+ local m = models[p]
+ if m then
+ return m, nil
+ end
+ local text, err = zip:readString(p)
+ if not text then
+ return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p)
+ end
+ if string.sub(text, 1, 5) == "%3McF" then
+ return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped")
+ end
+ local mm, perr = parseModel(text, p, opts)
+ if not mm then
+ return nil, perr
+ end
+ models[p] = mm
+ return mm, nil
+ end
+ local root, rerr = getModel(rootP)
+ if not root then
+ return nil, rerr
+ end
+
+ local scene = Types.Scene.new()
+ local unitName = root.unit or "millimeter"
+ scene.meta.up = "z"
+ scene.meta.unit = UNITS[unitName] or 1e-3
+ scene.meta.metadata = root.metadata
+ scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required }
+
+ -- textures and materials (shared across model parts by part path + resource id)
+ local texCache: { [string]: number } = {}
+ local function texture(model: Model, id: number): number?
+ local key = model.path .. "#" .. id
+ if texCache[key] then
+ return texCache[key]
+ end
+ local r = model.res[id]
+ if not r or r.kind ~= "texture" or type(r.path) ~= "string" then
+ return nil
+ end
+ local data = zip:read(normPath(r.path))
+ local tex: Types.Texture = {
+ name = r.path,
+ data = data,
+ mime = r.contenttype,
+ uri = r.path,
+ sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil },
+ extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } },
+ }
+ table.insert(scene.textures, tex)
+ texCache[key] = #scene.textures
+ return #scene.textures
+ end
+ local matCache: { [string]: number } = {}
+ local function addMaterial(key: string, make: () -> Types.Material): number
+ local i = matCache[key]
+ if i then
+ return i
+ end
+ table.insert(scene.materials, make())
+ matCache[key] = #scene.materials
+ return #scene.materials
+ end
+ local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material
+ local m = Types.Scene.material(name)
+ m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] }
+ m.metallic = 0
+ m.roughness = 1
+ if c[4] < 1 then
+ m.alphaMode = "blend"
+ end
+ m.extras = { ["3mf"] = extras }
+ return m
+ end
+
+ -- property of one corner -> (group key, material index?, kind, resource, index)
+ local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number)
+ local r = model.res[pid]
+ if not r or p < 0 then
+ return "none", nil, "none", nil, 0
+ end
+ local k = r.kind
+ if k == "base" then
+ local item = r.items[p + 1]
+ if not item then
+ return "none", nil, "none", nil, 0
+ end
+ local key = "b" .. model.path .. "#" .. pid .. ":" .. p
+ return key, addMaterial(key, function()
+ return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex })
+ end), "base", r, p
+ elseif k == "color" then
+ return "c" .. model.path .. "#" .. pid, nil, "color", r, p
+ elseif k == "texgroup" then
+ local ti = r.texid and texture(model, r.texid)
+ local mat: number? = nil
+ if ti then
+ local mk = "t" .. model.path .. "#" .. (r.texid :: number)
+ mat = addMaterial(mk, function()
+ local m = Types.Scene.material("texture " .. tostring(r.texid))
+ m.metallic = 0
+ m.roughness = 1
+ m.baseColorTexture = { texture = ti :: number }
+ m.extras = { ["3mf"] = { texture = r.texid } }
+ return m
+ end)
+ end
+ return "t" .. model.path .. "#" .. pid, mat, "tex", r, p
+ elseif k == "composite" then
+ local item = r.items[p + 1]
+ local base = r.matid and model.res[r.matid]
+ if not item or not base or base.kind ~= "base" then
+ return "none", nil, "none", nil, 0
+ end
+ local key = "x" .. model.path .. "#" .. pid .. ":" .. p
+ return key, addMaterial(key, function()
+ local c, sum = { 0, 0, 0, 0 }, 0
+ for j, w in item do
+ local b = base.items[(r.matindices[j] or 0) + 1]
+ if b then
+ for q = 1, 4 do
+ c[q] += b.color[q] * w
+ end
+ sum += w
+ end
+ end
+ if sum > 0 then
+ for q = 1, 4 do
+ c[q] /= sum
+ end
+ else
+ c = { 1, 1, 1, 1 }
+ end
+ return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p })
+ end), "base", r, p
+ elseif k == "multi" and (depth or 0) < 1 then
+ local item = r.items[p + 1]
+ local first = r.pids[1]
+ if item and first then
+ return resolve(model, first, item[1] or 0, 1)
+ end
+ end
+ return "none", nil, "none", nil, 0
+ end
+
+ -- one Scene mesh per (part, object) with a mesh
+ local meshCache: { [string]: number } = {}
+ local function buildMesh(model: Model, o: any): number?
+ local key = model.path .. "#" .. o.id
+ local cached = meshCache[key]
+ if cached ~= nil then
+ return if cached > 0 then cached else nil
+ end
+ local groups: { [string]: any } = {}
+ local order: { any } = {}
+ local pos, tv, tp = o.positions, o.tv, o.tp
+ for t = 0, o.nt - 1 do
+ local pid = tp[t * 4 + 1]
+ local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] }
+ if pid < 0 then
+ pid = o.pid or -1
+ if ps[1] < 0 then
+ local d = o.pindex or (if pid >= 0 then 0 else -1)
+ ps = { d, d, d }
+ end
+ end
+ local gkey, mat, kind, res, _ = resolve(model, pid, ps[1])
+ local g = groups[gkey]
+ if not g then
+ g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 }
+ groups[gkey] = g
+ table.insert(order, g)
+ end
+ for c = 1, 3 do
+ local v = tv[t * 3 + c]
+ local vk = v
+ local pc = 0
+ if kind == "color" or kind == "tex" then
+ pc = ps[c]
+ local cnt = if kind == "color" then #res.items else res.count
+ if pc < 0 or pc >= cnt then
+ pc = ps[1]
+ end
+ if pc < 0 or pc >= cnt then
+ pc = 0
+ end
+ vk = v * (cnt + 1) + pc
+ end
+ local ni = g.vmap[vk]
+ if not ni then
+ ni = g.n
+ g.n += 1
+ g.vmap[vk] = ni
+ table.insert(g.pos, pos[v * 3 + 1])
+ table.insert(g.pos, pos[v * 3 + 2])
+ table.insert(g.pos, pos[v * 3 + 3])
+ if kind == "color" then
+ local col = res.items[pc + 1] or { 1, 1, 1, 1 }
+ table.insert(g.attr, toLinear(col[1]))
+ table.insert(g.attr, toLinear(col[2]))
+ table.insert(g.attr, toLinear(col[3]))
+ table.insert(g.attr, col[4])
+ elseif kind == "tex" then
+ table.insert(g.attr, res.uvs[pc * 2 + 1] or 0)
+ table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0))
+ end
+ end
+ table.insert(g.idx, ni)
+ end
+ end
+ local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } }
+ for _, g in order do
+ local n = g.n
+ local pa = Types.Scene.accessor(nil, "f32", 3, n)
+ for i, x in g.pos do
+ buffer.writef32(pa.data, (i - 1) * 4, x)
+ end
+ local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx)
+ for i, x in g.idx do
+ buffer.writeu32(ia.data, (i - 1) * 4, x)
+ end
+ local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material }
+ if g.kind == "color" then
+ local ca = Types.Scene.accessor(nil, "f32", 4, n)
+ for i, x in g.attr do
+ buffer.writef32(ca.data, (i - 1) * 4, x)
+ end
+ prim.attributes.COLOR_0 = ca
+ prim.extras = { ["3mf"] = { colorgroup = g.res.id } }
+ elseif g.kind == "tex" then
+ local ua = Types.Scene.accessor(nil, "f32", 2, n)
+ for i, x in g.attr do
+ buffer.writef32(ua.data, (i - 1) * 4, x)
+ end
+ prim.attributes.TEXCOORD_0 = ua
+ prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } }
+ end
+ table.insert(mesh.primitives, prim)
+ end
+ if #mesh.primitives == 0 then
+ meshCache[key] = 0
+ return nil
+ end
+ table.insert(scene.meshes, mesh)
+ meshCache[key] = #scene.meshes
+ return #scene.meshes
+ end
+
+ -- nodes: one per object instance (build items and components)
+ local nodeCount = 0
+ local maxNodes = opts.maxNodes or 2 ^ 20
+ local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?)
+ function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?)
+ if depth > MAX_DEPTH then
+ return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)")
+ end
+ nodeCount += 1
+ if nodeCount > maxNodes then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances")
+ end
+ local o = model.res[oid]
+ if not o or o.kind ~= "object" then
+ return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path)
+ end
+ local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } }
+ table.insert(scene.nodes, node)
+ local index = #scene.nodes
+ if o.positions then
+ node.mesh = buildMesh(model, o)
+ end
+ if o.components then
+ for _, c in o.components do
+ local m: Model? = model
+ if c.path then
+ local mm, err = getModel(c.path)
+ if not mm then
+ return nil, err
+ end
+ m = mm
+ end
+ local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path })
+ if not child then
+ return nil, err
+ end
+ table.insert(node.children, child)
+ end
+ end
+ return index, nil
+ end
+ for _, it in root.items do
+ local m: Model? = root
+ if it.path then
+ local mm, err = getModel(it.path)
+ if not mm then
+ return nil, err
+ end
+ m = mm
+ end
+ local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true })
+ if not idx then
+ return nil, err
+ end
+ table.insert(scene.roots, idx)
+ end
+ return scene, nil
+end
+
+function Read.open(r: any): (any, Err.Err?)
+ return Zip.open(r)
+end
+
+return Read
diff --git a/src/Formats/model/3mf/Write.luau b/src/Formats/model/3mf/Write.luau
new file mode 100644
index 0000000..a1f4f4b
--- /dev/null
+++ b/src/Formats/model/3mf/Write.luau
@@ -0,0 +1,417 @@
+--!strict
+-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles,
+-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the
+-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours),
+-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has
+-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/).
+-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale.
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+local Zip = require("@formats/containers/Zip")
+
+local Write = {}
+
+local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
+local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
+local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
+local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"
+local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" }
+local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
+local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" }
+
+local fmt = string.format
+local esc = Xml.escapeAttr
+
+local function num(x: number): string
+ if x ~= x or x == math.huge or x == -math.huge then
+ return "0"
+ end
+ if x == math.floor(x) and math.abs(x) < 1e15 then
+ return fmt("%d", x)
+ end
+ return fmt("%.9g", x)
+end
+
+local function toSrgb(c: number): number
+ c = math.clamp(c, 0, 1)
+ if c <= 0.0031308 then
+ return c * 12.92
+ end
+ return 1.055 * c ^ (1 / 2.4) - 0.055
+end
+
+local function hex(r: number, g: number, b: number, a: number): string
+ local function q(x: number): number
+ return math.clamp(math.floor(x * 255 + 0.5), 0, 255)
+ end
+ return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1)))
+end
+
+-- the triangle corner list of a primitive (0-based vertex indices) or nil
+local function triangles(prim: any): { number }?
+ local pos = prim.attributes and prim.attributes.POSITION
+ if type(pos) ~= "table" then
+ return nil
+ end
+ local n = pos.count
+ local ix: { number } = {}
+ if prim.indices then
+ local get = Types.Scene.reader(prim.indices)
+ if not get then
+ return nil
+ end
+ for i = 0, prim.indices.count - 1 do
+ ix[i + 1] = get(i, 0)
+ end
+ else
+ for i = 1, n do
+ ix[i] = i - 1
+ end
+ end
+ for _, v in ix do
+ if v ~= v or v < 0 or v >= n then
+ return nil
+ end
+ end
+ local mode = prim.mode or "triangles"
+ local out: { number } = {}
+ local function tri(a: number, b: number, c: number)
+ if a ~= b and b ~= c and a ~= c then
+ table.insert(out, a)
+ table.insert(out, b)
+ table.insert(out, c)
+ end
+ end
+ if mode == "triangles" then
+ for i = 1, #ix - 2, 3 do
+ tri(ix[i], ix[i + 1], ix[i + 2])
+ end
+ elseif mode == "triangle_strip" then
+ for i = 1, #ix - 2 do
+ if i % 2 == 1 then
+ tri(ix[i], ix[i + 1], ix[i + 2])
+ else
+ tri(ix[i + 1], ix[i], ix[i + 2])
+ end
+ end
+ elseif mode == "triangle_fan" then
+ for i = 2, #ix - 1 do
+ tri(ix[1], ix[i], ix[i + 1])
+ end
+ elseif mode == "polygons" and prim.faces then
+ local get = Types.Scene.reader(prim.faces)
+ if not get then
+ return nil
+ end
+ local at = 1
+ for f = 0, prim.faces.count - 1 do
+ local k = get(f, 0)
+ if at + k - 1 > #ix then
+ break
+ end
+ for j = 1, k - 2 do
+ tri(ix[at], ix[at + j], ix[at + j + 1])
+ end
+ at += k
+ end
+ else
+ return nil
+ end
+ return out
+end
+
+function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
+ local o = opts or {}
+ local nextId = 0
+ local function id(): number
+ nextId += 1
+ return nextId
+ end
+ local res: { string } = {} -- resource XML chunks, in definition order
+ local files: { { name: string, data: buffer, mime: string } } = {}
+
+ -- unit
+ local unitName: string, scale: number = "millimeter", 1
+ local mu: any = scene.meta and scene.meta.unit
+ if type(o.unit) == "string" and UNITS[o.unit] then
+ unitName = o.unit
+ if type(mu) == "number" and mu > 0 then
+ scale = mu / UNITS[o.unit]
+ end
+ elseif type(mu) == "number" and mu > 0 then
+ local found = false
+ for _, u in UNIT_ORDER do
+ if math.abs(UNITS[u] - mu) <= 1e-9 * mu then
+ unitName, found = u, true
+ break
+ end
+ end
+ if not found then
+ scale = mu / 1e-3
+ end
+ end
+
+ -- base materials: one group with every Scene material
+ local baseId: number? = nil
+ local nmat = #scene.materials
+ local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed
+ local needDefault = false
+ if nmat > 0 then
+ baseId = id()
+ end
+
+ -- textures used as base colour textures
+ local texRes: { [number]: number } = {}
+ local function textureId(ti: number): number?
+ if texRes[ti] ~= nil then
+ return if texRes[ti] > 0 then texRes[ti] else nil
+ end
+ local tex = scene.textures[ti]
+ local ext = tex and TEX_EXT[tex.mime or ""]
+ if not tex or type(tex.data) ~= "buffer" or not ext then
+ texRes[ti] = 0
+ return nil
+ end
+ local rid = id()
+ local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string)
+ table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string })
+ local s = tex.sampler
+ local function tile(w: string?): string
+ return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap"
+ end
+ local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto"
+ table.insert(res, fmt('\t\t\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter))
+ texRes[ti] = rid
+ return rid
+ end
+
+ -- objects
+ local objectOf: { [number]: number } = {}
+ local objChunks: { string } = {}
+ for mi, mesh in scene.meshes do
+ local verts: { string } = {}
+ local tris: { string } = {}
+ local base = 0
+ local objPid: number?, objP: number? = nil, nil
+ local anyNone = false
+ local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 }
+ for _, prim in mesh.primitives do
+ local corners = triangles(prim)
+ if not corners or #corners == 0 then
+ continue
+ end
+ local pos = prim.attributes.POSITION
+ local getP = Types.Scene.reader(pos)
+ if not getP then
+ continue
+ end
+ local n = pos.count
+ for v = 0, n - 1 do
+ table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0)))
+ end
+ -- properties: texture group, colour group, base material, none
+ local pid, kind = -1, "none"
+ local mat = prim.material and scene.materials[prim.material]
+ local uv = prim.attributes.TEXCOORD_0
+ local col = prim.attributes.COLOR_0
+ local tref = mat and mat.baseColorTexture
+ local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil
+ if tid and uv then
+ local get = Types.Scene.reader(uv)
+ if get then
+ pid, kind = id(), "tex"
+ local parts = { fmt('\t\t\n', pid, tid) }
+ for v = 0, n - 1 do
+ table.insert(parts, fmt('\t\t\t\n', num(get(v, 0)), num(1 - get(v, 1))))
+ end
+ table.insert(parts, "\t\t\n")
+ table.insert(res, table.concat(parts))
+ end
+ end
+ if kind == "none" and col then
+ local get = Types.Scene.reader(col)
+ if get then
+ pid, kind = id(), "color"
+ local parts = { fmt('\t\t\n', pid) }
+ local four = col.components >= 4
+ for v = 0, n - 1 do
+ table.insert(parts, fmt('\t\t\t\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1)))
+ end
+ table.insert(parts, "\t\t\n")
+ table.insert(res, table.concat(parts))
+ end
+ end
+ local pindex = -1
+ if kind == "none" and baseId and prim.material and scene.materials[prim.material] then
+ pid, kind, pindex = baseId :: number, "base", prim.material - 1
+ end
+ for i = 1, #corners, 3 do
+ local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base
+ if kind == "tex" or kind == "color" then
+ table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] })
+ elseif kind == "base" then
+ table.insert(triList, { a, b, c, pid, pindex, pindex, pindex })
+ else
+ table.insert(triList, { a, b, c, -1, -1, -1, -1 })
+ anyNone = true
+ end
+ if objPid == nil and kind ~= "none" then
+ objPid, objP = pid, if kind == "base" then pindex else corners[i]
+ end
+ end
+ base += n
+ end
+ if #triList == 0 then
+ continue
+ end
+ if objPid and anyNone then
+ needDefault = true
+ if not baseId then
+ baseId = id()
+ end
+ end
+ for _, t in triList do
+ if t[4] < 0 and objPid then
+ t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase
+ end
+ if t[4] < 0 then
+ table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3]))
+ elseif t[5] == t[6] and t[6] == t[7] then
+ table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5]))
+ else
+ table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7]))
+ end
+ end
+ local oid = id()
+ objectOf[mi] = oid
+ local head = fmt('\t\t\n" }))
+ table.insert(res, objChunks[#objChunks])
+ end
+
+ -- the base material group goes first (its id was taken first)
+ if baseId then
+ local parts = { fmt('\t\t\n', baseId) }
+ for _, m in scene.materials do
+ local c = m.baseColor or { 1, 1, 1, 1 }
+ table.insert(parts, fmt('\t\t\t\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1)))
+ end
+ if needDefault then
+ table.insert(parts, '\t\t\t\n')
+ end
+ table.insert(parts, "\t\t\n")
+ table.insert(res, 1, table.concat(parts))
+ end
+
+ -- build items: every node with a mesh, at its world matrix
+ local items: { string } = {}
+ local seen: { [number]: boolean } = {}
+ for _, pl in Types.Scene.flatten(scene) do
+ if seen[pl.node] then
+ continue
+ end
+ seen[pl.node] = true
+ local oid = objectOf[pl.mesh]
+ if not oid then
+ continue
+ end
+ local m = pl.matrix
+ local s = scale
+ local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s }
+ local ident = s == 1
+ for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do
+ if tr[i] ~= v then
+ ident = false
+ end
+ end
+ if ident then
+ table.insert(items, fmt('\t\t\n', oid))
+ else
+ local ns = table.create(12, "")
+ for i = 1, 12 do
+ ns[i] = num(tr[i])
+ end
+ table.insert(items, fmt('\t\t\n', oid, table.concat(ns, " ")))
+ end
+ end
+
+ -- metadata
+ local meta: { string } = {}
+ local md = scene.meta and scene.meta.metadata
+ if type(md) == "table" then
+ local keys: { string } = {}
+ for k: any, v: any in md do
+ if type(k) == "string" and (type(v) == "string" or type(v) == "number") then
+ table.insert(keys, k)
+ end
+ end
+ table.sort(keys)
+ for _, k in keys do
+ table.insert(meta, fmt('\t%s\n', esc(k), Xml.escape(tostring(md[k]))))
+ end
+ end
+
+ local model = table.concat({
+ '\n',
+ '\n',
+ table.concat(meta),
+ "\t\n",
+ table.concat(res),
+ "\t\n\t\n",
+ table.concat(items),
+ "\t\n\n",
+ })
+
+ local types = { '\n\n',
+ '\t\n',
+ '\t\n' }
+ local exts: { [string]: boolean } = {}
+ for _, f in files do
+ local e = string.match(f.name, "%.(%w+)$") :: string
+ if not exts[e] then
+ exts[e] = true
+ table.insert(types, fmt('\t\n', e, f.mime))
+ end
+ end
+ table.insert(types, "\n")
+ local rels = '\n\n'
+ .. fmt('\t\n', REL_MODEL)
+ .. "\n"
+
+ local w = Zip.writer()
+ local level = o.level or 6
+ local method = if level == 0 then "store" else "deflate"
+ local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method })
+ if ok then
+ ok, err = w:add("_rels/.rels", rels, { level = level, method = method })
+ end
+ if ok then
+ ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method })
+ end
+ if ok and #files > 0 then
+ local mr = { '\n\n' }
+ for i, f in files do
+ table.insert(mr, fmt('\t\n', esc(f.name), i, REL_TEXTURE))
+ end
+ table.insert(mr, "\n")
+ ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method })
+ for _, f in files do
+ if ok then
+ ok, err = w:add(f.name, f.data, { method = "store" })
+ end
+ end
+ end
+ if not ok then
+ return nil, err or Err.new(Err.ARG, "zip writer failed")
+ end
+ return w:finish()
+end
+
+return Write
diff --git a/src/Formats/model/3mf/init.luau b/src/Formats/model/3mf/init.luau
new file mode 100644
index 0000000..025a695
--- /dev/null
+++ b/src/Formats/model/3mf/init.luau
@@ -0,0 +1,95 @@
+--!strict
+-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2,
+-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts
+-- (codecs/Xml).
+-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from
+-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices
+-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata
+-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours
+-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to
+-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it
+-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first
+-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices
+-- are split where a vertex's corners carry different colours / texture coordinates.
+-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a
+-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups,
+-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit).
+-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are
+-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Zip = require("@formats/containers/Zip")
+local Read = require("@formats/model/3mf/Read")
+local Write = require("@formats/model/3mf/Write")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local ThreeMf = {
+ name = "3mf",
+ category = "model",
+ extensions = { "3mf" },
+ mime = { "model/3mf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
+ caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25)
+ maxNodes: number?, -- refuse more object instances (default 2^20)
+}
+export type EncodeOptions = {
+ unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else
+ -- millimeter); positions are scaled through the build transforms when meta.unit differs
+ level: number?, -- deflate level for the XML parts (default 6; 0 stores them)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function ThreeMf.sniff(r: Bytes.Reader): number
+ if r:peek(4) ~= "PK\3\4" then
+ return 0
+ end
+ -- the central directory sits at the end: look for the model part's name there, then at the start
+ local n = r:size()
+ local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536))
+ if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then
+ return 0.95
+ end
+ local head = r:peek(256)
+ if string.find(head, "3D/", 1, true) then
+ return 0.7
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
+ local zip, zerr = Zip.open(r)
+ if not zip then
+ return nil, zerr
+ end
+ local ok, scene, err = pcall(Read.scene, zip, opts or {})
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")")
+ end
+ return scene, err
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs a Scene")
+ end
+ if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then
+ return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit))
+ end
+ local ok, out, err = pcall(Write.build, scene, opts)
+ if not ok then
+ return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")")
+ end
+ return out, err
+end
+
+return ThreeMf
diff --git a/tests/model/3mf.luau b/tests/model/3mf.luau
new file mode 100644
index 0000000..f2a124a
--- /dev/null
+++ b/tests/model/3mf.luau
@@ -0,0 +1,420 @@
+-- model/3mf tests: the lib3mf test suite and SDK files, assimp's box.3mf and files from assimp's / trimesh's 3MF
+-- exporters against lib3mf (world triangles, area, bounds through build items and components; unit), assimp and
+-- trimesh; our writer's output read back by lib3mf / assimp / trimesh (3mf_xcheck); round trips through our own reader
+-- (materials, vertex colours, textures, hierarchy, units); hand-written packages for per-corner colour / texture
+-- groups, composite and multiproperties, components across model parts (p:path), units; error codes; the fuzz
+-- no-throw pass. Fixtures: tools/fixtures/3mf.py.
+local T = require("@tests/T")
+local ThreeMf = require("@formats/model/3mf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Zip = require("@formats/containers/Zip")
+local Cases = require("@tests/gen/3mf_cases")
+local Xcheck = require("@tests/gen/3mf_xcheck")
+
+local t = T.suite("3mf")
+
+local function decode(data: any, opts: any?): (any, any)
+ local b = if type(data) == "string" then buffer.fromstring(data) else data
+ return ThreeMf.decode(Bytes.reader(b), opts)
+end
+
+t:eq(ThreeMf.name, "3mf", "name")
+t:eq(ThreeMf.category, "model", "category")
+t:check(ThreeMf.caps.decode and ThreeMf.caps.encode and ThreeMf.extensions[1] == "3mf", "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
+
+-- world-space triangles, area and bounds of every placed primitive
+local function metrics(scene: any): (number, number, { number }, { number })
+ local tris, area = 0, 0
+ local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
+ for _, pl in Types.Scene.flatten(scene) do
+ local p = pl.primitive
+ local m = pl.matrix
+ local pos = p.attributes.POSITION
+ local W = {}
+ for i = 0, pos.count - 1 do
+ local x, y, z = buffer.readf32(pos.data, i * 12), buffer.readf32(pos.data, i * 12 + 4), buffer.readf32(pos.data, i * 12 + 8)
+ local w = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
+ W[i] = w
+ end
+ local ind = p.indices
+ for k = 0, ind.count // 3 - 1 do
+ local a, b, c = W[buffer.readu32(ind.data, k * 12)], W[buffer.readu32(ind.data, k * 12 + 4)], W[buffer.readu32(ind.data, k * 12 + 8)]
+ for _, v in { a, b, c } do
+ for q = 1, 3 do
+ lo[q] = math.min(lo[q], v[q])
+ hi[q] = math.max(hi[q], v[q])
+ end
+ end
+ local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }
+ local e2 = { c[1] - a[1], c[2] - a[2], c[3] - a[3] }
+ local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
+ area += math.sqrt(x * x + y * y + z * z) / 2
+ tris += 1
+ end
+ end
+ return tris, area, lo, hi
+end
+
+local function boundsNear(lo: { number }, hi: { number }, rmin: { number }, rmax: { number }): boolean
+ local ext = 0
+ for q = 1, 3 do
+ ext = math.max(ext, rmax[q] - rmin[q])
+ end
+ local eps = 1e-5 * math.max(ext, 1e-6)
+ for q = 1, 3 do
+ if math.abs(lo[q] - rmin[q]) > eps or math.abs(hi[q] - rmax[q]) > eps then
+ return false
+ end
+ end
+ return true
+end
+
+-- ------------------------------------------------------------------------------------------------ reference files
+local UNIT_NAMES = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
+local refCount, rejectedOk, unsupported = 0, 0, 0
+local byIndex = {}
+for i, c in Cases do
+ local scene, err = decode(c.data)
+ byIndex[i] = scene
+ local ref = c.lib3mf
+ if ref.failed then
+ -- lib3mf rejects these (strict checks we do not make); it is enough not to throw
+ rejectedOk += 1
+ continue
+ end
+ if not scene and err and err.code == Err.UNSUPPORTED and string.find(c.name, "SecureContent", 1, true) then
+ unsupported += 1 -- encrypted / wrapped model parts (the secure content extension)
+ continue
+ end
+ t:check(scene, c.name .. ": decode: " .. tostring(err))
+ if not scene then
+ continue
+ end
+ t:eq(scene.meta.source.unit, ref.unit, c.name .. ": unit")
+ t:eq(scene.meta.unit, UNIT_NAMES[ref.unit], c.name .. ": meta.unit")
+ t:eq(scene.meta.up, "z", c.name .. ": up")
+ local tris, area, lo, hi = metrics(scene)
+ t:eq(tris, ref.triangles, c.name .. ": world triangles (lib3mf)")
+ t:check(near(area, ref.area, 1e-5), string.format("%s: area %.7g, lib3mf %.7g", c.name, area, ref.area))
+ if ref.min then
+ t:check(boundsNear(lo, hi, ref.min, ref.max), c.name .. ": bounds (lib3mf)")
+ end
+ t:check(#scene.textures <= ref.textures, c.name .. ": textures <= lib3mf's texture2d count")
+ refCount += 1
+ -- trimesh reads build items and components the same way (it skips degenerate input)
+ local tm = c.trimesh
+ if tm and not tm.failed and tm.faces == tris and tm.faces > 0 then
+ t:check(near(area, tm.area, 1e-5), c.name .. ": area (trimesh)")
+ end
+end
+t:note("%d files: %d against lib3mf, %d rejected by lib3mf (decoded without throwing), %d secure content (UNSUPPORTED)", #Cases, refCount, rejectedOk, unsupported)
+
+-- ------------------------------------------------------------------------------------------------ our output read back
+local xchecked, withTextures = 0, 0
+for _, x in Xcheck do
+ local c = Cases[x.case]
+ local ref = c.lib3mf
+ if not byIndex[x.case] then
+ continue
+ end
+ t:check(not x.lib3mf.failed, x.name .. " (" .. c.name .. "): lib3mf reads our file: " .. tostring(x.lib3mf.failed))
+ if not x.lib3mf.failed then
+ t:eq(x.lib3mf.triangles, ref.triangles, c.name .. ": our file's triangles (lib3mf)")
+ t:check(near(x.lib3mf.area, ref.area, 1e-5), string.format("%s: our file's area %.7g vs %.7g (lib3mf)", c.name, x.lib3mf.area, ref.area))
+ if ref.min then
+ t:check(boundsNear(x.lib3mf.min, x.lib3mf.max, ref.min, ref.max), c.name .. ": our file's bounds (lib3mf)")
+ end
+ t:eq(x.lib3mf.unit, ref.unit, c.name .. ": our file's unit (lib3mf)")
+ -- the material groups made it: textures, colour groups, base materials
+ local scene = byIndex[x.case]
+ local tex, col = 0, 0
+ for _, m in scene.meshes do
+ for _, p in m.primitives do
+ if p.attributes.TEXCOORD_0 and p.material and scene.materials[p.material].baseColorTexture then
+ tex += 1
+ elseif p.attributes.COLOR_0 then
+ col += 1
+ end
+ end
+ end
+ t:check((tex == 0) == (x.lib3mf.texGroups == 0), c.name .. ": our texture groups (lib3mf)")
+ t:check(tex == 0 or x.lib3mf.textures > 0, c.name .. ": our textures (lib3mf)")
+ t:eq(x.lib3mf.colorGroups, col, c.name .. ": our colour groups (lib3mf)")
+ t:eq(x.lib3mf.baseGroups, if #scene.materials > 0 then 1 else 0, c.name .. ": our base material group (lib3mf)")
+ if tex > 0 then
+ withTextures += 1
+ end
+ end
+ t:check(not x.assimp.failed or c.assimp.failed, c.name .. ": assimp reads our file")
+ if not x.trimesh.failed and x.trimesh.faces > 0 and not c.trimesh.failed and c.trimesh.faces == x.trimesh.faces then
+ t:check(near(x.trimesh.area, c.trimesh.area, 1e-5), c.name .. ": our file's area (trimesh)")
+ end
+ xchecked += 1
+end
+t:note("%d of our files read back by lib3mf / assimp / trimesh like the originals (%d with textures)", xchecked, withTextures)
+
+-- ------------------------------------------------------------------------------------------------ round trips (ours)
+local rts = 0
+for i, c in Cases do
+ local scene = byIndex[i]
+ if scene and not c.lib3mf.failed then
+ local out, err = ThreeMf.encode(scene)
+ t:check(out, c.name .. ": encode: " .. tostring(err))
+ local back, berr = decode(out)
+ t:check(back, c.name .. ": decode ours: " .. tostring(berr))
+ local a1, b1 = metrics(scene)
+ local a2, b2 = metrics(back)
+ t:eq(a2, a1, c.name .. ": round trip triangles")
+ t:check(near(b2, b1, 1e-6), c.name .. ": round trip area")
+ t:eq(back.meta.unit, scene.meta.unit, c.name .. ": round trip unit")
+ -- textures: the same bytes
+ local used = 0
+ for _, m in back.materials do
+ if m.baseColorTexture then
+ used += 1
+ t:check(back.textures[m.baseColorTexture.texture].data ~= nil, c.name .. ": texture bytes")
+ end
+ end
+ rts += 1
+ end
+end
+t:note("%d round trips through our writer", rts)
+
+-- ------------------------------------------------------------------------------------------------ hand-written packages
+local function package(model: string, extra: { [string]: string }?): buffer
+ local w = Zip.writer()
+ w:add("[Content_Types].xml", '', { method = "store" })
+ w:add("_rels/.rels", '', { method = "store" })
+ w:add("3D/3dmodel.model", model, { method = "store" })
+ for k, v in extra or {} do
+ w:add(k, v, { method = "store" })
+ end
+ return (w:finish())
+end
+local HEAD = ''
+local QUAD = '%s'
+local samples = {}
+
+local function f32s(acc: any): { number }
+ local out = {}
+ for i = 0, acc.count * acc.components - 1 do
+ out[i + 1] = buffer.readf32(acc.data, i * 4)
+ end
+ return out
+end
+
+do -- per-corner colours: vertex 0 has two different colours -> split
+ local xml = string.format(HEAD, "inch")
+ .. 'quad & co'
+ .. ''
+ .. ''
+ .. ''
+ local pkg = package(xml)
+ table.insert(samples, pkg)
+ local s, err = decode(pkg)
+ t:check(s, "colours: " .. tostring(err))
+ t:eq(s.meta.unit, 0.0254, "colours: inch")
+ t:eq(s.meta.metadata.Title, "quad & co", "colours: metadata")
+ t:eq(#s.meshes, 1, "colours: one mesh")
+ local prim = s.meshes[1].primitives[1]
+ t:eq(#s.meshes[1].primitives, 1, "colours: one primitive")
+ -- corners: (0,red) (1,green) (2,blue) | (0,blue) (2,blue) (3,blue) -> 5 vertices
+ t:eq(prim.attributes.POSITION.count, 5, "colours: vertex 0 split by colour")
+ local col = f32s(prim.attributes.COLOR_0)
+ t:eq(col[1], 1, "colours: red r (linear)")
+ t:eq(col[2], 0, "colours: red g")
+ t:check(math.abs(col[8] - 128 / 255) < 1e-6, "colours: alpha kept linear")
+ t:eq(s.nodes[1].matrix[13], 10, "colours: transform tx")
+ t:eq(s.nodes[1].matrix[15], 30, "colours: transform tz")
+ -- through our writer and back: the same colours
+ local back = decode((ThreeMf.encode(s)))
+ local col2 = f32s(back.meshes[1].primitives[1].attributes.COLOR_0)
+ local same = #col2 == #col
+ for i = 1, #col do
+ same = same and math.abs(col[i] - col2[i]) < 1e-6
+ end
+ t:check(same, "colours: round trip exact (8-bit sRGB)")
+ t:eq(back.meta.metadata.Title, "quad & co", "colours: metadata round trip")
+ t:eq(back.meta.source.unit, "inch", "colours: unit round trip")
+end
+
+do -- base materials, object defaults, composite, multiproperties, textures
+ local png = "\137PNG\r\n\26\nfake"
+ local xml = string.format(HEAD, "millimeter") .. ""
+ .. ''
+ .. ''
+ .. ''
+ .. ''
+ .. ''
+ .. '"
+ local pkg = package(xml, { ["3D/Texture/a.png"] = png })
+ table.insert(samples, pkg)
+ local s, err = decode(pkg)
+ t:check(s, "materials: " .. tostring(err))
+ local prims = s.meshes[1].primitives
+ t:eq(#prims, 4, "materials: red, texture, composite, half (multi shares half)")
+ local red = s.materials[prims[1].material]
+ t:eq(red.name, "red", "materials: object default pid / pindex")
+ t:eq(red.baseColor[1], 1, "materials: red")
+ t:eq(red.extras["3mf"].displaycolor, "#FF0000", "materials: display colour kept")
+ local tex = s.materials[prims[2].material]
+ t:check(tex.baseColorTexture and s.textures[tex.baseColorTexture.texture], "materials: texture material")
+ local tx = s.textures[tex.baseColorTexture.texture]
+ t:eq(buffer.tostring(tx.data), png, "materials: texture bytes from the package")
+ t:eq(tx.mime, "image/png", "materials: texture mime")
+ t:eq(tx.sampler.wrapS, "clamp", "materials: tilestyleu")
+ t:eq(tx.sampler.wrapT, "mirror", "materials: tilestylev")
+ t:eq(tx.sampler.filter, "nearest", "materials: filter")
+ local uv = f32s(prims[2].attributes.TEXCOORD_0)
+ t:eq(uv[4], 0.75, "materials: v flipped to the top-left origin")
+ local comp = s.materials[prims[3].material]
+ local half = (128 / 255 + 0.055) / 1.055
+ t:check(math.abs(comp.baseColor[1] - (((1 + 128 / 255) / 2 + 0.055) / 1.055) ^ 2.4) < 1e-6, "materials: composite blends in sRGB")
+ t:eq(s.materials[prims[4].material].name, "half", "materials: multiproperties -> first layer")
+ t:eq(prims[4].indices.count, 6, "materials: multi and base 'half' share a primitive")
+ t:check(math.abs(s.materials[prims[4].material].baseColor[1] - half ^ 2.4) < 1e-6, "materials: sRGB -> linear")
+ -- round trip: texture + materials survive
+ local out = assert(ThreeMf.encode(s))
+ local back = assert(decode(out))
+ local tm = nil
+ for _, m in back.materials do
+ if m.baseColorTexture then
+ tm = m
+ end
+ end
+ t:check(tm and buffer.tostring(back.textures[tm.baseColorTexture.texture].data) == png, "materials: texture round trip")
+ t:eq(back.textures[1].sampler.wrapS, "clamp", "materials: sampler round trip")
+ local _, a1 = metrics(s)
+ local _, a2 = metrics(back)
+ t:check(near(a1, a2, 1e-6), "materials: area round trip")
+ local names = {}
+ for _, m in back.materials do
+ if m.name then
+ names[m.name] = true
+ end
+ end
+ t:check(names.red and names.half, "materials: base names round trip")
+end
+
+do -- components, another model part through p:path, nested transforms
+ local part = string.format(HEAD, "millimeter") .. ""
+ local xml = string.format(HEAD, "centimeter") .. ""
+ .. '"
+ .. ''
+ .. ''
+ local pkg = package(xml, { ["3D/other.model"] = part })
+ table.insert(samples, pkg)
+ local s, err = decode(pkg)
+ t:check(s, "components: " .. tostring(err))
+ t:eq(#s.roots, 2, "components: two build items")
+ t:eq(#s.meshes, 2, "components: meshes shared between instances")
+ t:eq(s.nodes[s.roots[1]].name, "group", "components: node names")
+ t:eq(#s.nodes[s.roots[1]].children, 2, "components: children")
+ local tris, area, lo, hi = metrics(s)
+ t:eq(tris, 6, "components: world triangles")
+ t:check(near(area, 2 * (2 + 1), 1e-9), "components: world area")
+ t:check(lo[1] == 0 and hi[1] == 6 and hi[3] == 1, "components: nested transforms")
+ t:eq(s.meta.unit, 0.01, "components: centimetre")
+ -- the writer flattens the hierarchy into build items
+ local back = assert(decode((ThreeMf.encode(s))))
+ local tris2, area2, lo2, hi2 = metrics(back)
+ t:eq(tris2, 6, "components: flattened round trip triangles")
+ t:check(near(area2, area, 1e-9) and lo2[1] == 0 and hi2[1] == 6 and hi2[3] == 1, "components: flattened round trip bounds")
+ t:eq(back.meta.source.unit, "centimeter", "components: unit round trip")
+ -- a unit 3MF lacks: scaled into millimetres
+ s.meta.unit = 0.5
+ local scaled = assert(decode((ThreeMf.encode(s))))
+ local _, _, _, hi3 = metrics(scaled)
+ t:eq(scaled.meta.source.unit, "millimeter", "units: millimetres when the scene's unit is not a 3MF unit")
+ t:check(math.abs(hi3[1] - 3000) < 1e-3, "units: positions scaled through the build transforms")
+ t:check(select(2, ThreeMf.encode(s, { unit = "parsec" :: any })).code == Err.ARG, "units: bad opts.unit")
+end
+
+do -- a Scene built by hand: strips, fans, polygons, vertex colours + texture coordinates, an unplaced mesh
+ local s = Types.Scene.new()
+ local pos = Types.Scene.accessor(nil, "f32", 3, 4)
+ for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do
+ buffer.writef32(pos.data, (i - 1) * 4, v)
+ end
+ local faces = Types.Scene.accessor(nil, "u32", 1, 1)
+ buffer.writeu32(faces.data, 0, 4)
+ local col = Types.Scene.accessor(nil, "unorm8", 3, 4)
+ buffer.fill(col.data, 0, 255)
+ s.meshes = {
+ { primitives = { { attributes = { POSITION = pos }, mode = "triangle_strip" }, { attributes = { POSITION = pos }, mode = "triangle_fan", material = 1 } } },
+ { primitives = { { attributes = { POSITION = pos, COLOR_0 = col }, mode = "polygons", faces = faces }, { attributes = { POSITION = pos }, mode = "points" } } },
+ }
+ s.materials = { Types.Scene.material("m") }
+ s.nodes = { { children = { 2 }, mesh = 1, translation = { 0, 0, 5 } }, { children = {}, mesh = 2, scale = { 2, 2, 2 } } }
+ s.roots = { 1 }
+ local out, err = ThreeMf.encode(s, { level = 0 })
+ t:check(out, "scene: encode " .. tostring(err))
+ table.insert(samples, out)
+ local back = assert(decode(out))
+ local tris, area, _, hi = metrics(back)
+ t:eq(tris, 6, "scene: strip + fan + polygon triangles (points skipped)")
+ t:check(near(area, 2 + 4, 1e-9), "scene: area with node transforms")
+ t:eq(hi[3], 5, "scene: parent translation applied to the child")
+ t:eq(#back.roots, 2, "scene: one build item per placed mesh")
+ local m2 = back.meshes[back.nodes[back.roots[2]].mesh]
+ t:check(m2.primitives[1].attributes.COLOR_0 ~= nil, "scene: vertex colours as a colour group")
+ t:check(select(2, ThreeMf.encode({} :: any)).code == Err.ARG, "encode: not a scene")
+end
+
+-- ------------------------------------------------------------------------------------------------ errors
+do
+ local _, e1 = decode("not a zip at all")
+ t:check(e1 and e1.code ~= nil, "errors: not a zip")
+ local w = Zip.writer()
+ w:add("hello.txt", "hi")
+ local _, e2 = decode((w:finish()))
+ t:eq(e2 and e2.code, Err.CORRUPT, "errors: no model part")
+ local bad = string.format(HEAD, "millimeter") .. '"
+ local _, e3 = decode(package(bad))
+ t:eq(e3 and e3.code, Err.CORRUPT, "errors: vertex index out of range")
+ local cyc = string.format(HEAD, "millimeter") .. ''
+ local _, e4 = decode(package(cyc))
+ t:eq(e4 and e4.code, Err.CORRUPT, "errors: component cycle")
+ local _, e5 = decode(package(string.format(HEAD, "millimeter") .. ""))
+ t:eq(e5 and e5.code, Err.CORRUPT, "errors: build item without an object")
+ local _, e6 = decode(package(string.format(HEAD, "millimeter") .. '"), { maxVertices = 2 })
+ t:eq(e6 and e6.code, Err.LIMIT, "errors: maxVertices")
+ table.insert(samples, package(bad))
+ table.insert(samples, package(cyc))
+ -- sniff
+ t:eq(ThreeMf.sniff(Bytes.reader(package(bad))), 0.95, "sniff: a 3MF package")
+ t:eq(ThreeMf.sniff(Bytes.reader((w:finish()))), 0, "sniff: another zip")
+ t:eq(ThreeMf.sniff(Bytes.reader(buffer.fromstring("solid x"))), 0, "sniff: not a zip")
+end
+
+-- ------------------------------------------------------------------------------------------------ fuzz
+do
+ for _, c in Cases do
+ if #c.data < 20000 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ local s = ThreeMf.decode(Bytes.reader(b))
+ if s then
+ ThreeMf.encode(s)
+ end
+ return s
+ end, samples, { mutations = 12 })
+end
+
+t:done()
diff --git a/tools/bench.luau b/tools/bench.luau
index 686cd01..57a004c 100644
--- a/tools/bench.luau
+++ b/tools/bench.luau
@@ -466,6 +466,14 @@ do
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
+ local ThreeMf = require("@formats/model/3mf")
+ local tmf = assert(ThreeMf.encode(scene))
+ bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
+ ThreeMf.decode(Bytes.reader(tmf))
+ end)
+ bench("3mf encode", 2, buffer.len(tmf), function()
+ ThreeMf.encode(scene)
+ end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
diff --git a/tools/fixtures/3mf.py b/tools/fixtures/3mf.py
new file mode 100644
index 0000000..d763398
--- /dev/null
+++ b/tools/fixtures/3mf.py
@@ -0,0 +1,111 @@
+# 3MF fixtures (tools/fixtures.py): the lib3mf test suite and SDK example files (nixpkgs#lib3mf.src, read only, never
+# committed: core, materials (base / colour / texture / composite / multiproperties), production parts, metadata,
+# units, thumbnails, files lib3mf rejects), assimp's box.3mf (nixpkgs#assimp.src), and files written by assimp's and
+# trimesh's 3MF exporters, with reference values from lib3mf 2.5 (tools/fixtures/_3mf_reference.py: world-space
+# triangles / area / bounds through build items and components, mesh object sizes, material group counts, unit),
+# assimp (`assimp info -r`) and trimesh (area, faces).
+# tests/gen/3mf_cases.luau { name, data, lib3mf = {...} | { failed }, assimp, trimesh }
+# tests/gen/3mf_xcheck.luau our encoder's output for every case (tools/fixtures/_3mf_encode.luau) read back by
+# lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh }
+import importlib.util, json, os, subprocess, sys
+
+INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/Xml", "src/Formats/containers/Zip",
+ "tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"]
+MAX_SIZE = 500_000
+
+
+def ref_module(ctx):
+ spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
+ m = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(m)
+ return m
+
+
+def store(attr):
+ out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + attr], check=True, capture_output=True)
+ return out.stdout.decode().strip().split("\n")[-1]
+
+
+def lib3mf(ctx, paths):
+ src, lib = store("lib3mf.src"), store("lib3mf")
+ res = subprocess.run([sys.executable, "-I", os.path.join(ctx.root, "tools", "fixtures", "_3mf_reference.py"),
+ os.path.join(src, "Autogenerated", "Bindings", "Python"), os.path.join(lib, "lib", "lib3mf")],
+ input=json.dumps(paths).encode(), capture_output=True, check=True)
+ return json.loads(res.stdout)
+
+
+TRIMESH_EXPORT = r"""
+import sys, trimesh
+m = trimesh.creation.icosphere(subdivisions=2, radius=10.0)
+b = trimesh.creation.box(extents=(4, 6, 8))
+b.apply_translation((20, 0, 0))
+s = trimesh.Scene([m, b])
+open(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdout", "wb").write(s.export(file_type="3mf"))
+"""
+
+
+def ply_torus(R=20.0, r=5.0, a=24, b=12):
+ import math
+ vs, fs = [], []
+ for i in range(a):
+ for j in range(b):
+ u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
+ vs.append(((R + r * math.cos(v)) * math.cos(u), (R + r * math.cos(v)) * math.sin(u), r * math.sin(v)))
+ for i in range(a):
+ for j in range(b):
+ p, q = i * b + j, ((i + 1) % a) * b + j
+ p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
+ fs.append((p, q2, p2))
+ fs.append((p, q, q2))
+ head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
+ return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
+
+
+def generate(ctx):
+ M = ref_module(ctx)
+ src = store("lib3mf.src")
+ files = []
+ for base in ("Tests/TestFiles", "SDK/Examples/Files"):
+ for d, _, fs in sorted(os.walk(os.path.join(src, base))):
+ for f in sorted(fs):
+ p = os.path.join(d, f)
+ if f.endswith(".3mf") and os.path.getsize(p) <= MAX_SIZE:
+ files.append(("lib3mf/" + os.path.relpath(p, os.path.join(src, base)), p))
+ files.append(("assimp/box.3mf", os.path.join(store("assimp.src"), "test", "models", "3MF", "box.3mf")))
+ tmp = M.tempdir()
+ ply = os.path.join(tmp, "torus.ply")
+ with open(ply, "wb") as f:
+ f.write(ply_torus())
+ out = os.path.join(tmp, "torus_assimp.3mf")
+ ctx.nix(["assimp"], ["assimp", "export", ply, out, "-f3mf"])
+ files.append(("assimp/torus_export.3mf", out))
+ tm = ctx.python(["trimesh", "numpy", "networkx", "lxml"], TRIMESH_EXPORT)
+ out = os.path.join(tmp, "trimesh_export.3mf")
+ with open(out, "wb") as f:
+ f.write(tm)
+ files.append(("trimesh/export.3mf", out))
+
+ paths = [p for _, p in files]
+ refs = lib3mf(ctx, paths)
+ infos = M.assimp_info(ctx, paths, raw=True)
+ tms = M.trimesh_metrics(ctx, paths)
+ cases = []
+ for (name, p), r, a, t in zip(files, refs, infos, tms):
+ cases.append({"name": name, "data": open(p, "rb").read(), "lib3mf": r, "assimp": a, "trimesh": t})
+ ctx.emit("3mf_cases", cases)
+
+ # the reference tools read our output
+ ours = M.luau_encode(ctx, "tools/fixtures/_3mf_encode.luau")
+ xtmp = M.tempdir()
+ names = sorted(ours, key=lambda n: int(n.split("_")[1].split(".")[0]))
+ xp = []
+ for n in names:
+ p = os.path.join(xtmp, n)
+ with open(p, "wb") as f:
+ f.write(ours[n])
+ xp.append(p)
+ xr = lib3mf(ctx, xp)
+ xi = M.assimp_info(ctx, xp, raw=True)
+ xt = M.trimesh_metrics(ctx, xp)
+ ctx.emit("3mf_xcheck", [{"name": n, "case": int(n.split("_")[1].split(".")[0]), "lib3mf": r, "assimp": a, "trimesh": t}
+ for n, r, a, t in zip(names, xr, xi, xt)])
diff --git a/tools/fixtures/_3mf_encode.luau b/tools/fixtures/_3mf_encode.luau
new file mode 100644
index 0000000..a31f85a
--- /dev/null
+++ b/tools/fixtures/_3mf_encode.luau
@@ -0,0 +1,28 @@
+-- tools/fixtures/_3mf_encode: run by tools/fixtures/3mf.py (luau CLI, repo root): decodes every 3MF case that lib3mf
+-- reads with our reader and encodes it with our writer, printing "rt_.3mf\t" lines for the reference tools
+-- (lib3mf, assimp, trimesh) to read back.
+local ThreeMf = require("@formats/model/3mf")
+local Bytes = require("@formats/core/Bytes")
+local Cases = require("@tests/gen/3mf_cases")
+
+local HEX = {}
+for i = 0, 255 do
+ HEX[i] = string.format("%02x", i)
+end
+local function hex(s: string): string
+ local out = table.create(#s)
+ for i = 1, #s do
+ out[i] = HEX[string.byte(s, i)]
+ end
+ return table.concat(out)
+end
+
+for i, c in Cases do
+ if not c.lib3mf.failed then
+ local scene = ThreeMf.decode(Bytes.reader(buffer.fromstring(c.data)))
+ if scene then
+ local out = assert(ThreeMf.encode(scene))
+ print(string.format("rt_%d.3mf\t%s", i, hex(buffer.tostring(out))))
+ end
+ end
+end
diff --git a/tools/fixtures/_3mf_reference.py b/tools/fixtures/_3mf_reference.py
new file mode 100644
index 0000000..f87d7d6
--- /dev/null
+++ b/tools/fixtures/_3mf_reference.py
@@ -0,0 +1,115 @@
+# 3MF reference values through lib3mf's Python binding (ctypes over lib3mf.so; both from nixpkgs), run by 3mf.py as
+# `python3 -I _3mf_reference.py < paths.json` -> JSON list, one entry per file:
+# { unit, items, meshObjects = [ [vertices, triangles] ... sorted ], triangles, area, min, max (world space, every
+# build item through its components), baseGroups, colorGroups, textures, texGroups } or { failed = message }
+import json, math, sys
+
+sys.path.insert(0, sys.argv[1])
+import Lib3MF # noqa: E402
+
+W = Lib3MF.Wrapper(sys.argv[2])
+UNITS = {0: "micron", 1: "millimeter", 2: "centimeter", 3: "inch", 4: "foot", 5: "meter"}
+
+
+def mat(t):
+ f = t.Fields
+ return [[f[r][c] for c in range(3)] for r in range(4)]
+
+
+def mul(a, b): # row-vector 4x3 affine: p * a * b
+ out = []
+ for r in range(4):
+ row = []
+ for c in range(3):
+ s = sum(a[r][k] * b[k][c] for k in range(3))
+ if r == 3:
+ s += b[3][c]
+ row.append(s)
+ out.append(row)
+ return out
+
+
+IDENT = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]
+
+
+def count(it):
+ n = 0
+ while it.MoveNext():
+ n += 1
+ return n
+
+
+def info(path):
+ model = W.CreateModel()
+ reader = model.QueryReader("3mf")
+ reader.SetStrictModeActive(False)
+ reader.ReadFromFile(path)
+ res = {"unit": UNITS.get(model.GetUnit().value if hasattr(model.GetUnit(), "value") else model.GetUnit(), "?")}
+ meshes = []
+ it = model.GetMeshObjects()
+ while it.MoveNext():
+ m = it.GetCurrentMeshObject()
+ meshes.append([m.GetVertexCount(), m.GetTriangleCount()])
+ res["meshObjects"] = sorted(meshes)
+ tot = {"tri": 0, "area": 0.0, "min": [math.inf] * 3, "max": [-math.inf] * 3}
+
+ def place(rid, M, depth):
+ if depth > 32:
+ return
+ try:
+ mo = model.GetMeshObjectByID(rid)
+ except Exception:
+ mo = None
+ if mo is not None:
+ verts = mo.GetVertices()
+ tris = mo.GetTriangleIndices()
+ P = []
+ for v in verts:
+ x, y, z = v.Coordinates[0], v.Coordinates[1], v.Coordinates[2]
+ P.append([x * M[0][c] + y * M[1][c] + z * M[2][c] + M[3][c] for c in range(3)])
+ for p in P:
+ for c in range(3):
+ tot["min"][c] = min(tot["min"][c], p[c])
+ tot["max"][c] = max(tot["max"][c], p[c])
+ for t in tris:
+ a, b, c = (P[i] for i in t.Indices)
+ e1 = [b[k] - a[k] for k in range(3)]
+ e2 = [c[k] - a[k] for k in range(3)]
+ cx = e1[1] * e2[2] - e1[2] * e2[1]
+ cy = e1[2] * e2[0] - e1[0] * e2[2]
+ cz = e1[0] * e2[1] - e1[1] * e2[0]
+ tot["area"] += math.sqrt(cx * cx + cy * cy + cz * cz) / 2
+ tot["tri"] += 1
+ return
+ co = model.GetComponentsObjectByID(rid)
+ for i in range(co.GetComponentCount()):
+ comp = co.GetComponent(i)
+ T = mat(comp.GetTransform()) if comp.HasTransform() else IDENT
+ place(comp.GetObjectResourceID(), mul(T, M), depth + 1)
+
+ items = model.GetBuildItems()
+ n = 0
+ while items.MoveNext():
+ bi = items.GetCurrent()
+ n += 1
+ T = mat(bi.GetObjectTransform()) if bi.HasObjectTransform() else IDENT
+ place(bi.GetObjectResourceID(), T, 0)
+ res["items"] = n
+ res["triangles"] = tot["tri"]
+ res["area"] = tot["area"]
+ if tot["tri"]:
+ res["min"], res["max"] = tot["min"], tot["max"]
+ res["baseGroups"] = count(model.GetBaseMaterialGroups())
+ res["colorGroups"] = count(model.GetColorGroups())
+ res["textures"] = count(model.GetTexture2Ds())
+ res["texGroups"] = count(model.GetTexture2DGroups())
+ return res
+
+
+out = []
+for p in json.loads(sys.stdin.read()):
+ try:
+ out.append(info(p))
+ except Exception as e: # noqa: BLE001
+ out.append({"failed": str(e)[:200]})
+print(json.dumps(out))