ws-3d: model/gltf (glTF 2.0 JSON + GLB read/write: accessors of every type incl. normalized/sparse/strided/padded matrices, PBR + KHR_materials_*, KHR_texture_transform, images kept encoded, samplers, cameras, KHR_lights_punctual, skins, animations, morph targets, KHR_mesh_quantization, extras/unknown extensions round trip); Khronos sample assets + gltfpack + assimp fixtures

This commit is contained in:
4DBug committed 2026-10-31 09:02:59 -05:00
1 parent 35891a06d1
commit 20ca5a054d
93 files changed
+5167 -5

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
--!strict
--!native
-- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene
-- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range
-- first (offsets, strides and counts against the buffer lengths); nothing here throws.
local Pack = {}
local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32
-- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is
-- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem =
-- cols * colBytes bytes each)
function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
if cols == 1 or colBytes == colStride then
if stride == elem then
bcopy(dst, 0, src, off, count * elem)
return
end
for i = 0, count - 1 do
bcopy(dst, i * elem, src, off + i * stride, elem)
end
return
end
for i = 0, count - 1 do
local s = off + i * stride
local d = i * elem
for c = 0, cols - 1 do
bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes)
end
end
end
-- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled)
function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
if cols == 1 or colBytes == colStride then
if stride == elem then
bcopy(dst, at, src, 0, count * elem)
return
end
for i = 0, count - 1 do
bcopy(dst, at + i * stride, src, i * elem, elem)
end
return
end
for i = 0, count - 1 do
local d = at + i * stride
local s = i * elem
for c = 0, cols - 1 do
bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes)
end
end
end
-- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element
-- idx[k] of dst becomes value k (values packed, elem bytes each)
function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean
for k = 0, n - 1 do
local i
if idxSize == 1 then
i = readu8(idx, idxOff + k)
elseif idxSize == 2 then
i = readu16(idx, idxOff + k * 2)
else
i = readu32(idx, idxOff + k * 4)
end
if i >= count then
return false
end
bcopy(dst, i * elem, values, valOff + k * elem, elem)
end
return true
end
return Pack
+661
View File
@@ -0,0 +1,661 @@
--!strict
-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type
-- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution,
-- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the
-- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the
-- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets,
-- scenes. glTF extras and unhandled extensions are kept in <object>.extras.gltf = { extras, extensions }.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Base64 = require("@formats/codecs/Base64")
local Pack = require("@formats/model/gltf/Pack")
local Read = {}
local COMPONENT: { [number]: { string } } = {
[5120] = { "i8", "snorm8" },
[5121] = { "u8", "unorm8" },
[5122] = { "i16", "snorm16" },
[5123] = { "u16", "unorm16" },
[5125] = { "u32", "" },
[5126] = { "f32", "" },
}
local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 }
local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 }
local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 }
local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" }
local WRAP = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" }
local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" }
-- the extensions this reader understands (everything else that is required -> UNSUPPORTED)
local KNOWN = {
KHR_lights_punctual = true,
KHR_mesh_quantization = true,
KHR_texture_transform = true,
KHR_materials_emissive_strength = true,
KHR_materials_unlit = true,
KHR_materials_clearcoat = true,
KHR_materials_transmission = true,
KHR_materials_volume = true,
KHR_materials_ior = true,
KHR_materials_specular = true,
KHR_materials_sheen = true,
KHR_materials_iridescence = true,
KHR_materials_anisotropy = true,
KHR_materials_dispersion = true,
KHR_materials_diffuse_transmission = true,
KHR_materials_variants = true,
KHR_materials_pbrSpecularGlossiness = true,
KHR_texture_basisu = true, -- the image stays encoded (image/ktx2)
EXT_texture_webp = true,
EXT_texture_avif = true,
KHR_node_visibility = true,
KHR_xmp_json_ld = true,
}
Read.KNOWN = KNOWN
export type Fetch = (uri: string) -> buffer?
type View = { buf: buffer, offset: number, length: number, stride: number? }
type Img = { data: buffer?, mime: string?, uri: string?, name: string? }
local function num(v: any, default: number): number
return if type(v) == "number" then v else default
end
local function int(v: any): number?
return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil
end
local function arr(v: any): { any }
return if type(v) == "table" then v else {}
end
local function str(v: any): string?
return if type(v) == "string" then v else nil
end
local function numbers(v: any, n: number): { number }?
if type(v) ~= "table" or #v ~= n then
return nil
end
for i = 1, n do
if type(v[i]) ~= "number" then
return nil
end
end
return table.move(v, 1, n, 1, {})
end
-- extras.gltf: the JSON extras and the extensions not turned into Scene fields
local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }?
local extras = obj.extras
local ext: { [string]: any }? = nil
if type(obj.extensions) == "table" then
for k, v in obj.extensions do
if not (handled and handled[k]) then
ext = ext or {}
local e: any = ext
e[k] = v
end
end
end
if extras == nil and ext == nil then
return nil
end
return { gltf = { extras = extras, extensions = ext } }
end
function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
if type(doc) ~= "table" then
return nil, Err.new(Err.CORRUPT, "the JSON is not an object")
end
local asset = doc.asset
if type(asset) ~= "table" or type(asset.version) ~= "string" then
return nil, Err.new(Err.CORRUPT, "no asset.version")
end
if string.sub(asset.version, 1, 1) ~= "2" then
return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)")
end
for _, e in arr(doc.extensionsRequired) do
if type(e) == "string" and not KNOWN[e] then
return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e)
end
end
local scene = Types.Scene.new()
-- buffers
local buffers: { buffer } = {}
local total = 0
for i, b in arr(doc.buffers) do
if type(b) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1))
end
local len = int(b.byteLength)
if not len then
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength")
end
total += len
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes")
end
local data: buffer? = nil
local uri = str(b.uri)
if uri == nil then
if i == 1 and bin then
data = bin
else
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk")
end
elseif string.sub(uri, 1, 5) == "data:" then
local d, derr = Base64.decodeDataUri(uri)
if not d then
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr))
end
data = d
else
data = fetch(uri)
if not data then
return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)")
end
end
if buffer.len(data :: buffer) < len then
return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength")
end
buffers[i] = data :: buffer
end
-- buffer views -> { buf, offset, length, stride }
local views: { View } = {}
for i, v in arr(doc.bufferViews) do
if type(v) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1))
end
local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength)
local b = bi and buffers[bi + 1]
if not b or not off or not len or off + len > buffer.len(b) then
return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range")
end
local stride = v.byteStride
if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then
return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride")
end
views[i] = { buf = b, offset = off, length = len, stride = stride }
end
-- accessors
local accessors: { Types.Accessor } = {}
for i, a in arr(doc.accessors) do
local label = "accessor " .. (i - 1)
if type(a) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad " .. label)
end
local ct, count, typ = a.componentType, int(a.count), a.type
local names = COMPONENT[ct]
local comps = TYPE_COMPONENTS[typ]
if not names or not count or not comps then
return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type")
end
local normalized = a.normalized == true
local tname = if normalized then names[2] else names[1]
if tname == "" then
return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1])
end
local size = SIZE[ct]
local cols = TYPE_COLUMNS[typ] or 1
local rows = comps // cols
local colBytes = rows * size
local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes
local elem = comps * size
local padded = cols * colStride
if count * elem > maxBytes then
return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes")
end
local data = buffer.create(count * elem)
local vi = a.bufferView
if vi ~= nil then
local view = int(vi) and views[vi + 1]
if not view then
return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView")
end
local off = int(a.byteOffset or 0)
if not off then
return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset")
end
local stride = view.stride or padded
if stride < padded and count > 1 then
return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element")
end
if count > 0 and off + (count - 1) * stride + padded > view.length then
return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView")
end
if count > 0 then
Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride)
end
end
local sp = a.sparse
if type(sp) == "table" then
local n = int(sp.count)
local si, sv = sp.indices, sp.values
if not n or type(si) ~= "table" or type(sv) ~= "table" then
return nil, Err.new(Err.CORRUPT, label .. ": bad sparse")
end
local isz = SIZE[si.componentType]
local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1]
local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0)
local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125
if not okType or not isz or not iv or not vv or not io or not vo then
return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values")
end
if io + n * isz > iv.length or vo + n * elem > vv.length then
return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView")
end
-- sparse values are tightly packed (matrices: padded columns, rare enough to repack first)
local vals, valOff = vv.buf, vv.offset + vo
if cols > 1 and colBytes ~= colStride then
vals = buffer.create(n * elem)
Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride)
valOff = 0
end
if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then
return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range")
end
end
local acc = Types.Scene.accessor(data, tname, comps, count)
if cols > 1 then
acc.matrix = true
end
acc.name = str(a.name)
accessors[i] = acc
end
local function accessor(v: any): Types.Accessor?
local k = int(v)
return if k then accessors[k + 1] else nil
end
-- images (kept encoded), samplers, textures
local images: { Img } = {}
for i, im in arr(doc.images) do
if type(im) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1))
end
local img: Img = { mime = str(im.mimeType), name = str(im.name) }
if im.bufferView ~= nil then
local view = int(im.bufferView) and views[im.bufferView + 1]
if not view then
return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView")
end
local d = buffer.create(view.length)
buffer.copy(d, 0, view.buf, view.offset, view.length)
img.data = d
elseif type(im.uri) == "string" then
if string.sub(im.uri, 1, 5) == "data:" then
local d, mime = Base64.decodeDataUri(im.uri)
if d then
img.data = d
img.mime = img.mime or mime
end
else
img.uri = im.uri
img.data = fetch(im.uri)
if not img.mime then
local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "")
img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil
end
end
end
images[i] = img
end
local samplers: { Types.Sampler } = {}
for i, s in arr(doc.samplers) do
if type(s) == "table" then
samplers[i] = {
wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any,
wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any,
filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil,
minFilter = MIN_FILTER[s.minFilter],
}
else
samplers[i] = {}
end
end
local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" }
for i, t in arr(doc.textures) do
if type(t) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1))
end
local src = t.source
local handled = {}
if type(t.extensions) == "table" then
for _, e in TEX_SOURCE_EXT do
local x = t.extensions[e]
if type(x) == "table" and int(x.source) then
src = x.source
handled[e] = true
break
end
end
end
local img = int(src) and images[src + 1]
local tex: Types.Texture = { name = str(t.name) }
if img then
tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri
tex.name = tex.name or img.name
end
local si = int(t.sampler)
if si and samplers[si + 1] then
tex.sampler = table.clone(samplers[si + 1])
end
tex.extras = keep(t, handled)
if next(handled) then
-- the fallback image (t.source) and the extension name, for writing the texture back the same way
tex.extras = tex.extras or { gltf = {} }
local g = (tex.extras :: any).gltf
g.sourceExtension = next(handled)
local fb = int(t.source) and images[t.source + 1]
if fb then
g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri }
end
end
table.insert(scene.textures, tex)
end
-- materials
local function texRef(info: any): Types.TextureRef?
if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then
return nil
end
local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil }
local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform
if type(tt) == "table" then
r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) }
end
return r
end
-- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef
local function convertExt(v: any): any
if type(v) ~= "table" then
return v
end
local out = if Types.isObject(v) or next(v) == nil then Types.object() else {}
for k, x in v do
if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then
out[k] = texRef(x)
else
out[k] = convertExt(x)
end
end
return out
end
for i, m in arr(doc.materials) do
if type(m) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1))
end
local mat = Types.Scene.material(str(m.name))
local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {}
mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 }
mat.baseColorTexture = texRef(pbr.baseColorTexture)
mat.metallic = num(pbr.metallicFactor, 1)
mat.roughness = num(pbr.roughnessFactor, 1)
mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture)
mat.normalTexture = texRef(m.normalTexture)
mat.occlusionTexture = texRef(m.occlusionTexture)
mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 }
mat.emissiveTexture = texRef(m.emissiveTexture)
mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque"
mat.alphaCutoff = num(m.alphaCutoff, 0.5)
mat.doubleSided = m.doubleSided == true
if type(m.extensions) == "table" then
local ext = {}
for k, v in m.extensions do
ext[k] = convertExt(v)
end
mat.extensions = ext
end
local kept = keep(m, mat.extensions and (mat.extensions :: any) or {})
local pk = keep(pbr, nil)
if pk then
kept = kept or { gltf = {} }
local kk: any = kept
kk.gltf.pbr = pk.gltf
end
mat.extras = kept
table.insert(scene.materials, mat)
end
-- meshes
for i, m in arr(doc.meshes) do
if type(m) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1))
end
local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) }
for k, p in arr(m.primitives) do
if type(p) ~= "table" or type(p.attributes) ~= "table" then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1))
end
if type(p.extensions) == "table" and (p.extensions.KHR_draco_mesh_compression or p.extensions.EXT_meshopt_compression) then
return nil, Err.new(Err.UNSUPPORTED, "compressed primitives (Draco / meshopt)")
end
local attrs: { [string]: Types.Accessor } = {}
local count = -1
for name, ai in p.attributes do
local a = accessor(ai)
if not a then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name)))
end
if count >= 0 and a.count ~= count then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1))
end
count = a.count
attrs[name] = a
end
local mode = MODES[if p.mode == nil then 4 else p.mode]
if not mode then
return nil, Err.new(Err.CORRUPT, "bad primitive mode")
end
local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil }
if p.indices ~= nil then
local ind = accessor(p.indices)
if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then
return nil, Err.new(Err.CORRUPT, "bad indices accessor")
end
-- indices must reference existing vertices
local get = Types.Scene.reader(ind) :: any
for q = 0, ind.count - 1 do
if get(q, 0) >= count then
return nil, Err.new(Err.CORRUPT, "index out of range")
end
end
prim.indices = ind
end
if type(p.targets) == "table" then
local targets = {}
for ti, t in p.targets do
local tt = {}
for name, ai in (if type(t) == "table" then t else {}) do
local a = accessor(ai)
if not a or a.count ~= count then
return nil, Err.new(Err.CORRUPT, "bad morph target accessor")
end
tt[name] = a
end
targets[ti] = tt
end
prim.targets = targets
end
prim.extras = keep(p, nil)
table.insert(mesh.primitives, prim)
end
table.insert(scene.meshes, mesh)
end
-- cameras, lights
for _, c in arr(doc.cameras) do
if type(c) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad camera")
end
if c.type == "orthographic" and type(c.orthographic) == "table" then
local o = c.orthographic
table.insert(scene.cameras, { name = str(c.name), type = "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) })
else
local p = if type(c.perspective) == "table" then c.perspective else {}
table.insert(scene.cameras, { name = str(c.name), type = "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil })
end
end
local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual
for _, l in arr(lp and lp.lights) do
if type(l) == "table" then
local spot = if type(l.spot) == "table" then l.spot else {}
table.insert(scene.lights, {
name = str(l.name),
type = if l.type == "spot" or l.type == "point" then l.type else "directional",
color = numbers(l.color, 3) or { 1, 1, 1 },
intensity = num(l.intensity, 1),
range = if type(l.range) == "number" then l.range else nil,
innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil,
outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil,
})
end
end
-- nodes
local nodes = arr(doc.nodes)
for i, n in nodes do
if type(n) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1))
end
local node: Types.Node = { name = str(n.name), children = {} }
for _, c in arr(n.children) do
if not int(c) or c >= #nodes then
return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child")
end
table.insert(node.children, c + 1)
end
if int(n.mesh) and n.mesh < #scene.meshes then
node.mesh = n.mesh + 1
end
if int(n.camera) and n.camera < #scene.cameras then
node.camera = n.camera + 1
end
if int(n.skin) and n.skin < #arr(doc.skins) then
node.skin = n.skin + 1
end
node.matrix = numbers(n.matrix, 16)
node.translation = numbers(n.translation, 3)
node.rotation = numbers(n.rotation, 4)
node.scale = numbers(n.scale, 3)
node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil
local handled = {}
local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual
if type(le) == "table" and int(le.light) and le.light < #scene.lights then
node.light = le.light + 1
handled.KHR_lights_punctual = true
end
node.extras = keep(n, handled)
scene.nodes[i] = node
end
-- a node may have one parent only, and no cycles
local parent: { [number]: number } = {}
for i, node in scene.nodes do
for _, c in node.children do
if parent[c] or c == i then
return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child")
end
parent[c] = i
end
end
for i in scene.nodes do
local seen, p = 0, parent[i]
while p do
seen += 1
if seen > #scene.nodes then
return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle")
end
p = parent[p]
end
end
-- skins
for _, s in arr(doc.skins) do
if type(s) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad skin")
end
local joints = {}
for _, j in arr(s.joints) do
if not int(j) or j >= #scene.nodes then
return nil, Err.new(Err.CORRUPT, "skin: bad joint")
end
table.insert(joints, j + 1)
end
table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil })
end
-- animations
for _, a in arr(doc.animations) do
if type(a) ~= "table" then
return nil, Err.new(Err.CORRUPT, "bad animation")
end
local anim: Types.Animation = { name = str(a.name), channels = {} }
local samplersA = arr(a.samplers)
local skipped = {}
for _, c in arr(a.channels) do
local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1]
local target = type(c) == "table" and c.target
if not s or type(target) ~= "table" then
return nil, Err.new(Err.CORRUPT, "animation: bad channel")
end
local input, output = accessor(s.input), accessor(s.output)
if not input or not output then
return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors")
end
local path = target.path
if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then
table.insert(anim.channels, {
node = target.node + 1,
path = path,
input = input,
output = output,
interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR",
})
else
table.insert(skipped, c) -- KHR_animation_pointer and friends
end
end
if #skipped > 0 then
local aa: any = anim
aa.extras = { gltf = { skippedChannels = #skipped } }
end
table.insert(scene.animations, anim)
end
-- scenes
local scenes = arr(doc.scenes)
local list = {}
for _, s in scenes do
local roots = {}
for _, n in arr(type(s) == "table" and s.nodes) do
if int(n) and n < #scene.nodes and not parent[n + 1] then
table.insert(roots, n + 1)
end
end
table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil })
end
local which = int(doc.scene) or 0
if list[which + 1] then
scene.roots = list[which + 1].nodes
elseif #list == 0 then
for i in scene.nodes do
if not parent[i] then
table.insert(scene.roots, i)
end
end
end
-- root extensions other than the lights, asset info
local rootExt = nil
if type(doc.extensions) == "table" then
for k, v in doc.extensions do
if k ~= "KHR_lights_punctual" then
rootExt = rootExt or {}
rootExt[k] = v
end
end
end
scene.meta.up = "y"
scene.meta.unit = 1
scene.meta.gltf = {
asset = asset,
scenes = list,
scene = if doc.scene ~= nil then which + 1 else nil,
extensionsUsed = doc.extensionsUsed,
extensionsRequired = doc.extensionsRequired,
extensions = rootExt,
extras = doc.extras,
}
return scene, nil
end
return Read
+696
View File
@@ -0,0 +1,696 @@
--!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
+248
View File
@@ -0,0 +1,248 @@
--!strict
-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and
-- binary (.glb). New code.
-- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every
-- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR
-- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior,
-- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept,
-- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime,
-- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins,
-- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a
-- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer.
-- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths).
-- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes <name>.bin and the
-- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension).
-- Not supported: Draco (KHR_draco_mesh_compression) and meshopt (EXT_meshopt_compression) compressed primitives
-- (UNSUPPORTED), KHR_animation_pointer channels (skipped and counted in the animation's extras).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Json = require("@formats/codecs/Json")
local Base64 = require("@formats/codecs/Base64")
local Read = require("@formats/model/gltf/Read")
local Write = require("@formats/model/gltf/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Gltf = {
name = "gltf",
category = "model",
extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths
files: { [string]: any }?, -- or: the files by uri
maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30)
}
export type EncodeOptions = {
binary: boolean?, -- write GLB (default: when opts.format is "glb")
format: string?, -- "glb" -> binary (set by the api from the destination's extension)
external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs)
files: { [string]: any }?, -- receives <name>.bin and images with external = true
name: string?, -- the destination's file name (names the external files)
embedImages: boolean?, -- default true (false with external = true)
}
-- ------------------------------------------------------------------------------------------------ constants
local GLB_MAGIC = 0x46546C67 -- "glTF"
local CHUNK_JSON = 0x4E4F534A
local CHUNK_BIN = 0x004E4942
-- ------------------------------------------------------------------------------------------------ sniff
function Gltf.sniff(r: Bytes.Reader): number
if r:peek(4) == "glTF" then
return 1
end
local head = r:peek(1024)
local s = string.gsub(head, "^\239\187\191", "")
if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then
return 0.9
end
if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetcher(opts: DecodeOptions?): Read.Fetch
return function(uri: string): buffer?
if not opts then
return nil
end
local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string
return string.char(tonumber(h, 16) :: number)
end)
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri] or opts.files[decoded]
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, uri)
v = if ok then res else nil
end
if type(v) == "string" then
return buffer.fromstring(v)
end
return if type(v) == "buffer" then v else nil
end
end
-- the JSON text and BIN chunk of a GLB
local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?)
local magic, version, length = r:u32le(), r:u32le(), r:u32le()
if r.err then
return nil, nil, r.err
end
if magic ~= GLB_MAGIC then
return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic")
end
if version ~= 2 then
return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version)
end
if length > r:size() then
return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8)
end
local json: string? = nil
local bin: buffer? = nil
while r:tell() + 8 <= length do
local clen, ctype = r:u32le(), r:u32le()
if clen > length - r:tell() then
return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8)
end
if ctype == CHUNK_JSON and json == nil then
json = r:string(clen)
elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then
bin = r:bytes(clen)
else
r:skip(clen)
end
if r.err then
return nil, nil, r.err
end
end
if not json then
return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk")
end
return json, bin, nil
end
function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local binary = r:peek(4) == "glTF"
local text: string?, bin: buffer?
if binary then
local t, b, err = glb(r)
if not t then
return nil, err
end
text, bin = t, b
else
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
end
local doc, jerr = Json.decode(text :: string)
if doc == nil then
return nil, jerr
end
local scene, err = Read.scene(doc, bin, fetcher(opts), opts)
if not scene then
return nil, err
end
scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" }
function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local binary = opts and (opts.binary or opts.format == "glb") or false
local external = opts and opts.external == true and type(opts.files) == "table" and not binary
local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external
local out, err = Write.build(scene, { binary = binary, embedImages = embedImages })
if not out then
return nil, err
end
local doc = out.doc
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local files = opts and opts.files
-- images: data: URIs, or files
if doc.images then
local n = 0
for _, im in doc.images do
if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then
for _, o in out.images do
if o.name == im.uri then
if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then
im.uri = Base64.dataUri(o.data, o.mime or "image/png")
else
n += 1
local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png")
files[fname] = o.data
im.uri = fname
end
break
end
end
elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then
for _, o in out.images do
if o.name == im.uri then
files[im.uri] = o.data
end
end
end
end
end
local binLen = buffer.len(out.bin)
if binLen > 0 then
local b = Types.object()
b.byteLength = binLen
if not binary then
if external then
local fname = base .. ".bin"
b.uri = fname
local ff: any = files
ff[fname] = out.bin
else
b.uri = Base64.dataUri(out.bin, "application/octet-stream")
end
end
doc.buffers = { b }
end
local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 })
if not text then
return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr))
end
if not binary then
return buffer.fromstring(text :: string), nil
end
local jpad = (4 - #(text :: string) % 4) % 4
local bpad = (4 - binLen % 4) % 4
local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad)
w:u32le(GLB_MAGIC)
w:u32le(2)
local lenAt = w:tell()
w:u32le(0)
w:u32le(#(text :: string) + jpad)
w:u32le(CHUNK_JSON)
w:string(text :: string)
w:string(string.rep(" ", jpad))
if binLen > 0 then
w:u32le(binLen + bpad)
w:u32le(CHUNK_BIN)
w:bytes(out.bin)
w:fill(0, bpad)
end
w:setU32le(lenAt, w:tell())
return w:finish(), nil
end
return Gltf