418 lines
14 KiB
Luau
418 lines
14 KiB
Luau
--!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<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\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<vertex x="%s" y="%s" z="%s" />\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<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) }
|
|
for v = 0, n - 1 do
|
|
table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1))))
|
|
end
|
|
table.insert(parts, "\t\t</m:texture2dgroup>\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<m:colorgroup id="%d">\n', pid) }
|
|
local four = col.components >= 4
|
|
for v = 0, n - 1 do
|
|
table.insert(parts, fmt('\t\t\t<m:color color="%s" />\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</m:colorgroup>\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<triangle v1="%d" v2="%d" v3="%d" />\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<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5]))
|
|
else
|
|
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\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<object id="%d" type="model"', oid)
|
|
if mesh.name then
|
|
head ..= fmt(' name="%s"', esc(mesh.name))
|
|
end
|
|
if objPid then
|
|
head ..= fmt(' pid="%d" pindex="%d"', objPid, objP :: number)
|
|
end
|
|
table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\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<basematerials id="%d">\n', baseId) }
|
|
for _, m in scene.materials do
|
|
local c = m.baseColor or { 1, 1, 1, 1 }
|
|
table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\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<base name="default" displaycolor="#FFFFFFFF" />\n')
|
|
end
|
|
table.insert(parts, "\t\t</basematerials>\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<item objectid="%d" />\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<item objectid="%d" transform="%s" />\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<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k]))))
|
|
end
|
|
end
|
|
|
|
local model = table.concat({
|
|
'<?xml version="1.0" encoding="UTF-8"?>\n',
|
|
'<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n',
|
|
table.concat(meta),
|
|
"\t<resources>\n",
|
|
table.concat(res),
|
|
"\t</resources>\n\t<build>\n",
|
|
table.concat(items),
|
|
"\t</build>\n</model>\n",
|
|
})
|
|
|
|
local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n',
|
|
'\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n',
|
|
'\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\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<Default Extension="%s" ContentType="%s" />\n', e, f.mime))
|
|
end
|
|
end
|
|
table.insert(types, "</Types>\n")
|
|
local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n'
|
|
.. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL)
|
|
.. "</Relationships>\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 = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' }
|
|
for i, f in files do
|
|
table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE))
|
|
end
|
|
table.insert(mr, "</Relationships>\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
|