--!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/core/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