ws-3d3: codecs/model/Vrml (VRML97 / X3D classic parser, X3D XML adapter, node graph -> Scene builder, writer) + model/vrml (.wrl read / write) + model/x3d (.x3d / .x3dv read / write; .x3db UNSUPPORTED); tests against VTK and assimp

This commit is contained in:
4DBug committed 2026-10-31 14:54:56 -05:00
1 parent 4c74171631
commit 76128bf381
20 files changed
+4906 -1

No files matched your search

+24
View File
@@ -494,6 +494,30 @@ local list: { Entry } = {
return require("@formats/model/vox")
end,
},
{
name = "vrml",
category = "model",
path = "model/vrml",
extensions = { "wrl", "wrz", "vrml" },
mime = { "model/vrml", "x-world/x-vrml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true },
load = function()
return require("@formats/model/vrml")
end,
},
{
name = "x3d",
category = "model",
path = "model/x3d",
extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" },
mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true },
load = function()
return require("@formats/model/x3d")
end,
},
{
name = "step",
category = "cad",
+590
View File
@@ -0,0 +1,590 @@
--!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
+168
View File
@@ -0,0 +1,168 @@
--!strict
-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding
-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here
-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans
-- true / false). Never throws.
local Fields = {}
local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte
-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted
local function mfString(s: string): { string }
local out = {}
local p = find(s, "[^%s,]")
if not p or byte(s, p) ~= 34 then
return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {}
end
local n = #s
while p and p <= n do
if byte(s, p) ~= 34 then
break
end
local q = p + 1
local parts = {}
while true do
local e = find(s, '["\\]', q)
if not e then
table.insert(parts, sub(s, q))
table.insert(out, table.concat(parts))
return out
end
table.insert(parts, sub(s, q, e - 1))
if byte(s, e) == 92 then
table.insert(parts, sub(s, e + 1, e + 1))
q = e + 2
else
p = e + 1
break
end
end
table.insert(out, table.concat(parts))
p = find(s, "[^%s,]", p)
end
return out
end
-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent
function Fields.nums(node: any, name: string): { number }?
local v = node.fields[name]
if v == nil then
return nil
end
if type(v) == "string" then
local out = {}
for w in gmatch(v, "[^%s,]+") do
local x = tonumber(w)
if x then
table.insert(out, x)
elseif w == "true" or w == "TRUE" then
table.insert(out, 1)
elseif w == "false" or w == "FALSE" then
table.insert(out, 0)
end
end
node.fields[name] = out
return out
end
if type(v) ~= "table" then
return nil
end
local ok = true
for _, x in v do
if type(x) ~= "number" then
ok = false
break
end
end
if ok then
return v
end
local out = {}
for _, x in v do
if type(x) == "number" then
table.insert(out, x)
elseif type(x) == "boolean" then
table.insert(out, if x then 1 else 0)
end
end
return out
end
function Fields.num(node: any, name: string, default: number): number
local v = Fields.nums(node, name)
return if v and type(v[1]) == "number" then v[1] else default
end
-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter)
function Fields.vec(node: any, name: string, default: { number }): { number }
local v = Fields.nums(node, name)
if not v or #v < #default then
return default
end
local out: { number } = {}
for i = 1, #default do
out[i] = v[i]
end
return out
end
function Fields.bool(node: any, name: string, default: boolean): boolean
local v = node.fields[name]
if type(v) == "string" then
local w = string.lower(string.match(v, "^%s*(%S*)") :: string)
return if w == "true" then true elseif w == "false" then false else default
end
if type(v) == "table" and type(v[1]) == "boolean" then
return v[1]
end
return default
end
function Fields.strs(node: any, name: string): { string }
local v = node.fields[name]
if type(v) == "string" then
local out = mfString(v)
node.fields[name] = out
return out
end
local out = {}
if type(v) == "table" then
for _, x in v do
if type(x) == "string" then
table.insert(out, x)
end
end
end
return out
end
function Fields.str(node: any, name: string, default: string?): string?
local v = node.fields[name]
if type(v) == "string" then
return v
end
if type(v) == "table" and type(v[1]) == "string" then
return v[1]
end
return default
end
-- nodes(node, name) -> the nodes of an SFNode / MFNode field
function Fields.nodes(node: any, name: string): { any }
local v = node.fields[name]
local out = {}
if type(v) == "table" then
for _, x in v do
if type(x) == "table" and type(x.type) == "string" then
table.insert(out, x)
end
end
end
return out
end
function Fields.node(node: any, name: string): any
return Fields.nodes(node, name)[1]
end
return Fields
+770
View File
@@ -0,0 +1,770 @@
--!strict
-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no
-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face
-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets
-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet,
-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale,
-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone,
-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to
-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data.
local Types = require("@formats/Types")
local Fields = require("@formats/codecs/model/Vrml/Fields")
local Geometry = {}
local S = Types.Scene
local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node
local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi
export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? }
local function f32(list: { number }, comps: number, count: number): Types.Accessor
local a = S.accessor(nil, "f32", comps, count)
local d = a.data
for i = 1, math.min(#list, comps * count) do
buffer.writef32(d, (i - 1) * 4, list[i])
end
return a
end
local function u32(list: { number }): Types.Accessor
local a = S.accessor(nil, "u32", 1, #list)
for i, v in list do
buffer.writeu32(a.data, (i - 1) * 4, v)
end
return a
end
-- the colour node's values and component count (Color: 3, ColorRGBA: 4)
local function colors(n: any): ({ number }?, number)
local c = node(n, "color")
if not c then
return nil, 3
end
local comps = if c.type == "ColorRGBA" then 4 else 3
return nums(c, "color") or {}, comps
end
local function points(n: any, field: string, sub: string): { number }?
local c = node(n, field)
return if c then nums(c, sub) or {} else nil
end
-- ------------------------------------------------------------------------------------------------ polygon meshes
-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil:
-- the coordinate index) or per-face indices.
type PolyIn = {
P: { number }, -- coordinates, 3 per point
corners: { number }, -- coordinate index per corner, face after face
sizes: { number }, -- corners per face
N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity)
C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?,
T: { number }?, tIdx: { number }?,
ccw: boolean,
}
local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
local P, corners, sizes = m.P, m.corners, m.sizes
local np = #P // 3
local N, C, T = m.N, m.C, m.T
local cc = m.cComps or 3
-- the attribute index of corner k (1-based) in face f (1-based)
local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number
if perFace then
return if list and #list > 0 then (list[f] or 0) else f - 1
end
return if list and #list > 0 then (list[k] or c) else c
end
local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0)
local vkey: { [string]: number } = {}
local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices
local out: { number } = {}
local outSizes: { number } = {}
local k = 0
for f, size in sizes do
local face: { number } = {}
local valid = size >= 3
for q = 1, size do
k += 1
local c = corners[k]
if c == nil or c < 0 or c >= np then
valid = false
end
face[q] = k
end
if valid then
local verts: { number } = {}
for q, kk in face do
local c = corners[kk]
if simple then
verts[q] = c
else
local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1
local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1
local ti = if T then idx(m.tIdx, false, f, kk, c) else -1
local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti
local v = vkey[key]
if not v then
v = #vsrc
vsrc[v + 1] = { c, ni, ci, ti }
vkey[key] = v
if v >= maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
end
verts[q] = v
end
end
if not m.ccw then
for a = 2, (size + 1) // 2 do
verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a]
end
end
if o.triangulate == false then
table.insert(outSizes, size)
for _, v in verts do
table.insert(out, v)
end
else
for a = 2, size - 1 do
table.insert(out, verts[1])
table.insert(out, verts[a])
table.insert(out, verts[a + 1])
end
end
end
end
local nv = if simple then np else #vsrc
if nv > maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
local flipV = o.flipV ~= false
local pos = S.accessor(nil, "f32", 3, nv)
local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil
local col = if C then S.accessor(nil, "f32", cc, nv) else nil
local tex = if T then S.accessor(nil, "f32", 2, nv) else nil
local wf = buffer.writef32
for v = 0, nv - 1 do
local s = if simple then nil else vsrc[v + 1]
local c = if s then s[1] else v
for q = 0, 2 do
wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0)
end
if nrm and N then
local ni = if s then s[2] else v
for q = 0, 2 do
wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0)
end
end
if col and C then
local ci = if s then s[3] else v
for q = 0, cc - 1 do
wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1)
end
end
if tex and T then
local ti = if s then s[4] else v
local tt = T[ti * 2 + 2] or 0
wf(tex.data, v * 8, T[ti * 2 + 1] or 0)
wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt)
end
end
local attrs: { [string]: Types.Accessor } = { POSITION = pos }
attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex
local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" }
if o.triangulate == false then
prim.mode = "polygons"
prim.faces = u32(outSizes)
end
return prim
end
-- split a -1 separated index list into corners + sizes
local function split(list: { number }): ({ number }, { number })
local corners, sizes = {}, {}
local run = 0
for _, x in list do
if x < 0 then
if run > 0 then
table.insert(sizes, run)
end
run = 0
else
table.insert(corners, x)
run += 1
end
end
if run > 0 then
table.insert(sizes, run)
end
return corners, sizes
end
-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners)
local function cornerList(list: { number }?): { number }?
if not list or #list == 0 then
return nil
end
local out = {}
for _, x in list do
if x >= 0 then
table.insert(out, x)
end
end
return out
end
local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local P = points(n, "coord", "point") or {}
local corners, sizes = split(nums(n, "coordIndex") or {})
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"),
C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"),
T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil,
tIdx = cornerList(nums(n, "texCoordIndex")),
}
return polyMesh(m, o, maxV)
end
-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts
local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local t = n.type
local P = points(n, "coord", "point") or {}
local np = #P // 3
local index = nums(n, "index")
local seq: { number }
if string.sub(t, 1, 7) == "Indexed" then
seq = index or {}
else
seq = {}
for i = 0, np - 1 do
seq[i + 1] = i
end
end
local corners, sizes = {}, {}
local function tri(a: number, b: number, c: number)
table.insert(corners, a)
table.insert(corners, b)
table.insert(corners, c)
table.insert(sizes, 3)
end
-- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips)
local function runs(): { { number } }
local out = {}
local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount")
if string.sub(t, 1, 7) == "Indexed" or not counts then
local cur = {}
for _, x in seq do
if x < 0 then
table.insert(out, cur)
cur = {}
else
table.insert(cur, x)
end
end
table.insert(out, cur)
else
local at = 1
for _, c in counts do
local cur = {}
for q = 0, c - 1 do
cur[q + 1] = seq[at + q]
end
at += c
table.insert(out, cur)
end
end
return out
end
if t == "IndexedTriangleSet" or t == "TriangleSet" then
for i = 1, #seq - 2, 3 do
tri(seq[i], seq[i + 1], seq[i + 2])
end
elseif t == "IndexedQuadSet" or t == "QuadSet" then
for i = 1, #seq - 3, 4 do
for q = 0, 3 do
table.insert(corners, seq[i + q])
end
table.insert(sizes, 4)
end
elseif string.find(t, "Fan", 1, true) then
for _, r in runs() do
for i = 2, #r - 1 do
tri(r[1], r[i], r[i + 1])
end
end
else
for _, r in runs() do
for i = 1, #r - 2 do
if i % 2 == 1 then
tri(r[i], r[i + 1], r[i + 2])
else
tri(r[i + 1], r[i], r[i + 2])
end
end
end
end
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer,
T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil,
}
return polyMesh(m, o, maxV)
end
local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0))
local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1)
local h: { number } = nums(n, "height") or {}
if nx < 2 or nz < 2 then
return nil, nil
end
if nx * nz > maxV then
return nil, "limit: elevation grid of " .. nx .. " x " .. nz
end
local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {}
for z = 0, nz - 1 do
for x = 0, nx - 1 do
table.insert(P, x * dx)
table.insert(P, h[z * nx + x + 1] or 0)
table.insert(P, z * dz)
table.insert(T, x / (nx - 1))
table.insert(T, z / (nz - 1))
end
end
for z = 0, nz - 2 do
for x = 0, nx - 2 do
local a = z * nx + x
-- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1
for _, c in { a, a + nx, a + nx + 1, a + 1 } do
table.insert(corners, c)
end
table.insert(sizes, 4)
end
end
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc,
cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T,
}
return polyMesh(m, o, maxV)
end
-- ------------------------------------------------------------------------------------------------ Extrusion
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 sub3(a: { number }, b: { number }): { number }
return { a[1] - b[1], a[2] - b[2], a[3] - b[3] }
end
local function norm(a: { number }): ({ number }, number)
local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l
end
-- rotate v about the unit axis k by angle a (Rodrigues)
local function rotate(v: { number }, k: { number }, a: number): { number }
local c, s = cos(a), sin(a)
local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c)
local kv = cross(k, v)
return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d }
end
local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 }
local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 }
local sc = nums(n, "scale") or { 1, 1 }
local ori = nums(n, "orientation") or { 0, 0, 1, 0 }
local ns, nc = #sp // 3, #cs // 2
if ns < 2 or nc < 2 then
return nil, nil
end
if ns * nc > maxV then
return nil, "limit: extrusion of " .. ns .. " x " .. nc
end
local spine = {}
for i = 1, ns do
spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] }
end
local function same(a: { number }, b: { number }): boolean
return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9
end
local closedSpine = same(spine[1], spine[ns])
local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9
-- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z
local Ys: { { number } }, Zs: { [number]: { number } } = {}, {}
for i = 1, ns do
local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil
local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil
local y = sub3(nxt or spine[i], prev or spine[i])
Ys[i] = norm(y)
if prev and nxt then
local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i])))
Zs[i] = if l > 1e-12 then z else nil
end
end
-- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction
local firstZ = nil
for i = 1, ns do
if Zs[i] then
firstZ = Zs[i]
break
end
end
for i = 1, ns do
if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then
Ys[i] = Ys[i - 1] or { 0, 1, 0 }
end
end
for i = 1, ns do
if not Zs[i] then
if firstZ then
Zs[i] = Zs[i - 1] or firstZ
else
local y = Ys[i]
local axis, l = norm(cross({ 0, 1, 0 }, y))
local ang = math.acos(math.clamp(y[2], -1, 1))
Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 }
end
end
if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then
Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] }
end
end
local nr = if closedSpine then ns - 1 else ns
local nring = if closedCs then nc - 1 else nc
local P = {}
for i = 1, nr do
local y, z = Ys[i], Zs[i]
local x = cross(y, z)
local si = if #sc >= i * 2 then i else 1
local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1
local oi = if #ori >= i * 4 then i else 1
local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0
for j = 1, nring do
local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz }
if ang ~= 0 then
v = rotate(v, ax, ang)
end
local s = spine[i]
table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3])
table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3])
table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3])
end
end
local corners, sizes = {}, {}
local function at(i: number, j: number): number
return ((i - 1) % nr) * nring + (j - 1) % nring
end
for i = 1, ns - 1 do
for j = 1, nc - 1 do
for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do
table.insert(corners, c)
end
table.insert(sizes, 4)
end
end
if not closedSpine then
if bool(n, "beginCap", true) then
for j = 1, nring do
table.insert(corners, at(1, j))
end
table.insert(sizes, nring)
end
if bool(n, "endCap", true) then
for j = nring, 1, -1 do
table.insert(corners, at(ns, j))
end
table.insert(sizes, nring)
end
end
return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV)
end
-- ------------------------------------------------------------------------------------------------ lines, points
local function lines(n: any, maxV: number): (any, string?)
local P = points(n, "coord", "point") or {}
local np = #P // 3
local C, cc = colors(n)
local perVertex = bool(n, "colorPerVertex", true)
local runs: { { number } } = {}
if n.type == "LineSet" then
local at = 0
for _, c in nums(n, "vertexCount") or {} do
local r = {}
for q = 0, c - 1 do
r[q + 1] = at + q
end
at += c
table.insert(runs, r)
end
else
local corners, sizes = split(nums(n, "coordIndex") or {})
local k = 0
for _, s in sizes do
local r = {}
for q = 1, s do
r[q] = corners[k + q]
end
k += s
table.insert(runs, r)
end
end
local cIdx = nums(n, "colorIndex") or {}
local cList = if perVertex then cornerList(cIdx) else nil
local vkey: { [string]: number } = {}
local src: { { number } } = {}
local out: { number } = {}
local k = 0
for li, r in runs do
local prev: number? = nil
for _, c in r do
k += 1
if c == nil or c < 0 or c >= np then
prev = nil
continue
end
local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1)
local key = c .. ":" .. ci
local v = vkey[key]
if not v then
v = #src
src[v + 1] = { c, ci }
vkey[key] = v
end
if prev then
table.insert(out, prev)
table.insert(out, v)
end
prev = v
end
end
if #src > maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
local pos = S.accessor(nil, "f32", 3, #src)
local col = if C then S.accessor(nil, "f32", cc, #src) else nil
for v, s in src do
for q = 0, 2 do
buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1])
end
if col and C then
for q = 0, cc - 1 do
buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1)
end
end
end
return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" }
end
local function pointSet(n: any, maxV: number): (any, string?)
local P = points(n, "coord", "point") or {}
local np = #P // 3
if np > maxV then
return nil, "limit: more than " .. maxV .. " points"
end
local C, cc = colors(n)
local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) }
if C then
local col = S.accessor(nil, "f32", cc, np)
for i = 0, np * cc - 1 do
buffer.writef32(col.data, i * 4, C[i + 1] or 1)
end
attrs.COLOR_0 = col
end
return { attributes = attrs, mode = "points" }
end
-- ------------------------------------------------------------------------------------------------ primitives
-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles)
local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive
local nv = #P // 3
if o.flipV ~= false then
for i = 2, #T, 2 do
T[i] = 1 - T[i]
end
end
return {
attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) },
indices = u32(I),
mode = "triangles",
}
end
local function box(n: any, o: Options): Types.Primitive
local s = vec(n, "size", { 2, 2, 2 })
local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2
local P, N, T, I = {}, {}, {}, {}
-- faces: normal, u axis, v axis (the specification's texture orientation)
local FACES = {
{ { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } },
{ { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } },
{ { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } },
}
for f, face in FACES do
local nn, u, v = face[1], face[2], face[3]
for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do
for q = 1, 3 do
local h = if q == 1 then hx elseif q == 2 then hy else hz
table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h)
table.insert(N, nn[q])
end
table.insert(T, (c[1] + 1) / 2)
table.insert(T, (c[2] + 1) / 2)
end
local b = (f - 1) * 4
for _, x in { 0, 1, 2, 0, 2, 3 } do
table.insert(I, b + x)
end
end
return direct(P, N, T, I, o)
end
-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z)
-- and runs counter-clockwise seen from +y
local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?)
for i = 0, segs do
local a = 2 * pi * i / segs
local x, z = -sin(a), -cos(a)
table.insert(P, x * r)
table.insert(P, y)
table.insert(P, z * r)
if N then
table.insert(N, x * (nr or 1))
table.insert(N, ny or 0)
table.insert(N, z * (nr or 1))
end
if T then
table.insert(T, i / segs)
table.insert(T, t)
end
end
end
-- a cap disc at height y facing ny (+1 / -1)
local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number)
local b = #P // 3
for i = 0, segs - 1 do
local a = 2 * pi * i / segs
local x, z = -sin(a), -cos(a)
table.insert(P, x * r)
table.insert(P, y)
table.insert(P, z * r)
table.insert(N, 0)
table.insert(N, ny)
table.insert(N, 0)
-- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom)
table.insert(T, x / 2 + 0.5)
table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5)
end
for i = 1, segs - 2 do
-- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom
if ny > 0 then
table.insert(I, b)
table.insert(I, b + i)
table.insert(I, b + i + 1)
else
table.insert(I, b)
table.insert(I, b + i + 1)
table.insert(I, b + i)
end
end
end
-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper)
local function band(I: { number }, a: number, b: number, segs: number)
for i = 0, segs - 1 do
table.insert(I, a + i)
table.insert(I, a + i + 1)
table.insert(I, b + i + 1)
table.insert(I, a + i)
table.insert(I, b + i + 1)
table.insert(I, b + i)
end
end
local function sphere(n: any, o: Options, segs: number): Types.Primitive
local r = num(n, "radius", 1)
local rings = math.max(2, segs // 2)
local P, N, T, I = {}, {}, {}, {}
for j = 0, rings do
local phi = pi * j / rings -- from the bottom
local y, rr = -cos(phi), sin(phi)
ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr)
end
for j = 0, rings - 1 do
band(I, j * (segs + 1), (j + 1) * (segs + 1), segs)
end
return direct(P, N, T, I, o)
end
local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive
local r = num(n, if cone then "bottomRadius" else "radius", 1)
local h = num(n, "height", 2)
local P, N, T, I = {}, {}, {}, {}
if bool(n, "side", true) then
-- side normals: a cone's lean outwards by its slope
local l = sqrt(r * r + h * h)
local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1
ring(P, N, T, segs, -h / 2, r, 0, ny, nr)
ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr)
band(I, 0, segs + 1, segs)
end
if not cone and bool(n, "top", true) then
cap(P, N, T, I, segs, h / 2, r, 1)
end
if bool(n, "bottom", true) then
cap(P, N, T, I, segs, -h / 2, r, -1)
end
return direct(P, N, T, I, o)
end
-- ------------------------------------------------------------------------------------------------ dispatch
-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here);
-- the second value of a success is the node's solid flag
function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any)
local t = n.type
local maxV = o.maxVertices or 2 ^ 24
local segs = math.clamp(math.floor(o.segments or 32), 3, 1024)
local solid = bool(n, "solid", true)
local prim: Types.Primitive?, err: string? = nil, nil
if t == "IndexedFaceSet" then
prim, err = faceSet(n, o, maxV)
elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then
prim, err = triSet(n, o, maxV)
elseif t == "ElevationGrid" then
prim, err = elevationGrid(n, o, maxV)
elseif t == "Extrusion" then
prim, err = extrusion(n, o, maxV)
elseif t == "IndexedLineSet" or t == "LineSet" then
prim, err = lines(n, maxV)
solid = false
elseif t == "PointSet" then
prim, err = pointSet(n, maxV)
solid = false
elseif t == "Box" then
prim = box(n, o)
elseif t == "Sphere" then
prim = sphere(n, o, segs)
elseif t == "Cylinder" then
prim = cylinder(n, o, segs, false)
elseif t == "Cone" then
prim = cylinder(n, o, segs, true)
else
return nil, nil
end
if not prim then
return nil, err
end
return prim, solid
end
return Geometry
+536
View File
@@ -0,0 +1,536 @@
--!strict
-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into
-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are
-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers,
-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO
-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside
-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations,
-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are
-- returned as nil, message ("line N: ...").
local Parse = {}
export type Node = { type: string, def: string?, fields: { [string]: any } }
export type Route = { from: Node, fromField: string, to: Node, toField: string }
export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? }
export type Graph = {
roots: { Node },
routes: { Route },
header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile
meta: { [string]: string }, -- META / WorldInfo statements
components: { string },
units: { [string]: { name: string, factor: number } },
protos: { [string]: Proto },
}
-- an IS reference in a PROTO body: fields[name] = { is = "protoField" }
export type IsRef = { is: string }
local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*"
local MAX_DEPTH = 200
local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true }
local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true }
-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared)
local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node
local done = memo[node]
if done then
return done
end
local out: Node = { type = node.type, def = node.def, fields = {} }
memo[node] = out
for k, v in node.fields do
if type(v) == "table" and type((v :: any).is) == "string" then
local name = (v :: any).is
local val = values[name]
if val == nil then
val = defaults[name]
end
out.fields[k] = val
elseif type(v) == "table" then
local arr = table.create(#v)
for i, x in v do
arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x
end
out.fields[k] = arr
else
out.fields[k] = v
end
end
return out
end
-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO
function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node?
if proto.extern or #proto.body == 0 then
return nil
end
local memo = {}
local first: Node? = nil
for _, n in proto.body do
local c = copy(n, values, proto.fields, memo)
first = first or c
end
if routes then
for _, r in proto.routes do
local from, to = memo[r.from], memo[r.to]
if from and to then
table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField })
end
end
end
local f = first :: Node
if def then
-- the instance gets its own copy of the node so its DEF name is its own
local out: Node = { type = f.type, def = def, fields = f.fields }
return out
end
return f
end
function Parse.parse(text: string): (Graph?, string?)
local n = #text
local p = 1
local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} }
local defs: { [string]: Node } = {}
local protos: { [string]: Proto } = graph.protos
local routes: { Route } = graph.routes
local failure: string? = nil
local depth = 0
local function line(at: number): number
local l = 1
for _ in gmatch(sub(text, 1, at), "\n") do
l += 1
end
return l
end
local function fail(msg: string)
if not failure then
failure = "line " .. line(p) .. ": " .. msg
end
end
-- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8
local v, enc = match(text, "^#VRML V(%S+) (%S+)")
if v then
graph.header.version, graph.header.encoding = v, enc
if v ~= "2.0" then
return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)"
end
else
v, enc = match(text, "^#X3D V(%S+) (%S+)")
if v then
graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true
end
end
-- the lexer: skip blanks, commas and comments; returns the next token kind and value
-- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof"
local function skip()
while true do
local q = find(text, "[^%s,]", p)
if not q then
p = n + 1
return
end
p = q
if byte(text, p) == 35 then -- '#'
local e = find(text, "[\r\n]", p)
p = if e then e else n + 1
else
return
end
end
end
local function token(): (string, any)
skip()
if p > n then
return "eof", nil
end
local c = byte(text, p)
if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ]
p += 1
return string.char(c), nil
elseif c == 34 then -- a string: \" and \\ escapes
local q = p + 1
local parts = {}
while true do
local e = find(text, '["\\]', q)
if not e then
fail("unterminated string")
p = n + 1
return "eof", nil
end
table.insert(parts, sub(text, q, e - 1))
if byte(text, e) == 92 then
table.insert(parts, sub(text, e + 1, e + 1))
q = e + 2
else
p = e + 1
return "str", table.concat(parts)
end
end
end
if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then
local s, e = find(text, "^[+-]?0[xX]%x+", p)
if not s then
s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p)
end
if not s then
s, e = find(text, "^[+-]?%d*%.?%d*", p)
end
local num = tonumber(sub(text, p, e))
if num then
p = (e :: number) + 1
return "num", num
end
if c == 46 then
p += 1
return ".", nil
end
-- +inf / -nan style words: read the word
local _, we = find(text, "^[^%s,%[%]{}#\"]+", p)
local w = sub(text, p, we)
p = (we :: number) + 1
local wl = string.lower(w)
local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil
if val == nil then
fail("bad number " .. w)
return "eof", nil
end
return "num", val
end
local s, e = find(text, ID1, p)
if s then
p = (e :: number) + 1
return "id", sub(text, s, e)
end
fail("unexpected character " .. sub(text, p, p))
p = n + 1
return "eof", nil
end
local function peek(): (string, any)
local save = p
local k, val = token()
p = save
return k, val
end
local parseNode: (first: string) -> (Node?, boolean)
local parseProto: (extern: boolean) -> ()
local parseRoute: () -> ()
-- a field value (after its name): an array of numbers / strings / booleans / nodes
local function value(): any
local k, val = token()
if k == "[" then
local out = {}
-- fast path: a bracket of plain numbers (big coordinate arrays)
local close = find(text, "]", p, true)
if close then
local seg = sub(text, p, close - 1)
if not find(seg, "[{}\"#]") then
local ok = true
for w in gmatch(seg, "[^%s,]+") do
local x = tonumber(w)
if x then
table.insert(out, x)
elseif w == "TRUE" or w == "FALSE" then
table.insert(out, w == "TRUE")
else
ok = false
break
end
end
if ok then
p = close + 1
return out
end
table.clear(out)
end
end
while not failure do
k, val = token()
if k == "]" then
return out
elseif k == "num" or k == "str" then
table.insert(out, val)
elseif k == "id" and (val == "TRUE" or val == "FALSE") then
table.insert(out, val == "TRUE")
elseif k == "id" and val == "NULL" then
continue
elseif k == "id" then
local node = parseNode(val)
if node then
table.insert(out, node)
end
else
fail("unexpected " .. k .. " in a [ ] value")
return out
end
end
return out
elseif k == "num" then
local out = { val }
while true do
local save = p
local k2, v2 = token()
if k2 ~= "num" then
p = save
break
end
table.insert(out, v2)
end
return out
elseif k == "str" then
return { val }
elseif k == "id" then
if val == "TRUE" or val == "FALSE" then
return { val == "TRUE" }
elseif val == "NULL" then
return {}
end
local node = parseNode(val)
return if node then { node } else {}
end
fail("missing field value")
return {}
end
-- the fields of a node body, up to its "}"
local function body(node: Node)
while not failure do
local k, name = token()
if k == "}" then
return
elseif k ~= "id" then
fail("expected a field name in " .. node.type .. ", got " .. k)
return
end
if name == "ROUTE" then
parseRoute()
elseif name == "PROTO" or name == "EXTERNPROTO" then
parseProto(name == "EXTERNPROTO")
elseif DECL[name] then
-- Script / shader interface: <access> <type> <name> [<value> | IS <name>]
local _, _t = token()
local fk, fname = token()
if fk ~= "id" then
fail("bad interface declaration in " .. node.type)
return
end
local pk, pv = peek()
if pk == "id" and pv == "IS" then
token()
local _, ref = token()
node.fields[fname] = { is = ref }
elseif HAS_VALUE[name] then
node.fields[fname] = value()
end
else
local pk, pv = peek()
if pk == "id" and pv == "IS" then
token()
local _, ref = token()
node.fields[name] = { is = ref }
else
node.fields[name] = value()
end
end
end
end
-- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { })
function parseNode(first: string): (Node?, boolean)
if first == "USE" then
local k, name = token()
if k ~= "id" then
fail("USE without a name")
return nil, false
end
local node = defs[name]
if not node then
fail("USE of an undefined name " .. tostring(name))
end
return node, true
end
local def: string? = nil
local typ = first
if first == "DEF" then
local k, name = token()
local k2, t2 = token()
if k ~= "id" or k2 ~= "id" then
fail("bad DEF")
return nil, false
end
def, typ = name, t2
end
local k = token()
if k ~= "{" then
fail("expected { after " .. typ)
return nil, false
end
depth += 1
if depth > MAX_DEPTH then
fail("limit: nodes nested deeper than " .. MAX_DEPTH)
return nil, false
end
local node: Node = { type = typ, def = def, fields = {} }
body(node)
depth -= 1
local proto = protos[typ]
if proto and not proto.extern then
local inst = Parse.expand(proto, node.fields, def, routes)
if inst then
node = inst
end
elseif proto then
(node :: any).extern = true
end
if def then
defs[def] = node
end
return node, false
end
-- ROUTE from.field TO to.field
function parseRoute()
local function path(): (string?, string?)
local k1, a = token()
local k2 = token()
local k3, b = token()
if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then
return nil, nil
end
return a, b
end
local a, af = path()
local k, to = token()
local b, bf = path()
if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then
fail("bad ROUTE")
return
end
local from, dst = defs[a :: string], defs[b :: string]
if from and dst then
table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string })
end
end
-- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url
function parseProto(extern: boolean)
local k, name = token()
if k ~= "id" or token() ~= "[" then
fail("bad PROTO")
return
end
local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
while not failure do
local k2, access = token()
if k2 == "]" then
break
elseif k2 ~= "id" or not DECL[access] then
fail("bad PROTO interface")
return
end
local _, _t = token()
local fk, fname = token()
if fk ~= "id" then
fail("bad PROTO interface")
return
end
if HAS_VALUE[access] and not extern then
proto.fields[fname] = value()
end
end
if extern then
value() -- the url list
protos[name] = proto
return
end
if token() ~= "{" then
fail("PROTO " .. tostring(name) .. " without a body")
return
end
-- the body has its own DEF names and its own routes
local outerDefs, outerRoutes = defs, routes
defs, routes = {}, proto.routes
while not failure do
local k3, w = token()
if k3 == "}" then
break
elseif k3 ~= "id" then
fail("bad PROTO body")
break
elseif w == "ROUTE" then
parseRoute()
elseif w == "PROTO" or w == "EXTERNPROTO" then
parseProto(w == "EXTERNPROTO")
else
local node = parseNode(w)
if node then
table.insert(proto.body, node)
end
end
end
defs, routes = outerDefs, outerRoutes
protos[name] = proto
end
-- statements
while not failure do
local k, w = token()
if k == "eof" then
break
elseif k ~= "id" then
fail("unexpected " .. k)
break
end
if w == "ROUTE" then
parseRoute()
elseif w == "PROTO" or w == "EXTERNPROTO" then
parseProto(w == "EXTERNPROTO")
elseif w == "PROFILE" then
local _, prof = token()
graph.header.profile = prof
elseif w == "COMPONENT" then
local _, comp = token() -- name:level is one id
table.insert(graph.components, tostring(comp))
elseif w == "META" then
local _, key = token()
local _, val = token()
graph.meta[tostring(key)] = tostring(val)
elseif w == "UNIT" then
local _, cat = token()
local _, uname = token()
local _, factor = token()
if type(cat) == "string" and type(factor) == "number" then
graph.units[cat] = { name = tostring(uname), factor = factor }
end
elseif w == "IMPORT" or w == "EXPORT" then
-- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene
local _, _a = token()
if peek() == "." then
token()
token()
end
local pk, pv = peek()
if pk == "id" and pv == "AS" then
token()
token()
end
else
local node = parseNode(w)
if node then
table.insert(graph.roots, node)
end
end
end
if failure then
return nil, failure
end
return graph, nil
end
return Parse
+750
View File
@@ -0,0 +1,750 @@
--!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("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Xml = require("@formats/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 formats-luau\n")
else
table.insert(out, "#VRML V2.0 utf8\n# written by formats-luau\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", "formats-luau")
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
+238
View File
@@ -0,0 +1,238 @@
--!strict
-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one
-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes;
-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their
-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE;
-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and
-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head /
-- meta, UNIT, component and the profile go into the graph header. Never throws.
local Xml = require("@formats/codecs/text/Xml")
local Parse = require("@formats/codecs/model/Vrml/Parse")
local VXml = {}
local GEOMETRY = {
"Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid",
"Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet",
"IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D",
"Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface",
}
local CONTAINER: { [string]: string } = {
Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material",
UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture",
MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform",
Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color",
TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord",
FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties",
LineProperties = "lineProperties",
}
for _, g in GEOMETRY do
CONTAINER[g] = "geometry"
end
local function container(el: Xml.Node, typ: string): string
local c = el.attrs.containerField
if type(c) == "string" and c ~= "" then
return c
end
if string.sub(typ, 1, 8) == "Metadata" then
return "metadata"
end
return CONTAINER[typ] or "children"
end
function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?)
local root = doc.root or doc
if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then
return nil, "no <X3D> root element"
end
local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} }
graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile
local defs: { [string]: Parse.Node } = {}
local protos = graph.protos
local routes = graph.routes
local depth = 0
local failure: string? = nil
local convert: (el: Xml.Node) -> Parse.Node?
local function route(el: Xml.Node)
local a = el.attrs
local from, to = defs[a.fromNode or ""], defs[a.toNode or ""]
local ff, tf = a.fromField, a.toField
if from and to and type(ff) == "string" and type(tf) == "string" then
table.insert(routes, { from = from, fromField = ff, to = to, toField = tf })
end
end
local declare: (el: Xml.Node, extern: boolean) -> ()
-- the child elements of a node into its fields
local function children(el: Xml.Node, node: Parse.Node)
for _, ch in el.children do
if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then
continue
end
local name = Xml.localName(ch.name)
if name == "ROUTE" then
route(ch)
elseif name == "IS" then
for _, c in Xml.children(ch, "connect") do
local nf, pf = c.attrs.nodeField, c.attrs.protoField
if nf and pf then
node.fields[nf] = { is = pf }
end
end
elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then
declare(ch, name == "ExternProtoDeclare")
elseif name == "field" or name == "fieldValue" then
continue -- Script / shader interfaces
else
local c = convert(ch)
if c then
local f = container(ch, if name == "ProtoInstance" then "" else name)
local list = node.fields[f]
if type(list) ~= "table" or (list :: any).is then
list = {}
node.fields[f] = list
end
table.insert(list, c)
end
end
end
end
-- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes
local function fieldValue(el: Xml.Node): any
if el.attrs.value ~= nil then
return el.attrs.value
end
local list = {}
for _, ch in el.children do
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
local c = convert(ch)
if c then
table.insert(list, c)
end
end
end
return list
end
function declare(el: Xml.Node, extern: boolean)
local name = el.attrs.name
if not name then
return
end
local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
local iface = if extern then el else Xml.child(el, "ProtoInterface")
if iface then
for _, f in Xml.children(iface, "field") do
if f.attrs.name then
proto.fields[f.attrs.name] = fieldValue(f)
end
end
end
local bodyEl = Xml.child(el, "ProtoBody")
if bodyEl and not extern then
local outerDefs, outerRoutes = defs, routes
defs, routes = {}, proto.routes
for _, ch in bodyEl.children do
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
local nm = Xml.localName(ch.name)
if nm == "ROUTE" then
route(ch)
elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then
declare(ch, nm == "ExternProtoDeclare")
else
local c = convert(ch)
if c then
table.insert(proto.body, c)
end
end
end
end
defs, routes = outerDefs, outerRoutes
end
protos[name] = proto
end
function convert(el: Xml.Node): Parse.Node?
local a = el.attrs
if a.USE then
return defs[a.USE]
end
depth += 1
if depth > 200 then
failure = failure or "limit: nodes nested deeper than 200"
depth -= 1
return nil
end
local typ = Xml.localName(el.name)
local node: any
if typ == "ProtoInstance" then
local proto = protos[a.name or ""]
local values = {}
for _, fv in Xml.children(el, "fieldValue") do
if fv.attrs.name then
values[fv.attrs.name] = fieldValue(fv)
end
end
local inst = proto and Parse.expand(proto, values, a.DEF, routes)
node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values }
else
node = { type = typ, def = a.DEF, fields = {} }
for k, v in a do
if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then
node.fields[k] = v
end
end
children(el, node)
end
depth -= 1
if a.DEF then
defs[a.DEF] = node
end
return node
end
for _, ch in root.children do
if type(ch) ~= "table" then
continue
end
local name = Xml.localName(ch.name)
if name == "head" then
for _, h in ch.children do
if type(h) == "table" then
local hn = Xml.localName(h.name)
if hn == "meta" and h.attrs.name then
graph.meta[h.attrs.name] = h.attrs.content or ""
elseif hn == "component" and h.attrs.name then
table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1"))
elseif hn == "unit" and h.attrs.category then
graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 }
end
end
end
elseif name == "Scene" then
local scene: Parse.Node = { type = "Scene", fields = {} }
children(ch, scene)
local list = scene.fields.children
if type(list) == "table" then
graph.roots = list
end
for f, v in scene.fields do
-- a top-level node with another containerField still shows
if f ~= "children" and type(v) == "table" then
for _, x in v do
table.insert(graph.roots, x)
end
end
end
end
end
if failure then
return nil, failure
end
return graph, nil
end
return VXml
+160
View File
@@ -0,0 +1,160 @@
--!strict
-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding
-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a
-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated
-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2.
--
-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content
-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } })
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/compress/Deflate")
local XmlCodec = require("@formats/codecs/text/Xml")
local Parse = require("@formats/codecs/model/Vrml/Parse")
local VXml = require("@formats/codecs/model/Vrml/Xml")
local Build = require("@formats/codecs/model/Vrml/Build")
local Write = require("@formats/codecs/model/Vrml/Write")
local Vrml = {}
export type Graph = Parse.Graph
export type Node = Parse.Node
export type Options = Build.Options & {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
maxBytes: number?, -- the inflated size of a gzipped file (default 2^28)
}
-- the bytes as text: gzip inflated, UTF-8 BOM dropped
local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?)
local b = if type(data) == "string" then buffer.fromstring(data) else data
if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then
local out, err = Deflate.gunzip(b)
if not out then
return nil, err
end
if buffer.len(out) > (maxBytes or 2 ^ 28) then
return nil, Err.new(Err.LIMIT, "inflated file over maxBytes")
end
b = out
end
local s = buffer.tostring(b)
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
return s, nil
end
local function code(msg: string): string
if string.find(msg, "unsupported", 1, true) then
return Err.UNSUPPORTED
elseif string.find(msg, "limit", 1, true) then
return Err.LIMIT
elseif string.find(msg, "unterminated", 1, true) then
return Err.TRUNCATED
end
return Err.CORRUPT
end
-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv)
function Vrml.parse(s: string): (Graph?, Err.Err?)
local g, msg = Parse.parse(s)
if not g then
return nil, Err.new(code(msg or "parse error"), msg or "parse error")
end
return g, nil
end
-- parseXml(text | XML document) -> the graph of an X3D XML file
function Vrml.parseXml(src: any): (Graph?, Err.Err?)
local doc = src
if type(src) == "string" then
local d, err = XmlCodec.decode(src)
if not d and err and err.code == Err.TRUNCATED and not string.find(src, "</X3D>", 1, true) then
-- VTK's X3D exporter leaves the root element open
d = XmlCodec.decode(src .. "\n</X3D>\n")
end
if not d then
return nil, err
end
doc = d
end
local g, msg = VXml.graph(doc)
if not g then
return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D")
end
return g, nil
end
-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED
function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?)
local s, err = text(data, opts and opts.maxBytes)
if not s then
return nil, err
end
local head = string.match(s, "^%s*(.?)")
if head == "<" then
return Vrml.parseXml(s)
end
if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then
return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)")
end
return Vrml.parse(s)
end
-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve
function Vrml.fetcher(opts: Options?): (uri: string) -> buffer?
return function(uri: string): buffer?
if not opts then
return nil
end
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri]
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
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
end
end
-- build(graph, opts?) -> Scene
function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.fetch = o.fetch or Vrml.fetcher(opts)
o.load = o.load or function(data: buffer): (any, string?)
local g, err = Vrml.graph(data, opts)
return g, if err then err.message else nil
end
local scene, msg = Build.scene(graph, o)
if not scene then
return nil, Err.new(code(msg or "build failed"), msg or "build failed")
end
return scene, nil
end
-- decode(bytes, opts?) -> Scene: graph + build
function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?)
local g, err = Vrml.graph(data, opts)
if not g then
return nil, err
end
return Vrml.build(g, opts)
end
-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files
function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local s, msg = Write.text(scene, opts or {})
if not s then
return nil, Err.new(Err.ARG, msg or "the scene could not be written")
end
return s, nil
end
return Vrml
+77
View File
@@ -0,0 +1,77 @@
--!strict
-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over
-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code.
-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD,
-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and
-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord,
-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided),
-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated
-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor ->
-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons
-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless
-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres).
-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet /
-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights,
-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials).
-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and
-- skins on write (the rest pose is written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Vrml = require("@formats/codecs/model/Vrml")
-- ------------------------------------------------------------------------------------------------ contract
local Wrl = {
name = "vrml",
category = "model",
extensions = { "wrl", "wrz", "vrml" },
mime = { "model/vrml", "x-world/x-vrml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
maxVertices: number?, -- per geometry (default 2^24)
}
export type EncodeOptions = {
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
name: string?, -- the destination's file name (names the image files)
flipV: boolean?, -- default true (the inverse of decode)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Wrl.sniff(r: Bytes.Reader): number
local head = r:peek(16)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.format = "vrml"
return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o)
end
-- ------------------------------------------------------------------------------------------------ encode
function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
o.encoding = "vrml97"
local text, err = Vrml.encode(scene, o)
if not text then
return nil, err
end
return buffer.fromstring(text), nil
end
return Wrl
+85
View File
@@ -0,0 +1,85 @@
--!strict
-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv,
-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares).
-- New code.
-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet,
-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA,
-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial /
-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField;
-- head meta, components and UNIT length (-> meta.unit).
-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the
-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras).
-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders,
-- H-Anim skinning, scripts.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Vrml = require("@formats/codecs/model/Vrml")
-- ------------------------------------------------------------------------------------------------ contract
local X3d = {
name = "x3d",
category = "model",
extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" },
mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
maxVertices: number?, -- per geometry (default 2^24)
}
export type EncodeOptions = {
encoding: ("xml" | "x3dv")?, -- default "xml"
format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
name: string?, -- the destination's file name (names the image files)
flipV: boolean?, -- default true (the inverse of decode)
}
-- ------------------------------------------------------------------------------------------------ sniff
function X3d.sniff(r: Bytes.Reader): number
local head = r:peek(1024)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.sub(head, 1, 5) == "#X3D " then
return 1
end
if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then
return 0.9
end
if string.find(head, "<X3D[%s>]") or string.find(head, "<!DOCTYPE X3D", 1, true) then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function X3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.format = "x3d"
return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o)
end
-- ------------------------------------------------------------------------------------------------ encode
function X3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
local classic = o.encoding == "x3dv" or o.format == "x3dv" or o.format == "x3dvz"
o.encoding = if classic then "x3dv" else "xml"
local text, err = Vrml.encode(scene, o)
if not text then
return nil, err
end
return buffer.fromstring(text), nil
end
return X3d