Files
rosetta/src/Formats/model/gltf/Write.luau
T

697 lines
22 KiB
Luau

--!strict
-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex
-- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires),
-- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither),
-- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats,
-- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their
-- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first
-- for concave faces).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pack = require("@formats/model/gltf/Pack")
local Write = {}
local object = Types.object
local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 }
local SIZE = Types.COMPONENT_SIZE
local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true }
local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 }
local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 }
local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 }
-- attribute types the core spec allows (others need KHR_mesh_quantization)
local CORE = {
POSITION = { f32 = true },
NORMAL = { f32 = true },
TANGENT = { f32 = true },
TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true },
COLOR = { f32 = true, unorm8 = true, unorm16 = true },
JOINTS = { u8 = true, u16 = true },
WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true },
}
export type Options = { embedImages: boolean?, binary: boolean? }
export type Out = { doc: any, bin: buffer, images: { { data: buffer, mime: string?, name: string } } }
local function convert(acc: Types.Accessor, to: string): Types.Accessor
local get = Types.Scene.reader(acc) :: (number, number) -> number
local out = Types.Scene.accessor(nil, to, acc.components, acc.count)
local w = if to == "f32" then buffer.writef32 else buffer.writeu32
local size = SIZE[to]
for i = 0, acc.count - 1 do
for c = 0, acc.components - 1 do
local v = get(i, c)
if to == "u32" then
v = math.clamp(math.floor(v), 0, 4294967295)
end
w(out.data, (i * acc.components + c) * size, v)
end
end
out.matrix = acc.matrix
out.name = acc.name
return out
end
local function checkAcc(acc: any, label: string): Err.Err?
if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then
return Err.new(Err.ARG, label .. ": not an accessor")
end
if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then
return Err.new(Err.ARG, label .. ": data is smaller than count x components")
end
return nil
end
function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?)
local binary = opts and opts.binary or false
local embedImages = not (opts and opts.embedImages == false)
local doc: { [string]: any } = object()
local used: { [string]: boolean } = {}
local required: { [string]: boolean } = {}
local bin = Bytes.writer(65536)
local views: { any } = {}
local accessors: { any } = {}
local accIndex: { [any]: number } = {}
local failure: Err.Err? = nil
local function view(data: buffer, length: number, target: number?, stride: number?): number
local pad = (4 - bin:tell() % 4) % 4
bin:fill(0, pad)
local v = object()
v.buffer = 0
v.byteOffset = bin:tell()
v.byteLength = length
v.target = target
v.byteStride = stride
bin:bytes(data, 0, length)
table.insert(views, v)
return #views - 1
end
-- accessor(acc, usage, attribute?) -> the glTF index (0-based)
local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number
local known = accIndex[acc]
if known then
return known
end
local err = checkAcc(acc, attribute or usage)
if err then
failure = failure or err
return 0
end
local a = acc
if usage == "index" then
if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then
a = convert(a, "u32")
end
elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then
a = convert(a, "f32")
end
if attribute then
local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute
local core = CORE[kind]
if core and not core[a.type] then
used.KHR_mesh_quantization = true
required.KHR_mesh_quantization = true
end
end
local size = SIZE[a.type]
local comps = a.components
local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16)
local cols = if isMat then math.sqrt(comps) else 1
local colBytes = (comps // cols) * size
local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes
local elem = comps * size
local padded = cols * colStride
local stride = padded
local byteStride: number? = nil
if usage == "vertex" and padded % 4 ~= 0 then
stride = (padded + 3) // 4 * 4
byteStride = stride
end
local data = a.data
local length = a.count * stride
if stride ~= elem then
data = buffer.create(length)
Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride)
end
local g = object()
g.bufferView = view(data, length, if usage == "vertex" then 34962 elseif usage == "index" then 34963 else nil, byteStride)
g.componentType = CT[a.type]
g.normalized = if NORMALIZED[a.type] then true else nil
g.count = a.count
g.type = if isMat then ({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] else ({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps]
g.name = acc.name
if not g.type then
failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type")
return 0
end
if attribute == "POSITION" or usage == "input" then
-- min / max of the raw component values
local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count)
local get = Types.Scene.reader(raw) :: (number, number) -> number
local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge)
for i = 0, a.count - 1 do
for c = 1, comps do
local v = get(i, c - 1)
if v < lo[c] then
lo[c] = v
end
if v > hi[c] then
hi[c] = v
end
end
end
if a.count > 0 then
g.min, g.max = lo, hi
end
end
table.insert(accessors, g)
local index = #accessors - 1
accIndex[acc] = index
return index
end
-- extras.gltf -> extras / extensions fields of a glTF object
local function restore(g: any, extras: any)
local saved = type(extras) == "table" and extras.gltf
if type(saved) ~= "table" then
return
end
if saved.extras ~= nil then
g.extras = saved.extras
end
if type(saved.extensions) == "table" then
g.extensions = g.extensions or object()
for k, v in saved.extensions do
if g.extensions[k] == nil then
g.extensions[k] = v
used[k] = true
end
end
end
end
-- images, samplers, textures
local images: { any } = {}
local imageOut: { { data: buffer, mime: string?, name: string } } = {}
local imageIndex: { [any]: number } = {}
local function image(data: buffer?, mime: string?, uri: string?, name: string?): number?
local key: any = data or uri
if key == nil then
return nil
end
if imageIndex[key] then
return imageIndex[key]
end
local im = object()
im.name = name
if data then
if binary then
im.bufferView = view(data, buffer.len(data), nil, nil)
im.mimeType = mime or "image/png"
elseif embedImages then
im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name
im.mimeType = mime
table.insert(imageOut, { data = data, mime = mime, name = im.uri })
else
im.uri = uri or ("\0file" .. (#images + 1))
im.mimeType = mime
table.insert(imageOut, { data = data, mime = mime, name = im.uri })
end
else
im.uri = uri
im.mimeType = mime
end
table.insert(images, im)
imageIndex[key] = #images - 1
return #images - 1
end
local samplers: { any } = {}
local samplerIndex: { [string]: number } = {}
local function sampler(s: Types.Sampler?): number?
if type(s) ~= "table" then
return nil
end
local g = object()
g.wrapS = if s.wrapS then WRAP[s.wrapS] else nil
g.wrapT = if s.wrapT then WRAP[s.wrapT] else nil
g.magFilter = if s.filter == "nearest" then 9728 elseif s.filter == "linear" then 9729 else nil
g.minFilter = if s.minFilter then MIN_FILTER[s.minFilter] else nil
local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter))
if samplerIndex[key] == nil then
table.insert(samplers, g)
samplerIndex[key] = #samplers - 1
end
return samplerIndex[key]
end
local textures: { any } = {}
for i, t in scene.textures or {} do
if type(t) ~= "table" then
return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table")
end
local g = object()
g.name = t.name
g.sampler = sampler(t.sampler)
local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil
local srcExt = saved and saved.sourceExtension
local img = image(t.data, t.mime, t.uri, t.name)
if srcExt and img then
g.extensions = object()
local e = object()
e.source = img
g.extensions[srcExt] = e
used[srcExt] = true
local fb = saved.fallback
if type(fb) == "table" then
g.source = image(fb.data, fb.mime, fb.uri, nil)
end
if g.source == nil then
required[srcExt] = true
end
else
g.source = img
end
restore(g, t.extras)
table.insert(textures, g)
end
local function texInfo(r: any, kind: string?): any
if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then
return nil
end
local g = object()
g.index = r.texture - 1
if r.texCoord and r.texCoord ~= 0 then
g.texCoord = r.texCoord
end
if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then
g.scale = r.scale
end
if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then
g.strength = r.strength
end
if type(r.transform) == "table" then
local tt = object()
tt.offset = r.transform.offset
tt.scale = r.transform.scale
tt.rotation = r.transform.rotation
tt.texCoord = r.transform.texCoord
g.extensions = object()
g.extensions.KHR_texture_transform = tt
used.KHR_texture_transform = true
end
return g
end
local function extValue(v: any, key: string?): any
if type(v) ~= "table" then
return v
end
if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then
return texInfo(v, if key == "normalTexture" or key == "clearcoatNormalTexture" then "normal" else nil)
end
local out = if Types.isObject(v) or next(v) == nil then object() else {}
for k, x in v do
out[k] = extValue(x, if type(k) == "string" then k else nil)
end
return out
end
-- materials
local materials: { any } = {}
for i, m in scene.materials or {} do
if type(m) ~= "table" then
return nil, Err.new(Err.ARG, "material " .. i .. ": not a table")
end
local g = object()
g.name = m.name
local pbr = object()
local bc = m.baseColor or { 1, 1, 1, 1 }
if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then
pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 }
end
pbr.baseColorTexture = texInfo(m.baseColorTexture)
if m.metallic ~= nil and m.metallic ~= 1 then
pbr.metallicFactor = m.metallic
end
if m.roughness ~= nil and m.roughness ~= 1 then
pbr.roughnessFactor = m.roughness
end
pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture)
local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil
if saved and saved.pbr then
restore(pbr, { gltf = saved.pbr })
end
g.pbrMetallicRoughness = pbr
g.normalTexture = texInfo(m.normalTexture, "normal")
g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion")
g.emissiveTexture = texInfo(m.emissiveTexture)
local em = m.emissive or { 0, 0, 0 }
if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then
g.emissiveFactor = { em[1], em[2], em[3] }
end
if m.alphaMode == "mask" then
g.alphaMode = "MASK"
if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then
g.alphaCutoff = m.alphaCutoff
end
elseif m.alphaMode == "blend" then
g.alphaMode = "BLEND"
end
if m.doubleSided then
g.doubleSided = true
end
if type(m.extensions) == "table" then
g.extensions = object()
for k, v in m.extensions do
g.extensions[k] = extValue(v, nil)
used[k] = true
end
end
restore(g, m.extras)
table.insert(materials, g)
end
-- meshes
local meshes: { any } = {}
for i, mesh in scene.meshes or {} do
if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then
return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives")
end
local g = object()
g.name = mesh.name
g.primitives = {}
for k, p in mesh.primitives do
if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then
return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k))
end
local gp = object()
gp.attributes = object()
local names = {}
for name in p.attributes do
table.insert(names, name)
end
table.sort(names)
for _, name in names do
gp.attributes[name] = accessor(p.attributes[name], "vertex", name)
end
local mode = p.mode or "triangles"
local indices = p.indices
if mode == "polygons" then
-- fan-triangulate
local faces = p.faces
local getf = faces and Types.Scene.reader(faces)
local n = if indices then indices.count else p.attributes.POSITION.count
local geti = if indices then Types.Scene.reader(indices) else nil
if not faces or not getf or (indices and not geti) then
return nil, Err.new(Err.ARG, "polygons without faces")
end
local list = {}
local at = 0
for f = 0, faces.count - 1 do
local c = getf(f, 0)
if at + c > n then
return nil, Err.new(Err.ARG, "faces run past the indices")
end
for a = 1, c - 2 do
for _, j in { at, at + a, at + a + 1 } do
table.insert(list, if geti then geti(j, 0) else j)
end
end
at += c
end
local ib = buffer.create(#list * 4)
for q, v in list do
buffer.writeu32(ib, (q - 1) * 4, v)
end
indices = Types.Scene.accessor(ib, "u32", 1, #list)
mode = "triangles"
end
if MODES[mode] == nil then
return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode))
end
if indices then
gp.indices = accessor(indices, "index", nil)
end
if mode ~= "triangles" then
gp.mode = MODES[mode]
end
if type(p.material) == "number" and materials[p.material] then
gp.material = p.material - 1
end
if type(p.targets) == "table" and #p.targets > 0 then
gp.targets = {}
for _, t in p.targets do
local gt = object()
local tn = {}
for name in t do
table.insert(tn, name)
end
table.sort(tn)
for _, name in tn do
gt[name] = accessor(t[name], "vertex", nil)
end
table.insert(gp.targets, gt)
end
end
restore(gp, p.extras)
table.insert(g.primitives, gp)
end
g.weights = mesh.weights
restore(g, mesh.extras)
table.insert(meshes, g)
end
-- cameras, lights
local cameras: { any } = {}
for _, c in scene.cameras or {} do
local g = object()
g.name = c.name
g.type = c.type
local p = object()
if c.type == "orthographic" then
p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100
g.orthographic = p
else
g.type = "perspective"
p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar
g.perspective = p
end
table.insert(cameras, g)
end
local lights: { any } = {}
for _, l in scene.lights or {} do
local g = object()
g.name = l.name
g.type = l.type
if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then
g.color = { l.color[1], l.color[2], l.color[3] }
end
if l.intensity ~= nil and l.intensity ~= 1 then
g.intensity = l.intensity
end
if l.type ~= "directional" then
g.range = l.range
end
if l.type == "spot" then
local s = object()
s.innerConeAngle = if l.innerCone and l.innerCone ~= 0 then l.innerCone else nil
s.outerConeAngle = if l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 then l.outerCone else nil
g.spot = s
end
table.insert(lights, g)
end
-- nodes
local nodes: { any } = {}
local nodeCount = #(scene.nodes or {})
for i, n in scene.nodes or {} do
if type(n) ~= "table" then
return nil, Err.new(Err.ARG, "node " .. i .. ": not a table")
end
local g = object()
g.name = n.name
if n.children and #n.children > 0 then
g.children = {}
for _, c in n.children do
if type(c) ~= "number" or c < 1 or c > nodeCount then
return nil, Err.new(Err.ARG, "node " .. i .. ": bad child")
end
table.insert(g.children, c - 1)
end
end
if n.mesh and meshes[n.mesh] then
g.mesh = n.mesh - 1
end
if n.camera and cameras[n.camera] then
g.camera = n.camera - 1
end
if n.skin and scene.skins[n.skin] then
g.skin = n.skin - 1
end
if n.matrix then
local ident = true
for k = 1, 16 do
if n.matrix[k] ~= Types.Scene.IDENTITY[k] then
ident = false
end
end
if not ident then
g.matrix = n.matrix
end
else
g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale
end
g.weights = n.weights
if n.light and lights[n.light] then
g.extensions = object()
local le = object()
le.light = n.light - 1
g.extensions.KHR_lights_punctual = le
used.KHR_lights_punctual = true
end
restore(g, n.extras)
table.insert(nodes, g)
end
-- skins
local skins: { any } = {}
for _, s in scene.skins or {} do
local g = object()
g.name = s.name
g.joints = {}
for _, j in s.joints or {} do
table.insert(g.joints, j - 1)
end
if s.inverseBindMatrices then
local ibm = s.inverseBindMatrices
if ibm.matrix == nil and ibm.components == 16 then
ibm.matrix = true
end
g.inverseBindMatrices = accessor(ibm, "other", nil)
end
if s.skeleton then
g.skeleton = s.skeleton - 1
end
table.insert(skins, g)
end
-- animations
local animations: { any } = {}
for _, a in scene.animations or {} do
local g = object()
g.name = a.name
g.channels, g.samplers = {}, {}
local samplerOf: { [string]: number } = {}
for _, c in a.channels or {} do
local input = accessor(c.input, "input", nil)
local output = accessor(c.output, "other", nil)
local key = input .. "/" .. output .. "/" .. tostring(c.interpolation)
if samplerOf[key] == nil then
local s = object()
s.input, s.output = input, output
if c.interpolation and c.interpolation ~= "LINEAR" then
s.interpolation = c.interpolation
end
table.insert(g.samplers, s)
samplerOf[key] = #g.samplers - 1
end
local ch = object()
ch.sampler = samplerOf[key]
ch.target = object()
ch.target.node = c.node - 1
ch.target.path = c.path
table.insert(g.channels, ch)
end
table.insert(animations, g)
end
if failure then
return nil, failure
end
-- scenes: the original list (meta.gltf.scenes) when it is there, else the roots
local meta = if type(scene.meta) == "table" then scene.meta else {}
local mg = type(meta.gltf) == "table" and meta.gltf or {}
local scenes = {}
if type(mg.scenes) == "table" and #mg.scenes > 0 then
for _, s in mg.scenes do
local g = object()
g.name = s.name
g.nodes = {}
for _, n in s.nodes or {} do
if nodes[n] then
table.insert(g.nodes, n - 1)
end
end
restore(g, s.extras)
table.insert(scenes, g)
end
-- the current roots replace the default scene's list
local which = mg.scene or 1
if scenes[which] then
scenes[which].nodes = {}
for _, r in scene.roots or {} do
table.insert(scenes[which].nodes, r - 1)
end
end
doc.scene = (mg.scene or 1) - 1
else
local g = object()
g.nodes = {}
for _, r in scene.roots or {} do
table.insert(g.nodes, r - 1)
end
table.insert(scenes, g)
doc.scene = 0
end
local asset = object()
asset.version = "2.0"
asset.generator = "formats-luau"
if type(mg.asset) == "table" then
asset.copyright = mg.asset.copyright
asset.minVersion = mg.asset.minVersion
asset.extras = mg.asset.extras
end
doc.asset = asset
-- root extensions kept from the source (variants, ...), the lights
if type(mg.extensions) == "table" then
doc.extensions = object()
for k, v in mg.extensions do
doc.extensions[k] = v
used[k] = true
end
end
if #lights > 0 then
doc.extensions = doc.extensions or object()
local lp = object()
lp.lights = lights
doc.extensions.KHR_lights_punctual = lp
used.KHR_lights_punctual = true
end
doc.extras = mg.extras
local function list(t: { [string]: boolean }): { string }?
local out = {}
for k in t do
table.insert(out, k)
end
table.sort(out)
return if #out > 0 then out else nil
end
-- the source's required extensions that are still used stay required
for _, e in (if type(mg.extensionsRequired) == "table" then mg.extensionsRequired else {}) do
if used[e] then
required[e] = true
end
end
doc.extensionsUsed = list(used)
doc.extensionsRequired = list(required)
doc.scenes = scenes
doc.nodes = if #nodes > 0 then nodes else nil
doc.meshes = if #meshes > 0 then meshes else nil
doc.materials = if #materials > 0 then materials else nil
doc.textures = if #textures > 0 then textures else nil
doc.images = if #images > 0 then images else nil
doc.samplers = if #samplers > 0 then samplers else nil
doc.cameras = if #cameras > 0 then cameras else nil
doc.skins = if #skins > 0 then skins else nil
doc.animations = if #animations > 0 then animations else nil
doc.accessors = if #accessors > 0 then accessors else nil
doc.bufferViews = if #views > 0 then views else nil
return { doc = doc, bin = bin:finish(), images = imageOut }, nil
end
return Write