merge ws/3d: obj stl ply off vox gltf/glb, ops/MeshOps, codecs Base64/MeshFlatten, api sibling files + texture encoding

This commit is contained in:
4DBug committed 2026-10-31 09:08:22 -05:00
commit 91eba2bc24
145 files changed
+16413 -17

No files matched your search

+72
View File
@@ -182,6 +182,78 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
{
name = "gltf",
category = "model",
path = "model/gltf",
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 },
load = function()
return require("@formats/model/gltf")
end,
},
{
name = "obj",
category = "model",
path = "model/obj",
extensions = { "obj" },
mime = { "model/obj" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true },
load = function()
return require("@formats/model/obj")
end,
},
{
name = "off",
category = "model",
path = "model/off",
extensions = { "off" },
mime = { "model/off", "text/plain" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
load = function()
return require("@formats/model/off")
end,
},
{
name = "ply",
category = "model",
path = "model/ply",
extensions = { "ply" },
mime = { "model/ply", "application/ply" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true },
load = function()
return require("@formats/model/ply")
end,
},
{
name = "stl",
category = "model",
path = "model/stl",
extensions = { "stl" },
mime = { "model/stl", "application/sla" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false },
load = function()
return require("@formats/model/stl")
end,
},
{
name = "vox",
category = "model",
path = "model/vox",
extensions = { "vox" },
mime = { "model/x-vox" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true },
load = function()
return require("@formats/model/vox")
end,
},
{
name = "bmfont",
category = "font",
+271 -13
View File
@@ -197,21 +197,66 @@ export type VideoDecoder = {
}
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no
-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255,
-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the
-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load.
--
-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference
-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the
-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture
-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write
-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil,
-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you.
--
-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look
-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it
-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the
-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`.
export type Accessor = {
data: buffer, -- tightly packed
type: "f32" | "u8" | "u16" | "u32" | "i8" | "i16" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
components: number, -- 1 (SCALAR) .. 4 (VEC4), 16 (MAT4)
data: buffer, -- tightly packed, little endian
type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4)
count: number,
matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4
name: string?,
}
export type Primitive = {
attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0
attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom
-- attributes start with "_" (glTF convention: PLY extra vertex properties, ...)
indices: Accessor?,
mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip",
-- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false;
-- MeshOps.triangulate turns them into triangles)
mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons",
faces: Accessor?,
material: number?, -- index into scene.materials (1-based)
targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas)
extras: { [string]: any }?,
}
export type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? }
export type Sampler = {
wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat"
wrapT: ("repeat" | "clamp" | "mirror")?,
filter: ("linear" | "nearest")?, -- magnification
minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case)
}
export type Texture = {
name: string?,
image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format
data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file)
mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ...
uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded
sampler: Sampler?,
extras: { [string]: any }?,
}
export type TextureRef = {
texture: number, -- index into scene.textures (1-based)
texCoord: number?, -- TEXCOORD_n set (default 0)
scale: number?, -- normalTexture scale
strength: number?, -- occlusionTexture strength
-- KHR_texture_transform (texCoord overrides the ref's texCoord)
transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?,
}
export type Mesh = { name: string?, primitives: { Primitive } }
export type Texture = { image: Image?, uri: string?, sampler: { wrapS: string?, wrapT: string?, filter: string? }? }
export type TextureRef = { texture: number, texCoord: number?, transform: { offset: { number }?, scale: { number }?, rotation: number? }? }
export type Material = {
name: string?,
baseColor: { number }, -- r, g, b, a linear 0..1
@@ -226,6 +271,9 @@ export type Material = {
alphaMode: "opaque" | "mask" | "blend",
alphaCutoff: number,
doubleSided: boolean,
-- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit
-- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs
extensions: { [string]: any }?,
extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ...
}
export type Node = {
@@ -235,17 +283,52 @@ export type Node = {
camera: number?,
light: number?,
skin: number?,
voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes)
translation: { number }?, -- TRS, or matrix (column-major 4x4), not both
rotation: { number }?, -- quaternion x, y, z, w
scale: { number }?,
matrix: { number }?,
weights: { number }?, -- morph target weights
extras: { [string]: any }?,
}
export type Camera = { type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
export type Light = { type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
export type Skin = { joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
export type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
export type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
export type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
export type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" }
export type Animation = { name: string?, channels: { Channel } }
-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index
export type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric)
export type Voxels = {
kind: "voxels",
name: string?,
size: { number }, -- x, y, z cells
data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z)
palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models)
materials: { [number]: VoxelMaterial }?, -- by palette index
}
local Voxels = {}
-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own)
function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels
local pal = palette
if not pal then
local p = table.create(255)
for i = 1, 255 do
p[i] = { i, i, i, 255 }
end
pal = p
end
return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil }
end
-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check
function Voxels.get(v: Voxels, x: number, y: number, z: number): number
return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z))
end
function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number)
buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index)
end
Types.Voxels = Voxels
export type Scene = {
kind: "scene",
nodes: { Node },
@@ -257,6 +340,7 @@ export type Scene = {
lights: { Light },
skins: { Skin },
animations: { Animation },
voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels
meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any },
}
@@ -273,11 +357,30 @@ function Scene.new(): Scene
lights = {},
skins = {},
animations = {},
voxels = nil,
meta = {},
}
end
function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor
return { data = data, type = type, components = components, count = count }
-- the byte size of one component of an accessor type
local COMPONENT_SIZE: { [string]: number } = {
f32 = 4,
f64 = 8,
u8 = 1,
u16 = 2,
u32 = 4,
i8 = 1,
i16 = 2,
i32 = 4,
unorm8 = 1,
unorm16 = 2,
snorm8 = 1,
snorm16 = 2,
}
Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE)
-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer)
function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor
local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4))
return { data = d, type = type, components = components, count = count }
end
function Scene.material(name: string?): Material
return {
@@ -301,6 +404,161 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
end
Types.Scene = Scene
-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted
-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type.
function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
local d, n, t = acc.data, acc.components, acc.type
local size = COMPONENT_SIZE[t]
if not size or type(d) ~= "buffer" then
return nil
end
local stride = n * size
local rb = buffer
if t == "f32" then
local f = rb.readf32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
elseif t == "f64" then
local f = rb.readf64
return function(i: number, c: number): number
return f(d, i * stride + c * 8)
end
elseif t == "u8" or t == "unorm8" then
local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1
return function(i: number, c: number): number
return f(d, i * stride + c) * k
end
elseif t == "u16" or t == "unorm16" then
local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1
return function(i: number, c: number): number
return f(d, i * stride + c * 2) * k
end
elseif t == "u32" then
local f = rb.readu32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
elseif t == "i8" then
local f = rb.readi8
return function(i: number, c: number): number
return f(d, i * stride + c)
end
elseif t == "snorm8" then
local f = rb.readi8
return function(i: number, c: number): number
return math.max(f(d, i * stride + c) / 127, -1)
end
elseif t == "i16" then
local f = rb.readi16
return function(i: number, c: number): number
return f(d, i * stride + c * 2)
end
elseif t == "snorm16" then
local f = rb.readi16
return function(i: number, c: number): number
return math.max(f(d, i * stride + c * 2) / 32767, -1)
end
elseif t == "i32" then
local f = rb.readi32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
end
return nil
end
-- the identity and products of column-major 4x4 matrices (flat arrays of 16)
local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })
Scene.IDENTITY = IDENTITY
function Scene.mul(a: { number }, b: { number }): { number }
local m = table.create(16, 0)
for col = 0, 3 do
for row = 0, 3 do
local s = 0
for k = 0, 3 do
s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
end
m[col * 4 + row + 1] = s
end
end
return m
end
-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S)
function Scene.nodeMatrix(node: Node): { number }
if node.matrix and #node.matrix == 16 then
return node.matrix
end
local t, r, sc = node.translation, node.rotation, node.scale
if not t and not r and not sc then
return IDENTITY
end
local tx, ty, tz = 0, 0, 0
if t then
tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
end
local x, y, z, w = 0, 0, 0, 1
if r then
x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1
end
local sx, sy, sz = 1, 1, 1
if sc then
sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1
end
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
return {
(1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0,
(2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0,
(2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0,
tx, ty, tz, 1,
}
end
export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number }
-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots
-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent.
function Scene.flatten(scene: Scene): { Placed }
local out: { Placed } = {}
local nodes = scene.nodes or {}
local roots = scene.roots
if not roots or #roots == 0 then
local child = {}
for _, n in nodes do
for _, c in n.children or {} do
child[c] = true
end
end
roots = {}
for i in nodes do
if not child[i] then
table.insert(roots, i)
end
end
end
local seen: { [number]: boolean } = {}
local function visit(i: number, parent: { number })
local node = nodes[i]
if not node or seen[i] then
return
end
seen[i] = true
local m = Scene.nodeMatrix(node)
local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m)
local mesh = node.mesh and scene.meshes[node.mesh]
if mesh then
for _, p in mesh.primitives do
table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number })
end
end
for _, c in node.children or {} do
visit(c, world)
end
end
for _, r in roots do
visit(r, IDENTITY)
end
return out
end
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
+140
View File
@@ -0,0 +1,140 @@
--!strict
--!native
-- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
-- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and
-- both alphabets; any other character is an error. Never throws.
--
-- local Base64 = require("@formats/codecs/Base64")
-- local s = Base64.encode(buf) -- string ("" for an empty buffer)
-- local b, err = Base64.decode(s) -- buffer | nil, "message"
-- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message
local Base64 = {}
local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
local ENC = buffer.fromstring(ALPHA)
local ENC_URL = buffer.fromstring(ALPHA_URL)
-- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad
local DEC = buffer.create(256)
buffer.fill(DEC, 0, 255)
for i = 1, 64 do
buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1)
end
buffer.writeu8(DEC, string.byte("-"), 62)
buffer.writeu8(DEC, string.byte("_"), 63)
for _, c in { 9, 10, 13, 32 } do
buffer.writeu8(DEC, c, 64)
end
buffer.writeu8(DEC, string.byte("="), 65)
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding.
function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string
local o = math.clamp(offset or 0, 0, buffer.len(buf))
local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o)
local enc = if opts and opts.url then ENC_URL else ENC
local pad = not (opts and opts.pad == false)
local full = n // 3
local rest = n - full * 3
local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1)
local out = buffer.create(outLen)
local p = 0
for i = 0, full - 1 do
local q = o + i * 3
local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2)
writeu8(out, p, readu8(enc, v // 262144))
writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
writeu8(out, p + 3, readu8(enc, v % 64))
p += 4
end
if rest > 0 then
local q = o + full * 3
local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0)
writeu8(out, p, readu8(enc, v // 262144))
writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
if rest == 2 then
writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
elseif pad then
writeu8(out, p + 2, 61)
end
if pad then
writeu8(out, p + 3, 61)
end
end
return buffer.tostring(out)
end
-- decode(s) -> buffer | nil, message
function Base64.decode(s: string | buffer): (buffer?, string?)
local src = if type(s) == "string" then buffer.fromstring(s) else s
local n = buffer.len(src)
local out = buffer.create((n // 4 + 1) * 3)
local acc, bits, p = 0, 0, 0
local padded = false
for i = 0, n - 1 do
local d = readu8(DEC, readu8(src, i))
if d < 64 then
if padded then
return nil, "data after padding"
end
acc = acc * 64 + d
bits += 6
if bits >= 8 then
bits -= 8
local byte = acc // (2 ^ bits)
writeu8(out, p, byte % 256)
p += 1
acc = acc % (2 ^ bits)
end
elseif d == 65 then
padded = true
elseif d ~= 64 then
return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i)
end
end
if bits >= 6 then
return nil, "truncated base64 (a single character in the last group)"
end
local res = buffer.create(p)
buffer.copy(res, 0, out, 0, p)
return res, nil
end
-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[<mime>][;params][;base64],<data>" (percent-encoded data
-- when not base64)
function Base64.decodeDataUri(uri: string): (buffer?, string?)
if string.sub(uri, 1, 5) ~= "data:" then
return nil, "not a data: URI"
end
local comma = string.find(uri, ",", 6, true)
if not comma then
return nil, "data: URI without a comma"
end
local head = string.sub(uri, 6, comma - 1)
local isB64 = string.sub(head, -7) == ";base64"
local mime = string.match(head, "^([^;]*)") or ""
if mime == "" then
mime = "text/plain"
end
local body = string.sub(uri, comma + 1)
if isB64 then
local b, err = Base64.decode(body)
if not b then
return nil, err
end
return b, mime
end
local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string
return string.char(tonumber(h, 16) :: number)
end)
return buffer.fromstring(decoded), mime
end
-- dataUri(buf, mime) -> "data:<mime>;base64,..."
function Base64.dataUri(buf: buffer, mime: string?): string
return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
end
return Base64
+556
View File
@@ -0,0 +1,556 @@
--!strict
-- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are),
-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring
-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices,
-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one
-- (ops/MeshOps.merge is the editing-side equivalent).
-- Never throws: bad input returns nil, message.
local Types = require("@formats/Types")
local Flatten = {}
local readf32, readf64 = buffer.readf32, buffer.readf64
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32
local SIZE = Types.COMPONENT_SIZE
-- normalized integer types: their scale (raw / scale = the normalized value)
local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 }
export type Attr = {
type: string, -- the accessor type shared by every part ("f32" when the parts disagree)
components: number,
raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers
values: { number }, -- count * components
}
export type PartInfo = {
prim: Types.Primitive,
mesh: Types.Mesh?,
node: Types.Node?,
firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh
vertexCount: number,
firstFace: number, -- 0-based offset of the part's faces
faceCount: number,
identity: boolean, -- no transform was applied
}
export type Merged = {
count: number, -- vertices
attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read
sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud)
corners: { number }, -- 0-based vertex indices, face after face
parts: { PartInfo },
}
-- ------------------------------------------------------------------------------------------------ accessors
-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg
function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
if type(acc) ~= "table" or type(acc.data) ~= "buffer" then
return nil, "accessor without a data buffer"
end
local t, comps, count = acc.type, acc.components, acc.count
local size = SIZE[t]
if size == nil then
return nil, "unknown accessor type " .. tostring(t)
end
if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then
return nil, "bad accessor components / count"
end
local n = count * comps
local d: buffer = acc.data
if buffer.len(d) < n * size then
return nil, "accessor data shorter than count * components"
end
local out = table.create(n)
if t == "f32" then
for i = 0, n - 1 do
out[i + 1] = readf32(d, i * 4)
end
elseif t == "f64" then
for i = 0, n - 1 do
out[i + 1] = readf64(d, i * 8)
end
elseif t == "u8" or t == "unorm8" then
for i = 0, n - 1 do
out[i + 1] = readu8(d, i)
end
elseif t == "u16" or t == "unorm16" then
for i = 0, n - 1 do
out[i + 1] = readu16(d, i * 2)
end
elseif t == "u32" then
for i = 0, n - 1 do
out[i + 1] = readu32(d, i * 4)
end
elseif t == "i8" or t == "snorm8" then
for i = 0, n - 1 do
out[i + 1] = readi8(d, i)
end
elseif t == "i16" or t == "snorm16" then
for i = 0, n - 1 do
out[i + 1] = readi16(d, i * 2)
end
else -- i32
for i = 0, n - 1 do
out[i + 1] = readi32(d, i * 4)
end
end
local scale = NORM[t]
if scale and not raw then
local signed = t == "snorm8" or t == "snorm16"
for i = 1, n do
local v = out[i] / scale
out[i] = if signed and v < -1 then -1 else v
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ transforms
local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
-- column-major 4x4 product a * b
local function mul(a: { number }, b: { number }): { number }
local m = table.create(16, 0)
for c = 0, 3 do
for r = 0, 3 do
local s = 0
for k = 0, 3 do
s += a[k * 4 + r + 1] * b[c * 4 + k + 1]
end
m[c * 4 + r + 1] = s
end
end
return m
end
local function numList(v: any, n: number): boolean
if type(v) ~= "table" then
return false
end
for i = 1, n do
if type(v[i]) ~= "number" then
return false
end
end
return true
end
-- a node's local matrix (nil: none), or nil, message
local function localMatrix(node: any): ({ number }?, string?)
if node.matrix ~= nil then
if not numList(node.matrix, 16) then
return nil, "node matrix is not 16 numbers"
end
local m = table.create(16)
for i = 1, 16 do
m[i] = node.matrix[i]
end
return m, nil
end
local t, q, s = node.translation, node.rotation, node.scale
if t == nil and q == nil and s == nil then
return nil, nil
end
if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then
return nil, "bad node translation / rotation / scale"
end
local x, y, z, w = 0, 0, 0, 1
if q then
x, y, z, w = q[1], q[2], q[3], q[4]
end
local sx, sy, sz = 1, 1, 1
if s then
sx, sy, sz = s[1], s[2], s[3]
end
local tx, ty, tz = 0, 0, 0
if t then
tx, ty, tz = t[1], t[2], t[3]
end
return {
(1 - 2 * (y * y + z * z)) * sx,
(2 * (x * y + z * w)) * sx,
(2 * (x * z - y * w)) * sx,
0,
(2 * (x * y - z * w)) * sy,
(1 - 2 * (x * x + z * z)) * sy,
(2 * (y * z + x * w)) * sy,
0,
(2 * (x * z + y * w)) * sz,
(2 * (y * z - x * w)) * sz,
(1 - 2 * (x * x + y * y)) * sz,
0,
tx,
ty,
tz,
1,
},
nil
end
local function isIdentity(m: { number }): boolean
for i = 1, 16 do
if m[i] ~= IDENTITY[i] then
return false
end
end
return true
end
type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? }
-- the primitive instances of a scene in traversal order, or nil, message
local function instances(scene: any): ({ Instance }?, string?)
local out: { Instance } = {}
local nodes, meshes = scene.nodes, scene.meshes
if type(nodes) ~= "table" or type(meshes) ~= "table" then
return nil, "scene without nodes / meshes tables"
end
local function addMesh(mi: any, node: Types.Node?, m: { number }?): string?
local mesh = meshes[mi]
if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then
return "node refers to a missing mesh " .. tostring(mi)
end
for _, prim in mesh.primitives do
if type(prim) ~= "table" or type(prim.attributes) ~= "table" then
return "bad primitive"
end
table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m })
end
return nil
end
local visiting: { [number]: boolean } = {}
local function visit(ni: any, parent: { number }?, depth: number): string?
local node = nodes[ni]
if type(node) ~= "table" then
return "missing node " .. tostring(ni)
end
if depth > 256 or visiting[ni] then
return "node hierarchy is cyclic or too deep"
end
visiting[ni] = true
local m, merr = localMatrix(node)
if merr then
return merr
end
local world = if m and parent then mul(parent, m) elseif m then m else parent
if node.mesh ~= nil then
local e = addMesh(node.mesh, node, world)
if e then
return e
end
end
if type(node.children) == "table" then
for _, c in node.children do
local e = visit(c, world, depth + 1)
if e then
return e
end
end
end
visiting[ni] = nil
return nil
end
local roots = scene.roots
if type(roots) == "table" and #roots > 0 then
for _, ri in roots do
local e = visit(ri, nil, 0)
if e then
return nil, e
end
end
elseif #nodes > 0 then
local isChild: { [number]: boolean } = {}
for _, n in nodes do
if type(n) == "table" and type(n.children) == "table" then
for _, c in n.children do
isChild[c] = true
end
end
end
for i = 1, #nodes do
if not isChild[i] then
local e = visit(i, nil, 0)
if e then
return nil, e
end
end
end
else
for i = 1, #meshes do
local e = addMesh(i, nil, nil)
if e then
return nil, e
end
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ faces
-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message
local function faces(prim: any, nv: number): (any, any, string?)
local mode = prim.mode or "triangles"
if mode == "points" then
return "points", nil, nil
elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then
return "skip", nil, nil
end
local idx: { number }
if prim.indices ~= nil then
local v, err = Flatten.numbers(prim.indices, true)
if not v then
return nil, nil, "indices: " .. tostring(err)
end
idx = v
else
idx = table.create(nv)
for i = 1, nv do
idx[i] = i - 1
end
end
for i = 1, #idx do
local v = idx[i]
if v < 0 or v >= nv or v % 1 ~= 0 then
return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv)
end
end
if mode == "triangles" then
local n = #idx - #idx % 3
if n ~= #idx then
local c = table.create(n)
table.move(idx, 1, n, 1, c)
idx = c
end
return false, idx, nil
elseif mode == "polygons" then
if prim.faces == nil then
return nil, nil, "polygons primitive without faces"
end
local sizes, err = Flatten.numbers(prim.faces, true)
if not sizes then
return nil, nil, "faces: " .. tostring(err)
end
local total = 0
for i = 1, #sizes do
local s = sizes[i]
if s < 0 or s % 1 ~= 0 then
return nil, nil, "bad face size"
end
total += s
end
if total ~= #idx then
return nil, nil, "face sizes do not add up to the index count"
end
return sizes, idx, nil
elseif mode == "triangle_strip" or mode == "triangle_fan" then
local c = {}
for i = 3, #idx do
if mode == "triangle_fan" then
table.insert(c, idx[1])
table.insert(c, idx[i - 1])
table.insert(c, idx[i])
elseif i % 2 == 1 then
table.insert(c, idx[i - 2])
table.insert(c, idx[i - 1])
table.insert(c, idx[i])
else
table.insert(c, idx[i - 1])
table.insert(c, idx[i - 2])
table.insert(c, idx[i])
end
end
return false, c, nil
end
return nil, nil, "unknown primitive mode " .. tostring(mode)
end
-- ------------------------------------------------------------------------------------------------ merge
-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0
local function fill(name: string, t: string, raw: boolean): number
if string.sub(name, 1, 6) ~= "COLOR_" then
return 0
end
return if raw and NORM[t] then NORM[t] else 1
end
local function f32(v: number): number
local b = buffer.create(4)
buffer.writef32(b, 0, v)
return buffer.readf32(b, 0)
end
-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always).
-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then).
function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?)
if type(scene) ~= "table" then
return nil, "not a scene"
end
local list, lerr = instances(scene)
if not list then
return nil, lerr
end
local triangulate = opts and opts.triangulate or false
-- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count
local types: { [string]: string } = {}
local comps: { [string]: number } = {}
local used: { Instance } = {}
for _, inst in list do
local mode = inst.prim.mode or "triangles"
if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then
local pos = inst.prim.attributes.POSITION
if type(pos) ~= "table" then
return nil, "primitive without POSITION"
end
table.insert(used, inst)
for name, acc in inst.prim.attributes do
if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then
local t = acc.type
if types[name] == nil then
types[name] = t
elseif types[name] ~= t then
types[name] = "f32"
end
comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0)
end
end
end
end
if (comps.POSITION or 3) < 3 then
return nil, "POSITION needs 3 components"
end
local attrs: { [string]: Attr } = {}
for name, t in types do
local raw = NORM[t] ~= nil
if name == "POSITION" or name == "NORMAL" then
raw = false
end
attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} }
end
local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} }
local sizes: { number } = {}
local anyFaces = false
local corners = merged.corners
for _, inst in used do
local prim: any = inst.prim
local posAcc = prim.attributes.POSITION
local nv = tonumber(posAcc.count) or 0
local m = inst.matrix
local identity = m == nil or isIdentity(m :: { number })
local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity }
for name, a in attrs do
local acc = prim.attributes[name]
local dst = a.values
local n0 = #dst
local ac = a.components
if acc == nil then
local f = fill(name, a.type, a.raw)
for i = 1, nv * ac do
dst[n0 + i] = f
end
else
if acc.count ~= nv then
return nil, name .. " count differs from POSITION"
end
local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type)
if not vals then
return nil, name .. ": " .. tostring(err)
end
local sc = acc.components
if a.raw and acc.type ~= a.type then
return nil, name .. ": mixed accessor types"
end
local f = fill(name, a.type, a.raw)
if name == "POSITION" and not identity then
local mm = m :: { number }
for i = 0, nv - 1 do
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13])
dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14])
dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15])
end
elseif name == "NORMAL" and not identity and sc >= 3 then
local mm = m :: { number }
-- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction
local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11]
local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1
local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1
local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1
local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1
for i = 0, nv - 1 do
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
-- column j of the cofactor matrix multiplies component j: (inverse transpose) * n
local nx = n11 * x + n21 * y + n31 * z
local ny = n12 * x + n22 * y + n32 * z
local nz = n13 * x + n23 * y + n33 * z
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 then
nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l
end
dst[n0 + i * 3 + 1] = f32(nx)
dst[n0 + i * 3 + 2] = f32(ny)
dst[n0 + i * 3 + 3] = f32(nz)
end
else
for i = 0, nv - 1 do
for c = 1, ac do
dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f
end
end
end
end
end
local fs, cs, ferr = faces(prim, nv)
if ferr then
return nil, ferr
end
local flip = false
if not identity then
local mm = m :: { number }
local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6])
flip = det < 0
end
if fs ~= "points" and fs ~= "skip" then
anyFaces = true
local base = merged.count
local cl: { number } = cs
local p = 0
local nf = if fs then #fs else #cl // 3
for f = 1, nf do
local s = if fs then fs[f] else 3
if triangulate then
for k = 2, s - 1 do
table.insert(sizes, 3)
local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1]
if flip then
b, c = c, b
end
table.insert(corners, base + a)
table.insert(corners, base + b)
table.insert(corners, base + c)
end
else
table.insert(sizes, s)
if flip then
table.insert(corners, base + cl[p + 1])
for k = s, 2, -1 do
table.insert(corners, base + cl[p + k])
end
else
for k = 1, s do
table.insert(corners, base + cl[p + k])
end
end
end
p += s
end
end
info.faceCount = #sizes - info.firstFace
merged.count += nv
table.insert(merged.parts, info)
end
merged.sizes = if anyFaces then sizes else nil
return merged, nil
end
return Flatten
+101 -3
View File
@@ -161,6 +161,26 @@ local function drain(dec: any): any
return a
end
-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs)
local function siblings(path: string): (uri: string) -> buffer?
local dir = string.match(path, "^(.*[/\\])") or ""
return function(uri: string): buffer?
if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then
return nil
end
local u = string.gsub(uri, "%%(%x%x)", function(h: string): string
return string.char(tonumber(h, 16) :: number)
end)
for part in string.gmatch(u, "[^/\\]+") do
if part == ".." then
return nil
end
end
local b = host.readFile(dir .. u)
return b
end
end
-- ------------------------------------------------------------------------------------------------ API
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
@@ -272,6 +292,11 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
if not m then
return nil, merr
end
if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then
-- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder
o = table.clone(o)
o.resolve = siblings(name)
end
local value, err
if m.decode then
local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
@@ -328,8 +353,10 @@ function F.open(src: any, opts: Options?): (any, Err.Err?)
return dec
end
local encodeTextures: (scene: any) -> Err.Err?
-- the writable format for a value: opts.format, the destination's extension, or the source format
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?)
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?)
local category = o.category
if category == nil and type(value) == "table" and type(value.kind) == "string" then
category = KIND_CATEGORY[value.kind]
@@ -359,16 +386,49 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr
end
return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name)
end
return entry, m, nil
return entry, m, nil, key
end
-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images)
function encodeTextures(scene: any): Err.Err?
if type(scene.textures) ~= "table" then
return nil
end
for _, tex in scene.textures do
if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then
local png, err = F.save(tex.image, nil, { format = "png" })
if not png then
return err
end
tex.data, tex.mime = png, "image/png"
end
end
return nil
end
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
local o = opts or {}
local entry, m, err = encoderFor(value, dest, o)
local entry, m, err, key = encoderFor(value, dest, o)
if not entry then
return nil, err
end
-- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file)
-- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin)
o = table.clone(o)
o.format = o.format or key
if dest then
o.name = o.name or string.match(dest, "([^/\\]+)$")
if o.files == nil then
o.files = {}
end
end
if type(value) == "table" and value.kind == "scene" then
local terr = encodeTextures(value)
if terr then
return nil, terr
end
end
local ok, buf, e = pcall(m.encode, value, withHooks(o))
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
@@ -381,6 +441,15 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
if not wok then
return nil, werr
end
if type(o.files) == "table" and o.files ~= (opts and opts.files) then
local dir = string.match(dest, "^(.*[/\\])") or ""
for fname, data in o.files do
local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data)
if not fok then
return nil, ferr
end
end
end
return true
end
return buf
@@ -470,4 +539,33 @@ for category in Types.CATEGORIES do
end
F.data.null = Types.null
-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose
-- image format is missing or broken keep image = nil and report an Err.
F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err })
local errs: { [number]: Err.Err } = {}
if type(scene) ~= "table" or type(scene.textures) ~= "table" then
return scene, errs
end
local resolve = opts and opts.resolve
for i, tex in scene.textures do
if type(tex) == "table" and tex.image == nil then
local data = tex.data
if data == nil and tex.uri and resolve then
data = resolve(tex.uri)
end
if data ~= nil then
local img, err = F.load(data, { category = "image", name = tex.uri, data = true })
if img then
tex.image = img
elseif err then
errs[i] = err
end
end
end
end
return scene, errs
end
return F
+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
+294
View File
@@ -0,0 +1,294 @@
--!strict
-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc,
-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping
-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the
-- reverse (from extras.obj when present, else from the PBR fields).
local Types = require("@formats/Types")
local Mtl = {}
export type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values
export type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } }
-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers
local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 }
local MAPS = {
map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true,
map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true,
map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true,
}
Mtl.MAPS = MAPS
local function parseMap(args: { string }): Map
local opts: { [string]: { string } } = {}
local i = 1
while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do
local key = string.sub(args[i], 2)
local vals = {}
i += 1
local n = OPT_ARGS[key]
if n then
for _ = 1, n do
if i <= #args then
table.insert(vals, args[i])
i += 1
end
end
else
-- -o / -s / -t: up to three numbers
while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do
table.insert(vals, args[i])
i += 1
end
end
opts[key] = vals
end
-- the file name is the rest (it may contain spaces)
local file = table.concat(args, " ", i)
return { file = file, options = opts }
end
-- parse(text) -> { Entry } in file order
function Mtl.parse(text: string): { Entry }
local out: { Entry } = {}
local cur: Entry? = nil
for line in string.gmatch(text, "[^\r\n]+") do
local l = string.gsub(line, "#.*$", "")
local words = {}
for w in string.gmatch(l, "%S+") do
table.insert(words, w)
end
local key = words[1]
if key == "newmtl" then
cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} }
table.insert(out, cur :: Entry)
elseif key and cur then
local e = cur :: Entry
local args = table.move(words, 2, #words, 1, {})
if MAPS[key] then
e.maps[key] = parseMap(args)
table.insert(e.order, key)
else
local nums = {}
for _, a in args do
local v = tonumber(a)
if v == nil then
nums = nil :: any
break
end
table.insert(nums, v)
end
if nums then
if e.values[key] == nil then
table.insert(e.order, key)
end
e.values[key] = nums
end
end
end
end
return out
end
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" }
function Mtl.mime(file: string): string?
local ext = string.match(file, "%.([%w]+)$")
return if ext then MIME[string.lower(ext)] else nil
end
-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map
function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
local m = Types.Scene.material(e.name)
local v = e.values
local kd = v.Kd
if kd and #kd >= 3 then
m.baseColor = { kd[1], kd[2], kd[3], 1 }
end
local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1
m.baseColor[4] = d
if d < 1 then
m.alphaMode = "blend"
end
local ke = v.Ke
if ke and #ke >= 3 then
m.emissive = { ke[1], ke[2], ke[3] }
end
m.metallic = if v.Pm then v.Pm[1] else 0
if v.Pr then
m.roughness = v.Pr[1]
elseif v.Ns then
m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1)
end
local function ref(key: string): Types.TextureRef?
local map = e.maps[key]
if not map or map.file == "" then
return nil
end
local r: Types.TextureRef = { texture = texture(map) }
local o, s = map.options.o, map.options.s
if o or s then
r.transform = {
offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil,
scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil,
}
end
if map.options.bm then
r.scale = tonumber(map.options.bm[1])
end
return r
end
m.baseColorTexture = ref("map_Kd")
m.emissiveTexture = ref("map_Ke")
m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump")
m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA")
if m.emissiveTexture and not ke then
m.emissive = { 1, 1, 1 }
end
-- everything else as it was, for the writer and for Phong renderers
local extra: { [string]: any } = {}
for k, vals in v do
extra[k] = vals
end
local maps: { [string]: any } = {}
for k, map in e.maps do
maps[k] = { file = map.file, options = map.options, texture = texture(map) }
end
m.extras = { obj = { values = extra, maps = maps, order = e.order } }
return m
end
local function num(v: number): string
if v == math.floor(v) and math.abs(v) < 1e15 then
return string.format("%d", v)
end
for _, f in { "%.6g", "%.9g", "%.17g" } do
local s = string.format(f, v)
if tonumber(s) == v then
return s
end
end
return string.format("%.17g", v)
end
Mtl.num = num
-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to.
function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string
local out = { "# written by formats-luau" }
for i, m in materials do
table.insert(out, "")
table.insert(out, "newmtl " .. names[i])
local saved = m.extras and m.extras.obj
local values: { [string]: { number } } = {}
local maps: { [string]: any } = {}
local order: { string } = {}
if type(saved) == "table" and type(saved.values) == "table" then
for k, vals in saved.values do
values[k] = vals
end
for k, mp in saved.maps or {} do
maps[k] = mp
end
order = table.clone(saved.order or {})
end
-- the PBR fields win over the saved Phong values they map to
local bc = m.baseColor or { 1, 1, 1, 1 }
values.Kd = { bc[1], bc[2], bc[3] }
if (bc[4] or 1) < 1 or values.d then
values.d = { bc[4] or 1 }
values.Tr = nil
end
local em = m.emissive or { 0, 0, 0 }
if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then
values.Ke = { em[1], em[2], em[3] }
end
if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then
values.Pr = { m.roughness }
end
if m.metallic ~= 0 or values.Pm then
values.Pm = { m.metallic }
end
local function setMap(key: string, ref: Types.TextureRef?)
if ref then
local file = textureFile(ref.texture)
if file then
local prev = maps[key]
local options = if prev and prev.texture == ref.texture then prev.options else {}
options = table.clone(options or {})
if ref.transform then
if ref.transform.offset then
options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) }
end
if ref.transform.scale then
options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) }
end
end
if ref.scale and key ~= "map_Kd" then
options.bm = { num(ref.scale) }
end
maps[key] = { file = file, options = options, texture = ref.texture }
end
end
end
setMap("map_Kd", m.baseColorTexture)
setMap("map_Ke", m.emissiveTexture)
if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then
setMap("norm", m.normalTexture)
end
setMap("map_ORM", m.metallicRoughnessTexture)
-- the saved order first, then the rest sorted
local keys = {}
local seen = {}
for _, k in order do
if (values[k] or maps[k]) and not seen[k] then
table.insert(keys, k)
seen[k] = true
end
end
local rest = {}
for k in values do
if not seen[k] then
table.insert(rest, k)
end
end
for k in maps do
if not seen[k] and not values[k] then
table.insert(rest, k)
end
end
table.sort(rest)
for _, k in rest do
seen[k] = true
table.insert(keys, k)
end
for _, k in keys do
local mp = maps[k]
if mp and type(mp.file) == "string" then
local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file
local parts = { k }
local okeys = {}
for ok in mp.options or {} do
table.insert(okeys, ok)
end
table.sort(okeys)
for _, ok in okeys do
table.insert(parts, "-" .. ok)
for _, ov in mp.options[ok] do
table.insert(parts, tostring(ov))
end
end
table.insert(parts, file)
table.insert(out, table.concat(parts, " "))
elseif values[k] then
local parts = { k }
for _, x in values[k] do
table.insert(parts, num(x))
end
table.insert(out, table.concat(parts, " "))
end
end
end
table.insert(out, "")
return table.concat(out, "\n")
end
return Mtl
+762
View File
@@ -0,0 +1,762 @@
--!strict
-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp
-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form
-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR
-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line
-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons",
-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false
-- keeps OBJ's).
-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group.
-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination.
-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups
-- (s: kept per node in extras.obj.smoothing, not used to compute normals).
-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to
-- opts.files[<name>.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mtl = require("@formats/model/obj/Mtl")
-- ------------------------------------------------------------------------------------------------ contract
local Obj = {
name = "obj",
category = "model",
extensions = { "obj" },
mime = { "model/obj" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention)
mtl: (string | buffer)?, -- the material library text, when not found through resolve / files
resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths)
files: { [string]: any }?, -- or: the other files by name
maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25)
}
export type EncodeOptions = {
name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl")
mtlName: string?, -- the .mtl file name (overrides name)
files: { [string]: any }?, -- receives the .mtl and embedded textures
flipV: boolean?, -- default true (the inverse of decode)
normals: boolean?, -- write vn (default true when the primitives have NORMAL)
texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0)
colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Obj.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.find(head, "\0", 1, true) then
return 0
end
if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then
return 0.6
end
if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then
return 0.4
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetch(opts: DecodeOptions?, uri: string): string?
if not opts then
return nil
end
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
if v == nil then
v = opts.files[string.match(uri, "([^/\\]+)$") or uri]
end
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) == "buffer" then
return buffer.tostring(v)
elseif type(v) == "string" then
return v
end
return nil
end
type Prim = {
material: string?,
mode: string,
cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none)
ct: { number },
cn: { number },
faces: { number }, -- corners per face (polygons / lines)
hasT: boolean,
hasN: boolean,
}
type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? }
function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local triangulate = not (opts and opts.triangulate == false)
local flipV = not (opts and opts.flipV == false)
local maxV = opts and opts.maxVertices or 2 ^ 25
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local P, C, UV, N = {}, {}, {}, {}
local np, nt, nn = 0, 0, 0
local hasColor = false
local sections: { Section } = {}
local byName: { [string]: Section } = {}
local cur: Section? = nil
local object: string? = nil
local group: string? = nil
local material: string? = nil
local smoothing: string? = nil
local mtllibs: { string } = {}
local skipped = 0
local corners = 0
local hasObjects = false
local lineNo = 0
local pos = 1
local len = #text
local function section(): Section
if cur then
return cur
end
local key = (object or "") .. "\0" .. (group or "")
local s = byName[key]
if not s then
s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing }
byName[key] = s
table.insert(sections, s)
end
cur = s
return s
end
local function prim(mode: string): Prim
local s = section()
local key = mode .. "\0" .. (material or "")
local p = s.byKey[key]
if not p then
p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false }
s.byKey[key] = p
table.insert(s.prims, p)
end
return p
end
-- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil
local function corner(tok: string): (number?, number, number)
local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$")
local vi = tonumber(a)
if not vi then
return nil, -1, -1
end
vi = if vi < 0 then np + vi else vi - 1
local ti, ni = -1, -1
local t = tonumber(b)
if t then
ti = if t < 0 then nt + t else t - 1
if ti < 0 or ti >= nt then
return nil, -1, -1
end
end
local n = tonumber(c)
if n then
ni = if n < 0 then nn + n else n - 1
if ni < 0 or ni >= nn then
return nil, -1, -1
end
end
if vi < 0 or vi >= np then
return nil, -1, -1
end
return vi, ti, ni
end
local fs: { string } = {}
while pos <= len do
local e = string.find(text, "\n", pos, true) or (len + 1)
local line = string.sub(text, pos, e - 1)
pos = e + 1
lineNo += 1
-- continuation lines
while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do
line = string.gsub(line, "\\\r?$", " ")
local e2 = string.find(text, "\n", pos, true) or (len + 1)
line ..= string.sub(text, pos, e2 - 1)
pos = e2 + 1
lineNo += 1
end
local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$")
if key == nil or string.sub(key, 1, 1) == "#" then
continue
end
local hash = string.find(rest, "#", 1, true)
if hash then
rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "")
end
if key == "v" then
local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)")
local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z)
if not fx or not fy or not fz then
return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo)
end
if np >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices")
end
P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz
local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c)
if cr and cg and cb then
hasColor = true
C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb
end
np += 1
elseif key == "vt" then
local u, v = string.match(rest, "^(%S+)%s*(%S*)")
local fu = tonumber(u)
if not fu then
return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo)
end
if nt >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates")
end
local fv = tonumber(v) or 0
UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv
nt += 1
elseif key == "vn" then
local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)")
local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z)
if not fx or not fy or not fz then
return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo)
end
if nn >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals")
end
N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz
nn += 1
elseif key == "f" or key == "l" or key == "p" then
table.clear(fs)
for tok in string.gmatch(rest, "%S+") do
table.insert(fs, tok)
end
local k = #fs
local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points"
if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then
return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo)
end
corners += k
if corners > maxV * 4 then
return nil, Err.new(Err.LIMIT, "too many face corners")
end
local p = prim(mode)
local base = #p.cv
for i, tok in fs do
local vi, ti, ni = corner(tok)
if not vi then
return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo)
end
p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni
if ti >= 0 then
p.hasT = true
end
if ni >= 0 then
p.hasN = true
end
end
if mode == "triangles" and k > 3 then
-- fan: rewrite the k corners as (k - 2) triangles
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
local o = base
for a = 2, k - 1 do
for _, j in { 1, a, a + 1 } do
o += 1
p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j]
end
end
elseif mode == "lines" then
-- a polyline -> segments
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
local o = base
for a = 1, k - 1 do
for _, j in { a, a + 1 } do
o += 1
p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j]
end
end
elseif mode == "polygons" then
table.insert(p.faces, k)
end
elseif key == "o" then
object = rest
group = nil
hasObjects = true
cur = nil
elseif key == "g" then
group = if rest == "" then nil else rest
cur = nil
elseif key == "usemtl" then
material = rest
elseif key == "mtllib" then
table.insert(mtllibs, rest)
elseif key == "s" then
smoothing = rest
if cur then
cur.smoothing = cur.smoothing or rest
end
else
skipped += 1
end
end
-- materials
local scene = Types.Scene.new()
local matIndex: { [string]: number } = {}
local texIndex: { [string]: number } = {}
local function texture(map: Mtl.Map): number
local file = string.gsub(map.file, "\\", "/")
local i = texIndex[file]
if i then
return i
end
local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) }
local data = fetch(opts, file)
if data then
tex.data = buffer.fromstring(data)
end
if map.options.clamp and map.options.clamp[1] == "on" then
tex.sampler = { wrapS = "clamp", wrapT = "clamp" }
end
table.insert(scene.textures, tex)
i = #scene.textures
texIndex[file] = i
return i
end
local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil
local missing: { string } = {}
local libs: { string } = {}
if mtlText then
table.insert(libs, mtlText :: string)
end
for _, lib in mtllibs do
local t = fetch(opts, lib)
if t then
table.insert(libs, t)
elseif not mtlText then
table.insert(missing, lib)
end
end
for _, lt in libs do
for _, e in Mtl.parse(lt) do
if not matIndex[e.name] then
table.insert(scene.materials, Mtl.toMaterial(e, texture))
matIndex[e.name] = #scene.materials
end
end
end
-- materials named by usemtl but not defined anywhere: a default one with the name
for _, s in sections do
for _, p in s.prims do
if p.material and not matIndex[p.material] then
table.insert(scene.materials, Types.Scene.material(p.material))
scene.materials[#scene.materials].metallic = 0
matIndex[p.material] = #scene.materials
end
end
end
-- vertices: one per distinct (v, vt, vn) in each primitive
local f32 = buffer.writef32
local KT, KN = nt + 1, nn + 1
local numericKeys = np * KT * KN < 2 ^ 52
local function build(p: Prim): Types.Primitive
local n = #p.cv
local map: { [any]: number } = {}
local verts: { number } = {}
local idx = buffer.create(n * 4)
local count = 0
for i = 1, n do
local v, t, nr = p.cv[i], p.ct[i], p.cn[i]
local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr)
local k = map[key]
if k == nil then
k = count
map[key] = k
count += 1
verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr
end
buffer.writeu32(idx, (i - 1) * 4, k)
end
local pb = buffer.create(count * 12)
local tb = if p.hasT then buffer.create(count * 8) else nil
local nb = if p.hasN then buffer.create(count * 12) else nil
local cb = if hasColor then buffer.create(count * 12) else nil
for k = 0, count - 1 do
local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3]
f32(pb, k * 12, P[v * 3 + 1])
f32(pb, k * 12 + 4, P[v * 3 + 2])
f32(pb, k * 12 + 8, P[v * 3 + 3])
if tb and t >= 0 then
f32(tb, k * 8, UV[t * 2 + 1])
f32(tb, k * 8 + 4, UV[t * 2 + 2])
end
if nb and nr >= 0 then
f32(nb, k * 12, N[nr * 3 + 1])
f32(nb, k * 12 + 4, N[nr * 3 + 2])
f32(nb, k * 12 + 8, N[nr * 3 + 3])
end
if cb then
f32(cb, k * 12, C[v * 3 + 1] or 1)
f32(cb, k * 12 + 4, C[v * 3 + 2] or 1)
f32(cb, k * 12 + 8, C[v * 3 + 3] or 1)
end
end
local A = Types.Scene.accessor
local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) }
if tb then
attrs.TEXCOORD_0 = A(tb, "f32", 2, count)
end
if nb then
attrs.NORMAL = A(nb, "f32", 3, count)
end
if cb then
attrs.COLOR_0 = A(cb, "f32", 3, count)
end
local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil }
if p.mode == "points" then
out.indices = if count == n then nil else out.indices
end
if p.mode == "polygons" then
local fb = buffer.create(#p.faces * 4)
for i, k in p.faces do
buffer.writeu32(fb, (i - 1) * 4, k)
end
out.faces = A(fb, "u32", 1, #p.faces)
end
return out
end
-- nodes: objects at the root, their groups as children; without objects every group is a root
local objectNode: { [string]: number } = {}
for _, s in sections do
if #s.prims > 0 then
local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} }
for _, p in s.prims do
table.insert(mesh.primitives, build(p))
end
table.insert(scene.meshes, mesh)
local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes }
if s.smoothing then
node.extras = { obj = { smoothing = s.smoothing } }
end
if hasObjects and s.object and s.group then
local oi = objectNode[s.object]
if not oi then
table.insert(scene.nodes, { name = s.object, children = {} })
oi = #scene.nodes
objectNode[s.object] = oi
table.insert(scene.roots, oi)
end
table.insert(scene.nodes, node)
table.insert(scene.nodes[oi].children, #scene.nodes)
else
if hasObjects and s.object and not s.group and objectNode[s.object] == nil then
table.insert(scene.nodes, node)
objectNode[s.object] = #scene.nodes
table.insert(scene.roots, #scene.nodes)
elseif hasObjects and s.object and objectNode[s.object] then
-- the object's own faces after its groups: a child too
table.insert(scene.nodes, node)
table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes)
else
table.insert(scene.nodes, node)
table.insert(scene.roots, #scene.nodes)
end
end
end
end
scene.meta.up = "y"
scene.meta.source = {
format = "obj",
positions = np,
texcoords = nt,
normals = nn,
vertexColors = hasColor,
mtllib = if #mtllibs > 0 then mtllibs else nil,
missingMtl = if #missing > 0 then missing else nil,
skipped = skipped,
}
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the shortest decimal that reads back as the same f32
local probe = buffer.create(4)
local function f32str(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
end
if v == math.floor(v) and math.abs(v) < 1e7 then
return string.format("%d", v)
end
buffer.writef32(probe, 0, v)
local want = buffer.readf32(probe, 0)
for _, f in { "%.6g", "%.7g", "%.8g" } do
local s = string.format(f, v)
buffer.writef32(probe, 0, tonumber(s) :: number)
if buffer.readf32(probe, 0) == want then
return s
end
end
return string.format("%.9g", v)
end
local function nameOk(s: string): string
local t = string.gsub(s, "[\r\n]", " ")
return t
end
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" }
function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, 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 flipV = not (opts and opts.flipV == false)
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local mtlName = opts and opts.mtlName or (base .. ".mtl")
local files = opts and opts.files
local placed = Types.Scene.flatten(scene)
local out = { "# written by formats-luau" }
local mats = scene.materials or {}
-- material names (unique), texture file names
local names: { string } = {}
local used: { [string]: boolean } = {}
for i, m in mats do
local n = string.gsub(m.name or ("material_" .. i), "%s", "_")
while used[n] do
n ..= "_" .. i
end
used[n] = true
names[i] = n
end
local texFiles: { [number]: string } = {}
local function textureFile(i: number): string?
if texFiles[i] then
return texFiles[i]
end
local tex = scene.textures and scene.textures[i]
if not tex then
return nil
end
local file = tex.uri
if (file == nil or string.find(file, "^data:")) and tex.data then
file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
end
if file and tex.data and type(files) == "table" then
files[file] = tex.data
end
texFiles[i] = file
return file
end
if #mats > 0 then
table.insert(out, "mtllib " .. mtlName)
if type(files) == "table" then
files[mtlName] = Mtl.write(mats, names, textureFile)
end
end
local nv, nt, nn = 0, 0, 0
local lastNode = -1
for _, pl in placed do
local prim = pl.primitive
local attrs = prim.attributes
local pos = attrs and attrs.POSITION
if not pos then
continue
end
local P = Types.Scene.reader(pos)
if not P then
return nil, Err.new(Err.ARG, "bad POSITION accessor")
end
if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then
return nil, Err.new(Err.ARG, "POSITION data is smaller than its count")
end
local m = pl.matrix
local ident = m == Types.Scene.IDENTITY
local node = scene.nodes[pl.node]
if pl.node ~= lastNode then
lastNode = pl.node
table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node)))
end
local n = pos.count
local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0) else nil
local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil
local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) else nil
for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do
if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then
return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION")
end
end
-- the normal matrix (inverse transpose) for baked normals
local nm: { number }? = nil
if Nr and not ident then
local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11]
local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
local k = if det ~= 0 then 1 / det else 1
nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k }
end
for v = 0, n - 1 do
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
if not ident then
x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
end
if Cc then
table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2))))
else
table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z)))
end
end
if T then
for v = 0, n - 1 do
local tv = T(v, 1)
table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv)))
end
end
if Nr then
for v = 0, n - 1 do
local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2)
if nm then
x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z
local l = math.sqrt(x * x + y * y + z * z)
if l > 0 then
x, y, z = x / l, y / l, z / l
end
end
table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z)))
end
end
if prim.material and names[prim.material] then
table.insert(out, "usemtl " .. names[prim.material])
end
local function ref(i: number): string
local s = tostring(nv + i + 1)
if T and Nr then
return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1)
elseif T then
return string.format("%s/%d", s, nt + i + 1)
elseif Nr then
return string.format("%s//%d", s, nn + i + 1)
end
return s
end
-- the corner list
local ind = prim.indices
local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil
local count = if ind then ind.count else n
if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then
return nil, Err.new(Err.ARG, "indices data is smaller than its count")
end
local function at(i: number): number
return if I then I(i, 0) else i
end
for i = 0, count - 1 do
if at(i) >= n then
return nil, Err.new(Err.ARG, "index out of range")
end
end
local mirror = not ident and (m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])) < 0
local function face(list: { number })
local parts = table.create(#list + 1)
parts[1] = "f"
if mirror then
for k = #list, 1, -1 do
table.insert(parts, ref(list[k]))
end
else
for k = 1, #list do
table.insert(parts, ref(list[k]))
end
end
table.insert(out, table.concat(parts, " "))
end
local mode = prim.mode or "triangles"
if mode == "triangles" then
for t = 0, count // 3 - 1 do
face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) })
end
elseif mode == "polygons" then
local F = if prim.faces then Types.Scene.reader(prim.faces) else nil
if not F or not prim.faces then
return nil, Err.new(Err.ARG, "polygons without faces")
end
local o = 0
for f = 0, prim.faces.count - 1 do
local k = F(f, 0)
if o + k > count then
return nil, Err.new(Err.ARG, "faces run past the indices")
end
local list = table.create(k)
for j = 0, k - 1 do
list[j + 1] = at(o + j)
end
if k >= 3 then
face(list)
end
o += k
end
elseif mode == "triangle_strip" or mode == "triangle_fan" then
for t = 0, count - 3 do
local a, b, c = at(t), at(t + 1), at(t + 2)
if mode == "triangle_fan" then
a = at(0)
elseif t % 2 == 1 then
a, b = b, a
end
face({ a, b, c })
end
elseif mode == "lines" then
for s = 0, count // 2 - 1 do
table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1)))
end
elseif mode == "line_strip" or mode == "line_loop" then
local parts = { "l" }
for i = 0, count - 1 do
table.insert(parts, ref(at(i)))
end
if mode == "line_loop" and count > 0 then
table.insert(parts, ref(at(0)))
end
table.insert(out, table.concat(parts, " "))
elseif mode == "points" then
for i = 0, count - 1 do
table.insert(out, "p " .. ref(at(i)))
end
end
nv += n
if T then
nt += n
end
if Nr then
nn += n
end
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files)
function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or type(scene.materials) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local files = {}
local o: any = table.clone(opts or {})
o.files = files
o.mtlName = "x.mtl"
local _, err = Obj.encode(scene, o)
if err then
return nil, err
end
local text = files["x.mtl"]
return buffer.fromstring(text or ""), nil
end
return Obj
+480
View File
@@ -0,0 +1,480 @@
--!strict
-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description
-- (geomview.org/docs/html/OFF.html).
-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the
-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`;
-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8
-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given).
-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces;
-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are
-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or
-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single
-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points".
-- meta.source = { format, keyword, vertices, faces, edges }.
-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes
-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons
-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are
-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF
-- (UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Flatten = require("@formats/codecs/MeshFlatten")
-- ------------------------------------------------------------------------------------------------ contract
local Off = {
name = "off",
category = "model",
extensions = { "off" },
mime = { "model/off", "text/plain" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons"
maxVertices: number?, -- default 2^24
maxFaces: number?, -- default 2^25
}
export type EncodeOptions = {
colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true)
normals: boolean?, -- write NORMAL (NOFF) when present (default true)
texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true)
comment: string?, -- a "# ..." line after the header keyword
}
-- ------------------------------------------------------------------------------------------------ constants
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
-- ------------------------------------------------------------------------------------------------ sniff
function Off.sniff(r: Bytes.Reader): number
local head = r:peek(512)
for _ = 1, 16 do -- leading comment lines
local rest = string.match(head, "^%s*#[^\n]*\n(.*)$")
if not rest then
break
end
head = rest
end
local kw = string.match(head, "^%s*(%w+)")
if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32
type ColorSet = { values: { number }, float: boolean, max: number }
local function colorType(c: ColorSet): string
return if not c.float and c.max > 1 then "unorm8" else "f32"
end
-- the colour accessor for count entries of 4 values (nan = absent: opaque white)
local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?)
local t = colorType(c)
local buf = buffer.create(count * (if t == "unorm8" then 4 else 16))
local vals = c.values
for i = 0, count * 4 - 1 do
local v = vals[i + 1]
if t == "unorm8" then
if v ~= v then
v = 255
elseif v < 0 or v > 255 or v % 1 ~= 0 then
return nil, "colour value out of range"
end
writeu8(buf, i, v)
else
writef32(buf, i * 4, if v ~= v then 1 else v)
end
end
return Types.Scene.accessor(buf, t, 4, count), nil
end
local function addColor(c: ColorSet, toks: { string }, from: number, n: number)
local vals = c.values
for k = 0, 3 do
if k < n then
local s = toks[from + k]
local v = tonumber(s) :: number
table.insert(vals, v)
if not c.float and string.find(s, "[%.eEnN]") then
c.float = true
end
if v > c.max then
c.max = v
end
else
table.insert(vals, 0 / 0) -- absent: full (opaque white)
end
end
end
function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local triangulate = true
if opts and opts.triangulate == false then
triangulate = false
end
local maxVertices = opts and opts.maxVertices or 2 ^ 24
local maxFaces = opts and opts.maxFaces or 2 ^ 25
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
-- the next non-empty line's tokens (comments stripped)
local at = 1
local lineNo = 0
local function line(): { string }?
while at <= #text do
local e = string.find(text, "\n", at, true) or (#text + 1)
local s = string.sub(text, at, e - 1)
at = e + 1
lineNo += 1
local hash = string.find(s, "#", 1, true)
if hash then
s = string.sub(s, 1, hash - 1)
end
local toks = {}
for w in string.gmatch(s, "%S+") do
table.insert(toks, w)
end
if #toks > 0 then
return toks
end
end
return nil
end
local head = line()
if not head then
return nil, Err.new(Err.TRUNCATED, "empty file")
end
local kw = head[1]
local rest = kw
local st, hasC, hasN = false, false, false
if string.sub(rest, 1, 2) == "ST" then
st, rest = true, string.sub(rest, 3)
end
if string.sub(rest, 1, 1) == "C" then
hasC, rest = true, string.sub(rest, 2)
end
if string.sub(rest, 1, 1) == "N" then
hasN, rest = true, string.sub(rest, 2)
end
if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then
return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)")
elseif rest ~= "OFF" then
return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20))
end
local counts: { string }
if head[2] == "BINARY" then
return nil, Err.new(Err.UNSUPPORTED, "binary OFF")
elseif #head >= 3 then
counts = { head[2], head[3], head[4] }
else
local c = line()
if not c then
return nil, Err.new(Err.TRUNCATED, "no counts line")
end
counts = c
end
local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0")
if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad counts line")
end
if nv > maxVertices then
return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices))
end
if nf > maxFaces then
return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces))
end
-- every vertex / face line takes at least 6 / 2 bytes
if nv * 6 + nf * 2 > #text - at + 2 then
return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need")
end
local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0)
local pos = buffer.create(nv * 12)
local nrm = if hasN then buffer.create(nv * 12) else nil
local tex = if st then buffer.create(nv * 8) else nil
local vcol: ColorSet = { values = {}, float = false, max = 0 }
for i = 0, nv - 1 do
local t = line()
if not t then
return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i))
end
local n = #t
local nc = 0
if hasC then
nc = n - fixed
if nc ~= 3 and nc ~= 4 then
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed))
end
elseif n < fixed then
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed))
end
for k = 1, fixed + nc do
if tonumber(t[k]) == nil then
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i))
end
end
writef32(pos, i * 12, tonumber(t[1]) :: number)
writef32(pos, i * 12 + 4, tonumber(t[2]) :: number)
writef32(pos, i * 12 + 8, tonumber(t[3]) :: number)
local k = 4
if nrm then
writef32(nrm, i * 12, tonumber(t[4]) :: number)
writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number)
writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number)
k = 7
end
if hasC then
addColor(vcol, t, k, nc)
k += nc
end
if tex then
writef32(tex, i * 8, tonumber(t[k]) :: number)
writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number)
end
end
local sizes = buffer.create(nf * 4)
local corners: { number } = {}
local fcol: ColorSet = { values = {}, float = false, max = 0 }
local anyFaceColor, colormap = false, false
for f = 0, nf - 1 do
local t = line()
if not t then
return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f))
end
local n = tonumber(t[1])
if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f))
end
writeu32(sizes, f * 4, n)
for k = 2, n + 1 do
local v = tonumber(t[k])
if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f))
end
table.insert(corners, v)
end
local nc = #t - n - 1
if nc == 3 or nc == 4 then
for k = n + 2, #t do
if tonumber(t[k]) == nil then
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f))
end
end
addColor(fcol, t, n + 2, nc)
anyFaceColor = true
else
if nc == 1 then
colormap = true
end
addColor(fcol, t, 1, 0)
end
end
-- the primitive
local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) }
if nrm then
attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv)
end
if hasC then
local acc, cerr = colorAccessor(vcol, nv)
if not acc then
return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr))
end
attrs.COLOR_0 = acc
end
if tex then
attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv)
end
local prim: Types.Primitive = { attributes = attrs, mode = "points" }
local extras: { [string]: any } = {}
if anyFaceColor then
local acc, cerr = colorAccessor(fcol, nf)
if not acc then
return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr))
end
extras.faceColors = acc
end
if nf > 0 then
local total = #corners
local cbuf = buffer.create(total * 4)
for i = 1, total do
writeu32(cbuf, (i - 1) * 4, corners[i])
end
local allTri = total == nf * 3
if allTri then
for f = 0, nf - 1 do
if buffer.readu32(sizes, f * 4) ~= 3 then
allTri = false
break
end
end
end
if allTri then
prim.mode = "triangles"
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
elseif triangulate then
local tris: { number } = {}
local fot: { number } = {}
local p = 0
for f = 0, nf - 1 do
local s = buffer.readu32(sizes, f * 4)
for k = 1, s - 2 do
table.insert(tris, corners[p + 1])
table.insert(tris, corners[p + k + 1])
table.insert(tris, corners[p + k + 2])
table.insert(fot, f)
end
p += s
end
local ib = buffer.create(#tris * 4)
for i, v in tris do
writeu32(ib, (i - 1) * 4, v)
end
prim.mode = "triangles"
prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris)
if anyFaceColor then
local fb = buffer.create(#fot * 4)
for i, v in fot do
writeu32(fb, (i - 1) * 4, v)
end
extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot)
end
else
prim.mode = "polygons"
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf)
end
end
if next(extras) then
prim.extras = extras
end
local scene = Types.Scene.fromPrimitive(prim, nil)
scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local scratch = buffer.create(4)
local function fnum(v: number): string?
writef32(scratch, 0, v)
v = buffer.readf32(scratch, 0)
if v ~= v or v == math.huge or v == -math.huge then
return nil
end
return string.format("%.9g", v)
end
-- a colour attribute's 4 components of entry i (0-based) as text
local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string
local out = table.create(4)
for c = 1, 4 do
local v = if c <= comps then vals[i * comps + c] else nil
if a.raw and a.type == "unorm8" then
out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255))
else
if v == nil then
v = 1
elseif a.raw then
v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1)
end
out[c] = fnum(v :: number) or "0"
end
end
return table.concat(out, " ")
end
function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false
local m, merr = Flatten.merge(scene, function(name: string): boolean
return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT)
end, { triangulate = false })
if not m then
return nil, Err.new(Err.ARG, tostring(merr))
end
local A = m.attrs
local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0
if T and T.raw then
return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type")
end
local nv = m.count
local sizes = m.sizes or {}
local nf = #sizes
local out = table.create(nv + nf + 3)
table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF")
if o.comment then
table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " "))
end
table.insert(out, string.format("%d %d 0", nv, nf))
local pv = P.values
for i = 0, nv - 1 do
local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3])
if not (x and y and z) then
return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate")
end
local s = x .. " " .. y .. " " .. z
if N then
local nvv = N.values
s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0")
end
if C then
s ..= " " .. colorText(C, C.values, C.components, i)
end
if T then
local tv, tc = T.values, T.components
s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0")
end
table.insert(out, s)
end
-- face colours of a single primitive (per file face, or through faceOfTriangle)
local fc: Flatten.Attr? = nil
local fcMap: { number }? = nil
if wantC and #m.parts == 1 and nf > 0 then
local ex = m.parts[1].prim.extras
local acc = type(ex) == "table" and ex.faceColors
if acc then
local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16"
local vals = Flatten.numbers(acc, raw)
if vals then
local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals }
if acc.count == nf then
fc = a
elseif ex.faceOfTriangle then
local fot = Flatten.numbers(ex.faceOfTriangle, true)
if fot and #fot == nf then
fc, fcMap = a, fot
for _, f in fot do
if f < 0 or f >= acc.count then
fc = nil
break
end
end
end
end
end
end
end
local corners = m.corners
local p = 0
for f = 1, nf do
local s = sizes[f]
local line = table.create(s + 2)
line[1] = string.format("%d", s)
for k = 1, s do
line[k + 1] = string.format("%d", corners[p + k])
end
p += s
if fc then
local src = if fcMap then fcMap[f] else f - 1
table.insert(line, colorText(fc, fc.values, fc.components, src))
end
table.insert(out, table.concat(line, " "))
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
return Off
+212
View File
@@ -0,0 +1,212 @@
--!strict
--!native
--!optimize 2
-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32,
-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of
-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the
-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list
-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws.
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64 = buffer.readf32, buffer.readf64
local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32
local writef32, writef64 = buffer.writef32, buffer.writef64
local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift
local Binary = {}
Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 }
local SIZE = Binary.SIZE
local scratch = buffer.create(8)
local function swap16(v: number): number
return rshift(v, 8) + band(v, 255) * 256
end
-- rd(b, q, code, be) -> the value at q
local function rd(b: buffer, q: number, code: number, be: boolean): number
if not be then
if code == 7 then
return readf32(b, q)
elseif code == 2 then
return readu8(b, q)
elseif code == 5 then
return readi32(b, q)
elseif code == 6 then
return readu32(b, q)
elseif code == 8 then
return readf64(b, q)
elseif code == 1 then
return readi8(b, q)
elseif code == 3 then
return readi16(b, q)
end
return readu16(b, q)
end
if code <= 2 then
return if code == 1 then readi8(b, q) else readu8(b, q)
elseif code <= 4 then
local v = swap16(readu16(b, q))
return if code == 3 and v >= 32768 then v - 65536 else v
elseif code <= 7 then
local v = byteswap(readu32(b, q))
if code == 6 then
return v
elseif code == 5 then
return if v >= 2147483648 then v - 4294967296 else v
end
writeu32(scratch, 0, v)
return readf32(scratch, 0)
end
writeu32(scratch, 0, byteswap(readu32(b, q + 4)))
writeu32(scratch, 4, byteswap(readu32(b, q)))
return readf64(scratch, 0)
end
Binary.rd = rd
-- wr(d, o, code, v): v as code, little endian
local function wr(d: buffer, o: number, code: number, v: number)
if code == 7 then
writef32(d, o, v)
elseif code == 6 then
writeu32(d, o, v)
elseif code == 5 then
writei32(d, o, v)
elseif code == 2 then
writeu8(d, o, v)
elseif code == 8 then
writef64(d, o, v)
elseif code == 1 then
writei8(d, o, v)
elseif code == 3 then
writei16(d, o, v)
else
writeu16(d, o, v)
end
end
Binary.wr = wr
-- put(d, o, code, v, be): v as code in either byte order (the writer)
function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean)
if not be or code <= 2 then
wr(d, o, code, v)
return
end
wr(scratch, 0, code, v)
if code <= 4 then
writeu16(d, o, swap16(readu16(scratch, 0)))
elseif code <= 7 then
writeu32(d, o, byteswap(readu32(scratch, 0)))
else
writeu32(d, o, byteswap(readu32(scratch, 4)))
writeu32(d, o + 4, byteswap(readu32(scratch, 0)))
end
end
-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p
function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number })
for k = 1, np do
local sc, dc, d = code[k], dCode[k], dst[k]
local q0, o0, st = p + srcOff[k], dOff[k], dStride[k]
if sc == dc and not be then
local sz = SIZE[sc]
if sz == 4 then
for i = 0, n - 1 do
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
end
elseif sz == 1 then
for i = 0, n - 1 do
writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize))
end
elseif sz == 2 then
for i = 0, n - 1 do
writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize))
end
else
for i = 0, n - 1 do
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4))
end
end
else
for i = 0, n - 1 do
wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be))
end
end
end
end
-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property,
-- or -1, message (truncated rows, a negative / fractional count)
function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any)
local totals = table.create(np, 0)
local q = p
for _ = 1, n do
for k = 1, np do
if isList[k] then
local cc = countCode[k]
local csz = SIZE[cc]
if q + csz > limit then
return -1, "list runs past the end"
end
local c = rd(b, q, cc, be)
if c < 0 or c ~= c // 1 then
return -1, "bad list count"
end
q += csz + c * SIZE[code[k]]
if q > limit then
return -1, "list runs past the end"
end
totals[k] += c
else
q += SIZE[code[k]]
if q > limit then
return -1, "row runs past the end"
end
end
end
end
return q, totals
end
-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message.
-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their
-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows
-- must have passed scan() with the same arguments.
function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?)
local at = table.create(np, 0)
local q = p
for i = 0, n - 1 do
for k = 1, np do
local sc, dc, d = code[k], dCode[k], dst[k]
if isList[k] then
local cc = countCode[k]
local c = rd(b, q, cc, be)
q += SIZE[cc]
writeu32(sizes[k], i * 4, c)
local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k]
if bd >= 0 then
for j = 0, c - 1 do
local v = rd(b, q, sc, be)
q += ssz
if v < 0 or v >= bd or v ~= v // 1 then
return false, "vertex index out of range"
end
wr(d, (ia + j) * dsz, dc, v)
end
else
for j = 0, c - 1 do
wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be))
q += ssz
end
end
at[k] = ia + c
else
wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be))
q += SIZE[sc]
end
end
end
return true, nil
end
return Binary
File diff suppressed because it is too large. Load diff
+77
View File
@@ -0,0 +1,77 @@
--!strict
--!native
--!optimize 2
-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5
-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that
-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws.
local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift
local Decode = {}
-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into
-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes).
function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number
local any = 0
for i = 0, n - 1 do
local q = p + i * 50
local o = i * 36
local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8)
writeu32(nrm, o, nx)
writeu32(nrm, o + 4, ny)
writeu32(nrm, o + 8, nz)
writeu32(nrm, o + 12, nx)
writeu32(nrm, o + 16, ny)
writeu32(nrm, o + 20, nz)
writeu32(nrm, o + 24, nx)
writeu32(nrm, o + 28, ny)
writeu32(nrm, o + 32, nz)
writeu32(pos, o, readu32(b, q + 12))
writeu32(pos, o + 4, readu32(b, q + 16))
writeu32(pos, o + 8, readu32(b, q + 20))
writeu32(pos, o + 12, readu32(b, q + 24))
writeu32(pos, o + 16, readu32(b, q + 28))
writeu32(pos, o + 20, readu32(b, q + 32))
writeu32(pos, o + 24, readu32(b, q + 36))
writeu32(pos, o + 28, readu32(b, q + 40))
writeu32(pos, o + 32, readu32(b, q + 44))
local a = readu16(b, q + 48)
writeu16(attr, i * 2, a)
any = bor(any, a)
end
return any
end
-- 5-bit -> 8-bit, rounded
local function x8(v: number): number
return (v * 255 + 15) // 31
end
-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid,
-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour,
-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a).
function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer)
for i = 0, n - 1 do
local w = readu16(attr, i * 2)
local r, g, bl, al = dr, dg, db, da
local own = if magics then w < 0x8000 else w >= 0x8000
if own then
local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31))
g, al = mid, 255
if magics then
r, bl = lo, hi
else
r, bl = hi, lo
end
end
local o = i * 12
for k = 0, 2 do
writeu8(out, o + k * 4, r)
writeu8(out, o + k * 4 + 1, g)
writeu8(out, o + k * 4 + 2, bl)
writeu8(out, o + k * 4 + 3, al)
end
end
end
return Decode
+467
View File
@@ -0,0 +1,467 @@
--!strict
-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description
-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec).
-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the
-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView:
-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the
-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in
-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly
-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in
-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final
-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material,
-- solids, facets }.
-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans
-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after
-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle
-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either
-- convention. Not supported: binary-only extensions other than the two colour conventions.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Decode = require("@formats/model/stl/Decode")
local Flatten = require("@formats/codecs/MeshFlatten")
-- ------------------------------------------------------------------------------------------------ contract
local Stl = {
name = "stl",
category = "model",
extensions = { "stl" },
mime = { "model/stl", "application/sla" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFaces: number?, -- refuse more facets (default 2^25)
colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the
-- header = magics, else any attribute with bit 15 set = viscam, else none)
}
export type EncodeOptions = {
ascii: boolean?, -- default false (binary)
colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only)
defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly
-- that colour refer to it, the others carry their own (alpha 255)
name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh")
header: string?, -- the binary header text (at most 80 bytes; default "formats-luau STL")
normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8, readu32 = buffer.readu8, buffer.readu32
local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32
local function lower5(s: string): boolean
return string.lower(s) == "solid"
end
-- ------------------------------------------------------------------------------------------------ sniff
function Stl.sniff(r: Bytes.Reader): number
local size = r:remaining()
if size >= 84 then
local c = r:peek(4, 80)
local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216
if 84 + 50 * n == size then
return 0.9
end
end
local head = r:peek(512)
local s = string.match(head, "^%s*(%a+)")
if s and lower5(s) then
local l = string.lower(head)
return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive
return {
attributes = {
POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3),
NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3),
},
mode = "triangles",
}
end
local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?)
local b, base, size = r.buf, r.base, r.limit - r.base
local n = readu32(b, base + 80)
if n > maxFaces then
return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80)
end
if 84 + 50 * n > size then
return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80)
end
local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2)
local any = Decode.binary(b, base + 84, n, pos, nrm, attr)
local header = buffer.readstring(b, base, 80)
local cut = string.find(header, "\0", 1, true) -- the text before the first NUL
local text = if cut then string.sub(header, 1, cut - 1) else header
local mode = colors
local ci = string.find(header, "COLOR=", 1, true)
if mode == "auto" then
mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none"
end
local prim = soupPrim(n, pos, nrm)
local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n }
if mode == "viscam" or mode == "magics" then
local dc = { 255, 255, 255, 255 }
if mode == "magics" and ci and ci + 9 <= 80 then
local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based)
dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) }
source.defaultColor = dc
local mi = string.find(header, "MATERIAL=", 1, true)
if mi and mi + 8 + 12 <= 80 then
local m = base + mi + 8
local function rgba(k: number): { number }
return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) }
end
source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) }
end
end
local col = buffer.create(n * 12)
Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col)
prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3)
source.colors = mode
elseif any ~= 0 then
prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } }
end
local scene = Types.Scene.fromPrimitive(prim, nil)
scene.meta.up = "z"
scene.meta.source = source :: any
return scene, nil
end
local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local at = 1
local function tok(): string?
local s, e = string.find(text, "%S+", at)
if not s then
return nil
end
at = (e :: number) + 1
return string.sub(text, s, e)
end
local function restOfLine(): string
local e = string.find(text, "\n", at, true) or (#text + 1)
local line = string.sub(text, at, e - 1)
at = e + 1
return string.match(line, "^%s*(.-)%s*$") or ""
end
local function num(): number?
local t = tok()
return if t then tonumber(t) else nil
end
type Solid = { name: string, pos: { number }, nrm: { number } }
local solids: { Solid } = {}
local facets = 0
while true do
local t = tok()
if t == nil then
break
end
if string.lower(t) ~= "solid" then
return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20))
end
local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} }
table.insert(solids, cur)
local pos, nrm = cur.pos, cur.nrm
while true do
local w = tok()
if w == nil then
break -- a missing endsolid at the end
end
local lw = string.lower(w)
if lw == "endsolid" then
restOfLine()
break
elseif lw ~= "facet" then
return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20))
end
local nx, ny, nz = 0, 0, 0
local k = tok()
if k and string.lower(k) == "normal" then
local a, bb, c = num(), num(), num()
if a == nil or bb == nil or c == nil then
return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal")
end
nx, ny, nz = a, bb, c
k = tok()
end
local l2 = tok()
if k == nil or l2 == nil then
return nil, Err.new(Err.TRUNCATED, "facet cut short")
end
if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then
return nil, Err.new(Err.CORRUPT, "expected outer loop")
end
local vs: { number } = {}
while true do
local v = tok()
if v == nil then
return nil, Err.new(Err.TRUNCATED, "facet cut short")
end
local lv = string.lower(v)
if lv == "endloop" then
break
elseif lv ~= "vertex" then
return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20))
end
local x, y, z = num(), num(), num()
if x == nil or y == nil or z == nil then
return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex")
end
table.insert(vs, x)
table.insert(vs, y)
table.insert(vs, z)
end
local e = tok()
if e == nil then
return nil, Err.new(Err.TRUNCATED, "facet cut short")
elseif string.lower(e) ~= "endfacet" then
return nil, Err.new(Err.CORRUPT, "expected endfacet")
end
local nvs = #vs // 3
if nvs < 3 then
return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices")
end
for j = 2, nvs - 1 do
for _, vi in { 0, j - 1, j } do
table.insert(pos, vs[vi * 3 + 1])
table.insert(pos, vs[vi * 3 + 2])
table.insert(pos, vs[vi * 3 + 3])
table.insert(nrm, nx)
table.insert(nrm, ny)
table.insert(nrm, nz)
end
facets += 1
end
if facets > maxFaces then
return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces))
end
end
end
if #solids == 0 then
return nil, Err.new(Err.TRUNCATED, "no solid")
end
local prims: { Types.Primitive } = {}
local names: { string } = {}
for i, s in solids do
local n = #s.pos // 9
local pos, nrm = buffer.create(n * 36), buffer.create(n * 36)
for j = 1, n * 9 do
writef32(pos, (j - 1) * 4, s.pos[j])
writef32(nrm, (j - 1) * 4, s.nrm[j])
end
local prim = soupPrim(n, pos, nrm)
prim.extras = { solid = s.name }
prims[i] = prim
names[i] = s.name
end
local first = solids[1].name
local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil)
for i = 2, #prims do
table.insert(scene.meshes[1].primitives, prims[i])
end
scene.meta.up = "z"
scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets }
return scene, nil
end
function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local maxFaces = opts and opts.maxFaces or 2 ^ 25
local colors = opts and opts.colors or "auto"
if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then
return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none")
end
local size = r.limit - r.base
if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then
return decodeBinary(r, maxFaces, colors)
end
local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)")
if s and lower5(s) then
return decodeAscii(r, maxFaces)
end
if size < 84 then
return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base)
end
-- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED)
return decodeBinary(r, maxFaces, colors)
end
-- ------------------------------------------------------------------------------------------------ encode
local scratch = buffer.create(4)
local function f32(v: number): number
writef32(scratch, 0, v)
return buffer.readf32(scratch, 0)
end
-- a COLOR_0 component as 0..255
local function byte(a: Flatten.Attr, v: number): number
if a.raw then
if a.type == "unorm16" then
return (v * 255 + 32767) // 65535
end
return math.clamp(v, 0, 255)
end
return math.floor(math.clamp(v, 0, 1) * 255 + 0.5)
end
local function to5(c: number): number
return (c * 31 + 127) // 255
end
local function keep(name: string): boolean
return name == "NORMAL" or name == "COLOR_0"
end
function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local colors = o.colors
if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then
return nil, Err.new(Err.ARG, "colors must be viscam or magics")
end
if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then
return nil, Err.new(Err.ARG, "normals must be compute or attribute")
end
if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then
return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes")
end
local m, merr = Flatten.merge(scene, keep, { triangulate = true })
if not m then
return nil, Err.new(Err.ARG, tostring(merr))
end
local P = m.attrs.POSITION.values
local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil
local C = m.attrs.COLOR_0
local corners = m.corners
local nf = #corners // 3
-- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based)
local function normal(f: number): (number, number, number)
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
if N then
return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3]
end
local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3]
local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az
local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 and l < math.huge then
return nx / l, ny / l, nz / l
end
return 0, 0, 0
end
if o.ascii then
local out = table.create(nf * 7 + 2 * #m.parts)
local used: { [string]: boolean } = {}
local function fmt(v: number): string?
v = f32(v)
if v ~= v or v == math.huge or v == -math.huge then
return nil
end
return string.format("%.9g", v)
end
for _, part in m.parts do
local name = o.name
if name == nil then
local ex = part.prim.extras
name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh"
end
name = string.gsub(tostring(name), "[\r\n]", " ")
if used[name] then -- distinct names: some readers merge solids by name
local k = 2
while used[name .. "_" .. k] do
k += 1
end
name = name .. "_" .. k
end
used[name] = true
table.insert(out, "solid " .. name .. "\n")
for f = part.firstFace, part.firstFace + part.faceCount - 1 do
local nx, ny, nz = normal(f)
table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0"))
for k = 1, 3 do
local v = corners[f * 3 + k] * 3
local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3])
if not (x and y and z) then
return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate")
end
table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n")
end
table.insert(out, " endloop\n endfacet\n")
end
table.insert(out, "endsolid " .. name .. "\n")
end
if #m.parts == 0 then
table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n")
end
return buffer.fromstring(table.concat(out)), nil
end
-- binary
local buf = buffer.create(84 + 50 * nf)
local header = o.header or "formats-luau STL"
if colors == "magics" then
local dc = o.defaultColor or { 255, 255, 255, 255 }
if type(dc) ~= "table" or #dc < 4 then
return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }")
end
header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1)
end
local dcol: { number }? = nil
if colors == "magics" then
local dc = o.defaultColor or { 255, 255, 255, 255 }
dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 }
end
buffer.writestring(buf, 0, header)
writeu32(buf, 80, nf)
-- the attribute words: colours, or the raw words of a single STL-decoded primitive
local rawAttr: { number }? = nil
if colors == nil and #m.parts == 1 then
local ex = m.parts[1].prim.extras
local fa = ex and ex.faceAttributes
local acc = fa and fa.attribute
if acc and acc.count == nf then
rawAttr = Flatten.numbers(acc, true)
end
end
for f = 0, nf - 1 do
local q = 84 + f * 50
local nx, ny, nz = normal(f)
writef32(buf, q, nx)
writef32(buf, q + 4, ny)
writef32(buf, q + 8, nz)
for k = 0, 2 do
local v = corners[f * 3 + k + 1] * 3
writef32(buf, q + 12 + k * 12, P[v + 1])
writef32(buf, q + 16 + k * 12, P[v + 2])
writef32(buf, q + 20 + k * 12, P[v + 3])
end
local w = 0
if colors and C then
local a = corners[f * 3 + 1] * C.components
local cv = C.values
local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0))
if colors == "viscam" then
w = 0x8000 + r5 * 1024 + g5 * 32 + b5
elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then
w = 0x8000 -- the object colour
else
w = r5 + g5 * 32 + b5 * 1024
end
elseif colors == "magics" then
w = 0x8000 -- the object colour
elseif rawAttr then
w = math.clamp(rawAttr[f + 1] // 1, 0, 65535)
end
writeu16(buf, q + 48, w)
end
return buf, nil
end
return Stl
+61
View File
@@ -0,0 +1,61 @@
--!strict
--!native
-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI
-- records. Callers check every range first; nothing here throws.
local Grid = {}
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the
-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted.
-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz.
function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number
local skipped = 0
local sxy = sx * sy
for k = 0, n - 1 do
local p = off + k * 4
local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
if x < sx and y < sy and z < sz and i ~= 0 then
writeu8(dst, x + sx * y + sxy * z, i)
else
skipped += 1
end
end
return skipped
end
-- count(data, cells) -> the number of non-empty cells in data[0, cells)
function Grid.count(data: buffer, cells: number): number
local n = 0
for k = 0, cells - 1 do
if readu8(data, k) ~= 0 then
n += 1
end
end
return n
end
-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest).
-- The caller sizes dst with count() (sx, sy, sz <= 256).
function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number
local p = at
local k = 0
for z = 0, sz - 1 do
for y = 0, sy - 1 do
for x = 0, sx - 1 do
local i = readu8(data, k)
if i ~= 0 then
writeu8(dst, p, x)
writeu8(dst, p + 1, y)
writeu8(dst, p + 2, z)
writeu8(dst, p + 3, i)
p += 4
end
k += 1
end
end
end
return p
end
return Grid
+903
View File
@@ -0,0 +1,903 @@
--!strict
-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt)
-- and the files MagicaVoxel 0.99.x saves (version 150 and 200).
-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP /
-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials,
-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown
-- chunks are kept raw and written back.
-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per
-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as
-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is
-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes.
-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must
-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk.
-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Grid = require("@formats/model/vox/Grid")
-- ------------------------------------------------------------------------------------------------ contract
local Vox = {
name = "vox",
category = "model",
extensions = { "vox" },
mime = { "model/x-vox" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27)
}
export type EncodeOptions = {
version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one)
}
type Dict = { [string]: string }
type GraphNode = {
kind: string,
id: number,
attrs: Dict,
child: number?,
layer: number?,
frames: { Dict }?,
children: { number }?,
models: { { model: number, attributes: Dict } }?,
}
-- ------------------------------------------------------------------------------------------------ constants
-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps
local DEFAULT_PALETTE: { { number } } = {}
do
local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 }
for _, r in steps do
for _, g in steps do
for _, b in steps do
if #DEFAULT_PALETTE < 215 then
table.insert(DEFAULT_PALETTE, { r, g, b, 255 })
end
end
end
end
local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
for ch = 1, 4 do
for _, v in ramp do
local c = { 0, 0, 0, 255 }
if ch == 4 then
c = { v, v, v, 255 }
else
c[ch] = v
end
table.insert(DEFAULT_PALETTE, c)
end
end
end
Vox.DEFAULT_PALETTE = DEFAULT_PALETTE
local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs
local MAX_DEPTH = 256
-- ------------------------------------------------------------------------------------------------ sniff
function Vox.sniff(r: Bytes.Reader): number
return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function str(r: Bytes.Reader): string
local n = r:i32le()
if n < 0 or n > r:remaining() then
r:fail(Err.CORRUPT, "bad string length")
return ""
end
return r:string(n)
end
local function dict(r: Bytes.Reader): Dict
local d: Dict = {}
local n = r:i32le()
if n < 0 or n * 8 > r:remaining() then
r:fail(Err.CORRUPT, "bad dictionary size")
return d
end
for _ = 1, n do
local k = str(r)
local v = str(r)
if r.err then
break
end
d[k] = v
end
return d
end
local function ints(s: string?): { number }
local out = {}
if s then
for w in string.gmatch(s, "%S+") do
table.insert(out, tonumber(w) or 0)
end
end
return out
end
-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation
local function rotation(b: number): { { number } }?
local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3)
if i0 > 2 or i1 > 2 or i0 == i1 then
return nil
end
local i2 = 3 - i0 - i1
local function sign(bit: number): number
return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1
end
return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } }
end
-- the node transform of a frame dictionary (_r, _t)
local function applyFrame(node: Types.Node, f: Dict)
local t = ints(f._t)
local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
local rb = tonumber(f._r)
local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil
if not rows then
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
node.translation = { tx, ty, tz }
end
return
end
-- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix
local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }
for row = 1, 3 do
R[row][rows[row][1] + 1] = rows[row][2]
end
local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1])
if det < 0 then
node.matrix = {
R[1][1], R[2][1], R[3][1], 0,
R[1][2], R[2][2], R[3][2], 0,
R[1][3], R[2][3], R[3][3], 0,
tx, ty, tz, 1,
}
return
end
local m00, m11, m22 = R[1][1], R[2][2], R[3][3]
local tr = m00 + m11 + m22
local x, y, z, w
if tr > 0 then
local s = math.sqrt(tr + 1) * 2
w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s
elseif m00 > m11 and m00 > m22 then
local s = math.sqrt(1 + m00 - m11 - m22) * 2
w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s
elseif m11 > m22 then
local s = math.sqrt(1 + m11 - m00 - m22) * 2
w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s
else
local s = math.sqrt(1 + m22 - m00 - m11) * 2
w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s
end
node.rotation = { x, y, z, w }
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
node.translation = { tx, ty, tz }
end
end
-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers
local function material(d: Dict): Types.VoxelMaterial
local m: Types.VoxelMaterial = { type = "diffuse" }
for k, v in d do
local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k
if key == "type" then
m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v
else
m[key] = tonumber(v) or v
end
end
return m
end
type Parsed = {
version: number,
models: { Types.Voxels },
palette: { { number } }?,
materials: { [number]: Types.VoxelMaterial },
graph: { [number]: GraphNode },
meta: { [string]: any },
skipped: number,
}
local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
local maxCells = opts and opts.maxCells or 2 ^ 27
if r:string(4) ~= "VOX " then
return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
end
local version = r:u32le()
if r:string(4) ~= "MAIN" then
if r.err then
return nil, r.err
end
return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8)
end
local mainN, mainM = r:i32le(), r:i32le()
if r.err then
return nil, r.err
end
if mainN < 0 or mainM < 0 or not r:skip(mainN) then
return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12)
end
local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 }
local meta = out.meta
local unknown: { any } = {}
local layers, robjs, cams = {}, {}, {}
local stop = r:tell() + mainM
if stop > r:size() then
return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16)
end
local pending: { number }? = nil
local cells = 0
while r:tell() + 12 <= stop do
local at = r:tell()
local id = r:string(4)
local n, m = r:i32le(), r:i32le()
if n < 0 or m < 0 then
return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at)
elseif n > stop - r:tell() or m > stop - r:tell() - n then
return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at)
end
local c = r:slice(n)
if id == "SIZE" then
local sx, sy, sz = c:i32le(), c:i32le(), c:i32le()
if c.err or sx < 1 or sy < 1 or sz < 1 then
return nil, Err.new(Err.CORRUPT, "bad model size", at)
end
cells += sx * sy * sz
if cells > maxCells then
return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at)
end
pending = { sx, sy, sz }
elseif id == "XYZI" then
local size = pending
if not size then
return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at)
end
pending = nil
local count = c:i32le()
if c.err or count < 0 or count * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad voxel count", at)
end
local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE)
out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count)
table.insert(out.models, v)
elseif id == "RGBA" then
if n < 1024 then
return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at)
end
local pal = table.create(255)
for i = 1, 255 do
pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() }
end
out.palette = pal
elseif id == "MATL" then
local mid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at)
end
out.materials[mid] = material(d)
elseif id == "nTRN" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() }
c:i32le() -- reserved
node.layer = c:i32le()
local nf = c:i32le()
if c.err or nf < 0 or nf * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at)
end
local frames = {}
for k = 1, nf do
frames[k] = dict(c)
end
node.frames = frames
if c.err then
return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at)
end
out.graph[node.id] = node
elseif id == "nGRP" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
local nc = c:i32le()
if c.err or nc < 0 or nc * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at)
end
local children = table.create(nc)
for k = 1, nc do
children[k] = c:i32le()
end
node.children = children
out.graph[node.id] = node
elseif id == "nSHP" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
local nm = c:i32le()
if c.err or nm < 0 or nm * 8 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at)
end
local models = {}
for k = 1, nm do
models[k] = { model = c:i32le() + 1, attributes = dict(c) }
end
if c.err then
return nil, Err.new(Err.CORRUPT, "bad nSHP models", at)
end
node.models = models
out.graph[node.id] = node
elseif id == "LAYR" then
local lid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at)
end
table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d })
elseif id == "rOBJ" then
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at)
end
table.insert(robjs, d)
elseif id == "rCAM" then
local cid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at)
end
table.insert(cams, { id = cid, attributes = d })
elseif id == "NOTE" then
local nn = c:i32le()
if c.err or nn < 0 or nn * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at)
end
local notes = table.create(nn)
for k = 1, nn do
notes[k] = str(c)
end
if c.err then
return nil, Err.new(Err.CORRUPT, "bad NOTE names", at)
end
meta.notes = notes
elseif id == "IMAP" then
local map = {}
for k = 1, math.min(n, 256) do
map[k] = c:u8()
end
meta.indexMap = map
elseif id == "META" then
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad META chunk", at)
end
meta.info = d
else
if id == "PACK" then
meta.pack = c:i32le()
end
table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? })
end
if m > 0 then
local kids = r:bytes(math.min(m, r:remaining()))
if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then
unknown[#unknown].children = kids
end
end
if r.err then
return nil, r.err
end
end
if r:tell() < stop then
return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell())
end
if #out.models == 0 then
return nil, Err.new(Err.CORRUPT, "no models")
end
if #layers > 0 then
meta.layers = layers
end
if #robjs > 0 then
meta.renderObjects = robjs
end
if #cams > 0 then
meta.cameras = cams
end
if #unknown > 0 then
meta.chunks = unknown
end
return out, nil
end
-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node)
local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number?
local t = graph[id]
if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then
return nil
end
visiting[id] = true
local node: Types.Node = { name = t.attrs._name, children = {} }
local index = #scene.nodes + 1
scene.nodes[index] = node
local frames = t.frames or {}
if frames[1] then
applyFrame(node, frames[1])
end
local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer }
if #frames > 1 or (frames[1] and frames[1]._f) then
vox.frames = frames
end
node.extras = { vox = vox }
local child = if t.child then graph[t.child] else nil
if child and child.kind == "nGRP" then
vox.group = child.attrs
for _, c in child.children or {} do
local ci = build(scene, graph, c, depth + 1, visiting, nmodels)
if ci then
table.insert(node.children, ci)
end
end
elseif child and child.kind == "nSHP" then
local models = child.models or {}
vox.shape = { attributes = child.attrs, models = models }
local first = models[1]
if first and first.model >= 1 and first.model <= nmodels then
node.voxels = first.model
end
end
visiting[id] = nil
return index
end
-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err
function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?)
local p, err = parse(r, opts)
if not p then
return nil, err
end
local pal = p.palette or DEFAULT_PALETTE
local mats = if next(p.materials) then p.materials else nil
for _, v in p.models do
v.palette = pal
v.materials = mats
end
return p.models, nil
end
function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local p, err = parse(r, opts)
if not p then
return nil, err
end
local scene = Types.Scene.new()
local pal = p.palette or DEFAULT_PALETTE
local mats = if next(p.materials) then p.materials else nil
for _, v in p.models do
v.palette = pal
v.materials = mats
end
scene.voxels = p.models
if p.graph[0] then
local root = build(scene, p.graph, 0, 0, {}, #p.models)
if root then
scene.roots = { root }
end
end
if #scene.nodes == 0 then
-- no scene graph (version 150 files): one node per model
for i = 1, #p.models do
scene.nodes[i] = { children = {}, voxels = i }
scene.roots[i] = i
end
end
scene.meta.up = "z"
scene.meta.vox = p.meta
scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function number(v: any): string
if type(v) ~= "number" then
return tostring(v)
end
if v == math.floor(v) and math.abs(v) < 2 ^ 53 then
return string.format("%d", v)
end
for _, f in { "%.6g", "%.9g", "%.17g" } do
local s = string.format(f, v)
if tonumber(s) == v then
return s
end
end
return string.format("%.17g", v)
end
local function sortedKeys(d: { [string]: any }): { string }
local keys = {}
for k in d do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
return keys
end
local function wstr(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
local function wdict(w: Bytes.Writer, d: { [string]: any }?)
if not d then
w:u32le(0)
return
end
local keys = sortedKeys(d)
w:u32le(#keys)
for _, k in keys do
wstr(w, k)
wstr(w, number(d[k]))
end
end
-- a node's transform as a frame dictionary (_r, _t) | nil, message
local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?)
local f: Dict = {}
if base then
for k, v in base do
if k ~= "_r" and k ~= "_t" then
f[k] = v
end
end
end
local m = Types.Scene.nodeMatrix(node)
local cols, signs = {}, {}
for row = 0, 2 do
local best, bv, rest = 0, 0, 0
for col = 0, 2 do
local v = m[col * 4 + row + 1]
if math.abs(v) > math.abs(bv) then
rest = math.max(rest, math.abs(bv))
best, bv = col, v
else
rest = math.max(rest, math.abs(v))
end
end
if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then
return nil, "node rotation is not a multiple of 90 degrees (or has a scale)"
end
table.insert(cols, best)
signs[row + 1] = if bv < 0 then 1 else 0
end
local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64
if rb ~= IDENTITY_R then
f._r = tostring(rb)
end
local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5)
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
f._t = string.format("%d %d %d", tx, ty, tz)
end
return f, nil
end
type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? }
function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local version = opts and opts.version or 200
if type(version) ~= "number" or version < 0 then
return nil, Err.new(Err.ARG, "bad version")
end
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
end
local scene: Types.Scene
if value.kind == "voxels" then
scene = Types.Scene.new()
scene.voxels = { value }
scene.nodes[1] = { children = {}, voxels = 1 }
scene.roots[1] = 1
elseif value.kind == "scene" then
scene = value
else
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
end
local models = scene.voxels
if type(models) ~= "table" or #models == 0 then
return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)")
end
for i, v in models do
local s = v.size
if type(s) ~= "table" or type(v.data) ~= "buffer" then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid")
end
for k = 1, 3 do
if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis")
end
end
if buffer.len(v.data) < s[1] * s[2] * s[3] then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid")
end
end
local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {}
local w = Bytes.writer(65536)
w:string("VOX ")
w:u32le(version)
w:string("MAIN")
w:u32le(0)
local mAt = w:tell()
w:u32le(0)
local function chunk(id: string, body: () -> ())
w:string(id)
local at = w:tell()
w:u32le(0)
w:u32le(0)
body()
w:setU32le(at, w:tell() - at - 8)
end
if type(meta.info) == "table" then
chunk("META", function()
wdict(w, meta.info)
end)
end
-- models
for _, v in models do
local sx, sy, sz = v.size[1], v.size[2], v.size[3]
chunk("SIZE", function()
w:u32le(sx)
w:u32le(sy)
w:u32le(sz)
end)
local count = Grid.count(v.data, sx * sy * sz)
chunk("XYZI", function()
w:u32le(count)
local at = w:reserve(count * 4)
Grid.write(w.buf, at, v.data, sx, sy, sz)
w.pos = at + count * 4
end)
end
-- the scene graph
local records: { Record } = {}
local nextId = 0
local function alloc(): number
local id = nextId
nextId += 1
return id
end
local nodes = scene.nodes or {}
local visiting: { [number]: boolean } = {}
local failure: string? = nil
local function shape(model: number, vx: any?): number
local id = alloc()
local ms = {}
local saved = vx and vx.shape
if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then
for _, sm in saved.models do
if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then
table.insert(ms, { model = sm.model - 1, attributes = sm.attributes })
end
end
end
if #ms == 0 then
ms[1] = { model = model - 1, attributes = nil }
end
table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms })
return id
end
local function visit(index: number, depth: number, layer: number?): number?
local node = nodes[index]
if not node or visiting[index] or depth > MAX_DEPTH then
failure = failure or "the node tree has a loop or is too deep"
return nil
end
visiting[index] = true
local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil
local id = alloc()
local attrs: { [string]: any } = {}
if vx and type(vx.attributes) == "table" then
for k, v in vx.attributes do
attrs[k] = v
end
end
attrs._name = node.name
local saved = vx and type(vx.frames) == "table" and vx.frames or nil
local f, ferr = frameOf(node, saved and saved[1])
if not f then
failure = failure or ferr
f = {}
end
local frames = { f :: Dict }
if saved then
for k = 2, #saved do
frames[k] = saved[k]
end
end
local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames }
table.insert(records, rec)
local kids = node.children or {}
local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models
if hasVox and #kids == 0 then
rec.child = shape(node.voxels :: number, vx)
else
local gid = alloc()
local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} }
table.insert(records, grp)
rec.child = gid
if hasVox then
local tid = alloc()
local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } }
table.insert(records, t2)
table.insert(grp.children :: { number }, tid)
t2.child = shape(node.voxels :: number, vx)
end
for _, c in kids do
local cid = visit(c, depth + 1, nil)
if cid then
table.insert(grp.children :: { number }, cid)
end
end
end
visiting[index] = nil
return id
end
local roots = scene.roots or {}
local single = if #roots == 1 then nodes[roots[1]] else nil
if single and single.voxels == nil then
visit(roots[1], 0, -1)
elseif #roots > 0 then
local rid = alloc()
local gid = alloc()
local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } }
local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} }
table.insert(records, rec)
table.insert(records, grp)
for _, ri in roots do
local cid = visit(ri, 1, nil)
if cid then
table.insert(grp.children :: { number }, cid)
end
end
end
if failure then
return nil, Err.new(Err.ARG, failure)
end
for _, rec in records do
chunk(rec.kind, function()
w:u32le(rec.id)
wdict(w, rec.attrs)
if rec.kind == "nTRN" then
w:u32le(rec.child or 0)
w:u32le(0xFFFFFFFF)
w:u32le((rec.layer or 0) % 4294967296)
local frames = rec.frames or { {} }
w:u32le(#frames)
for _, f in frames do
wdict(w, f)
end
elseif rec.kind == "nGRP" then
local ch = rec.children or {}
w:u32le(#ch)
for _, c in ch do
w:u32le(c)
end
else
local ms = rec.models or {}
w:u32le(#ms)
for _, sm in ms do
w:u32le(sm.model)
wdict(w, sm.attributes)
end
end
end)
end
-- layers
if type(meta.layers) == "table" then
for _, l in meta.layers do
chunk("LAYR", function()
w:u32le(tonumber(l.id) or 0)
local d: { [string]: any } = {}
if type(l.attributes) == "table" then
for k, v in l.attributes do
d[k] = v
end
end
d._name = l.name
d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil
wdict(w, d)
w:u32le(0xFFFFFFFF)
end)
end
end
-- palette
local pal = models[1].palette or DEFAULT_PALETTE
chunk("RGBA", function()
for i = 1, 256 do
local c = pal[i]
if type(c) == "table" then
w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255))
else
w:u32le(0)
end
end
end)
if type(meta.indexMap) == "table" then
chunk("IMAP", function()
for k = 1, 256 do
w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255))
end
end)
end
-- materials
local mats = models[1].materials
if type(mats) == "table" then
local ids = {}
for id in mats do
if type(id) == "number" then
table.insert(ids, id)
end
end
table.sort(ids)
for _, id in ids do
local m = mats[id]
chunk("MATL", function()
w:u32le(id)
local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") }
for k, v in m do
if k ~= "type" and type(k) == "string" then
d["_" .. k] = v
end
end
wdict(w, d)
end)
end
end
if type(meta.renderObjects) == "table" then
for _, d in meta.renderObjects do
chunk("rOBJ", function()
wdict(w, d)
end)
end
end
if type(meta.cameras) == "table" then
for _, cam in meta.cameras do
chunk("rCAM", function()
w:u32le(tonumber(cam.id) or 0)
wdict(w, cam.attributes)
end)
end
end
if type(meta.notes) == "table" then
chunk("NOTE", function()
w:u32le(#meta.notes)
for _, s in meta.notes do
wstr(w, tostring(s))
end
end)
end
if type(meta.chunks) == "table" then
for _, u in meta.chunks do
if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then
w:string(u.id)
w:u32le(buffer.len(u.content))
w:u32le(if u.children then buffer.len(u.children) else 0)
w:bytes(u.content)
if u.children then
w:bytes(u.children)
end
end
end
end
w:setU32le(mAt, w:tell() - mAt - 4)
return w:finish(), nil
end
return Vox
+167
View File
@@ -0,0 +1,167 @@
--!strict
--!native
-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each
-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged
-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are
-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the
-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz.
local Greedy = {}
local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
export type Out = {
positions: buffer, -- f32 x3 per vertex
normals: buffer, -- f32 x3 per vertex
index: buffer, -- u8 palette index per vertex
indices: buffer, -- u32, 6 per quad
vertices: number,
quads: number,
}
-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale
function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out
local cap = 1024
local pos = buffer.create(cap * 48)
local nrm = buffer.create(cap * 48)
local idx = buffer.create(cap * 4)
local tri = buffer.create(cap * 24)
local quads = 0
local maxFace = math.max(sx * sy, sy * sz, sz * sx)
local mask = buffer.create(maxFace * 4)
local corner = { 0, 0, 0 }
for d = 0, 2 do
-- u, v: the two other axes, cyclic so that e_u x e_v = e_d
local u, v = (d + 1) % 3, (d + 2) % 3
local nd = if d == 0 then sx elseif d == 1 then sy else sz
local nu = if u == 0 then sx elseif u == 1 then sy else sz
local nv = if v == 0 then sx elseif v == 1 then sy else sz
local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy
local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy
local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy
for slice = -1, nd - 1 do
-- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d)
local any = false
for j = 0, nv - 1 do
for i = 0, nu - 1 do
local base = i * stu + j * stv
local a = if slice >= 0 then readu8(data, base + slice * std) else 0
local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0
local m = 0
if a ~= 0 and b == 0 then
m = a
elseif a == 0 and b ~= 0 then
m = -b
end
if m ~= 0 then
any = true
end
writei32(mask, (i + j * nu) * 4, m)
end
end
if any then
for j = 0, nv - 1 do
local i = 0
while i < nu do
local m = readi32(mask, (i + j * nu) * 4)
if m == 0 then
i += 1
else
local w = 1
while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do
w += 1
end
local h = 1
local grow = true
while j + h < nv and grow do
for k = 0, w - 1 do
if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then
grow = false
break
end
end
if grow then
h += 1
end
end
for jj = j, j + h - 1 do
for k = 0, w - 1 do
writei32(mask, (i + k + jj * nu) * 4, 0)
end
end
-- emit the rectangle
if quads == cap then
local ncap = cap * 2
local function grow2(b: buffer, per: number): buffer
local nb = buffer.create(ncap * per)
buffer.copy(nb, 0, b, 0, cap * per)
return nb
end
pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24)
cap = ncap
end
corner[d + 1] = slice + 1
corner[u + 1] = i
corner[v + 1] = j
local cx, cy, cz = corner[1], corner[2], corner[3]
-- the u and v edge vectors
local ux = if u == 0 then w else 0
local uy = if u == 1 then w else 0
local uz = if u == 2 then w else 0
local vx = if v == 0 then h else 0
local vy = if v == 1 then h else 0
local vz = if v == 2 then h else 0
local nsign = if m > 0 then 1 else -1
local nx = if d == 0 then nsign else 0
local ny = if d == 1 then nsign else 0
local nz = if d == 2 then nsign else 0
local col = if m > 0 then m else -m
local vb = quads * 48
local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale
writef32(pos, vb, px0)
writef32(pos, vb + 4, py0)
writef32(pos, vb + 8, pz0)
writef32(pos, vb + 12, px0 + ux * scale)
writef32(pos, vb + 16, py0 + uy * scale)
writef32(pos, vb + 20, pz0 + uz * scale)
writef32(pos, vb + 24, px0 + (ux + vx) * scale)
writef32(pos, vb + 28, py0 + (uy + vy) * scale)
writef32(pos, vb + 32, pz0 + (uz + vz) * scale)
writef32(pos, vb + 36, px0 + vx * scale)
writef32(pos, vb + 40, py0 + vy * scale)
writef32(pos, vb + 44, pz0 + vz * scale)
for k = 0, 3 do
writef32(nrm, vb + k * 12, nx)
writef32(nrm, vb + k * 12 + 4, ny)
writef32(nrm, vb + k * 12 + 8, nz)
writeu8(idx, quads * 4 + k, col)
end
local v0 = quads * 4
local ib = quads * 24
if m > 0 then
writeu32(tri, ib, v0)
writeu32(tri, ib + 4, v0 + 1)
writeu32(tri, ib + 8, v0 + 2)
writeu32(tri, ib + 12, v0)
writeu32(tri, ib + 16, v0 + 2)
writeu32(tri, ib + 20, v0 + 3)
else
writeu32(tri, ib, v0)
writeu32(tri, ib + 4, v0 + 2)
writeu32(tri, ib + 8, v0 + 1)
writeu32(tri, ib + 12, v0)
writeu32(tri, ib + 16, v0 + 3)
writeu32(tri, ib + 20, v0 + 2)
end
quads += 1
i += w
end
end
end
end
end
end
return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads }
end
return Greedy
File diff suppressed because it is too large. Load diff