Files
rosetta/src/Formats/model/dae/init.luau
T

207 lines
8.2 KiB
Luau

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