From a7b4a69177df7dd1270bd467143176bec560356d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:27 -0500 Subject: [PATCH] ws-3d2/dae: model/dae (Collada 1.4/1.5 + .zae) read: geometry (all primitive kinds, shared offsets), common-profile materials + images, node tree (all transform elements, instance_node), skin + morph controllers, cameras, lights, animations resampled to TRS channels (clips); write: Collada 1.4.1 / .zae (meshes, materials, images, nodes, cameras, lights). Tests against assimp's Collada models (nixpkgs assimp.src at fixture time), assimp exports of glTF samples vs their originals, assimp reading our output, round trips, fuzz Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/dae/Math.luau | 188 +++ src/Formats/model/dae/Read.luau | 1879 ++++++++++++++++++++++++++++++ src/Formats/model/dae/Write.luau | 376 ++++++ src/Formats/model/dae/init.luau | 206 ++++ tests/model/dae.luau | 581 +++++++++ tools/fixtures/_dae_encode.luau | 36 + tools/fixtures/dae.py | 106 ++ 9 files changed, 3385 insertions(+) create mode 100644 src/Formats/model/dae/Math.luau create mode 100644 src/Formats/model/dae/Read.luau create mode 100644 src/Formats/model/dae/Write.luau create mode 100644 src/Formats/model/dae/init.luau create mode 100644 tests/model/dae.luau create mode 100644 tools/fixtures/_dae_encode.luau create mode 100644 tools/fixtures/dae.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..6560539 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| model | 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 | 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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..bd40fa6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,6 +194,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "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 = "gltf", category = "model", 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>', tag, tex, uv or 0, tag) + end + local v = c or { 0, 0, 0, 1 } + return format("<%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\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("

" .. list(idx) .. "

\n
\n") + table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets }) + end + end + w("
\n") + -- cameras / lights + if #scene.cameras > 0 then + w("\n") + for i, cam in scene.cameras do + local body: string + if cam.type == "orthographic" then + body = format("%s%s%s%s", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000)) + else + body = format("%s%s%s%s", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("%s", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000)) + end + w(format('%s\n', i, nameAttr(cam.name), body)) + end + w("\n") + end + if #scene.lights > 0 then + w("\n") + for i, l in scene.lights do + local c = l.color or { 1, 1, 1 } + local k = l.intensity or 1 + local col = format("%s %s %s", f(c[1] * k), f(c[2] * k), f(c[3] * k)) + local body = if l.type == "spot" then format("%s100%s0", col, f(math.deg(l.outerCone or math.pi / 4) * 2)) + elseif l.type == "point" then format("%s100", col) + else format("%s", col) + w(format('%s\n', i, nameAttr(l.name), body)) + end + w("\n") + end + -- the node tree + w('\n') + local seen: { [number]: boolean } = {} + local function node(i: number, depth: number) + local n = scene.nodes[i] + if not n or seen[i] or depth > 512 then + return + end + seen[i] = true + w(format('%s', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n))))) + if n.mesh and geoms[n.mesh] then + for _, g in geoms[n.mesh] do + if g.material then + local binds = {} + for k = 0, g.sets - 1 do + table.insert(binds, format('', k, k)) + end + w(format('%s', g.id, g.material, g.material, concat(binds))) + else + w(format('', g.id)) + end + end + end + if n.camera and scene.cameras[n.camera] then + w(format('', n.camera)) + end + if n.light and scene.lights[n.light] then + w(format('', n.light)) + end + w("\n") + for _, c in n.children or {} do + node(c, depth + 1) + end + w("\n") + end + local roots = scene.roots + if not roots or #roots == 0 then + local isChild = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + isChild[c] = true + end + end + roots = {} + for i in scene.nodes do + if not isChild[i] then + table.insert(roots, i) + end + end + end + for _, r in roots do + node(r, 0) + end + w('\n\n
\n') + return concat(out) +end + +return Write diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau new file mode 100644 index 0000000..1e245b1 --- /dev/null +++ b/src/Formats/model/dae/init.luau @@ -0,0 +1,206 @@ +--!strict +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its +-- manifest.xml and the images). New code. +-- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input +-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), +-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / +-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> +-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), +-- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix / +-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances +-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under +-- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph +-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; +-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as +-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE +-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, +-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" +-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left +-- origin (opts.flipV = false keeps Collada's). +-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. +-- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves +-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than +-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Zip = require("@formats/containers/Zip") +local Read = require("@formats/model/dae/Read") +local Write = require("@formats/model/dae/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Dae = { + name = "dae", + category = "model", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths + files: { [string]: any }?, -- or: the files by uri / base name + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention) + maxVertices: number?, -- refuse more output vertices / array values (default 2^25) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Dae.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + if string.sub(head, 1, 4) == "PK\3\4" then + local nlen = string.byte(head, 27) or 0 + local name = string.lower(string.sub(head, 31, 30 + nlen)) + if string.find(name, "%.dae$") or name == "manifest.xml" then + return 0.95 + end + return 0 + end + -- UTF-16 files: drop the zero bytes + if string.find(string.sub(head, 1, 4), "\0", 1, true) then + head = string.gsub(head, "%z", "") + end + if string.find(head, ", else the first .dae entry +local function zae(r: Bytes.Reader): (any, string?, Err.Err?) + local zip, err = Zip.open(r) + if not zip then + return nil, nil, err + end + local main: string? = nil + local manifest = zip:readString("manifest.xml") + if manifest then + local d = Xml.decode(manifest) + local rootEl = d and d.root and Xml.child(d.root, "dae_root") + if rootEl then + main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") + main = main and string.gsub(main, "^%./", "") + end + end + if not main or not zip:find(main) then + main = nil + for _, e in zip:list() do + if string.find(string.lower(e.name), "%.dae$") then + main = e.name + break + end + end + end + if not main then + return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae") + end + local text, rerr = zip:readString(main) + if not text then + return nil, nil, rerr + end + return zip, text, nil +end + +function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text: string + local zip: any = nil + if r:peek(4) == "PK\3\4" then + local z, t, err = zae(r) + if not z then + return nil, err + end + zip, text = z, t :: string + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local scene, err = Read.scene(doc, fetcher(opts, zip), opts) + if not scene then + return nil, err + end + if zip and scene.meta.source then + scene.meta.source.zae = true + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Dae.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.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "zae" then + -- a zip: manifest.xml, the .dae and its images + local files = {} + local o = table.clone(opts) + o.files = files + o.name = "model.dae" + local text = Write.build(scene, o) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + local w = Zip.writer() + w:add("manifest.xml", '\n./model.dae\n') + w:add("model.dae", text) + local names = {} + for name in files do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + w:add(name, files[name], { method = "store" }) + end + return w:finish() + end + local text = Write.build(scene, opts) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + return buffer.fromstring(text), nil +end + +return Dae diff --git a/tests/model/dae.luau b/tests/model/dae.luau new file mode 100644 index 0000000..d27e246 --- /dev/null +++ b/tests/model/dae.luau @@ -0,0 +1,581 @@ +-- model/dae tests: assimp's Collada test models (triangles / polylist / polygons / tristrips, UTF-16 and BOM files, +-- decimal commas, 2 UV sets, vertex colours, instance_node, cameras, lights, nested / clipped / full-rotation +-- animations, skins, .zae) and glTF samples exported by assimp's Collada exporter, against `assimp info -r` (meshes, +-- faces, bounds in assimp's space, materials, animations, cameras, lights), and against the glTF originals read by +-- model/gltf (skinned rest-pose bounds, joints, every LINEAR animation key); our writer's output read back by assimp +-- (dae_xcheck) and by us (round trips, .dae and .zae); polygons kept with triangulate = false; textures decoded lazily +-- at the api layer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dae.py. +local T = require("@tests/T") +local F = require("@formats") +local Dae = require("@formats/model/dae") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/dae_cases") +local Xcheck = require("@tests/gen/dae_xcheck") + +local Scene = Types.Scene +local t = T.suite("dae") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Dae.decode(Bytes.reader(b), opts) +end + +t:eq(Dae.name, "dae", "name") +t:eq(Dae.category, "model", "category") +t:check(Dae.caps.decode and Dae.caps.encode and table.find(Dae.extensions, "zae"), "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end +local function nearV(a: { number }, b: { number }, eps: number): boolean + for i = 1, #b do + if not near(a[i], b[i], eps) then + return false + end + end + return #a == #b +end +local function fmt(v: { number }?): string + if not v then + return "-" + end + return string.format("(%.4g %.4g %.4g)", v[1], v[2], v[3]) +end + +-- assimp's counts: one mesh per primitive reached (instances of one primitive once), faces as stored +local function counts(scene: any): (number, number) + local prims, faces = 0, 0 + local seen = {} + for _, pl in Scene.flatten(scene) do + if not seen[pl.primitive] then + seen[pl.primitive] = true + local p = pl.primitive + prims += 1 + if p.mode == "polygons" then + faces += p.faces.count + elseif p.mode == "triangles" then + faces += p.indices.count // 3 + elseif p.mode == "lines" then + faces += p.indices.count // 2 + end + end + end + return prims, faces +end + +local function inverse(m: { number }): { number } + -- general 4x4 inverse (column-major; cofactors) + local inv = table.create(16, 0) + local a = m + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + for i = 1, 16 do + inv[i] /= det + end + return inv +end + +local function grow(lo: { number }, hi: { number }, x: number, y: number, z: number) + lo[1], lo[2], lo[3] = math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) + hi[1], hi[2], hi[3] = math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) +end +local function apply(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 bounds `assimp info` prints: its Collada importer puts the up-axis rotation and unit scale on the root node, +-- and Info.cpp accumulates node transforms as local * parent (sic); skinned meshes without their bind shape matrix +local function assimpBounds(scene: any, written: boolean?): ({ number }?, { number }?) + local u = scene.meta.unit or 1 + local root = if scene.meta.up == "z" then { u, 0, 0, 0, 0, 0, -u, 0, 0, u, 0, 0, 0, 0, 0, 1 } + elseif scene.meta.up == "x" then { 0, u, 0, 0, -u, 0, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 } + else { u, 0, 0, 0, 0, u, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 } + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local seen = {} + local function visit(i: number, parent: { number }) + local n = scene.nodes[i] + if seen[i] then + return + end + seen[i] = true + local m = Scene.mul(Scene.nodeMatrix(n), parent) + local mesh = n.mesh and scene.meshes[n.mesh] + if mesh then + local mm = m + local skin = n.skin and scene.skins[n.skin] + if skin and not written and skin.extras and skin.extras.dae and skin.extras.dae.bindShapeMatrix then + mm = Scene.mul(m, inverse(skin.extras.dae.bindShapeMatrix)) + end + for _, p in mesh.primitives do + local pos = p.attributes.POSITION + for v = 0, pos.count - 1 do + grow(lo, hi, apply(mm, buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8))) + end + end + end + for _, c in n.children do + visit(c, m) + end + end + for _, r in scene.roots do + visit(r, root) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- world matrices (correct order) of every node +local function worlds(scene: any): { [number]: { number } } + local w = {} + local function visit(i: number, parent: { number }) + if w[i] then + return + end + w[i] = Scene.mul(parent, Scene.nodeMatrix(scene.nodes[i])) + for _, c in scene.nodes[i].children do + visit(c, w[i]) + end + end + for _, r in scene.roots do + visit(r, Scene.IDENTITY) + end + return w +end + +-- bounds of the rest pose with skins applied (glTF semantics: skinned vertices = sum w * world(joint) * ibm * v) +local function posedBounds(scene: any): ({ number }?, { number }?) + local w = worlds(scene) + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for ni, m in w do + local n = scene.nodes[ni] + local mesh = n.mesh and scene.meshes[n.mesh] + if mesh then + local skin = n.skin and scene.skins[n.skin] + local jm = {} + if skin then + local ibm = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, jn in skin.joints do + local inv = table.create(16, 0) + for k = 1, 16 do + inv[k] = if ibm then ibm(j - 1, k - 1) else (if k % 5 == 1 then 1 else 0) + end + jm[j - 1] = Scene.mul(w[jn] or Scene.IDENTITY, inv) + end + end + for _, p in mesh.primitives do + local pos = p.attributes.POSITION + local J = skin and p.attributes.JOINTS_0 and Scene.reader(p.attributes.JOINTS_0) + local W = skin and p.attributes.WEIGHTS_0 and Scene.reader(p.attributes.WEIGHTS_0) + 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) + if J and W then + local sx, sy, sz = 0, 0, 0 + for k = 0, 3 do + local wt = W(v, k) + if wt > 0 then + local px, py, pz = apply(jm[J(v, k)] or Scene.IDENTITY, x, y, z) + sx, sy, sz = sx + wt * px, sy + wt * py, sz + wt * pz + end + end + grow(lo, hi, sx, sy, sz) + else + grow(lo, hi, apply(m, x, y, z)) + end + end + end + end + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +local function lightCount(scene: any): number + local n = #scene.lights + for _, node in scene.nodes do + if node.extras and node.extras.dae and node.extras.dae.ambientLight then + n += 1 + end + end + return n +end + +-- a channel's value at time tm (LINEAR; rotations nlerped) +local function channelAt(ch: any, tm: number): { number } + local inp, out = Scene.reader(ch.input) :: any, Scene.reader(ch.output) :: any + local n, c = ch.input.count, ch.output.components + local function at(i: number): { number } + local r = {} + for k = 0, c - 1 do + r[k + 1] = out(i, k) + end + return r + end + if tm <= inp(0, 0) then + return at(0) + end + for i = 1, n - 1 do + local t1 = inp(i, 0) + if tm <= t1 + 1e-6 then + local t0 = inp(i - 1, 0) + local f = if t1 > t0 then math.clamp((tm - t0) / (t1 - t0), 0, 1) else 1 + local a, b = at(i - 1), at(i) + for k = 1, c do + a[k] += (b[k] - a[k]) * f + end + return a + end + end + return at(n - 1) +end + +local checked = { assimp = 0, bounds = 0, gltf = 0, keys = 0, roundTrips = 0, xcheck = 0 } +local decoded: { [number]: any } = {} +local samples: { string } = {} +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + t:eq(scene.meta.source.format, "dae", c.name .. ": source") + local ref = c.assimp + local prims, faces = counts(scene) + if ref and not ref.failed then + -- assimp builds a placeholder skeleton mesh for scenes without meshes + if prims > 0 then + t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, ref.faces, c.name .. ": faces (assimp)") + local lo, hi = assimpBounds(scene) + local ok = lo ~= nil and hi ~= nil and nearV(lo :: any, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4) + t:check(ok, string.format("%s: bounds %s %s, assimp %s %s", c.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max))) + checked.bounds += 1 + -- assimp adds a default material when a mesh has none + t:check(ref.materials - #scene.materials == 0 or ref.materials - #scene.materials == 1, c.name .. ": materials (assimp)") + end + t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)") + t:eq(lightCount(scene), ref.lights, c.name .. ": lights (assimp)") + t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)") + checked.assimp += 1 + end + -- against the glTF original of an assimp export + if c.gltf then + local g, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(c.gltf)), { files = c.gltfFiles }) + t:check(g, c.name .. ": gltf original: " .. tostring(gerr)) + if g then + local glo, ghi = posedBounds(g) + local lo, hi = posedBounds(scene) + -- assimp's exporter folds a root Z-up rotation node of the source into Z_UP + if lo and hi and scene.meta.up == "z" then + lo, hi = { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] } + end + t:check(lo and glo and nearV(lo, glo, 1e-4) and nearV(hi :: any, ghi :: any, 1e-4), string.format("%s: posed bounds %s %s, glTF %s %s", c.name, fmt(lo), fmt(hi), fmt(glo), fmt(ghi))) + t:eq(#scene.skins, #g.skins, c.name .. ": skins") + if #g.skins > 0 and #scene.skins > 0 then + t:eq(#scene.skins[1].joints, #g.skins[1].joints, c.name .. ": joints") + end + -- every LINEAR key of the original, evaluated on our resampled channels (nodes matched by name) + local byName = {} + for ni, n in scene.nodes do + if n.name then + byName[n.name] = byName[n.name] or ni + end + end + -- assimp's Collada exporter writes key times in milliseconds (its glTF importer's ticks per second) + local function maxTime(sc: any): number + local m = 0 + for _, a in sc.animations do + for _, ch in a.channels do + m = math.max(m, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4)) + end + end + return m + end + local gmax, omax = maxTime(g), maxTime(scene) + local tscale = if gmax > 0 and near(omax / gmax, 1000, 1e-3) then 1000 else 1 + -- (files assimp cannot read back: its exporter left out animation sources; their channels are dropped) + for _, ga in if ref and not ref.failed then g.animations else {} do + for _, gc in ga.channels do + local gname = g.nodes[gc.node].name + local ni = gname and byName[gname] + if gc.interpolation == "LINEAR" and gc.path ~= "weights" and ni then + local ours = nil + for _, a in scene.animations do + for _, ch in a.channels do + if ch.node == ni and ch.path == gc.path then + ours = ch + end + end + end + t:check(ours, c.name .. ": animated " .. gname .. " " .. gc.path) + if ours then + local gin, gout = Scene.reader(gc.input) :: any, Scene.reader(gc.output) :: any + for k = 0, gc.input.count - 1 do + local want = {} + for q = 0, gc.output.components - 1 do + want[q + 1] = gout(k, q) + end + local got = channelAt(ours, gin(k, 0) * tscale) + local ok + if gc.path == "rotation" then + local d = math.abs(got[1] * want[1] + got[2] * want[2] + got[3] * want[3] + got[4] * want[4]) + ok = d > 1 - 1e-4 + else + ok = nearV(got, want, 1e-4) + end + t:check(ok, string.format("%s: %s %s at %g", c.name, gname, gc.path, gin(k, 0))) + checked.keys += 1 + end + end + end + end + end + checked.gltf += 1 + end + end + -- the full rotations file: no resampled step over 90 degrees + if string.find(c.name, "full_rotations", 1, true) then + local worst = 1 + for _, a in scene.animations do + for _, ch in a.channels do + if ch.path == "rotation" then + local r = Scene.reader(ch.output) :: any + for k = 1, ch.output.count - 1 do + local d = 0 + for q = 0, 3 do + d += r(k, q) * r(k - 1, q) + end + worst = math.min(worst, d) + end + end + end + end + t:check(worst >= math.cos(math.rad(45)) - 1e-6, "full rotations: subdivided (worst dot " .. worst .. ")") + end + -- round trip through our writer (.dae, and .zae for a few) + local tri = decode(c.data, { files = c.files }) + decoded[i] = tri + local files = {} + local out, eerr = Dae.encode(tri, { files = files, name = "rt.dae" }) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + if out then + local back, berr = decode(out, { files = files }) + t:check(back, c.name .. ": re-decode: " .. tostring(berr)) + if back then + local p1, f1 = counts(tri) + local p2, f2 = counts(back) + t:eq(p2, p1, c.name .. ": round trip meshes") + t:eq(f2, f1, c.name .. ": round trip faces") + local lo1, hi1 = MeshOps.bounds(tri) + local lo2, hi2 = MeshOps.bounds(back) + t:check((lo1 == nil and lo2 == nil) or (lo1 and lo2 and nearV(lo2, lo1, 1e-5) and nearV(hi2 :: any, hi1 :: any, 1e-5)), c.name .. ": round trip bounds") + t:eq(#back.materials, #tri.materials, c.name .. ": round trip materials") + t:eq(#back.cameras, #tri.cameras, c.name .. ": round trip cameras") + t:eq(#back.lights, #tri.lights, c.name .. ": round trip lights") + t:eq(#back.textures, #tri.textures, c.name .. ": round trip textures") + for ti, tex in tri.textures do + local bt = back.textures[ti] + if tex.data and bt then + t:check(bt.data and buffer.tostring(bt.data) == buffer.tostring(tex.data), c.name .. ": round trip texture " .. ti) + end + end + for mi, m in tri.materials do + local bm = back.materials[mi] + t:check(bm and nearV(bm.baseColor, m.baseColor, 1e-6), c.name .. ": round trip baseColor " .. mi) + end + checked.roundTrips += 1 + end + end + if #c.data < 20000 then + table.insert(samples, c.data) + end +end + +-- assimp reads what we wrote like the source +for _, x in Xcheck do + local src = decoded[x.case] + local ref = x.assimp + t:check(ref and not ref.failed, x.name .. ": assimp reads our file") + if src and ref and not ref.failed then + local prims, faces = counts(src) + if prims > 0 then + t:eq(ref.meshes, prims, x.name .. ": meshes (assimp, ours)") + t:eq(ref.faces, faces, x.name .. ": faces (assimp, ours)") + local lo, hi = assimpBounds(src, true) -- our writer bakes the bind shape (it writes no skins) + t:check(lo and nearV(lo, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4), string.format("%s: bounds %s %s, assimp %s %s", x.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max))) + end + t:eq(ref.cameras, #src.cameras, x.name .. ": cameras (assimp, ours)") + t:eq(ref.lights, #src.lights, x.name .. ": lights (assimp, ours)") + checked.xcheck += 1 + end +end + +-- polygons: kept or fan-triangulated +local function case(name: string): any + for i, c in Cases do + if string.find(c.name, name, 1, true) then + return c, i + end + end + return nil, nil +end +do + local c = case("ConcavePolygon") + if c then + local s = decode(c.data, { triangulate = false }) + local p = s.meshes[1].primitives[1] + t:eq(p.mode, "polygons", "polygons kept") + local corners = 0 + local get = Scene.reader(p.faces) :: any + for k = 0, p.faces.count - 1 do + corners += get(k, 0) - 2 + end + local s2 = decode(c.data) + t:eq(s2.meshes[1].primitives[1].mode, "triangles", "polygons triangulated") + t:eq(s2.meshes[1].primitives[1].indices.count // 3, corners, "fan triangle count") + local tri = MeshOps.triangulate(p) + t:check(tri and tri.indices.count // 3 == corners, "MeshOps ear-clips the kept polygon") + end +end + +-- materials and textures (duck: blinn, a TGA diffuse texture; decoded at the api layer) +do + local c = case("assimp/duck.dae") + if c then + local s = decode(c.data, { files = c.files }) + local m = s.materials[1] + local ti = m.baseColorTexture and m.baseColorTexture.texture + local tex = ti and s.textures[ti] + t:check(tex and tex.data, "duck: diffuse texture bytes") + t:eq(tex and tex.mime, "image/tga", "duck: texture mime") + t:check(m.extras.phong.model == "blinn" and type(m.extras.phong.shininess) == "number", "duck: phong extras") + local _, errs = F.model.loadTextures(s) + t:check(tex and tex.image and tex.image.width > 0 and errs[ti :: number] == nil, "duck: texture decoded lazily") + -- without the image files: the uri stays, no data + local s2 = decode(c.data) + t:check(ti and s2.textures[ti].data == nil and s2.textures[ti].uri == "./duckCM.tga", "duck: uri without files") + local cam = s.cameras[1] + t:check(cam.type == "perspective" and cam.yfov > 0 and cam.yfov < math.pi, "duck: camera") + t:eq(s.meta.up, "y", "duck: up axis") + end + local z = case("assimp/duck.zae") + if z then + local s = decode(z.data) + t:check(s.textures[1] and s.textures[1].data, "zae: texture read from the zip") + t:check(Dae.sniff(Bytes.reader(buffer.fromstring(z.data))) > 0.9, "zae sniff") + local zb = Dae.encode(s, { format = "zae" }) + local back = zb and decode(zb) + t:check(back and back.textures[1] and back.textures[1].data and buffer.len(back.textures[1].data) == buffer.len(s.textures[1].data), "zae round trip with the texture") + end + local l = case("assimp/lights.dae") + if l then + local s = decode(l.data) + local kinds = {} + for _, li in s.lights do + kinds[li.type] = (kinds[li.type] or 0) + 1 + end + t:check(kinds.point == 2 and kinds.directional == 1 and kinds.spot == 1, "lights: kinds") + t:eq(lightCount(s) - #s.lights, 1, "lights: one ambient") + end + local u = case("cube_UTF16LE") + if u then + t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(u.data))), 1, "UTF-16 sniff") + end + local k = case("kwxport") + if k then + local s = decode(k.data) + t:check(s.meta.up == "z" and near(s.meta.unit, 0.0254, 1e-9), "kwxport: Z_UP, inches") + t:check(s.meshes[1].primitives[1].attributes.COLOR_0 ~= nil, "kwxport: vertex colours") + end + local uv2 = case("cube_with_2UVs") + if uv2 then + local s = decode(uv2.data) + local a = s.meshes[1].primitives[1].attributes + t:check(a.TEXCOORD_0 and a.TEXCOORD_1, "2 UV sets") + end + local clips = case("library_animation_clips") + if clips then + local s = decode(clips.data) + t:check(#s.animations == 2 and s.animations[1].name ~= nil, "animation clips named") + t:check(#s.skins >= 1 and s.skins[1].inverseBindMatrices ~= nil, "clips: skin with inverse bind matrices") + local p = s.meshes[s.nodes[(function() + for i, n in s.nodes do + if n.skin then + return i + end + end + return 1 + end)()].mesh].primitives[1] + local w = Scene.reader(p.attributes.WEIGHTS_0) :: any + local okSum = true + for v = 0, p.attributes.WEIGHTS_0.count - 1 do + local sum = w(v, 0) + w(v, 1) + w(v, 2) + w(v, 3) + if sum > 0 and math.abs(sum - 1) > 1e-5 then + okSum = false + end + end + t:check(okSum, "clips: weights normalized") + end +end + +-- api: F.load by content / extension +do + local c = case("cube_tristrips") + if c then + local s, err = F.load(c.data) + t:check(s and s.meta.source.format == "dae", "F.load: " .. tostring(err)) + local out = F.save(s, nil, { format = "dae" }) + t:check(out and string.find(buffer.tostring(out), "') + t:check(e1 and e1.code == Err.CORRUPT, "not COLLADA: CORRUPT") + local _, e2 = decode('') + t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "unclosed XML") + local bad = [[ +0 0 0 +

0 0 7

+
]] + local _, e3 = decode(bad) + t:check(e3 and e3.code == Err.CORRUPT, "index out of range: CORRUPT") + local _, e4 = decode(string.gsub(bad, "0 0 7", "0 0 0"), { maxVertices = 0 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: LIMIT") + local ok = decode((string.gsub(bad, "0 0 7", "0 0 0"))) + t:check(ok and #ok.meshes == 1 and ok.meshes[1].primitives[1].attributes.POSITION.count == 1, "minimal file") + local _, e5 = Dae.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode: ARG") + t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(""))), 0, "sniff: other XML") + table.insert(samples, (string.gsub(bad, "0 0 7", "0 0 0"))) +end + +t:note("%d cases: %d against assimp (%d bounds), %d against their glTF originals (%d animation keys), %d round trips", #Cases, checked.assimp, checked.bounds, checked.gltf, checked.keys, checked.roundTrips) +t:note("%d of our files read back by assimp like the sources", checked.xcheck) +t:fuzz("decode", function(b: buffer) + return Dae.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_dae_encode.luau b/tools/fixtures/_dae_encode.luau new file mode 100644 index 0000000..120b76c --- /dev/null +++ b/tools/fixtures/_dae_encode.luau @@ -0,0 +1,36 @@ +-- tools/fixtures/_dae_encode: run by tools/fixtures/dae.py (luau CLI, repo root): decodes every Collada case with our +-- reader and encodes it with our writer (rt_.dae + its image files, and rt_.zae for the first cases), +-- printing "\t" lines for assimp to read back. +local Dae = require("@formats/model/dae") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/dae_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local scene, err = Dae.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local files = {} + local dae = assert(Dae.encode(scene, { files = files, name = "rt_" .. i .. ".dae" })) + print(string.format("rt_%d.dae\t%s", i, hex(buffer.tostring(dae)))) + for name, data in files do + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + if i <= 3 then + local zae = assert(Dae.encode(scene, { format = "zae" })) + print(string.format("rt_%d.zae\t%s", i, hex(buffer.tostring(zae)))) + end + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/dae.py b/tools/fixtures/dae.py new file mode 100644 index 0000000..e8c4430 --- /dev/null +++ b/tools/fixtures/dae.py @@ -0,0 +1,106 @@ +# Collada fixtures (tools/fixtures.py): assimp's Collada test models (read from the nixpkgs assimp source at fixture +# time, never committed: test/models/Collada, licences in that folder's licence.md), glTF sample models converted to +# .dae by assimp's Collada exporter (skins, animations, cameras, textures), with reference values from `assimp info -r` +# (meshes, faces, vertices, bounds, materials, animations, cameras, lights, bones). Blender 5 has no Collada support. +# tests/gen/dae_cases.luau { name, main, data, files = { name -> bytes }, assimp, gltf? + gltfFiles? (the original +# of an assimp export: the test compares skins and animations with it) } +# tests/gen/dae_xcheck.luau our encoder's .dae of every case (tools/fixtures/_dae_encode.luau) read back by assimp: +# { name, case, assimp } +import importlib.util, os, re, subprocess + +INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau", + "tests/fixtures/gltf"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_src(): + out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def info(ctx, M, path): + a = M.assimp_info(ctx, [path], raw=True)[0] + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {"failed": True} + for label in ("Animations", "Cameras", "Lights", "Bones", "Materials"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + if m: + a[label.lower()] = int(m.group(1)) + # assimp's root node transform (its Collada importer bakes up axis / unit conversion into it): not reported by + # `assimp info`; the test applies the conversion itself + return a + + +IMAGE_EXT = (".jpg", ".jpeg", ".png", ".tga", ".bmp") + + +def generate(ctx): + M = ref_module(ctx) + src = os.path.join(assimp_src(), "test", "models", "Collada") + cases = [] + images = {f: os.path.join(src, f) for f in sorted(os.listdir(src)) if f.lower().endswith(IMAGE_EXT)} + for f in sorted(os.listdir(src)): + if not (f.lower().endswith(".dae") or f.lower().endswith(".zae")) or "_triangulate" in f: + continue # the *_triangulate files are the same models again (fixture size) + path = os.path.join(src, f) + data = open(path, "rb").read() + files = {} + text = data.decode("latin-1") + for im, ip in images.items(): + if im in text: + files[im] = open(ip, "rb").read() + cases.append({"name": "assimp/" + f, "main": f, "path": path, "files": files}) + # glTF samples -> assimp's Collada exporter + tmp = M.tempdir() + groot = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), + ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"), + ("Cameras", "glTF", "Cameras.gltf"), ("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb"), + ("SimpleMeshes", "glTF", "SimpleMeshes.gltf"), ("InterpolationTest", "glTF-Binary", "InterpolationTest.glb"), + ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")): + d = os.path.join(groot, model, variant) + if not os.path.exists(os.path.join(d, main)): + continue + out = os.path.join(tmp, model + ".dae") + try: + ctx.nix("assimp", ["assimp", "export", os.path.join(d, main), out, "-fcollada"]) + except subprocess.CalledProcessError: + continue + files = {} + text = open(out, "rb").read().decode("latin-1") + for f in os.listdir(tmp): + if f.lower().endswith(IMAGE_EXT) and f in text: + files[f] = open(os.path.join(tmp, f), "rb").read() + for f in os.listdir(d): + if f.lower().endswith(IMAGE_EXT) and f in text: + files[f] = open(os.path.join(d, f), "rb").read() + orig = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != main} + cases.append({"name": "assimp-export/" + model, "main": model + ".dae", "path": out, "files": files, + "gltf": open(os.path.join(d, main), "rb").read(), "gltfFiles": orig}) + for c in cases: + c["assimp"] = info(ctx, M, c["path"]) + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("dae_cases", cases) + + # assimp reads our output + ours = M.luau_encode(ctx, "tools/fixtures/_dae_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + if name.endswith(".dae") or name.endswith(".zae"): + names.append(name) + out = [] + for n in names: + out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": info(ctx, M, os.path.join(xtmp, n))}) + ctx.emit("dae_xcheck", out)