ws-3d: Types Scene extensions (compatible): Accessor f64/i32/matrix/name, Primitive polygons mode + faces/targets/extras, Mesh weights, Texture data/mime/name/Sampler, TextureRef texCoord/scale/strength/transform.texCoord, Material extensions, Node voxels/weights, names on Camera/Light/Skin, Scene.voxels + Voxels type, COMPONENT_SIZE, Scene.accessor(nil) allocates; api: opts.resolve for sibling files on path loads, save passes format key/name/files and writes sibling files, image-only textures encoded to PNG before model writers, F.model.loadTextures

This commit is contained in:
4DBug committed 2026-10-31 08:25:00 -05:00
1 parent cdcb5b0b77
commit a55b58b102
2 files changed
+217 -16

No files matched your search

+116 -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 {
+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
@@ -179,6 +199,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), o)
@@ -233,8 +258,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]
@@ -264,16 +291,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, o)
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
@@ -286,6 +346,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
@@ -375,4 +444,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