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 <[email protected]>
This commit is contained in:
1 parent
75c677074a
commit
a7b4a69177
9 files changed
+3385
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,376 @@
|
||||
--!strict
|
||||
-- model/dae/Write: Scene -> Collada 1.4.1 text. One <geometry> 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 <matrix>; 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('<source id="%s"><float_array id="%s-array" count="%d">%s</float_array>', id, id, n, concat(vals, " ")))
|
||||
local ps = {}
|
||||
for c = 1, comps do
|
||||
ps[c] = format('<param name="%s" type="float"/>', params[c] or "V")
|
||||
end
|
||||
table.insert(out, format('<technique_common><accessor source="#%s-array" count="%d" stride="%d">%s</accessor></technique_common></source>\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><texture texture="%s" texcoord="UVSET%d"/></%s>', tag, tex, uv or 0, tag)
|
||||
end
|
||||
local v = c or { 0, 0, 0, 1 }
|
||||
return format("<%s><color>%s %s %s %s</color></%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('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\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('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up))
|
||||
-- images
|
||||
local imageId: { [number]: string } = {}
|
||||
if #scene.textures > 0 then
|
||||
w("<library_images>\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('<image id="%s"%s><init_from>%s</init_from></image>\n', id, nameAttr(tex.name), Xml.escape(uri :: string)))
|
||||
end
|
||||
end
|
||||
w("</library_images>\n")
|
||||
end
|
||||
-- effects + materials
|
||||
if #scene.materials > 0 then
|
||||
w("<library_effects>\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('<newparam sid="%s-surface"><surface type="2D"><init_from>%s</init_from></surface></newparam><newparam sid="%s"><sampler2D><source>%s-surface</source></sampler2D></newparam>', 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("<shininess><float>%s</float></shininess>", f(sh)))
|
||||
end
|
||||
end
|
||||
if (bc[4] or 1) < 1 then
|
||||
table.insert(body, '<transparent opaque="A_ONE"><color>1 1 1 1</color></transparent>')
|
||||
table.insert(body, format("<transparency><float>%s</float></transparency>", f(bc[4])))
|
||||
end
|
||||
local extra = ""
|
||||
if ntex or mat.doubleSided then
|
||||
extra = "<extra><technique profile=\"FCOLLADA\">" .. (if ntex then format('<bump><texture texture="%s" texcoord="UVSET%d"/></bump>', ntex, nuv or 0) else "") .. (if mat.doubleSided then "<double_sided>1</double_sided>" else "") .. "</technique></extra>"
|
||||
end
|
||||
w(format('<effect id="effect%d"><profile_COMMON>%s<technique sid="common"><%s>%s</%s>%s</technique></profile_COMMON></effect>\n', i, concat(params), model, concat(body), model, extra))
|
||||
end
|
||||
w("</library_effects>\n<library_materials>\n")
|
||||
for i, mat in scene.materials do
|
||||
w(format('<material id="material%d"%s><instance_effect url="#effect%d"/></material>\n', i, nameAttr(mat.name), i))
|
||||
end
|
||||
w("</library_materials>\n")
|
||||
end
|
||||
-- geometries: one per primitive
|
||||
local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {}
|
||||
w("<library_geometries>\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('<geometry id="%s"%s><mesh>\n', id, nameAttr(mesh.name)))
|
||||
source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false)
|
||||
local ins = { format('<input semantic="VERTEX" source="#%s-vertices" offset="0"/>', id) }
|
||||
if prim.attributes.NORMAL then
|
||||
source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false)
|
||||
table.insert(ins, format('<input semantic="NORMAL" source="#%s-normals" offset="0"/>', 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('<input semantic="TEXCOORD" source="#%s-uv%d" offset="0" set="%d"/>', 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('<input semantic="COLOR" source="#%s-color%d" offset="0" set="%d"/>', id, k, k))
|
||||
end
|
||||
w(format('<vertices id="%s-vertices"><input semantic="POSITION" source="#%s-positions"/></vertices>\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("<vcount>" .. list(sizes) .. "</vcount>")
|
||||
end
|
||||
w("<p>" .. list(idx) .. "</p></" .. kind .. ">\n</mesh></geometry>\n")
|
||||
table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets })
|
||||
end
|
||||
end
|
||||
w("</library_geometries>\n")
|
||||
-- cameras / lights
|
||||
if #scene.cameras > 0 then
|
||||
w("<library_cameras>\n")
|
||||
for i, cam in scene.cameras do
|
||||
local body: string
|
||||
if cam.type == "orthographic" then
|
||||
body = format("<orthographic><xmag>%s</xmag><ymag>%s</ymag><znear>%s</znear><zfar>%s</zfar></orthographic>", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000))
|
||||
else
|
||||
body = format("<perspective><yfov>%s</yfov>%s<znear>%s</znear><zfar>%s</zfar></perspective>", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("<aspect_ratio>%s</aspect_ratio>", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000))
|
||||
end
|
||||
w(format('<camera id="camera%d"%s><optics><technique_common>%s</technique_common></optics></camera>\n', i, nameAttr(cam.name), body))
|
||||
end
|
||||
w("</library_cameras>\n")
|
||||
end
|
||||
if #scene.lights > 0 then
|
||||
w("<library_lights>\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("<color>%s %s %s</color>", f(c[1] * k), f(c[2] * k), f(c[3] * k))
|
||||
local body = if l.type == "spot" then format("<spot>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation><falloff_angle>%s</falloff_angle><falloff_exponent>0</falloff_exponent></spot>", col, f(math.deg(l.outerCone or math.pi / 4) * 2))
|
||||
elseif l.type == "point" then format("<point>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation></point>", col)
|
||||
else format("<directional>%s</directional>", col)
|
||||
w(format('<light id="light%d"%s><technique_common>%s</technique_common></light>\n', i, nameAttr(l.name), body))
|
||||
end
|
||||
w("</library_lights>\n")
|
||||
end
|
||||
-- the node tree
|
||||
w('<library_visual_scenes><visual_scene id="scene" name="scene">\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('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', 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('<bind_vertex_input semantic="UVSET%d" input_semantic="TEXCOORD" input_set="%d"/>', k, k))
|
||||
end
|
||||
w(format('<instance_geometry url="#%s"><bind_material><technique_common><instance_material symbol="m%d" target="#material%d">%s</instance_material></technique_common></bind_material></instance_geometry>', g.id, g.material, g.material, concat(binds)))
|
||||
else
|
||||
w(format('<instance_geometry url="#%s"/>', g.id))
|
||||
end
|
||||
end
|
||||
end
|
||||
if n.camera and scene.cameras[n.camera] then
|
||||
w(format('<instance_camera url="#camera%d"/>', n.camera))
|
||||
end
|
||||
if n.light and scene.lights[n.light] then
|
||||
w(format('<instance_light url="#light%d"/>', n.light))
|
||||
end
|
||||
w("\n")
|
||||
for _, c in n.children or {} do
|
||||
node(c, depth + 1)
|
||||
end
|
||||
w("</node>\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('</visual_scene></library_visual_scenes>\n<scene><instance_visual_scene url="#scene"/></scene>\n</COLLADA>\n')
|
||||
return concat(out)
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -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 (<mesh> 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>, 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
|
||||
-- <skeleton> 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: <spline> / <brep> geometry, polygon holes (<ph>: 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, "<COLLADA", 1, true) then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch
|
||||
return function(uri: string): buffer?
|
||||
local v: any = nil
|
||||
if zip then
|
||||
local d = zip:read(uri)
|
||||
if d then
|
||||
return d
|
||||
end
|
||||
end
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
if v == nil then
|
||||
v = opts.files[string.match(uri, "([^/\\]+)$") or uri]
|
||||
end
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
end
|
||||
|
||||
-- the main .dae of a .zae: manifest.xml's <dae_root>, 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", '<?xml version="1.0" encoding="utf-8"?>\n<dae_root>./model.dae</dae_root>\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
|
||||
Reference in new issue
Block a user