--!strict -- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, -- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; -- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, -- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> -- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material -- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of -- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or -- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> -- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and -- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). -- Never throws: returns nil, message. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Flatten = require("@rosetta/codecs/model/MeshFlatten") local Xml = require("@rosetta/codecs/text/Xml") local Write = {} export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } -- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers -- per line), "bool", "str", "mstr" (MFString), "node", "nodes" type WNode = { type: string, def: string?, use: string?, fields: { { any } } } local format, concat = string.format, table.concat local function fmt(v: number): string if v ~= v then return "0" elseif v == math.huge then return "1e38" elseif v == -math.huge then return "-1e38" elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then return format("%d", v) end return format("%.9g", v) end local function W(t: string, def: string?): WNode return { type = t, def = def, fields = {} } end local function F(n: WNode, name: string, kind: string, value: any, per: number?) table.insert(n.fields, { name, kind, value, per }) end -- names: valid, unique DEF names local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string local s = string.gsub(name or "", "[^%w_]", "_") if s == "" or string.find(s, "^%d") then s = fallback .. (if s ~= "" then "_" .. s else "") end local base, k = s, 1 while used[s] do k += 1 s = base .. "_" .. k end used[s] = true return s end end -- axis-angle of a quaternion (x, y, z, w) local function axisAngle(q: { number }): { number } local x, y, z, w = q[1], q[2], q[3], q[4] local l = math.sqrt(x * x + y * y + z * z + w * w) if l > 0 then x, y, z, w = x / l, y / l, z / l, w / l end local s = math.sqrt(math.max(0, 1 - w * w)) if s < 1e-9 then return { 0, 0, 1, 0 } end return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } end -- ------------------------------------------------------------------------------------------------ geometry local function values(acc: any): { number }? return (Flatten.numbers(acc)) end local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } local keep = function(n: string): boolean return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" end local m, err = Flatten.merge(tmp, keep, { triangulate = false }) if not m then return nil, err end if not m.sizes or #m.sizes == 0 then return nil, nil end local g = W("IndexedFaceSet") local coord = W("Coordinate") F(coord, "point", "mf", m.attrs.POSITION.values, 3) F(g, "coord", "node", coord) local idx = {} local p = 0 for _, s in m.sizes do for k = 1, s do table.insert(idx, m.corners[p + k]) end table.insert(idx, -1) p += s end F(g, "coordIndex", "mf", idx, 0) local nrm = m.attrs.NORMAL if nrm then local nn = W("Normal") F(nn, "vector", "mf", nrm.values, 3) F(g, "normal", "node", nn) end local tc = m.attrs.TEXCOORD_0 if tc then local t = W("TextureCoordinate") local vals, c = {}, tc.components for i = 0, m.count - 1 do local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] table.insert(vals, s) table.insert(vals, if o.flipV ~= false then 1 - tt else tt) end F(t, "point", "mf", vals, 2) F(g, "texCoord", "node", t) end local col = m.attrs.COLOR_0 if col then local c = col.components local rgba = c >= 4 and x3d local cn = W(if rgba then "ColorRGBA" else "Color") local vals = {} local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 for i = 0, m.count - 1 do for k = 1, if rgba then 4 else 3 do table.insert(vals, (col.values[i * c + k] or 1) / scale) end end F(cn, "color", "mf", vals, if rgba then 4 else 3) F(g, "color", "node", cn) end F(g, "solid", "bool", not doubleSided) return g, nil end -- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) local function coordNode(prim: any): (WNode?, number) local pos = values(prim.attributes.POSITION) if not pos then return nil, 0 end local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components local p3 = {} for i = 0, nv - 1 do for k = 1, 3 do table.insert(p3, pos[i * pc + k] or 0) end end local coord = W("Coordinate") F(coord, "point", "mf", p3, 3) return coord, nv end local function colorNode(prim: any, nv: number, x3d: boolean): WNode? local acc = prim.attributes.COLOR_0 local col = acc and values(acc) if not col then return nil end local c = acc.components local rgba = c >= 4 and x3d local vals = {} for i = 0, nv - 1 do for k = 1, if rgba then 4 else 3 do table.insert(vals, col[i * c + k] or 1) end end local cn = W(if rgba then "ColorRGBA" else "Color") F(cn, "color", "mf", vals, if rgba then 4 else 3) return cn end local function lineSet(prim: any, x3d: boolean): (WNode?, string?) local coord, nv = coordNode(prim) if not coord then return nil, "lines without POSITION" end local ind: { number } if prim.indices then ind = values(prim.indices) or {} else ind = {} for i = 0, nv - 1 do ind[i + 1] = i end end local idx = {} local mode = prim.mode if mode == "lines" then for i = 1, #ind - 1, 2 do table.insert(idx, ind[i]) table.insert(idx, ind[i + 1]) table.insert(idx, -1) end else for _, v in ind do table.insert(idx, v) end if mode == "line_loop" and #ind > 0 then table.insert(idx, ind[1]) end table.insert(idx, -1) end for _, v in idx do if v >= nv then return nil, "line index out of range" end end local g = W("IndexedLineSet") F(g, "coord", "node", coord) local cn = colorNode(prim, nv, x3d) if cn then F(g, "color", "node", cn) end F(g, "coordIndex", "mf", idx, 0) return g, nil end local function pointSet(prim: any, x3d: boolean): (WNode?, string?) local coord, nv = coordNode(prim) if not coord then return nil, "points without POSITION" end local g = W("PointSet") F(g, "coord", "node", coord) local cn = colorNode(prim, nv, x3d) if cn then F(g, "color", "node", cn) end return g, nil end -- ------------------------------------------------------------------------------------------------ materials local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? if written[i] then return written[i] end local tex = scene.textures[i] if not tex then return nil end local url = tex.uri if tex.data and type(o.files) == "table" then local base = string.match(o.name or "model", "([^/\\]+)$") or "model" base = string.gsub(base, "%.[^.]*$", "") local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) o.files[file] = tex.data url = file end if url then written[i] = url end return url end local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode local m = scene.materials[mi] local app = W("Appearance") local mat = W("Material") local x = m.extras and m.extras.vrml or {} local c = m.baseColor or { 1, 1, 1, 1 } F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) local e = m.emissive or { 0, 0, 0 } if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) end if type(x.specularColor) == "table" then F(mat, "specularColor", "sf", x.specularColor) end local sh = x.shininess if type(sh) ~= "number" then local r = math.max(m.roughness or 1, 1e-3) sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) end F(mat, "shininess", "sf", { sh }) if type(x.ambientIntensity) == "number" then F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) end if (c[4] or 1) < 1 then F(mat, "transparency", "sf", { 1 - c[4] }) end F(app, "material", "node", mat) local ref = m.baseColorTexture if ref and type(ref.texture) == "number" then local url = textureUrl(scene, ref.texture, o, written) local img = scene.textures[ref.texture] and scene.textures[ref.texture].image if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then local it if url then it = W("ImageTexture") F(it, "url", "mstr", { url }) else -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) it = W("PixelTexture") local w, h = img.width, img.height local v = { w, h, 4 } for row = h - 1, 0, -1 do for x = 0, w - 1 do table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) end end -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA for i = 4, #v do local p = v[i] v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 end F(it, "image", "sf", v) end local s = scene.textures[ref.texture].sampler if s and s.wrapS == "clamp" then F(it, "repeatS", "bool", false) end if s and s.wrapT == "clamp" then F(it, "repeatT", "bool", false) end F(app, "texture", "node", it) local tf = ref.transform if tf then local tt = W("TextureTransform") if tf.offset then F(tt, "translation", "sf", tf.offset) end if tf.scale then F(tt, "scale", "sf", tf.scale) end if tf.rotation then F(tt, "rotation", "sf", { tf.rotation }) end F(app, "textureTransform", "node", tt) end end end return app end -- ------------------------------------------------------------------------------------------------ the tree function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() local nodeDef: { [number]: string } = {} local meshShapes: { [number]: { WNode } } = {} local appDef: { [any]: string } = {} local written: { [number]: string } = {} local failure: string? = nil local function shapes(mi: number): { WNode } local done = meshShapes[mi] if done then -- USE the shapes written before local out = {} for _, s in done do table.insert(out, { type = "Shape", use = s.def, fields = {} }) end return out end local mesh = scene.meshes[mi] local out = {} for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do local mode = prim.mode or "triangles" local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil local geo, err if mode == "lines" or mode == "line_strip" or mode == "line_loop" then geo, err = lineSet(prim, x3d) elseif mode == "points" then geo, err = pointSet(prim, x3d) else geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) end if err then failure = failure or err end if geo then local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) if mat then local key = prim.material if appDef[key] then F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) else local app = appearance(scene, prim.material, o, written) app.def = name(mat.name, "Material") appDef[key] = app.def F(sh, "appearance", "node", app) end end F(sh, "geometry", "node", geo) table.insert(out, sh) end end meshShapes[mi] = out return out end local visiting: { [number]: boolean } = {} local function transform(ni: number): WNode? local n = scene.nodes[ni] if type(n) ~= "table" or visiting[ni] then return nil end visiting[ni] = true local def = name(n.name, "Node") nodeDef[ni] = def local t = W("Transform", def) local tr, rot, sc = n.translation, n.rotation, n.scale if n.matrix then tr, rot, sc = Mat4.decompose(n.matrix) end if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) end if rot then local aa = axisAngle(rot) if aa[4] ~= 0 then F(t, "rotation", "sf", aa) end end if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) end local kids: { WNode } = {} if type(n.mesh) == "number" then for _, s in shapes(n.mesh) do table.insert(kids, s) end end local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil if cam then local v if cam.type == "orthographic" and x3d then v = W("OrthoViewpoint") local xm, ym = cam.xmag or 1, cam.ymag or 1 F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) else v = W("Viewpoint") F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) end F(v, "position", "sf", { 0, 0, 0 }) if cam.name then F(v, "description", "str", cam.name) end table.insert(kids, v) end local l = if type(n.light) == "number" then scene.lights[n.light] else nil if l then local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" local ln = W(typ) local c = l.color or { 1, 1, 1 } F(ln, "color", "sf", { c[1], c[2], c[3] }) F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) if typ ~= "PointLight" then F(ln, "direction", "sf", { 0, 0, -1 }) end if typ ~= "DirectionalLight" then F(ln, "location", "sf", { 0, 0, 0 }) F(ln, "radius", "sf", { l.range or 100 }) end if typ == "SpotLight" then F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) F(ln, "beamWidth", "sf", { l.innerCone or 0 }) end table.insert(kids, ln) end for _, c in n.children or {} do local ct = transform(c) if ct then table.insert(kids, ct) end end if #kids > 0 then F(t, "children", "nodes", kids) end visiting[ni] = nil return t end local roots: { WNode } = {} local list = scene.roots if type(list) ~= "table" or #list == 0 then -- no roots: every node without a parent local child = {} for _, n in scene.nodes do for _, c in n.children or {} do child[c] = true end end list = {} for i = 1, #scene.nodes do if not child[i] then table.insert(list, i) end end end for _, ri in list do local t = transform(ri) if t then table.insert(roots, t) end end if #scene.nodes == 0 then for mi = 1, #scene.meshes do for _, s in shapes(mi) do table.insert(roots, s) end end end -- animations: a TimeSensor per animation, an interpolator per channel local routes: { { string } } = {} for ai, anim in scene.animations or {} do local tmax = 0 local chans = {} for _, ch in anim.channels or {} do local target = nodeDef[ch.node] if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then local input, output = values(ch.input), values(ch.output) if input and output and #input > 0 then tmax = math.max(tmax, input[#input]) table.insert(chans, { ch, target, input, output }) end end end if #chans > 0 then local cycle = if tmax > 0 then tmax else 1 local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) F(ts, "cycleInterval", "sf", { cycle }) F(ts, "loop", "bool", true) table.insert(roots, ts) for k, c in chans do local ch, target, input, output = c[1], c[2], c[3], c[4] local rot = ch.path == "rotation" local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) local keys = {} for i, tv in input do keys[i] = tv / cycle end local comps = if rot then 4 else 3 local stride = #output // #input -- CUBICSPLINE stores in-tangent, value, out-tangent per key local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 local kv = {} for i = 0, #input - 1 do local v = {} for q = 1, comps do v[q] = output[i * stride + off + q] or 0 end if rot then v = axisAngle(v) end for _, x in v do table.insert(kv, x) end end F(it, "key", "mf", keys, 0) F(it, "keyValue", "mf", kv, comps) table.insert(roots, it) table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) end end end if failure then return nil, nil, failure end return roots, routes, nil end -- ------------------------------------------------------------------------------------------------ serializers local function numbers(vals: { number }, per: number?, indent: string): string local out = table.create(#vals) for i, v in vals do out[i] = fmt(v) end if per == 0 then -- index lists: one face per line local lines, cur = {}, {} for i, v in vals do table.insert(cur, out[i]) if v == -1 then table.insert(lines, concat(cur, " ")) cur = {} end end if #cur > 0 then table.insert(lines, concat(cur, " ")) end return concat(lines, "\n" .. indent) end if per and per > 0 then local lines = {} for i = 1, #out, per do table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) end return concat(lines, ",\n" .. indent) end return concat(out, " ") end local function quote(s: string): string return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' end local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string local out = {} if x3d then table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n") else table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n") end local function emit(n: WNode, ind: string): string if n.use then return "USE " .. n.use end local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } local ind2 = ind .. " " for _, f in n.fields do local fname, kind, v, per = f[1], f[2], f[3], f[4] local s if kind == "sf" then s = numbers(v, nil, ind2) elseif kind == "mf" then s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" elseif kind == "bool" then s = if v then "TRUE" else "FALSE" elseif kind == "str" then s = quote(v) elseif kind == "mstr" then local q = {} for i, x in v do q[i] = quote(x) end s = "[ " .. concat(q, " ") .. " ]" elseif kind == "node" then s = emit(v, ind2) else local q = {} for i, x in v do q[i] = ind2 .. " " .. emit(x, ind2 .. " ") end s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" end table.insert(parts, ind2 .. fname .. " " .. s) end table.insert(parts, ind .. "}") return concat(parts, "\n") end for _, r in roots do table.insert(out, emit(r, "")) end for _, r in routes do table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) end return concat(out, "\n") .. "\n" end -- the containerField a child element needs when it is not its type's default local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) local function element(n: WNode, field: string): any local attrs = Types.object() local kids = {} if (DEFAULT[n.type] or "children") ~= field then Types.set(attrs, "containerField", field) end if n.use then Types.set(attrs, "USE", n.use) return Xml.element(n.type, attrs :: any) end if n.def then Types.set(attrs, "DEF", n.def) end for _, f in n.fields do local fname, kind, v, per = f[1], f[2], f[3], f[4] if kind == "sf" then Types.set(attrs, fname, numbers(v, nil, "")) elseif kind == "mf" then local s = numbers(v, per, "") Types.set(attrs, fname, (string.gsub(s, "\n", " "))) elseif kind == "bool" then Types.set(attrs, fname, if v then "true" else "false") elseif kind == "str" then Types.set(attrs, fname, v) elseif kind == "mstr" then local q = {} for i, x in v do q[i] = quote(x) end Types.set(attrs, fname, concat(q, " ")) elseif kind == "node" then table.insert(kids, element(v, fname)) else for _, x in v do table.insert(kids, element(x, fname)) end end end return Xml.element(n.type, attrs :: any, kids) end local sceneKids = {} for _, r in roots do table.insert(sceneKids, element(r, "children")) end for _, r in routes do local a = Types.object() Types.set(a, "fromNode", r[1]) Types.set(a, "fromField", r[2]) Types.set(a, "toNode", r[3]) Types.set(a, "toField", r[4]) table.insert(sceneKids, Xml.element("ROUTE", a :: any)) end local ra = Types.object() Types.set(ra, "profile", "Interchange") Types.set(ra, "version", "3.3") local meta = Types.object() Types.set(meta, "name", "generator") Types.set(meta, "content", "rosetta") local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) if not s then return nil, if err then err.message else "xml" end return s, nil end -- text(scene, opts) -> the file text function Write.text(scene: any, o: Options): (string?, string?) local roots, routes, err = Write.graph(scene, o) if not roots or not routes then return nil, err end if o.encoding == "xml" then return xml(roots, routes) end return classic(roots, routes, o.encoding == "x3dv"), nil end return Write