diff --git a/compat/luajit.lua b/compat/luajit.lua
index c5b1813..72cb133 100644
--- a/compat/luajit.lua
+++ b/compat/luajit.lua
@@ -404,13 +404,28 @@ do
end
-- ---------------------------------------------------------------------------------------------------- __iter
+local function arrayIter(s, i)
+ local t, n = s[1], s[2]
+ i = i + 1
+ local v = t[i]
+ while v == nil and i < n do
+ i = i + 1
+ v = t[i]
+ end
+ if v ~= nil then return i, v end
+end
function M.__iter(t, s, c)
if rawtype(t) == "function" then return t, s, c end
if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end
local mt = getmetatable(t)
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
local n = #t
- if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part
+ -- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part;
+ -- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps
+ -- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau.
+ if n > 0 and t[0] == nil and next(t, n) == nil then
+ return arrayIter, { t, n }, 0
+ end
return next, t, nil
end
diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index 5328084..9cdec7e 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -34,12 +34,17 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` |
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` |
| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` |
+| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
+| 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 | 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` |
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
+| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
+| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index 0866b80..22ebd2b 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -362,6 +362,42 @@ local list: { Entry } = {
return require("@formats/video/y4m")
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 = "dae",
+ category = "model",
+ path = "model/dae",
+ extensions = { "dae", "zae" },
+ mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" },
+ caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
+ load = function()
+ return require("@formats/model/dae")
+ end,
+ },
+ {
+ name = "fbx",
+ category = "model",
+ path = "model/fbx",
+ extensions = { "fbx" },
+ mime = { "application/vnd.autodesk.fbx", "model/fbx" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
+ caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
+ load = function()
+ return require("@formats/model/fbx")
+ end,
+ },
{
name = "gltf",
category = "model",
@@ -422,6 +458,18 @@ local list: { Entry } = {
return require("@formats/model/stl")
end,
},
+ {
+ name = "usda",
+ category = "model",
+ path = "model/usda",
+ extensions = { "usda", "usd", "usdz" },
+ mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
+ deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
+ caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
+ load = function()
+ return require("@formats/model/usda")
+ end,
+ },
{
name = "vox",
category = "model",
@@ -434,6 +482,18 @@ local list: { Entry } = {
return require("@formats/model/vox")
end,
},
+ {
+ name = "step",
+ category = "cad",
+ path = "cad/step",
+ extensions = { "step", "stp", "p21" },
+ mime = { "model/step", "application/step", "application/p21" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
+ load = function()
+ return require("@formats/cad/step")
+ end,
+ },
{
name = "bmfont",
category = "font",
diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau
index 7914957..f34b569 100644
--- a/src/Formats/Types.luau
+++ b/src/Formats/Types.luau
@@ -614,7 +614,9 @@ end
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
-export type StepEntity = { id: number, type: string, args: { any } }
+-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order;
+-- section = the DATA section index when a file has more than one (edition 3)
+export type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? }
export type Cad = {
kind: "cad",
schema: string, -- "AP203", "AP214", "AP242", ...
diff --git a/src/Formats/cad/step/Brep.luau b/src/Formats/cad/step/Brep.luau
new file mode 100644
index 0000000..2d44ef7
--- /dev/null
+++ b/src/Formats/cad/step/Brep.luau
@@ -0,0 +1,248 @@
+--!strict
+-- cad/step/Brep: the injected B-rep plug-in (Formats.plugins.brep; formats-luau never requires a kernel). Normalises
+-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a
+-- Scene. Interpreted on purpose: the plug-in's errors unwind through here.
+--
+-- The interface (every function may throw; results are checked):
+-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?,
+-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 })
+-- write(bodies: { Body }, opts) -> string bodies -> STEP text
+-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based
+-- triples }, faceOf = { [triangle] = Face (face.color?) }? }
+-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read =
+-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body).
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+
+local Brep = {}
+
+export type Plugin = {
+ read: (text: string, opts: any) -> any,
+ write: ((bodies: { any }, opts: any) -> string)?,
+ tessellate: ((body: any, opts: any) -> any)?,
+}
+
+local function rgbOf(c: any): (number?, number?, number?)
+ if c == nil then
+ return nil, nil, nil
+ end
+ local ok, r, g, b = pcall(function(): (any, any, any)
+ if type(c) == "table" then
+ return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3]
+ end
+ return (c :: any).R, (c :: any).G, (c :: any).B -- Color3
+ end)
+ if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then
+ return r, g, b
+ end
+ return nil, nil, nil
+end
+
+-- plugin(p) -> the normalised interface, or nil + the reason
+function Brep.plugin(p: any): (Plugin?, string?)
+ if type(p) ~= "table" then
+ return nil, "needs the B-rep plug-in (Formats.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })"
+ end
+ if type(p.read) == "function" then
+ return {
+ read = p.read,
+ write = if type(p.write) == "function" then p.write else nil,
+ tessellate = if type(p.tessellate) == "function" then p.tessellate else nil,
+ }, nil
+ end
+ local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess
+ if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then
+ return {
+ read = function(text: string, opts: any): any
+ return SB.read(S.parse(text), opts)
+ end,
+ write = if type(SW) == "table" and type(SW.write) == "function"
+ then function(bodies: { any }, opts: any): string
+ local o = if type(opts) == "table" then table.clone(opts) else {}
+ if o.colors == nil then
+ local colors = {}
+ for i, b in bodies do
+ local r, g, bl = rgbOf(type(b) == "table" and b.color or nil)
+ if r then
+ colors[i] = { r, g, bl }
+ end
+ end
+ o.colors = colors
+ end
+ return SW.write(bodies, o)
+ end
+ else nil,
+ tessellate = if type(Tess) == "table" and type(Tess.body) == "function"
+ then function(body: any, opts: any): any
+ return Tess.body(body, opts)
+ end
+ else nil,
+ }, nil
+ end
+ return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules"
+end
+
+-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep
+function Brep.find(opts: any): (Plugin?, Err.Err?)
+ local p = nil
+ if type(opts) == "table" then
+ p = opts.brep
+ if p == nil and type(opts.plugins) == "table" then
+ p = opts.plugins.brep
+ end
+ end
+ local plug, why = Brep.plugin(p)
+ if not plug then
+ return nil, Err.new(Err.UNSUPPORTED, why :: string)
+ end
+ return plug, nil
+end
+
+-- read(plug, text, opts) -> bodies, result | nil, Err
+function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?)
+ local ok, res = pcall(plug.read, text, opts)
+ if not ok then
+ return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res))
+ end
+ if type(res) ~= "table" or type(res.bodies) ~= "table" then
+ return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies")
+ end
+ return res.bodies, res, nil
+end
+
+-- write(plug, bodies, opts) -> text | nil, Err
+function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?)
+ local w = plug.write
+ if not w then
+ return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()")
+ end
+ local ok, res = pcall(w, bodies, opts)
+ if not ok then
+ return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res))
+ end
+ if type(res) ~= "string" then
+ return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text")
+ end
+ return res, nil
+end
+
+local function xyz(p: any): (number, number, number)
+ if type(p) == "table" then
+ return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0
+ end
+ return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3
+end
+
+local function linear(c: number): number
+ c = math.clamp(c, 0, 1)
+ return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4
+end
+
+-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by
+-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written)
+function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?)
+ local tess = plug.tessellate
+ if not tess then
+ return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()")
+ end
+ local scene = Types.Scene.new()
+ scene.meta.up = "z"
+ scene.meta.unit = 0.001
+ local tessOpts = if type(opts) == "table" and type(opts.tess) == "table"
+ then opts.tess
+ else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 }
+ local matByKey: { [string]: number } = {}
+ local function material(r: number?, g: number?, b: number?): number
+ local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default"
+ local m = matByKey[key]
+ if m then
+ return m
+ end
+ local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default")
+ if r then
+ mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 }
+ mat.extras = { color = { r, g, b } }
+ else
+ mat.baseColor = { 0.6, 0.6, 0.6, 1 }
+ end
+ mat.metallic, mat.roughness = 0, 0.5
+ table.insert(scene.materials, mat)
+ matByKey[key] = #scene.materials
+ return #scene.materials
+ end
+ for bi, body in bodies do
+ local ok, mesh = pcall(tess, body, tessOpts)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh))
+ end
+ if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then
+ return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh")
+ end
+ local cok, prims = pcall(function(): { Types.Primitive }
+ local P, N, I = mesh.positions, mesh.normals, mesh.indices
+ local nv = #P
+ local pos = Types.Scene.accessor(nil, "f32", 3, nv)
+ local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil
+ for i = 1, nv do
+ local x, y, z = xyz(P[i])
+ buffer.writef32(pos.data, (i - 1) * 12, x)
+ buffer.writef32(pos.data, (i - 1) * 12 + 4, y)
+ buffer.writef32(pos.data, (i - 1) * 12 + 8, z)
+ if nrm then
+ local a, b, c = xyz(N[i])
+ buffer.writef32(nrm.data, (i - 1) * 12, a)
+ buffer.writef32(nrm.data, (i - 1) * 12 + 4, b)
+ buffer.writef32(nrm.data, (i - 1) * 12 + 8, c)
+ end
+ end
+ local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil)
+ -- triangles grouped by colour, in first-seen order
+ local groups: { { mat: number, tris: { number } } } = {}
+ local byMat: { [number]: { mat: number, tris: { number } } } = {}
+ local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {}
+ local nt = #I // 3
+ for t = 1, nt do
+ local f = faceOf[t]
+ local r, g, b = rgbOf(type(f) == "table" and f.color or nil)
+ if not r then
+ r, g, b = br, bg, bb
+ end
+ local m = material(r, g, b)
+ local grp = byMat[m]
+ if not grp then
+ grp = { mat = m, tris = {} }
+ byMat[m] = grp
+ table.insert(groups, grp)
+ end
+ table.insert(grp.tris, t)
+ end
+ local out: { Types.Primitive } = {}
+ for _, grp in groups do
+ local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3)
+ for k, t in grp.tris do
+ for c = 0, 2 do
+ local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1
+ buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0)))
+ end
+ end
+ local attrs: { [string]: Types.Accessor } = { POSITION = pos }
+ if nrm then
+ attrs.NORMAL = nrm
+ end
+ table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat })
+ end
+ return out
+ end)
+ if not cok then
+ return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims))
+ end
+ local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi
+ table.insert(scene.meshes, { name = name, primitives = prims })
+ table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes })
+ table.insert(scene.roots, #scene.nodes)
+ end
+ scene.meta.source = { format = "step", tessellated = true, bodies = #bodies }
+ return scene, nil
+end
+
+return Brep
diff --git a/src/Formats/cad/step/Parse.luau b/src/Formats/cad/step/Parse.luau
new file mode 100644
index 0000000..1a86bf3
--- /dev/null
+++ b/src/Formats/cad/step/Parse.luau
@@ -0,0 +1,573 @@
+--!strict
+--!native
+-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass
+-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`),
+-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every
+-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary,
+-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset.
+--
+-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v };
+-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`)
+-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so
+-- the writer prints it back as a real; integral numbers without that mark are written as integers.
+local Parse = {}
+
+local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor
+
+local MAX_DEPTH = 100
+
+export type Ctx = {
+ s: string,
+ n: number,
+ err: string?,
+ errAt: number?,
+ null: any,
+ derived: any,
+}
+
+local function fail(ctx: Ctx, msg: string, at: number): nil
+ if not ctx.err then
+ ctx.err, ctx.errAt = msg, at
+ end
+ return nil
+end
+
+-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error)
+local function skip(ctx: Ctx, i: number): number
+ local s, n = ctx.s, ctx.n
+ while i <= n do
+ local c = sbyte(s, i)
+ if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then
+ i += 1
+ elseif c == 47 and sbyte(s, i + 1) == 42 then
+ local _, e = sfind(s, "*/", i + 2, true)
+ if not e then
+ fail(ctx, "unterminated comment", i)
+ return n + 1
+ end
+ i = e + 1
+ else
+ return i
+ end
+ end
+ return i
+end
+
+local function isAlpha(c: number): boolean
+ return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
+end
+local function isWord(c: number): boolean
+ return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57)
+end
+
+-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none
+local function keyword(ctx: Ctx, i: number): (string?, number)
+ local s, n = ctx.s, ctx.n
+ local j = i
+ if j <= n and sbyte(s, j) == 33 then -- '!' user-defined
+ j += 1
+ end
+ if j > n or not isAlpha(sbyte(s, j) :: number) then
+ return nil, i
+ end
+ j += 1
+ while j <= n and isWord(sbyte(s, j) :: number) do
+ j += 1
+ end
+ return string.upper(ssub(s, i, j - 1)), j
+end
+
+-- UTF-8 of a code point
+local function utf8char(cp: number): string
+ if cp < 0x80 then
+ return schar(cp)
+ elseif cp < 0x800 then
+ return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64)
+ elseif cp < 0x10000 then
+ return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
+ elseif cp < 0x110000 then
+ return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
+ end
+ return "\239\191\189"
+end
+Parse.utf8char = utf8char
+
+local function hexAt(s: string, i: number, k: number): number?
+ local h = ssub(s, i, i + k - 1)
+ if #h ~= k or sfind(h, "[^%x]") then
+ return nil
+ end
+ return tonumber(h, 16)
+end
+
+-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\,
+-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed)
+-- pass through.
+function Parse.unescape(raw: string): string
+ if not sfind(raw, "[\\']") then
+ return raw
+ end
+ local out = {}
+ local i, n = 1, #raw
+ local plain = 1
+ while i <= n do
+ local c = sbyte(raw, i)
+ if c == 39 then -- '' -> '
+ table.insert(out, ssub(raw, plain, i))
+ i += 2
+ plain = i
+ elseif c == 92 then
+ table.insert(out, ssub(raw, plain, i - 1))
+ local d = sbyte(raw, i + 1)
+ if d == 92 then
+ table.insert(out, "\\")
+ i += 2
+ elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c
+ table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256))
+ i += 4
+ elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page
+ i += 4
+ elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh
+ local h = hexAt(raw, i + 3, 2)
+ if h then
+ table.insert(out, utf8char(h))
+ i += 5
+ else
+ table.insert(out, "\\")
+ i += 1
+ end
+ elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then
+ local k = if sbyte(raw, i + 2) == 50 then 4 else 8
+ local j = i + 4
+ local hi: number? = nil
+ while j <= n do
+ if sbyte(raw, j) == 92 then
+ break
+ end
+ local cp = hexAt(raw, j, k)
+ if not cp then
+ break
+ end
+ if k == 4 and cp >= 0xD800 and cp < 0xDC00 then
+ hi = cp
+ elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then
+ table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00)))
+ hi = nil
+ else
+ table.insert(out, utf8char(cp))
+ hi = nil
+ end
+ j += k
+ end
+ if ssub(raw, j, j + 3) == "\\X0\\" then
+ j += 4
+ end
+ i = j
+ else
+ table.insert(out, "\\")
+ i += 1
+ end
+ plain = i
+ else
+ i += 1
+ end
+ end
+ table.insert(out, ssub(raw, plain, n))
+ return table.concat(out)
+end
+
+local function markReal(t: { [any]: any }, key: any)
+ local mt: any = getmetatable(t)
+ if not mt then
+ mt = { __reals = {} }
+ setmetatable(t, mt)
+ end
+ mt.__reals[key] = true
+end
+
+-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure)
+local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean)
+
+local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number)
+ -- i is just past "("
+ local s = ctx.s
+ local out = {}
+ i = skip(ctx, i)
+ if sbyte(s, i) == 41 then
+ return out, i + 1
+ end
+ local k = 0
+ while true do
+ local v, j, intReal = value(ctx, i, depth + 1)
+ if v == nil then
+ return nil, j
+ end
+ k += 1
+ out[k] = v
+ if intReal then
+ markReal(out, k)
+ end
+ j = skip(ctx, j)
+ local c = sbyte(s, j)
+ if c == 44 then
+ i = skip(ctx, j + 1)
+ elseif c == 41 then
+ return out, j + 1
+ elseif c == nil then
+ return fail(ctx, "truncated list", j), j
+ else
+ return fail(ctx, "expected , or ) in a list", j), j
+ end
+ end
+end
+Parse.list = list
+
+value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean)
+ if depth > MAX_DEPTH then
+ return fail(ctx, "lists nested too deeply", i), i, false
+ end
+ local s = ctx.s
+ i = skip(ctx, i)
+ local c = sbyte(s, i)
+ if c == nil then
+ return fail(ctx, "truncated parameter", i), i, false
+ elseif c == 35 then -- #ref
+ local _, e = sfind(s, "^%d+", i + 1)
+ if not e then
+ return fail(ctx, "bad entity reference", i), i, false
+ end
+ return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false
+ elseif c == 39 then -- 'string'
+ local j = i + 1
+ while true do
+ local q = sfind(s, "'", j, true)
+ if not q then
+ return fail(ctx, "unterminated string", i), i, false
+ end
+ if sbyte(s, q + 1) == 39 then
+ j = q + 2
+ else
+ return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false
+ end
+ end
+ elseif c == 36 then
+ return ctx.null, i + 1, false
+ elseif c == 42 then
+ return ctx.derived, i + 1, false
+ elseif c == 40 then
+ local l, j = list(ctx, i + 1, depth)
+ return l, j, false
+ elseif c == 46 then -- .ENUM.
+ local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1)
+ if not e then
+ return fail(ctx, "bad enumeration", i), i, false
+ end
+ return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
+ elseif c == 34 then -- "binary"
+ local _, e = sfind(s, "^[0-3]%x*\"", i + 1)
+ if not e then
+ return fail(ctx, "bad binary literal", i), i, false
+ end
+ return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
+ elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then
+ local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i)
+ local tok = ssub(s, i, e :: number)
+ local num = tonumber(if c == 43 then ssub(tok, 2) else tok)
+ if num == nil then
+ -- "1.E" without digits and the like
+ local core = string.match(tok, "^[+-]?%d*%.?%d*")
+ num = core and tonumber(if c == 43 then ssub(core, 2) else core)
+ if num == nil then
+ return fail(ctx, "bad number", i), i, false
+ end
+ e = i + #(core :: string) - 1
+ end
+ local real = sfind(tok, "[.eE]") ~= nil
+ local nv = num :: number
+ return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv
+ elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value)
+ local word, j = keyword(ctx, i)
+ j = skip(ctx, j)
+ if word == nil or sbyte(s, j) ~= 40 then
+ return fail(ctx, "expected a parameter", i), i, false
+ end
+ local v, k, intReal = value(ctx, j + 1, depth + 1)
+ if v == nil then
+ return nil, k, false
+ end
+ k = skip(ctx, k)
+ if sbyte(s, k) ~= 41 then
+ return fail(ctx, "expected ) after a typed parameter", k), k, false
+ end
+ local t = { typed = word, value = v }
+ if intReal then
+ markReal(t, "value")
+ end
+ return t, k + 1, false
+ end
+ return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false
+end
+Parse.value = value
+
+-- the simple record at i: NAME(params) -> type, args, next
+local function record(ctx: Ctx, i: number): (string?, { any }?, number)
+ local word, j = keyword(ctx, i)
+ if not word then
+ return fail(ctx, "expected an entity name", i), nil, i
+ end
+ j = skip(ctx, j)
+ if sbyte(ctx.s, j) ~= 40 then
+ return fail(ctx, "expected ( after " .. word, j), nil, j
+ end
+ local args, k = list(ctx, j + 1, 0)
+ if not args then
+ return nil, nil, k
+ end
+ return word, args, k
+end
+
+-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
+local function expect(ctx: Ctx, i: number, ch: number, what: string): number?
+ i = skip(ctx, i)
+ if sbyte(ctx.s, i) ~= ch then
+ if i > ctx.n then
+ return fail(ctx, "truncated: expected " .. what, i)
+ end
+ return fail(ctx, "expected " .. what, i)
+ end
+ return i + 1
+end
+
+local function at(s: string, i: number, word: string): boolean
+ return ssub(s, i, i + #word - 1) == word
+end
+
+export type Result = {
+ header: { [string]: { any } },
+ headerOrder: { string },
+ entities: { [number]: any },
+ count: number,
+ sections: { { name: any?, schema: any? } },
+ extra: { { name: string, text: string } },
+ duplicates: number,
+ terminated: boolean,
+}
+
+-- parse(s, opts) -> Result | nil, message, offset (1-based position in s)
+function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?)
+ local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived }
+ local res: Result = {
+ header = {},
+ headerOrder = {},
+ entities = {},
+ count = 0,
+ sections = {},
+ extra = {},
+ duplicates = 0,
+ terminated = false,
+ }
+ local i = skip(ctx, 1)
+ if not at(s, i, "ISO-10303-21") then
+ return nil, "no ISO-10303-21 magic", i
+ end
+ local ni = expect(ctx, i + 12, 59, ";")
+ if not ni then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = ni
+ local sawData = false
+ while true do
+ i = skip(ctx, i)
+ if ctx.err then
+ return nil, ctx.err, ctx.errAt
+ end
+ if i > ctx.n then
+ if not sawData then
+ return nil, "truncated: no DATA section", i
+ end
+ break
+ end
+ if at(s, i, "END-ISO-10303-21") then
+ res.terminated = true
+ local e = expect(ctx, i + 16, 59, ";")
+ if not e then
+ return nil, ctx.err, ctx.errAt
+ end
+ break
+ end
+ local word, j = keyword(ctx, i)
+ if word == "HEADER" then
+ local e = expect(ctx, j, 59, ";")
+ if not e then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = e
+ while true do
+ i = skip(ctx, i)
+ if at(s, i, "ENDSEC") then
+ local e2 = expect(ctx, i + 6, 59, ";")
+ if not e2 then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = e2
+ break
+ end
+ if i > ctx.n then
+ return nil, "truncated header", i
+ end
+ local t, args, k = record(ctx, i)
+ if not t then
+ return nil, ctx.err, ctx.errAt
+ end
+ local e2 = expect(ctx, k, 59, ";")
+ if not e2 then
+ return nil, ctx.err, ctx.errAt
+ end
+ if res.header[t] == nil then
+ table.insert(res.headerOrder, t)
+ end
+ res.header[t] = args :: { any }
+ i = e2
+ end
+ elseif word == "DATA" then
+ sawData = true
+ local sec: { name: any?, schema: any? } = {}
+ j = skip(ctx, j)
+ if sbyte(s, j) == 40 then
+ local params, k = list(ctx, j + 1, 0)
+ if not params then
+ return nil, ctx.err, ctx.errAt
+ end
+ sec.name, sec.schema = params[1], params[2]
+ j = k
+ end
+ table.insert(res.sections, sec)
+ local secIndex = #res.sections
+ local e = expect(ctx, j, 59, ";")
+ if not e then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = e
+ while true do
+ i = skip(ctx, i)
+ if ctx.err then
+ return nil, ctx.err, ctx.errAt
+ end
+ local c = sbyte(s, i)
+ if c == nil then
+ return nil, "truncated: the DATA section has no ENDSEC", i
+ end
+ if c ~= 35 then
+ if at(s, i, "ENDSEC") then
+ local e2 = expect(ctx, i + 6, 59, ";")
+ if not e2 then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = e2
+ break
+ end
+ return nil, "expected an entity instance (#id = ...)", i
+ end
+ local _, idEnd = sfind(s, "^%d+", i + 1)
+ if not idEnd then
+ return nil, "bad entity instance name", i
+ end
+ local id = tonumber(ssub(s, i + 1, idEnd)) :: number
+ local k = expect(ctx, idEnd + 1, 61, "=")
+ if not k then
+ return nil, ctx.err, ctx.errAt
+ end
+ k = skip(ctx, k)
+ local ent: any
+ if sbyte(s, k) == 40 then -- complex instance (A(..) B(..))
+ local parts = {}
+ k = skip(ctx, k + 1)
+ while sbyte(s, k) ~= 41 do
+ if k > ctx.n then
+ return nil, "truncated complex instance", k
+ end
+ local t, args, k2 = record(ctx, k)
+ if not t then
+ return nil, ctx.err, ctx.errAt
+ end
+ table.insert(parts, { type = t, args = args })
+ k = skip(ctx, k2)
+ end
+ if #parts == 0 then
+ return nil, "empty complex instance", k
+ end
+ ent = { id = id, type = "COMPLEX", args = {}, parts = parts }
+ k += 1
+ else
+ local t, args, k2 = record(ctx, k)
+ if not t then
+ return nil, ctx.err, ctx.errAt
+ end
+ ent = { id = id, type = t, args = args }
+ k = k2
+ end
+ local e2 = expect(ctx, k, 59, ";")
+ if not e2 then
+ return nil, ctx.err, ctx.errAt
+ end
+ if secIndex > 1 then
+ ent.section = secIndex
+ end
+ if res.entities[id] then
+ res.duplicates += 1
+ else
+ res.count += 1
+ if res.count > maxEntities then
+ return nil, "LIMIT", i
+ end
+ end
+ res.entities[id] = ent
+ i = e2
+ end
+ elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then
+ -- kept as raw text (to the ENDSEC outside strings)
+ local k = j
+ local stop: number? = nil
+ while k <= ctx.n do
+ local c = sbyte(s, k)
+ if c == 39 then
+ local q = k + 1
+ while true do
+ local p = sfind(s, "'", q, true)
+ if not p then
+ return nil, "unterminated string", k
+ end
+ if sbyte(s, p + 1) == 39 then
+ q = p + 2
+ else
+ k = p + 1
+ break
+ end
+ end
+ elseif c == 69 and at(s, k, "ENDSEC") then
+ stop = k
+ break
+ else
+ k += 1
+ end
+ end
+ if not stop then
+ return nil, "truncated " .. word .. " section", i
+ end
+ table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) })
+ local e2 = expect(ctx, stop + 6, 59, ";")
+ if not e2 then
+ return nil, ctx.err, ctx.errAt
+ end
+ i = e2
+ else
+ return nil, "unknown section " .. tostring(word), i
+ end
+ end
+ if not sawData then
+ return nil, "no DATA section", i
+ end
+ return res, nil, nil
+end
+
+return Parse
diff --git a/src/Formats/cad/step/Write.luau b/src/Formats/cad/step/Write.luau
new file mode 100644
index 0000000..0045126
--- /dev/null
+++ b/src/Formats/cad/step/Write.luau
@@ -0,0 +1,252 @@
+--!strict
+--!native
+-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings
+-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid
+-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws:
+-- failures return nil, message.
+local Write = {}
+
+local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge
+
+local MAX_DEPTH = 100
+
+-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E)
+function Write.real(v: number): string?
+ if v ~= v or v == huge or v == -huge then
+ return nil
+ end
+ local s = sformat("%.15g", v)
+ if tonumber(s) ~= v then
+ s = sformat("%.16g", v)
+ if tonumber(s) ~= v then
+ s = sformat("%.17g", v)
+ end
+ end
+ s = string.upper(s)
+ local e = sfind(s, "E", 1, true)
+ if not sfind(s, ".", 1, true) then
+ if e then
+ s = ssub(s, 1, e - 1) .. "." .. ssub(s, e)
+ else
+ s ..= "."
+ end
+ end
+ return s
+end
+
+local HEX = "0123456789ABCDEF"
+local function hex(v: number, k: number): string
+ local out = table.create(k)
+ for i = k, 1, -1 do
+ local d = v % 16
+ out[i] = ssub(HEX, d + 1, d + 1)
+ v = floor(v / 16)
+ end
+ return table.concat(out)
+end
+
+-- a string's Part 21 literal (with the quotes)
+function Write.str(s: string): string
+ if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \
+ return "'" .. s .. "'"
+ end
+ local out = { "'" }
+ local i, n = 1, #s
+ local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run
+ local function close()
+ if wide then
+ table.insert(out, "\\X0\\")
+ wide = nil
+ end
+ end
+ while i <= n do
+ local c = sbyte(s, i) :: number
+ if c >= 32 and c < 127 then
+ close()
+ if c == 39 then
+ table.insert(out, "''")
+ elseif c == 92 then
+ table.insert(out, "\\\\")
+ else
+ table.insert(out, string.char(c))
+ end
+ i += 1
+ else
+ -- a UTF-8 sequence -> code point
+ local cp: number? = nil
+ local len = 1
+ if c >= 0xC2 and c < 0xE0 then
+ local c2 = sbyte(s, i + 1)
+ if c2 and c2 >= 0x80 and c2 < 0xC0 then
+ cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2
+ end
+ elseif c >= 0xE0 and c < 0xF0 then
+ local c2, c3 = sbyte(s, i + 1, i + 2)
+ if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then
+ local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80)
+ if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then
+ cp, len = v, 3
+ end
+ end
+ elseif c >= 0xF0 and c < 0xF5 then
+ local c2, c3, c4 = sbyte(s, i + 1, i + 3)
+ if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then
+ local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80)
+ if v >= 0x10000 and v < 0x110000 then
+ cp, len = v, 4
+ end
+ end
+ end
+ if cp == nil then
+ close()
+ table.insert(out, "\\X\\" .. hex(c, 2))
+ i += 1
+ else
+ local k = if cp >= 0x10000 then 8 else 4
+ if wide ~= k then
+ close()
+ table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\")
+ wide = k
+ end
+ table.insert(out, hex(cp, k))
+ i += len
+ end
+ end
+ end
+ close()
+ table.insert(out, "'")
+ return table.concat(out)
+end
+
+local function isName(s: any): boolean
+ return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil
+end
+Write.isName = isName
+
+export type Ctx = { out: { string }, null: any, derived: any, err: string? }
+
+local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean
+
+local function reals(t: any): { [any]: boolean }?
+ local mt = getmetatable(t)
+ return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil
+end
+
+local function list(ctx: Ctx, t: { any }, depth: number): boolean
+ local out = ctx.out
+ table.insert(out, "(")
+ local marks = reals(t)
+ local n = #t
+ for i = 1, n do
+ if i > 1 then
+ table.insert(out, ",")
+ end
+ if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then
+ return false
+ end
+ end
+ table.insert(out, ")")
+ return true
+end
+Write.list = list
+
+value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean
+ local out = ctx.out
+ if depth > MAX_DEPTH then
+ ctx.err = "values nested too deeply (or a cycle)"
+ return false
+ end
+ local tv = type(v)
+ if tv == "number" then
+ if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then
+ table.insert(out, sformat("%.0f", v))
+ return true
+ end
+ local r = Write.real(v)
+ if not r then
+ ctx.err = "a number that STEP cannot hold (nan / inf)"
+ return false
+ end
+ table.insert(out, r)
+ return true
+ elseif tv == "string" then
+ table.insert(out, Write.str(v))
+ return true
+ elseif tv == "boolean" then
+ table.insert(out, if v then ".T." else ".F.")
+ return true
+ elseif tv == "table" then
+ if v == ctx.null then
+ table.insert(out, "$")
+ return true
+ elseif v == ctx.derived then
+ table.insert(out, "*")
+ return true
+ end
+ local ref = v.ref
+ if ref ~= nil then
+ if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then
+ ctx.err = "bad entity reference " .. tostring(ref)
+ return false
+ end
+ table.insert(out, sformat("#%.0f", ref))
+ return true
+ end
+ local enum = v.enum
+ if enum ~= nil then
+ if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then
+ ctx.err = "bad enumeration " .. tostring(enum)
+ return false
+ end
+ table.insert(out, "." .. string.upper(enum) .. ".")
+ return true
+ end
+ local bin = v.binary
+ if bin ~= nil then
+ if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then
+ ctx.err = "bad binary literal"
+ return false
+ end
+ table.insert(out, "\"" .. string.upper(bin) .. "\"")
+ return true
+ end
+ local typed = v.typed
+ if typed ~= nil then
+ if not isName(typed) then
+ ctx.err = "bad typed parameter name " .. tostring(typed)
+ return false
+ end
+ if v.value == nil then
+ ctx.err = "typed parameter " .. typed .. " without a value"
+ return false
+ end
+ local marks = reals(v)
+ table.insert(out, string.upper(typed) .. "(")
+ if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then
+ return false
+ end
+ table.insert(out, ")")
+ return true
+ end
+ return list(ctx, v, depth)
+ end
+ ctx.err = "cannot write a " .. tv .. " value"
+ return false
+end
+Write.value = value
+
+-- record(ctx, type, args) -> appends TYPE(args)
+function Write.record(ctx: Ctx, t: any, args: any): boolean
+ if not isName(t) then
+ ctx.err = "bad entity type " .. tostring(t)
+ return false
+ end
+ if type(args) ~= "table" then
+ ctx.err = "entity " .. t .. " without an args list"
+ return false
+ end
+ table.insert(ctx.out, string.upper(t))
+ return list(ctx, args, 0)
+end
+
+return Write
diff --git a/src/Formats/cad/step/init.luau b/src/Formats/cad/step/init.luau
new file mode 100644
index 0000000..1062a7a
--- /dev/null
+++ b/src/Formats/cad/step/init.luau
@@ -0,0 +1,412 @@
+--!strict
+-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema).
+-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME /
+-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and
+-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers;
+-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to
+-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" },
+-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE /
+-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same
+-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII).
+--
+-- B-rep bodies and tessellation come from an injected kernel, never required by formats-luau:
+-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text,
+-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } }
+-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = }
+-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) /
+-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies /
+-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up,
+-- millimetres (meta.unit = 0.001).
+-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT),
+-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Parse = require("@formats/cad/step/Parse")
+local Write = require("@formats/cad/step/Write")
+local Brep = require("@formats/cad/step/Brep")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Step = {
+ name = "step",
+ category = "cad",
+ extensions = { "step", "stp", "p21" },
+ mime = { "model/step", "application/step", "application/p21" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse larger files (default 2^30)
+ maxEntities: number?, -- refuse more instances (default 2^24)
+}
+export type EncodeOptions = {
+ schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA
+ name: string?, -- FILE_NAME name (default: the header's, else "model")
+ timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00")
+ crlf: boolean?, -- CRLF line ends (default LF)
+}
+export type BrepOptions = {
+ brep: any?, -- the plug-in (else opts.plugins.brep)
+ plugins: { [string]: any }?,
+ chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead
+ tess: { [string]: any }?,
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+Step.NULL = table.freeze({ null = true }) -- $
+Step.DERIVED = table.freeze({ derived = true }) -- *
+
+local SCHEMAS = {
+ AP203 = "CONFIG_CONTROL_DESIGN",
+ AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }",
+ AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }",
+}
+Step.SCHEMAS = SCHEMAS
+
+-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself
+local function schemaOf(name: string): string
+ local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name)
+ if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then
+ return "AP203"
+ elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then
+ return "AP214"
+ elseif string.find(n, "^AP242") then
+ return "AP242"
+ end
+ return n
+end
+Step.schemaOf = schemaOf
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Step.sniff(r: Bytes.Reader): number
+ local head = r:peek(256)
+ if string.sub(head, 1, 3) == "\239\187\191" then
+ head = string.sub(head, 4)
+ end
+ head = string.gsub(head, "^%s*/%*.-%*/", "")
+ if string.find(head, "^%s*ISO%-10303%-21%s*;") then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?)
+ local size = r.limit - r.base
+ if size > (opts and opts.maxBytes or 2 ^ 30) then
+ return nil, Err.new(Err.LIMIT, "file over maxBytes")
+ end
+ local s = buffer.readstring(r.buf, r.base, size)
+ local bom = 0
+ if string.sub(s, 1, 3) == "\239\187\191" then
+ s = string.sub(s, 4)
+ bom = 3
+ end
+ local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24)
+ if not res then
+ local off = if at then r.base + bom + at - 1 else nil
+ if msg == "LIMIT" then
+ return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off)
+ end
+ local m = msg or "parse error"
+ if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then
+ return nil, Err.new(Err.TRUNCATED, m, off)
+ end
+ return nil, Err.new(Err.CORRUPT, m, off)
+ end
+ local fs = res.header.FILE_SCHEMA
+ local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else ""
+ local cad: Types.Cad = {
+ kind = "cad",
+ schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown",
+ header = res.header,
+ entities = res.entities,
+ meta = {
+ count = res.count,
+ headerOrder = res.headerOrder,
+ source = {
+ format = "step",
+ schemaName = schemaName,
+ sections = res.sections,
+ extra = if #res.extra > 0 then res.extra else nil,
+ duplicates = if res.duplicates > 0 then res.duplicates else nil,
+ terminated = res.terminated,
+ },
+ },
+ }
+ return cad, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } }
+ local h = if type(cad.header) == "table" then cad.header else {}
+ local out: { [string]: { any } } = {}
+ for k, v in h do
+ out[k] = v
+ end
+ if type(out.FILE_DESCRIPTION) ~= "table" then
+ out.FILE_DESCRIPTION = { { "formats-luau" }, "2;1" }
+ end
+ if type(out.FILE_NAME) ~= "table" then
+ out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "formats-luau", "formats-luau", "" }
+ end
+ local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil)
+ if schema then
+ out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } }
+ end
+ return out
+end
+
+function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)")
+ end
+ local o: EncodeOptions = opts or {}
+ local nl = if o.crlf then "\r\n" else "\n"
+ local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil }
+ local out = ctx.out
+ table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl)
+ local header = headerArgs(cad, o)
+ local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" }
+ local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true }
+ local meta: any = if type(cad.meta) == "table" then cad.meta else {}
+ local rest = {}
+ for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do
+ if type(k) == "string" and header[k] and not seen[k] then
+ seen[k] = true
+ table.insert(order, k)
+ end
+ end
+ for k in header do
+ if type(k) == "string" and not seen[k] then
+ table.insert(rest, k)
+ end
+ end
+ table.sort(rest)
+ for _, k in rest do
+ table.insert(order, k)
+ end
+ for _, k in order do
+ if not Write.record(ctx, k, header[k]) then
+ return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err))
+ end
+ table.insert(out, ";" .. nl)
+ end
+ table.insert(out, "ENDSEC;" .. nl)
+ local source = if type(meta.source) == "table" then meta.source else {}
+ if type(source.extra) == "table" then
+ for _, x in source.extra do
+ if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then
+ table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl)
+ end
+ end
+ end
+ -- entities by section, in id order
+ local ids = {}
+ for id, e in cad.entities do
+ if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then
+ return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")")
+ end
+ table.insert(ids, id)
+ end
+ table.sort(ids)
+ local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} }
+ for si, sec in sections do
+ if #sections > 1 then
+ table.insert(out, "DATA")
+ local params = {}
+ if sec.name ~= nil then
+ params[1] = sec.name
+ params[2] = if sec.schema ~= nil then sec.schema else {}
+ if not Write.list(ctx, params, 0) then
+ return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err))
+ end
+ end
+ table.insert(out, ";" .. nl)
+ else
+ table.insert(out, "DATA;" .. nl)
+ end
+ for _, id in ids do
+ local e: any = cad.entities[id]
+ local esec = if type(e.section) == "number" then e.section else 1
+ if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then
+ table.insert(out, string.format("#%.0f=", id))
+ if e.type == "COMPLEX" or type(e.parts) == "table" then
+ if type(e.parts) ~= "table" or #e.parts == 0 then
+ return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts")
+ end
+ table.insert(out, "(")
+ for _, p in e.parts do
+ if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then
+ return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part"))
+ end
+ end
+ table.insert(out, ")")
+ elseif not Write.record(ctx, e.type, e.args) then
+ return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err))
+ end
+ table.insert(out, ";" .. nl)
+ end
+ end
+ table.insert(out, "ENDSEC;" .. nl)
+ end
+ table.insert(out, "END-ISO-10303-21;" .. nl)
+ return buffer.fromstring(table.concat(out)), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- get(cad, id | { ref = id }) -> the entity
+function Step.get(cad: Types.Cad, id: any): Types.StepEntity?
+ if type(id) == "table" then
+ id = id.ref
+ end
+ return cad.entities[id]
+end
+
+-- ids(cad) -> the instance ids in ascending order
+function Step.ids(cad: Types.Cad): { number }
+ local out = {}
+ for id in cad.entities do
+ table.insert(out, id)
+ end
+ table.sort(out)
+ return out
+end
+
+-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending
+function Step.byType(cad: Types.Cad, name: string): { number }
+ local n = string.upper(name)
+ local out = {}
+ for id, e in cad.entities do
+ if e.type == n then
+ table.insert(out, id)
+ elseif e.parts then
+ for _, p in e.parts do
+ if p.type == n then
+ table.insert(out, id)
+ break
+ end
+ end
+ end
+ end
+ table.sort(out)
+ return out
+end
+
+-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance)
+function Step.part(e: Types.StepEntity?, name: string): { any }?
+ if not e then
+ return nil
+ end
+ if e.type == name then
+ return e.args
+ end
+ if e.parts then
+ for _, p in e.parts do
+ if p.type == name then
+ return p.args
+ end
+ end
+ end
+ return nil
+end
+
+-- add(cad, type, args) -> id: a new instance after the highest id
+function Step.add(cad: Types.Cad, type: string, args: { any }): number
+ local top = 0
+ for id in cad.entities do
+ if id > top then
+ top = id
+ end
+ end
+ local id = top + 1
+ cad.entities[id] = { id = id, type = string.upper(type), args = args }
+ cad.meta.count = (cad.meta.count or 0) + 1
+ return id
+end
+
+-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`)
+function Step.real(t: { [any]: any }, key: any): { [any]: any }
+ local mt: any = getmetatable(t)
+ if not mt then
+ mt = { __reals = {} }
+ setmetatable(t, mt)
+ end
+ mt.__reals[key] = true
+ return t
+end
+
+-- new(schema?) -> an empty Cad ("AP214" by default)
+function Step.new(schema: string?): Types.Cad
+ return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } }
+end
+
+-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason
+Step.plugin = Brep.plugin
+
+local function textOf(cad: Types.Cad): (string?, Err.Err?)
+ local buf, err = Step.encode(cad)
+ if not buf then
+ return nil, err
+ end
+ return buffer.tostring(buf), nil
+end
+
+-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err
+function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any)
+ local plug, perr = Brep.find(opts)
+ if not plug then
+ return nil, perr
+ end
+ local text, err = textOf(cad)
+ if not text then
+ return nil, err
+ end
+ local bodies, res, rerr = Brep.read(plug, text, opts)
+ if not bodies then
+ return nil, rerr
+ end
+ return bodies, res
+end
+
+-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err
+function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?)
+ if type(bodies) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs a list of bodies")
+ end
+ local plug, perr = Brep.find(opts)
+ if not plug then
+ return nil, perr
+ end
+ local text, err = Brep.write(plug, bodies, opts)
+ if not text then
+ return nil, err
+ end
+ return Step.decode(Bytes.reader(buffer.fromstring(text)))
+end
+
+-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err
+function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?)
+ local plug, perr = Brep.find(opts)
+ if not plug then
+ return nil, perr
+ end
+ local bodies = value
+ if type(value) == "table" and value.kind == "cad" then
+ local b, err = Step.toBodies(value, opts)
+ if not b then
+ return nil, err
+ end
+ bodies = b
+ end
+ if type(bodies) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies")
+ end
+ return Brep.scene(plug, bodies, opts)
+end
+
+return Step
diff --git a/src/Formats/init.luau b/src/Formats/init.luau
index a5604b2..57d5dcc 100644
--- a/src/Formats/init.luau
+++ b/src/Formats/init.luau
@@ -259,6 +259,7 @@ end
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
-- the embedded parts) when called directly.
+-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
--
-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets
-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 /
@@ -278,10 +279,13 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
end
local function withHooks(o: Options): Options
- if o.decodeImage ~= nil and o.encodeImage ~= nil and o.openAudio ~= nil then
+ if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then
return o
end
local c = table.clone(o)
+ if c.plugins == nil then
+ c.plugins = F.plugins
+ end
if c.openAudio == nil then
c.openAudio = openAudio
end
@@ -587,6 +591,30 @@ for category in Types.CATEGORIES do
end
F.data.null = Types.null
+-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
+-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
+-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
+for _, fn in { "toBodies", "fromBodies", "tessellate" } do
+ local name: string = fn
+ F.cad[name] = function(value: any, opts: Options?): (any, any)
+ local o = if opts then table.clone(opts) else {}
+ if o.plugins == nil then
+ o.plugins = F.plugins
+ end
+ local m, err = F.format("step")
+ if not m then
+ return nil, err
+ end
+ local ok, a, b = pcall(m[name], value, o)
+ if not ok then
+ return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step")
+ end
+ if a == nil and type(b) == "table" and b.code then
+ return nil, Err.wrap(b, "step")
+ end
+ return a, b
+ end
+end
-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited
-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8).
F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?)
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/src/Formats/model/dae/Math.luau b/src/Formats/model/dae/Math.luau
new file mode 100644
index 0000000..594a53b
--- /dev/null
+++ b/src/Formats/model/dae/Math.luau
@@ -0,0 +1,188 @@
+--!strict
+-- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's
+-- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }.
+local DaeMath = {}
+
+local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos
+
+function DaeMath.identity(): { number }
+ return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
+end
+
+-- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1)
+function DaeMath.fromRows(v: { number }, at: number?): { number }
+ local o = (at or 1) - 1
+ local m = table.create(16, 0)
+ for r = 0, 3 do
+ for c = 0, 3 do
+ m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0)
+ end
+ end
+ return m
+end
+
+function DaeMath.toRows(m: { number }): { number }
+ local v = table.create(16, 0)
+ for r = 0, 3 do
+ for c = 0, 3 do
+ v[r * 4 + c + 1] = m[c * 4 + r + 1]
+ end
+ end
+ return v
+end
+
+function DaeMath.mul(a: { number }, b: { number }): { number }
+ local m = table.create(16, 0)
+ for col = 0, 3 do
+ for row = 0, 3 do
+ local s = 0
+ for k = 0, 3 do
+ s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
+ end
+ m[col * 4 + row + 1] = s
+ end
+ end
+ return m
+end
+
+function DaeMath.translation(x: number, y: number, z: number): { number }
+ return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
+end
+
+function DaeMath.scaling(x: number, y: number, z: number): { number }
+ return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
+end
+
+-- axisAngle(x, y, z, degrees) -> quaternion
+function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number }
+ local l = sqrt(x * x + y * y + z * z)
+ if l < 1e-12 then
+ return { 0, 0, 0, 1 }
+ end
+ local h = rad(degrees) / 2
+ local s = sin(h) / l
+ return { x * s, y * s, z * s, cos(h) }
+end
+
+function DaeMath.quatMatrix(q: { number }): { number }
+ local x, y, z, w = q[1], q[2], q[3], q[4]
+ local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
+ return {
+ 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
+ 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
+ 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
+ 0, 0, 0, 1,
+ }
+end
+
+local function cross(a: { number }, b: { number }): { number }
+ return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
+end
+local function norm(a: { number }): { number }
+ local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
+ if l < 1e-20 then
+ return { 0, 0, 0 }
+ end
+ return { a[1] / l, a[2] / l, a[3] / l }
+end
+
+-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest
+function DaeMath.lookat(v: { number }): { number }
+ local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0
+ local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) })
+ local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z))
+ local y = cross(z, x)
+ return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 }
+end
+
+-- skew(angle, rotation axis, translation axis) (RenderMan's skew)
+function DaeMath.skew(v: { number }): { number }
+ local a = rad(v[1] or 0)
+ local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 })
+ local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 })
+ local s = math.tan(a)
+ local m = DaeMath.identity()
+ -- M = I + s * t * r^T (column-major: m[col*4 + row])
+ for row = 0, 2 do
+ for col = 0, 2 do
+ m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1]
+ end
+ end
+ return m
+end
+
+-- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix)
+function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?)
+ if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then
+ return nil, nil, nil
+ end
+ local c1 = { m[1], m[2], m[3] }
+ local c2 = { m[5], m[6], m[7] }
+ local c3 = { m[9], m[10], m[11] }
+ local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3])
+ local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3])
+ local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3])
+ if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then
+ return nil, nil, nil
+ end
+ local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz }
+ local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3]
+ local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3]
+ local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3]
+ if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then
+ return nil, nil, nil
+ end
+ local cr = cross(x, y)
+ if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then
+ sx = -sx
+ x = { -x[1], -x[2], -x[3] }
+ end
+ -- rotation matrix (columns x, y, z) -> quaternion
+ local m00, m01, m02 = x[1], y[1], z[1]
+ local m10, m11, m12 = x[2], y[2], z[2]
+ local m20, m21, m22 = x[3], y[3], z[3]
+ local tr = m00 + m11 + m22
+ local qx, qy, qz, qw
+ if tr > 0 then
+ local s = sqrt(tr + 1) * 2
+ qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
+ elseif m00 > m11 and m00 > m22 then
+ local s = sqrt(1 + m00 - m11 - m22) * 2
+ qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
+ elseif m11 > m22 then
+ local s = sqrt(1 + m11 - m00 - m22) * 2
+ qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
+ else
+ local s = sqrt(1 + m22 - m00 - m11) * 2
+ qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
+ end
+ local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw)
+ return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz }
+end
+
+-- transformPoint / transformDir (column-major m)
+function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number)
+ return 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]
+end
+
+-- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4
+function DaeMath.normalMatrix(m: { number }): { number }
+ local a, b, c = m[1], m[5], m[9]
+ local d, e, f = m[2], m[6], m[10]
+ local g, h, i = m[3], m[7], m[11]
+ local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
+ local det = a * A + b * B + c * C
+ if abs(det) < 1e-30 then
+ return DaeMath.identity()
+ end
+ local k = 1 / det
+ -- inverse = adj / det; its transpose has rows = cofactors
+ return {
+ A * k, B * k, C * k, 0,
+ -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
+ (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
+ 0, 0, 0, 1,
+ }
+end
+
+return DaeMath
diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau
new file mode 100644
index 0000000..82bbb59
--- /dev/null
+++ b/src/Formats/model/dae/Read.luau
@@ -0,0 +1,1879 @@
+--!strict
+-- model/dae/Read: a parsed Collada document (codecs/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons /
+-- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile
+-- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains,
+-- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix /
+-- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin
+-- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as
+-- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform
+-- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS
+-- channels; one animation per animation clip, else one for the file).
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+local Base64 = require("@formats/codecs/Base64")
+local M = require("@formats/model/dae/Math")
+
+local Read = {}
+
+export type Fetch = (uri: string) -> buffer?
+
+local Scene = Types.Scene
+local find, sub, gmatch, match, lower, upper = string.find, string.sub, string.gmatch, string.match, string.lower, string.upper
+local children, child, text = Xml.children, Xml.child, Xml.text
+
+local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" }
+local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" }
+local PARAM_SIZE = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 }
+local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 }
+
+-- ------------------------------------------------------------------------------------------------ helpers
+local function numbers(s: string, limit: number): ({ number }?, string?)
+ local out = {}
+ local n = 0
+ for w in gmatch(s, "[^%s]+") do
+ n += 1
+ if n > limit then
+ return nil, "array over the limit"
+ end
+ local v = tonumber(w)
+ if v == nil and find(w, ",", 1, true) and not find(w, ".", 1, true) then
+ v = tonumber((string.gsub(w, ",", "."))) -- decimal commas (some 3ds Max exporters)
+ end
+ if v == nil then
+ local lw = lower(w)
+ v = if lw == "nan" or lw == "-nan" or lw == "1.#qnan" or lw == "-1.#ind" then 0 elseif lw == "inf" or lw == "1.#inf" then math.huge elseif lw == "-inf" or lw == "-1.#inf" then -math.huge elseif lw == "true" then 1 elseif lw == "false" then 0 else 0
+ end
+ out[n] = v :: number
+ end
+ return out, nil
+end
+local function words(s: string): { string }
+ local out = {}
+ for w in gmatch(s, "[^%s]+") do
+ table.insert(out, w)
+ end
+ return out
+end
+local function attr(node: any, name: string): string?
+ local v = node and node.attrs and node.attrs[name]
+ return if type(v) == "string" then v else nil
+end
+local function urlId(url: string?): string?
+ if not url then
+ return nil
+ end
+ return match(url, "^#(.*)$") or url
+end
+local function lname(node: any): string
+ return Xml.localName(node.name)
+end
+local function numText(node: any, default: number): number
+ if not node then
+ return default
+ end
+ return tonumber(match(text(node), "[^%s]+") or "") or default
+end
+local function color(node: any): { number }?
+ local c = node and child(node, "color")
+ if not c then
+ return nil
+ end
+ local v = numbers(text(c), 16) or {}
+ return { v[1] or 0, v[2] or 0, v[3] or 0, v[4] or 1 }
+end
+
+type Ctx = {
+ doc: any,
+ ids: { [string]: any },
+ fetch: Fetch,
+ scene: Types.Scene,
+ limit: number,
+ vertices: number,
+ flipV: boolean,
+ triangulate: boolean,
+ sources: { [any]: any },
+ materials: { [string]: number },
+ textures: { [string]: number },
+ images: { [string]: any },
+ meshes: { [string]: number },
+ skins: { [string]: number },
+ posIndex: { [any]: { number } },
+ nodeOf: { [string]: { number } }, -- collada node id -> scene nodes
+ info: { [number]: any }, -- scene node -> { el, xf, sid, cid }
+ pendingSkins: { any },
+ skipped: { [string]: number },
+ err: string?,
+ depth: number,
+}
+
+local function skip(C: Ctx, what: string)
+ C.skipped[what] = (C.skipped[what] or 0) + 1
+end
+
+-- ------------------------------------------------------------------------------------------------ sources
+-- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params)
+local function readSource(C: Ctx, el: any): any
+ local cached = C.sources[el]
+ if cached ~= nil then
+ return cached or nil
+ end
+ C.sources[el] = false
+ local arrEl: any = nil
+ local strings = false
+ for _, ch in children(el) do
+ local n = lname(ch)
+ if n == "float_array" or n == "int_array" or n == "bool_array" then
+ arrEl = ch
+ elseif n == "Name_array" or n == "IDREF_array" or n == "SIDREF_array" or n == "token_array" then
+ arrEl, strings = ch, true
+ end
+ end
+ local values: { any } = {}
+ if arrEl then
+ if strings then
+ values = words(text(arrEl))
+ else
+ local v, e = numbers(text(arrEl), C.limit)
+ if not v then
+ C.err = e
+ return nil
+ end
+ values = v
+ end
+ end
+ local tc = child(el, "technique_common")
+ local acc = tc and child(tc, "accessor")
+ local out: any
+ if not acc then
+ out = { data = values, comps = 1, count = #values }
+ else
+ local count = tonumber(attr(acc, "count") or "") or 0
+ local stride = tonumber(attr(acc, "stride") or "") or 1
+ local offset = tonumber(attr(acc, "offset") or "") or 0
+ local picks = {}
+ local pos = 0
+ local anyNamed = false
+ for _, p in children(acc, "param") do
+ if attr(p, "name") then
+ anyNamed = true
+ end
+ end
+ for _, p in children(acc, "param") do
+ local w = PARAM_SIZE[attr(p, "type") or ""] or 1
+ if attr(p, "name") or not anyNamed then
+ for k = 0, w - 1 do
+ table.insert(picks, pos + k)
+ end
+ end
+ pos += w
+ end
+ if #picks == 0 then
+ for k = 0, stride - 1 do
+ table.insert(picks, k)
+ end
+ end
+ if stride < 1 or count < 0 or count * stride > C.limit * 16 then
+ C.err = "bad accessor"
+ return nil
+ end
+ count = math.min(count, math.max(0, (#values - offset) // math.max(stride, 1)))
+ local comps = #picks
+ local data = table.create(count * comps)
+ local n = 0
+ for i = 0, count - 1 do
+ local base = offset + i * stride + 1
+ for _, k in picks do
+ n += 1
+ data[n] = values[base + k] or 0
+ end
+ end
+ out = { data = data, comps = comps, count = count }
+ end
+ C.sources[el] = out
+ return out
+end
+
+local function sourceById(C: Ctx, url: string?): any
+ local id = urlId(url)
+ local el = id and C.ids[id]
+ if not el or lname(el) ~= "source" then
+ return nil
+ end
+ return readSource(C, el)
+end
+
+-- ------------------------------------------------------------------------------------------------ images, materials
+local function fetchImage(C: Ctx, ref: string): (buffer?, string)
+ local uri = ref
+ uri = string.gsub(uri, "^file:///(%a:)", "%1")
+ uri = string.gsub(uri, "^file://", "")
+ local data = C.fetch(uri)
+ if not data then
+ local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string
+ return string.char(tonumber(h, 16) :: number)
+ end)
+ data = C.fetch(decoded)
+ if not data then
+ local base = match(decoded, "([^/\\]+)$")
+ if base and base ~= decoded then
+ data = C.fetch(base)
+ end
+ end
+ end
+ return data, uri
+end
+
+local function image(C: Ctx, id: string): any
+ local cached = C.images[id]
+ if cached ~= nil then
+ return cached or nil
+ end
+ C.images[id] = false
+ local el = C.ids[id]
+ if not el or lname(el) ~= "image" then
+ return nil
+ end
+ local img: any = { name = attr(el, "name") or id }
+ local init = child(el, "init_from")
+ local hex: any = child(el, "data")
+ if init then
+ local ref = child(init, "ref")
+ local s = match(text(ref or init), "^%s*(.-)%s*$") or ""
+ if s ~= "" then
+ if sub(s, 1, 5) == "data:" then
+ local d, mime = Base64.decodeDataUri(s)
+ if d then
+ img.data, img.mime = d, mime
+ end
+ else
+ local d, uri = fetchImage(C, s)
+ img.data, img.uri = d, uri
+ local ext = match(uri, "%.([%w]+)$")
+ img.mime = ext and MIME[lower(ext)]
+ end
+ end
+ hex = hex or child(init, "hex")
+ end
+ if hex and not img.data then
+ local h = string.gsub(text(hex), "%s+", "")
+ if #h % 2 == 0 and not find(h, "[^%x]") then
+ local b = buffer.create(#h // 2)
+ for i = 0, #h // 2 - 1 do
+ buffer.writeu8(b, i, tonumber(sub(h, i * 2 + 1, i * 2 + 2), 16) :: number)
+ end
+ img.data = b
+ local fmt = attr(hex, "format") or attr(el, "format")
+ img.mime = fmt and MIME[lower(fmt)]
+ end
+ end
+ if img.data and not img.mime then
+ local b = img.data
+ if buffer.len(b) >= 4 then
+ local m4 = buffer.readstring(b, 0, 4)
+ img.mime = if m4 == "\137PNG" then "image/png" elseif sub(m4, 1, 3) == "\255\216\255" then "image/jpeg" else nil
+ end
+ end
+ C.images[id] = img
+ return img
+end
+
+-- the effect's newparams by sid (this level and the profile's)
+local function newparams(effect: any, profile: any, technique: any): { [string]: any }
+ local out = {}
+ for _, scope in { effect, profile, technique } do
+ if scope then
+ for _, np in children(scope, "newparam") do
+ local sid = attr(np, "sid")
+ if sid then
+ out[sid] = np
+ end
+ end
+ end
+ end
+ return out
+end
+
+-- texture(effect params, sampler sid) -> scene texture index
+local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number?
+ local np = params[samplerSid]
+ local imageId: string? = nil
+ local sampler: any = nil
+ if np then
+ local s2d = child(np, "sampler2D") or child(np, "samplerCUBE") or child(np, "sampler3D")
+ if s2d then
+ sampler = s2d
+ local inst = child(s2d, "instance_image")
+ if inst then
+ imageId = urlId(attr(inst, "url"))
+ else
+ local src = child(s2d, "source")
+ local surfNp = src and params[match(text(src), "^%s*(.-)%s*$") or ""]
+ local surf = surfNp and child(surfNp, "surface")
+ local init = surf and child(surf, "init_from")
+ if init then
+ imageId = match(text(init), "^%s*(.-)%s*$")
+ end
+ end
+ else
+ local surf = child(np, "surface")
+ local init = surf and child(surf, "init_from")
+ if init then
+ imageId = match(text(init), "^%s*(.-)%s*$")
+ end
+ end
+ else
+ -- many exporters reference the image id directly
+ imageId = samplerSid
+ end
+ if not imageId then
+ return nil
+ end
+ local key = imageId .. "|" .. samplerSid
+ local cached = C.textures[key]
+ if cached then
+ return cached
+ end
+ local img = image(C, imageId)
+ if not img then
+ return nil
+ end
+ local tex: Types.Texture = { name = img.name, data = img.data, mime = img.mime, uri = img.uri }
+ if sampler then
+ local ws, wt = child(sampler, "wrap_s"), child(sampler, "wrap_t")
+ local mag = child(sampler, "magfilter")
+ local smp: Types.Sampler = {}
+ if ws then
+ smp.wrapS = WRAP[upper(match(text(ws), "[%w_]+") or "")] :: any
+ end
+ if wt then
+ smp.wrapT = WRAP[upper(match(text(wt), "[%w_]+") or "")] :: any
+ end
+ if mag then
+ local f = upper(match(text(mag), "[%w_]+") or "")
+ smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil
+ end
+ if next(smp) then
+ tex.sampler = smp
+ end
+ end
+ table.insert(C.scene.textures, tex)
+ local idx = #C.scene.textures
+ C.textures[key] = idx
+ return idx
+end
+
+-- one colour-or-texture parameter of a common technique
+local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any)
+ if not el then
+ return nil, nil
+ end
+ local c = color(el)
+ local f = child(el, "float")
+ local tx = child(el, "texture")
+ local ref: any = nil
+ if tx then
+ local ti = texture(C, params, attr(tx, "texture") or "")
+ if ti then
+ ref = { texture = ti }
+ local set = uvsets[attr(tx, "texcoord") or ""]
+ if set and set > 0 then
+ ref.texCoord = set
+ end
+ end
+ end
+ if c then
+ return c, ref
+ elseif f then
+ return numText(f, 0), ref
+ end
+ local pr = child(el, "param")
+ if pr then
+ local np = params[attr(pr, "ref") or ""]
+ local v = np and (child(np, "float4") or child(np, "float3") or child(np, "float"))
+ if v then
+ local nums = numbers(text(v), 16) or {}
+ if #nums == 1 then
+ return nums[1], ref
+ end
+ return { nums[1] or 0, nums[2] or 0, nums[3] or 0, nums[4] or 1 }, ref
+ end
+ end
+ return nil, ref
+end
+
+local function material(C: Ctx, id: string, uvsets: { [string]: number }): number?
+ local cached = C.materials[id]
+ if cached then
+ return cached
+ end
+ local el = C.ids[id]
+ if not el or lname(el) ~= "material" then
+ return nil
+ end
+ local mat = Scene.material(attr(el, "name") or id)
+ mat.metallic = 0
+ local inst = child(el, "instance_effect")
+ local effect = inst and C.ids[urlId(attr(inst, "url")) or ""]
+ local phong: { [string]: any } = {}
+ if effect and lname(effect) == "effect" then
+ local profile = child(effect, "profile_COMMON")
+ local tech = profile and child(profile, "technique")
+ local shader: any = nil
+ if tech then
+ for _, ch in children(tech) do
+ local n = lname(ch)
+ if n == "phong" or n == "blinn" or n == "lambert" or n == "constant" then
+ shader = ch
+ phong.model = n
+ break
+ end
+ end
+ end
+ local params = newparams(effect, profile, tech)
+ if shader then
+ local diffuse, dtex = param(C, params, child(shader, "diffuse"), uvsets)
+ local emission, etex = param(C, params, child(shader, "emission"), uvsets)
+ local ambient, atex = param(C, params, child(shader, "ambient"), uvsets)
+ local specular, stex = param(C, params, child(shader, "specular"), uvsets)
+ local shininess = param(C, params, child(shader, "shininess"), uvsets)
+ local reflective = param(C, params, child(shader, "reflective"), uvsets)
+ local reflectivity = param(C, params, child(shader, "reflectivity"), uvsets)
+ local transparentEl = child(shader, "transparent")
+ local transparent, ttex = param(C, params, transparentEl, uvsets)
+ local transparency = param(C, params, child(shader, "transparency"), uvsets)
+ local ior = param(C, params, child(shader, "index_of_refraction"), uvsets)
+ phong.diffuse, phong.diffuseTexture = diffuse, dtex
+ phong.emission, phong.emissionTexture = emission, etex
+ phong.ambient, phong.ambientTexture = ambient, atex
+ phong.specular, phong.specularTexture = specular, stex
+ phong.shininess, phong.reflective, phong.reflectivity = shininess, reflective, reflectivity
+ phong.transparent, phong.transparentTexture, phong.transparency = transparent, ttex, transparency
+ phong.indexOfRefraction = ior
+ if type(diffuse) == "table" then
+ mat.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 } -- its alpha is not opacity (exporters write 0)
+ end
+ if phong.model == "constant" and type(emission) == "table" then
+ mat.baseColor = { emission[1], emission[2], emission[3], 1 }
+ mat.extensions = { KHR_materials_unlit = {} }
+ end
+ if dtex then
+ mat.baseColorTexture = dtex
+ if type(diffuse) ~= "table" then
+ mat.baseColor = { 1, 1, 1, 1 }
+ end
+ end
+ if type(emission) == "table" and phong.model ~= "constant" then
+ mat.emissive = { emission[1], emission[2], emission[3] }
+ end
+ if etex then
+ mat.emissiveTexture = etex
+ mat.emissive = { 1, 1, 1 }
+ end
+ if type(shininess) == "number" then
+ mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1)
+ end
+ -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance)
+ if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then
+ local mode = attr(transparentEl, "opaque") or "A_ONE"
+ local tv = if type(transparency) == "number" then transparency else 1
+ local tc: any = if type(transparent) == "table" then transparent else { 1, 1, 1, 1 }
+ local a: number
+ if mode == "RGB_ZERO" then
+ a = 1 - tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169)
+ elseif mode == "A_ZERO" then
+ a = 1 - tv * tc[4]
+ elseif mode == "RGB_ONE" then
+ a = tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169)
+ else
+ a = tv * tc[4]
+ end
+ a = math.clamp(a, 0, 1)
+ if a < 0.999 and a > 0.001 then
+ mat.baseColor[4] = a
+ mat.alphaMode = "blend"
+ end
+ phong.opacity = a
+ end
+ if ttex then
+ mat.alphaMode = "blend"
+ end
+ end
+ -- FCOLLADA / MAX3D / OpenCOLLADA extras: bump maps and double sidedness
+ for _, scope in { tech, profile, effect } do
+ if scope then
+ for _, ex in children(scope, "extra") do
+ for _, tq in children(ex, "technique") do
+ local bump = child(tq, "bump")
+ if bump and not mat.normalTexture then
+ local _, btex = param(C, params, bump, uvsets)
+ if btex then
+ mat.normalTexture = btex
+ end
+ end
+ local ds = child(tq, "double_sided")
+ if ds and numText(ds, 0) ~= 0 then
+ mat.doubleSided = true
+ end
+ end
+ end
+ end
+ end
+ end
+ mat.extras = { phong = phong }
+ table.insert(C.scene.materials, mat)
+ local idx = #C.scene.materials
+ C.materials[id] = idx
+ return idx
+end
+
+-- ------------------------------------------------------------------------------------------------ geometry
+type Input = { semantic: string, source: any, offset: number, set: number }
+
+-- the inputs of a primitive element (VERTEX expanded into the inputs)
+local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number)
+ local out: { Input } = {}
+ local stride = 0
+ for _, inp in children(prim, "input") do
+ local sem = upper(attr(inp, "semantic") or "")
+ local offset = tonumber(attr(inp, "offset") or "") or 0
+ local set = tonumber(attr(inp, "set") or "") or 0
+ if offset + 1 > stride then
+ stride = offset + 1
+ end
+ if sem == "VERTEX" then
+ local vel = C.ids[urlId(attr(inp, "source")) or ""] or verticesEl
+ if vel and lname(vel) == "vertices" then
+ for _, vin in children(vel, "input") do
+ local vs = upper(attr(vin, "semantic") or "")
+ local src = sourceById(C, attr(vin, "source"))
+ if src then
+ table.insert(out, { semantic = vs, source = src, offset = offset, set = tonumber(attr(vin, "set") or "") or set })
+ end
+ end
+ end
+ else
+ local src = sourceById(C, attr(inp, "source"))
+ if src then
+ table.insert(out, { semantic = sem, source = src, offset = offset, set = set })
+ end
+ end
+ end
+ return out, math.max(stride, 1)
+end
+
+-- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode
+local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string)
+ local p: { number } = {}
+ local faces: { number } = {}
+ local starts: { number } = {}
+ local function addP(el: any): (number, number)
+ local v, e = numbers(text(el), C.limit)
+ if not v then
+ C.err = e
+ return 0, 0
+ end
+ local base = #p
+ table.move(v, 1, #v, base + 1, p)
+ return base // stride, #v // stride
+ end
+ if kind == "triangles" or kind == "lines" then
+ local per = if kind == "triangles" then 3 else 2
+ local pe = child(prim, "p")
+ if pe then
+ local _, n = addP(pe)
+ local count = math.min(tonumber(attr(prim, "count") or "") or n // per, n // per)
+ for f = 0, count - 1 do
+ table.insert(faces, per)
+ for k = 0, per - 1 do
+ table.insert(starts, f * per + k)
+ end
+ end
+ end
+ return p, faces, starts, kind
+ elseif kind == "polylist" then
+ local pe = child(prim, "p")
+ local vc = child(prim, "vcount")
+ if pe and vc then
+ local _, n = addP(pe)
+ local counts = numbers(text(vc), C.limit) or {}
+ local at = 0
+ for _, c in counts do
+ c = math.floor(c)
+ if c < 0 or at + c > n then
+ break
+ end
+ table.insert(faces, c)
+ for k = 0, c - 1 do
+ table.insert(starts, at + k)
+ end
+ at += c
+ end
+ end
+ return p, faces, starts, "polygons"
+ elseif kind == "polygons" then
+ local list = children(prim, "p")
+ for _, ph in children(prim, "ph") do
+ local outer = child(ph, "p")
+ if outer then
+ table.insert(list, outer)
+ end
+ skip(C, "polygon holes")
+ end
+ for _, pe in list do
+ local first, n = addP(pe)
+ if n > 0 then
+ table.insert(faces, n)
+ for k = 0, n - 1 do
+ table.insert(starts, first + k)
+ end
+ end
+ end
+ return p, faces, starts, "polygons"
+ elseif kind == "linestrips" then
+ for _, pe in children(prim, "p") do
+ local first, n = addP(pe)
+ for k = 0, n - 2 do
+ table.insert(faces, 2)
+ table.insert(starts, first + k)
+ table.insert(starts, first + k + 1)
+ end
+ end
+ return p, faces, starts, "lines"
+ elseif kind == "tristrips" or kind == "trifans" then
+ for _, pe in children(prim, "p") do
+ local first, n = addP(pe)
+ for k = 0, n - 3 do
+ table.insert(faces, 3)
+ if kind == "trifans" then
+ table.insert(starts, first)
+ table.insert(starts, first + k + 1)
+ table.insert(starts, first + k + 2)
+ elseif k % 2 == 0 then
+ table.insert(starts, first + k)
+ table.insert(starts, first + k + 1)
+ table.insert(starts, first + k + 2)
+ else
+ table.insert(starts, first + k + 1)
+ table.insert(starts, first + k)
+ table.insert(starts, first + k + 2)
+ end
+ end
+ end
+ return p, faces, starts, "triangles"
+ end
+ return nil, nil, nil, kind
+end
+
+local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true }
+
+type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } }
+
+-- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs)
+local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built?
+ local ins, stride = inputs(C, prim, verticesEl)
+ local p, faces, starts, mode = corners(C, prim, kind, stride)
+ if C.err or not p or not faces or not starts then
+ return nil
+ end
+ local posIn: Input? = nil
+ for _, i in ins do
+ if i.semantic == "POSITION" then
+ posIn = i
+ break
+ end
+ end
+ if not posIn then
+ skip(C, "primitives without positions")
+ return nil
+ end
+ -- attribute names
+ local named: { { input: Input, name: string, comps: number } } = {}
+ local texSets: { number } = {}
+ local texInputs: { Input } = {}
+ local colorN, normalSeen = 0, false
+ for _, i in ins do
+ if i.semantic == "TEXCOORD" then
+ table.insert(texInputs, i)
+ end
+ end
+ table.sort(texInputs, function(a: Input, b: Input): boolean
+ if a.set ~= b.set then
+ return a.set < b.set
+ end
+ return a.offset < b.offset
+ end)
+ for k, i in texInputs do
+ texSets[k] = i.set
+ table.insert(named, { input = i, name = "TEXCOORD_" .. (k - 1), comps = 2 })
+ end
+ for _, i in ins do
+ local s = i.semantic
+ local comps = math.min(i.source.comps, 4)
+ if s == "POSITION" then
+ if i == posIn then
+ table.insert(named, { input = i, name = "POSITION", comps = 3 })
+ end
+ elseif s == "NORMAL" then
+ table.insert(named, { input = i, name = if normalSeen then "_NORMAL" .. i.set else "NORMAL", comps = 3 })
+ normalSeen = true
+ elseif s == "COLOR" then
+ table.insert(named, { input = i, name = "COLOR_" .. colorN, comps = if comps >= 4 then 4 else 3 })
+ colorN += 1
+ elseif s ~= "TEXCOORD" then
+ table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) })
+ end
+ end
+ -- de-index
+ local np = #p
+ local keyOf: { [any]: number } = {}
+ local tuples: { number } = {} -- the first p index of each output vertex's tuple
+ local corner = table.create(#starts)
+ local count = 0
+ for ci, s in starts do
+ local base = s * stride
+ if base + stride > np then
+ C.err = "index list too short"
+ return nil
+ end
+ local key: any
+ if stride == 1 then
+ key = p[base + 1]
+ else
+ key = table.concat(p, ",", base + 1, base + stride)
+ end
+ local v = keyOf[key]
+ if not v then
+ v = count
+ count += 1
+ keyOf[key] = v
+ tuples[count] = base
+ end
+ corner[ci] = v
+ end
+ C.vertices += count
+ if C.vertices > C.limit then
+ C.err = "over the vertex limit"
+ return nil
+ end
+ local attributes: { [string]: Types.Accessor } = {}
+ local posIndex = table.create(count, 0)
+ for _, a in named do
+ local src = a.input.source
+ local comps, scomps = a.comps, src.comps
+ local data, n = src.data, src.count
+ local buf = buffer.create(count * comps * 4)
+ local off = a.input.offset + 1
+ local isTex = sub(a.name, 1, 9) == "TEXCOORD_"
+ local isPos = a.name == "POSITION"
+ for v = 0, count - 1 do
+ local idx = p[tuples[v + 1] + off]
+ if idx == nil or idx < 0 or idx >= n or idx ~= idx // 1 then
+ C.err = "index out of range"
+ return nil
+ end
+ if isPos then
+ posIndex[v + 1] = idx
+ end
+ local at = idx * scomps
+ for k = 1, comps do
+ local x = if k <= scomps then data[at + k] else (if k == 4 then 1 else 0)
+ if type(x) ~= "number" then
+ x = 0
+ end
+ if isTex and k == 2 and C.flipV then
+ x = 1 - x
+ end
+ buffer.writef32(buf, (v * comps + k - 1) * 4, x)
+ end
+ end
+ attributes[a.name] = Scene.accessor(buf, "f32", comps, count)
+ end
+ local nc = #corner
+ local out: Types.Primitive = { attributes = attributes, mode = "triangles" }
+ if mode == "polygons" then
+ local allTri = true
+ for _, f in faces do
+ if f ~= 3 then
+ allTri = false
+ break
+ end
+ end
+ if allTri then
+ mode = "triangles"
+ elseif C.triangulate then
+ -- fan triangulation
+ local tri = {}
+ local at = 0
+ for _, f in faces do
+ for k = 1, f - 2 do
+ table.insert(tri, corner[at + 1])
+ table.insert(tri, corner[at + k + 1])
+ table.insert(tri, corner[at + k + 2])
+ end
+ at += f
+ end
+ corner, nc, mode = tri, #tri, "triangles"
+ else
+ local fb = buffer.create(#faces * 4)
+ for i, f in faces do
+ buffer.writeu32(fb, (i - 1) * 4, f)
+ end
+ out.faces = Scene.accessor(fb, "u32", 1, #faces)
+ end
+ end
+ out.mode = mode :: any
+ local ib = buffer.create(nc * 4)
+ for i = 1, nc do
+ buffer.writeu32(ib, (i - 1) * 4, corner[i])
+ end
+ out.indices = Scene.accessor(ib, "u32", 1, nc)
+ return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex }
+end
+
+-- geometry(el) -> the built primitives (cached per geometry element)
+local function geometry(C: Ctx, el: any): { Built }?
+ local cached = C.posIndex[el]
+ if cached then
+ return cached :: any
+ end
+ local mesh = child(el, "mesh") or child(el, "convex_mesh")
+ if not mesh then
+ if child(el, "spline") or child(el, "brep") then
+ skip(C, "spline / brep geometry")
+ end
+ return nil
+ end
+ local verticesEl = child(mesh, "vertices")
+ local out: { Built } = {}
+ for _, ch in children(mesh) do
+ local n = lname(ch)
+ if PRIMS[n] then
+ local b = buildPrim(C, ch, verticesEl, n)
+ if C.err then
+ return nil
+ end
+ if b then
+ table.insert(out, b)
+ end
+ end
+ end
+ C.posIndex[el] = out :: any
+ return out
+end
+
+-- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set
+local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } })
+ local syms: { [string]: string } = {}
+ local sets: { [string]: { [string]: number } } = {}
+ local bm = node and child(node, "bind_material")
+ local tc = bm and child(bm, "technique_common")
+ if tc then
+ for _, im in children(tc, "instance_material") do
+ local sym, target = attr(im, "symbol"), urlId(attr(im, "target"))
+ if sym and target then
+ syms[sym] = target
+ local s = {}
+ for _, bvi in children(im, "bind_vertex_input") do
+ local sem = attr(bvi, "semantic")
+ if sem then
+ s[sem] = tonumber(attr(bvi, "input_set") or "") or 0
+ end
+ end
+ sets[sym] = s
+ end
+ end
+ end
+ return syms, sets
+end
+
+local function copyAccessor(a: Types.Accessor): Types.Accessor
+ local b = buffer.create(buffer.len(a.data))
+ buffer.copy(b, 0, a.data)
+ return Scene.accessor(b, a.type, a.components, a.count)
+end
+
+-- mesh(geometry element, instance element, skin?) -> scene mesh index
+local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?)
+ local syms, sets = bindings(inst)
+ local parts = { key }
+ for s, t in syms do
+ table.insert(parts, s .. "=" .. t)
+ end
+ table.sort(parts)
+ local k = table.concat(parts, ";")
+ local built = geometry(C, geomEl)
+ if not built or #built == 0 then
+ return nil, nil
+ end
+ local cached = C.meshes[k]
+ if cached then
+ return cached, built
+ end
+ local mesh: Types.Mesh = { name = attr(geomEl, "name") or attr(geomEl, "id"), primitives = {} }
+ for _, b in built do
+ local prim = b.prim
+ if bindShape then
+ -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared)
+ local attrs = table.clone(prim.attributes)
+ local pos = copyAccessor(attrs.POSITION)
+ for v = 0, pos.count - 1 do
+ local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)
+ x, y, z = M.point(bindShape, x, y, z)
+ buffer.writef32(pos.data, v * 12, x)
+ buffer.writef32(pos.data, v * 12 + 4, y)
+ buffer.writef32(pos.data, v * 12 + 8, z)
+ end
+ attrs.POSITION = pos
+ if attrs.NORMAL then
+ local nm = M.normalMatrix(bindShape)
+ local nrm = copyAccessor(attrs.NORMAL)
+ for v = 0, nrm.count - 1 do
+ local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8)
+ x, y, z = nm[1] * x + nm[5] * y + nm[9] * z, nm[2] * x + nm[6] * y + nm[10] * z, nm[3] * x + nm[7] * y + nm[11] * z
+ local l = math.sqrt(x * x + y * y + z * z)
+ if l > 0 then
+ x, y, z = x / l, y / l, z / l
+ end
+ buffer.writef32(nrm.data, v * 12, x)
+ buffer.writef32(nrm.data, v * 12 + 4, y)
+ buffer.writef32(nrm.data, v * 12 + 8, z)
+ end
+ attrs.NORMAL = nrm
+ end
+ prim = table.clone(prim)
+ prim.attributes = attrs
+ else
+ prim = table.clone(prim)
+ end
+ local sym = b.symbol
+ local target = sym and (syms[sym] or (if C.ids[sym] and lname(C.ids[sym]) == "material" then sym else nil))
+ if not target then
+ -- no (or an unbound) symbol and a single binding: that one (MakeHuman leaves out the symbol)
+ local only, n = nil, 0
+ for s2 in syms do
+ only, n = s2, n + 1
+ end
+ if n == 1 then
+ sym = only
+ target = syms[only :: string]
+ end
+ end
+ if target then
+ -- texcoord semantic -> TEXCOORD_n index among this primitive's sets
+ local uv: { [string]: number } = {}
+ for sem, set in (sym and sets[sym]) or {} do
+ uv[sem] = (table.find(b.texSets, set) or 1) - 1
+ end
+ prim.material = material(C, target, uv)
+ end
+ table.insert(mesh.primitives, prim)
+ end
+ table.insert(C.scene.meshes, mesh)
+ local idx = #C.scene.meshes
+ C.meshes[k] = idx
+ return idx, built
+end
+
+-- morph controller -> mesh with targets (deltas)
+local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number?
+ local base = C.ids[urlId(attr(morph, "source")) or ""]
+ if not base or lname(base) ~= "geometry" then
+ return nil
+ end
+ local idx, built = meshFor(C, base, inst, "morph:" .. (attr(ctrl, "id") or ""), nil)
+ if not idx or not built then
+ return nil
+ end
+ local mesh = C.scene.meshes[idx]
+ if mesh.weights then
+ return idx
+ end
+ local relative = upper(attr(morph, "method") or "NORMALIZED") == "RELATIVE"
+ local targetsEl = child(morph, "targets")
+ local targetIds: { string } = {}
+ local weights: { number } = {}
+ if targetsEl then
+ for _, inp in children(targetsEl, "input") do
+ local sem = upper(attr(inp, "semantic") or "")
+ local src = sourceById(C, attr(inp, "source"))
+ if src and sem == "MORPH_TARGET" then
+ for _, v in src.data do
+ table.insert(targetIds, tostring(v))
+ end
+ elseif src and sem == "MORPH_WEIGHT" then
+ for _, v in src.data do
+ table.insert(weights, if type(v) == "number" then v else 0)
+ end
+ end
+ end
+ end
+ local tbuilt: { { Built } } = {}
+ for _, tid in targetIds do
+ local g = C.ids[tid]
+ local tb = g and lname(g) == "geometry" and geometry(C, g)
+ if not tb or #tb ~= #built then
+ skip(C, "morph targets with another topology")
+ return idx
+ end
+ table.insert(tbuilt, tb)
+ end
+ for pi, prim in mesh.primitives do
+ local targets = {}
+ for ti, tb in tbuilt do
+ local tp = tb[pi].prim
+ local t: { [string]: Types.Accessor } = {}
+ for _, name in { "POSITION", "NORMAL" } do
+ local a, b = prim.attributes[name], tp.attributes[name]
+ if a and b and a.count == b.count then
+ local d = buffer.create(a.count * 12)
+ for i = 0, a.count * 3 - 1 do
+ local bv = buffer.readf32(b.data, i * 4)
+ buffer.writef32(d, i * 4, if relative then bv else bv - buffer.readf32(a.data, i * 4))
+ end
+ t[name] = Scene.accessor(d, "f32", 3, a.count)
+ end
+ end
+ targets[ti] = t
+ end
+ prim.targets = targets
+ end
+ mesh.weights = weights
+ return idx
+end
+
+-- ------------------------------------------------------------------------------------------------ cameras, lights
+local function camera(C: Ctx, el: any): number?
+ local optics = child(el, "optics")
+ local tc = optics and child(optics, "technique_common")
+ if not tc then
+ return nil
+ end
+ local cam: Types.Camera
+ local persp, ortho = child(tc, "perspective"), child(tc, "orthographic")
+ if persp then
+ local xfov, yfov = child(persp, "xfov"), child(persp, "yfov")
+ local aspect = child(persp, "aspect_ratio")
+ local ar = if aspect then numText(aspect, 1) else nil
+ local yf: number
+ if yfov then
+ yf = math.rad(numText(yfov, 45))
+ elseif xfov and ar then
+ yf = 2 * math.atan(math.tan(math.rad(numText(xfov, 45)) / 2) / ar)
+ else
+ yf = math.rad(numText(xfov, 45))
+ end
+ if xfov and yfov and not ar then
+ local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2)
+ ar = if ty > 0 then tx / ty else nil
+ end
+ cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) }
+ elseif ortho then
+ local xm, ym = child(ortho, "xmag"), child(ortho, "ymag")
+ local ar = numText(child(ortho, "aspect_ratio"), 1)
+ local x = if xm then numText(xm, 1) else numText(ym, 1) * ar
+ local y = if ym then numText(ym, 1) else numText(xm, 1) / ar
+ cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) }
+ else
+ return nil
+ end
+ table.insert(C.scene.cameras, cam)
+ return #C.scene.cameras
+end
+
+-- light(el) -> light index, or nil and the ambient colour
+local function light(C: Ctx, el: any): (number?, { number }?)
+ local tc = child(el, "technique_common")
+ if not tc then
+ return nil, nil
+ end
+ local amb = child(tc, "ambient")
+ if amb then
+ return nil, color(amb) or { 1, 1, 1, 1 }
+ end
+ local kinds = { directional = "directional", point = "point", spot = "spot" }
+ for k, t in kinds do
+ local l = child(tc, k)
+ if l then
+ local c = color(l) or { 1, 1, 1 }
+ local lt: Types.Light = { name = attr(el, "name") or attr(el, "id"), type = t :: any, color = { c[1], c[2], c[3] }, intensity = 1 }
+ if t == "spot" then
+ local fa = numText(child(l, "falloff_angle"), 180)
+ lt.outerCone = math.clamp(math.rad(fa) / 2, 0, math.pi / 2)
+ lt.innerCone = 0
+ end
+ table.insert(C.scene.lights, lt)
+ local idx = #C.scene.lights
+ if t ~= "directional" then
+ lt.extras = {
+ dae = {
+ constantAttenuation = numText(child(l, "constant_attenuation"), 1),
+ linearAttenuation = numText(child(l, "linear_attenuation"), 0),
+ quadraticAttenuation = numText(child(l, "quadratic_attenuation"), 0),
+ falloffExponent = if t == "spot" then numText(child(l, "falloff_exponent"), 0) else nil,
+ },
+ } :: any
+ end
+ return idx, nil
+ end
+ end
+ return nil, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ nodes
+local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 }
+
+-- the matrix of one transform element's values
+local function xfMatrix(kind: string, v: { number }): { number }
+ if kind == "matrix" then
+ return M.fromRows(v)
+ elseif kind == "translate" then
+ return M.translation(v[1] or 0, v[2] or 0, v[3] or 0)
+ elseif kind == "rotate" then
+ return M.quatMatrix(M.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0))
+ elseif kind == "scale" then
+ return M.scaling(v[1] or 1, v[2] or 1, v[3] or 1)
+ elseif kind == "lookat" then
+ return M.lookat(v)
+ elseif kind == "skew" then
+ return M.skew(v)
+ end
+ return M.identity()
+end
+
+local function compose(xf: { any }): { number }
+ local m = M.identity()
+ for _, x in xf do
+ m = M.mul(m, xfMatrix(x.kind, x.values))
+ end
+ return m
+end
+
+local function setTransform(node: Types.Node, m: { number })
+ local t, r, s = M.decompose(m)
+ node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil
+ if t and r and s then
+ if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
+ node.translation = t
+ end
+ if math.abs(r[4]) < 1 - 1e-9 then
+ node.rotation = r
+ end
+ if math.abs(s[1] - 1) > 1e-7 or math.abs(s[2] - 1) > 1e-7 or math.abs(s[3] - 1) > 1e-7 then
+ node.scale = s
+ end
+ else
+ for i = 1, 16 do
+ if math.abs(m[i] - M.identity()[i]) > 0 then
+ node.matrix = m
+ break
+ end
+ end
+ end
+end
+
+local visitNode: (C: Ctx, el: any) -> number?
+
+local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number
+ table.insert(C.scene.nodes, node)
+ local idx = #C.scene.nodes
+ table.insert(parent.children, idx)
+ return idx
+end
+
+-- the instances of a node: the first of each kind on the node itself, the rest on child nodes
+local function instances(C: Ctx, el: any, node: Types.Node, idx: number)
+ local function slot(kind: string, name: string?): (Types.Node, number)
+ local n: any = node
+ if n[kind] == nil then
+ return node, idx
+ end
+ local extra: Types.Node = { name = name, children = {} }
+ return extra, addChild(C, node, extra)
+ end
+ for _, ch in children(el) do
+ local n = lname(ch)
+ if n == "instance_geometry" then
+ local g = C.ids[urlId(attr(ch, "url")) or ""]
+ if g and lname(g) == "geometry" then
+ local mi = meshFor(C, g, ch, "geom:" .. (attr(g, "id") or ""), nil)
+ if C.err then
+ return
+ end
+ if mi then
+ local target = slot("mesh", attr(g, "name"))
+ target.mesh = mi
+ end
+ end
+ elseif n == "instance_controller" then
+ local ctrl = C.ids[urlId(attr(ch, "url")) or ""]
+ local skinEl = ctrl and child(ctrl, "skin")
+ local morph = ctrl and child(ctrl, "morph")
+ if skinEl then
+ -- the skin's source may be a morph controller
+ local src = C.ids[urlId(attr(skinEl, "source")) or ""]
+ local morphEl = src and lname(src) == "controller" and child(src, "morph")
+ if morphEl then
+ src = C.ids[urlId(attr(morphEl, "source")) or ""]
+ skip(C, "skins over morph controllers (morph dropped)")
+ end
+ if src and lname(src) == "geometry" then
+ local bsm = child(skinEl, "bind_shape_matrix")
+ local bind = if bsm then M.fromRows(numbers(text(bsm), 16) or {}) else nil
+ local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind)
+ if C.err then
+ return
+ end
+ if mi and built then
+ local target, ti = slot("mesh", attr(ctrl, "name"))
+ target.mesh = mi
+ local roots = {}
+ for _, sk in children(ch, "skeleton") do
+ table.insert(roots, urlId(match(text(sk), "^%s*(.-)%s*$")))
+ end
+ table.insert(C.pendingSkins, { node = ti, ctrl = ctrl, skin = skinEl, mesh = mi, built = built, roots = roots, bind = bind })
+ end
+ end
+ elseif morph then
+ local mi = morphMesh(C, ctrl, morph, ch)
+ if C.err then
+ return
+ end
+ if mi then
+ local target = slot("mesh", attr(ctrl, "name"))
+ target.mesh = mi
+ target.weights = C.scene.meshes[mi].weights
+ end
+ end
+ elseif n == "instance_camera" then
+ local cel = C.ids[urlId(attr(ch, "url")) or ""]
+ local ci = cel and lname(cel) == "camera" and camera(C, cel)
+ if ci then
+ local target = slot("camera", C.scene.cameras[ci].name)
+ target.camera = ci
+ end
+ elseif n == "instance_light" then
+ local lel = C.ids[urlId(attr(ch, "url")) or ""]
+ if lel and lname(lel) == "light" then
+ local li, ambient = light(C, lel)
+ if li then
+ local target = slot("light", C.scene.lights[li].name)
+ target.light = li
+ elseif ambient then
+ local ex: any = node.extras or {}
+ ex.dae = ex.dae or {}
+ ex.dae.ambientLight = ambient
+ node.extras = ex
+ end
+ end
+ elseif n == "instance_node" then
+ local target = C.ids[urlId(attr(ch, "url")) or ""]
+ if target and lname(target) == "node" then
+ local ci = visitNode(C, target)
+ if ci then
+ table.insert(node.children, ci)
+ end
+ end
+ end
+ end
+end
+
+visitNode = function(C: Ctx, el: any): number?
+ if C.depth > 256 or #C.scene.nodes > C.limit then
+ C.err = "node tree too deep or too large (instance_node cycle?)"
+ return nil
+ end
+ C.depth += 1
+ local xf = {}
+ for _, ch in children(el) do
+ local n = lname(ch)
+ local want = XFORMS[n]
+ if want then
+ local v = numbers(text(ch), 64) or {}
+ table.insert(xf, { kind = n, sid = attr(ch, "sid"), values = v })
+ end
+ end
+ local node: Types.Node = { name = attr(el, "name") or attr(el, "id"), children = {} }
+ setTransform(node, compose(xf))
+ table.insert(C.scene.nodes, node)
+ local idx = #C.scene.nodes
+ local id = attr(el, "id")
+ C.info[idx] = { xf = xf, sid = attr(el, "sid"), id = id, joint = upper(attr(el, "type") or "") == "JOINT" }
+ if id then
+ C.nodeOf[id] = C.nodeOf[id] or {}
+ table.insert(C.nodeOf[id], idx)
+ end
+ if upper(attr(el, "type") or "") == "JOINT" then
+ node.extras = { dae = { joint = true, sid = attr(el, "sid") } } :: any
+ end
+ instances(C, el, node, idx)
+ for _, ch in children(el, "node") do
+ if C.err then
+ break
+ end
+ local ci = visitNode(C, ch)
+ if ci then
+ table.insert(node.children, ci)
+ end
+ end
+ C.depth -= 1
+ return idx
+end
+
+-- ------------------------------------------------------------------------------------------------ skins
+-- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere
+local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number?
+ local nodes = C.scene.nodes
+ local function search(i: number, depth: number): number?
+ if depth > 300 then
+ return nil
+ end
+ local inf = C.info[i]
+ if inf and (inf.sid == name or (byId and inf.id == name)) then
+ return i
+ end
+ for _, c in nodes[i].children do
+ local r = search(c, depth + 1)
+ if r then
+ return r
+ end
+ end
+ return nil
+ end
+ for _, r in roots do
+ local f = search(r, 0)
+ if f then
+ return f
+ end
+ end
+ for i in nodes do
+ local inf = C.info[i]
+ if inf and (inf.sid == name or inf.id == name) then
+ return i
+ end
+ end
+ for i, n in nodes do
+ if n.name == name then
+ return i
+ end
+ end
+ return nil
+end
+
+local function resolveSkins(C: Ctx)
+ local cache: { [string]: number } = {}
+ for _, ps in C.pendingSkins do
+ local skinEl = ps.skin
+ local jointsEl = child(skinEl, "joints")
+ local names: { string } = {}
+ local byId = false
+ local ibm: any = nil
+ if jointsEl then
+ for _, inp in children(jointsEl, "input") do
+ local sem = upper(attr(inp, "semantic") or "")
+ local srcEl = C.ids[urlId(attr(inp, "source")) or ""]
+ local src = srcEl and lname(srcEl) == "source" and readSource(C, srcEl)
+ if src and sem == "JOINT" then
+ for _, v in src.data do
+ table.insert(names, tostring(v))
+ end
+ byId = child(srcEl, "IDREF_array") ~= nil
+ elseif src and sem == "INV_BIND_MATRIX" then
+ ibm = src
+ end
+ end
+ end
+ local roots: { number } = {}
+ for _, r in ps.roots do
+ for _, ni in C.nodeOf[r] or {} do
+ table.insert(roots, ni)
+ end
+ end
+ local jointNodes: { number } = {}
+ local ok = #names > 0
+ for i, nm in names do
+ local j = findJoint(C, nm, roots, byId)
+ if not j then
+ ok = false
+ break
+ end
+ jointNodes[i] = j
+ end
+ if not ok then
+ skip(C, "skins with unresolved joints")
+ continue
+ end
+ local key = (attr(ps.ctrl, "id") or "") .. "|" .. table.concat(jointNodes, ",")
+ local si = cache[key]
+ if not si then
+ local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes }
+ if ps.bind then
+ local sk: any = skin
+ sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals
+ end
+ if ibm and ibm.comps == 16 and ibm.count >= #names then
+ local b = buffer.create(#names * 64)
+ for i = 0, #names - 1 do
+ local cm = M.fromRows(ibm.data, i * 16 + 1)
+ for k = 1, 16 do
+ buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k])
+ end
+ end
+ local acc = Scene.accessor(b, "f32", 16, #names)
+ acc.matrix = true
+ skin.inverseBindMatrices = acc
+ end
+ if roots[1] then
+ skin.skeleton = roots[1]
+ end
+ table.insert(C.scene.skins, skin)
+ si = #C.scene.skins
+ cache[key] = si
+ end
+ C.scene.nodes[ps.node].skin = si
+ -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh)
+ local mesh = C.scene.meshes[ps.mesh]
+ if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then
+ continue
+ end
+ local vw = child(skinEl, "vertex_weights")
+ if not vw then
+ continue
+ end
+ local jOff, wOff, wSrc = 0, 1, nil
+ local stride = 1
+ for _, inp in children(vw, "input") do
+ local sem = upper(attr(inp, "semantic") or "")
+ local off = tonumber(attr(inp, "offset") or "") or 0
+ stride = math.max(stride, off + 1)
+ if sem == "JOINT" then
+ jOff = off
+ elseif sem == "WEIGHT" then
+ wOff = off
+ wSrc = sourceById(C, attr(inp, "source"))
+ end
+ end
+ local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {}
+ local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {}
+ local wdata = wSrc and wSrc.data or {}
+ local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4
+ local at = 0
+ for pi, c in vcount do
+ local list = {}
+ for _ = 1, math.floor(c) do
+ local j, w = v[at + jOff + 1], v[at + wOff + 1]
+ at += stride
+ local wv = if w then wdata[w + 1] else nil
+ if j and j >= 0 and j < #names and type(wv) == "number" and wv > 0 then
+ table.insert(list, { j, wv })
+ end
+ end
+ table.sort(list, function(a: { number }, b: { number }): boolean
+ return a[2] > b[2]
+ end)
+ local total = 0
+ for k = 1, math.min(4, #list) do
+ total += list[k][2]
+ end
+ local e = {}
+ for k = 1, math.min(4, #list) do
+ e[k * 2 - 1], e[k * 2] = list[k][1], list[k][2] / total
+ end
+ per[pi] = e
+ end
+ for pi, prim in mesh.primitives do
+ local posIndex = ps.built[pi] and ps.built[pi].posIndex
+ local n = prim.attributes.POSITION.count
+ if posIndex and #posIndex == n then
+ local jt = if #names < 256 then "u8" else "u16"
+ local js = if jt == "u8" then 1 else 2
+ local jb = buffer.create(n * 4 * js)
+ local wb = buffer.create(n * 16)
+ for vi = 0, n - 1 do
+ local e = per[posIndex[vi + 1] + 1]
+ for k = 0, 3 do
+ local j, w = 0, 0
+ if e and e[k * 2 + 1] then
+ j, w = e[k * 2 + 1], e[k * 2 + 2]
+ end
+ if js == 1 then
+ buffer.writeu8(jb, vi * 4 + k, j)
+ else
+ buffer.writeu16(jb, (vi * 4 + k) * 2, j)
+ end
+ buffer.writef32(wb, (vi * 4 + k) * 4, w)
+ end
+ end
+ prim.attributes.JOINTS_0 = Scene.accessor(jb, jt, 4, n)
+ prim.attributes.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n)
+ end
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ animations
+type Curve = { input: { number }, output: { number }, stride: number, interp: { string }, member: number?, xf: any }
+
+local function sample(c: Curve, t: number): { number }
+ local inp, out, st = c.input, c.output, c.stride
+ local n = #inp
+ local function at(i: number): { number }
+ local r = table.create(st)
+ for k = 1, st do
+ r[k] = out[(i - 1) * st + k] or 0
+ end
+ return r
+ end
+ if n == 0 then
+ return {}
+ end
+ if t <= inp[1] then
+ return at(1)
+ end
+ if t >= inp[n] then
+ return at(n)
+ end
+ local lo, hi = 1, n
+ while hi - lo > 1 do
+ local mid = (lo + hi) // 2
+ if inp[mid] <= t then
+ lo = mid
+ else
+ hi = mid
+ end
+ end
+ local a, b = at(lo), at(hi)
+ if c.interp[lo] == "STEP" then
+ return a
+ end
+ local span = inp[hi] - inp[lo]
+ local f = if span > 0 then (t - inp[lo]) / span else 0
+ for k = 1, st do
+ a[k] += (b[k] - a[k]) * f
+ end
+ return a
+end
+
+-- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element
+local function target(C: Ctx, s: string): ({ number }?, any, number?)
+ -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/"
+ local id, sids = match(s, "^([^/]*)/(.*)$")
+ if not id then
+ return nil, nil, nil
+ end
+ local spath, rest = match(sids, "^([^%.%(]*)(.*)$")
+ if not spath then
+ return nil, nil, nil
+ end
+ local parts = string.split(id .. "/" .. spath, "/")
+ local nodes = C.nodeOf[parts[1]]
+ if not nodes or #parts < 2 then
+ return nil, nil, nil
+ end
+ local sid = parts[#parts]
+ local info = C.info[nodes[1]]
+ local xf: any = nil
+ for _, x in info.xf do
+ if x.sid == sid then
+ xf = x
+ break
+ end
+ end
+ if not xf then
+ return nil, nil, nil
+ end
+ local member: number? = nil
+ if rest and rest ~= "" then
+ local m1 = match(rest, "^%.(.+)$")
+ if m1 then
+ member = MEMBER[upper(m1)]
+ if not member then
+ return nil, nil, nil
+ end
+ else
+ local i, j = match(rest, "^%((%d+)%)%((%d+)%)$")
+ if i then
+ member = tonumber(i) :: number * 4 + tonumber(j) :: number + 1
+ else
+ local k = match(rest, "^%((%d+)%)$")
+ if not k then
+ return nil, nil, nil
+ end
+ member = tonumber(k) :: number + 1
+ end
+ end
+ end
+ return nodes, xf, member
+end
+
+-- the channels of one (recursively) -> curves grouped by node
+local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number)
+ if depth > 64 then
+ return
+ end
+ for _, ch in children(anim, "channel") do
+ local smp = C.ids[urlId(attr(ch, "source")) or ""]
+ local nodes, xf, member = target(C, attr(ch, "target") or "")
+ if smp and lname(smp) == "sampler" and nodes and xf then
+ local input, output, interp: any = nil, nil, nil
+ for _, inp in children(smp, "input") do
+ local sem = upper(attr(inp, "semantic") or "")
+ local src = sourceById(C, attr(inp, "source"))
+ if sem == "INPUT" then
+ input = src
+ elseif sem == "OUTPUT" then
+ output = src
+ elseif sem == "INTERPOLATION" then
+ interp = src
+ end
+ end
+ if input and output and input.count > 0 then
+ local stride = if member then 1 else #xf.values
+ local ins = {}
+ for i = 1, input.count do
+ local x = input.data[(i - 1) * input.comps + 1]
+ ins[i] = if type(x) == "number" then x else 0
+ end
+ local outs = output.data
+ if #outs >= input.count * stride then
+ local ip = {}
+ if interp then
+ for i = 1, input.count do
+ ip[i] = upper(tostring(interp.data[i] or "LINEAR"))
+ end
+ end
+ local curve: Curve = { input = ins, output = outs, stride = stride, interp = ip, member = member, xf = xf }
+ for _, ni in nodes do
+ if not byNode[ni] then
+ byNode[ni] = {}
+ table.insert(order, ni)
+ end
+ table.insert(byNode[ni], curve)
+ end
+ end
+ end
+ elseif not (nodes and xf) then
+ skip(C, "animation channels on other targets")
+ end
+ end
+ for _, sub2 in children(anim, "animation") do
+ collect(C, sub2, byNode, order, depth + 1)
+ end
+end
+
+local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, order: { number }): Types.Animation?
+ local channels: { Types.Channel } = {}
+ for _, ni in order do
+ local curves = byNode[ni]
+ local info = C.info[ni]
+ -- the union of the key times, plus subdivisions of rotations over 90 degrees
+ local set: { [number]: boolean } = {}
+ local times: { number } = {}
+ local function add(t: number)
+ if not set[t] then
+ set[t] = true
+ table.insert(times, t)
+ end
+ end
+ for _, c in curves do
+ for i, t in c.input do
+ add(t)
+ if i > 1 and c.xf.kind == "rotate" and (c.member == 4 or c.member == nil) then
+ local k = if c.member then 1 else 4
+ local a, b = c.output[(i - 2) * c.stride + k] or 0, c.output[(i - 1) * c.stride + k] or 0
+ local steps = math.min(math.ceil(math.abs(b - a) / 90), 64)
+ for s = 1, steps - 1 do
+ add(c.input[i - 1] + (t - c.input[i - 1]) * s / steps)
+ end
+ end
+ end
+ if #times > C.limit then
+ return nil
+ end
+ end
+ table.sort(times)
+ local n = #times
+ local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12)
+ local prev: { number }? = nil
+ for i, t in times do
+ -- this time's values of each animated element
+ local xf = {}
+ for k, x in info.xf do
+ xf[k] = { kind = x.kind, values = table.clone(x.values) }
+ end
+ for _, c in curves do
+ local v = sample(c, t)
+ local k = table.find(info.xf, c.xf)
+ if k then
+ local vals = xf[k].values
+ if c.member then
+ vals[c.member] = v[1] or 0
+ else
+ for j = 1, #v do
+ vals[j] = v[j]
+ end
+ end
+ end
+ end
+ local tr, ro, sc = M.decompose(compose(xf))
+ tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 }
+ if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then
+ ro = { -ro[1], -ro[2], -ro[3], -ro[4] }
+ end
+ prev = ro
+ for k = 1, 3 do
+ buffer.writef32(tb, ((i - 1) * 3 + k - 1) * 4, tr[k])
+ buffer.writef32(sb, ((i - 1) * 3 + k - 1) * 4, sc[k])
+ end
+ for k = 1, 4 do
+ buffer.writef32(rb, ((i - 1) * 4 + k - 1) * 4, ro[k])
+ end
+ end
+ local ib = buffer.create(n * 4)
+ for i, t in times do
+ buffer.writef32(ib, (i - 1) * 4, t)
+ end
+ local input = Scene.accessor(ib, "f32", 1, n)
+ table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" })
+ table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" })
+ table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" })
+ -- the node is now TRS-driven
+ local node = C.scene.nodes[ni]
+ if node.matrix then
+ setTransform(node, node.matrix)
+ end
+ end
+ if #channels == 0 then
+ return nil
+ end
+ return { name = name, channels = channels }
+end
+
+local function animations(C: Ctx, root: any)
+ local libs = children(root, "library_animations")
+ if #libs == 0 then
+ return
+ end
+ local clipsLib = child(root, "library_animation_clips")
+ local clips = clipsLib and children(clipsLib, "animation_clip") or {}
+ if #clips > 0 then
+ for _, clip in clips do
+ local byNode, order = {}, {}
+ for _, ia in children(clip, "instance_animation") do
+ local a = C.ids[urlId(attr(ia, "url")) or ""]
+ if a and lname(a) == "animation" then
+ collect(C, a, byNode, order, 0)
+ end
+ end
+ local anim = bake(C, attr(clip, "name") or attr(clip, "id"), byNode, order)
+ if anim then
+ table.insert(C.scene.animations, anim)
+ end
+ end
+ return
+ end
+ local byNode, order = {}, {}
+ local name: string? = nil
+ local count = 0
+ for _, lib in libs do
+ for _, a in children(lib, "animation") do
+ collect(C, a, byNode, order, 0)
+ count += 1
+ name = name or attr(a, "name") or attr(a, "id")
+ end
+ end
+ local anim = bake(C, if count == 1 then name else nil, byNode, order)
+ if anim then
+ table.insert(C.scene.animations, anim)
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ scene
+function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?)
+ local root = doc and doc.root
+ if not root or lname(root) ~= "COLLADA" then
+ return nil, Err.new(Err.CORRUPT, "no root element")
+ end
+ local scene = Scene.new()
+ local C: Ctx = {
+ doc = doc,
+ ids = {},
+ fetch = fetch,
+ scene = scene,
+ limit = opts and opts.maxVertices or 2 ^ 25,
+ vertices = 0,
+ flipV = not (opts and opts.flipV == false),
+ triangulate = not (opts and opts.triangulate == false),
+ sources = {},
+ materials = {},
+ textures = {},
+ images = {},
+ meshes = {},
+ skins = {},
+ posIndex = {},
+ nodeOf = {},
+ info = {},
+ pendingSkins = {},
+ skipped = {},
+ err = nil,
+ depth = 0,
+ }
+ for _, el in Xml.descendants(root) do
+ local id = el.attrs.id
+ -- duplicate ids: the first one, unless it is empty (some exporters write before the real one)
+ if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then
+ C.ids[id] = el
+ end
+ end
+ -- asset: up axis, unit
+ local asset = child(root, "asset")
+ local up = asset and child(asset, "up_axis")
+ local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP"
+ scene.meta.up = if upAxis == "Z_UP" then "z" elseif upAxis == "X_UP" then "x" :: any else "y"
+ local unit = asset and child(asset, "unit")
+ local meter = unit and attr(unit, "meter")
+ scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1
+ -- the instanced visual scene (else the first one)
+ local vsId: string? = nil
+ local sceneEl = child(root, "scene")
+ local ivs = sceneEl and child(sceneEl, "instance_visual_scene")
+ if ivs then
+ vsId = urlId(attr(ivs, "url"))
+ end
+ local vs = vsId and C.ids[vsId]
+ if not vs or lname(vs) ~= "visual_scene" then
+ local lib = child(root, "library_visual_scenes")
+ vs = lib and child(lib, "visual_scene")
+ end
+ if vs then
+ for _, n in children(vs, "node") do
+ local idx = visitNode(C, n)
+ if C.err then
+ break
+ end
+ if idx then
+ table.insert(scene.roots, idx)
+ end
+ end
+ end
+ if C.err then
+ return nil, Err.new(if find(C.err :: string, "limit", 1, true) then Err.LIMIT else Err.CORRUPT, C.err :: string)
+ end
+ resolveSkins(C)
+ animations(C, root)
+ if C.err then
+ return nil, Err.new(Err.CORRUPT, C.err :: string)
+ end
+ local contributor = asset and child(asset, "contributor")
+ local tool = contributor and child(contributor, "authoring_tool")
+ scene.meta.source = {
+ format = "dae",
+ version = attr(root, "version"),
+ upAxis = upAxis,
+ authoringTool = if tool then text(tool) else nil,
+ skipped = if next(C.skipped) then C.skipped else nil,
+ }
+ return scene, nil
+end
+
+return Read
diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau
new file mode 100644
index 0000000..86e6d2a
--- /dev/null
+++ b/src/Formats/model/dae/Write.luau
@@ -0,0 +1,376 @@
+--!strict
+-- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips
+-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n
+-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its
+-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras;
+-- lights. Not written: skins, morph targets, animations.
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+local Base64 = require("@formats/codecs/Base64")
+local M = require("@formats/model/dae/Math")
+
+local Write = {}
+
+local Scene = Types.Scene
+local format, concat = string.format, table.concat
+local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" }
+
+local function f(v: number): string
+ if v ~= v or v == math.huge or v == -math.huge then
+ return "0"
+ end
+ if v == math.floor(v) and math.abs(v) < 1e15 then
+ return format("%d", v)
+ end
+ return format("%.9g", v)
+end
+local function list(v: { number }): string
+ local out = table.create(#v)
+ for i, x in v do
+ out[i] = f(x)
+ end
+ return concat(out, " ")
+end
+local function esc(s: string): string
+ return Xml.escapeAttr(s)
+end
+local function nameAttr(s: string?): string
+ return if s then ' name="' .. esc(s) .. '"' else ""
+end
+
+-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind
+local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?)
+ local n = prim.attributes.POSITION.count
+ local idx: { number } = {}
+ if prim.indices then
+ local get = Scene.reader(prim.indices)
+ if not get then
+ return nil, nil, nil
+ end
+ for i = 0, prim.indices.count - 1 do
+ idx[i + 1] = get(i, 0)
+ end
+ else
+ for i = 0, n - 1 do
+ idx[i + 1] = i
+ end
+ end
+ for _, i in idx do
+ if i < 0 or i >= n then
+ return nil, nil, nil
+ end
+ end
+ local mode = prim.mode or "triangles"
+ if mode == "triangles" then
+ local m = #idx - #idx % 3
+ return table.move(idx, 1, m, 1, {}), "triangles", nil
+ elseif mode == "triangle_strip" or mode == "triangle_fan" then
+ local out = {}
+ for k = 1, #idx - 2 do
+ if mode == "triangle_fan" then
+ table.insert(out, idx[1])
+ table.insert(out, idx[k + 1])
+ table.insert(out, idx[k + 2])
+ elseif k % 2 == 1 then
+ table.insert(out, idx[k])
+ table.insert(out, idx[k + 1])
+ table.insert(out, idx[k + 2])
+ else
+ table.insert(out, idx[k + 1])
+ table.insert(out, idx[k])
+ table.insert(out, idx[k + 2])
+ end
+ end
+ return out, "triangles", nil
+ elseif mode == "lines" then
+ local m = #idx - #idx % 2
+ return table.move(idx, 1, m, 1, {}), "lines", nil
+ elseif mode == "line_strip" or mode == "line_loop" then
+ local out = {}
+ for k = 1, #idx - 1 do
+ table.insert(out, idx[k])
+ table.insert(out, idx[k + 1])
+ end
+ if mode == "line_loop" and #idx > 2 then
+ table.insert(out, idx[#idx])
+ table.insert(out, idx[1])
+ end
+ return out, "lines", nil
+ elseif mode == "polygons" and prim.faces then
+ local get = Scene.reader(prim.faces)
+ if not get then
+ return nil, nil, nil
+ end
+ local sizes = {}
+ local total = 0
+ for i = 0, prim.faces.count - 1 do
+ sizes[i + 1] = get(i, 0)
+ total += sizes[i + 1]
+ end
+ if total ~= #idx then
+ return nil, nil, nil
+ end
+ return idx, "polylist", sizes
+ end
+ return nil, nil, nil
+end
+
+local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean)
+ local get = Scene.reader(acc)
+ if not get then
+ return
+ end
+ local vals = table.create(acc.count * comps)
+ local n = 0
+ for i = 0, acc.count - 1 do
+ for c = 0, comps - 1 do
+ n += 1
+ local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0)
+ if flipV and c == 1 then
+ v = 1 - v
+ end
+ vals[n] = f(v)
+ end
+ end
+ table.insert(out, format('%s', id, id, n, concat(vals, " ")))
+ local ps = {}
+ for c = 1, comps do
+ ps[c] = format('', params[c] or "V")
+ end
+ table.insert(out, format('%s\n', id, acc.count, comps, concat(ps)))
+end
+
+local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string
+ if tex then
+ return format('<%s>%s>', tag, tex, uv or 0, tag)
+ end
+ local v = c or { 0, 0, 0, 1 }
+ return format("<%s>%s %s %s %s%s>", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag)
+end
+
+function Write.build(scene: Types.Scene, opts: any?): string?
+ local files = opts and type(opts.files) == "table" and opts.files or nil
+ local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
+ local flipV = not (opts and opts.flipV == false)
+ local out: { string } = {}
+ local function w(s: string)
+ table.insert(out, s)
+ end
+ w('\n\n')
+ local meta = scene.meta or {}
+ local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP"
+ w(format('formats-luau1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up))
+ -- images
+ local imageId: { [number]: string } = {}
+ if #scene.textures > 0 then
+ w("\n")
+ for i, tex in scene.textures do
+ local uri: string? = nil
+ if tex.data then
+ if files then
+ uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png")
+ files[uri :: string] = tex.data
+ else
+ uri = Base64.dataUri(tex.data, tex.mime or "image/png")
+ end
+ elseif tex.uri then
+ uri = tex.uri
+ end
+ if uri then
+ local id = "image" .. i
+ imageId[i] = id
+ w(format('%s\n', id, nameAttr(tex.name), Xml.escape(uri :: string)))
+ end
+ end
+ w("\n")
+ end
+ -- effects + materials
+ if #scene.materials > 0 then
+ w("\n")
+ for i, mat in scene.materials do
+ local ph: any = mat.extras and mat.extras.phong or {}
+ local params = {}
+ local function texParam(ref: Types.TextureRef?): (string?, number?)
+ if not ref or not imageId[ref.texture] then
+ return nil, nil
+ end
+ local sid = "tex" .. ref.texture
+ if not params[sid] then
+ params[sid] = true
+ table.insert(params, format('%s%s-surface', sid, imageId[ref.texture], sid, sid))
+ end
+ return sid, ref.texCoord
+ end
+ local dtex, duv = texParam(mat.baseColorTexture)
+ local etex, euv = texParam(mat.emissiveTexture)
+ local ntex, nuv = texParam(mat.normalTexture)
+ local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil
+ local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong"
+ local body = {}
+ local bc = mat.baseColor
+ if unlit then
+ table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil))
+ else
+ table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv))
+ table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil))
+ table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv))
+ if model == "phong" then
+ table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil))
+ local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0)
+ table.insert(body, format("%s", f(sh)))
+ end
+ end
+ if (bc[4] or 1) < 1 then
+ table.insert(body, '1 1 1 1')
+ table.insert(body, format("%s", f(bc[4])))
+ end
+ local extra = ""
+ if ntex or mat.doubleSided then
+ extra = "" .. (if ntex then format('', ntex, nuv or 0) else "") .. (if mat.doubleSided then "1" else "") .. ""
+ end
+ w(format('%s<%s>%s%s>%s\n', i, concat(params), model, concat(body), model, extra))
+ end
+ w("\n\n")
+ for i, mat in scene.materials do
+ w(format('\n', i, nameAttr(mat.name), i))
+ end
+ w("\n")
+ end
+ -- geometries: one per primitive
+ local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {}
+ w("\n")
+ for mi, mesh in scene.meshes do
+ geoms[mi] = {}
+ for pi, prim in mesh.primitives do
+ local pos = prim.attributes and prim.attributes.POSITION
+ if not pos then
+ continue
+ end
+ local idx, kind, sizes = corners(prim)
+ if not idx or not kind or #idx == 0 then
+ continue
+ end
+ local id = format("mesh%d-%d", mi, pi)
+ w(format('\n', id, nameAttr(mesh.name)))
+ source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false)
+ local ins = { format('', id) }
+ if prim.attributes.NORMAL then
+ source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false)
+ table.insert(ins, format('', id))
+ end
+ local sets = 0
+ for k = 0, 7 do
+ local a = prim.attributes["TEXCOORD_" .. k]
+ if not a then
+ break
+ end
+ source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV)
+ table.insert(ins, format('', id, k, k))
+ sets += 1
+ end
+ for k = 0, 7 do
+ local a = prim.attributes["COLOR_" .. k]
+ if not a then
+ break
+ end
+ local c = if a.components >= 4 then 4 else 3
+ source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false)
+ table.insert(ins, format('', id, k, k))
+ end
+ w(format('\n', id, id))
+ local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else ""
+ local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number })
+ w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins)))
+ if sizes then
+ w("" .. list(sizes) .. "")
+ end
+ w("