--!strict -- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. -- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, -- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through -- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when -- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. -- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial -- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture -- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: -- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / -- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a -- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in -- meta.source.skipped. Never throws: bad data returns nil, message. local Types = require("@formats/Types") local Mat4 = require("@formats/codecs/model/Mat4") local Fields = require("@formats/codecs/model/Vrml/Fields") local Geometry = require("@formats/codecs/model/Vrml/Geometry") local Build = {} local S = Types.Scene local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes local deg = math.deg export type Options = Geometry.Options & { fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph format: string?, -- meta.source.format maxInline: number?, -- Inline nesting (default 8) } local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } -- nodes with nothing to show (not counted as skipped) local QUIET = { WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, StringSensor = true, LoadSensor = true, } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } local function quat(r: { number }): { number } return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) end local function qmul(a: { number }, b: { number }): { number } return { a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], } end local function qrot(q: { number }, v: { number }): { number } local m = Mat4.fromQuat(q) local x, y, z = Mat4.point(m, v[1], v[2], v[3]) return { x, y, z } end local function isZero(v: { number }): boolean return v[1] == 0 and v[2] == 0 and v[3] == 0 end local function isIdentityQ(q: { number }): boolean return q[1] == 0 and q[2] == 0 and q[3] == 0 end -- the rotation taking unit vector a onto b local function between(a: { number }, b: { number }): { number } local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) if l < 1e-12 then return { 0, 0, 0, 1 } end local bx, by, bz = b[1] / l, b[2] / l, b[3] / l local d = a[1] * bx + a[2] * by + a[3] * bz if d < -0.999999 then -- opposite: half a turn about any perpendicular axis return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } end local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx local w = 1 + d local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) return { cx / n, cy / n, cz / n, w / n } end type Ctx = { scene: Types.Scene, opts: Options, meshes: { [any]: any }, materials: { [any]: any }, textures: { [any]: number }, instances: { [any]: { { node: number, center: { number }, so: { number } } } }, skipped: { [string]: number }, depth: number, inline: number, failure: string?, } local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number local nodes_ = ctx.scene.nodes table.insert(nodes_, n) local i = #nodes_ if parent then table.insert(nodes_[parent].children, i) else table.insert(ctx.scene.roots, i) end return i end -- ------------------------------------------------------------------------------------------------ materials local function texture(ctx: Ctx, t: any): number? if not t then return nil end if t.type == "MultiTexture" then return texture(ctx, nodes(t, "texture")[1]) end local cached = ctx.textures[t] if cached then return cached end local tex: Types.Texture = { name = t.def } if t.type == "ImageTexture" or t.type == "MovieTexture" then local urls = strs(t, "url") local fetch = ctx.opts.fetch for _, u in urls do local clean = string.match(u, "^([^#?]*)") or u if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then tex.uri = clean end local data = fetch and fetch(clean) if data then tex.uri, tex.data = clean, data break end end tex.uri = tex.uri or urls[1] local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") tex.mime = if ext then MIME[string.lower(ext)] else nil elseif t.type == "PixelTexture" then -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) local v = nums(t, "image") or {} local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then local img = Types.Image.new(w, h) for i = 0, w * h - 1 do local px = math.floor(v[4 + i]) % 2 ^ (8 * c) local b = table.create(4, 0) for k = c, 1, -1 do b[k] = px % 256 px //= 256 end local r, g, bl, a if c <= 2 then r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 else r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 end -- the image's first row is the bottom one local row = h - 1 - i // w local o = (row * w + i % w) * 4 buffer.writeu8(img.pixels, o, r) buffer.writeu8(img.pixels, o + 1, g) buffer.writeu8(img.pixels, o + 2, bl) buffer.writeu8(img.pixels, o + 3, a) end tex.image = img end else ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 return nil end local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) if not rs or not rt then tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } end table.insert(ctx.scene.textures, tex) ctx.textures[t] = #ctx.scene.textures return #ctx.scene.textures end local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? local i = texture(ctx, t) if not i then return nil end local ref: Types.TextureRef = { texture = i } if xf and xf.type == "TextureTransform" then local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then ref.transform = { offset = tr, scale = sc, rotation = rot } end end return ref end local function material(ctx: Ctx, app: any, solid: boolean): number? if not app and solid then return nil end local key = app or "default" local cache = ctx.materials[key] if type(cache) ~= "table" then cache = {} ctx.materials[key] = cache end local hit = (cache :: any)[solid] if hit then return hit end local m = S.material(app and app.def) m.metallic = 0 local x: { [string]: any } = {} local mat = app and node(app, "material") local tex = app and node(app, "texture") local xf = app and node(app, "textureTransform") if mat and mat.type == "TwoSidedMaterial" then m.doubleSided = true x.twoSided = true end if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) m.name = mat.def or m.name m.baseColor = { d[1], d[2], d[3], 1 - tr } m.emissive = e m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb if tr > 0 then m.alphaMode = "blend" end -- X3D 4 texture fields local dt = node(mat, "diffuseTexture") if dt then m.baseColorTexture = textureRef(ctx, dt, nil) end local nt = node(mat, "normalTexture") if nt then m.normalTexture = textureRef(ctx, nt, nil) end elseif mat and mat.type == "PhysicalMaterial" then local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) local tr = num(mat, "transparency", 0) m.name = mat.def or m.name m.baseColor = { b[1], b[2], b[3], 1 - tr } m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) if tr > 0 then m.alphaMode = "blend" end local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } for field, slot in slots do local t = node(mat, field) if t then (m :: any)[slot] = textureRef(ctx, t, nil) end end elseif mat and mat.type == "UnlitMaterial" then local e = vec(mat, "emissiveColor", { 1, 1, 1 }) m.name = mat.def or m.name m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } m.extensions = { KHR_materials_unlit = {} } else -- no material: unlit white (the specifications' default) m.extensions = { KHR_materials_unlit = {} } end if tex and not m.baseColorTexture then m.baseColorTexture = textureRef(ctx, tex, xf) if m.baseColorTexture and xf then x.textureCenter = vec(xf, "center", { 0, 0 }) end end if not solid then m.doubleSided = true end m.extras = { vrml = x } table.insert(ctx.scene.materials, m) local idx = #ctx.scene.materials ;(cache :: any)[solid] = idx return idx end -- ------------------------------------------------------------------------------------------------ nodes local walk: (ctx: Ctx, n: any, parent: number?) -> () local function shape(ctx: Ctx, n: any, parent: number?) local geo = node(n, "geometry") if not geo then return end local mi = ctx.meshes[n] if mi == nil then local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) if not prim then if solidOrErr then ctx.failure = ctx.failure or solidOrErr else ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 end ctx.meshes[n] = false :: any return end local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count if count == 0 then -- nothing to draw (no valid faces / points) ctx.meshes[n] = false return end prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) mi = #ctx.scene.meshes ctx.meshes[n] = mi elseif mi == false then return end addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) end local function viewpoint(ctx: Ctx, n: any, parent: number?) local cam: any if n.type == "OrthoViewpoint" then local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } else cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } end cam.name = n.def or str(n, "description") table.insert(ctx.scene.cameras, cam) local o = vec(n, "orientation", { 0, 0, 1, 0 }) local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } if o[4] ~= 0 then nd.rotation = quat(o) end addNode(ctx, nd, parent) end local function light(ctx: Ctx, n: any, parent: number?) local t = n.type local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } local nd: Types.Node = { name = n.def, children = {} } local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } if t == "DirectionalLight" then l.type = "directional" nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) else nd.translation = vec(n, "location", { 0, 0, 0 }) l.range = num(n, "radius", 100) x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) if t == "SpotLight" then l.type = "spot" nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) local cut = num(n, "cutOffAngle", 0.785398) l.outerCone = cut l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) end end ;(l :: any).extras = { vrml = x } table.insert(ctx.scene.lights, l) nd.light = #ctx.scene.lights addNode(ctx, nd, parent) end local function children(ctx: Ctx, n: any, parent: number?) if n.type == "Switch" then local which = math.floor(num(n, "whichChoice", -1)) local list = nodes(n, "choice") if #list == 0 then list = nodes(n, "children") end local c = list[which + 1] if which >= 0 and c then walk(ctx, c, parent) end return elseif n.type == "LOD" then local list = nodes(n, "level") if #list == 0 then list = nodes(n, "children") end if list[1] then walk(ctx, list[1], parent) end return end for _, f in CHILDREN do for _, c in nodes(n, f) do walk(ctx, c, parent) end end end local function transform(ctx: Ctx, n: any, parent: number?) local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) local qr, qs = quat(r), quat(so) local outer: Types.Node = { name = n.def, children = {} } local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } if not isZero(tt) then outer.translation = tt end local q = if isIdentityQ(qs) then qr else qmul(qr, qs) if not isIdentityQ(q) then outer.rotation = q end if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then outer.scale = s end local oi = addNode(ctx, outer, parent) local list = ctx.instances[n] if not list then list = {} ctx.instances[n] = list end table.insert(list, { node = oi, center = c, so = qs }) local holder = oi if not isZero(c) or not isIdentityQ(qs) then local inv = { -qs[1], -qs[2], -qs[3], qs[4] } local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } if not isIdentityQ(inv) then inner.rotation = inv end holder = addNode(ctx, inner, oi) end children(ctx, n, holder) end local function inline(ctx: Ctx, n: any, parent: number?) local fetch, load = ctx.opts.fetch, ctx.opts.load if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 return end for _, u in strs(n, "url") do local data = fetch(string.match(u, "^([^#?]*)") or u) if data then local g = load(data) if g then local holder = addNode(ctx, { name = n.def, children = {} }, parent) ctx.inline += 1 for _, root in g.roots do walk(ctx, root, holder) end ctx.inline -= 1 return end end end ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 end function walk(ctx: Ctx, n: any, parent: number?) if ctx.failure or type(n) ~= "table" then return end ctx.depth += 1 if ctx.depth > 200 then ctx.failure = "limit: scene nested deeper than 200" return end local t = n.type if TRANSFORM[t] then transform(ctx, n, parent) elseif GROUP[t] then local holder = parent if n.def or parent == nil then holder = addNode(ctx, { name = n.def, children = {} }, parent) end children(ctx, n, holder) elseif t == "Shape" then shape(ctx, n, parent) elseif t == "CADFace" then for _, s in nodes(n, "shape") do walk(ctx, s, parent) end elseif t == "Viewpoint" or t == "OrthoViewpoint" then viewpoint(ctx, n, parent) elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then light(ctx, n, parent) elseif t == "Inline" then inline(ctx, n, parent) elseif t == "WorldInfo" then local src = ctx.scene.meta.source :: any src.title = str(n, "title") local info = strs(n, "info") src.info = if #info > 0 then info else nil elseif not QUIET[t] then ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 end ctx.depth -= 1 end -- ------------------------------------------------------------------------------------------------ animation local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } local function animations(ctx: Ctx, routes: { any }) -- interpolator -> its TimeSensor local timer: { [any]: any } = {} for _, r in routes do if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then timer[r.to] = r.from end end local anims: { [any]: Types.Animation } = {} local order: { any } = {} for _, r in routes do local path = TARGET[r.toField] local it = r.from local inst = ctx.instances[r.to] if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then continue end if (path == "rotation") ~= (it.type == "OrientationInterpolator") then continue end local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} local comps = if path == "rotation" then 4 else 3 local n = math.min(#key, #kv // comps) if n == 0 then continue end local ts = timer[it] local cycle = if ts then num(ts, "cycleInterval", 1) else 1 local input = S.accessor(nil, "f32", 1, n) for i = 0, n - 1 do buffer.writef32(input.data, i * 4, key[i + 1] * cycle) end local id = ts or "routes" local anim = anims[id] if not anim then anim = { name = if ts then ts.def else nil, channels = {} } anims[id] = anim table.insert(order, id) end for _, at in inst do local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) local prev: { number }? = nil for i = 0, n - 1 do local v: { number } if path == "rotation" then v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) if not isIdentityQ(at.so) then v = qmul(v, at.so) end if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then v = { -v[1], -v[2], -v[3], -v[4] } end prev = v elseif path == "translation" then v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } else v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } end for c = 1, #v do buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) end end table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) end end for _, id in order do table.insert(ctx.scene.animations, anims[id]) end end -- ------------------------------------------------------------------------------------------------ scene function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) local scene = S.new() scene.meta.up = "y" local units = graph.units or {} scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 local h = graph.header or {} local skipped: { [string]: number } = {} scene.meta.source = { format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, } local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } for _, n in graph.roots do walk(ctx, n, nil) end if ctx.failure then return nil, ctx.failure end animations(ctx, graph.routes or {}) return scene, nil end return Build